repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
coldtobi/RBDOOM-3-BFG | neo/renderer/Model_md3.cpp | 10586 | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "RenderCommon.h"
#include "Model_local.h"
#include "Model_md3.h"
/***********************************************************************
idMD3Mesh
***********************************************************************/
#define LL(x) x=LittleLong(x)
/*
=================
idRenderModelMD3::InitFromFile
=================
*/
void idRenderModelMD3::InitFromFile( const char* fileName )
{
int i, j;
md3Header_t* pinmodel;
md3Frame_t* frame;
md3Surface_t* surf;
md3Shader_t* shader;
md3Triangle_t* tri;
md3St_t* st;
md3XyzNormal_t* xyz;
md3Tag_t* tag;
void* buffer;
int version;
int size;
name = fileName;
size = fileSystem->ReadFile( fileName, &buffer, NULL );
if( !size || size < 0 )
{
return;
}
pinmodel = ( md3Header_t* )buffer;
version = LittleLong( pinmodel->version );
if( version != MD3_VERSION )
{
fileSystem->FreeFile( buffer );
common->Warning( "InitFromFile: %s has wrong version (%i should be %i)",
fileName, version, MD3_VERSION );
return;
}
size = LittleLong( pinmodel->ofsEnd );
dataSize += size;
md3 = ( md3Header_t* )Mem_Alloc( size, TAG_MODEL );
memcpy( md3, buffer, LittleLong( pinmodel->ofsEnd ) );
LL( md3->ident );
LL( md3->version );
LL( md3->numFrames );
LL( md3->numTags );
LL( md3->numSurfaces );
LL( md3->ofsFrames );
LL( md3->ofsTags );
LL( md3->ofsSurfaces );
LL( md3->ofsEnd );
if( md3->numFrames < 1 )
{
common->Warning( "InitFromFile: %s has no frames", fileName );
fileSystem->FreeFile( buffer );
return;
}
// swap all the frames
frame = ( md3Frame_t* )( ( byte* )md3 + md3->ofsFrames );
for( i = 0 ; i < md3->numFrames ; i++, frame++ )
{
frame->radius = LittleFloat( frame->radius );
for( j = 0 ; j < 3 ; j++ )
{
frame->bounds[0][j] = LittleFloat( frame->bounds[0][j] );
frame->bounds[1][j] = LittleFloat( frame->bounds[1][j] );
frame->localOrigin[j] = LittleFloat( frame->localOrigin[j] );
}
}
// swap all the tags
tag = ( md3Tag_t* )( ( byte* )md3 + md3->ofsTags );
for( i = 0 ; i < md3->numTags * md3->numFrames ; i++, tag++ )
{
for( j = 0 ; j < 3 ; j++ )
{
tag->origin[j] = LittleFloat( tag->origin[j] );
tag->axis[0][j] = LittleFloat( tag->axis[0][j] );
tag->axis[1][j] = LittleFloat( tag->axis[1][j] );
tag->axis[2][j] = LittleFloat( tag->axis[2][j] );
}
}
// swap all the surfaces
surf = ( md3Surface_t* )( ( byte* )md3 + md3->ofsSurfaces );
for( i = 0 ; i < md3->numSurfaces ; i++ )
{
LL( surf->ident );
LL( surf->flags );
LL( surf->numFrames );
LL( surf->numShaders );
LL( surf->numTriangles );
LL( surf->ofsTriangles );
LL( surf->numVerts );
LL( surf->ofsShaders );
LL( surf->ofsSt );
LL( surf->ofsXyzNormals );
LL( surf->ofsEnd );
if( surf->numVerts > SHADER_MAX_VERTEXES )
{
common->Error( "InitFromFile: %s has more than %i verts on a surface (%i)",
fileName, SHADER_MAX_VERTEXES, surf->numVerts );
}
if( surf->numTriangles * 3 > SHADER_MAX_INDEXES )
{
common->Error( "InitFromFile: %s has more than %i triangles on a surface (%i)",
fileName, SHADER_MAX_INDEXES / 3, surf->numTriangles );
}
// change to surface identifier
surf->ident = 0; //SF_MD3;
// lowercase the surface name so skin compares are faster
int slen = ( int )strlen( surf->name );
for( j = 0; j < slen; j++ )
{
surf->name[j] = tolower( surf->name[j] );
}
// strip off a trailing _1 or _2
// this is a crutch for q3data being a mess
j = strlen( surf->name );
if( j > 2 && surf->name[j - 2] == '_' )
{
surf->name[j - 2] = 0;
}
// register the shaders
shader = ( md3Shader_t* )( ( byte* )surf + surf->ofsShaders );
for( j = 0 ; j < surf->numShaders ; j++, shader++ )
{
const idMaterial* sh;
sh = declManager->FindMaterial( shader->name );
shader->shader = sh;
}
// swap all the triangles
tri = ( md3Triangle_t* )( ( byte* )surf + surf->ofsTriangles );
for( j = 0 ; j < surf->numTriangles ; j++, tri++ )
{
LL( tri->indexes[0] );
LL( tri->indexes[1] );
LL( tri->indexes[2] );
}
// swap all the ST
st = ( md3St_t* )( ( byte* )surf + surf->ofsSt );
for( j = 0 ; j < surf->numVerts ; j++, st++ )
{
st->st[0] = LittleFloat( st->st[0] );
st->st[1] = LittleFloat( st->st[1] );
}
// swap all the XyzNormals
xyz = ( md3XyzNormal_t* )( ( byte* )surf + surf->ofsXyzNormals );
for( j = 0 ; j < surf->numVerts * surf->numFrames ; j++, xyz++ )
{
xyz->xyz[0] = LittleShort( xyz->xyz[0] );
xyz->xyz[1] = LittleShort( xyz->xyz[1] );
xyz->xyz[2] = LittleShort( xyz->xyz[2] );
xyz->normal = LittleShort( xyz->normal );
}
// find the next surface
surf = ( md3Surface_t* )( ( byte* )surf + surf->ofsEnd );
}
fileSystem->FreeFile( buffer );
}
/*
=================
idRenderModelMD3::IsDynamicModel
=================
*/
dynamicModel_t idRenderModelMD3::IsDynamicModel() const
{
return DM_CACHED;
}
/*
=================
idRenderModelMD3::LerpMeshVertexes
=================
*/
void idRenderModelMD3::LerpMeshVertexes( srfTriangles_t* tri, const struct md3Surface_s* surf, const float backlerp, const int frame, const int oldframe ) const
{
short* oldXyz, *newXyz;
float oldXyzScale, newXyzScale;
int vertNum;
int numVerts;
newXyz = ( short* )( ( byte* )surf + surf->ofsXyzNormals ) + ( frame * surf->numVerts * 4 );
newXyzScale = MD3_XYZ_SCALE * ( 1.0 - backlerp );
numVerts = surf->numVerts;
if( backlerp == 0 )
{
//
// just copy the vertexes
//
for( vertNum = 0 ; vertNum < numVerts ; vertNum++, newXyz += 4 )
{
idDrawVert* outvert = &tri->verts[tri->numVerts];
outvert->xyz.x = newXyz[0] * newXyzScale;
outvert->xyz.y = newXyz[1] * newXyzScale;
outvert->xyz.z = newXyz[2] * newXyzScale;
tri->numVerts++;
}
}
else
{
//
// interpolate and copy the vertexes
//
oldXyz = ( short* )( ( byte* )surf + surf->ofsXyzNormals ) + ( oldframe * surf->numVerts * 4 );
oldXyzScale = MD3_XYZ_SCALE * backlerp;
for( vertNum = 0 ; vertNum < numVerts ; vertNum++, oldXyz += 4, newXyz += 4 )
{
idDrawVert* outvert = &tri->verts[tri->numVerts];
// interpolate the xyz
outvert->xyz.x = oldXyz[0] * oldXyzScale + newXyz[0] * newXyzScale;
outvert->xyz.y = oldXyz[1] * oldXyzScale + newXyz[1] * newXyzScale;
outvert->xyz.z = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale;
tri->numVerts++;
}
}
}
/*
=============
idRenderModelMD3::InstantiateDynamicModel
=============
*/
idRenderModel* idRenderModelMD3::InstantiateDynamicModel( const struct renderEntity_s* ent, const viewDef_t* view, idRenderModel* cachedModel )
{
int i, j;
float backlerp;
int* triangles;
int indexes;
int numVerts;
md3Surface_t* surface;
int frame, oldframe;
idRenderModelStatic* staticModel;
if( cachedModel )
{
delete cachedModel;
cachedModel = NULL;
}
staticModel = new( TAG_MODEL ) idRenderModelStatic;
staticModel->bounds.Clear();
surface = ( md3Surface_t* )( ( byte* )md3 + md3->ofsSurfaces );
// TODO: these need set by an entity
frame = ent->shaderParms[SHADERPARM_MD3_FRAME]; // probably want to keep frames < 1000 or so
oldframe = ent->shaderParms[SHADERPARM_MD3_LASTFRAME];
backlerp = ent->shaderParms[SHADERPARM_MD3_BACKLERP];
for( i = 0; i < md3->numSurfaces; i++ )
{
srfTriangles_t* tri = R_AllocStaticTriSurf();
R_AllocStaticTriSurfVerts( tri, surface->numVerts );
R_AllocStaticTriSurfIndexes( tri, surface->numTriangles * 3 );
tri->bounds.Clear();
modelSurface_t surf;
surf.geometry = tri;
md3Shader_t* shaders = ( md3Shader_t* )( ( byte* )surface + surface->ofsShaders );
surf.shader = shaders->shader;
LerpMeshVertexes( tri, surface, backlerp, frame, oldframe );
triangles = ( int* )( ( byte* )surface + surface->ofsTriangles );
indexes = surface->numTriangles * 3;
for( j = 0 ; j < indexes ; j++ )
{
tri->indexes[j] = triangles[j];
}
tri->numIndexes += indexes;
const idVec2* texCoords = ( idVec2* )( ( byte* )surface + surface->ofsSt );
numVerts = surface->numVerts;
for( j = 0; j < numVerts; j++ )
{
tri->verts[j].SetTexCoord( texCoords[j] );
}
R_BoundTriSurf( tri );
staticModel->AddSurface( surf );
staticModel->bounds.AddPoint( surf.geometry->bounds[0] );
staticModel->bounds.AddPoint( surf.geometry->bounds[1] );
// find the next surface
surface = ( md3Surface_t* )( ( byte* )surface + surface->ofsEnd );
}
return staticModel;
}
/*
=====================
idRenderModelMD3::Bounds
=====================
*/
idBounds idRenderModelMD3::Bounds( const struct renderEntity_s* ent ) const
{
idBounds ret;
ret.Clear();
if( !ent || !md3 )
{
// just give it the editor bounds
ret.AddPoint( idVec3( -10, -10, -10 ) );
ret.AddPoint( idVec3( 10, 10, 10 ) );
return ret;
}
md3Frame_t* frame = ( md3Frame_t* )( ( byte* )md3 + md3->ofsFrames );
ret.AddPoint( frame->bounds[0] );
ret.AddPoint( frame->bounds[1] );
return ret;
}
| gpl-3.0 |
nusnlp/nea | nea/asap_reader.py | 7046 | import random
import codecs
import sys
import nltk
import logging
import re
import numpy as np
import pickle as pk
logger = logging.getLogger(__name__)
num_regex = re.compile('^[+-]?[0-9]+\.?[0-9]*$')
ref_scores_dtype = 'int32'
asap_ranges = {
0: (0, 60),
1: (2,12),
2: (1,6),
3: (0,3),
4: (0,3),
5: (0,4),
6: (0,4),
7: (0,30),
8: (0,60)
}
def get_ref_dtype():
return ref_scores_dtype
def tokenize(string):
tokens = nltk.word_tokenize(string)
for index, token in enumerate(tokens):
if token == '@' and (index+1) < len(tokens):
tokens[index+1] = '@' + re.sub('[0-9]+.*', '', tokens[index+1])
tokens.pop(index)
return tokens
def get_score_range(prompt_id):
return asap_ranges[prompt_id]
def get_model_friendly_scores(scores_array, prompt_id_array):
arg_type = type(prompt_id_array)
assert arg_type in {int, np.ndarray}
if arg_type is int:
low, high = asap_ranges[prompt_id_array]
scores_array = (scores_array - low) / (high - low)
else:
assert scores_array.shape[0] == prompt_id_array.shape[0]
dim = scores_array.shape[0]
low = np.zeros(dim)
high = np.zeros(dim)
for ii in range(dim):
low[ii], high[ii] = asap_ranges[prompt_id_array[ii]]
scores_array = (scores_array - low) / (high - low)
assert np.all(scores_array >= 0) and np.all(scores_array <= 1)
return scores_array
def convert_to_dataset_friendly_scores(scores_array, prompt_id_array):
arg_type = type(prompt_id_array)
assert arg_type in {int, np.ndarray}
if arg_type is int:
low, high = asap_ranges[prompt_id_array]
scores_array = scores_array * (high - low) + low
assert np.all(scores_array >= low) and np.all(scores_array <= high)
else:
assert scores_array.shape[0] == prompt_id_array.shape[0]
dim = scores_array.shape[0]
low = np.zeros(dim)
high = np.zeros(dim)
for ii in range(dim):
low[ii], high[ii] = asap_ranges[prompt_id_array[ii]]
scores_array = scores_array * (high - low) + low
return scores_array
def is_number(token):
return bool(num_regex.match(token))
def load_vocab(vocab_path):
logger.info('Loading vocabulary from: ' + vocab_path)
with open(vocab_path, 'rb') as vocab_file:
vocab = pk.load(vocab_file)
return vocab
def create_vocab(file_path, prompt_id, maxlen, vocab_size, tokenize_text, to_lower):
logger.info('Creating vocabulary from: ' + file_path)
if maxlen > 0:
logger.info(' Removing sequences with more than ' + str(maxlen) + ' words')
total_words, unique_words = 0, 0
word_freqs = {}
with codecs.open(file_path, mode='r', encoding='UTF8') as input_file:
input_file.next()
for line in input_file:
tokens = line.strip().split('\t')
essay_id = int(tokens[0])
essay_set = int(tokens[1])
content = tokens[2].strip()
score = float(tokens[6])
if essay_set == prompt_id or prompt_id <= 0:
if to_lower:
content = content.lower()
if tokenize_text:
content = tokenize(content)
else:
content = content.split()
if maxlen > 0 and len(content) > maxlen:
continue
for word in content:
try:
word_freqs[word] += 1
except KeyError:
unique_words += 1
word_freqs[word] = 1
total_words += 1
logger.info(' %i total words, %i unique words' % (total_words, unique_words))
import operator
sorted_word_freqs = sorted(word_freqs.items(), key=operator.itemgetter(1), reverse=True)
if vocab_size <= 0:
# Choose vocab size automatically by removing all singletons
vocab_size = 0
for word, freq in sorted_word_freqs:
if freq > 1:
vocab_size += 1
vocab = {'<pad>':0, '<unk>':1, '<num>':2}
vcb_len = len(vocab)
index = vcb_len
for word, _ in sorted_word_freqs[:vocab_size - vcb_len]:
vocab[word] = index
index += 1
return vocab
def read_essays(file_path, prompt_id):
logger.info('Reading tsv from: ' + file_path)
essays_list = []
essays_ids = []
with codecs.open(file_path, mode='r', encoding='UTF8') as input_file:
input_file.next()
for line in input_file:
tokens = line.strip().split('\t')
if int(tokens[1]) == prompt_id or prompt_id <= 0:
essays_list.append(tokens[2].strip())
essays_ids.append(int(tokens[0]))
return essays_list, essays_ids
def read_dataset(file_path, prompt_id, maxlen, vocab, tokenize_text, to_lower, score_index=6, char_level=False):
logger.info('Reading dataset from: ' + file_path)
if maxlen > 0:
logger.info(' Removing sequences with more than ' + str(maxlen) + ' words')
data_x, data_y, prompt_ids = [], [], []
num_hit, unk_hit, total = 0., 0., 0.
maxlen_x = -1
with codecs.open(file_path, mode='r', encoding='UTF8') as input_file:
input_file.next()
for line in input_file:
tokens = line.strip().split('\t')
essay_id = int(tokens[0])
essay_set = int(tokens[1])
content = tokens[2].strip()
score = float(tokens[score_index])
if essay_set == prompt_id or prompt_id <= 0:
if to_lower:
content = content.lower()
if char_level:
#content = list(content)
raise NotImplementedError
else:
if tokenize_text:
content = tokenize(content)
else:
content = content.split()
if maxlen > 0 and len(content) > maxlen:
continue
indices = []
if char_level:
raise NotImplementedError
else:
for word in content:
if is_number(word):
indices.append(vocab['<num>'])
num_hit += 1
elif word in vocab:
indices.append(vocab[word])
else:
indices.append(vocab['<unk>'])
unk_hit += 1
total += 1
data_x.append(indices)
data_y.append(score)
prompt_ids.append(essay_set)
if maxlen_x < len(indices):
maxlen_x = len(indices)
logger.info(' <num> hit rate: %.2f%%, <unk> hit rate: %.2f%%' % (100*num_hit/total, 100*unk_hit/total))
return data_x, data_y, prompt_ids, maxlen_x
def get_data(paths, prompt_id, vocab_size, maxlen, tokenize_text=True, to_lower=True, sort_by_len=False, vocab_path=None, score_index=6):
train_path, dev_path, test_path = paths[0], paths[1], paths[2]
if not vocab_path:
vocab = create_vocab(train_path, prompt_id, maxlen, vocab_size, tokenize_text, to_lower)
if len(vocab) < vocab_size:
logger.warning('The vocabualry includes only %i words (less than %i)' % (len(vocab), vocab_size))
else:
assert vocab_size == 0 or len(vocab) == vocab_size
else:
vocab = load_vocab(vocab_path)
if len(vocab) != vocab_size:
logger.warning('The vocabualry includes %i words which is different from given: %i' % (len(vocab), vocab_size))
logger.info(' Vocab size: %i' % (len(vocab)))
train_x, train_y, train_prompts, train_maxlen = read_dataset(train_path, prompt_id, maxlen, vocab, tokenize_text, to_lower)
dev_x, dev_y, dev_prompts, dev_maxlen = read_dataset(dev_path, prompt_id, 0, vocab, tokenize_text, to_lower)
test_x, test_y, test_prompts, test_maxlen = read_dataset(test_path, prompt_id, 0, vocab, tokenize_text, to_lower)
overal_maxlen = max(train_maxlen, dev_maxlen, test_maxlen)
return ((train_x,train_y,train_prompts), (dev_x,dev_y,dev_prompts), (test_x,test_y,test_prompts), vocab, len(vocab), overal_maxlen, 1)
| gpl-3.0 |
ygenc/onlineLDA | onlineldavb_new/build/scipy/scipy/special/tests/test_data.py | 9545 | import os
import numpy as np
from numpy import arccosh, arcsinh, arctanh
from scipy.special import (
erf, erfc, log1p, expm1,
jn, jv, yn, yv, iv, kv, kn, gamma, gammaln, digamma, beta, cbrt,
ellipe, ellipeinc, ellipk, ellipkm1, ellipj, erfinv, erfcinv, exp1, expi,
expn, zeta, gammaincinv, lpmv
)
from scipy.special._testutils import FuncData
DATASETS = np.load(os.path.join(os.path.dirname(__file__),
"data", "boost.npz"))
def data(func, dataname, *a, **kw):
kw.setdefault('dataname', dataname)
return FuncData(func, DATASETS[dataname], *a, **kw)
def ellipk_(k):
return ellipk(k*k)
def ellipe_(k):
return ellipe(k*k)
def ellipeinc_(f, k):
return ellipeinc(f, k*k)
def ellipj_(k):
return ellipj(k*k)
def zeta_(x):
return zeta(x, 1.)
def assoc_legendre_p_boost_(nu, mu, x):
# the boost test data is for integer orders only
return lpmv(mu, nu.astype(int), x)
def legendre_p_via_assoc_(nu, x):
return lpmv(0, nu, x)
def test_boost():
TESTS = [
data(arccosh, 'acosh_data_ipp-acosh_data', 0, 1, rtol=5e-13),
data(arccosh, 'acosh_data_ipp-acosh_data', 0j, 1, rtol=5e-14),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0, 1, rtol=1e-11),
data(arcsinh, 'asinh_data_ipp-asinh_data', 0j, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0, 1, rtol=1e-11),
data(arctanh, 'atanh_data_ipp-atanh_data', 0j, 1, rtol=1e-11),
data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p',
(0,1,2), 3, rtol=1e-11),
data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p',
(0,1), 2, rtol=1e-11),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_exp_data_ipp-beta_exp_data', (0,1), 2, rtol=1e-13),
data(beta, 'beta_small_data_ipp-beta_small_data', (0,1), 2),
data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0),
data(digamma, 'digamma_data_ipp-digamma_data', 0, 1),
data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=1e-13),
data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-11),
data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-11),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1),
data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1),
data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1),
data(ellipkm1, '-ellipkm1', 0, 1),
data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1),
data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14),
data(erf, 'erf_data_ipp-erf_data', 0, 1),
data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-14),
data(erfc, 'erf_data_ipp-erf_data', 0, 2),
data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1),
data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1),
data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2),
data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1),
data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1),
data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2),
data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1),
data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1),
#data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2),
data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9),
data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13),
data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1),
data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2),
data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14),
data(gamma, 'test_gamma_data_ipp-near_0', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_1', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_2', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1),
data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9),
data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9),
data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10),
data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11),
data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11),
data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1),
data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1), 2, rtol=1e-12),
data(iv, 'bessel_i_data_ipp-bessel_i_data', (0,1j), 2, rtol=2e-10, atol=1e-306),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1), 2, rtol=1e-9),
data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', (0,1j), 2, rtol=2e-10),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11),
data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12),
data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12),
data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12,
knownfailure="Known bug in Cephes kn implementation"),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12),
data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12),
data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12),
data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-12,
knownfailure="Known bug in Cephes yv implementation"),
data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10),
data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1, param_filter=(lambda s: s > 1)),
data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1, param_filter=(lambda s: s > 1)),
data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data', (0,1), 2,
rtol=1e-12),
data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
(0,1), 2, rtol=1e-11),
# XXX: the data file needs reformatting...
#data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
# (0,1), 2),
# -- not used yet:
# assoc_legendre_p.txt
# binomial_data.txt
# binomial_large_data.txt
# binomial_quantile_data.txt
# ellint_f_data.txt
# ellint_pi2_data.txt
# ellint_pi3_data.txt
# ellint_pi3_large_data.txt
# ellint_rc_data.txt
# ellint_rd_data.txt
# ellint_rf_data.txt
# ellint_rj_data.txt
# expinti_data_long.txt
# factorials.txt
# gammap1m1_data.txt
# hermite.txt
# ibeta_data.txt
# ibeta_int_data.txt
# ibeta_inv_data.txt
# ibeta_inva_data.txt
# ibeta_large_data.txt
# ibeta_small_data.txt
# igamma_big_data.txt
# igamma_int_data.txt
# igamma_inva_data.txt
# igamma_med_data.txt
# igamma_small_data.txt
# laguerre2.txt
# laguerre3.txt
# legendre_p.txt
# legendre_p_large.txt
# ncbeta.txt
# ncbeta_big.txt
# nccs.txt
# near_0.txt
# near_1.txt
# near_2.txt
# near_m10.txt
# near_m55.txt
# negative_binomial_quantile_data.txt
# poisson_quantile_data.txt
# sph_bessel_data.txt
# sph_neumann_data.txt
# spherical_harmonic.txt
# tgamma_delta_ratio_data.txt
# tgamma_delta_ratio_int.txt
# tgamma_delta_ratio_int2.txt
# tgamma_ratio_data.txt
]
for test in TESTS:
yield _test_factory, test
def _test_factory(test, dtype=np.double):
"""Boost test"""
olderr = np.seterr(all='ignore')
try:
test.check(dtype=dtype)
finally:
np.seterr(**olderr)
| gpl-3.0 |
manojdjoshi/dnSpy | Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/Win32EnvironmentStringBuilder.cs | 1172 | /*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
using System.Text;
namespace dndbg.Engine {
static class Win32EnvironmentStringBuilder {
public static string CreateEnvironmentUnicodeString(IEnumerable<KeyValuePair<string, string>> environment) {
var sb = new StringBuilder();
foreach (var kv in environment) {
sb.Append(kv.Key);
sb.Append('=');
sb.Append(kv.Value);
sb.Append('\0');
}
sb.Append('\0');
return sb.ToString();
}
}
}
| gpl-3.0 |
jsanchezp/e-edd | es.ucm.fdi.ed2.emf.editor/src/es/ucm/fdi/emf/model/ed2/presentation/Ed2ActionBarContributor.java | 14342 | /**
*/
package es.ucm.fdi.emf.model.ed2.presentation;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.ui.action.ControlAction;
import org.eclipse.emf.edit.ui.action.CreateChildAction;
import org.eclipse.emf.edit.ui.action.CreateSiblingAction;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.action.LoadResourceAction;
import org.eclipse.emf.edit.ui.action.ValidateAction;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.SubContributionItem;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
/**
* This is the action bar contributor for the Ed2 model editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class Ed2ActionBarContributor
extends EditingDomainActionBarContributor
implements ISelectionChangedListener {
/**
* This keeps track of the active editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IEditorPart activeEditorPart;
/**
* This keeps track of the current selection provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ISelectionProvider selectionProvider;
/**
* This action opens the Properties view.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IAction showPropertiesViewAction =
new Action(Ed2EditorPlugin.INSTANCE.getString("_UI_ShowPropertiesView_menu_item")) {
@Override
public void run() {
try {
getPage().showView("org.eclipse.ui.views.PropertySheet");
}
catch (PartInitException exception) {
Ed2EditorPlugin.INSTANCE.log(exception);
}
}
};
/**
* This action refreshes the viewer of the current editor if the editor
* implements {@link org.eclipse.emf.common.ui.viewer.IViewerProvider}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IAction refreshViewerAction =
new Action(Ed2EditorPlugin.INSTANCE.getString("_UI_RefreshViewer_menu_item")) {
@Override
public boolean isEnabled() {
return activeEditorPart instanceof IViewerProvider;
}
@Override
public void run() {
if (activeEditorPart instanceof IViewerProvider) {
Viewer viewer = ((IViewerProvider)activeEditorPart).getViewer();
if (viewer != null) {
viewer.refresh();
}
}
}
};
/**
* This will contain one {@link org.eclipse.emf.edit.ui.action.CreateChildAction} corresponding to each descriptor
* generated for the current selection by the item provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> createChildActions;
/**
* This is the menu manager into which menu contribution items should be added for CreateChild actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createChildMenuManager;
/**
* This will contain one {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} corresponding to each descriptor
* generated for the current selection by the item provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> createSiblingActions;
/**
* This is the menu manager into which menu contribution items should be added for CreateSibling actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createSiblingMenuManager;
/**
* This creates an instance of the contributor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Ed2ActionBarContributor() {
super(ADDITIONS_LAST_STYLE);
loadResourceAction = new LoadResourceAction();
validateAction = new ValidateAction();
controlAction = new ControlAction();
}
/**
* This adds Separators for editor additions to the tool bar.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void contributeToToolBar(IToolBarManager toolBarManager) {
toolBarManager.add(new Separator("ed2-settings"));
toolBarManager.add(new Separator("ed2-additions"));
}
/**
* This adds to the menu bar a menu and some separators for editor additions,
* as well as the sub-menus for object creation items.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void contributeToMenu(IMenuManager menuManager) {
super.contributeToMenu(menuManager);
IMenuManager submenuManager = new MenuManager(Ed2EditorPlugin.INSTANCE.getString("_UI_Ed2Editor_menu"), "es.ucm.fdi.emf.model.ed2MenuID");
menuManager.insertAfter("additions", submenuManager);
submenuManager.add(new Separator("settings"));
submenuManager.add(new Separator("actions"));
submenuManager.add(new Separator("additions"));
submenuManager.add(new Separator("additions-end"));
// Prepare for CreateChild item addition or removal.
//
createChildMenuManager = new MenuManager(Ed2EditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item"));
submenuManager.insertBefore("additions", createChildMenuManager);
// Prepare for CreateSibling item addition or removal.
//
createSiblingMenuManager = new MenuManager(Ed2EditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item"));
submenuManager.insertBefore("additions", createSiblingMenuManager);
// Force an update because Eclipse hides empty menus now.
//
submenuManager.addMenuListener
(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuManager) {
menuManager.updateAll(true);
}
});
addGlobalActions(submenuManager);
}
/**
* When the active editor changes, this remembers the change and registers with it as a selection provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
activeEditorPart = part;
// Switch to the new selection provider.
//
if (selectionProvider != null) {
selectionProvider.removeSelectionChangedListener(this);
}
if (part == null) {
selectionProvider = null;
}
else {
selectionProvider = part.getSite().getSelectionProvider();
selectionProvider.addSelectionChangedListener(this);
// Fake a selection changed event to update the menus.
//
if (selectionProvider.getSelection() != null) {
selectionChanged(new SelectionChangedEvent(selectionProvider, selectionProvider.getSelection()));
}
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionChangedListener},
* handling {@link org.eclipse.jface.viewers.SelectionChangedEvent}s by querying for the children and siblings
* that can be added to the selected object and updating the menus accordingly.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void selectionChanged(SelectionChangedEvent event) {
// Remove any menu items for old selection.
//
if (createChildMenuManager != null) {
depopulateManager(createChildMenuManager, createChildActions);
}
if (createSiblingMenuManager != null) {
depopulateManager(createSiblingMenuManager, createSiblingActions);
}
// Query the new selection for appropriate new child/sibling descriptors
//
Collection<?> newChildDescriptors = null;
Collection<?> newSiblingDescriptors = null;
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection && ((IStructuredSelection)selection).size() == 1) {
Object object = ((IStructuredSelection)selection).getFirstElement();
EditingDomain domain = ((IEditingDomainProvider)activeEditorPart).getEditingDomain();
newChildDescriptors = domain.getNewChildDescriptors(object, null);
newSiblingDescriptors = domain.getNewChildDescriptors(null, object);
}
// Generate actions for selection; populate and redraw the menus.
//
createChildActions = generateCreateChildActions(newChildDescriptors, selection);
createSiblingActions = generateCreateSiblingActions(newSiblingDescriptors, selection);
if (createChildMenuManager != null) {
populateManager(createChildMenuManager, createChildActions, null);
createChildMenuManager.update(true);
}
if (createSiblingMenuManager != null) {
populateManager(createSiblingMenuManager, createSiblingActions, null);
createSiblingMenuManager.update(true);
}
}
/**
* This generates a {@link org.eclipse.emf.edit.ui.action.CreateChildAction} for each object in <code>descriptors</code>,
* and returns the collection of these actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> generateCreateChildActions(Collection<?> descriptors, ISelection selection) {
Collection<IAction> actions = new ArrayList<IAction>();
if (descriptors != null) {
for (Object descriptor : descriptors) {
actions.add(new CreateChildAction(activeEditorPart, selection, descriptor));
}
}
return actions;
}
/**
* This generates a {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} for each object in <code>descriptors</code>,
* and returns the collection of these actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> generateCreateSiblingActions(Collection<?> descriptors, ISelection selection) {
Collection<IAction> actions = new ArrayList<IAction>();
if (descriptors != null) {
for (Object descriptor : descriptors) {
actions.add(new CreateSiblingAction(activeEditorPart, selection, descriptor));
}
}
return actions;
}
/**
* This populates the specified <code>manager</code> with {@link org.eclipse.jface.action.ActionContributionItem}s
* based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection,
* by inserting them before the specified contribution item <code>contributionID</code>.
* If <code>contributionID</code> is <code>null</code>, they are simply added.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void populateManager(IContributionManager manager, Collection<? extends IAction> actions, String contributionID) {
if (actions != null) {
for (IAction action : actions) {
if (contributionID != null) {
manager.insertBefore(contributionID, action);
}
else {
manager.add(action);
}
}
}
}
/**
* This removes from the specified <code>manager</code> all {@link org.eclipse.jface.action.ActionContributionItem}s
* based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void depopulateManager(IContributionManager manager, Collection<? extends IAction> actions) {
if (actions != null) {
IContributionItem[] items = manager.getItems();
for (int i = 0; i < items.length; i++) {
// Look into SubContributionItems
//
IContributionItem contributionItem = items[i];
while (contributionItem instanceof SubContributionItem) {
contributionItem = ((SubContributionItem)contributionItem).getInnerItem();
}
// Delete the ActionContributionItems with matching action.
//
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem)contributionItem).getAction();
if (actions.contains(action)) {
manager.remove(contributionItem);
}
}
}
}
}
/**
* This populates the pop-up menu before it appears.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void menuAboutToShow(IMenuManager menuManager) {
super.menuAboutToShow(menuManager);
MenuManager submenuManager = null;
submenuManager = new MenuManager(Ed2EditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item"));
populateManager(submenuManager, createChildActions, null);
menuManager.insertBefore("edit", submenuManager);
submenuManager = new MenuManager(Ed2EditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item"));
populateManager(submenuManager, createSiblingActions, null);
menuManager.insertBefore("edit", submenuManager);
}
/**
* This inserts global actions before the "additions-end" separator.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void addGlobalActions(IMenuManager menuManager) {
menuManager.insertAfter("additions-end", new Separator("ui-actions"));
menuManager.insertAfter("ui-actions", showPropertiesViewAction);
refreshViewerAction.setEnabled(refreshViewerAction.isEnabled());
menuManager.insertAfter("ui-actions", refreshViewerAction);
super.addGlobalActions(menuManager);
}
/**
* This ensures that a delete action will clean up all references to deleted objects.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean removeAllReferencesOnDelete() {
return true;
}
}
| gpl-3.0 |
bowhan/bowtie2 | scripts/test/regressions.py | 8745 | #!/usr/bin/env python
import os
import inspect
import unittest
import logging
import shutil
import bt2face
import dataface
import btdata
from optparse import OptionParser
class TestRegressions(unittest.TestCase):
"""
Main regression fixture.
"""
def test_288(self):
""" Check if --un option works correctly when used with --no-unal
"""
# run --un and record unaligned file size and orig file size
# run --no-unal and record file size
# check if --no-unali + --un files size equal the orig file size
out_sam = 'test288_out.sam'
not_algn = 'test288_nal.fastq'
ref_index = os.path.join(g_bdata.index_dir_path,'lambda_virus')
reads = os.path.join(g_bdata.reads_dir_path,'longreads.fq')
args = "--quiet -x %s -U %s -a --un %s -S %s" % (ref_index,reads,not_algn,out_sam)
ret = g_bt.run(args)
self.assertEqual(ret,0)
sam_size = dataface.SamFile(out_sam).size()
no_algn_size = dataface.FastaQFile(not_algn).size()
args = "--quiet -x %s -U %s -a --un %s --no-unal -S %s" % (ref_index,reads,not_algn,out_sam)
ret = g_bt.run(args)
self.assertEqual(ret,0)
no_al_sam_size = dataface.SamFile(out_sam).size()
self.assertEqual(no_al_sam_size + no_algn_size, sam_size)
os.remove(out_sam)
os.remove(not_algn)
def test_279(self):
""" Check if --un-conc option works correctly when used with --no-unal
"""
out_no_conc = 'test279_nconc.fq'
out_conc = 'test279_conc.fq'
out_sam = 'test279.sam'
out_p1_nc = 'test279_nconc.1.fq'
out_p2_nc = 'test279_nconc.2.fq'
out_p1_conc = 'test279_conc.1.fq'
out_p2_conc = 'test279_conc.2.fq'
ref_index = os.path.join(g_bdata.index_dir_path,'lambda_virus')
pairs_1 = os.path.join(g_bdata.reads_dir_path,'reads_1.fq')
pairs_2 = os.path.join(g_bdata.reads_dir_path,'reads_2.fq')
args = "--quiet -x %s -1 %s -2 %s --un-conc %s --dovetail --al-conc %s -S %s" % (ref_index,pairs_1,pairs_2,out_no_conc,out_conc,out_sam)
ret = g_bt.run(args)
self.assertEqual(ret,0)
conc_p1_size_step1 = dataface.FastaQFile(out_p1_conc).size()
conc_p2_size_step1 = dataface.FastaQFile(out_p2_conc).size()
nc_p1_size_step1 = dataface.FastaQFile(out_p1_nc).size()
nc_p2_size_step1 = dataface.FastaQFile(out_p2_nc).size()
self.assertEqual(conc_p1_size_step1, conc_p2_size_step1, "Number of concordant sequences in pass 1 should match.")
self.assertEqual(nc_p1_size_step1, nc_p2_size_step1, "Number of non-concordant sequences in pass 1 should match.")
args = "--quiet -x %s -1 %s -2 %s --no-unal --un-conc %s --dovetail --al-conc %s -S %s" % (ref_index,pairs_1,pairs_2,out_no_conc,out_conc,out_sam)
ret = g_bt.run(args)
self.assertEqual(ret,0)
conc_p1_size_step2 = dataface.FastaQFile(out_p1_conc).size()
conc_p2_size_step2 = dataface.FastaQFile(out_p2_conc).size()
nc_p1_size_step2 = dataface.FastaQFile(out_p1_nc).size()
nc_p2_size_step2 = dataface.FastaQFile(out_p2_nc).size()
self.assertEqual(conc_p1_size_step2, conc_p2_size_step2, "Number of concordant sequences in pass 2 should match.")
self.assertEqual(nc_p1_size_step2, nc_p2_size_step2, "Number of non-concordant sequences in pass 2 should match.")
self.assertEqual(conc_p1_size_step1, conc_p1_size_step2, "Number of concordant sequences in both steps should match.")
self.assertEqual(conc_p2_size_step1, conc_p2_size_step2, "Number of concordant sequences in both steps should match.")
self.assertEqual(nc_p1_size_step1, nc_p1_size_step2, "Number of non-concordant sequences in both steps should match.")
self.assertEqual(nc_p2_size_step1, nc_p2_size_step2, "Number of non-concordant sequences in both steps should match.")
self.assertTrue(1,"temp")
os.remove(out_p1_conc)
os.remove(out_p2_conc)
os.remove(out_p1_nc)
os.remove(out_p2_nc)
os.remove(out_sam)
def test_version(self):
""" Check if --version option works correctly.
"""
args = "--version"
ret = g_bt.silent_run(args)
self.assertEqual(ret,0)
def test_x_option(self):
""" Check if -x is indeed mandatory.
"""
ref_index = os.path.join(g_bdata.index_dir_path,'lambda_virus')
reads = os.path.join(g_bdata.reads_dir_path,'longreads.fq')
out_sam = 'test_x_option.sam'
args = "%s -U %s -S %s " % (ref_index,reads,out_sam)
ret = g_bt.silent_run(args)
self.assertNotEqual(ret,0)
args = "-x %s -U %s -S %s " % (ref_index,reads,out_sam)
ret = g_bt.silent_run(args)
self.assertEqual(ret, 0)
os.remove(out_sam)
def test_313(self):
""" Check if --un-conc, --al-conc, --un, --al do not fail in case of a dot
character present in their path name.
"""
ref_index = os.path.join(g_bdata.index_dir_path,'lambda_virus')
pairs_1 = os.path.join(g_bdata.reads_dir_path,'reads_1.fq')
pairs_2 = os.path.join(g_bdata.reads_dir_path,'reads_2.fq')
no_dot_dir = 'nodotdir'
dot_dir = 'v.12_.test'
un_basename = 'bname'
out_spec = os.path.join(no_dot_dir,un_basename)
out_spec_dot= os.path.join(dot_dir,un_basename)
args = "--quiet -x %s -1 %s -2 %s --un-conc %s -S %s" % (ref_index,pairs_1,pairs_2,out_spec,os.devnull)
try:
os.makedirs(no_dot_dir)
os.makedirs(dot_dir)
except:
pass
ret = g_bt.silent_run(args)
self.assertEqual(ret, 0)
mate1_count = dataface.FastaQFile(out_spec + '.1').size()
args = "--quiet -x %s -1 %s -2 %s --un-conc %s -S %s" % (ref_index,pairs_1,pairs_2,out_spec_dot,os.devnull)
ret = g_bt.silent_run(args)
self.assertEqual(ret, 0, "--un-conc should work with dots in its path.")
mate1_count_dot = dataface.FastaQFile(out_spec_dot + '.1').size()
self.assertEqual(mate1_count, mate1_count_dot, "Number of seqs should be the same.")
args = "--quiet -x %s -1 %s -2 %s --un-conc %s -S %s" % (ref_index,pairs_1,pairs_2,dot_dir,os.devnull)
ret = g_bt.silent_run(args)
self.assertEqual(ret, 0, "--un-conc should work with a path only.")
mate1_fs = os.path.join(dot_dir,"un-conc-mate.1")
self.assertTrue(os.path.isfile(mate1_fs), "--un-conc output is missing for path only case.")
mate1_count_dot_only = dataface.FastaQFile(mate1_fs).size()
self.assertEqual(mate1_count, mate1_count_dot_only, "Number of seqs should be the same.")
args= "--quiet -x %s -1 %s -2 %s --un-conc %s --al-conc %s --un %s -S %s" % (ref_index,pairs_1,pairs_2,dot_dir,dot_dir,dot_dir,os.devnull)
ret = g_bt.run(args)
self.assertEqual(ret, 0)
mate1_al = os.path.join(dot_dir,"al-conc-mate.1")
mate1_un = os.path.join(dot_dir,"un-seqs")
self.assertTrue(
os.path.isfile(mate1_fs) and
os.path.isfile(mate1_al) and
os.path.isfile(mate1_un),
"--un-conc, --al-conc and --un should not clobber"
)
shutil.rmtree(no_dot_dir)
shutil.rmtree(dot_dir)
def get_suite():
loader = unittest.TestLoader()
return loader.loadTestsFromTestCase(TestRegressions)
def parse_args():
usage = " %prog [options] \n\n"
usage += "Some regression tests.\n"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
action="store_true",dest="verbose", default=False,
help="Print more info about each test.")
(options, args) = parser.parse_args()
return options
g_bdata = None
g_bt = None
if __name__ == "__main__":
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.ERROR)
options = parse_args()
runner = unittest.TextTestRunner()
if options.verbose:
logging.getLogger().setLevel(level=logging.INFO)
runner = unittest.TextTestRunner(verbosity=2)
src_file_path = os.path.realpath(inspect.getsourcefile(parse_args))
curr_path = os.path.dirname(src_file_path)
bw2_subdir = 'bowtie2'
i = curr_path.find(bw2_subdir)
bt2_path = curr_path[:i+len(bw2_subdir)]
g_bdata = btdata.ExampleData(bt2_path)
g_bt = bt2face.BowtieSuite(bt2_path)
runner.run(get_suite())
| gpl-3.0 |
TeoTwawki/darkstar | scripts/zones/Kazham/npcs/Dodmos.lua | 2684 | -----------------------------------
-- Area: Kazham
-- NPC: Dodmos
-- Starts Quest: Trial Size Trial By Fire
-- !pos 102.647 -14.999 -97.664 250
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/teleports");
local ID = require("scripts/zones/Kazham/IDs");
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1544,1) == true and player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_FIRE) == QUEST_ACCEPTED and player:getMainJob() == dsp.job.SMN) then
player:startEvent(287,0,1544,0,20);
end
end;
function onTrigger(player,npc)
local TrialSizeFire = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_FIRE);
if (player:getMainLvl() >= 20 and player:getMainJob() == dsp.job.SMN and TrialSizeFire == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 2) then --Requires player to be Summoner at least lvl 20
player:startEvent(286,0,1544,0,20); --mini tuning fork, zone, level
elseif (TrialSizeFire == QUEST_ACCEPTED) then
local FireFork = player:hasItem(1544);
if (FireFork == true) then
player:startEvent(272); --Dialogue given to remind player to be prepared
elseif (FireFork == false and tonumber(os.date("%j")) ~= player:getVar("TrialSizeFire_date")) then
player:startEvent(290,0,1544,0,20); --Need another mini tuning fork
end
elseif (TrialSizeFire == QUEST_COMPLETED) then
player:startEvent(289); --Defeated Avatar
else
player:startEvent(275); --Standard dialogue
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 286 and option == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,1544); --Mini tuning fork
else
player:setVar("TrialSizeFire_date", 0);
player:addQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_FIRE);
player:addItem(1544);
player:messageSpecial(ID.text.ITEM_OBTAINED,1544);
end
elseif (csid == 290 and option == 1) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,1544); --Mini tuning fork
else
player:addItem(1544);
player:messageSpecial(ID.text.ITEM_OBTAINED,1544);
end
elseif (csid == 287 and option == 1) then
dsp.teleport.to(player, dsp.teleport.id.CLOISTER_OF_FLAMES);
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Ship_bound_for_Selbina/mobs/Sea_Crab.lua | 821 | -----------------------------------
-- Area: Ship bound for Selbina (220)
-- Mob: Sea_Crab
-----------------------------------
-- require("scripts/zones/Ship_bound_for_Selbina/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| gpl-3.0 |
Zefz/egoboo | game/src/game/GUI/MessageLog.hpp | 1819 | //********************************************************************************************
//*
//* This file is part of Egoboo.
//*
//* Egoboo 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.
//*
//* Egoboo 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 Egoboo. If not, see <http://www.gnu.org/licenses/>.
//*
//********************************************************************************************
/// @file game/GUI/MessageLog.hpp
/// @author Johan Jansen
#pragma once
#include "game/GUI/Component.hpp"
namespace Ego {
namespace GUI {
class MessageLog : public Component {
public:
MessageLog();
virtual void draw(DrawingContext& drawingContext) override;
void addMessage(const std::string &message);
private:
static constexpr uint32_t MESSAGE_DURATION_MS = 3000; //How many milliseconds a message should be rendered before it is removed
static constexpr uint32_t MESSAGE_FADE_TIME_MS = 700; //How many milliseconds it takes to fade away completely
struct Message {
public:
Message(const std::string& setText, uint32_t ticks) :
text(setText),
lifeTime(ticks) {
//ctor
}
std::string text;
uint32_t lifeTime;
};
std::list<Message> _messages;
};
} // namespace GUI
} // namespace Ego
| gpl-3.0 |
fdelapena/easyrpg-editor-qt | src/gamecharacter.cpp | 10592 | #include "gamecharacter.h"
GameCharacter::GameCharacter() :
m_name(""),
m_title(""),
m_minlvl(1),
m_maxlvl(99),
m_docritical(true),
m_critical(30),
m_dualweapons(false),
m_fixedequip(false),
m_ai(false),
m_strongdefense(false),
m_profession(-1),
m_facename("<none>"),
m_faceindex(0),
m_charaname("<none>"),
m_charaindex(0),
m_charatranslucent(false),
m_battleset(-1),
m_expinitial(300),
m_expincrement(300),
m_expcorrection(0),
m_initialweapon(-1),
m_initialshield(-1),
m_initialarmor(-1),
m_initialhelmet(-1),
m_initialother(-1),
m_battleranimation(-1)
{
for (int i = 0; i < 100; i++) {
m_hpcurve.append(1);
m_mpcurve.append(0);
m_attackcurve.append(1);
m_defensecurve.append(1);
m_intelligencecurve.append(1);
m_agilitycurve.append(1);
}
}
GameCharacter::GameCharacter(const GameCharacter &other) :
m_name(other.m_name),
m_title(other.m_title),
m_minlvl(other.m_minlvl),
m_maxlvl(other.m_maxlvl),
m_docritical(other.m_docritical),
m_critical(other.m_critical),
m_dualweapons(other.m_dualweapons),
m_fixedequip(other.m_fixedequip),
m_ai(other.m_ai),
m_strongdefense(other.m_strongdefense),
m_profession(other.m_profession),
m_facename(other.m_facename),
m_faceindex(other.m_faceindex),
m_charaname(other.m_charaname),
m_charaindex(other.m_charaindex),
m_charatranslucent(other.m_charatranslucent),
m_battleset(other.m_battleset),
m_expinitial(other.m_expinitial),
m_expincrement(other.m_expincrement),
m_expcorrection(other.m_expcorrection),
m_initialweapon(other.m_initialweapon),
m_initialshield(other.m_initialshield),
m_initialarmor(other.m_initialarmor),
m_initialhelmet(other.m_initialhelmet),
m_initialother(other.m_initialother),
m_battleranimation(other.m_battleranimation)
{
for (int i = 0; i < 100; i++) {
m_hpcurve.append(other.m_hpcurve[i]);
m_mpcurve.append(other.m_mpcurve[i]);
m_attackcurve.append(other.m_attackcurve[i]);
m_defensecurve.append(other.m_defensecurve[i]);
m_intelligencecurve.append(other.m_intelligencecurve[i]);
m_agilitycurve.append(other.m_agilitycurve[i]);
}
}
GameCharacter::~GameCharacter()
{
}
GameCharacter &GameCharacter::operator=(const GameCharacter &other)
{
if (this != &other){
this->~GameCharacter();
new (this) GameCharacter(other);
}
return *this;
}
bool GameCharacter::operator==(const GameCharacter &other)
{
#define check(var) var == other.var
return (check(m_name) &&
check(m_title) &&
check(m_minlvl) &&
check(m_maxlvl) &&
check(m_docritical) &&
check(m_critical) &&
check(m_dualweapons) &&
check(m_fixedequip) &&
check(m_ai) &&
check(m_strongdefense) &&
check(m_profession) &&
check(m_battleset) &&
check(m_initialweapon) &&
check(m_initialshield) &&
check(m_initialarmor) &&
check(m_initialhelmet) &&
check(m_initialother) &&
check(m_battleranimation) &&
check(m_faceindex) &&
check(m_facename) &&
check(m_charaindex) &&
check(m_charaname) &&
check(m_charatranslucent) &&
check(m_expinitial) &&
check(m_expincrement) &&
check(m_expcorrection) &&
check(m_hpcurve) &&
check(m_mpcurve) &&
check(m_attackcurve) &&
check(m_defensecurve) &&
check(m_intelligencecurve) &&
check(m_agilitycurve));
#undef check
}
bool GameCharacter::operator!=(const GameCharacter &other)
{
return !(this->operator ==(other));
}
void GameCharacter::name(QString n_name) {m_name = n_name;}
void GameCharacter::title(QString n_title) {m_title = n_title;}
void GameCharacter::minlvl(int n_lvl) {m_minlvl = n_lvl;}
void GameCharacter::maxlvl(int n_lvl) {m_maxlvl = n_lvl;}
void GameCharacter::docritical(bool n_crit) {m_docritical = n_crit;}
void GameCharacter::critical(int n_critical) {m_critical = n_critical;}
void GameCharacter::dualweapons(bool n_dual) {m_dualweapons = n_dual;}
void GameCharacter::fixedequip(bool n_fixed) {m_fixedequip = n_fixed;}
void GameCharacter::ai(bool n_ai) {m_ai = n_ai;}
void GameCharacter::strongdefense(bool n_sdef) {m_strongdefense = n_sdef;}
void GameCharacter::profession(int n_profession) {m_profession = n_profession;}
void GameCharacter::faceset(QString n_facename, int n_faceindex) {m_facename = n_facename;
m_faceindex = n_faceindex;}
void GameCharacter::facename(QString n_facename) {m_facename = n_facename;}
void GameCharacter::faceindex(int n_faceindex) {m_faceindex = n_faceindex;}
void GameCharacter::charaset(QString n_charaname, int n_charaindex) {m_charaname = n_charaname;
m_charaindex = n_charaindex;}
void GameCharacter::charaname(QString n_charaname) {m_charaname = n_charaname;}
void GameCharacter::charaindex(int n_charaindex) {m_charaindex = n_charaindex;}
void GameCharacter::charatranslucent(bool n_charatranslucent) {m_charatranslucent = n_charatranslucent;}
void GameCharacter::battleset(int n_battleset) {m_battleset = n_battleset;}
void GameCharacter::hpcurve(QVector<int> n_curve) {m_hpcurve = n_curve;}
void GameCharacter::mpcurve(QVector<int> n_curve) {m_mpcurve = n_curve;}
void GameCharacter::attackcurve(QVector<int> n_curve) {m_attackcurve = n_curve;}
void GameCharacter::defensecurve(QVector<int> n_curve) {m_defensecurve = n_curve;}
void GameCharacter::intelligencecurve(QVector<int> n_curve) {m_intelligencecurve = n_curve;}
void GameCharacter::agilitycurve(QVector<int> n_curve) {m_agilitycurve = n_curve;}
void GameCharacter::expcurve(int n_expinitial, int n_expincrement, int n_expcorrection) {m_expinitial = n_expinitial;
m_expincrement = n_expincrement;
m_expcorrection = n_expcorrection;}
void GameCharacter::expinitial(int n_expinitial) {m_expinitial = n_expinitial;}
void GameCharacter::expincrement(int n_expincrement) {m_expincrement = n_expincrement;}
void GameCharacter::expcorrection(int n_expcorrection) {m_expcorrection = n_expcorrection;}
void GameCharacter::initialweapon(int n_initialequip) {m_initialweapon = n_initialequip;}
void GameCharacter::initialshield(int n_initialequip) {m_initialshield = n_initialequip;}
void GameCharacter::initialarmor(int n_initialequip) {m_initialarmor = n_initialequip;}
void GameCharacter::initialhelmet(int n_initialequip) {m_initialhelmet = n_initialequip;}
void GameCharacter::initialother(int n_initialequip) {m_initialother = n_initialequip;}
int GameCharacter::battleranimation() const {return m_battleranimation;}
void GameCharacter::battleranimation(int n_animation) {m_battleranimation = n_animation;}
QMap<int, int> *GameCharacter::skills() {return &m_skills;}
void GameCharacter::regskill(int skill_id, int lvl) {m_skills.insert(skill_id, lvl);}
void GameCharacter::unregskill(int skill_id) {m_skills.remove(skill_id);}
QList<int> GameCharacter::skilllist() {return m_skills.keys();}
QMap<int, int> *GameCharacter::attributeranks() {return &m_attranks;}
QMap<int, int> *GameCharacter::statusranks() {return &m_stsranks;}
void GameCharacter::setattrank(int n_rankid, int n_rankvalue) {m_attranks.insert(n_rankid, n_rankvalue);}
void GameCharacter::setstsrank(int n_rankid, int n_rankvalue) {m_stsranks.insert(n_rankid, n_rankvalue);}
int GameCharacter::getattrank(int att_id) const {if (att_id >= 0 && att_id < m_attranks.keys().count()) return m_attranks[att_id]; else return 0;}
int GameCharacter::getstsrank(int sts_id) const {if (sts_id >= 0 && sts_id < m_stsranks.keys().count()) return m_stsranks[sts_id]; else return 0;}
QMap<int, QVariant> *GameCharacter::customProperties() {return &m_customProperties;}
QVariant GameCharacter::getcustom(const int c_id) const {return m_customProperties[c_id];}
void GameCharacter::setcustom(const int c_id, QVariant n_custom) {m_customProperties[c_id] = n_custom;}
int GameCharacter::initialother() const {return m_initialother;}
int GameCharacter::initialhelmet() const {return m_initialhelmet;}
int GameCharacter::initialarmor() const {return m_initialarmor;}
int GameCharacter::initialshield() const {return m_initialshield;}
int GameCharacter::initialweapon() const {return m_initialweapon;}
int GameCharacter::expcorrection() const {return m_expcorrection;}
int GameCharacter::expincrement() const {return m_expincrement;}
int GameCharacter::expinitial() const {return m_expinitial;}
QVector<int> GameCharacter::agilitycurve() const {return m_agilitycurve;}
QVector<int> GameCharacter::intelligencecurve() const {return m_intelligencecurve;}
QVector<int> GameCharacter::defensecurve() const {return m_defensecurve;}
QVector<int> GameCharacter::attackcurve() const {return m_attackcurve;}
QVector<int> GameCharacter::mpcurve() const {return m_mpcurve;}
QVector<int> GameCharacter::hpcurve() const {return m_hpcurve;}
int GameCharacter::battleset() const {return m_battleset;}
bool GameCharacter::charatranslucent() const {return m_charatranslucent;}
int GameCharacter::charaindex() const {return m_charaindex;}
QString GameCharacter::charaname() const {return m_charaname;}
int GameCharacter::faceindex() const {return m_faceindex;}
QString GameCharacter::facename() const {return m_facename;}
int GameCharacter::profession() const {return m_profession;}
bool GameCharacter::strongdefense() const {return m_strongdefense;}
bool GameCharacter::ai() const {return m_ai;}
bool GameCharacter::fixedequip() const {return m_fixedequip;}
bool GameCharacter::dualweapons() const {return m_dualweapons;}
int GameCharacter::critical() const {return m_critical;}
bool GameCharacter::docritical() const {return m_docritical;}
int GameCharacter::maxlvl() const {return m_maxlvl;}
int GameCharacter::minlvl() const {return m_minlvl;}
QString GameCharacter::title() const {return m_title;}
QString GameCharacter::name() const {return m_name;}
| gpl-3.0 |
ashleyblackmore/cpp-ethereum | libwebthree/WebThree.cpp | 4510 | /*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WebThree.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "WebThree.h"
#include <chrono>
#include <thread>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <libdevcore/Log.h>
#include <libethereum/Defaults.h>
#include <libethereum/EthereumHost.h>
#include <libwhisper/WhisperHost.h>
#include "BuildInfo.h"
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::eth;
using namespace dev::shh;
WebThreeDirect::WebThreeDirect(
std::string const& _clientVersion,
std::string const& _dbPath,
WithExisting _we,
std::set<std::string> const& _interfaces,
NetworkPreferences const& _n,
bytesConstRef _network
):
m_clientVersion(_clientVersion),
m_net(_clientVersion, _n, _network)
{
if (_dbPath.size())
Defaults::setDBPath(_dbPath);
if (_interfaces.count("eth"))
{
m_ethereum.reset(new eth::EthashClient(&m_net, shared_ptr<GasPricer>(), _dbPath, _we, 0));
string bp = DEV_QUOTED(ETH_BUILD_PLATFORM);
vector<string> bps;
boost::split(bps, bp, boost::is_any_of("/"));
bps[0] = bps[0].substr(0, 5);
bps[1] = bps[1].substr(0, 3);
bps.back() = bps.back().substr(0, 3);
m_ethereum->setExtraData(rlpList(0, string(dev::Version) + "++" + string(DEV_QUOTED(ETH_COMMIT_HASH)).substr(0, 4) + (ETH_CLEAN_REPO ? "-" : "*") + string(DEV_QUOTED(ETH_BUILD_TYPE)).substr(0, 1) + boost::join(bps, "/")));
}
if (_interfaces.count("shh"))
m_whisper = m_net.registerCapability<WhisperHost>(new WhisperHost);
}
WebThreeDirect::~WebThreeDirect()
{
// Utterly horrible right now - WebThree owns everything (good), but:
// m_net (Host) owns the eth::EthereumHost via a shared_ptr.
// The eth::EthereumHost depends on eth::Client (it maintains a reference to the BlockChain field of Client).
// eth::Client (owned by us via a unique_ptr) uses eth::EthereumHost (via a weak_ptr).
// Really need to work out a clean way of organising ownership and guaranteeing startup/shutdown is perfect.
// Have to call stop here to get the Host to kill its io_service otherwise we end up with left-over reads,
// still referencing Sessions getting deleted *after* m_ethereum is reset, causing bad things to happen, since
// the guarantee is that m_ethereum is only reset *after* all sessions have ended (sessions are allowed to
// use bits of data owned by m_ethereum).
m_net.stop();
m_ethereum.reset();
}
std::string WebThreeDirect::composeClientVersion(std::string const& _client, std::string const& _clientName)
{
return _client + "-" + "v" + dev::Version + "-" + string(DEV_QUOTED(ETH_COMMIT_HASH)).substr(0, 8) + (ETH_CLEAN_REPO ? "" : "*") + "/" + _clientName + "/" DEV_QUOTED(ETH_BUILD_TYPE) "-" DEV_QUOTED(ETH_BUILD_PLATFORM);
}
p2p::NetworkPreferences const& WebThreeDirect::networkPreferences() const
{
return m_net.networkPreferences();
}
void WebThreeDirect::setNetworkPreferences(p2p::NetworkPreferences const& _n, bool _dropPeers)
{
auto had = isNetworkStarted();
if (had)
stopNetwork();
m_net.setNetworkPreferences(_n, _dropPeers);
if (had)
startNetwork();
}
std::vector<PeerSessionInfo> WebThreeDirect::peers()
{
return m_net.peerSessionInfo();
}
size_t WebThreeDirect::peerCount() const
{
return m_net.peerCount();
}
void WebThreeDirect::setIdealPeerCount(size_t _n)
{
return m_net.setIdealPeerCount(_n);
}
void WebThreeDirect::setPeerStretch(size_t _n)
{
return m_net.setPeerStretch(_n);
}
bytes WebThreeDirect::saveNetwork()
{
return m_net.saveNetwork();
}
void WebThreeDirect::addNode(NodeId const& _node, bi::tcp::endpoint const& _host)
{
m_net.addNode(_node, NodeIPEndpoint(_host.address(), _host.port(), _host.port()));
}
void WebThreeDirect::requirePeer(NodeId const& _node, bi::tcp::endpoint const& _host)
{
m_net.requirePeer(_node, NodeIPEndpoint(_host.address(), _host.port(), _host.port()));
}
| gpl-3.0 |
MoonLightDE/MoonLightDE | src/notifications/src/notifyd.cpp | 4317 | /* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alec Moskvin <alecm@gmx.com>
* Petr Vanek <petr@scribus.info>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "notifyd.h"
#include <QDebug>
/*
* Implementation of class Notifyd
*/
Notifyd::Notifyd(QObject* parent) : mId(0) {
m_area = new NotificationArea();
m_settings = new LxQt::Settings("notifications");
reloadSettings();
connect(this, SIGNAL(notificationAdded(uint, QString, QString, QString, QString, int, QStringList, QVariantMap)),
m_area->layout(), SLOT(addNotification(uint, QString, QString, QString, QString, int, QStringList, QVariantMap)));
connect(this, SIGNAL(notificationClosed(uint, uint)),
m_area->layout(), SLOT(removeNotification(uint, uint)));
// feedback for original caller
connect(m_area->layout(), SIGNAL(notificationClosed(uint, uint)),
this, SIGNAL(NotificationClosed(uint, uint)));
connect(m_area->layout(), SIGNAL(actionInvoked(uint, QString)),
this, SIGNAL(ActionInvoked(uint, QString)));
connect(m_settings, SIGNAL(settingsChanged()),
this, SLOT(reloadSettings()));
}
Notifyd::~Notifyd() {
m_area->deleteLater();
}
void Notifyd::CloseNotification(uint id) {
emit notificationClosed(id, 3);
}
QStringList Notifyd::GetCapabilities() {
QStringList caps;
caps
<< "actions"
// << "action-icons"
<< "body"
<< "body-hyperlinks"
<< "body-images"
<< "body-markup"
// << "icon-multi"
// << "icon-static"
<< "persistence"
// << "sound"
;
return caps;
}
QString Notifyd::GetServerInformation(QString& vendor,
QString& version,
QString& spec_version) {
spec_version = QString("1.2");
version = QString(LXQT_VERSION);
vendor = QString("lxde.org");
return QString("lxqt-notificationd");
}
uint Notifyd::Notify(const QString& app_name,
uint replaces_id,
const QString& app_icon,
const QString& summary,
const QString& body,
const QStringList& actions,
const QVariantMap& hints,
int expire_timeout
) {
uint ret;
if (replaces_id == 0) {
mId++;
ret = mId;
} else
ret = replaces_id;
#if 0
qDebug() << QString("Notify(\n"
" app_name = %1\n"
" replaces_id = %2\n"
" app_icon = %3\n"
" summary = %4\n"
" body = %5\n"
).arg(app_name, QString::number(replaces_id), app_icon, summary, body)
<< " actions =" << actions << endl
<< " hints =" << hints << endl
<< QString(" expire_timeout = %1\n) => %2").arg(QString::number(expire_timeout), QString::number(mId));
#endif
// handling the "server decides" timeout
if (expire_timeout == -1) {
expire_timeout = m_serverTimeout;
expire_timeout *= 1000;
}
emit notificationAdded(ret, app_name, summary, body, app_icon, expire_timeout, actions, hints);
return ret;
}
void Notifyd::reloadSettings() {
m_serverTimeout = m_settings->value("server_decides", 10).toInt();
m_area->setSettings(
m_settings->value("placement", "bottom-right").toString().toLower(),
m_settings->value("width", 300).toInt(),
m_settings->value("spacing", 6).toInt());
}
| gpl-3.0 |
sethryder/modpackindex | app/views/user/menu.blade.php | 1983 | <div class="col-md-3 col-sm-5">
<div class="list-group">
<a href="{{ action('UserController@getProfile', [$user['username']]) }}" class="list-group-item @if ($page == 'profile') active @endif">
<i class="fa fa-user"></i>Profile
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
@if ($show_modpacks)
<a href="{{ action('UserController@getModpacks', [$user['username']]) }}" class="list-group-item @if ($page == 'modpacks') active @endif">
<i class="fa fa-archive"></i>Modpacks
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
@endif
@if ($show_mods)
<a href="{{ action('UserController@getMods', [$user['username']]) }}" class="list-group-item @if ($page == 'mods') active @endif">
<i class="fa fa-file"></i>Mods
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
@endif
@if ($show_servers)
<a href="{{ action('UserController@getServers', [$user['username']]) }}" class="list-group-item @if ($page == 'servers') active @endif">
<i class="fa fa-cloud"></i>Servers
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
@endif
@if ($my_profile)
<a href="{{ action('UserController@getEditProfile') }}" class="list-group-item @if ($page == 'edit') active @endif">
<i class="fa fa-plus"></i>Edit Profile
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
<a href="{{ action('UserController@getEditPassword') }}" class="list-group-item @if ($page == 'password') active @endif">
<i class="fa fa-edit"></i>Change Password
<i class="fa fa-chevron-right list-group-chevron"></i>
</a>
@endif
</div>
<!-- /.list-group -->
</div>
<!-- /.col --> | gpl-3.0 |
eraffxi/darkstar | scripts/zones/Crawlers_Nest_[S]/TextIDs.lua | 367 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6905; -- You cannot obtain the item
ITEM_OBTAINED = 6909; -- Obtained: <item>
GIL_OBTAINED = 6910; -- Obtained <number> gil
KEYITEM_OBTAINED = 6912; -- Obtained key item:
-- Other Texts
ITEM_DELIVERY_DIALOG = 7676; -- Hello! Any packages to sendy-wend
| gpl-3.0 |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/ErrorLogWrapper.java | 1128 | package ar.edu.itba.tpf.chatterbot.web;
import ar.edu.itba.tpf.chatterbot.model.ErrorLog;
public class ErrorLogWrapper {
private final static int MESSAGE_SIZE = 45;
private final static int STACKTRACE_SIZE = 30;
ErrorLog errorLog;
boolean selected;
public ErrorLogWrapper(ErrorLog errorLog) {
this.errorLog = errorLog;
this.selected = false;
}
public ErrorLog getErrorLog() {
return errorLog;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getShrinkMessage() {
if (this.errorLog.getMessage().length() > MESSAGE_SIZE) {
return this.errorLog.getMessage().substring(0, MESSAGE_SIZE) + "...";
} else {
return this.errorLog.getMessage();
}
}
public String getShrinkStackTrace() {
if (this.errorLog.getStackTrace().length() > STACKTRACE_SIZE) {
return this.errorLog.getStackTrace().substring(0, STACKTRACE_SIZE) + "...";
} else {
return this.errorLog.getStackTrace();
}
}
}
| gpl-3.0 |
BackupTheBerlios/cuon-svn | cuon_client/cuon/Articles/SingleArticleSale.py | 1763 | # -*- coding: utf-8 -*-
##Copyright (C) [2003] [Jürgen Hamel, D-32584 Löhne]
##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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from cuon.Databases.SingleData import SingleData
import logging
import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import gobject
#from gtk import TRUE, FALSE
class SingleArticleSale(SingleData):
def __init__(self, allTables):
SingleData.__init__(self)
# tables.dbd and address
self.sNameOfTable = "articles_sales"
self.xmlTableDef = 0
# self.loadTable()
# self.saveTable()
self.loadTable(allTables)
self.setStore( gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_UINT) )
self.listHeader['names'] = ['designation', 'ID']
self.listHeader['size'] = [25,10,25,25,10]
print "number of Columns "
print len(self.table.Columns)
#
self.articlesNumber = 0
def readNonWidgetEntries(self, dicValues):
print 'readNonWidgetEntries(self) by SingleSales'
dicValues['articles_number'] = [self.articlesNumber, 'int']
return dicValues
| gpl-3.0 |
nacjm/MatterOverdrive | src/main/java/matteroverdrive/data/quest/logic/AbstractQuestLogicBlock.java | 1487 | package matteroverdrive.data.quest.logic;
import com.google.gson.JsonObject;
import matteroverdrive.data.quest.QuestBlock;
import matteroverdrive.data.quest.QuestItem;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
/**
* Created by Simeon on 1/5/2016.
*/
public abstract class AbstractQuestLogicBlock extends AbstractQuestLogic
{
protected QuestBlock block;
protected QuestItem blockStack;
public AbstractQuestLogicBlock()
{
}
public AbstractQuestLogicBlock(QuestBlock block)
{
this.block = block;
}
public AbstractQuestLogicBlock(QuestItem blockStack)
{
this.blockStack = blockStack;
}
@Override
public void loadFromJson(JsonObject jsonObject)
{
if (jsonObject.has("block"))
{
block = new QuestBlock(jsonObject.getAsJsonObject("block"));
}
else
{
blockStack = new QuestItem(jsonObject.getAsJsonObject("item"));
}
}
protected boolean areBlockStackTheSame(ItemStack stack)
{
return blockStack.getItemStack().isItemEqual(stack) && ItemStack.areItemStackTagsEqual(blockStack.getItemStack(), stack);
}
protected boolean areBlocksTheSame(IBlockState blockState)
{
return this.block.isTheSame(blockState);
}
protected String replaceBlockNameInText(String text)
{
if (blockStack != null)
{
text = text.replace("$block", blockStack.getItemStack().getDisplayName());
}
else
{
text = text.replace("$block", block.getBlockState().getBlock().getLocalizedName());
}
return text;
}
}
| gpl-3.0 |
4lin/galaxyz | download/includes/pages/game/class.ShowGalaxyPage.php | 4791 | <?php
/**
* 2Moons
* Copyright (C) 2012 Jan Kröpke
*
* 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 2Moons
* @author Jan Kröpke <info@2moons.cc>
* @copyright 2012 Jan Kröpke <info@2moons.cc>
* @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License
* @version 1.7.3 (2013-05-19)
* @info $Id: class.ShowGalaxyPage.php 2640 2013-03-23 19:23:26Z slaver7 $
* @link http://2moons.cc/
*/
require_once('includes/classes/class.FleetFunctions.php');
require_once('includes/classes/class.GalaxyRows.php');
class ShowGalaxyPage extends AbstractPage
{
public static $requireModule = MODULE_RESEARCH;
function __construct()
{
parent::__construct();
}
public function show()
{
global $USER, $PLANET, $resource, $LNG, $reslist, $CONF;
$action = HTTP::_GP('action', '');
$galaxyLeft = HTTP::_GP('galaxyLeft', '');
$galaxyRight = HTTP::_GP('galaxyRight', '');
$systemLeft = HTTP::_GP('systemLeft', '');
$systemRight = HTTP::_GP('systemRight', '');
$galaxy = min(max(HTTP::_GP('galaxy', (int) $PLANET['galaxy']), 1), Config::get('max_galaxy'));
$system = min(max(HTTP::_GP('system', (int) $PLANET['system']), 1), Config::get('max_system'));
$planet = min(max(HTTP::_GP('planet', (int) $PLANET['planet']), 1), Config::get('max_planets'));
$type = HTTP::_GP('type', 1);
$current = HTTP::_GP('current', 0);
if (!empty($galaxyLeft))
$galaxy = max($galaxy - 1, 1);
elseif (!empty($galaxyRight))
$galaxy = min($galaxy + 1, Config::get('max_galaxy'));
if (!empty($systemLeft))
$system = max($system - 1, 1);
elseif (!empty($systemRight))
$system = min($system + 1, Config::get('max_system'));
if ($galaxy != $PLANET['galaxy'] || $system != $PLANET['system'])
{
if($PLANET['deuterium'] < Config::get('deuterium_cost_galaxy'))
{
$this->printMessage($LNG['gl_no_deuterium_to_view_galaxy'], array("game.php?page=galaxy", 3));
exit;
} else {
$PLANET['deuterium'] -= Config::get('deuterium_cost_galaxy');
}
}
$targetDefensive = $reslist['defense'];
$targetDefensive[] = 502;
$MissleSelector[0] = $LNG['gl_all_defenses'];
foreach($targetDefensive as $Element)
{
$MissleSelector[$Element] = $LNG['tech'][$Element];
}
$galaxyRows = new GalaxyRows;
$galaxyRows->setGalaxy($galaxy);
$galaxyRows->setSystem($system);
$Result = $galaxyRows->getGalaxyData();
$this->tplObj->loadscript('galaxy.js');
$this->tplObj->assign_vars(array(
'GalaxyRows' => $Result,
'planetcount' => sprintf($LNG['gl_populed_planets'], count($Result)),
'action' => $action,
'galaxy' => $galaxy,
'system' => $system,
'planet' => $planet,
'type' => $type,
'current' => $current,
'maxfleetcount' => FleetFunctions::GetCurrentFleets($USER['id']),
'fleetmax' => FleetFunctions::GetMaxFleetSlots($USER),
'currentmip' => $PLANET[$resource[503]],
'grecyclers' => $PLANET[$resource[219]],
'recyclers' => $PLANET[$resource[209]],
'spyprobes' => $PLANET[$resource[210]],
'missile_count' => sprintf($LNG['gl_missil_to_launch'], $PLANET[$resource[503]]),
'spyShips' => array(210 => $USER['spio_anz']),
'settings_fleetactions' => $USER['settings_fleetactions'],
'current_galaxy' => $PLANET['galaxy'],
'current_system' => $PLANET['system'],
'current_planet' => $PLANET['planet'],
'planet_type' => $PLANET['planet_type'],
'max_planets' => Config::get('max_planets'),
'MissleSelector' => $MissleSelector,
'ShortStatus' => array(
'vacation' => $LNG['gl_short_vacation'],
'banned' => $LNG['gl_short_ban'],
'inactive' => $LNG['gl_short_inactive'],
'longinactive' => $LNG['gl_short_long_inactive'],
'noob' => $LNG['gl_short_newbie'],
'strong' => $LNG['gl_short_strong'],
'enemy' => $LNG['gl_short_enemy'],
'friend' => $LNG['gl_short_friend'],
'member' => $LNG['gl_short_member'],
),
));
$this->display('page.galaxy.default.tpl');
}
} | gpl-3.0 |
RaysaOliveira/cloudsim-plus | cloudsim-plus/src/main/java/org/cloudsimplus/autoscaling/VerticalVmScaling.java | 14868 | /*
* CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for
* Modeling and Simulation of Cloud Computing Infrastructures and Services.
* http://cloudsimplus.org
*
* Copyright (C) 2015-2016 Universidade da Beira Interior (UBI, Portugal) and
* the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil).
*
* This file is part of CloudSim Plus.
*
* CloudSim Plus 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.
*
* CloudSim Plus 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 CloudSim Plus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cloudsimplus.autoscaling;
import org.cloudbus.cloudsim.allocationpolicies.VmAllocationPolicy;
import org.cloudbus.cloudsim.brokers.DatacenterBroker;
import org.cloudbus.cloudsim.cloudlets.Cloudlet;
import org.cloudbus.cloudsim.datacenters.Datacenter;
import org.cloudbus.cloudsim.resources.*;
import static org.cloudbus.cloudsim.utilizationmodels.UtilizationModel.Unit;
import org.cloudbus.cloudsim.utilizationmodels.UtilizationModel;
import org.cloudbus.cloudsim.vms.Vm;
import org.cloudsimplus.autoscaling.resources.ResourceScaling;
import org.cloudsimplus.listeners.EventListener;
import java.util.function.Function;
/**
* A Vm <a href="https://en.wikipedia.org/wiki/Scalability#Horizontal_and_vertical_scaling">Vertical Scaling</a> mechanism
* used by a {@link DatacenterBroker} to request the dynamic scale of VM resources up or down, according to the current resource usage.
* For each resource supposed to be scaled, a different {@code VerticalVmScaling} instance should be provided.
* If a scaling object is going to be set to a Vm, it has to be exclusive of that Vm.
* Different Vms must have different instances of a scaling object.
*
* <p>A {@link Vm} runs a set of {@link Cloudlet}s. When a {@code VerticalVmScaling} object is attached to a {@link Vm},
* it's required to define which {@link #getResourceClass() resource will be scaled} ({@link Ram}, {@link Bandwidth}, etc)
* when it's {@link #getLowerThresholdFunction() under} or {@link #getUpperThresholdFunction() overloaded}.
* </p>
*
* <p>
* The scaling request follows this path:
* <ul>
* <li>a {@link Vm} that has a {@link VerticalVmScaling} object set monitors its own resource usage
* using an {@link EventListener}, to check if an {@link #getLowerThresholdFunction() under} or
* {@link #getUpperThresholdFunction() overload} condition is met;</li>
* <li>if any of these conditions is met, the Vm uses the VerticalVmScaling to send a scaling request to its {@link DatacenterBroker};</li>
* <li>the DatacenterBroker fowards the request to the {@link Datacenter} where the Vm is hosted;</li>
* <li>the Datacenter delegates the task to its {@link VmAllocationPolicy};</li>
* <li>the VmAllocationPolicy checks if there is resource availability and then finally scale the Vm.</li>
* </ul>
* </p>
*
* <h1>WARNING</h1>
* <hr>
* Make sure that the {@link UtilizationModel} of some of these {@code Cloudlets}
* is defined as {@link Unit#ABSOLUTE ABSOLUTE}. Defining the {@code UtilizationModel}
* of all {@code Cloudlets} running inside the {@code Vm} as {@link Unit#PERCENTAGE PERCENTAGE}
* causes these {@code Cloudlets} to automatically increase/decrease their resource usage when the
* {@code Vm} resource is vertically scaled. This is not a CloudSim Plus issue, but the natural and
* maybe surprising effect that may trap researchers trying to implement and assess VM scaling policies.
*
* <p>Consider the following example: a {@code VerticalVmScaling} is attached to a {@code Vm} to double
* its {@link Ram} when its usage reaches 50%. The {@code Vm} has 10GB of RAM.
* All {@code Cloudlets} running inside this {@code Vm} have a {@link UtilizationModel}
* for their RAM utilization define in {@link Unit#PERCENTAGE PERCENTAGE}. When the RAM utilization of all these
* {@code Cloudlets} reach the 50% (5GB), the {@code Vm} {@link Ram} will be doubled.
* However, as the RAM usage of the running {@code Cloudlets} is defined in percentage, they will
* continue to use 50% of {@code Vm}'s RAM, that now represents 10GB from the 20GB capacity.
* This way, the vertical scaling will have no real benefit.</p>
*
* @author Manoel Campos da Silva Filho
* @since CloudSim Plus 1.1.0
*/
public interface VerticalVmScaling extends VmScaling {
/**
* An attribute that implements the Null Object Design Pattern for {@link VerticalVmScaling}
* objects.
*/
VerticalVmScaling NULL = new VerticalVmScalingNull();
/**
* Gets the class of Vm resource this scaling object will request up or down scaling.
* Such a class can be {@link Ram}.class, {@link Bandwidth}.class or {@link Pe}.class.
* @return
* @see #getResource()
*/
Class<? extends ResourceManageable> getResourceClass();
/**
* Sets the class of Vm resource that this scaling object will request up or down scaling.
* Such a class can be {@link Ram}.class, {@link Bandwidth}.class or {@link Pe}.class.
* @param resourceClass the resource class to set
* @return
*/
VerticalVmScaling setResourceClass(Class<? extends ResourceManageable> resourceClass);
/**
* Gets the factor that will be used to scale a Vm resource up or down,
* whether such a resource is over or underloaded, according to the
* defined predicates.
*
* <p>If the resource to scale is a {@link Pe}, this is the number of PEs
* to request adding or removing when the VM is over or underloaded, respectively.
* For any other kind of resource, this is a percentage value in scale from 0 to 1. Every time the
* VM needs to be scaled up or down, this factor will be applied
* to increase or reduce a specific VM allocated resource.</p>
*
* @return the scaling factor to set which may be an absolute value (for {@link Pe} scaling)
* or percentage (for scaling other resources)
* @see #getUpperThresholdFunction()
*/
double getScalingFactor();
/**
* Sets the factor that will be used to scale a Vm resource up or down,
* whether such a resource is over or underloaded, according to the
* defined predicates.
*
* <p>If the resource to scale is a {@link Pe}, this is the number of PEs
* to request adding or removing when the VM is over or underloaded, respectively.
* For any other kind of resource, this is a percentage value in scale from 0 to 1. Every time the
* VM needs to be scaled up or down, this factor will be applied
* to increase or reduce a specific VM allocated resource.</p>
*
* @param scalingFactor the scaling factor to set which may be an absolute value (for {@link Pe} scaling)
* or percentage (for scaling other resources)
* @see #getUpperThresholdFunction()
*/
VerticalVmScaling setScalingFactor(double scalingFactor);
/**
* Gets the lower or upper resource utilization threshold {@link Function},
* depending if the Vm resource is under or overloaded, respectively.
*
* @return the lower resource utilization threshold function if the Vm resource
* is underloaded, upper resource utilization threshold function if the Vm resource
* is overloaded, or a function that always returns 0 if the Vm is is not in these conditions.
* @see #getLowerThresholdFunction()
* @see #getUpperThresholdFunction()
*/
Function<Vm, Double> getResourceUsageThresholdFunction();
/**
* Checks if the Vm is underloaded or not, based on the
* {@link #getLowerThresholdFunction()}.
* @return true if the Vm is underloaded, false otherwise
*/
boolean isVmUnderloaded();
/**
* Checks if the Vm is overloaded or not, based on the
* {@link #getUpperThresholdFunction()}.
* @return true if the Vm is overloaded, false otherwise
*/
boolean isVmOverloaded();
/**
* Gets the actual Vm {@link Resource} this scaling object is in charge of scaling.
* This resource is defined after calling the {@link #setResourceClass(Class)}.
* @return
*/
Resource getResource();
/**
* Gets the absolute amount of the Vm resource which has to be
* scaled up or down, based on the {@link #getScalingFactor() scaling factor}.
*
* @return the absolute amount of the Vm resource to scale
* @see #getResourceClass()
*/
double getResourceAmountToScale();
/**
* Performs the vertical scale if the Vm is overloaded, according to the {@link #getUpperThresholdFunction()} predicate,
* increasing the Vm resource to which the scaling object is linked to (that may be RAM, CPU, BW, etc),
* by the factor defined a scaling factor.
*
* <p>The time interval in which it will be checked if the Vm is overloaded
* depends on the {@link Datacenter#getSchedulingInterval()} value.
* Make sure to set such a value to enable the periodic overload verification.</p>
*
* @param time current simulation time
* @see #getScalingFactor()
*/
@Override
boolean requestScalingIfPredicateMatch(double time);
/**
* Gets a {@link Function} that defines the upper utilization threshold for a {@link #getVm() Vm}
* which indicates if it is overloaded or not.
* If it is overloaded, the Vm's {@link DatacenterBroker} will request to up scale the VM.
* The up scaling is performed by increasing the amount of the {@link #getResourceClass() resource}
* the scaling is associated to.
*
* <p>This function must receive a {@link Vm} and return the upper utilization threshold
* for it as a percentage value between 0 and 1 (where 1 is 100%).
* The VM will be defined as overloaded if the utilization of the {@link Resource}
* this scaling object is related to is higher than the value returned by the {@link Function}
* returned by this method.</p>
*
* @return
* @see #setUpperThresholdFunction(Function)
*/
Function<Vm, Double> getUpperThresholdFunction();
/**
* Sets a {@link Function} that defines the upper utilization threshold for a {@link #getVm() Vm}
* which indicates if it is overloaded or not.
* If it is overloaded, the Vm's {@link DatacenterBroker} will request to up scale the VM.
* The up scaling is performed by increasing the amount of the {@link #getResourceClass() resource}
* the scaling is associated to.
*
* <p>This function must receive a {@link Vm} and return the upper utilization threshold
* for it as a percentage value between 0 and 1 (where 1 is 100%).</p>
*
* <p>By setting the upper threshold as a {@link Function} instead of a directly
* storing a {@link Double} value which represent the threshold, it is possible
* to define the threshold dynamically instead of using a static value.
* Furthermore, the threshold function can be reused for scaling objects of
* different VMs.</p>
*
* @param upperThresholdFunction the upper utilization threshold function to set.
* The VM will be defined as overloaded if the utilization of the {@link Resource}
* this scaling object is related to is higher than the value returned by this {@link Function}.
* @return
*/
VerticalVmScaling setUpperThresholdFunction(Function<Vm, Double> upperThresholdFunction);
/**
* Gets a {@link Function} that defines the lower utilization threshold for a {@link #getVm() Vm}
* which indicates if it is underloaded or not.
* If it is underloaded, the Vm's {@link DatacenterBroker} will request to down scale the VM.
* The down scaling is performed by decreasing the amount of the {@link #getResourceClass() resource}
* the scaling is associated to.
*
*
* <p>This function must receive a {@link Vm} and return the lower utilization threshold
* for it as a percentage value between 0 and 1 (where 1 is 100%).
*
* The VM will be defined as underloaded if the utilization of the {@link Resource}
* this scaling object is related to is lower than the value returned by the {@link Function}
* returned by this method.</p>
*
* @return
* @see #setLowerThresholdFunction(Function)
*/
Function<Vm, Double> getLowerThresholdFunction();
/**
* Sets a {@link Function} that defines the lower utilization threshold for a {@link #getVm() Vm}
* which indicates if it is underloaded or not.
* If it is underloaded, the Vm's {@link DatacenterBroker} will request to down scale the VM.
* The down scaling is performed by decreasing the amount of the {@link #getResourceClass() resource}
* the scaling is associated to.
*
* <p>This function must receive a {@link Vm} and return the lower utilization threshold
* for it as a percentage value between 0 and 1 (where 1 is 100%).</p>
*
* <p>By setting the lower threshold as a {@link Function} instead of a directly
* storing a {@link Double} value which represent the threshold, it is possible
* to define the threshold dynamically instead of using a static value.
* Furthermore, the threshold function can be reused for scaling objects of
* different VMs.</p>
*
* @param lowerThresholdFunction the lower utilization threshold function to set.
* The VM will be defined as underloaded if the utilization of the {@link Resource}
* this scaling object is related to is lower than the value returned by this {@link Function}.
* @return
*/
VerticalVmScaling setLowerThresholdFunction(Function<Vm, Double> lowerThresholdFunction);
/**
* Sets the {@link ResourceScaling}.
* @param resourceScaling the {@link ResourceScaling} to set
* @return
*/
VerticalVmScaling setResourceScaling(ResourceScaling resourceScaling);
/**
* Gets the current amount allocated to the {@link #getResource() resource} managed by this scaling object.
* It is just a shortcut to {@code getVmResourceToScale.getAllocatedResource()}.
* @return the amount of allocated resource
*/
long getAllocatedResource();
}
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Dynamis-Jeuno/mobs/Vanguard_Smithy.lua | 812 | -----------------------------------
-- Area: Dynamis - Jeuno (188)
-- Mob: Vanguard_Smithy
-----------------------------------
-- require("scripts/zones/Dynamis-Jeuno/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| gpl-3.0 |
HEPcodes/FeynHiggs | extse/OasatPdep.app/SecDec3/loop/T12345m12012/together/epstothe0/f4.cc | 6607 | #include "intfile.hh"
dcmplx Pf4(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
double x3=x[3];
dcmplx y[149];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=em[1];
y[4]=esx[0];
y[5]=x1*y[1]*y[2];
y[6]=x1*y[1]*y[3];
y[7]=-(x1*y[1]*y[4]);
y[8]=y[1]*y[2];
y[9]=x3*y[1]*y[2];
y[10]=x3*y[1]*y[3];
y[11]=-(x3*y[1]*y[4]);
y[12]=-x1;
y[13]=1.+y[12];
y[14]=x0*y[1]*y[2];
y[15]=x2*y[1]*y[2];
y[16]=x0*y[1]*y[3];
y[17]=x2*y[1]*y[3];
y[18]=2.*x1*x2*y[1]*y[3];
y[19]=x2*x2;
y[20]=y[1]*y[3]*y[19];
y[21]=-(x0*y[1]*y[4]);
y[22]=-(x2*y[1]*y[4]);
y[23]=-x0;
y[24]=1.+y[23];
y[25]=lrs[0];
y[26]=2.*y[1]*y[2];
y[27]=2.*x0*y[1]*y[2];
y[28]=x2*x3*y[1]*y[2];
y[29]=x2*x3*y[1]*y[3];
y[30]=-(x2*x3*y[1]*y[4]);
y[31]=2.*x0*x3*y[1]*y[2];
y[32]=x1*x3*y[1]*y[2];
y[33]=2.*x0*x2*x3*y[1]*y[2];
y[34]=x1*x2*x3*y[1]*y[2];
y[35]=x1*x3*y[1]*y[3];
y[36]=x1*x2*x3*y[1]*y[3];
y[37]=x3*y[1]*y[3]*y[19];
y[38]=-(x1*x3*y[1]*y[4]);
y[39]=-(x1*x2*x3*y[1]*y[4]);
y[40]=y[5]+y[6]+y[7]+y[9]+y[15]+y[17]+y[22]+y[26]+y[27]+y[28]+y[29]+y[30]+y[\
31]+y[32]+y[33]+y[34]+y[35]+y[36]+y[37]+y[38]+y[39];
y[41]=lrs[1];
y[42]=-x2;
y[43]=1.+y[42];
y[44]=y[1]*y[3];
y[45]=2.*x2*x3*y[1]*y[3];
y[46]=-(y[1]*y[4]);
y[47]=lambda*lambda;
y[48]=x0*x2*y[1]*y[2];
y[49]=2.*x1*y[1]*y[3];
y[50]=x0*x2*y[1]*y[3];
y[51]=-(x0*x2*y[1]*y[4]);
y[52]=y[8]+y[14]+y[15]+y[16]+y[17]+y[18]+y[20]+y[21]+y[22]+y[48]+y[49]+y[50]\
+y[51];
y[53]=y[8]+y[9]+y[10]+y[11]+y[28]+y[29]+y[30]+y[44]+y[46];
y[54]=2.*x0*x2*y[1]*y[2];
y[55]=x1*x2*y[1]*y[2];
y[56]=x1*x2*y[1]*y[3];
y[57]=-(x1*x2*y[1]*y[4]);
y[58]=y[5]+y[6]+y[7]+y[8]+y[15]+y[17]+y[20]+y[22]+y[27]+y[54]+y[55]+y[56]+y[\
57];
y[59]=2.*y[1]*y[3];
y[60]=x0*x3*y[1]*y[2];
y[61]=x0*x3*y[1]*y[3];
y[62]=2.*x1*x3*y[1]*y[3];
y[63]=-(x0*x3*y[1]*y[4]);
y[64]=x0*x2*x3*y[1]*y[2];
y[65]=2.*x2*y[1]*y[3];
y[66]=x0*x2*x3*y[1]*y[3];
y[67]=2.*x1*x2*x3*y[1]*y[3];
y[68]=-(x0*x2*x3*y[1]*y[4]);
y[69]=y[8]+y[9]+y[14]+y[16]+y[21]+y[28]+y[29]+y[30]+y[37]+y[44]+y[46]+y[49]+\
y[60]+y[61]+y[62]+y[63]+y[64]+y[65]+y[66]+y[67]+y[68];
y[70]=lrs[2];
y[71]=x0*x0;
y[72]=y[1]*y[2]*y[71];
y[73]=x0*x1*y[1]*y[2];
y[74]=x0*x1*y[1]*y[3];
y[75]=x1*x1;
y[76]=y[1]*y[3]*y[75];
y[77]=2.*x0*x2*y[1]*y[3];
y[78]=-(x0*x1*y[1]*y[4]);
y[79]=y[5]+y[6]+y[7]+y[14]+y[16]+y[18]+y[21]+y[72]+y[73]+y[74]+y[76]+y[77]+y\
[78];
y[80]=2.*x3*y[1]*y[2];
y[81]=2.*x2*x3*y[1]*y[2];
y[82]=y[26]+y[80]+y[81];
y[83]=-(lambda*MYI*x0*y[24]*y[25]*y[82]);
y[84]=-(lambda*MYI*y[24]*y[25]*y[40]);
y[85]=lambda*MYI*x0*y[25]*y[40];
y[86]=1.+y[83]+y[84]+y[85];
y[87]=2.*x3*y[1]*y[3];
y[88]=y[45]+y[59]+y[87];
y[89]=-(lambda*MYI*x1*y[13]*y[41]*y[88]);
y[90]=-(lambda*MYI*y[13]*y[41]*y[69]);
y[91]=lambda*MYI*x1*y[41]*y[69];
y[92]=1.+y[89]+y[90]+y[91];
y[93]=-x3;
y[94]=1.+y[93];
y[95]=y[8]+y[9]+y[10]+y[11]+y[31]+y[32]+y[35]+y[38]+y[44]+y[45]+y[46];
y[96]=y[9]+y[10]+y[11]+y[45]+y[59]+y[60]+y[61]+y[62]+y[63];
y[97]=x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[53]*y[58];
y[98]=-(lambda*MYI*x1*y[13]*y[41]*y[52]*y[86]);
y[99]=y[97]+y[98];
y[100]=x3*y[1]*y[2]*y[71];
y[101]=x0*x1*x3*y[1]*y[2];
y[102]=x0*x1*x3*y[1]*y[3];
y[103]=x3*y[1]*y[3]*y[75];
y[104]=2.*x0*x2*x3*y[1]*y[3];
y[105]=-(x0*x1*x3*y[1]*y[4]);
y[106]=y[8]+y[14]+y[16]+y[21]+y[32]+y[35]+y[38]+y[44]+y[46]+y[49]+y[60]+y[61\
]+y[63]+y[65]+y[67]+y[100]+y[101]+y[102]+y[103]+y[104]+y[105];
y[107]=lrs[3];
y[108]=x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[58]*y[96];
y[109]=-(x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[52]*y[95]);
y[110]=y[108]+y[109];
y[111]=-(x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[52]*y[53]);
y[112]=lambda*MYI*x0*y[24]*y[25]*y[58]*y[92];
y[113]=y[111]+y[112];
y[114]=2.*x0*x3*y[1]*y[3];
y[115]=y[59]+y[62]+y[114];
y[116]=-(lambda*MYI*x2*y[43]*y[70]*y[115]);
y[117]=-(lambda*MYI*y[43]*y[70]*y[106]);
y[118]=lambda*MYI*x2*y[70]*y[106];
y[119]=1.+y[116]+y[117]+y[118];
y[120]=x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[53]*y[95];
y[121]=-(lambda*MYI*x1*y[13]*y[41]*y[86]*y[96]);
y[122]=y[120]+y[121];
y[123]=-(x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[53]*y[96]);
y[124]=lambda*MYI*x0*y[24]*y[25]*y[92]*y[95];
y[125]=y[123]+y[124];
y[126]=pow(y[53],2);
y[127]=x0*x1*y[13]*y[24]*y[25]*y[41]*y[47]*y[126];
y[128]=y[86]*y[92];
y[129]=y[127]+y[128];
y[130]=x2*y[1]*y[2]*y[71];
y[131]=x0*x1*x2*y[1]*y[2];
y[132]=x0*x1*x2*y[1]*y[3];
y[133]=x2*y[1]*y[3]*y[75];
y[134]=x0*y[1]*y[3]*y[19];
y[135]=x1*y[1]*y[3]*y[19];
y[136]=-(x0*x1*x2*y[1]*y[4]);
y[137]=y[5]+y[14]+y[48]+y[50]+y[51]+y[55]+y[56]+y[57]+y[72]+y[73]+y[74]+y[76\
]+y[78]+y[130]+y[131]+y[132]+y[133]+y[134]+y[135]+y[136];
y[138]=-(lambda*MYI*x0*y[24]*y[25]*y[40]);
y[139]=x0+y[138];
y[140]=-(lambda*MYI*x1*y[13]*y[41]*y[69]);
y[141]=x1+y[140];
y[142]=-(lambda*MYI*x3*y[94]*y[107]*y[137]);
y[143]=x3+y[142];
y[144]=-(lambda*MYI*x2*y[43]*y[70]*y[106]);
y[145]=x2+y[144];
y[146]=pow(y[139],2);
y[147]=pow(y[141],2);
y[148]=pow(y[145],2);
FOUT=(pow(bi,-2)*(-(lambda*MYI*x3*y[52]*y[94]*y[107]*(-(lambda*MYI*x2*y[43]*\
y[70]*y[95]*y[110])-y[99]*y[119]-lambda*MYI*x2*y[43]*y[70]*y[79]*y[122]))+l\
ambda*MYI*x3*y[58]*y[94]*y[107]*(-(lambda*MYI*x2*y[43]*y[70]*y[96]*y[110])-\
y[113]*y[119]-lambda*MYI*x2*y[43]*y[70]*y[79]*y[125])+lambda*MYI*x3*y[79]*y\
[94]*y[107]*(lambda*MYI*x2*y[43]*y[70]*y[96]*y[99]-lambda*MYI*x2*y[43]*y[70\
]*y[95]*y[113]-lambda*MYI*x2*y[43]*y[70]*y[79]*y[129])+(lambda*MYI*x2*y[43]\
*y[70]*y[96]*y[122]-lambda*MYI*x2*y[43]*y[70]*y[95]*y[125]+y[119]*y[129])*(\
1.+lambda*MYI*x3*y[107]*y[137]-lambda*MYI*y[94]*y[107]*y[137])))/((y[1]+y[1\
]*y[139]+y[1]*y[141]+y[1]*y[139]*y[143]+y[1]*y[141]*y[143]+y[1]*y[145]+y[1]\
*y[139]*y[143]*y[145]+y[1]*y[141]*y[143]*y[145])*(y[8]+2.*y[1]*y[2]*y[139]+\
y[1]*y[2]*y[141]+y[1]*y[3]*y[141]-y[1]*y[4]*y[141]+y[1]*y[2]*y[139]*y[141]+\
y[1]*y[3]*y[139]*y[141]-y[1]*y[4]*y[139]*y[141]+y[1]*y[2]*y[139]*y[143]+y[1\
]*y[2]*y[141]*y[143]+y[1]*y[2]*y[139]*y[141]*y[143]+y[1]*y[3]*y[139]*y[141]\
*y[143]-y[1]*y[4]*y[139]*y[141]*y[143]+y[1]*y[2]*y[145]+y[1]*y[3]*y[145]-y[\
1]*y[4]*y[145]+y[1]*y[2]*y[139]*y[145]+y[1]*y[3]*y[139]*y[145]-y[1]*y[4]*y[\
139]*y[145]+2.*y[1]*y[3]*y[141]*y[145]+y[1]*y[2]*y[139]*y[143]*y[145]+y[1]*\
y[3]*y[139]*y[143]*y[145]-y[1]*y[4]*y[139]*y[143]*y[145]+y[1]*y[2]*y[141]*y\
[143]*y[145]+y[1]*y[3]*y[141]*y[143]*y[145]-y[1]*y[4]*y[141]*y[143]*y[145]+\
y[1]*y[2]*y[139]*y[141]*y[143]*y[145]+y[1]*y[3]*y[139]*y[141]*y[143]*y[145]\
-y[1]*y[4]*y[139]*y[141]*y[143]*y[145]+y[1]*y[2]*y[146]+y[1]*y[2]*y[143]*y[\
146]+y[1]*y[2]*y[143]*y[145]*y[146]+y[1]*y[3]*y[147]+y[1]*y[3]*y[143]*y[147\
]+y[1]*y[3]*y[143]*y[145]*y[147]+y[1]*y[3]*y[148]+y[1]*y[3]*y[139]*y[143]*y\
[148]+y[1]*y[3]*y[141]*y[143]*y[148]));
return (FOUT);
}
| gpl-3.0 |
frazzy123/madisonclone | app/views/login/signup.blade.php | 1359 | @extends('layouts/main')
@section('content')
<div class="content col-md-12">
<div class="row">
<div class="md-col-12">
<h1>Signup</h1>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
{{ Form::open(array('url'=>'user/signup', 'method'=>'post')) }}
<!-- First Name -->
<div class="form-group">
{{ Form::label('fname', 'First Name') . Form::text('fname', Input::old('fname'), array('placeholder'=>'First Name', 'class'=>'form-control')) }}
</div>
<!-- Last Name -->
<div class="form-group">
{{ Form::label('lname', 'Last Name') . Form::text('lname', Input::old('lname'), array('placeholder'=>'Last Name', 'class'=>'form-control')) }}
</div>
<!-- Email -->
<div class="form-group">
{{ Form::label('email', 'Email') . Form::text('email', Input::old('email'), array('placeholder'=>'Email', 'class'=>'form-control')) }}
</div>
<!-- Password -->
<div class="form-group">
{{ Form::label('password', 'Password') . Form::password('password', array('placeholder'=>'Password', 'class'=>'form-control')) }}
</div>
<!-- Submit -->
{{ Form::submit('Signup', array('class'=>'btn btn-default')) }}
{{ Form::token() . Form::close() }}
</div>
</div>
<div class="row">
<div social-login message="Sign up"></div>
</div>
</div>
@endsection | gpl-3.0 |
martin-craig/Airtime | python_apps/media-monitor2/media/monitor/owners.py | 1424 | # -*- coding: utf-8 -*-
from media.monitor.log import Loggable
class Owner(Loggable):
def __init__(self):
# hash: 'filepath' => owner_id
self.owners = {}
def get_owner(self,f):
""" Get the owner id of the file 'f' """
o = self.owners[f] if f in self.owners else -1
self.logger.info("Received owner for %s. Owner: %s" % (f, o))
return o
def add_file_owner(self,f,owner):
""" Associate file f with owner. If owner is -1 then do we will not record
it because -1 means there is no owner. Returns True if f is being stored
after the function. False otherwise. """
if owner == -1: return False
if f in self.owners:
if owner != self.owners[f]: # check for fishiness
self.logger.info("Warning ownership of file '%s' changed from '%d' to '%d'"
% (f, self.owners[f], owner))
else: return True
self.owners[f] = owner
return True
def has_owner(self,f):
""" True if f is owned by somebody. False otherwise. """
return f in self.owners
def remove_file_owner(self,f):
""" Try and delete any association made with file f. Returns true if
the the association was actually deleted. False otherwise. """
if f in self.owners:
del self.owners[f]
return True
else: return False
| gpl-3.0 |
eraffxi/darkstar | scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs.lua | 572 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6381; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6387; -- Obtained: <item>
GIL_OBTAINED = 6388; -- Obtained <number> gil
KEYITEM_OBTAINED = 6390; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7048; -- You can't fish here.
-- Shops
JIDWAHN_SHOP_DIALOG = 7311; -- Would you care for some items to use on your travels?
-- Other
ON_WAY_TO_NASHMAU = 7312; -- We are on our way to Nashmau
| gpl-3.0 |
surveyproject/surveyproject_main_public | Reflector/Nsurvey_WebControls/Votations.NSurvey.WebControls.UI/SectionQuestion.cs | 44910 | /**************************************************************************************************
NSurvey - The web survey and form engine
Copyright (c) 2004, 2005 Thomas Zumbrunn. (http://www.nsurvey.org)
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.
************************************************************************************************/
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Threading;
using Votations.NSurvey;
using Votations.NSurvey.Data;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.WebControlsFactories;
using Votations.NSurvey.Resources;
namespace Votations.NSurvey.WebControls.UI
{
/// <summary>
/// Abstract class that questions which needs
/// postback handling of the answers and handling
/// of multiple inner answer sections
/// </summary>
public abstract class SectionQuestion : ActiveQuestion
{
/// <summary>
/// Sets the style for the section's answer grid header
/// </summary>
[
Category("Styles"),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)]
public Style SectionGridAnswersHeaderStyle
{
get { return _sectionGridAnswersHeaderStyle == null ? new Style() : _sectionGridAnswersHeaderStyle; }
set { _sectionGridAnswersHeaderStyle = value; }
}
/// <summary>
/// Sets the style for the section's answer grid overview items
/// </summary>
[
Category("Styles"),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)]
public Style SectionGridAnswersItemStyle
{
get { return _sectionGridAnswersItemStyle == null ? new Style() : _sectionGridAnswersItemStyle; }
set { _sectionGridAnswersItemStyle = value; }
}
/// <summary>
/// Sets the style for the section's answer grid overview items
/// </summary>
[
Category("Styles"),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)]
public Style SectionGridAnswersAlternatingItemStyle
{
get { return _sectionGridAnswersAlternatingItemStyle == null ? new Style() : _sectionGridAnswersAlternatingItemStyle; }
set { _sectionGridAnswersAlternatingItemStyle = value; }
}
/// <summary>
/// Sets the style for the section's answer grid table
/// </summary>
[
Category("Styles"),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty)]
public Style SectionGridAnswersStyle
{
get { return _sectionGridAnswersStyle == null ? new Style() : _sectionGridAnswersStyle; }
set { _sectionGridAnswersStyle = value; }
}
/// <summary>
/// how many section is the user allowed
/// to create in this question
/// </summary>
public int MaxSections
{
get { return _maxSections; }
set { _maxSections = value; }
}
/// <summary>
/// How the user can create sections
/// </summary>
public RepeatableSectionMode RepeatMode
{
get { return _repeatMode; }
set { _repeatMode = value; }
}
/// <summary>
/// Text show to the user to add a new section
/// </summary>
public string AddSectionLinkText
{
get
{
return _addSectionLinkText == null ?
ResourceManager.GetString("AddSectionLinkText", LanguageCode) : _addSectionLinkText;
}
set { _addSectionLinkText = value; }
}
/// <summary>
/// Text show to the user to delete a section
/// </summary>
public string DeleteSectionLinkText
{
get
{
return _deleteSectionLinkText == null ?
ResourceManager.GetString("DeleteSectionLinkText", LanguageCode) : _deleteSectionLinkText;
}
set { _deleteSectionLinkText = value; }
}
/// <summary>
/// Text show to the user to edit a section in the grid
/// </summary>
public string EditSectionLinkText
{
get
{
return _editSectionLinkText == null ?
ResourceManager.GetString("EditSectionLinkText", LanguageCode) : _editSectionLinkText;
}
set { _editSectionLinkText = value; }
}
/// <summary>
/// Text show to the user to edit a section in the grid
/// </summary>
public string UpdateSectionLinkText
{
get
{
return _updateSectionLinkText == null ?
ResourceManager.GetString("UpdateSectionLinkText", LanguageCode) : _updateSectionLinkText;
}
set { _updateSectionLinkText = value; }
}
/// <summary>
/// Cancel button caption
/// </summary>
public string CancelButtonText
{
get
{
return _cancelButtonText ?? ResourceManager.GetString("CancelButtonText", LanguageCode);
}
set { _cancelButtonText = value; }
}
/// <summary>
/// Enable server side validation of grid answer section items
/// </summary>
public bool EnableGridSectionServerSideValidation
{
get { return _enableGridSectionServerSideValidation; }
set { _enableGridSectionServerSideValidation = value; }
}
/// <summary>
/// Enable client side validation of grid answer section items
/// </summary>
public bool EnableGridSectionClientSideValidation
{
get { return _enableGridSectionClientSideValidation; }
set { _enableGridSectionClientSideValidation = value; }
}
/// <summary>
/// Number of sections owned by this question
/// </summary>
public int SectionCount
{
get
{
if (ViewState["SectionCount"] != null)
{
return int.Parse(ViewState["SectionCount"].ToString());
}
else
{
ViewState["SectionCount"] = GetSectionCountFromState();
}
return int.Parse(ViewState["SectionCount"].ToString());
}
set { ViewState["SectionCount"] = value; }
}
/// <summary>
/// Answers that will be shown in the section's
/// grid overview
/// </summary>
public int[] GridAnswers
{
get { return _gridAnswers; }
set { _gridAnswers = value; }
}
/// <summary>
/// In which state is the current grid
/// </summary>
protected SectionGridMode GridMode
{
get
{
if (ViewState["SectionGridMode"] == null)
{
ViewState["SectionGridMode"] = SectionGridMode.None;
}
return (SectionGridMode)ViewState["SectionGridMode"];
}
set { ViewState["SectionGridMode"] = value; }
}
/// <summary>
/// Section Uids must be stored between
/// postbacks to make sure that the section
/// control gets the correct uid back
/// </summary>
protected ArrayList SectionUids
{
get
{
if (ViewState["SectionUids"] == null)
{
ViewState["SectionUids"] = new ArrayList();
}
return (ArrayList)ViewState["SectionUids"];
}
set { ViewState["SectionUids"] = value; }
}
/// <summary>
/// Style for the section's option row
/// </summary>
public Style SectionOptionStyle
{
get { return _sectionOptionStyle == null ? _sectionOptionStyle = new Style() : _sectionOptionStyle; }
set { _sectionOptionStyle = value; }
}
/// <summary>
/// Contains all sections and section options
/// </summary>
protected Table SectionTable
{
get { return _sectionTable; }
set { _sectionTable = value; }
}
/// <summary>
/// To which section are the new answer
/// in the grid be assigned
/// </summary>
public int TargetSection
{
get
{
if (ViewState["TargetSection"] == null)
{
ViewState["TargetSection"] = -1;
}
return int.Parse(ViewState["TargetSection"].ToString());
}
set { ViewState["TargetSection"] = value; }
}
/// <summary>
/// Compose all answer sections into a question
/// </summary>
protected override void CreateChildControls()
{
// Clears all childs controls
Controls.Clear();
BuildQuestion();
}
/// <summary>
/// Build the question layout with its
/// child controls
/// </summary>
virtual protected void BuildQuestion()
{
Controls.Add(QuestionTable);
// Build default layout
TableCell questionTableCell = new TableCell(); // default layout table cell
TableRow questionTableRow = new TableRow(); // default layout table row
string requiredMarkerHtml = string.Empty;
string titleString = ResourceManager.GetString("MandatoryQuestionTitle");
if (ValidationMark.Length != 0 &&
(MinSelectionRequired > 0 || MaxSelectionAllowed > 0))
{
//requiredMarkerHtml = string.Format("<span class='{0}'> {1}</span>",ValidationMarkStyle.CssClass.ToString(),ValidationMark);
requiredMarkerHtml = string.Format(" <span class='{0}' title='{1}'></span>", ValidationMarkStyle.CssClass.ToString(), titleString);
}
// Set question's text
//Label questionLabel = new Label();
Literal questionLabel = new Literal();
questionLabel.Mode = LiteralMode.Transform;
if (QuestionNumber > 0)
{
// JJ Div to enclose the number and another div for text. Inline style is used because that is always necessary.can be moved into style sheet
questionLabel.Text = string.Format(@"<div class='question-number-div'>{0}.
</div><div class='question-text-div'>{1}{2}{3}</div>", QuestionNumber, Text, requiredMarkerHtml, HelpText);
//TODO (THis is not a real TODO- just a makrker) Question Number align subsequent lines with Text and not number
}
else
{
//questionLabel.Text = Text;
questionLabel.Text = string.Format(@"<div class='question-text-div'>{0}{1}{2}</div>", Text, requiredMarkerHtml, HelpText);
}
questionTableCell.Controls.Add(questionLabel);
/*TODO JJ Commented out introducing span above after the question text
if (ValidationMark.Length != 0 &&
(MinSelectionRequired > 0 || MaxSelectionAllowed > 0))
{
Label validationMark = new Label();
validationMark.Text = ValidationMark;
validationMark.ControlStyle.CopyFrom(ValidationMarkStyle);
questionTableCell.Controls.Add(validationMark);
}
* */
questionTableRow.ControlStyle.CopyFrom(QuestionStyle);
// Creates the row
questionTableRow.Cells.Add(questionTableCell);
QuestionTable.Rows.Add(questionTableRow);
// Add the section table to the tree to get correct uid for children
//_sectionTable.CellSpacing = 0;
//_sectionTable.CellPadding = 2;
//_sectionTable.Width = Unit.Percentage(100);
QuestionTable.Rows.Add(BuildRow(_sectionTable, AnswerStyle));
// Create grid with current answers and section only to add a new entry
if (RepeatMode == RepeatableSectionMode.GridAnswers)
{
BuildSingleSection();
}
// Create all sections
else
{
BuildMultipleSections();
}
//QuestionTable.Width = Unit.Percentage(100);
//QuestionTable.CellSpacing = 0;
//QuestionTable.CellPadding = 2;
}
/// <summary>
/// Creates the section's container
/// </summary>
virtual protected void BuildMultipleSections()
{
for (int i = 0; i <= SectionCount; i++)
{
AddSection(i, GetSectionUid(i));
}
}
/// <summary>
/// Builds a section option table for the
/// given section number
/// </summary>
virtual protected Table GetSectionOptions(int sectionNumber, int sectionUid)
{
Table sectionOptionTable = Votations.NSurvey.BE.Votations.NSurvey.Constants.Commons.GetCentPercentTable();//JJ;
TableRow sectionOptionRow = new TableRow();
TableCell sectionOptionCell = new TableCell();
if (MaxSections == 0 || sectionNumber + 1 < MaxSections)
{
sectionOptionCell = new TableCell();
LinkButton addSectionAfterButton = new LinkButton();
addSectionAfterButton.ControlStyle.CopyFrom(SectionOptionStyle);
addSectionAfterButton.Text = AddSectionLinkText;
addSectionAfterButton.ID = " AddSectionAfterButton" + sectionUid;
addSectionAfterButton.Command += new CommandEventHandler(AddSectionButton_Click);
addSectionAfterButton.CommandArgument = (sectionNumber + 1).ToString();
addSectionAfterButton.Enabled = RenderMode != ControlRenderMode.ReadOnly;
sectionOptionCell.Controls.Add(addSectionAfterButton);
sectionOptionRow.Cells.Add(sectionOptionCell);
}
if (sectionNumber > 0)
{
sectionOptionCell = new TableCell();
if (MaxSections == 0 || sectionNumber + 1 < MaxSections)
{
//html to separate add and delete linkbuttons
sectionOptionCell.Controls.Add(new LiteralControl("<div style='position:relative;top:10px; left: -7px; line-height: 0px;'>– </div>"));
}
LinkButton removeSectionButton = new LinkButton();
removeSectionButton.ControlStyle.CopyFrom(SectionOptionStyle);
removeSectionButton.Text = DeleteSectionLinkText;
removeSectionButton.ID = " RemoveSectionButton" + sectionUid;
removeSectionButton.CommandArgument = sectionNumber.ToString();
removeSectionButton.Command += new CommandEventHandler(RemoveSectionButton_Command);
sectionOptionCell.Controls.Add(removeSectionButton);
sectionOptionRow.Cells.Add(sectionOptionCell);
}
sectionOptionTable.Rows.Add(sectionOptionRow);
sectionOptionTable.ControlStyle.CopyFrom(SectionOptionStyle);
//sectionOptionTable.CellSpacing = 0;
//sectionOptionTable.CellPadding = 2;
return sectionOptionTable;
}
/// <summary>
/// Adds / inserts a new full answer section
/// </summary>
protected virtual void AddSectionButton_Click(object sender, CommandEventArgs e)
{
if (MaxSections == 0 || SectionCount + 1 < MaxSections)
{
int sectionNumber = int.Parse(e.CommandArgument.ToString());
if (sectionNumber > SectionCount)
{
SectionCount++;
AddSection(SectionCount, GetSectionUid(SectionCount));
}
else
{
InsertSection(sectionNumber);
SectionCount++;
}
}
}
/// <summary>
/// Inserts a new section at the given
/// section number
/// </summary>
virtual protected void InsertSection(int sectionNumber)
{
// increment all user answers section numbers
for (int i = SectionCount; i >= sectionNumber; i--)
{
ChangeStateAnswersSection(i, i + 1);
}
// Update web control's sections number
for (int i = sectionNumber; i < _sections.Count; i++)
{
_sections[i].SectionNumber = _sections[i].SectionNumber + 1;
}
// Insert a new Uid for the section
SectionUids.Insert(sectionNumber, GetUidForSection());
// Creates a new section
Section section = CreateSection(sectionNumber, GetSectionUid(sectionNumber));
_sections.Insert(sectionNumber, section);
_sectionTable.Rows.AddAt((sectionNumber) * 2, BuildRow(section, null));
_sectionTable.Rows.AddAt((sectionNumber) * 2, BuildRow(GetSectionOptions(sectionNumber, section.SectionUid), SectionOptionStyle));
}
/// <summary>
/// Returns a random unique ID
/// </summary>
/// <returns>uId</returns>
private int GetUidForSection()
{
Random r = new Random();
int uId = r.Next(90000); //no larger than 90000
while (UidExists(uId))
{
uId = r.Next(90000); //no smaller than 1, no larger than 90000
}
return uId;
}
/// <summary>
/// Checks if the Uid already exists in the section
/// Uids collection to avoid duplicates
/// </summary>
/// <param name="uId"></param>
/// <returns>true or false</returns>
private bool UidExists(int uId)
{
for (int i = 0; i < SectionUids.Count; i++)
{
if (SectionUids[i].ToString() == uId.ToString())
{
return true;
}
}
return false;
}
/// <summary>
/// Adds a new section using the provided section Uid
/// </summary>
virtual protected void AddSection(int sectionNumber, int sectionUid)
{
Section section = CreateSection(sectionNumber, sectionUid);
_sections.Add(section);
if (RepeatMode == RepeatableSectionMode.FullAnswers)
{
_sectionTable.Rows.Add(BuildRow(GetSectionOptions(sectionNumber, section.SectionUid), SectionOptionStyle));
_sectionTable.Rows.Add(BuildRow(section, null));
}
else if (RepeatMode == RepeatableSectionMode.GridAnswers)
{
_sectionTable.Rows.Add(BuildRow(section, null));
}
else
{
_sectionTable.Rows.Add(BuildRow(section, null));
}
}
/// <summary>
/// Deletes a section from the question
/// </summary>
protected virtual void RemoveSectionButton_Command(object sender, CommandEventArgs e)
{
int deletedSectionNumber = int.Parse(e.CommandArgument.ToString());
RemoveSection(deletedSectionNumber);
}
/// <summary>
/// Creates and adds a new section
/// to the question
/// </summary>
private void RemoveSection(int sectionNumber)
{
// Deletes any answer left by the user
DeleteStateAnswersForSection(sectionNumber);
// Decrement all user answers section numbers
for (int i = sectionNumber + 1; i < SectionCount; i++)
{
ChangeStateAnswersSection(i, i - 1);
}
// Update local section count and remove the Guid
// of the unwated question
SectionCount = SectionCount - 1;
SectionUids.RemoveAt(sectionNumber);
// Remove unwanted section
_sectionTable.Rows.RemoveAt((sectionNumber * 2));
_sectionTable.Rows.RemoveAt((sectionNumber * 2));
// Update web control's sections number
for (int i = sectionNumber; i < _sections.Count; i++)
{
_sections[i].SectionNumber = _sections[i].SectionNumber - 1;
}
}
/// <summary>
/// Builds a answer's overview datagrid and
/// if required show an "add new" section
/// </summary>
private void BuildSingleSection()
{
_sectionGrid = GetSectionAnswersGrid();
_sectionGrid.ID = "SectionGrid" + QuestionId;
_sectionGrid.QuestionId = QuestionId;
_sectionGrid.AddSection += new SectionAnswersEventHandler(AnswersGrid_AddSection);
_sectionGrid.DeleteSection += new SectionAnswersEventHandler(AnswersGrid_DeleteSection);
_sectionGrid.EditSection += new SectionAnswersEventHandler(AnswersGrid_EditSection);
_sectionGrid.AddSectionLinkText = AddSectionLinkText;
_sectionGrid.DeleteSectionLinkText = DeleteSectionLinkText;
_sectionGrid.SectionGridAnswersHeaderStyle = SectionGridAnswersHeaderStyle;
_sectionGrid.SectionGridAnswersItemStyle = SectionGridAnswersItemStyle;
_sectionGrid.SectionGridAnswersAlternatingItemStyle = SectionGridAnswersAlternatingItemStyle;
_sectionGrid.SectionGridAnswersStyle = SectionGridAnswersStyle;
_sectionGrid.EditSectionLinkText = EditSectionLinkText;
_sectionGrid.RenderMode = RenderMode;
_sectionGrid.MaxSections = MaxSections;
_sectionGrid.GridAnswers = _gridAnswers;
if (_sectionGrid != null)
{
QuestionTable.Rows.Add(BuildRow(_sectionGrid, null));
}
// Assign any previous posted answers to the grid
GridAnswerDataCollection gridAnswers = GetGridVoterAnswers();
if (gridAnswers != null)
{
_sectionGrid.GridVoterAnswers = gridAnswers;
}
bool firstAddNewSection = TargetSection == -1 && _sectionGrid.GridVoterAnswers.Count == 0,
nextAddNewSection =
TargetSection > -1 && _sectionGrid.GridVoterAnswers.Count > 0 ||
TargetSection == 0 && _sectionGrid.GridVoterAnswers.Count == 0;
// Do we need to show a new section space
if (firstAddNewSection || nextAddNewSection)
{
// Is this the first time ever that we show an add new section space
if (_sectionGrid.GridVoterAnswers.Count == 0)
{
GridMode = SectionGridMode.AddNew;
}
AddSection(-1, 0);
AddSubmitSectionButtons(GridMode == SectionGridMode.Edit);
}
}
/// <summary>
/// Parse the answer state and returns the
/// answers of this question
/// </summary>
/// <returns></returns>
protected virtual GridAnswerDataCollection GetGridVoterAnswers()
{
GridAnswerDataCollection gridAnswers = null;
if (VoterAnswersState != null)
{
VoterAnswersData.VotersAnswersRow[] answerState =
(VoterAnswersData.VotersAnswersRow[])VoterAnswersState.Select("QuestionId = " + QuestionId);
if (answerState != null && answerState.Length > 0)
{
gridAnswers = new GridAnswerDataCollection();
for (int i = 0; i < answerState.Length; i++)
{
gridAnswers.Add(new GridAnswerData(answerState[i].QuestionId, answerState[i].AnswerId, answerState[i].SectionNumber, answerState[i].AnswerText, (AnswerTypeMode)answerState[i].TypeMode));
}
}
}
return gridAnswers;
}
/// <summary>
/// A new section has been requested on the grid.
/// Show a "new section" area
/// </summary>
protected virtual void AnswersGrid_AddSection(object sender, SectionAnswersItemEventArgs e)
{
_sectionTable.Controls.Clear();
AddSection(-1, 0);
SectionCount = 0;
TargetSection = int.Parse(e.SectionNumber.ToString());
AddSubmitSectionButtons(false);
GridMode = SectionGridMode.AddNew;
}
/// <summary>
/// A new section has been requested for edit
/// Show a "new section" area with the section's answers
/// </summary>
protected virtual void AnswersGrid_EditSection(object sender, SectionAnswersItemEventArgs e)
{
_sectionTable.Controls.Clear();
if (e.SectionAnswers != null)
{
PostedAnswerDataCollection postedAnswers = new PostedAnswerDataCollection();
foreach (GridAnswerData answer in e.SectionAnswers)
{
if (VoterAnswersState == null)
{
VoterAnswersData voterAnswersData = new VoterAnswersData();
voterAnswersData.EnforceConstraints = false;
VoterAnswersState = voterAnswersData.VotersAnswers;
}
VoterAnswersData.VotersAnswersRow voterAnswer = VoterAnswersState.NewVotersAnswersRow();
voterAnswer.AnswerId = answer.AnswerId;
voterAnswer.QuestionId = QuestionId;
voterAnswer.SectionNumber = -1;
voterAnswer.AnswerText = answer.FieldText;
voterAnswer.VoterId = -1;
VoterAnswersState.AddVotersAnswersRow(voterAnswer);
}
}
// Dont use any default answers as we have
// setup an existing answer set
EnableAnswersDefault = false;
AddSection(-1, 0);
SectionCount = 0;
TargetSection = int.Parse(e.SectionNumber.ToString());
AddSubmitSectionButtons(true);
GridMode = SectionGridMode.Edit;
}
/// <summary>
/// A section has been removed on the grid.
/// Update the target section number if any was setup or
/// show a "new section" area if the last section has
/// been removed on the grid
/// </summary>
protected virtual void AnswersGrid_DeleteSection(object sender, SectionAnswersItemEventArgs e)
{
int deletedSection = int.Parse(e.SectionNumber.ToString());
// Is the deleted section being in edit mode ?
if (GridMode == SectionGridMode.Edit && TargetSection == deletedSection)
{
//Removes it
SectionCount = -1;
TargetSection = -1;
GridMode = SectionGridMode.None;
_sectionTable.Controls.Clear();
// Did the user delete the last section ?
if (GetSectionCountFromAnswers(_postedAnswers) < 1)
{
AddSection(-1, 0);
AddSubmitSectionButtons(GridMode == SectionGridMode.Edit);
SectionCount = 0;
TargetSection = 0;
}
}
else
{
// Is an add section is already displayed ?
if (_sections.Count > 0)
{
// Is the target section
if (TargetSection > 0 && TargetSection >= deletedSection)
{
TargetSection--;
// Updates the button arguments
AddSubmitSectionButtons(GridMode == SectionGridMode.Edit);
}
}
else
{
// Did the user delete the last section ?
if (GetSectionCountFromAnswers(_postedAnswers) < 1)
{
AddSection(-1, 0);
AddSubmitSectionButtons(GridMode == SectionGridMode.Edit);
SectionCount = 0;
TargetSection = 0;
}
}
}
}
private void AddSubmitSectionButtons(bool editMode)
{
_buttonsPlaceHolder.Controls.Clear();
Button cancelSectionButton = new Button();
Button submitSectioButton;
if (editMode)
{
submitSectioButton = _updateSectionButton;
submitSectioButton.ID = "SubmitSectionButton";
submitSectioButton.Text = UpdateSectionLinkText;
submitSectioButton.CssClass = CssXmlManager.GetString("AnswerUploadButton");
submitSectioButton.Click += new EventHandler(UpdateSectionButton_Click);
}
else
{
submitSectioButton = _addSectionButton;
submitSectioButton.Text = AddSectionLinkText;
submitSectioButton.CssClass = CssXmlManager.GetString("AnswerUploadButton");
submitSectioButton.Click += new EventHandler(SubmitSectionButton_Click);
}
// Does the section generate client side validation scripts
if (EnableGridSectionClientSideValidation && _sections[0].GeneratesClientSideScript())
{
submitSectioButton.Attributes.Add("OnClick", string.Format("return {0}{1}();",
GlobalConfig.QuestionValidationFunction, _sections[0].UniqueID.Replace(":", "_")));
}
submitSectioButton.Enabled = RenderMode != ControlRenderMode.ReadOnly;
_buttonsPlaceHolder.Controls.Add(submitSectioButton);
if (_sectionGrid.GridVoterAnswers.Count > 0)
{
cancelSectionButton.ID = "CancelSectionButton";
cancelSectionButton.Text = CancelButtonText;
cancelSectionButton.CssClass = CssXmlManager.GetString("AnswerUploadButton");
cancelSectionButton.Click += new EventHandler(CancelSectionButton_Click);
_buttonsPlaceHolder.Controls.Add(cancelSectionButton);
}
_sectionTable.Rows.Add(BuildRow(_buttonsPlaceHolder, null));
}
/// <summary>
/// Add new posted answers to the section grid
/// </summary>
private void SubmitSectionButton_Click(object sender, EventArgs e)
{
// Can we store the section's answer into the temp question datagrid store?
if (!EnableGridSectionServerSideValidation || (!IsSelectionOverflow && !IsSelectionRequired && !HasInvalidAnswers
&& _sectionGrid != null))
{
ReBindGrid();
}
// Do we need to check for validation errors ?
if (EnableGridSectionServerSideValidation)
{
EnableServerSideValidation = true;
}
}
/// <summary>
/// Updates section grid with the posted answers
/// </summary>
private void UpdateSectionButton_Click(object sender, EventArgs e)
{
if (!EnableGridSectionServerSideValidation || (!IsSelectionOverflow && !IsSelectionRequired && !HasInvalidAnswers
&& _sectionGrid != null))
{
// Makes sure no answers are left to avoid duplicates
DeleteSectionAnswers(TargetSection, _postedAnswers);
// "Insert" updated answers
SwitchAnswerSectionNumber(-1, TargetSection, _postedAnswers);
ReBindGrid();
}
// Do we need to check for validation errors ?
if (EnableGridSectionServerSideValidation)
{
EnableServerSideValidation = true;
}
}
/// <summary>
/// Cancel the "new section" area
/// </summary>
private void CancelSectionButton_Click(object sender, EventArgs e)
{
SectionCount = -1;
TargetSection = -1;
GridMode = SectionGridMode.None;
_sectionTable.Controls.Clear();
}
/// <summary>
/// Rebind grid based on posted answers
/// </summary>
private void ReBindGrid()
{
// Clear all items and avoid duplicates in the grid as
// they have already been posted back and are available
// in the _questionEventArgs.Answers
_sectionGrid.GridVoterAnswers.Clear();
// add answers to the grid
foreach (PostedAnswerData postedAnswer in _postedAnswers)
{
_sectionGrid.GridVoterAnswers.Add(new GridAnswerData(QuestionId, postedAnswer.AnswerId, postedAnswer.SectionNumber, postedAnswer.FieldText, postedAnswer.TypeMode));
}
if (_sectionGrid.GridVoterAnswers.Count > 0)
{
SectionCount = -1;
TargetSection = -1;
GridMode = SectionGridMode.None;
_sectionTable.Controls.Clear();
_sectionGrid.Controls.Clear();
_sectionGrid.BindSectionGrid();
}
}
/// <summary>
/// Handles posted answers and make sure
/// to post answers if there aren't any in the section
/// or delete all unvalidated answers if answers exist
/// in the section
/// </summary>
override protected void PostedAnswersHandler(PostedAnswerDataCollection answers)
{
_postedAnswers = answers;
if (RepeatMode == RepeatableSectionMode.GridAnswers)
{
int sectionCount = GetSectionCountFromAnswers(answers);
// if update, add modes and update, add buttons as not been
// used or at least one section already exisits
// delete all updated answers
if ((GridMode == SectionGridMode.Edit &&
Context.Request[_updateSectionButton.UniqueID] == null) ||
(GridMode == SectionGridMode.AddNew &&
Context.Request[_addSectionButton.UniqueID] == null &&
sectionCount >= 0))
{
// Delete all answers as we dont want to post unvalidated answers
DeleteSectionAnswers(-1, answers);
}
// are we currently add an existing section ?
else if (GridMode == SectionGridMode.AddNew)
{
// Reorder the posted answer sections based on
// the current target section number
OrderTargetSectionAnswers(TargetSection, answers);
}
}
}
/// <summary>
/// Removes all answers related to the target section number
/// </summary>
protected void DeleteSectionAnswers(int targetSection, PostedAnswerDataCollection answers)
{
for (int i = answers.Count - 1; i >= 0; i--)
{
// Find and update the section number
if (answers[i].SectionNumber == targetSection)
{
answers.RemoveAt(i);
}
}
}
/// <summary>
/// Reorder the posted section in the correct
/// order based on the target section's new section number
/// new section answers are marked with a -1 sectionnumber
/// </summary>
/// <param name="targetSection"></param>
protected void OrderTargetSectionAnswers(int targetSection, PostedAnswerDataCollection answers)
{
int sectionCount = GetSectionCountFromAnswers(answers);
// Is this the first section ever posted ?
if ((targetSection == -1 || targetSection == 0) && sectionCount == -1)
{
foreach (PostedAnswerData postedAnswer in answers)
{
// Find and update the new section posted answers
if (postedAnswer.SectionNumber == -1)
{
postedAnswer.SectionNumber = 0;
}
}
}
else if (targetSection != -1 && targetSection <= sectionCount)
{
// increment all user answers section numbers
for (int i = sectionCount; i >= targetSection; i--)
{
SwitchAnswerSectionNumber(i, i + 1, answers);
}
}
if (targetSection != -1)
{
// Inserts the new section answers
foreach (PostedAnswerData postedAnswer in answers)
{
// Find and update the new section posted answers
if (postedAnswer.SectionNumber == -1)
{
postedAnswer.SectionNumber = targetSection;
}
}
}
}
/// <summary>
/// Returns the section based count on the
/// current posted answer's data, doesnt include
/// the count of any "add new section" only counted
/// are the section already posted, validated and stored in
/// the grid
/// </summary>
public int GetSectionCountFromAnswers(PostedAnswerDataCollection postedAnswers)
{
int sectionCount = -1;
if (postedAnswers != null)
{
for (int i = 0; i < postedAnswers.Count; i++)
{
if (postedAnswers[i].SectionNumber > sectionCount)
{
sectionCount = postedAnswers[i].SectionNumber;
}
}
}
return sectionCount;
}
/// <summary>
/// Change the all answers with the section number to the new section number
/// </summary>
private void SwitchAnswerSectionNumber(int sectionNumber, int newSectionNumber, PostedAnswerDataCollection answers)
{
// Inserts the new section answers
foreach (PostedAnswerData postedAnswer in answers)
{
// Find and update the new section posted answers
if (postedAnswer.SectionNumber == sectionNumber)
{
postedAnswer.SectionNumber = newSectionNumber;
}
}
}
private void DeleteStateAnswersForSection(int sectionNumber)
{
if (VoterAnswersState != null)
{
VoterAnswersData.VotersAnswersRow[] answerState =
(VoterAnswersData.VotersAnswersRow[])VoterAnswersState.Select("QuestionId = " + QuestionId + " AND SectionNumber=" + sectionNumber);
for (int i = 0; i < answerState.Length; i++)
{
VoterAnswersState.RemoveVotersAnswersRow(answerState[i]);
}
}
}
private void ChangeStateAnswersSection(int oldSectionNumber, int newSectionNumber)
{
if (VoterAnswersState != null)
{
VoterAnswersData.VotersAnswersRow[] answerState =
(VoterAnswersData.VotersAnswersRow[])VoterAnswersState.Select("QuestionId = " + QuestionId + " AND SectionNumber=" + oldSectionNumber);
for (int i = 0; i < answerState.Length; i++)
{
answerState[i].SectionNumber = newSectionNumber;
}
}
}
/// <summary>
/// Returns the exsiting Uid of the section
/// if it doesnt exists creates a random
/// UId and store it in the viewstate collection
/// for futur postbacks
/// </summary>
virtual protected int GetSectionUid(int sectionNumber)
{
int sectionUid = -1;
if (SectionUids.Count <= sectionNumber)
{
for (int i = SectionUids.Count; i <= sectionNumber; i++)
{
sectionUid = GetUidForSection();
SectionUids.Add(sectionUid);
}
}
else
{
sectionUid = int.Parse(SectionUids[sectionNumber].ToString());
}
return sectionUid;
}
/// <summary>
/// Must returns the number of sections that
/// must be restored for this question, should
/// be based on the current answerstate
/// </summary>
/// <returns></returns>
abstract protected int GetSectionCountFromState();
/// <summary>
/// Must return a new section
/// populated with its answers or child questions
/// </summary>
abstract protected Section CreateSection(int sectionNumber, int sectionGuid);
/// <summary>
/// Must return a valid grid that will be use in
/// grid section mode. Null can be returned if no
/// grid can be generated
/// </summary>
abstract protected SectionAnswersGridItem GetSectionAnswersGrid();
/// <summary>
/// Notify subscriber that a script has been generated
/// for the given section
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Section_ClientScriptGenerated(object sender, QuestionItemClientScriptEventArgs e)
{
OnClientScriptGeneration(e);
}
private Table _sectionTable = Votations.NSurvey.BE.Votations.NSurvey.Constants.Commons.GetSectPercentTable();//JJ;
private SectionCollection _sections = new SectionCollection();
private Style _sectionOptionStyle;
private int _maxSections = 0;
private RepeatableSectionMode _repeatMode = RepeatableSectionMode.None;
private string _addSectionLinkText,
_deleteSectionLinkText,
_updateSectionLinkText,
_editSectionLinkText,
_cancelButtonText;
private Button _addSectionButton = new Button(),
_updateSectionButton = new Button();
private PlaceHolder _buttonsPlaceHolder = new PlaceHolder();
private PostedAnswerDataCollection _postedAnswers;
SectionAnswersGridItem _sectionGrid;
private Style _sectionGridAnswersStyle,
_sectionGridAnswersHeaderStyle,
_sectionGridAnswersAlternatingItemStyle,
_sectionGridAnswersItemStyle;
bool _enableGridSectionServerSideValidation = false,
_enableGridSectionClientSideValidation = false;
int[] _gridAnswers = new int[0];
}
}
| gpl-3.0 |
ciscoqid/librenms | html/includes/common/top-devices.inc.php | 16837 | <?php
/* Copyright (C) 2015 Sergiusz Paprzycki <serek@walcz.net>
* Copyright (C) 2016 Cercel Valentin <crc@nuamchefazi.ro>
*
* This widget is based on legacy frontpage module created by Paul Gear.
*
* 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 LibreNMS\Authentication\Auth;
$top_query = $widget_settings['top_query'] ?: 'traffic';
$sort_order = $widget_settings['sort_order'];
$selected_sort_asc = '';
$selected_sort_desc = '';
if ($sort_order === 'asc') {
$selected_sort_asc = 'selected';
} elseif ($sort_order === 'desc') {
$selected_sort_desc = 'selected';
}
$selected_traffic = '';
$selected_uptime = '';
$selected_ping = '';
$selected_cpu = '';
$selected_ram = '';
$selected_poller = '';
$selected_storage = '';
switch ($top_query) {
case "traffic":
$table_header = 'Traffic';
$selected_traffic = 'selected';
$graph_type = 'device_bits';
$graph_params = array();
break;
case "uptime":
$table_header = 'Uptime';
$selected_uptime = 'selected';
$graph_type = 'device_uptime';
$graph_params = array('tab' => 'graphs', 'group' => 'system');
break;
case "ping":
$table_header = 'Response time';
$selected_ping = 'selected';
$graph_type = 'device_ping_perf';
$graph_params = array('tab' => 'graphs', 'group' => 'poller');
break;
case "cpu":
$table_header = 'CPU Load';
$selected_cpu = 'selected';
$graph_type = 'device_processor';
$graph_params = array('tab' => 'health', 'metric' => 'processor');
break;
case "ram":
$table_header = 'Memory usage';
$selected_ram = 'selected';
$graph_type = 'device_mempool';
$graph_params = array('tab' => 'health', 'metric' => 'mempool');
break;
case "poller":
$table_header = 'Poller duration';
$selected_poller = 'selected';
$graph_type = 'device_poller_perf';
$graph_params = array('tab' => 'graphs', 'group' => 'poller');
break;
case "storage":
$table_header = 'Disk usage';
$selected_storage = 'selected';
$graph_type = 'device_storage';
$graph_params = array('tab' => 'health', 'metric' => 'storage');
break;
}
$widget_settings['device_count'] = $widget_settings['device_count'] > 0 ? $widget_settings['device_count'] : 5;
$widget_settings['time_interval'] = $widget_settings['time_interval'] > 0 ? $widget_settings['time_interval'] : 15;
if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
$common_output[] = '
<form class="form" onsubmit="widget_settings(this); return false;">
<div class="form-group">
<div class="col-sm-4">
<label for="title" class="control-label availability-map-widget-header">Widget title</label>
</div>
<div class="col-sm-6">
<input type="text" class="form-control" name="title" placeholder="Custom title for widget" value="' . htmlspecialchars($widget_settings['title']) . '">
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
<label for="top_query" class="control-label availability-map-widget-header">Top query</label>
</div>
<div class="col-sm-6">
<select class="form-control" name="top_query">
<option value="traffic" ' . $selected_traffic . '>Traffic</option>
<option value="uptime" ' . $selected_uptime . '>Uptime</option>
<option value="ping" ' . $selected_ping . '>Response time</option>
<option value="poller" ' . $selected_poller . '>Poller duration</option>
<option value="cpu" ' . $selected_cpu . '>Processor load</option>
<option value="ram" ' . $selected_ram . '>Memory usage</option>
<option value="storage" ' . $selected_storage . '>Disk usage</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
<label for="top_query" class="control-label availability-map-widget-header">Sort order</label>
</div>
<div class="col-sm-6">
<select class="form-control" name="sort_order">
<option value="asc" ' . $selected_sort_asc . '>Ascending</option>
<option value="desc" ' . $selected_sort_desc . '>Descending</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
<label for="graph_type" class="control-label availability-map-widget-header">Number of Devices</label>
</div>
<div class="col-sm-6">
<input class="form-control" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" name="device_count" id="input_count_' . $unique_id . '" value="' . $widget_settings['device_count'] . '">
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
<label for="graph_type" class="control-label availability-map-widget-header">Time interval (minutes)</label>
</div>
<div class="col-sm-6">
<input class="form-control" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" name="time_interval" id="input_time_' . $unique_id . '" value="' . $widget_settings['time_interval'] . '">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button type="submit" class="btn btn-default">Set</button>
</div>
</div>
</form>';
} else {
$interval = $widget_settings['time_interval'];
(integer)$interval_seconds = ($interval * 60);
(integer)$device_count = $widget_settings['device_count'];
$common_output[] = '<h4>Top ' . $device_count . ' devices (last ' . $interval . ' minutes)</h4>';
$params = ['interval' => $interval_seconds, 'count' => $device_count];
if (!Auth::user()->hasGlobalRead()) {
$params['user'] = Auth::id();
}
if ($top_query === 'traffic') {
if (Auth::user()->hasGlobalRead()) {
$query = '
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d
WHERE d.device_id = p.device_id
AND unix_timestamp() - p.poll_time < :interval
AND ( p.ifInOctets_rate > 0
OR p.ifOutOctets_rate > 0 )
GROUP BY d.device_id
ORDER BY total ' . $sort_order . '
LIMIT :count
';
} else {
$query = '
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user AND `P`.`device_id` = `d`.`device_id` AND
d.device_id = p.device_id
AND unix_timestamp() - p.poll_time < :interval
AND ( p.ifInOctets_rate > 0
OR p.ifOutOctets_rate > 0 )
GROUP BY d.device_id
ORDER BY total ' . $sort_order . '
LIMIT :count
';
}
} elseif ($top_query === 'uptime') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `uptime`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `uptime` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `uptime`, `hostname`, `last_polled`, `d`.`device_id`, `d`.`sysName`
FROM `devices` as `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user
AND `P`.`device_id` = `d`.`device_id`
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `uptime` ' . $sort_order . '
LIMIT :count';
}
} elseif ($top_query === 'ping') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `last_ping_timetaken`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `last_ping_timetaken` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `last_ping_timetaken`, `hostname`, `last_polled`, `d`.`device_id`, `d`.`sysName`
FROM `devices` as `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user
AND `P`.`device_id` = `d`.`device_id`
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `last_ping_timetaken` ' . $sort_order . '
LIMIT :count';
}
} elseif ($top_query === 'cpu') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, avg(`processor_usage`) as `cpuload`, `d`.`sysName`
FROM `processors` AS `procs`, `devices` AS `d`
WHERE `d`.`device_id` = `procs`.`device_id`
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
GROUP BY `d`.`device_id`, `d`.`hostname`, `d`.`last_polled`, `d`.`sysName`
ORDER BY `cpuload` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, avg(`processor_usage`) as `cpuload`, `d`.`sysName`
FROM `processors` AS procs, `devices` AS `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user AND `P`.`device_id` = `procs`.`device_id` AND `P`.`device_id` = `d`.`device_id`
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
GROUP BY `procs`.`device_id`, `d`.`hostname`, `d`.`last_polled`, `d`.`sysName`
ORDER BY `cpuload` ' . $sort_order . '
LIMIT :count';
}
} elseif ($top_query === 'ram') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `mempool_perc`, `d`.`sysName`
FROM `mempools` as `mem`, `devices` as `d`
WHERE `d`.`device_id` = `mem`.`device_id`
AND `mempool_descr` IN (\'Physical memory\',\'Memory\')
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `mempool_perc` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `mempool_perc`, `d`.`sysName`
FROM `mempools` as `mem`, `devices` as `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user AND `P`.`device_id` = `mem`.`device_id` AND `P`.`device_id` = `d`.`device_id`
AND `mempool_descr` IN (\'Physical memory\',\'Memory\')
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `mempool_perc` ' . $sort_order . '
LIMIT :count';
}
} elseif ($top_query === 'storage') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `storage_perc`, `d`.`sysName`, `storage_descr`, `storage_perc_warn`, `storage_id`
FROM `storage` as `disk`, `devices` as `d`
WHERE `d`.`device_id` = `disk`.`device_id`
AND `d`.`type` = \'server\'
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `storage_perc` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `storage_perc`, `d`.`sysName`, `storage_descr`, `storage_perc_warn`, `storage_id`
FROM `storage` as `disk`, `devices` as `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user AND `P`.`device_id` = `disk`.`device_id` AND `P`.`device_id` = `d`.`device_id`
AND `d`.`type` = \'server\'
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `storage_perc` ' . $sort_order . '
LIMIT :count';
}
} elseif ($top_query === 'poller') {
if (Auth::user()->hasGlobalRead()) {
$query = 'SELECT `last_polled_timetaken`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `last_polled_timetaken` ' . $sort_order . '
LIMIT :count';
} else {
$query = 'SELECT `last_polled_timetaken`, `hostname`, `last_polled`, `d`.`device_id`, `d`.`sysName`
FROM `devices` as `d`, `devices_perms` AS `P`
WHERE `P`.`user_id` = :user
AND `P`.`device_id` = `d`.`device_id`
AND unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
ORDER BY `last_polled_timetaken` ' . $sort_order . '
LIMIT :count';
}
}
$common_output[] = '
<div class="table-responsive">
<table class="table table-hover table-condensed table-striped bootgrid-table">
<thead>
<tr>
<th class="text-left">Device</th>';
if ($top_query == 'storage') {
$common_output[] = '<th class="text-left">Storage Device</th>';
}
$common_output[] = ' <th class="text-left">' . $table_header . '</a></th>
</tr>
</thead>
<tbody>';
foreach (dbFetchRows($query, $params) as $result) {
$common_output[] = '
<tr>
<td class="text-left">' . generate_device_link($result, shorthost($result['hostname'])) . '</td>
<td class="text-left">';
if ($top_query == 'storage') {
$graph_array = array();
$graph_array['height'] = '100';
$graph_array['width'] = '210';
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $drive['storage_id'];
$graph_array['type'] = $graph_type;
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = 'no';
$overlib_content = generate_overlib_content($graph_array, $result['hostname'].' - '.$result['storage_descr']);
$link_array = $graph_array;
$link_array['page'] = 'graphs';
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link = generate_url($link_array);
$percent = $result['storage_perc'];
$background = get_percentage_colours($percent, $result['storage_perc_warn']);
$common_output[] = shorten_text($result['storage_descr'], 50).'</td><td class="text-left">';
$common_output[] = overlib_link($link, print_percentage_bar(150, 20, $percent, null, 'ffffff', $background['left'], $percent.'%', 'ffffff', $background['right']), $overlib_content);
} else {
$common_output[] = generate_device_link($result, generate_minigraph_image($result, $config['time']['day'], $config['time']['now'], $graph_type, 'no', 150, 21), $graph_params, 0, 0, 0);
}
$common_output[] = '</td></tr>';
}
$common_output[] = '
</tbody>
</table>
</div>';
}
| gpl-3.0 |
XeCycle/indico | indico/MaKaC/webinterface/rh/authorDisplay.py | 1511 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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.
#
# Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
from MaKaC.webinterface.pages import authors
from MaKaC.webinterface import urlHandlers
from MaKaC.webinterface.rh.contribDisplay import RHContributionDisplayBase
from MaKaC.errors import MaKaCError
class RHAuthorDisplayBase( RHContributionDisplayBase ):
def _checkParams( self, params ):
RHContributionDisplayBase._checkParams( self, params )
self._authorId = params.get( "authorId", "" ).strip()
if self._authorId == "":
raise MaKaCError(_("Author ID not found. The URL you are trying to access might be wrong."))
class RHAuthorDisplay( RHAuthorDisplayBase ):
_uh = urlHandlers.UHContribAuthorDisplay
def _process( self ):
p = authors.WPAuthorDisplay( self, self._contrib, self._authorId )
return p.display()
| gpl-3.0 |
holger-seelig/titania | Titania/Titania/Editors/NodePropertiesEditor/NodePropertiesEditor.cpp | 4768 | /* -*- Mode: C++; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
*******************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
*
* All rights reserved. Holger Seelig <holger.seelig@yahoo.de>.
*
* THIS IS UNPUBLISHED SOURCE CODE OF create3000.
*
* The copyright notice above does not evidence any actual of intended
* publication of such source code, and is an unpublished work by create3000.
* This material contains CONFIDENTIAL INFORMATION that is the property of
* create3000.
*
* No permission is granted to copy, distribute, or create derivative works from
* the contents of this software, in whole or in part, without the prior written
* permission of create3000.
*
* NON-MILITARY USE ONLY
*
* All create3000 software are effectively free software with a non-military use
* restriction. It is free. Well commented source is provided. You may reuse the
* source in any way you please with the exception anything that uses it must be
* marked to indicate is contains 'non-military use only' components.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 1999, 2016 Holger Seelig <holger.seelig@yahoo.de>.
*
* This file is part of the Titania Project.
*
* Titania is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 only, as published by the
* Free Software Foundation.
*
* Titania is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License version 3 for more
* details (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License version 3
* along with Titania. If not, see <http://www.gnu.org/licenses/gpl.html> for a
* copy of the GPLv3 License.
*
* For Silvio, Joy and Adi.
*
******************************************************************************/
#include "NodePropertiesEditor.h"
#include "../../Browser/X3DBrowserWindow.h"
#include "../../Configuration/config.h"
namespace titania {
namespace puck {
NodePropertiesEditor::NodePropertiesEditor (X3DBrowserWindow* const browserWindow) :
X3DBaseInterface (browserWindow, browserWindow -> getMasterBrowser ()),
X3DNodePropertiesEditorInterface (get_ui ("Editors/NodePropertiesEditor.glade")),
X3DUserDefinedFieldsEditor (),
X3DImportedNodesEditor (),
X3DExportedNodesEditor (),
node (),
nodeName (this, getNameEntry (), getRenameButton ())
{
addChildObjects (node);
setup ();
}
void
NodePropertiesEditor::initialize ()
{
X3DNodePropertiesEditorInterface::initialize ();
X3DUserDefinedFieldsEditor::initialize ();
X3DImportedNodesEditor::initialize ();
X3DExportedNodesEditor::initialize ();
}
void
NodePropertiesEditor::configure ()
{
X3DNodePropertiesEditorInterface::configure ();
getNodeChildNotebook () .set_current_page (getConfig () -> getItem <int32_t> ("currentPage"));
}
void
NodePropertiesEditor::set_selection (const X3D::MFNode & selection)
{
X3DNodePropertiesEditorInterface::set_selection (selection);
if (node)
node -> name_changed () .removeInterest (&NodePropertiesEditor::set_name, this);
node = selection .empty () ? nullptr : selection .back ();
if (node)
{
node -> name_changed () .addInterest (&NodePropertiesEditor::set_name, this);
set_name ();
getTypeNameEntry () .set_text (node -> getTypeName ());
getComponentEntry () .set_text (node -> getComponent () .first);
getContainerFieldEntry () .set_text (node -> getContainerField ());
}
else
{
getHeaderBar () .set_subtitle (_ ("Select a node to display its properties."));
getTypeNameEntry () .set_text ("");
getComponentEntry () .set_text ("");
getContainerFieldEntry () .set_text ("");
}
nodeName .setNode (node);
X3DUserDefinedFieldsEditor::setNode (node);
X3DImportedNodesEditor::setNode (node);
X3DExportedNodesEditor::setNode (node);
}
void
NodePropertiesEditor::set_name ()
{
getHeaderBar () .set_subtitle (node -> getTypeName () + " »" + node -> getName () + "«");
}
void
NodePropertiesEditor::store ()
{
getConfig () -> setItem ("currentPage", getNodeChildNotebook () .get_current_page ());
X3DUserDefinedFieldsEditor::store ();
X3DNodePropertiesEditorInterface::store ();
}
NodePropertiesEditor::~NodePropertiesEditor ()
{
dispose ();
}
} // puck
} // titania
| gpl-3.0 |
brunosr1985/PHPLogin | node_modules/ionic-angular/umd/navigation/url-serializer.js | 24549 | (function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "@angular/core", "../util/util"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var util_1 = require("../util/util");
/**
* @hidden
*/
var UrlSerializer = (function () {
/**
* @param {?} _app
* @param {?} config
*/
function UrlSerializer(_app, config) {
this._app = _app;
if (config && util_1.isArray(config.links)) {
this.links = exports.normalizeLinks(config.links);
}
else {
this.links = [];
}
}
/**
* Parse the URL into a Path, which is made up of multiple NavSegments.
* Match which components belong to each segment.
* @param {?} browserUrl
* @return {?}
*/
UrlSerializer.prototype.parse = function (browserUrl) {
if (browserUrl.charAt(0) === '/') {
browserUrl = browserUrl.substr(1);
}
// trim off data after ? and #
browserUrl = browserUrl.split('?')[0].split('#')[0];
return convertUrlToSegments(this._app, browserUrl, this.links);
};
/**
* @param {?} navContainer
* @param {?} nameOrComponent
* @return {?}
*/
UrlSerializer.prototype.createSegmentFromName = function (navContainer, nameOrComponent) {
var /** @type {?} */ configLink = this.getLinkFromName(nameOrComponent);
if (configLink) {
return this._createSegment(this._app, navContainer, configLink, null);
}
return null;
};
/**
* @param {?} nameOrComponent
* @return {?}
*/
UrlSerializer.prototype.getLinkFromName = function (nameOrComponent) {
return this.links.find(function (link) {
return (link.component === nameOrComponent) ||
(link.name === nameOrComponent);
});
};
/**
* Serialize a path, which is made up of multiple NavSegments,
* into a URL string. Turn each segment into a string and concat them to a URL.
* @param {?} segments
* @return {?}
*/
UrlSerializer.prototype.serialize = function (segments) {
if (!segments || !segments.length) {
return '/';
}
var /** @type {?} */ sections = segments.map(function (segment) {
if (segment.type === 'tabs') {
if (segment.requiresExplicitNavPrefix) {
return "/" + segment.type + "/" + segment.navId + "/" + segment.secondaryId + "/" + segment.id;
}
return "/" + segment.secondaryId + "/" + segment.id;
}
// it's a nav
if (segment.requiresExplicitNavPrefix) {
return "/" + segment.type + "/" + segment.navId + "/" + segment.id;
}
return "/" + segment.id;
});
return sections.join('');
};
/**
* Serializes a component and its data into a NavSegment.
* @param {?} navContainer
* @param {?} component
* @param {?} data
* @return {?}
*/
UrlSerializer.prototype.serializeComponent = function (navContainer, component, data) {
if (component) {
var /** @type {?} */ link = exports.findLinkByComponentData(this.links, component, data);
if (link) {
return this._createSegment(this._app, navContainer, link, data);
}
}
return null;
};
/**
* \@internal
* @param {?} app
* @param {?} navContainer
* @param {?} configLink
* @param {?} data
* @return {?}
*/
UrlSerializer.prototype._createSegment = function (app, navContainer, configLink, data) {
var /** @type {?} */ urlParts = configLink.segmentParts;
if (util_1.isPresent(data)) {
// create a copy of the original parts in the link config
urlParts = urlParts.slice();
// loop through all the data and convert it to a string
var /** @type {?} */ keys = Object.keys(data);
var /** @type {?} */ keysLength = keys.length;
if (keysLength) {
for (var /** @type {?} */ i = 0; i < urlParts.length; i++) {
if (urlParts[i].charAt(0) === ':') {
for (var /** @type {?} */ j = 0; j < keysLength; j++) {
if (urlParts[i] === ":" + keys[j]) {
// this data goes into the URL part (between slashes)
urlParts[i] = encodeURIComponent(data[keys[j]]);
break;
}
}
}
}
}
}
var /** @type {?} */ requiresExplicitPrefix = true;
if (navContainer.parent) {
requiresExplicitPrefix = navContainer.parent && navContainer.parent.getAllChildNavs().length > 1;
}
else {
// if it's a root nav, and there are multiple root navs, we need an explicit prefix
requiresExplicitPrefix = app.getRootNavById(navContainer.id) && app.getRootNavs().length > 1;
}
return {
id: urlParts.join('/'),
name: configLink.name,
component: configLink.component,
loadChildren: configLink.loadChildren,
data: data,
defaultHistory: configLink.defaultHistory,
navId: navContainer.name || navContainer.id,
type: navContainer.getType(),
secondaryId: navContainer.getSecondaryIdentifier(),
requiresExplicitNavPrefix: requiresExplicitPrefix
};
};
return UrlSerializer;
}());
exports.UrlSerializer = UrlSerializer;
function UrlSerializer_tsickle_Closure_declarations() {
/** @type {?} */
UrlSerializer.prototype.links;
/** @type {?} */
UrlSerializer.prototype._app;
}
/**
* @param {?} name
* @return {?}
*/
function formatUrlPart(name) {
name = name.replace(URL_REPLACE_REG, '-');
name = name.charAt(0).toLowerCase() + name.substring(1).replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
});
while (name.indexOf('--') > -1) {
name = name.replace('--', '-');
}
if (name.charAt(0) === '-') {
name = name.substring(1);
}
if (name.substring(name.length - 1) === '-') {
name = name.substring(0, name.length - 1);
}
return encodeURIComponent(name);
}
exports.formatUrlPart = formatUrlPart;
exports.isPartMatch = function (urlPart, configLinkPart) {
if (util_1.isPresent(urlPart) && util_1.isPresent(configLinkPart)) {
if (configLinkPart.charAt(0) === ':') {
return true;
}
return (urlPart === configLinkPart);
}
return false;
};
exports.createMatchedData = function (matchedUrlParts, link) {
var /** @type {?} */ data = null;
for (var /** @type {?} */ i = 0; i < link.segmentPartsLen; i++) {
if (link.segmentParts[i].charAt(0) === ':') {
data = data || {};
data[link.segmentParts[i].substring(1)] = decodeURIComponent(matchedUrlParts[i]);
}
}
return data;
};
exports.findLinkByComponentData = function (links, component, instanceData) {
var /** @type {?} */ foundLink = null;
var /** @type {?} */ foundLinkDataMatches = -1;
for (var /** @type {?} */ i = 0; i < links.length; i++) {
var /** @type {?} */ link = links[i];
if (link.component === component) {
// ok, so the component matched, but multiple links can point
// to the same component, so let's make sure this is the right link
var /** @type {?} */ dataMatches = 0;
if (instanceData) {
var /** @type {?} */ instanceDataKeys = Object.keys(instanceData);
// this link has data
for (var /** @type {?} */ j = 0; j < instanceDataKeys.length; j++) {
if (util_1.isPresent(link.dataKeys[instanceDataKeys[j]])) {
dataMatches++;
}
}
}
else if (link.dataLen) {
// this component does not have data but the link does
continue;
}
if (dataMatches >= foundLinkDataMatches) {
foundLink = link;
foundLinkDataMatches = dataMatches;
}
}
}
return foundLink;
};
exports.normalizeLinks = function (links) {
for (var /** @type {?} */ i = 0, /** @type {?} */ ilen = links.length; i < ilen; i++) {
var /** @type {?} */ link = links[i];
if (util_1.isBlank(link.segment)) {
link.segment = link.name;
}
link.dataKeys = {};
link.segmentParts = link.segment.split('/');
link.segmentPartsLen = link.segmentParts.length;
// used for sorting
link.staticLen = link.dataLen = 0;
var /** @type {?} */ stillCountingStatic = true;
for (var /** @type {?} */ j = 0; j < link.segmentPartsLen; j++) {
if (link.segmentParts[j].charAt(0) === ':') {
link.dataLen++;
stillCountingStatic = false;
link.dataKeys[link.segmentParts[j].substring(1)] = true;
}
else if (stillCountingStatic) {
link.staticLen++;
}
}
}
// sort by the number of parts, with the links
// with the most parts first
return links.sort(sortConfigLinks);
};
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function sortConfigLinks(a, b) {
// sort by the number of parts
if (a.segmentPartsLen > b.segmentPartsLen) {
return -1;
}
if (a.segmentPartsLen < b.segmentPartsLen) {
return 1;
}
// sort by the number of static parts in a row
if (a.staticLen > b.staticLen) {
return -1;
}
if (a.staticLen < b.staticLen) {
return 1;
}
// sort by the number of total data parts
if (a.dataLen < b.dataLen) {
return -1;
}
if (a.dataLen > b.dataLen) {
return 1;
}
return 0;
}
var /** @type {?} */ URL_REPLACE_REG = /\s+|\?|\!|\$|\,|\.|\+|\"|\'|\*|\^|\||\/|\\|\[|\]|#|%|`|>|<|;|:|@|&|=/g;
/**
* @hidden
*/
exports.DeepLinkConfigToken = new core_1.InjectionToken('USERLINKS');
/**
* @param {?} app
* @param {?} userDeepLinkConfig
* @return {?}
*/
function setupUrlSerializer(app, userDeepLinkConfig) {
return new UrlSerializer(app, userDeepLinkConfig);
}
exports.setupUrlSerializer = setupUrlSerializer;
/**
* @param {?} navGroupStrings
* @return {?}
*/
function navGroupStringtoObjects(navGroupStrings) {
// each string has a known format-ish, convert it to it
return navGroupStrings.map(function (navGroupString) {
var /** @type {?} */ sections = navGroupString.split('/');
if (sections[0] === 'nav') {
return {
type: 'nav',
navId: sections[1],
niceId: sections[1],
secondaryId: null,
segmentPieces: sections.splice(2)
};
}
else if (sections[0] === 'tabs') {
return {
type: 'tabs',
navId: sections[1],
niceId: sections[1],
secondaryId: sections[2],
segmentPieces: sections.splice(3)
};
}
return {
type: null,
navId: null,
niceId: null,
secondaryId: null,
segmentPieces: sections
};
});
}
exports.navGroupStringtoObjects = navGroupStringtoObjects;
/**
* @param {?} url
* @return {?}
*/
function urlToNavGroupStrings(url) {
var /** @type {?} */ tokens = url.split('/');
var /** @type {?} */ keywordIndexes = [];
for (var /** @type {?} */ i = 0; i < tokens.length; i++) {
if (i !== 0 && (tokens[i] === 'nav' || tokens[i] === 'tabs')) {
keywordIndexes.push(i);
}
}
// append the last index + 1 to the list no matter what
keywordIndexes.push(tokens.length);
var /** @type {?} */ groupings = [];
var /** @type {?} */ activeKeywordIndex = 0;
var /** @type {?} */ tmpArray = [];
for (var /** @type {?} */ i = 0; i < tokens.length; i++) {
if (i >= keywordIndexes[activeKeywordIndex]) {
groupings.push(tmpArray.join('/'));
tmpArray = [];
activeKeywordIndex++;
}
tmpArray.push(tokens[i]);
}
// okay, after the loop we've gotta push one more time just to be safe
groupings.push(tmpArray.join('/'));
return groupings;
}
exports.urlToNavGroupStrings = urlToNavGroupStrings;
/**
* @param {?} app
* @param {?} url
* @param {?} navLinks
* @return {?}
*/
function convertUrlToSegments(app, url, navLinks) {
var /** @type {?} */ pairs = convertUrlToDehydratedSegments(url, navLinks);
return hydrateSegmentsWithNav(app, pairs);
}
exports.convertUrlToSegments = convertUrlToSegments;
/**
* @param {?} url
* @param {?} navLinks
* @return {?}
*/
function convertUrlToDehydratedSegments(url, navLinks) {
var /** @type {?} */ navGroupStrings = urlToNavGroupStrings(url);
var /** @type {?} */ navGroups = navGroupStringtoObjects(navGroupStrings);
return getSegmentsFromNavGroups(navGroups, navLinks);
}
exports.convertUrlToDehydratedSegments = convertUrlToDehydratedSegments;
/**
* @param {?} app
* @param {?} dehydratedSegmentPairs
* @return {?}
*/
function hydrateSegmentsWithNav(app, dehydratedSegmentPairs) {
var /** @type {?} */ segments = [];
for (var /** @type {?} */ i = 0; i < dehydratedSegmentPairs.length; i++) {
var /** @type {?} */ navs = getNavFromNavGroup(dehydratedSegmentPairs[i].navGroup, app);
// okay, cool, let's walk through the segments and hydrate them
for (var _i = 0, _a = dehydratedSegmentPairs[i].segments; _i < _a.length; _i++) {
var dehydratedSegment = _a[_i];
if (navs.length === 1) {
segments.push(hydrateSegment(dehydratedSegment, navs[0]));
navs = navs[0].getActiveChildNavs();
}
else if (navs.length > 1) {
// this is almost certainly an async race condition bug in userland
// if you're in this state, it would be nice to just bail here
// but alas we must perservere and handle the issue
// the simple solution is to just use the last child
// because that is probably what the user wants anyway
// remember, do not harm, even if it makes our shizzle ugly
segments.push(hydrateSegment(dehydratedSegment, navs[navs.length - 1]));
navs = navs[navs.length - 1].getActiveChildNavs();
}
else {
break;
}
}
}
return segments;
}
exports.hydrateSegmentsWithNav = hydrateSegmentsWithNav;
/**
* @param {?} navGroup
* @param {?} app
* @return {?}
*/
function getNavFromNavGroup(navGroup, app) {
if (navGroup.navId) {
var /** @type {?} */ rootNav = app.getNavByIdOrName(navGroup.navId);
if (rootNav) {
return [rootNav];
}
return [];
}
// we don't know what nav to use, so just use the root nav.
// if there is more than one root nav, throw an error
return app.getRootNavs();
}
exports.getNavFromNavGroup = getNavFromNavGroup;
/**
* @param {?} navGroups
* @param {?} navLinks
* @return {?}
*/
function getSegmentsFromNavGroups(navGroups, navLinks) {
var /** @type {?} */ pairs = [];
var /** @type {?} */ usedNavLinks = new Set();
for (var _i = 0, navGroups_1 = navGroups; _i < navGroups_1.length; _i++) {
var navGroup = navGroups_1[_i];
var /** @type {?} */ segments = [];
var /** @type {?} */ segmentPieces = navGroup.segmentPieces.concat([]);
for (var /** @type {?} */ i = segmentPieces.length; i >= 0; i--) {
var /** @type {?} */ created = false;
for (var /** @type {?} */ j = 0; j < i; j++) {
var /** @type {?} */ startIndex = i - j - 1;
var /** @type {?} */ endIndex = i;
var /** @type {?} */ subsetOfUrl = segmentPieces.slice(startIndex, endIndex);
for (var _a = 0, navLinks_1 = navLinks; _a < navLinks_1.length; _a++) {
var navLink = navLinks_1[_a];
if (!usedNavLinks.has(navLink.name)) {
var /** @type {?} */ segment = getSegmentsFromUrlPieces(subsetOfUrl, navLink);
if (segment) {
i = startIndex + 1;
usedNavLinks.add(navLink.name);
created = true;
// sweet, we found a segment
segments.push(segment);
// now we want to null out the url subsection in the segmentPieces
for (var /** @type {?} */ k = startIndex; k < endIndex; k++) {
segmentPieces[k] = null;
}
break;
}
}
}
if (created) {
break;
}
}
if (!created && segmentPieces[i - 1]) {
// this is very likely a tab's secondary identifier
segments.push({
id: null,
name: null,
secondaryId: segmentPieces[i - 1],
component: null,
loadChildren: null,
data: null,
defaultHistory: null
});
}
}
// since we're getting segments in from right-to-left in the url, reverse them
// so they're in the correct order. Also filter out and bogus segments
var /** @type {?} */ orderedSegments = segments.reverse();
// okay, this is the lazy persons approach here.
// so here's the deal! Right now if section of the url is not a part of a segment
// it is almost certainly the secondaryId for a tabs component
// basically, knowing the segment for the `tab` itself is good, but we also need to know
// which tab is selected, so we have an identifer in the url that is associated with the tabs component
// telling us which tab is selected. With that in mind, we are going to go through and find the segments with only secondary identifiers,
// and simply add the secondaryId to the next segment, and then remove the empty segment from the list
for (var /** @type {?} */ i = 0; i < orderedSegments.length; i++) {
if (orderedSegments[i].secondaryId && !orderedSegments[i].id && ((i + 1) <= orderedSegments.length - 1)) {
orderedSegments[i + 1].secondaryId = orderedSegments[i].secondaryId;
orderedSegments[i] = null;
}
}
var /** @type {?} */ cleanedSegments = segments.filter(function (segment) { return !!segment; });
// if the nav group has a secondary id, make sure the first segment also has it set
if (navGroup.secondaryId && segments.length) {
cleanedSegments[0].secondaryId = navGroup.secondaryId;
}
pairs.push({
navGroup: navGroup,
segments: cleanedSegments
});
}
return pairs;
}
exports.getSegmentsFromNavGroups = getSegmentsFromNavGroups;
/**
* @param {?} urlSections
* @param {?} navLink
* @return {?}
*/
function getSegmentsFromUrlPieces(urlSections, navLink) {
if (navLink.segmentPartsLen !== urlSections.length) {
return null;
}
for (var /** @type {?} */ i = 0; i < urlSections.length; i++) {
if (!exports.isPartMatch(urlSections[i], navLink.segmentParts[i])) {
// just return an empty array if the part doesn't match
return null;
}
}
return {
id: urlSections.join('/'),
name: navLink.name,
component: navLink.component,
loadChildren: navLink.loadChildren,
data: exports.createMatchedData(urlSections, navLink),
defaultHistory: navLink.defaultHistory
};
}
exports.getSegmentsFromUrlPieces = getSegmentsFromUrlPieces;
/**
* @param {?} segment
* @param {?} nav
* @return {?}
*/
function hydrateSegment(segment, nav) {
var /** @type {?} */ hydratedSegment = (Object.assign({}, segment));
hydratedSegment.type = nav.getType();
hydratedSegment.navId = nav.name || nav.id;
// secondaryId is set on an empty dehydrated segment in the case of tabs to identify which tab is selected
hydratedSegment.secondaryId = segment.secondaryId;
return hydratedSegment;
}
exports.hydrateSegment = hydrateSegment;
/**
* @param {?} urlChunks
* @param {?} navLink
* @return {?}
*/
function getNonHydratedSegmentIfLinkAndUrlMatch(urlChunks, navLink) {
var /** @type {?} */ allSegmentsMatch = true;
for (var /** @type {?} */ i = 0; i < urlChunks.length; i++) {
if (!exports.isPartMatch(urlChunks[i], navLink.segmentParts[i])) {
allSegmentsMatch = false;
break;
}
}
if (allSegmentsMatch) {
return {
id: navLink.segmentParts.join('/'),
name: navLink.name,
component: navLink.component,
loadChildren: navLink.loadChildren,
data: exports.createMatchedData(urlChunks, navLink),
defaultHistory: navLink.defaultHistory
};
}
return null;
}
exports.getNonHydratedSegmentIfLinkAndUrlMatch = getNonHydratedSegmentIfLinkAndUrlMatch;
});
//# sourceMappingURL=url-serializer.js.map | gpl-3.0 |
marekjm/viuavm | src/assembler/frontend/static_analyser/checkers/check_op_texteq.cpp | 2541 | /*
* Copyright (C) 2018 Marek Marecki
*
* This file is part of Viua VM.
*
* Viua VM 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.
*
* Viua VM 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 Viua VM. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <vector>
#include <viua/assembler/frontend/static_analyser.h>
#include <viua/support/string.h>
using viua::assembler::frontend::parser::Instruction;
namespace viua { namespace assembler { namespace frontend {
namespace static_analyser { namespace checkers {
auto check_op_texteq(Register_usage_profile& register_usage_profile,
Instruction const& instruction) -> void
{
auto result = get_operand<Register_index>(instruction, 0);
if (not result) {
throw invalid_syntax(instruction.operands.at(0)->tokens,
"invalid operand")
.note("expected register index");
}
check_if_name_resolved(register_usage_profile, *result);
auto lhs = get_operand<Register_index>(instruction, 1);
if (not lhs) {
throw invalid_syntax(instruction.operands.at(1)->tokens,
"invalid left-hand side operand")
.note("expected register index");
}
auto rhs = get_operand<Register_index>(instruction, 2);
if (not rhs) {
throw invalid_syntax(instruction.operands.at(2)->tokens,
"invalid right-hand side operand")
.note("expected register index");
}
check_use_of_register(register_usage_profile, *lhs);
check_use_of_register(register_usage_profile, *rhs);
assert_type_of_register<viua::internals::Value_types::TEXT>(
register_usage_profile, *lhs);
assert_type_of_register<viua::internals::Value_types::TEXT>(
register_usage_profile, *rhs);
auto val = Register(*result);
val.value_type = viua::internals::Value_types::BOOLEAN;
register_usage_profile.define(val, result->tokens.at(0));
}
}}}}} // namespace viua::assembler::frontend::static_analyser::checkers
| gpl-3.0 |
Karlosjp/Clase-DAM | Santo Domingo Savio/Clase-DAM-2/Desarrollo de interfaces/Ejercicios/Ejercicios/src/Ejercicio4.java | 489 |
public class Ejercicio4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Recorrer un array de enteros y dar la cantidad total de nº pares
int contador = 0;
int [] enteros = {4, 5, 7, 10, 14, 9, 17, 2, 1, 28};
// i = 0 1 2 3 4 5 6 7 8
for (int i=0; i<enteros.length; i++) {
//int numero = enteros[i]; //4
if (enteros[i]%2 == 0) {
contador++;
}
}
System.out.println(contador);
}
}
| gpl-3.0 |
alexey4petrov/pythonFlu | Foam/src/OpenFOAM/fields/DimensionedFields/DimensionedField_scalar_volMesh.hh | 1431 | // pythonFlu - Python wrapping for OpenFOAM C++ API
// Copyright (C) 2010- Alexey Petrov
// Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR)
//
// 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/>.
//
// See http://sourceforge.net/projects/pythonflu
//
// Author : Alexey PETROV
//---------------------------------------------------------------------------
#ifndef DimensionedField_scalar_volMesh_hh
#define DimensionedField_scalar_volMesh_hh
//----------------------------------------------------------------------------
#include "Foam/src/OpenFOAM/fields/DimensionedFields/DimensionedField.hh"
#include "Foam/src/OpenFOAM/fields/Fields/primitiveFields.hh"
#include "Foam/src/finiteVolume/volMesh.hh"
//---------------------------------------------------------------------------
#endif
| gpl-3.0 |
GuillaumeDelente/OpenBike | src/fr/openbike/android/ui/HomeActivity.java | 13935 | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.openbike.android.ui;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import fr.openbike.android.IActivityHelper;
import fr.openbike.android.R;
import fr.openbike.android.database.OpenBikeDBAdapter;
import fr.openbike.android.model.Network;
import fr.openbike.android.service.ILocationServiceListener;
import fr.openbike.android.service.LocationService;
import fr.openbike.android.service.SyncService;
import fr.openbike.android.service.LocationService.LocationBinder;
import fr.openbike.android.utils.ActivityHelper;
import fr.openbike.android.utils.DetachableResultReceiver;
public class HomeActivity extends Activity implements ILocationServiceListener,
DetachableResultReceiver.Receiver, IActivityHelper {
public static final String ACTION_CHOOSE_NETWORK = "action_choose_network";
private static final String EXTRA_NETWORKS = "extra_networks";
private AlertDialog mNetworkDialog;
private NetworkAdapter mNetworkAdapter;
private SharedPreferences mSharedPreferences;
private LayoutInflater mLayoutInflater;
private ActivityHelper mActivityHelper = null;
protected DetachableResultReceiver mReceiver = null;
private boolean mBound = false;
private LocationService mService = null;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get
// LocalService instance
LocationBinder binder = (LocationBinder) service;
mService = binder.getService();
mBound = true;
mService.addListener(HomeActivity.this);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
mReceiver = DetachableResultReceiver.getInstance(new Handler());
mActivityHelper = new ActivityHelper(this);
mActivityHelper.setupActionBar(null);
mLayoutInflater = LayoutInflater.from(this);
mNetworkAdapter = new NetworkAdapter(this);
if (savedInstanceState != null) {
ArrayList<Network> networks = (ArrayList<Network>) savedInstanceState
.getSerializable(EXTRA_NETWORKS);
if (networks != null)
mNetworkAdapter.insertAll(networks);
}
mSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
setListeners();
PreferenceManager.setDefaultValues(this, R.xml.filter_preferences,
false);
PreferenceManager.setDefaultValues(this, R.xml.map_preferences, false);
PreferenceManager
.setDefaultValues(this, R.xml.other_preferences, false);
PreferenceManager.setDefaultValues(this, R.xml.location_preferences,
false);
startService(new Intent(this, LocationService.class));
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
super.onNewIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
mReceiver.setReceiver(this);
if (ACTION_CHOOSE_NETWORK.equals(getIntent().getAction())) {
setIntent(new Intent());
showChooseNetwork();
return;
}
if (mNetworkDialog == null || !mNetworkDialog.isShowing()) {
mActivityHelper.onResume();
}
}
@Override
protected void onStart() {
if (mSharedPreferences.getBoolean(
AbstractPreferencesActivity.LOCATION_PREFERENCE, true)) {
Intent intent = new Intent(this, LocationService.class);
bindService(intent, mConnection, 0);
}
super.onStart();
}
@Override
protected void onStop() {
if (mBound) {
mService.removeListener(HomeActivity.this);
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
@Override
protected void onPause() {
mReceiver.clearReceiver();
super.onPause();
}
private void showChooseNetwork() {
final Intent intent = new Intent(SyncService.ACTION_CHOOSE_NETWORK,
null, this, SyncService.class);
stopService(intent);
intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mReceiver);
startService(intent);
}
/**
*
*/
private void setListeners() {
findViewById(R.id.home_btn_list).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this,
OpenBikeListActivity.class));
}
});
findViewById(R.id.home_btn_map).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this,
OpenBikeMapActivity.class));
}
});
findViewById(R.id.home_btn_favorite).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this,
OpenBikeListActivity.class)
.setAction(OpenBikeListActivity.ACTION_FAVORITE));
}
});
findViewById(R.id.home_btn_filters).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this,
FiltersPreferencesActivity.class));
}
});
findViewById(R.id.home_btn_settings).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this,
SettingsPreferencesActivity.class));
}
});
findViewById(R.id.home_btn_search).setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
getActivityHelper().goSearch();
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mNetworkDialog != null && mNetworkDialog.isShowing()) {
if (!mNetworkAdapter.isEmpty())
outState.putSerializable(EXTRA_NETWORKS, mNetworkAdapter
.getItems());
}
super.onSaveInstanceState(outState);
}
@Override
protected Dialog onCreateDialog(int id) {
final SharedPreferences.Editor editor = mSharedPreferences.edit();
switch (id) {
case R.id.choose_network:
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
mNetworkDialog = new AlertDialog.Builder(this).setCancelable(false)
.setTitle(getString(R.string.choose_network_title))
.setSingleChoiceItems(mNetworkAdapter, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
editor
.putInt(
AbstractPreferencesActivity.NETWORK_PREFERENCE,
((Network) ((AlertDialog) dialog)
.getListView()
.getAdapter()
.getItem(item))
.getId());
Button okButton = mNetworkDialog
.getButton(Dialog.BUTTON_POSITIVE);
okButton.setEnabled(true);
}
}).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
ListView listView = ((AlertDialog) dialog)
.getListView();
Network network = (Network) listView
.getItemAtPosition(listView
.getCheckedItemPosition());
OpenBikeDBAdapter.getInstance(
HomeActivity.this)
.insertNetwork(network);
editor.commit();
setCurrentNetwork(editor, network);
getActivityHelper().startUpdate();
} catch (SQLiteException e) {
dismissDialog(R.id.choose_network);
showDialog(R.id.database_error);
}
}
private void setCurrentNetwork(Editor editor,
Network network) {
editor
.putString(
AbstractPreferencesActivity.UPDATE_SERVER_URL,
network.getServerUrl());
editor
.putInt(
AbstractPreferencesActivity.NETWORK_LATITUDE,
network.getLatitude());
editor
.putInt(
AbstractPreferencesActivity.NETWORK_LONGITUDE,
network.getLongitude());
editor
.putString(
AbstractPreferencesActivity.NETWORK_NAME,
network.getName());
editor
.putString(
AbstractPreferencesActivity.NETWORK_CITY,
network.getCity());
editor
.putString(
AbstractPreferencesActivity.SPECIAL_STATION,
network.getSpecialName());
Cursor networkCursor = OpenBikeDBAdapter
.getInstance(HomeActivity.this)
.getNetwork(
network.getId(),
new String[] { OpenBikeDBAdapter.KEY_VERSION });
editor
.putLong(
AbstractPreferencesActivity.STATIONS_VERSION,
networkCursor.moveToFirst() ? (long) networkCursor
.getInt(0)
: 0);
editor.commit();
/*
* ErrorReporter.getInstance().putCustomData(
* "Network",
* String.valueOf(network.getId()));
*/
}
}).setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (preferences
.getInt(
AbstractPreferencesActivity.NETWORK_PREFERENCE,
AbstractPreferencesActivity.NO_NETWORK) == AbstractPreferencesActivity.NO_NETWORK) {
finish();
} else {
dismissDialog(R.id.choose_network);
}
}
}).create();
return mNetworkDialog;
default:
Dialog dialog = getActivityHelper().onCreateDialog(id);
if (dialog != null)
return dialog;
}
return super.onCreateDialog(id);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActivityHelper.onPostCreate(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mActivityHelper.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.home_menu_items, menu);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mActivityHelper.onPrepareOptionsMenu(menu);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
default:
return mActivityHelper.onOptionsItemSelected(item)
|| super.onOptionsItemSelected(item);
}
}
private void displayNetworks(ArrayList<Network> networks) {
mNetworkAdapter.insertAll(networks);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case R.id.choose_network:
if (((AlertDialog) dialog).getListView().getEmptyView() == null) {
View emptyView = mLayoutInflater.inflate(R.layout.loading_view,
null);
emptyView.setVisibility(View.GONE);
((ViewGroup) ((AlertDialog) dialog).getListView().getParent())
.addView(emptyView);
((AlertDialog) dialog).getListView().setEmptyView(emptyView);
}
if (mNetworkAdapter != null)
mNetworkAdapter.notifyDataSetChanged();
((AlertDialog) dialog).getButton(Dialog.BUTTON_POSITIVE)
.setEnabled(
((AlertDialog) dialog).getListView()
.getCheckedItemPosition() != -1);
break;
default:
if (mNetworkDialog != null
&& mNetworkDialog.isShowing()
&& (id == R.id.json_error || id == R.id.database_error || id == R.id.network_error)) {
mNetworkDialog.dismiss();
}
getActivityHelper().onPrepareDialog(id, dialog);
}
super.onPrepareDialog(id, dialog);
}
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == SyncService.STATUS_SYNC_NETWORKS) {
showDialog(R.id.choose_network);
} else if (resultCode == SyncService.STATUS_SYNC_NETWORKS_FINISHED) {
ArrayList<Network> networks = resultData
.getParcelableArrayList(SyncService.EXTRA_RESULT);
displayNetworks(networks);
} else {
getActivityHelper().onReceiveResult(resultCode, resultData);
}
}
/**
* Returns the {@link ActivityHelper} object associated with this activity.
*/
@Override
public ActivityHelper getActivityHelper() {
return mActivityHelper;
}
@Override
public void onLocationChanged(Location l, boolean alert) {
// Nothing
}
@Override
public void onLocationProvidersChanged(int id) {
if (!isFinishing()) {
showDialog(id);
}
}
@Override
public void onStationsUpdated() {
// String a = null;
// a.length();
}
}
| gpl-3.0 |
mcisse3007/moodle_esco_master | filter/jmol/yui/jsmol/j2s/J/adapter/smarter/SmarterJmolAdapter.js | 9315 | Clazz.declarePackage ("J.adapter.smarter");
Clazz.load (["J.api.JmolAdapter"], "J.adapter.smarter.SmarterJmolAdapter", ["java.io.BufferedReader", "javajs.api.GenericBinaryDocument", "JU.Rdr", "J.adapter.smarter.AtomIterator", "$.AtomSetCollection", "$.AtomSetCollectionReader", "$.BondIterator", "$.Resolver", "$.StructureIterator", "JU.Logger"], function () {
c$ = Clazz.declareType (J.adapter.smarter, "SmarterJmolAdapter", J.api.JmolAdapter);
Clazz.overrideMethod (c$, "getFileTypeName",
function (ascOrReader) {
if (Clazz.instanceOf (ascOrReader, J.adapter.smarter.AtomSetCollection)) return (ascOrReader).fileTypeName;
if (Clazz.instanceOf (ascOrReader, java.io.BufferedReader)) return J.adapter.smarter.Resolver.getFileType (ascOrReader);
return null;
}, "~O");
Clazz.overrideMethod (c$, "getAtomSetCollectionReader",
function (name, type, bufferedReader, htParams) {
return J.adapter.smarter.SmarterJmolAdapter.staticGetAtomSetCollectionReader (name, type, bufferedReader, htParams);
}, "~S,~S,~O,java.util.Map");
c$.staticGetAtomSetCollectionReader = Clazz.defineMethod (c$, "staticGetAtomSetCollectionReader",
function (name, type, bufferedReader, htParams) {
try {
var ret = J.adapter.smarter.Resolver.getAtomCollectionReader (name, type, bufferedReader, htParams, -1);
if (Clazz.instanceOf (ret, String)) {
try {
J.adapter.smarter.SmarterJmolAdapter.close (bufferedReader);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
} else {
throw e;
}
}
} else {
(ret).setup (name, htParams, bufferedReader);
}return ret;
} catch (e) {
try {
J.adapter.smarter.SmarterJmolAdapter.close (bufferedReader);
} catch (ex) {
if (Clazz.exceptionOf (ex, Exception)) {
} else {
throw ex;
}
}
bufferedReader = null;
JU.Logger.error ("" + e);
return "" + e;
}
}, "~S,~S,~O,java.util.Map");
Clazz.defineMethod (c$, "getAtomSetCollectionFromReader",
function (fname, reader, htParams) {
var ret = J.adapter.smarter.Resolver.getAtomCollectionReader (fname, null, reader, htParams, -1);
if (Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollectionReader)) {
(ret).setup (fname, htParams, reader);
return (ret).readData ();
}return "" + ret;
}, "~S,~O,java.util.Map");
Clazz.overrideMethod (c$, "getAtomSetCollection",
function (ascReader) {
return J.adapter.smarter.SmarterJmolAdapter.staticGetAtomSetCollection (ascReader);
}, "~O");
c$.staticGetAtomSetCollection = Clazz.defineMethod (c$, "staticGetAtomSetCollection",
function (a) {
var br = null;
try {
br = a.reader;
var ret = a.readData ();
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollection))) return ret;
var asc = ret;
if (asc.errorMessage != null) return asc.errorMessage;
return asc;
} catch (e) {
try {
JU.Logger.info (e.toString ());
} catch (ee) {
if (Clazz.exceptionOf (ee, Exception)) {
JU.Logger.error (e.toString ());
} else {
throw ee;
}
}
try {
br.close ();
} catch (ex) {
if (Clazz.exceptionOf (ex, Exception)) {
} else {
throw ex;
}
}
br = null;
JU.Logger.error ("" + e);
return "" + e;
}
}, "J.adapter.smarter.AtomSetCollectionReader");
Clazz.overrideMethod (c$, "getAtomSetCollectionReaders",
function (filesReader, names, types, htParams, getReadersOnly) {
var vwr = htParams.get ("vwr");
var size = names.length;
var readers = (getReadersOnly ? new Array (size) : null);
var reader = null;
if (htParams.containsKey ("concatenate")) {
var s = "";
for (var i = 0; i < size; i++) {
var f = vwr.getFileAsString3 (names[i], false, null);
if (i > 0 && size <= 3 && f.startsWith ("{")) {
var type = (f.contains ("/outliers/") ? "validation" : "domains");
var x = vwr.evaluateExpressionAsVariable (f);
if (x != null && x.getMap () != null) htParams.put (type, x);
continue;
}if (names[i].indexOf ("/rna3dhub/") >= 0) {
s += "\n_rna3d \n;" + f + "\n;\n";
continue;
}if (names[i].indexOf ("/dssr/") >= 0) {
s += "\n_dssr \n;" + f + "\n;\n";
continue;
}s += f;
if (!s.endsWith ("\n")) s += "\n";
}
size = 1;
reader = JU.Rdr.getBR (s);
}var atomsets = (getReadersOnly ? null : new Array (size));
var r = null;
for (var i = 0; i < size; i++) {
try {
if (r != null) htParams.put ("vwr", vwr);
if (reader == null) reader = filesReader.getBufferedReaderOrBinaryDocument (i, false);
if (!(Clazz.instanceOf (reader, java.io.BufferedReader) || Clazz.instanceOf (reader, javajs.api.GenericBinaryDocument))) return reader;
var ret = J.adapter.smarter.Resolver.getAtomCollectionReader (names[i], (types == null ? null : types[i]), reader, htParams, i);
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollectionReader))) return ret;
r = ret;
r.setup (null, null, null);
if (r.isBinary) {
r.setup (names[i], htParams, filesReader.getBufferedReaderOrBinaryDocument (i, true));
} else {
r.setup (names[i], htParams, reader);
}reader = null;
if (getReadersOnly) {
readers[i] = r;
} else {
ret = r.readData ();
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollection))) return ret;
atomsets[i] = ret;
if (atomsets[i].errorMessage != null) return atomsets[i].errorMessage;
}} catch (e) {
JU.Logger.error ("" + e);
if (!vwr.isJS) e.printStackTrace ();
return "" + e;
}
}
if (getReadersOnly) return readers;
return this.getAtomSetCollectionFromSet (readers, atomsets, htParams);
}, "J.api.JmolFilesReaderInterface,~A,~A,java.util.Map,~B");
Clazz.overrideMethod (c$, "getAtomSetCollectionFromSet",
function (readerSet, atomsets, htParams) {
var readers = readerSet;
var asc = (atomsets == null ? new Array (readers.length) : atomsets);
if (atomsets == null) {
for (var i = 0; i < readers.length; i++) {
try {
var ret = readers[i].readData ();
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollection))) return ret;
asc[i] = ret;
if (asc[i].errorMessage != null) return asc[i].errorMessage;
} catch (e) {
JU.Logger.error ("" + e);
return "" + e;
}
}
}var result;
if (htParams.containsKey ("trajectorySteps")) {
result = asc[0];
try {
result.finalizeTrajectoryAs (htParams.get ("trajectorySteps"), htParams.get ("vibrationSteps"));
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
if (result.errorMessage == null) result.errorMessage = "" + e;
} else {
throw e;
}
}
} else if (asc[0].isTrajectory) {
result = asc[0];
for (var i = 1; i < asc.length; i++) asc[0].mergeTrajectories (asc[i]);
} else {
result = (asc.length == 1 ? asc[0] : new J.adapter.smarter.AtomSetCollection ("Array", null, asc, null));
}return (result.errorMessage == null ? result : result.errorMessage);
}, "~O,~O,java.util.Map");
Clazz.overrideMethod (c$, "getAtomSetCollectionFromDOM",
function (DOMNode, htParams) {
try {
var ret = J.adapter.smarter.Resolver.DOMResolve (DOMNode, htParams);
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollectionReader))) return ret;
var a = ret;
a.setup ("DOM node", htParams, null);
ret = a.readDataObject (DOMNode);
if (!(Clazz.instanceOf (ret, J.adapter.smarter.AtomSetCollection))) return ret;
var asc = ret;
if (asc.errorMessage != null) return asc.errorMessage;
return asc;
} catch (e) {
JU.Logger.error ("" + e);
return "" + e;
}
}, "~O,java.util.Map");
Clazz.overrideMethod (c$, "finish",
function (asc) {
(asc).finish ();
}, "~O");
Clazz.overrideMethod (c$, "getAtomSetCollectionName",
function (asc) {
return (asc).collectionName;
}, "~O");
Clazz.overrideMethod (c$, "getAtomSetCollectionAuxiliaryInfo",
function (asc) {
return (asc).ascAuxiliaryInfo;
}, "~O");
Clazz.overrideMethod (c$, "getAtomSetCount",
function (asc) {
return (asc).atomSetCount;
}, "~O");
Clazz.overrideMethod (c$, "getAtomSetNumber",
function (asc, atomSetIndex) {
return (asc).getAtomSetNumber (atomSetIndex);
}, "~O,~N");
Clazz.overrideMethod (c$, "getAtomSetName",
function (asc, atomSetIndex) {
return (asc).getAtomSetName (atomSetIndex);
}, "~O,~N");
Clazz.overrideMethod (c$, "getAtomSetAuxiliaryInfo",
function (asc, atomSetIndex) {
return (asc).getAtomSetAuxiliaryInfo (atomSetIndex);
}, "~O,~N");
Clazz.overrideMethod (c$, "getHydrogenAtomCount",
function (asc) {
return (asc).getHydrogenAtomCount ();
}, "~O");
Clazz.overrideMethod (c$, "getBondList",
function (asc) {
return (asc).getBondList ();
}, "~O");
Clazz.overrideMethod (c$, "getAtomCount",
function (asc) {
var a = asc;
return (a.bsAtoms == null ? a.ac : a.bsAtoms.cardinality ());
}, "~O");
Clazz.overrideMethod (c$, "coordinatesAreFractional",
function (asc) {
return (asc).coordinatesAreFractional;
}, "~O");
Clazz.overrideMethod (c$, "getAtomIterator",
function (asc) {
return new J.adapter.smarter.AtomIterator (asc);
}, "~O");
Clazz.overrideMethod (c$, "getBondIterator",
function (asc) {
return new J.adapter.smarter.BondIterator (asc);
}, "~O");
Clazz.overrideMethod (c$, "getStructureIterator",
function (asc) {
return (asc).structureCount == 0 ? null : new J.adapter.smarter.StructureIterator (asc);
}, "~O");
c$.close = Clazz.defineMethod (c$, "close",
function (bufferedReader) {
if (Clazz.instanceOf (bufferedReader, java.io.BufferedReader)) (bufferedReader).close ();
else (bufferedReader).close ();
}, "~O");
Clazz.defineStatics (c$,
"PATH_KEY", ".PATH");
c$.PATH_SEPARATOR = c$.prototype.PATH_SEPARATOR = System.getProperty ("path.separator", "/");
});
| gpl-3.0 |
FredericoMFalcao/GroupBettingSystem | _www/phpmyadmin/js/tbl_structure.js | 19866 | /* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* @fileoverview functions used on the table structure page
* @name Table Structure
*
* @requires jQuery
* @requires jQueryUI
* @required js/functions.js
*/
/**
* AJAX scripts for tbl_structure.php
*
* Actions ajaxified here:
* Drop Column
* Add Primary Key
* Drop Primary Key/Index
*
*/
/**
* Reload fields table
*/
function reloadFieldForm () {
$.post($('#fieldsForm').attr('action'), $('#fieldsForm').serialize() + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (form_data) {
var $temp_div = $('<div id=\'temp_div\'><div>').append(form_data.message);
$('#fieldsForm').replaceWith($temp_div.find('#fieldsForm'));
$('#addColumns').replaceWith($temp_div.find('#addColumns'));
$('#move_columns_dialog').find('ul').replaceWith($temp_div.find('#move_columns_dialog ul'));
$('#moveColumns').removeClass('move-active');
});
$('#page_content').show();
}
function checkFirst () {
if ($('select[name=after_field] option:selected').data('pos') === 'first') {
$('input[name=field_where]').val('first');
} else {
$('input[name=field_where]').val('after');
}
}
/**
* Unbind all event handlers before tearing down a page
*/
AJAX.registerTeardown('tbl_structure.js', function () {
$(document).off('click', 'a.drop_column_anchor.ajax');
$(document).off('click', 'a.add_key.ajax');
$(document).off('click', '#move_columns_anchor');
$(document).off('click', '#printView');
$(document).off('submit', '.append_fields_form.ajax');
$('body').off('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]');
$(document).off('click', 'a[name^=partition_action].ajax');
$(document).off('click', '#remove_partitioning.ajax');
});
AJAX.registerOnload('tbl_structure.js', function () {
// Re-initialize variables.
primary_indexes = [];
indexes = [];
fulltext_indexes = [];
spatial_indexes = [];
/**
*Ajax action for submitting the "Column Change" and "Add Column" form
*/
$('.append_fields_form.ajax').off();
$(document).on('submit', '.append_fields_form.ajax', function (event) {
event.preventDefault();
/**
* @var the_form object referring to the export form
*/
var $form = $(this);
var field_cnt = $form.find('input[name=orig_num_fields]').val();
function submitForm () {
$msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
$.post($form.attr('action'), $form.serialize() + PMA_commonParams.get('arg_separator') + 'do_save_data=1', function (data) {
if ($('.sqlqueryresults').length !== 0) {
$('.sqlqueryresults').remove();
} else if ($('.error:not(.tab)').length !== 0) {
$('.error:not(.tab)').remove();
}
if (typeof data.success !== 'undefined' && data.success === true) {
$('#page_content')
.empty()
.append(data.message)
.show();
PMA_highlightSQL($('#page_content'));
$('.result_query .notice').remove();
reloadFieldForm();
$form.remove();
PMA_ajaxRemoveMessage($msg);
PMA_init_slider();
PMA_reloadNavigation();
} else {
PMA_ajaxShowMessage(data.error, false);
}
}); // end $.post()
}
function checkIfConfirmRequired ($form, $field_cnt) {
var i = 0;
var id;
var elm;
var val;
var name_orig;
var elm_orig;
var val_orig;
var checkRequired = false;
for (i = 0; i < field_cnt; i++) {
id = '#field_' + i + '_5';
elm = $(id);
val = elm.val();
name_orig = 'input[name=field_collation_orig\\[' + i + '\\]]';
elm_orig = $form.find(name_orig);
val_orig = elm_orig.val();
if (val && val_orig && val !== val_orig) {
checkRequired = true;
break;
}
}
return checkRequired;
}
/*
* First validate the form; if there is a problem, avoid submitting it
*
* checkTableEditForm() needs a pure element and not a jQuery object,
* this is why we pass $form[0] as a parameter (the jQuery object
* is actually an array of DOM elements)
*/
if (checkTableEditForm($form[0], field_cnt)) {
// OK, form passed validation step
PMA_prepareForAjaxRequest($form);
if (PMA_checkReservedWordColumns($form)) {
// User wants to submit the form
// If Collation is changed, Warn and Confirm
if (checkIfConfirmRequired($form, field_cnt)) {
var question = sprintf(
PMA_messages.strChangeColumnCollation, 'https://wiki.phpmyadmin.net/pma/Garbled_data'
);
$form.PMA_confirm(question, $form.attr('action'), function (url) {
submitForm();
});
} else {
submitForm();
}
}
}
}); // end change table button "do_save_data"
/**
* Attach Event Handler for 'Drop Column'
*/
$(document).on('click', 'a.drop_column_anchor.ajax', function (event) {
event.preventDefault();
/**
* @var curr_table_name String containing the name of the current table
*/
var curr_table_name = $(this).closest('form').find('input[name=table]').val();
/**
* @var curr_row Object reference to the currently selected row (i.e. field in the table)
*/
var $curr_row = $(this).parents('tr');
/**
* @var curr_column_name String containing name of the field referred to by {@link curr_row}
*/
var curr_column_name = $curr_row.children('th').children('label').text().trim();
curr_column_name = escapeHtml(curr_column_name);
/**
* @var $after_field_item Corresponding entry in the 'After' field.
*/
var $after_field_item = $('select[name=\'after_field\'] option[value=\'' + curr_column_name + '\']');
/**
* @var question String containing the question to be asked for confirmation
*/
var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
var $this_anchor = $(this);
$this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
var params = getJSConfirmCommonParam(this, $this_anchor.getPostData());
params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1';
$.post(url, params, function (data) {
if (typeof data !== 'undefined' && data.success === true) {
PMA_ajaxRemoveMessage($msg);
if ($('.result_query').length) {
$('.result_query').remove();
}
if (data.sql_query) {
$('<div class="result_query"></div>')
.html(data.sql_query)
.prependTo('#structure_content');
PMA_highlightSQL($('#page_content'));
}
// Adjust the row numbers
for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
$row.find('td:nth-child(2)').text(new_val);
}
$after_field_item.remove();
$curr_row.hide('medium').remove();
// Remove the dropped column from select menu for 'after field'
$('select[name=after_field]').find(
'[value="' + curr_column_name + '"]'
).remove();
// by default select the (new) last option to add new column
// (in case last column is dropped)
$('select[name=after_field] option:last').attr('selected','selected');
// refresh table stats
if (data.tableStat) {
$('#tablestatistics').html(data.tableStat);
}
// refresh the list of indexes (comes from sql.php)
$('.index_info').replaceWith(data.indexes_list);
PMA_reloadNavigation();
} else {
PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ' : ' + data.error, false);
}
}); // end $.post()
}); // end $.PMA_confirm()
}); // end of Drop Column Anchor action
/**
* Attach Event Handler for 'Print' link
*/
$(document).on('click', '#printView', function (event) {
event.preventDefault();
// Take to preview mode
printPreview();
}); // end of Print View action
/**
* Ajax Event handler for adding keys
*/
$(document).on('click', 'a.add_key.ajax', function (event) {
event.preventDefault();
var $this = $(this);
var curr_table_name = $this.closest('form').find('input[name=table]').val();
var curr_column_name = $this.parents('tr').children('th').children('label').text().trim();
var add_clause = '';
if ($this.is('.add_primary_key_anchor')) {
add_clause = 'ADD PRIMARY KEY';
} else if ($this.is('.add_index_anchor')) {
add_clause = 'ADD INDEX';
} else if ($this.is('.add_unique_anchor')) {
add_clause = 'ADD UNIQUE';
} else if ($this.is('.add_spatial_anchor')) {
add_clause = 'ADD SPATIAL';
} else if ($this.is('.add_fulltext_anchor')) {
add_clause = 'ADD FULLTEXT';
}
var question = PMA_sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' +
escapeHtml(curr_table_name) + '` ' + add_clause + '(`' + escapeHtml(curr_column_name) + '`);');
var $this_anchor = $(this);
$this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
PMA_ajaxShowMessage();
AJAX.source = $this;
var params = getJSConfirmCommonParam(this, $this_anchor.getPostData());
params += PMA_commonParams.get('arg_separator') + 'ajax_page_request=1';
$.post(url, params, AJAX.responseHandler);
}); // end $.PMA_confirm()
}); // end Add key
/**
* Inline move columns
**/
$(document).on('click', '#move_columns_anchor', function (e) {
e.preventDefault();
if ($(this).hasClass('move-active')) {
return;
}
/**
* @var button_options Object that stores the options passed to jQueryUI
* dialog
*/
var button_options = {};
button_options[PMA_messages.strGo] = function (event) {
event.preventDefault();
var $msgbox = PMA_ajaxShowMessage();
var $this = $(this);
var $form = $this.find('form');
var serialized = $form.serialize();
// check if any columns were moved at all
if (serialized === $form.data('serialized-unmoved')) {
PMA_ajaxRemoveMessage($msgbox);
$this.dialog('close');
return;
}
$.post($form.prop('action'), serialized + PMA_commonParams.get('arg_separator') + 'ajax_request=true', function (data) {
if (data.success === false) {
PMA_ajaxRemoveMessage($msgbox);
$this
.clone()
.html(data.error)
.dialog({
title: $(this).prop('title'),
height: 230,
width: 900,
modal: true,
buttons: button_options_error
}); // end dialog options
} else {
// sort the fields table
var $fields_table = $('table#tablestructure tbody');
// remove all existing rows and remember them
var $rows = $fields_table.find('tr').remove();
// loop through the correct order
for (var i in data.columns) {
var the_column = data.columns[i];
var $the_row = $rows
.find('input:checkbox[value=\'' + the_column + '\']')
.closest('tr');
// append the row for this column to the table
$fields_table.append($the_row);
}
var $firstrow = $fields_table.find('tr').eq(0);
// Adjust the row numbers and colors
for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
$row
.find('td:nth-child(2)')
.text($row.index() + 1)
.end()
.removeClass('odd even')
.addClass($row.index() % 2 === 0 ? 'odd' : 'even');
}
PMA_ajaxShowMessage(data.message);
$this.dialog('close');
}
});
};
button_options[PMA_messages.strCancel] = function () {
$(this).dialog('close');
};
var button_options_error = {};
button_options_error[PMA_messages.strOK] = function () {
$(this).dialog('close').remove();
};
var columns = [];
$('#tablestructure').find('tbody tr').each(function () {
var col_name = $(this).find('input:checkbox').eq(0).val();
var hidden_input = $('<input/>')
.prop({
name: 'move_columns[]',
type: 'hidden'
})
.val(col_name);
columns[columns.length] = $('<li/>')
.addClass('placeholderDrag')
.text(col_name)
.append(hidden_input);
});
var col_list = $('#move_columns_dialog').find('ul')
.find('li').remove().end();
for (var i in columns) {
col_list.append(columns[i]);
}
col_list.sortable({
axis: 'y',
containment: $('#move_columns_dialog').find('div'),
tolerance: 'pointer'
}).disableSelection();
var $form = $('#move_columns_dialog').find('form');
$form.data('serialized-unmoved', $form.serialize());
$('#move_columns_dialog').dialog({
modal: true,
buttons: button_options,
open: function () {
if ($('#move_columns_dialog').parents('.ui-dialog').height() > $(window).height()) {
$('#move_columns_dialog').dialog('option', 'height', $(window).height());
}
},
beforeClose: function () {
$('#move_columns_anchor').removeClass('move-active');
}
});
});
/**
* Handles multi submits in table structure page such as change, browse, drop, primary etc.
*/
$('body').on('click', '#fieldsForm.ajax button[name="submit_mult"], #fieldsForm.ajax input[name="submit_mult"]', function (e) {
e.preventDefault();
var $button = $(this);
var $form = $button.parents('form');
var argsep = PMA_commonParams.get('arg_separator');
var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
PMA_ajaxShowMessage();
AJAX.source = $form;
$.post($form.attr('action'), submitData, AJAX.responseHandler);
});
/**
* Handles clicks on Action links in partition table
*/
$(document).on('click', 'a[name^=partition_action].ajax', function (e) {
e.preventDefault();
var $link = $(this);
function submitPartitionAction (url) {
var params = {
'ajax_request' : true,
'ajax_page_request' : true
};
PMA_ajaxShowMessage();
AJAX.source = $link;
$.post(url, params, AJAX.responseHandler);
}
if ($link.is('#partition_action_DROP')) {
var question = PMA_messages.strDropPartitionWarning;
$link.PMA_confirm(question, $link.attr('href'), function (url) {
submitPartitionAction(url);
});
} else if ($link.is('#partition_action_TRUNCATE')) {
var question = PMA_messages.strTruncatePartitionWarning;
$link.PMA_confirm(question, $link.attr('href'), function (url) {
submitPartitionAction(url);
});
} else {
submitPartitionAction($link.attr('href'));
}
});
/**
* Handles remove partitioning
*/
$(document).on('click', '#remove_partitioning.ajax', function (e) {
e.preventDefault();
var $link = $(this);
var question = PMA_messages.strRemovePartitioningWarning;
$link.PMA_confirm(question, $link.attr('href'), function (url) {
var params = {
'ajax_request' : true,
'ajax_page_request' : true
};
PMA_ajaxShowMessage();
AJAX.source = $link;
$.post(url, params, AJAX.responseHandler);
});
});
$(document).on('change', 'select[name=after_field]', function () {
checkFirst();
});
});
/** Handler for "More" dropdown in structure table rows */
AJAX.registerOnload('tbl_structure.js', function () {
var windowwidth = $(window).width();
if (windowwidth > 768) {
if (! $('#fieldsForm').hasClass('HideStructureActions')) {
$('.table-structure-actions').width(function () {
var width = 5;
$(this).find('li').each(function () {
width += $(this).outerWidth(true);
});
return width;
});
}
}
$('.jsresponsive').css('max-width', (windowwidth - 35) + 'px');
var tableRows = $('.central_columns');
$.each(tableRows, function (index, item) {
if ($(item).hasClass('add_button')) {
$(item).click(function () {
$('input:checkbox').prop('checked', false);
$('#checkbox_row_' + (index + 1)).prop('checked', true);
$('button[value=add_to_central_columns]').click();
});
} else {
$(item).click(function () {
$('input:checkbox').prop('checked', false);
$('#checkbox_row_' + (index + 1)).prop('checked', true);
$('button[value=remove_from_central_columns]').click();
});
}
});
});
| gpl-3.0 |
dLobatog/smart-proxy | test/dns_libvirt/dns_libvirt_provider_test.rb | 1900 | require 'test_helper'
require 'dns_libvirt/plugin_configuration'
require 'dns_libvirt/dns_libvirt_plugin'
require 'dns_libvirt/dns_libvirt_main'
class DnsLibvirtProviderTest < Test::Unit::TestCase
def setup
fixture = <<XMLFIXTURE
<network>
<name>default</name>
<domain name='local.lan'/>
<dns>
<host ip='192.168.122.1'>
<hostname>some.example.com</hostname>
</host>
</dns>
<ip address='192.168.122.0' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.1' end='192.168.122.250'/>
<host mac='52:54:00:e2:62:08' name='some.example.com' ip='192.168.122.1'/>
</dhcp>
</ip>
</network>
XMLFIXTURE
@libvirt_network = mock()
@libvirt_network.stubs(:dump_xml).returns(fixture)
@subject = Proxy::Dns::Libvirt::Record.new('default', @libvirt_network)
end
def test_add_a_record
fqdn = "abc.example.com"
ip = "192.168.122.2"
@subject.libvirt_network.expects(:add_dns_a_record).with(fqdn, ip)
@subject.create_a_record(fqdn, ip)
end
def test_del_a_record
fqdn = "abc.example.com"
ip = "192.168.122.2"
@subject.expects(:find_ip_for_host).with(fqdn).returns(ip)
@subject.libvirt_network.expects(:del_dns_a_record).with(fqdn, ip)
@subject.remove_a_record(fqdn)
end
def test_add_aaaa_record
fqdn = "abc6.example.com"
ip = "2001:db8:85a3:0:0:8a2e:370:7334"
@subject.libvirt_network.expects(:add_dns_a_record).with(fqdn, ip)
@subject.create_a_record(fqdn, ip)
end
def test_del_aaaa_record
fqdn = "abc6.example.com"
ip = "2001:db8:85a3:0:0:8a2e:370:7334"
@subject.expects(:find_ip_for_host).with(fqdn).returns(ip)
@subject.libvirt_network.expects(:del_dns_a_record).with(fqdn, ip)
@subject.remove_a_record(fqdn)
end
def test_del_a_record_failure
assert_raise Proxy::Dns::NotFound do
@subject.remove_a_record('does_not_exist')
end
end
end
| gpl-3.0 |
obiba/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/ace/client/js/noconflict/mode-scad.js | 26875 | /*
* Copyright (c) 2017 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
ace.define('ace/mode/scad', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/scad_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function (require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var scadHighlightRules = require("./scad_highlight_rules").scadHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function () {
this.$tokenizer = new Tokenizer(new scadHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function () {
this.toggleCommentLines = function (state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)\/\//;
for (var i = startRow; i <= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i = startRow; i <= endRow; i++) {
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "//");
}
};
this.getNextLineIndent = function (state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length - 1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function (state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function (state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define('ace/mode/scad_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function (require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var scadHighlightRules = function () {
var keywordMapper = this.createKeywordMapper({
"variable.language": "this",
"keyword": "module|if|else|for",
"constant.language": "NULL"
}, "identifier");
this.$rules = {
"start": [
{
token: "comment",
regex: "\\/\\/.*$"
},
DocCommentHighlightRules.getStartRule("start"),
{
token: "comment", // multi line comment
regex: "\\/\\*",
next: "comment"
},
{
token: "string", // single line
regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
},
{
token: "string", // multi line string start
regex: '["].*\\\\$',
next: "qqstring"
},
{
token: "string", // single line
regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
},
{
token: "string", // multi line string start
regex: "['].*\\\\$",
next: "qstring"
},
{
token: "constant.numeric", // hex
regex: "0[xX][0-9a-fA-F]+\\b"
},
{
token: "constant.numeric", // float
regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
},
{
token: "constant", // <CONSTANT>
regex: "<[a-zA-Z0-9.]+>"
},
{
token: "keyword", // pre-compiler directivs
regex: "(?:use|include)"
},
{
token: keywordMapper,
regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
},
{
token: "keyword.operator",
regex: "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"
},
{
token: "paren.lparen",
regex: "[[({]"
},
{
token: "paren.rparen",
regex: "[\\])}]"
},
{
token: "text",
regex: "\\s+"
}
],
"comment": [
{
token: "comment", // closing comment
regex: ".*?\\*\\/",
next: "start"
},
{
token: "comment", // comment spanning whole line
regex: ".+"
}
],
"qqstring": [
{
token: "string",
regex: '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next: "start"
},
{
token: "string",
regex: '.+'
}
],
"qstring": [
{
token: "string",
regex: "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next: "start"
},
{
token: "string",
regex: '.+'
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(scadHighlightRules, TextHighlightRules);
exports.scadHighlightRules = scadHighlightRules;
});
ace.define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function (require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function () {
this.$rules = {
"start": [
{
token: "comment.doc.tag",
regex: "@[\\w\\d_]+" // TODO: fix email addresses
},
{
token: "comment.doc.tag",
regex: "\\bTODO\\b"
},
{
defaultToken: "comment.doc"
}
]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function (start) {
return {
token: "comment.doc", // doc comment
regex: "\\/\\*(?=\\*)",
next: start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token: "comment.doc", // closing comment
regex: "\\*\\/",
next: start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function (require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function () {
};
(function () {
this.checkOutdent = function (line, input) {
if (!/^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function (doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column - 1), indent);
};
this.$getIndent = function (line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function (require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var autoInsertedBrackets = 0;
var autoInsertedRow = -1;
var autoInsertedLineEnd = "";
var maybeInsertedBrackets = 0;
var maybeInsertedRow = -1;
var maybeInsertedLineStart = "";
var maybeInsertedLineEnd = "";
var CstyleBehaviour = function () {
CstyleBehaviour.isSaneInsertion = function (editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function (token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function (editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
autoInsertedBrackets = 0;
autoInsertedRow = cursor.row;
autoInsertedLineEnd = bracket + line.substr(cursor.column);
autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function (editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
maybeInsertedBrackets = 0;
maybeInsertedRow = cursor.row;
maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
maybeInsertedLineEnd = line.substr(cursor.column);
maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function (cursor, line, bracket) {
return autoInsertedBrackets > 0 &&
cursor.row === autoInsertedRow &&
bracket === autoInsertedLineEnd[0] &&
line.substr(cursor.column) === autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function (cursor, line) {
return maybeInsertedBrackets > 0 &&
cursor.row === maybeInsertedRow &&
line.substr(cursor.column) === maybeInsertedLineEnd &&
line.substr(0, cursor.column) == maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function () {
autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function () {
maybeInsertedBrackets = 0;
maybeInsertedRow = -1;
};
this.add("braces", "insertion", function (state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column])) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}' || closing !== "") {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
var next_indent = this.$getIndent(line);
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '[') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column - 1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length + col - 1) && token.value.lastIndexOf(quote) === token.value.length - 1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1, 1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function (require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function () {
};
oop.inherits(FoldMode, BaseFoldMode);
(function () {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function (session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i + match[0].length, 1);
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
}).call(FoldMode.prototype);
});
| gpl-3.0 |
Hernanarce/pelisalacarta | python/main-classic/servers/copiapop.py | 2803 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para copiapop
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
from core import config
from core import httptools
from core import jsontools
from core import logger
from core import scrapertools
def test_video_exists(page_url):
logger.info("(page_url='%s')" % page_url)
if "copiapop.com" in page_url:
from channels import copiapop
logueado, error_message = copiapop.login("copiapop.com")
if not logueado:
return False, error_message
data = httptools.downloadpage(page_url).data
if ("File was deleted" or "Not Found" or "File was locked by administrator") in data:
return False, "[Copiapop] El archivo no existe o ha sido borrado"
return True, ""
def get_video_url(page_url, premium=False, user="", password="", video_password=""):
logger.info("(page_url='%s')" % page_url)
video_urls = []
data = httptools.downloadpage(page_url).data
host = "http://copiapop.com"
host_string = "copiapop"
if "diskokosmiko.mx" in page_url:
host = "http://diskokosmiko.mx"
host_string = "diskokosmiko"
url = scrapertools.find_single_match(data, '<form action="([^"]+)" class="download_form"')
if url:
url = host + url
fileid = url.rsplit("f=", 1)[1]
token = scrapertools.find_single_match(data, '<div class="download_container">.*?name="__RequestVerificationToken".*?value="([^"]+)"')
post = "fileId=%s&__RequestVerificationToken=%s" % (fileid, token)
headers = {'X-Requested-With': 'XMLHttpRequest'}
data = httptools.downloadpage(url, post, headers).data
data = jsontools.load_json(data)
mediaurl = data.get("DownloadUrl")
extension = data.get("Extension")
video_urls.append([".%s [%s]" % (extension, host_string), mediaurl])
for video_url in video_urls:
logger.info(" %s - %s" % (video_url[0], video_url[1]))
return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
encontrados = set()
devuelve = []
patronvideos = '(copiapop.com|diskokosmiko.mx)/(.*?)[\s\'"]*$'
logger.info("#" + patronvideos + "#")
matches = re.compile(patronvideos, re.DOTALL).findall(data)
for host, match in matches:
titulo = "[copiapop]"
url = "http://%s/%s" % (host, match)
if url not in encontrados:
logger.info(" url=" + url)
devuelve.append([titulo, url, 'copiapop'])
encontrados.add(url)
else:
logger.info(" url duplicada=" + url)
return devuelve
| gpl-3.0 |
goodagood/testexp | cooka/tmp/inherits-b.js | 500 | var EventEmitter = require('events').EventEmitter;
var util = require('util');
// Define the constructor for your derived "class"
function Master(arg1, arg2) {
// call the super constructor to initialize `this`
EventEmitter.call(this);
// your own initialization of `this` follows here
};
// Declare that your class should use EventEmitter as its prototype.
// This is roughly equivalent to: Master.prototype = Object.create(EventEmitter.prototype)
util.inherits(Master, EventEmitter);
| gpl-3.0 |
MyEmbeddedWork/ARM_CORTEX_M3-STM32 | 1. Docs/Doxygen/html/struct_c_a_n___f_i_f_o_mail_box___type_def.js | 479 | var struct_c_a_n___f_i_f_o_mail_box___type_def =
[
[ "RDHR", "struct_c_a_n___f_i_f_o_mail_box___type_def.html#a95890984bd67845015d40e82fb091c93", null ],
[ "RDLR", "struct_c_a_n___f_i_f_o_mail_box___type_def.html#ac7d62861de29d0b4fcf11fabbdbd76e7", null ],
[ "RDTR", "struct_c_a_n___f_i_f_o_mail_box___type_def.html#a49d74ca8b402c2b9596bfcbe4cd051a9", null ],
[ "RIR", "struct_c_a_n___f_i_f_o_mail_box___type_def.html#a034504d43f7b16b320745a25b3a8f12d", null ]
]; | gpl-3.0 |
SKuipers/core | modules/Rubrics/src/Visualise.php | 6077 | <?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\Module\Rubrics;
use Gibbon\UI\Chart\Chart;
/**
* Attendance display & edit class
*
* @version v18
* @since v18
*/
class Visualise
{
protected $absoluteURL;
protected $page;
protected $guid;
protected $gibbonPersonID;
protected $columns;
protected $rows;
protected $cells;
protected $contexts;
/**
* Constructor
*
* @version v18
* @since v18
* @return void
*/
public function __construct($absoluteURL, $page, $gibbonPersonID, array $columns, array $rows, array $cells, array $contexts)
{
$this->absoluteURL = $absoluteURL;
$this->page = $page;
$this->gibbonPersonID = $gibbonPersonID;
$this->columns = $columns;
$this->rows = $rows;
$this->cells = $cells;
$this->contexts = $contexts;
}
/**
* renderVisualise
*
* @version v18
* @since v18
* @param $legend should the legend be included?
* @param $image should the chart be saved as an image
* @param $path if image is saved, where should it be saved (defaults to standard upload location)
* @param $id optionally outputs the image path to the value of the given id
* @return void
*/
public function renderVisualise($legend = true, $image = false, $path = '', $id = '')
{
//Filter out columns to ignore from visualisation
$this->columns = array_filter($this->columns, function ($item) {
return (isset($item['visualise']) && $item['visualise'] == 'Y');
});
if (!empty($this->columns) && !empty($this->cells)) {
//Cycle through rows to calculate means
$means = array() ;
foreach ($this->rows as $row) {
$means[$row['gibbonRubricRowID']]['title'] = $row['title'];
$means[$row['gibbonRubricRowID']]['cumulative'] = 0;
$means[$row['gibbonRubricRowID']]['denonimator'] = 0;
//Cycle through cells, and grab those for this row
$cellCount = 1 ;
foreach ($this->cells[$row['gibbonRubricRowID']] as $cell) {
$visualise = false ;
foreach ($this->columns as $column) {
if ($column['gibbonRubricColumnID'] == $cell['gibbonRubricColumnID']) {
$visualise = true ;
}
}
if ($visualise) {
foreach ($this->contexts as $entry) {
if ($entry['gibbonRubricCellID'] == $cell['gibbonRubricCellID']) {
$means[$row['gibbonRubricRowID']]['cumulative'] += $cellCount;
$means[$row['gibbonRubricRowID']]['denonimator']++;
}
}
$cellCount++;
}
}
}
$columnCount = count($this->columns);
$data = array_map(function ($mean) use ($columnCount) {
return !empty($mean['denonimator'])
? round((($mean['cumulative']/$mean['denonimator'])/$columnCount), 2)
: 0;
}, $means);
$this->page->scripts->add('chart');
$chart = Chart::create('visualisation'.$this->gibbonPersonID, 'polarArea')
->setLegend(['display' => $legend, 'position' => 'right'])
->setLabels(array_column($means, 'title'))
->setColorOpacity(0.6);
$options = [
'responsive' => 'true',
'maintainAspectRatio' => 'true',
'aspectRatio' => 2,
'height' => '32vw',
'scale' => [
'min' => 0.0,
'max' => 1.0,
'ticks' => [
'callback' => $chart->addFunction('function(tickValue, index, ticks) {
return Number(tickValue).toFixed(1);
}'),
],
]
];
if ($image) {
$options['animation'] = [
'duration' => 0,
'onComplete' => $chart->addFunction('function(e) {
var img = visualisation'.$this->gibbonPersonID.'.toDataURL("image/png");
$.ajax({ url: "'.$this->absoluteURL.'/modules/Rubrics/src/visualise_saveAjax.php", type: "POST", data: {img: img, gibbonPersonID: \''.$this->gibbonPersonID.'\', path: \''.$path.'\'}, dataType: "html", success: function (data) {
'.( $id ? '$("#'.$id.'").val(data);' : '' ).'
} });
this.options.animation.onComplete = null;
}'),
];
}
$chart->setOptions($options);
// Handle custom colours only if there is one unique colour per row
$rowColours = array_unique(array_column($this->rows, 'backgroundColor'));
if (count($rowColours) == count($this->rows)) {
$chart->setColors($rowColours);
}
$chart->addDataset('rubric')->setData($data);
return $chart->render();
}
}
}
| gpl-3.0 |
legislated/legislated-api | app/services/ilga/scrape_hearings.rb | 2717 | module Ilga
class ScrapeHearings
include Scraper
Hearing = Struct.new(
:ilga_id,
:url
)
def call(chamber)
info("> #{task_name}: start")
info(" - chamber: #{chamber}")
result = scrape_hearings(chamber)
info("\n> #{task_name}: finished")
result
end
private
def scrape_hearings(chamber)
info("\n> #{task_name}: visit chamber root")
url = chamber_url(chamber)
page.visit(url)
# click the month tab to view all the upcoming hearings
month_tab = page.first('#CommitteeHearingTabstrip li a', text: 'Month')
raise Error, "#{task_name}: couldn't find month 'tab'" if month_tab.blank?
month_tab.click
scrape_paged_hearings(chamber, url)
end
def scrape_paged_hearings(chamber, url, page_number = 0)
return [] if url.nil?
info("\n> #{task_name}: visit paged committee hearings")
info(" - name: #{chamber}")
info(" - page: #{page_number}")
# visit page if necessary and wait for it to load
page.visit(url) if page_number != 0
wait_for_ajax
return [] if page.has_css?('.t-no-data')
# get hearings from each row
rows = page
.find_all('#CommitteeHearingTabstrip tbody tr')
debug(" - hearing rows: #{rows.count}")
hearings = rows
.map { |row| build_hearing(row) }
.compact
info(" - hearings: #{hearings.count}")
# aggregate the next page's results if it's available
next_url = find_next_page_url
info(" - next?: #{!next_url.nil?}")
hearings + scrape_paged_hearings(chamber, next_url, page_number + 1)
end
def build_hearing(row)
link = row.first('td.t-last a')
url = link&.[](:href)
uri = clean_url(url)
if uri.nil?
debug(" - hearing w/o url, link: #{link}")
return nil
end
Hearing.new(
uri.path.split('/').last.to_i, # ilga_id
uri.to_s
)
end
# find the next page link by searching for its icon
def find_next_page_url
link = page.first(:xpath, "//*[@class='t-arrow-next']/..")
return nil if link.nil? || link[:class].include?('t-state-disabled')
link[:href]
end
def clean_url(url)
return nil if url.nil?
uri = URI.parse(url)
uri.query = URI.encode_www_form(CGI.parse(uri.query).without('_'))
uri
end
def chamber_url(chamber)
case chamber
when Chamber::LOWER
'http://my.ilga.gov/Hearing/AllHearings?chamber=H'
when Chamber::UPPER
'http://my.ilga.gov/Hearing/AllHearings?chamber=S'
else
raise "Unknown chamber kind: #{kind}"
end
end
end
end
| gpl-3.0 |
MultiverseKing/MultiverseKing_JME | MultiverseKingGame/src/org/multiverseking/game/gui/control/CameraTrackWindow.java | 3092 | package org.multiverseking.game.gui.control;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import org.hexgridapi.core.coordinate.HexCoordinate;
import tonegod.gui.controls.menuing.Menu;
import tonegod.gui.core.Element;
import tonegod.gui.core.ElementManager;
/**
*
* @author roah
*/
public abstract class CameraTrackWindow {
protected final ElementManager screen;
protected final Camera camera;
protected Vector2f offset;
protected HexCoordinate inspectedPosition;
protected int inspectedSpatialHeight = Integer.MIN_VALUE;
protected Element screenElement;
public CameraTrackWindow(ElementManager screen, Camera camera) {
this(screen, camera, new Vector2f());
}
public CameraTrackWindow(ElementManager screen, Camera camera, Vector2f offset) {
this.screen = screen;
this.camera = camera;
this.offset = offset;
}
public void update(float tpf) {
if (screen.getElementById(screenElement.getUID()) != null && screenElement.getIsVisible()) {
Vector3f value = camera.getScreenCoordinates(inspectedSpatialHeight == Integer.MIN_VALUE ? inspectedPosition.toWorldPosition(): inspectedPosition.toWorldPosition(inspectedSpatialHeight));
if (value.x > 0 && value.x < screen.getWidth() * 0.9f
&& value.y > 0 && value.y < screen.getHeight() * 0.9f) {
screenElement.setPosition(new Vector2f(value.x + offset.x, value.y + offset.y));
} else {
hide();
}
}
}
public void show(HexCoordinate pos) {
if (screen.getElementById(screenElement.getUID()) == null) {
screen.addElement(screenElement);
}
inspectedPosition = pos;
Vector3f value = camera.getScreenCoordinates(inspectedSpatialHeight == Integer.MIN_VALUE ? pos.toWorldPosition(): pos.toWorldPosition(inspectedSpatialHeight));
if (screenElement instanceof Menu) {
((Menu) screenElement).showMenu(null, value.x, value.y);
} else {
screenElement.setPosition(value.x, value.y);
screenElement.show();
}
}
public void show(HexCoordinate pos, int height) {
inspectedSpatialHeight = height;
show(pos);
}
public boolean isVisible() {
return screenElement.getIsVisible();
}
public void hide() {
if (screenElement instanceof Menu) {
((Menu) screenElement).hideMenu();
} else {
screenElement.hide();
}
}
public void removeFromScreen() {
if (screenElement.getElementParent() != null) {
screenElement.getElementParent().removeChild(screenElement);
} else {
screen.removeElement(screenElement);
}
}
public String getUID() {
return screenElement.getUID();
}
public Element getScreenElement() {
return screenElement;
}
public HexCoordinate getInspectedSpatialPosition() {
return inspectedPosition;
}
}
| gpl-3.0 |
oikarinen/plugin.audio.spotlight | spotlight/service/session/PlaylistCallbacks.py | 1519 | #
# Copyright (c) Dariusz Biskup
#
# This file is part of Spotlight
#
# Spotlight 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.
#
# Spotlight 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/>
#
from spotify.playlistcontainer import PlaylistContainerCallbacks
class PlaylistCallbacks(PlaylistContainerCallbacks):
def __init__(self, cache_storage):
self.cache_storage = cache_storage
def playlist_added(self, container, playlist, position):
print 'Invalidating cache.'
self.cache_storage.invalidate_all()
def playlist_removed(self, container, playlist, position):
print 'Invalidating cache.'
self.cache_storage.invalidate_all()
def playlist_moved(self, container, playlist, position, new_position):
print 'Invalidating cache.'
self.cache_storage.invalidate_all()
def container_loaded(self, container):
print 'Invalidating cache.'
self.cache_storage.invalidate_all()
| gpl-3.0 |
OpenCFD/OpenFOAM-1.7.x | src/OpenFOAM/fields/DimensionedFields/DimensionedField/DimensionedFieldI.H | 2387 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Type, class GeoMesh>
inline const DimensionedField<Type, GeoMesh>&
DimensionedField<Type, GeoMesh>::null()
{
return *reinterpret_cast< DimensionedField<Type, GeoMesh>* >(0);
}
template<class Type, class GeoMesh>
inline const typename GeoMesh::Mesh&
DimensionedField<Type, GeoMesh>::mesh() const
{
return mesh_;
}
template<class Type, class GeoMesh>
inline const dimensionSet& DimensionedField<Type, GeoMesh>::dimensions() const
{
return dimensions_;
}
template<class Type, class GeoMesh>
inline dimensionSet& DimensionedField<Type, GeoMesh>::dimensions()
{
return dimensions_;
}
template<class Type, class GeoMesh>
inline const Field<Type>& DimensionedField<Type, GeoMesh>::field() const
{
return *this;
}
template<class Type, class GeoMesh>
inline Field<Type>& DimensionedField<Type, GeoMesh>::field()
{
return *this;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
ner01/MobileAppTest | Groceries/platforms/android/src/main/assets/app/tns_modules/tns-core-modules/ui/segmented-bar/segmented-bar.js | 10065 | function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var font_1 = require("../styling/font");
var segmented_bar_common_1 = require("./segmented-bar-common");
__export(require("./segmented-bar-common"));
var R_ID_TABS = 0x01020013;
var R_ID_TABCONTENT = 0x01020011;
var R_ATTR_STATE_SELECTED = 0x010100a1;
var TITLE_TEXT_VIEW_ID = 16908310;
var apiLevel;
var selectedIndicatorThickness;
var TabHost;
var TabChangeListener;
var TabContentFactory;
function initializeNativeClasses() {
if (TabChangeListener) {
return;
}
apiLevel = android.os.Build.VERSION.SDK_INT;
selectedIndicatorThickness = segmented_bar_common_1.layout.toDevicePixels(apiLevel >= 21 ? 2 : 5);
var TabChangeListenerImpl = (function (_super) {
__extends(TabChangeListenerImpl, _super);
function TabChangeListenerImpl(owner) {
var _this = _super.call(this) || this;
_this.owner = owner;
return global.__native(_this);
}
TabChangeListenerImpl.prototype.onTabChanged = function (id) {
var owner = this.owner;
if (owner.shouldChangeSelectedIndex()) {
owner.selectedIndex = parseInt(id);
}
};
return TabChangeListenerImpl;
}(java.lang.Object));
TabChangeListenerImpl = __decorate([
Interfaces([android.widget.TabHost.OnTabChangeListener])
], TabChangeListenerImpl);
var TabContentFactoryImpl = (function (_super) {
__extends(TabContentFactoryImpl, _super);
function TabContentFactoryImpl(owner) {
var _this = _super.call(this) || this;
_this.owner = owner;
return global.__native(_this);
}
TabContentFactoryImpl.prototype.createTabContent = function (tag) {
var tv = new android.widget.TextView(this.owner._context);
tv.setVisibility(android.view.View.GONE);
tv.setMaxLines(1);
tv.setEllipsize(android.text.TextUtils.TruncateAt.END);
return tv;
};
return TabContentFactoryImpl;
}(java.lang.Object));
TabContentFactoryImpl = __decorate([
Interfaces([android.widget.TabHost.TabContentFactory])
], TabContentFactoryImpl);
var TabHostImpl = (function (_super) {
__extends(TabHostImpl, _super);
function TabHostImpl(context, attrs) {
var _this = _super.call(this, context, attrs) || this;
return global.__native(_this);
}
TabHostImpl.prototype.onAttachedToWindow = function () {
};
return TabHostImpl;
}(android.widget.TabHost));
TabHost = TabHostImpl;
TabChangeListener = TabChangeListenerImpl;
TabContentFactory = TabContentFactoryImpl;
}
var SegmentedBarItem = (function (_super) {
__extends(SegmentedBarItem, _super);
function SegmentedBarItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
SegmentedBarItem.prototype.createNativeView = function () {
return this.nativeView;
};
SegmentedBarItem.prototype.setupNativeView = function (tabIndex) {
var titleTextView = this.parent.nativeView.getTabWidget().getChildAt(tabIndex).findViewById(TITLE_TEXT_VIEW_ID);
this.nativeView = titleTextView;
if (titleTextView) {
segmented_bar_common_1.initNativeView(this);
if (this.titleDirty) {
this._update();
}
}
};
SegmentedBarItem.prototype._update = function () {
var tv = this.nativeView;
if (tv) {
var title = this.title;
title = (title === null || title === undefined) ? "" : title;
tv.setText(title);
this.titleDirty = false;
}
else {
this.titleDirty = true;
}
};
SegmentedBarItem.prototype[segmented_bar_common_1.colorProperty.getDefault] = function () {
return this.nativeView.getCurrentTextColor();
};
SegmentedBarItem.prototype[segmented_bar_common_1.colorProperty.setNative] = function (value) {
var color = value instanceof segmented_bar_common_1.Color ? value.android : value;
this.nativeView.setTextColor(color);
};
SegmentedBarItem.prototype[segmented_bar_common_1.fontSizeProperty.getDefault] = function () {
return { nativeSize: this.nativeView.getTextSize() };
};
SegmentedBarItem.prototype[segmented_bar_common_1.fontSizeProperty.setNative] = function (value) {
if (typeof value === "number") {
this.nativeView.setTextSize(value);
}
else {
this.nativeView.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, value.nativeSize);
}
};
SegmentedBarItem.prototype[segmented_bar_common_1.fontInternalProperty.getDefault] = function () {
return this.nativeView.getTypeface();
};
SegmentedBarItem.prototype[segmented_bar_common_1.fontInternalProperty.setNative] = function (value) {
this.nativeView.setTypeface(value instanceof font_1.Font ? value.getAndroidTypeface() : value);
};
SegmentedBarItem.prototype[segmented_bar_common_1.selectedBackgroundColorProperty.getDefault] = function () {
var viewGroup = this.nativeView.getParent();
return viewGroup.getBackground().getConstantState();
};
SegmentedBarItem.prototype[segmented_bar_common_1.selectedBackgroundColorProperty.setNative] = function (value) {
var viewGroup = this.nativeView.getParent();
if (value instanceof segmented_bar_common_1.Color) {
var color = value.android;
var backgroundDrawable = viewGroup.getBackground();
if (apiLevel > 21 && backgroundDrawable && typeof backgroundDrawable.setColorFilter === "function") {
var newDrawable = backgroundDrawable.getConstantState().newDrawable();
newDrawable.setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_IN);
org.nativescript.widgets.ViewHelper.setBackground(viewGroup, newDrawable);
}
else {
var stateDrawable = new android.graphics.drawable.StateListDrawable();
var colorDrawable = new org.nativescript.widgets.SegmentedBarColorDrawable(color, selectedIndicatorThickness);
var arr = Array.create("int", 1);
arr[0] = R_ATTR_STATE_SELECTED;
stateDrawable.addState(arr, colorDrawable);
stateDrawable.setBounds(0, 15, viewGroup.getRight(), viewGroup.getBottom());
org.nativescript.widgets.ViewHelper.setBackground(viewGroup, stateDrawable);
}
}
else {
org.nativescript.widgets.ViewHelper.setBackground(viewGroup, value.newDrawable());
}
};
return SegmentedBarItem;
}(segmented_bar_common_1.SegmentedBarItemBase));
exports.SegmentedBarItem = SegmentedBarItem;
var SegmentedBar = (function (_super) {
__extends(SegmentedBar, _super);
function SegmentedBar() {
return _super !== null && _super.apply(this, arguments) || this;
}
SegmentedBar.prototype.shouldChangeSelectedIndex = function () {
return !this._addingTab;
};
SegmentedBar.prototype.createNativeView = function () {
initializeNativeClasses();
var context = this._context;
var nativeView = new TabHost(context, null);
var tabHostLayout = new android.widget.LinearLayout(context);
tabHostLayout.setOrientation(android.widget.LinearLayout.VERTICAL);
var tabWidget = new android.widget.TabWidget(context);
tabWidget.setId(R_ID_TABS);
tabHostLayout.addView(tabWidget);
var frame = new android.widget.FrameLayout(context);
frame.setId(R_ID_TABCONTENT);
frame.setVisibility(android.view.View.GONE);
tabHostLayout.addView(frame);
nativeView.addView(tabHostLayout);
var listener = new TabChangeListener(this);
nativeView.setOnTabChangedListener(listener);
nativeView.listener = listener;
nativeView.setup();
return nativeView;
};
SegmentedBar.prototype.initNativeView = function () {
_super.prototype.initNativeView.call(this);
var nativeView = this.nativeView;
nativeView.listener.owner = this;
this._tabContentFactory = this._tabContentFactory || new TabContentFactory(this);
};
SegmentedBar.prototype.disposeNativeView = function () {
var nativeView = this.nativeView;
nativeView.listener.owner = null;
_super.prototype.disposeNativeView.call(this);
};
SegmentedBar.prototype.insertTab = function (tabItem, index) {
var tabHost = this.nativeView;
var tab = tabHost.newTabSpec(index + "");
tab.setIndicator(tabItem.title + "");
tab.setContent(this._tabContentFactory);
this._addingTab = true;
tabHost.addTab(tab);
tabItem.setupNativeView(index);
this._addingTab = false;
};
SegmentedBar.prototype[segmented_bar_common_1.selectedIndexProperty.getDefault] = function () {
return -1;
};
SegmentedBar.prototype[segmented_bar_common_1.selectedIndexProperty.setNative] = function (value) {
this.nativeView.setCurrentTab(value);
};
SegmentedBar.prototype[segmented_bar_common_1.itemsProperty.getDefault] = function () {
return null;
};
SegmentedBar.prototype[segmented_bar_common_1.itemsProperty.setNative] = function (value) {
var _this = this;
this.nativeView.clearAllTabs();
var newItems = value;
if (newItems) {
newItems.forEach(function (item, i, arr) { return _this.insertTab(item, i); });
}
segmented_bar_common_1.selectedIndexProperty.coerce(this);
};
return SegmentedBar;
}(segmented_bar_common_1.SegmentedBarBase));
exports.SegmentedBar = SegmentedBar;
//# sourceMappingURL=segmented-bar.js.map | gpl-3.0 |
clynrey/android-soap-enabler | library/src/test/java/org/asoape/sample/ContactEmail.java | 1296 | /**
* Android SOAP Enabler is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* Android SOAP Enabler 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 Lesser GNU General Public License
* along with Android SOAP Enabler. If not, see <http://www.gnu.org/licenses/>.
*
* ©2011, Android SOAP Enabler Development Team
*/
package org.asoape.sample;
import fr.norsys.asoape.xml.binding.annotation.XmlElement;
import fr.norsys.asoape.xml.binding.annotation.XmlElement.Cardinality;
import fr.norsys.asoape.xml.binding.annotation.XmlType;
@XmlType( propOrder = "email" )
public class ContactEmail
extends ContactInfo
{
@XmlElement( name = "email", targetType = String.class, cardinality = Cardinality.ONE )
private String email;
public String getEmail()
{
return email;
}
public void setEmail( String email )
{
this.email = email;
}
}
| gpl-3.0 |
xrunuo/xrunuo | Scripts/Distro/Engines/Reports/Persistance/PersistableObjectCollection.cs | 6261 | //------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace Server.Engines.Reports
{
using System;
using System.Collections;
/// <summary>
/// Strongly typed collection of Server.Engines.Reports.PersistableObject.
/// </summary>
public class ObjectCollection : System.Collections.CollectionBase
{
/// <summary>
/// Default constructor.
/// </summary>
public ObjectCollection()
: base()
{
}
/// <summary>
/// Gets or sets the value of the Server.Engines.Reports.PersistableObject at a specific position in the ObjectCollection.
/// </summary>
public Server.Engines.Reports.PersistableObject this[int index] { get { return ( (Server.Engines.Reports.PersistableObject) ( this.List[index] ) ); } set { this.List[index] = value; } }
/// <summary>
/// Append a Server.Engines.Reports.PersistableObject entry to this collection.
/// </summary>
/// <param name="value">Server.Engines.Reports.PersistableObject instance.</param>
/// <returns>The position into which the new element was inserted.</returns>
public int Add( Server.Engines.Reports.PersistableObject value )
{
return this.List.Add( value );
}
public void AddRange( PersistableObject[] col )
{
this.InnerList.AddRange( col );
}
/// <summary>
/// Determines whether a specified Server.Engines.Reports.PersistableObject instance is in this collection.
/// </summary>
/// <param name="value">Server.Engines.Reports.PersistableObject instance to search for.</param>
/// <returns>True if the Server.Engines.Reports.PersistableObject instance is in the collection; otherwise false.</returns>
public bool Contains( Server.Engines.Reports.PersistableObject value )
{
return this.List.Contains( value );
}
/// <summary>
/// Retrieve the index a specified Server.Engines.Reports.PersistableObject instance is in this collection.
/// </summary>
/// <param name="value">Server.Engines.Reports.PersistableObject instance to find.</param>
/// <returns>The zero-based index of the specified Server.Engines.Reports.PersistableObject instance. If the object is not found, the return value is -1.</returns>
public int IndexOf( Server.Engines.Reports.PersistableObject value )
{
return this.List.IndexOf( value );
}
/// <summary>
/// Removes a specified Server.Engines.Reports.PersistableObject instance from this collection.
/// </summary>
/// <param name="value">The Server.Engines.Reports.PersistableObject instance to remove.</param>
public void Remove( Server.Engines.Reports.PersistableObject value )
{
this.List.Remove( value );
}
/// <summary>
/// Returns an enumerator that can iterate through the Server.Engines.Reports.PersistableObject instance.
/// </summary>
/// <returns>An Server.Engines.Reports.PersistableObject's enumerator.</returns>
new public ObjectCollectionEnumerator GetEnumerator()
{
return new ObjectCollectionEnumerator( this );
}
/// <summary>
/// Insert a Server.Engines.Reports.PersistableObject instance into this collection at a specified index.
/// </summary>
/// <param name="index">Zero-based index.</param>
/// <param name="value">The Server.Engines.Reports.PersistableObject instance to insert.</param>
public void Insert( int index, Server.Engines.Reports.PersistableObject value )
{
this.List.Insert( index, value );
}
/// <summary>
/// Strongly typed enumerator of Server.Engines.Reports.PersistableObject.
/// </summary>
public class ObjectCollectionEnumerator : System.Collections.IEnumerator
{
/// <summary>
/// Current index
/// </summary>
private int _index;
/// <summary>
/// Current element pointed to.
/// </summary>
private Server.Engines.Reports.PersistableObject _currentElement;
/// <summary>
/// Collection to enumerate.
/// </summary>
private ObjectCollection _collection;
/// <summary>
/// Default constructor for enumerator.
/// </summary>
/// <param name="collection">Instance of the collection to enumerate.</param>
internal ObjectCollectionEnumerator( ObjectCollection collection )
{
_index = -1;
_collection = collection;
}
/// <summary>
/// Gets the Server.Engines.Reports.PersistableObject object in the enumerated ObjectCollection currently indexed by this instance.
/// </summary>
public Server.Engines.Reports.PersistableObject Current
{
get
{
if ( ( ( _index == -1 ) || ( _index >= _collection.Count ) ) )
{
throw new System.IndexOutOfRangeException( "Enumerator not started." );
}
else
{
return _currentElement;
}
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
object IEnumerator.Current
{
get
{
if ( ( ( _index == -1 ) || ( _index >= _collection.Count ) ) )
{
throw new System.IndexOutOfRangeException( "Enumerator not started." );
}
else
{
return _currentElement;
}
}
}
/// <summary>
/// Reset the cursor, so it points to the beginning of the enumerator.
/// </summary>
public void Reset()
{
_index = -1;
_currentElement = null;
}
/// <summary>
/// Advances the enumerator to the next queue of the enumeration, if one is currently available.
/// </summary>
/// <returns>true, if the enumerator was succesfully advanced to the next queue; false, if the enumerator has reached the end of the enumeration.</returns>
public bool MoveNext()
{
if ( ( _index < ( _collection.Count - 1 ) ) )
{
_index = ( _index + 1 );
_currentElement = this._collection[_index];
return true;
}
_index = _collection.Count;
return false;
}
}
}
} | gpl-3.0 |
zyvitski/DSG | doxygen/html/search/functions_12.js | 3491 | var searchData=
[
['_7eanalogsaw',['~AnalogSaw',['../class_d_s_g_1_1_analog_1_1_analog_saw.html#a42a5fe22e0c3b9d1bd3996fe5bbd24ba',1,'DSG::Analog::AnalogSaw']]],
['_7eanalogsquare',['~AnalogSquare',['../class_d_s_g_1_1_analog_1_1_analog_square.html#a17b3928f19cb6bf0c151b5e1159de1db',1,'DSG::Analog::AnalogSquare']]],
['_7eanalogtriangle',['~AnalogTriangle',['../class_d_s_g_1_1_analog_1_1_analog_triangle.html#af6e127d2fb623afad9b172e7c8b3c656',1,'DSG::Analog::AnalogTriangle']]],
['_7eblit',['~Blit',['../class_d_s_g_1_1_b_l_i_t_1_1_blit.html#a92da2e1763735b3e17f7b9a24377f988',1,'DSG::BLIT::Blit']]],
['_7eblitsaw',['~BlitSaw',['../class_d_s_g_1_1_b_l_i_t_1_1_blit_saw.html#a4744c63b29aee896823f19965e11e515',1,'DSG::BLIT::BlitSaw']]],
['_7ebuffer',['~Buffer',['../class_d_s_g_1_1_buffer.html#a619fc41bf263a419da1a19254e194101',1,'DSG::Buffer']]],
['_7edcblocker',['~DCBlocker',['../class_d_s_g_1_1_filter_1_1_d_c_blocker.html#a5393dac29a226f5912f6d1705b69eecf',1,'DSG::Filter::DCBlocker']]],
['_7edelay',['~Delay',['../class_d_s_g_1_1_delay.html#ac2df9a0120744cc8efa15556e4293a2c',1,'DSG::Delay']]],
['_7edpwsaw',['~DPWSaw',['../class_d_s_g_1_1_d_p_w_1_1_d_p_w_saw.html#afc78ee5a1353dec65adf963a677e95fe',1,'DSG::DPW::DPWSaw']]],
['_7eeptrsaw',['~EPTRSaw',['../class_d_s_g_1_1_e_p_t_r_1_1_e_p_t_r_saw.html#a932fb8ef2df61ed06e6cca5cdc622884',1,'DSG::EPTR::EPTRSaw']]],
['_7efilterbase',['~FilterBase',['../class_d_s_g_1_1_filter_1_1_filter_base.html#a1e220c7fe383eba4822f3896d8b2c2b2',1,'DSG::Filter::FilterBase']]],
['_7efouriersaw',['~FourierSaw',['../class_d_s_g_1_1_fourier_1_1_fourier_saw.html#acd28c4942553271ed9f39e8f05b8db6d',1,'DSG::Fourier::FourierSaw']]],
['_7efourierseriesgenerator',['~FourierSeriesGenerator',['../class_d_s_g_1_1_fourier_1_1_fourier_series_generator.html#a6e5b0a582b040035a47a0855456d71c1',1,'DSG::Fourier::FourierSeriesGenerator']]],
['_7efouriersquare',['~FourierSquare',['../class_d_s_g_1_1_fourier_1_1_fourier_square.html#af78565a799ebfd4be03cc0294dff1f85',1,'DSG::Fourier::FourierSquare']]],
['_7efouriertriangle',['~FourierTriangle',['../class_d_s_g_1_1_fourier_1_1_fourier_triangle.html#a780bfb898d144200ff2bfb48849b4d24',1,'DSG::Fourier::FourierTriangle']]],
['_7egenericgenerator',['~GenericGenerator',['../class_d_s_g_1_1_generic_generator.html#aeaca1efdba7186a8b3b1879b092e7bec',1,'DSG::GenericGenerator']]],
['_7eharmonic',['~Harmonic',['../class_d_s_g_1_1_fourier_1_1_harmonic.html#aad4e5d3e4ef8cd53bf01b0624246b826',1,'DSG::Fourier::Harmonic']]],
['_7eleakyintegrator',['~LeakyIntegrator',['../class_d_s_g_1_1_filter_1_1_leaky_integrator.html#a3a79cdbcf90a7924c05ec87b89fca83d',1,'DSG::Filter::LeakyIntegrator']]],
['_7elut',['~LUT',['../class_d_s_g_1_1_l_u_t.html#ad939097dc1474825c7aa5ef2c427de4d',1,'DSG::LUT']]],
['_7enoisegenerator',['~NoiseGenerator',['../class_d_s_g_1_1_noise_generator.html#a964f0af791b5e09e63470bf42ddbce79',1,'DSG::NoiseGenerator']]],
['_7ephasor',['~Phasor',['../class_d_s_g_1_1_phasor.html#a37b72afd6bd58cebf10cc937e73ef094',1,'DSG::Phasor']]],
['_7eringbuffer',['~RingBuffer',['../class_d_s_g_1_1_ring_buffer.html#a771d30b04b6f0313c203530685fbeb3a',1,'DSG::RingBuffer']]],
['_7esignalgenerator',['~SignalGenerator',['../class_d_s_g_1_1_signal_generator.html#a7b52d391974bc36a19fdcf617ad976cb',1,'DSG::SignalGenerator']]],
['_7esignalprocess',['~SignalProcess',['../class_d_s_g_1_1_signal_process.html#ad9b6a758241a092ddc38e13effc9553f',1,'DSG::SignalProcess']]]
];
| gpl-3.0 |
Darkpeninsula/DarkCore-Old | src/server/scripts/EasternKingdoms/BlackwingLair/boss_victor_nefarius.cpp | 14959 | /*
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2011-2012 Darkpeninsula Project <http://www.darkpeninsula.eu/>
*
* 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
*/
/* ScriptData
SDName: Boss_Victor_Nefarius
SD%Complete: 75
SDComment: Missing some text, Vael beginning event, and spawns Nef in wrong place
SDCategory: Blackwing Lair
EndScriptData */
#include "ScriptPCH.h"
#define SAY_GAMESBEGIN_1 -1469004
#define SAY_GAMESBEGIN_2 -1469005
#define SAY_VAEL_INTRO -1469006 //when he corrupts Vaelastrasz
#define GOSSIP_ITEM_1 "I've made no mistakes."
#define GOSSIP_ITEM_2 "You have lost your mind, Nefarius. You speak in riddles."
#define GOSSIP_ITEM_3 "Please do."
#define CREATURE_BRONZE_DRAKANOID 14263
#define CREATURE_BLUE_DRAKANOID 14261
#define CREATURE_RED_DRAKANOID 14264
#define CREATURE_GREEN_DRAKANOID 14262
#define CREATURE_BLACK_DRAKANOID 14265
#define CREATURE_CHROMATIC_DRAKANOID 14302
#define CREATURE_NEFARIAN 11583
#define ADD_X1 -7591.151855f
#define ADD_X2 -7514.598633f
#define ADD_Y1 -1204.051880f
#define ADD_Y2 -1150.448853f
#define ADD_Z1 476.800476f
#define ADD_Z2 476.796570f
#define NEF_X -7445
#define NEF_Y -1332
#define NEF_Z 536
#define HIDE_X -7592
#define HIDE_Y -1264
#define HIDE_Z 481
#define SPELL_SHADOWBOLT 21077
#define SPELL_FEAR 26070
//This script is complicated
//Instead of morphing Victor Nefarius we will have him control phase 1
//And then have him spawn "Nefarian" for phase 2
//When phase 2 starts Victor Nefarius will go into hiding and stop attacking
//If Nefarian despawns because he killed the players then this guy will EnterEvadeMode
//and allow players to start the event over
//If nefarian dies then he will kill himself then he will kill himself in his hiding place
//To prevent players from doing the event twice
class boss_victor_nefarius : public CreatureScript
{
public:
boss_victor_nefarius() : CreatureScript("boss_victor_nefarius") { }
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
pPlayer->PlayerTalkClass->ClearMenus();
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF+1:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
pPlayer->SEND_GOSSIP_MENU(7198, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+2:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3);
pPlayer->SEND_GOSSIP_MENU(7199, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+3:
pPlayer->CLOSE_GOSSIP_MENU();
DoScriptText(SAY_GAMESBEGIN_1, pCreature);
CAST_AI(boss_victor_nefarius::boss_victor_nefariusAI, pCreature->AI())->BeginEvent(pPlayer);
break;
}
return true;
}
bool OnGossipHello(Player* pPlayer, Creature* pCreature)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1 , GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
pPlayer->SEND_GOSSIP_MENU(7134, pCreature->GetGUID());
return true;
}
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_victor_nefariusAI (pCreature);
}
struct boss_victor_nefariusAI : public ScriptedAI
{
boss_victor_nefariusAI(Creature *c) : ScriptedAI(c)
{
NefarianGUID = 0;
switch (urand(0, 19))
{
case 0:
DrakType1 = CREATURE_BRONZE_DRAKANOID;
DrakType2 = CREATURE_BLUE_DRAKANOID;
break;
case 1:
DrakType1 = CREATURE_BRONZE_DRAKANOID;
DrakType2 = CREATURE_RED_DRAKANOID;
break;
case 2:
DrakType1 = CREATURE_BRONZE_DRAKANOID;
DrakType2 = CREATURE_GREEN_DRAKANOID;
break;
case 3:
DrakType1 = CREATURE_BRONZE_DRAKANOID;
DrakType2 = CREATURE_BLACK_DRAKANOID;
break;
case 4:
DrakType1 = CREATURE_BLUE_DRAKANOID;
DrakType2 = CREATURE_BRONZE_DRAKANOID;
break;
case 5:
DrakType1 = CREATURE_BLUE_DRAKANOID;
DrakType2 = CREATURE_RED_DRAKANOID;
break;
case 6:
DrakType1 = CREATURE_BLUE_DRAKANOID;
DrakType2 = CREATURE_GREEN_DRAKANOID;
break;
case 7:
DrakType1 = CREATURE_BLUE_DRAKANOID;
DrakType2 = CREATURE_BLACK_DRAKANOID;
break;
case 8:
DrakType1 = CREATURE_RED_DRAKANOID;
DrakType2 = CREATURE_BRONZE_DRAKANOID;
break;
case 9:
DrakType1 = CREATURE_RED_DRAKANOID;
DrakType2 = CREATURE_BLUE_DRAKANOID;
break;
case 10:
DrakType1 = CREATURE_RED_DRAKANOID;
DrakType2 = CREATURE_GREEN_DRAKANOID;
break;
case 11:
DrakType1 = CREATURE_RED_DRAKANOID;
DrakType2 = CREATURE_BLACK_DRAKANOID;
break;
case 12:
DrakType1 = CREATURE_GREEN_DRAKANOID;
DrakType2 = CREATURE_BRONZE_DRAKANOID;
break;
case 13:
DrakType1 = CREATURE_GREEN_DRAKANOID;
DrakType2 = CREATURE_BLUE_DRAKANOID;
break;
case 14:
DrakType1 = CREATURE_GREEN_DRAKANOID;
DrakType2 = CREATURE_RED_DRAKANOID;
break;
case 15:
DrakType1 = CREATURE_GREEN_DRAKANOID;
DrakType2 = CREATURE_BLACK_DRAKANOID;
break;
case 16:
DrakType1 = CREATURE_BLACK_DRAKANOID;
DrakType2 = CREATURE_BRONZE_DRAKANOID;
break;
case 17:
DrakType1 = CREATURE_BLACK_DRAKANOID;
DrakType2 = CREATURE_BLUE_DRAKANOID;
break;
case 18:
DrakType1 = CREATURE_BLACK_DRAKANOID;
DrakType2 = CREATURE_GREEN_DRAKANOID;
break;
case 19:
DrakType1 = CREATURE_BLACK_DRAKANOID;
DrakType2 = CREATURE_RED_DRAKANOID;
break;
}
}
uint32 SpawnedAdds;
uint32 AddSpawnTimer;
uint32 ShadowBoltTimer;
uint32 FearTimer;
uint32 MindControlTimer;
uint32 ResetTimer;
uint32 DrakType1;
uint32 DrakType2;
uint64 NefarianGUID;
uint32 NefCheckTime;
void Reset()
{
SpawnedAdds = 0;
AddSpawnTimer = 10000;
ShadowBoltTimer = 5000;
FearTimer = 8000;
ResetTimer = 900000; //On official it takes him 15 minutes(900 seconds) to reset. We are only doing 1 minute to make testing easier
NefarianGUID = 0;
NefCheckTime = 2000;
me->SetUInt32Value(UNIT_NPC_FLAGS, 1);
me->setFaction(35);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
void BeginEvent(Player *pTarget)
{
DoScriptText(SAY_GAMESBEGIN_2, me);
//DarkCore::Singleton<MapManager>::Instance().GetMap(me->GetMapId(), me)->GetPlayers().begin();
/*
list <Player*>::const_iterator i = sMapMgr->GetMap(me->GetMapId(), me)->GetPlayers().begin();
for (i = sMapMgr->GetMap(me->GetMapId(), me)->GetPlayers().begin(); i != sMapMgr->GetMap(me->GetMapId(), me)->GetPlayers().end(); ++i)
{
AttackStart((*i));
}
*/
me->SetUInt32Value(UNIT_NPC_FLAGS, 0);
me->setFaction(103);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
AttackStart(pTarget);
}
void EnterCombat(Unit * /*who*/)
{
}
void MoveInLineOfSight(Unit *who)
{
//We simply use this function to find players until we can use pMap->GetPlayers()
if (who && who->GetTypeId() == TYPEID_PLAYER && me->IsHostileTo(who))
{
//Add them to our threat list
me->AddThreat(who, 0.0f);
}
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//Only do this if we haven't spawned nef yet
if (SpawnedAdds < 42)
{
//ShadowBoltTimer
if (ShadowBoltTimer <= diff)
{
if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(pTarget, SPELL_SHADOWBOLT);
ShadowBoltTimer = urand(3000, 10000);
} else ShadowBoltTimer -= diff;
//FearTimer
if (FearTimer <= diff)
{
if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(pTarget, SPELL_FEAR);
FearTimer = 10000 + (rand()%10000);
} else FearTimer -= diff;
//Add spawning mechanism
if (AddSpawnTimer <= diff)
{
//Spawn 2 random types of creatures at the 2 locations
uint32 CreatureID;
Creature* Spawned = NULL;
Unit *pTarget = NULL;
//1 in 3 chance it will be a chromatic
if (urand(0, 2) == 0)
CreatureID = CREATURE_CHROMATIC_DRAKANOID;
else
CreatureID = DrakType1;
++SpawnedAdds;
//Spawn Creature and force it to start attacking a random target
Spawned = me->SummonCreature(CreatureID, ADD_X1, ADD_Y1, ADD_Z1, 5.000f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (pTarget && Spawned)
{
Spawned->AI()->AttackStart(pTarget);
Spawned->setFaction(103);
}
//1 in 3 chance it will be a chromatic
if (urand(0, 2) == 0)
CreatureID = CREATURE_CHROMATIC_DRAKANOID;
else
CreatureID = DrakType2;
++SpawnedAdds;
Spawned = me->SummonCreature(CreatureID, ADD_X2, ADD_Y2, ADD_Z2, 5.000f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (pTarget && Spawned)
{
Spawned->AI()->AttackStart(pTarget);
Spawned->setFaction(103);
}
//Begin phase 2 by spawning Nefarian and what not
if (SpawnedAdds >= 42)
{
//Teleport Victor Nefarius way out of the map
//sMapMgr->GetMap(me->GetMapId(), me)->CreatureRelocation(me, 0, 0, -5000, 0);
//Interrupt any spell casting
me->InterruptNonMeleeSpells(false);
//Root self
DoCast(me, 33356);
//Make super invis
DoCast(me, 8149);
//Teleport self to a hiding spot (this causes errors in the DarkCore log but no real issues)
DoTeleportTo(HIDE_X, HIDE_Y, HIDE_Z);
me->AddUnitState(UNIT_STAT_FLEEING);
//Spawn nef and have him attack a random target
Creature* Nefarian = me->SummonCreature(CREATURE_NEFARIAN, NEF_X, NEF_Y, NEF_Z, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 120000);
pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (pTarget && Nefarian)
{
Nefarian->AI()->AttackStart(pTarget);
Nefarian->setFaction(103);
NefarianGUID = Nefarian->GetGUID();
}
else sLog->outError("TSCR: Blackwing Lair: Unable to spawn nefarian properly.");
}
AddSpawnTimer = 4000;
} else AddSpawnTimer -= diff;
}
else if (NefarianGUID)
{
if (NefCheckTime <= diff)
{
Unit* Nefarian = Unit::GetCreature((*me), NefarianGUID);
//If nef is dead then we die to so the players get out of combat
//and cannot repeat the event
if (!Nefarian || !Nefarian->isAlive())
{
NefarianGUID = 0;
me->ForcedDespawn();
}
NefCheckTime = 2000;
} else NefCheckTime -= diff;
}
}
};
};
void AddSC_boss_victor_nefarius()
{
new boss_victor_nefarius();
} | gpl-3.0 |
sc13-bioinf/EAGER-CLI | src/main/java/Modules/stats/Flagstat.java | 2531 | /*
* Copyright (c) 2016. EAGER-CLI Alexander Peltzer
* 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 Modules.stats;
import IO.Communicator;
import Modules.AModule;
/**
* Created by peltzer on 1/28/15.
*/
public class Flagstat extends AModule {
public static final int DEFAULT = 0;
public static final int FILTERED = 1;
public static final int SAM = 2;
private int currentConfiguration = DEFAULT;
public Flagstat(Communicator c){
super(c);
}
public Flagstat(Communicator c, int currentConfiguration){
super(c);
this.currentConfiguration = currentConfiguration;
}
@Override
public void setParameters() {
String toFireBash = "";
switch(currentConfiguration){
case SAM :
case DEFAULT :
toFireBash = "samtools flagstat "+this.inputfile.get(0)+" > "+this.inputfile.get(0)+".stats";
this.parameters = new String[]{"/bin/sh", "-c", toFireBash};
this.outputfile = this.inputfile;
break;
case FILTERED : toFireBash = "samtools flagstat "+this.inputfile.get(0)+" > "+this.inputfile.get(0)+".qF.stats";
this.parameters = new String[]{"/bin/sh", "-c", toFireBash};
this.outputfile = this.inputfile;
break;
}
}
@Override
public String getOutputfolder() {
return this.communicator.getGUI_resultspath() + "/4-Samtools";
}
@Override
public String getModulename(){
return super.getModulename() + getSubModuleName();
}
private String getSubModuleName() {
switch (currentConfiguration){
case SAM:
return "sam";
case DEFAULT:
return "default";
case FILTERED:
return "filtered";
default: return "default";
}
}
}
| gpl-3.0 |
TwistPHP/TwistPHP | dist/twist/Core/Controllers/Base.controller.php | 15511 | <?php
/**
* TwistPHP - An open source PHP MVC framework built from the ground up.
* Shadow Technologies Ltd.
*
* 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/>.
*
* @author Shadow Technologies Ltd. <contact@shadow-technologies.co.uk>
* @license https://www.gnu.org/licenses/gpl.html GPL License
* @link https://twistphp.com
*/
namespace Twist\Core\Controllers;
use Twist\Classes\Error;
/**
* Base Controller should be used as an extension to every route controller class that is made with the exception of those controllers that use BaseControllerAJAX and BaseControllerUser.
* @package Twist\Core\Classes
*/
class Base{
protected $arrMessages = array();
protected $arrAliasURIs = array();
protected $arrReplaceURIs = array();
protected $arrRoute = array();
protected static $resValidator = null;
/**
* @var \Twist\Core\Helpers\Route
*/
protected $resRoute = null;
/**
* A function that is called by Routes both to ensure that the controller has been extended and so that we can pass in resources and information required by the controller.
*
* @param \Twist\Core\Helpers\Route $resRoute
* @param array $arrRouteData
* @return bool
*/
final public function _extended($resRoute,$arrRouteData){
//Can be used to modify the baseView etc
$this->resRoute = $resRoute;
//Store the route data for use later
$this->arrRoute = $arrRouteData;
return $this->_baseCalls();
}
/**
* This function is called by _extended, replace this function putting calls such as alias and replaces
* and is only needed if creating a new expendable Base Controller such as baseUser and baseAJAX.
*/
protected function _baseCalls(){
//Leave empty - this is to be extended only!
return true;
}
/**
* Default response from any controller, this function can be replaced in a controller to do what is required.
* The default response is a 404 page.
*
* @return bool
*/
public function _default(){
return $this->_404();
}
/**
* The main response of the controller, treat this function as though it where an index.php file.
* As default the responses returned is that of _default.
*
* @return bool
*/
public function _index(){
return $this->_default();
}
/**
* This is the function that will be called in the even that Routes was unable to find a exact controller response.
*
* @return bool
*/
public function _fallback(){
return $this->_404();
}
/**
* Over-ride the base view for the current page only.
*
* @param null $mxdBaseView
* @return null|string
*/
public function _baseView($mxdBaseView = null){
if(!is_null($mxdBaseView)){
$this->resRoute->baseViewForce();
}
return $this->resRoute->baseView($mxdBaseView);
}
/**
* Ignore the base view for the current page only.
*/
public function _baseViewIgnore(){
$this->resRoute->baseViewIgnore();
}
/**
* Set the timeout for the current page (Some pages may have allot to do so this can be done per page).
*
* @param int $intTimeout
*/
public function _timeout($intTimeout = 30){
set_time_limit($intTimeout);
}
/**
* Ignore user abort, when in use the scrip will carry on processing until complete even if the user closes the browser window or stops the request from loading.
*
* @param bool $blIgnore
*/
public function _ignoreUserAbort($blIgnore = true){
ignore_user_abort($blIgnore);
}
/**
* Register an alias URI for a response function for instance if you had thankYou() as the function name you could register 'thank-you' as an alias URI.
* All aliases must be registered from within a __construct function in your controller. Adding an alias means that the original thankYou() will still be callable by routes.
*
* @param string $strURI Relative part of the URI to use as an alias
* @param string $strFunctionName Function to call upon URI match
*/
protected function _aliasURI($strURI,$strFunctionName){
$this->arrAliasURIs[$strURI] = $strFunctionName;
}
/**
* Get an array of all the aliases registered for this controller.
*
* @return array
*/
public function _getAliases(){
return $this->arrAliasURIs;
}
/**
* Register an replace URI for a response function for instance if you had thankYou() as the function name you could register 'thank-you' as an replace URI.
* All replaces must be registered from within a __construct function in your controller. Adding a replace means that the original thankYou() will no-longer be callable by routes.
*
* @param string $strURI Relative part of the URI to use as a replacement
* @param string $strFunctionName Function to replace/call upon URI match
*/
protected function _replaceURI($strURI,$strFunctionName){
$this->arrReplaceURIs[$strFunctionName] = $strURI;
}
/**
* Get an array of all the replacements registered for this controller.
*
* @return array
*/
public function _getReplacements(){
return $this->arrReplaceURIs;
}
/**
* Function to call any controller response with the correct method prefix if any has been setup. If the response function is not found a 404 page will be output.
*
* @param string $strCallFunctionName Name of the function to be called
* @return bool
*/
final protected function _callFunction($strCallFunctionName){
$arrControllerFunctions = array();
foreach(get_class_methods($this) as $strFunctionName){
$arrControllerFunctions[strtolower($strFunctionName)] = $strFunctionName;
}
$strRequestMethodFunction = sprintf('%s%s',strtolower($_SERVER['REQUEST_METHOD']),strtolower($strCallFunctionName));
if(array_key_exists($strRequestMethodFunction,$arrControllerFunctions)){
$strFunctionName = (string) $arrControllerFunctions[$strRequestMethodFunction];
return $this->$strFunctionName();
}elseif(array_key_exists(strtolower($strCallFunctionName),$arrControllerFunctions)){
$strFunctionName = (string) $arrControllerFunctions[strtolower($strCallFunctionName)];
return $this->$strFunctionName();
}else{
return $this->_404();
}
}
/**
* Returns either a single item (if key passed in) from the route array otherwise returns the whole array.
*
* @param null|string $strReturnKey
* @return array
*/
final protected function _route($strReturnKey = null){
return array_key_exists($strReturnKey, $this->arrRoute) ? $this->arrRoute[$strReturnKey] : $this->arrRoute;
}
/**
* Process files that have been uploaded and return an array of uploaded data, this is to help when a browser does not support teh pure AJAX uploader.
*
* @param string $strFileKey
* @param string $strType
* @return array|mixed
*/
public function _upload($strFileKey,$strType = 'file'){
$arrOut = array();
if(count($_FILES) && array_key_exists($strFileKey,$_FILES)){
$resUpload = new Upload();
if(is_array($_FILES[$strFileKey]['name'])){
foreach($_FILES[$strFileKey]['name'] as $intKey => $mxdValue){
$arrOut[] = json_decode($resUpload->$strType($strFileKey,$intKey),true);
}
}else{
$arrOut = json_decode($resUpload->$strType($strFileKey),true);
}
}
return $arrOut;
}
/**
* Halts all scripts and outputs a 404 page to the screen.
*
* @return bool
*/
final public function _404(){
return $this->_error(404);
}
/**
* Halts all scripts and outputs the desired error page by response code (for example 404 or 403) to the screen.
*
* @param int $intError HTTP Response code of the error page to be output
* @return bool
*/
final public function _error($intError){
return $this->_response($intError);
}
/**
* Halts all scripts and outputs the desired error page by response code (for example 404 or 403) to the screen.
*
* @param int $intError HTTP Response code of the error page to be output
* @param null|string $strCustomDescription Custom description to be included in the response page
* @return bool
*/
final public function _response($intError,$strCustomDescription = null){
Error::response($intError,$strCustomDescription);
return false;
}
/**
* Add an error message, the messages can be output using the {messages:error} template tag, you can also output all messages using {messages:all}.
*
* @param string $strMessage Message to be output as an error
* @param null|string $strKey
*/
public function _errorMessage($strMessage,$strKey = null){
\Twist::errorMessage($strMessage,$strKey);
}
/**
* Add an warning message, the messages can be output using the {messages:warning} template tag, you can also output all messages using {messages:all}.
*
* @param string $strMessage Message to be output as a warning
* @param null|string $strKey
*/
public function _warningMessage($strMessage,$strKey = null){
\Twist::warningMessage($strMessage,$strKey);
}
/**
* Add an notice message, the messages can be output using the {messages:notice} template tag, you can also output all messages using {messages:all}.
*
* @param string $strMessage Message to be output as a notice
* @param null|string $strKey
*/
public function _noticeMessage($strMessage,$strKey = null){
\Twist::noticeMessage($strMessage,$strKey);
}
/**
* Add an success message, the messages can be output using the {messages:success} template tag, you can also output all messages using {messages:all}.
*
* @param string $strMessage Message to be output as successful
* @param null|string $strKey
*/
public function _successMessage($strMessage,$strKey = null){
\Twist::successMessage($strMessage,$strKey);
}
/**
* Returns the Meta object so that page titles, keywords and other meta items can all be updated before being output to the base template.
*
* @return null|object|resource|\Twist\Core\Models\Route\Meta
*/
public function _meta(){
return $this->resRoute->meta();
}
/**
* Returns the Model object which is only set when {model:App\My\Model} is defined in your URI, From here all functions of the model can be called.
*
* @return null|Object
*/
public function _model(){
return $this->resRoute->model();
}
/**
* Get a Route URI var from the route vars, passing in null will return the whole array of route vars.
*
* @param null $strVarKey
* @return string|array|null
*/
protected function _var($strVarKey = null){
if(is_null($strVarKey)){
return $this->arrRoute['vars'];
}else{
return (array_key_exists($strVarKey,$this->arrRoute['vars'])) ? $this->arrRoute['vars'][$strVarKey] : null;
}
}
/**
* Process a view template file and return the output.
* @param string $dirView
* @param null $arrViewTags
* @param bool $blRemoveUnusedTags
* @return string
*/
protected function _view($dirView,$arrViewTags = null,$blRemoveUnusedTags = false){
return \Twist::View()->build($dirView,$arrViewTags,$blRemoveUnusedTags);
}
/**
* @alias _view
* @param string $dirView
* @param null $arrViewTags
* @param bool $blRemoveUnusedTags
* @return string
*/
protected function _render($dirView,$arrViewTags = null,$blRemoveUnusedTags = false){
return $this->_view($dirView,$arrViewTags,$blRemoveUnusedTags);
}
/**
* Set a required parameter for the API method, if missing or type validation fails an error will be returned
* @param $strName
* @param string $strFormatRequired
* @param bool $lbAllowBlank
*/
protected function _required($strName,$strFormatRequired = 'string',$lbAllowBlank = false){
self::$resValidator = (is_null(self::$resValidator)) ? \Twist::Validate()->createTest() : self::$resValidator;
$strFunction = (string) 'check'.ucfirst($strFormatRequired);
if($strFormatRequired == 'integer'){
self::$resValidator->$strFunction($strName,null,null,$lbAllowBlank,true);
}else{
self::$resValidator->$strFunction($strName,$lbAllowBlank,true);
}
}
/**
* Set a optional parameter for the API method, if type validation fails an error will be returned
* @param $strName
* @param string $strFormatRequired
* @param bool $lbAllowBlank
*/
protected function _optional($strName,$strFormatRequired = 'string',$lbAllowBlank = false){
self::$resValidator = (is_null(self::$resValidator)) ? \Twist::Validate()->createTest() : self::$resValidator;
$strFunction = (string) 'check'.ucfirst($strFormatRequired);
//Only attempt to validate if exists as this is an optional param
if(array_key_exists($strName,$_POST)){
if($strFormatRequired == 'integer'){
self::$resValidator->$strFunction($strName,null,null,$lbAllowBlank,false);
}elseif($strFormatRequired == 'array'){
self::$resValidator->$strFunction($strName,null,null,$lbAllowBlank,false);
}else{
self::$resValidator->$strFunction($strName,$lbAllowBlank,false);
}
}else{
$_POST[$strName] = null;
}
}
/**
* Check to see that the required and optional _POST parameters have been met, violations will though a Twist error response
* @param bool $blFirstErrorOnly
* @return bool
* @throws \Exception
*/
protected function _check($blFirstErrorOnly = false){
$blSuccess = true;
self::$resValidator = (is_null(self::$resValidator)) ? \Twist::Validate()->createTest() : self::$resValidator;
$arrResult = self::$resValidator->test($_POST);
if(!self::$resValidator->success()){
//Output error messages
foreach($arrResult['results'] as $strField => $arrEachResult){
if($arrEachResult['status'] == false){
if(strstr($strField,'email') && strstr($arrEachResult['message'],'incorrectly formatted data')){
$arrEachResult['message'] = 'Please enter a valid email address';
}elseif(strstr($strField,'website') && strstr($arrEachResult['message'],'incorrectly formatted data')){
$arrEachResult['message'] = 'Please enter the full website URL including the correct http:// or https:// prefix, for example: https://www.example.com';
}
//Only output one error response at a time, auto kills script
$this->_errorMessage($arrEachResult['message'],'controller');
$blSuccess = false;
if($blFirstErrorOnly){
break;
}
}
}
}
return $blSuccess;
}
/**
* Returns the status of the _POST validation check
* @return bool
*/
protected function _status(){
return (!is_null(self::$resValidator)) ? self::$resValidator->success() : false;
}
}
| gpl-3.0 |
Severed-Infinity/technium | build/tmp/recompileMc/sources/net/minecraftforge/fml/common/ProgressManager.java | 5186 | /*
* Minecraft Forge
* Copyright (c) 2016.
*
* 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 version 2.1
* of the License.
*
* 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
*/
package net.minecraftforge.fml.common;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.common.base.Joiner;
/**
* Not a fully fleshed out API, may change in future MC versions.
* However feel free to use and suggest additions.
*/
public class ProgressManager
{
private static final List<ProgressBar> bars = new CopyOnWriteArrayList<ProgressBar>();
/**
* Not a fully fleshed out API, may change in future MC versions.
* However feel free to use and suggest additions.
*/
public static ProgressBar push(String title, int steps)
{
return push(title, steps, false);
}
/**
* Not a fully fleshed out API, may change in future MC versions.
* However feel free to use and suggest additions.
*/
public static ProgressBar push(String title, int steps, boolean timeEachStep)
{
ProgressBar bar = new ProgressBar(title, steps);
bars.add(bar);
if (timeEachStep)
{
bar.timeEachStep();
}
FMLCommonHandler.instance().processWindowMessages();
return bar;
}
public static boolean isDisplayVSyncForced() {
return FMLCommonHandler.instance().isDisplayVSyncForced();
}
/**
* Not a fully fleshed out API, may change in future MC versions.
* However feel free to use and suggest additions.
*/
public static void pop(ProgressBar bar)
{
if(bar.getSteps() != bar.getStep()) throw new IllegalStateException("can't pop unfinished ProgressBar " + bar.getTitle());
bars.remove(bar);
if (bar.getSteps() != 0)
{
long newTime = System.nanoTime();
if (bar.timeEachStep)
{
String timeString = String.format("%.3f", ((float) (newTime - bar.lastTime) / 1000000 / 1000));
FMLLog.log.debug("Bar Step: {} - {} took {}s", bar.getTitle(), bar.getMessage(), timeString);
}
String timeString = String.format("%.3f", ((float) (newTime - bar.startTime) / 1000000 / 1000));
if (bar.getSteps() == 1)
FMLLog.log.debug("Bar Finished: {} - {} took {}s", bar.getTitle(), bar.getMessage(), timeString);
else
FMLLog.log.debug("Bar Finished: {} took {}s", bar.getTitle(), timeString);
}
FMLCommonHandler.instance().processWindowMessages();
}
/*
* Internal use only.
*/
public static Iterator<ProgressBar> barIterator()
{
return bars.iterator();
}
/**
* Not a fully fleshed out API, may change in future MC versions.
* However feel free to use and suggest additions.
*/
public static class ProgressBar
{
private final String title;
private final int steps;
private volatile int step = 0;
private volatile String message = "";
private boolean timeEachStep = false;
private long startTime = System.nanoTime();
private long lastTime = startTime;
private ProgressBar(String title, int steps)
{
this.title = title;
this.steps = steps;
}
public void step(Class<?> classToName, String... extra)
{
step(ClassNameUtils.shortName(classToName)+Joiner.on(' ').join(extra));
}
public void step(String message)
{
if(step >= steps) throw new IllegalStateException("too much steps for ProgressBar " + title);
if (timeEachStep && step != 0)
{
long newTime = System.nanoTime();
FMLLog.log.debug(String.format("Bar Step: %s - %s took %.3fs", getTitle(), getMessage(), ((float)(newTime - lastTime) / 1000000 / 1000)));
lastTime = newTime;
}
step++;
this.message = FMLCommonHandler.instance().stripSpecialChars(message);
FMLCommonHandler.instance().processWindowMessages();
}
public String getTitle()
{
return title;
}
public int getSteps()
{
return steps;
}
public int getStep()
{
return step;
}
public String getMessage()
{
return message;
}
public void timeEachStep()
{
this.timeEachStep = true;
}
}
} | gpl-3.0 |
dementeddevil/EasyTablesTest | Components/crosslight-ui-components-4.0/samples/ViewSliderSamples.iOS/ViewControllers/AutoSlideViewController.designer.cs | 417 | // WARNING
//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
namespace ViewSliderSamples.iOS
{
[Register ("AutoSlideViewController")]
partial class AutoSlideViewController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| gpl-3.0 |
mbshopM/openconcerto | OpenConcerto/src/org/jdesktop/swingx/plaf/LookAndFeelAddons.java | 12890 | /*
* $Id: LookAndFeelAddons.java,v 1.15 2005/12/10 11:33:36 l2fprod Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.plaf;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import org.jdesktop.swingx.plaf.aqua.AquaLookAndFeelAddons;
import org.jdesktop.swingx.plaf.metal.MetalLookAndFeelAddons;
import org.jdesktop.swingx.plaf.motif.MotifLookAndFeelAddons;
import org.jdesktop.swingx.plaf.windows.WindowsClassicLookAndFeelAddons;
import org.jdesktop.swingx.plaf.windows.WindowsLookAndFeelAddons;
import org.jdesktop.swingx.util.OS;
/**
* Provides additional pluggable UI for new components added by the
* library. By default, the library uses the pluggable UI returned by
* {@link #getBestMatchAddonClassName()}.
* <p>
* The default addon can be configured using the
* <code>swing.addon</code> system property as follow:
* <ul>
* <li>on the command line,
* <code>java -Dswing.addon=ADDONCLASSNAME ...</code></li>
* <li>at runtime and before using the library components
* <code>System.getProperties().put("swing.addon", ADDONCLASSNAME);</code>
* </li>
* </ul>
* <p>
* The addon can also be installed directly by calling the
* {@link #setAddon(String)}method. For example, to install the
* Windows addons, add the following statement
* <code>LookAndFeelAddons.setAddon("org.jdesktop.swingx.plaf.windows.WindowsLookAndFeelAddons");</code>.
*
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public class LookAndFeelAddons {
private static List/*<ComponentAddon>*/ contributedComponents =
new ArrayList();
/**
* Key used to ensure the current UIManager has been populated by the
* LookAndFeelAddons.
*/
private static final Object APPCONTEXT_INITIALIZED = new Object();
private static boolean trackingChanges = false;
private static PropertyChangeListener changeListener;
static {
// load the default addon
String addonClassname = getBestMatchAddonClassName();
try {
addonClassname = System.getProperty("swing.addon", addonClassname);
} catch (SecurityException e) {
// security exception may arise in Java Web Start
}
try {
setAddon(addonClassname);
} catch (Exception e) {
// PENDING(fred) do we want to log an error and continue with a default
// addon class or do we just fail?
throw new ExceptionInInitializerError(e);
}
setTrackingLookAndFeelChanges(true);
// this addon ensure resource bundle gets added to lookandfeel defaults
// and re-added by #maybeInitialize if needed
contribute(new AbstractComponentAddon("MinimumAddon") {
protected void addBasicDefaults(LookAndFeelAddons addon, List defaults) {
addResource(defaults, "org.jdesktop.swingx.plaf.resources.swingx");
}
});
}
private static LookAndFeelAddons currentAddon;
public void initialize() {
for (Iterator iter = contributedComponents.iterator(); iter
.hasNext();) {
ComponentAddon addon = (ComponentAddon)iter.next();
addon.initialize(this);
}
}
public void uninitialize() {
for (Iterator iter = contributedComponents.iterator(); iter
.hasNext();) {
ComponentAddon addon = (ComponentAddon)iter.next();
addon.uninitialize(this);
}
}
/**
* Adds the given defaults in UIManager.
*
* @param keysAndValues
*/
public void loadDefaults(Object[] keysAndValues) {
for (int i = 0, c = keysAndValues.length; i < c; i = i + 2) {
UIManager.getLookAndFeelDefaults().put(keysAndValues[i], keysAndValues[i + 1]);
}
}
public void unloadDefaults(Object[] keysAndValues) {
for (int i = 0, c = keysAndValues.length; i < c; i = i + 2) {
UIManager.getLookAndFeelDefaults().put(keysAndValues[i], null);
}
}
public static void setAddon(String addonClassName)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
setAddon(Class.forName(addonClassName));
}
public static void setAddon(Class addonClass) throws InstantiationException,
IllegalAccessException {
LookAndFeelAddons addon = (LookAndFeelAddons)addonClass.newInstance();
setAddon(addon);
}
public static void setAddon(LookAndFeelAddons addon) {
if (currentAddon != null) {
currentAddon.uninitialize();
}
addon.initialize();
currentAddon = addon;
UIManager.put(APPCONTEXT_INITIALIZED, Boolean.TRUE);
}
public static LookAndFeelAddons getAddon() {
return currentAddon;
}
/**
* Based on the current look and feel (as returned by
* <code>UIManager.getLookAndFeel()</code>), this method returns
* the name of the closest <code>LookAndFeelAddons</code> to use.
*
* @return the addon matching the currently installed look and feel
*/
public static String getBestMatchAddonClassName() {
String lnf = UIManager.getLookAndFeel().getClass().getName();
String addon;
if (UIManager.getCrossPlatformLookAndFeelClassName().equals(lnf)) {
addon = MetalLookAndFeelAddons.class.getName();
} else if (UIManager.getSystemLookAndFeelClassName().equals(lnf)) {
addon = getSystemAddonClassName();
} else if ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel".equals(lnf) ||
"com.jgoodies.looks.windows.WindowsLookAndFeel".equals(lnf)) {
if (OS.isUsingWindowsVisualStyles()) {
addon = WindowsLookAndFeelAddons.class.getName();
} else {
addon = WindowsClassicLookAndFeelAddons.class.getName();
}
} else if ("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"
.equals(lnf)) {
addon = WindowsClassicLookAndFeelAddons.class.getName();
} else if (UIManager.getLookAndFeel().getID().equals("Motif")) {
addon = MotifLookAndFeelAddons.class.getName();
} else {
addon = getSystemAddonClassName();
}
return addon;
}
/**
* Gets the addon best suited for the operating system where the
* virtual machine is running.
*
* @return the addon matching the native operating system platform.
*/
public static String getSystemAddonClassName() {
String addon = WindowsClassicLookAndFeelAddons.class.getName();
if (OS.isMacOSX()) {
addon = AquaLookAndFeelAddons.class.getName();
} else if (OS.isWindows()) {
// see whether of not visual styles are used
if (OS.isUsingWindowsVisualStyles()) {
addon = WindowsLookAndFeelAddons.class.getName();
} else {
addon = WindowsClassicLookAndFeelAddons.class.getName();
}
}
return addon;
}
/**
* Each new component added by the library will contribute its
* default UI classes, colors and fonts to the LookAndFeelAddons.
* See {@link ComponentAddon}.
*
* @param component
*/
public static void contribute(ComponentAddon component) {
contributedComponents.add(component);
if (currentAddon != null) {
// make sure to initialize any addons added after the
// LookAndFeelAddons has been installed
component.initialize(currentAddon);
}
}
/**
* Removes the contribution of the given addon
*
* @param component
*/
public static void uncontribute(ComponentAddon component) {
contributedComponents.remove(component);
if (currentAddon != null) {
component.uninitialize(currentAddon);
}
}
/**
* Workaround for IDE mixing up with classloaders and Applets environments.
* Consider this method as API private. It must not be called directly.
*
* @param component
* @param expectedUIClass
* @return an instance of expectedUIClass
*/
public static ComponentUI getUI(JComponent component, Class expectedUIClass) {
maybeInitialize();
// solve issue with ClassLoader not able to find classes
String uiClassname = (String)UIManager.get(component.getUIClassID());
try {
Class uiClass = Class.forName(uiClassname);
UIManager.put(uiClassname, uiClass);
} catch (ClassNotFoundException e) {
// we ignore the ClassNotFoundException
}
ComponentUI ui = UIManager.getUI(component);
if (expectedUIClass.isInstance(ui)) {
return ui;
} else {
String realUI = ui.getClass().getName();
Class realUIClass;
try {
realUIClass = expectedUIClass.getClassLoader()
.loadClass(realUI);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Failed to load class " + realUI, e);
}
Method createUIMethod = null;
try {
createUIMethod = realUIClass.getMethod("createUI", new Class[]{JComponent.class});
} catch (NoSuchMethodException e1) {
throw new RuntimeException("Class " + realUI + " has no method createUI(JComponent)");
}
try {
return (ComponentUI)createUIMethod.invoke(null, new Object[]{component});
} catch (Exception e2) {
throw new RuntimeException("Failed to invoke " + realUI + "#createUI(JComponent)");
}
}
}
/**
* With applets, if you reload the current applet, the UIManager will be
* reinitialized (entries previously added by LookAndFeelAddons will be
* removed) but the addon will not reinitialize because addon initialize
* itself through the static block in components and the classes do not get
* reloaded. This means component.updateUI will fail because it will not find
* its UI.
*
* This method ensures LookAndFeelAddons get re-initialized if needed. It must
* be called in every component updateUI methods.
*/
private static synchronized void maybeInitialize() {
if (currentAddon != null) {
// this is to ensure "UIManager#maybeInitialize" gets called and the
// LAFState initialized
UIManager.getLookAndFeelDefaults();
if (!UIManager.getBoolean(APPCONTEXT_INITIALIZED)) {
setAddon(currentAddon);
}
}
}
//
// TRACKING OF THE CURRENT LOOK AND FEEL
//
private static class UpdateAddon implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
try {
setAddon(getBestMatchAddonClassName());
} catch (Exception e) {
// should not happen
throw new RuntimeException(e);
}
}
}
/**
* If true, everytime the Swing look and feel is changed, the addon which
* best matches the current look and feel will be automatically selected.
*
* @param tracking
* true to automatically update the addon, false to not automatically
* track the addon. Defaults to false.
* @see #getBestMatchAddonClassName()
*/
public static synchronized void setTrackingLookAndFeelChanges(boolean tracking) {
if (trackingChanges != tracking) {
if (tracking) {
if (changeListener == null) {
changeListener = new UpdateAddon();
}
UIManager.addPropertyChangeListener(changeListener);
} else {
if (changeListener != null) {
UIManager.removePropertyChangeListener(changeListener);
}
changeListener = null;
}
trackingChanges = tracking;
}
}
/**
* @return true if the addon will be automatically change to match the current
* look and feel
* @see #setTrackingLookAndFeelChanges(boolean)
*/
public static synchronized boolean isTrackingLookAndFeelChanges() {
return trackingChanges;
}
}
| gpl-3.0 |
mayioit/MacroMedicalSystem | Samples/Google/Calendar/SchedulingComponent.cs | 12314 | #region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using ClearCanvas.Common;
using ClearCanvas.Desktop;
using ClearCanvas.Desktop.Validation;
using ClearCanvas.Common.Utilities;
using ClearCanvas.ImageViewer;
using ClearCanvas.ImageViewer.StudyManagement;
using ClearCanvas.Desktop.Tables;
using ClearCanvas.Desktop.Tools;
using ClearCanvas.Desktop.Actions;
namespace ClearCanvas.Samples.Google.Calendar
{
/// <summary>
/// Defines the tool context interface for tools that extend <see cref="SchedulingToolExtensionPoint"/>.
/// </summary>
public interface ISchedulingToolContext : IToolContext
{
/// <summary>
/// Gets the desktop window in which the scheduling component is running.
/// </summary>
DesktopWindow DesktopWindow { get; }
/// <summary>
/// Gets the currently selected appointment in the appointment list, or null if none is selected.
/// </summary>
CalendarEvent SelectedAppointment { get; }
/// <summary>
/// Occurs when the selected appointment changes.
/// </summary>
event EventHandler SelectedAppointmentChanged;
/// <summary>
/// Gets a list of all appointments currently displayed in the appointment list.
/// </summary>
IList<CalendarEvent> AllAppointments { get; }
}
/// <summary>
/// Extension point for tools that extend the functionality of the <see cref="SchedulingComponent"/>.
/// </summary>
[ExtensionPoint]
public class SchedulingToolExtensionPoint : ExtensionPoint<ITool>
{
}
/// <summary>
/// Extension point for views onto <see cref="SchedulingComponent"/>
/// </summary>
[ExtensionPoint]
public class SchedulingComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView>
{
}
/// <summary>
/// SchedulingComponent class
/// </summary>
[AssociateView(typeof(SchedulingComponentViewExtensionPoint))]
public class SchedulingComponent : ApplicationComponent
{
#region Implementation of ISchedulingToolContext
/// <summary>
/// Inner class that provides the implementation of <see cref="ISchedulingToolContext"/>.
/// </summary>
public class SchedulingToolContext : ToolContext, ISchedulingToolContext
{
private SchedulingComponent _owner;
internal SchedulingToolContext(SchedulingComponent owner)
{
_owner = owner;
}
#region ISchedulingToolContext Members
public DesktopWindow DesktopWindow
{
get { return _owner.Host.DesktopWindow; }
}
public CalendarEvent SelectedAppointment
{
get { return _owner._selectedAppointment; }
}
public event EventHandler SelectedAppointmentChanged
{
add { _owner._selectedAppointmentChanged += value; }
remove { _owner._selectedAppointmentChanged -= value; }
}
public IList<CalendarEvent> AllAppointments
{
get { return _owner._appointments.Items; }
}
#endregion
}
#endregion
private string _patientInfo;
private string _comment;
private DateTime _appointmentDate;
private Table<CalendarEvent> _appointments;
private CalendarEvent _selectedAppointment;
private event EventHandler _selectedAppointmentChanged;
private Calendar _calendar;
private ToolSet _extensionTools;
private ActionModelRoot _menuModel;
private ActionModelRoot _toolbarModel;
/// <summary>
/// Constructor
/// </summary>
public SchedulingComponent()
{
}
/// <summary>
/// Initialize the component.
/// </summary>
public override void Start()
{
_calendar = new Calendar();
_appointmentDate = Platform.Time; // init to current time
// define the structure of the appointments table
_appointments = new Table<CalendarEvent>();
_appointments.Columns.Add(new TableColumn<CalendarEvent, string>(SR.AppointmentTableDate,
delegate(CalendarEvent e) { return Format.Date(e.StartTime); }));
_appointments.Columns.Add(new TableColumn<CalendarEvent, string>(SR.AppointmentTableComment,
delegate(CalendarEvent e) { return e.Description; }));
// create extension tools and action models
_extensionTools = new ToolSet(new SchedulingToolExtensionPoint(), new SchedulingToolContext(this));
_menuModel = ActionModelRoot.CreateModel(this.GetType().FullName, "scheduling-appointments-contextmenu", _extensionTools.Actions);
_toolbarModel = ActionModelRoot.CreateModel(this.GetType().FullName, "scheduling-appointments-toolbar", _extensionTools.Actions);
// initialize patient info from active workspace
UpdatePatientInfo(this.Host.DesktopWindow.ActiveWorkspace);
// subscribe to desktop window for changes in active workspace
this.Host.DesktopWindow.Workspaces.ItemActivationChanged += Workspaces_ItemActivationChanged;
base.Start();
}
/// <summary>
/// Clean up the component.
/// </summary>
public override void Stop()
{
// important to dispose of extension tools
_extensionTools.Dispose();
// important to unsubscribe from this event, or the DesktopWindow will continue to hold a reference to this component
this.Host.DesktopWindow.Workspaces.ItemActivationChanged -= Workspaces_ItemActivationChanged;
base.Stop();
}
/// <summary>
/// Keep the component synchronized with the active workspace.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Workspaces_ItemActivationChanged(object sender, ItemEventArgs<Workspace> e)
{
Workspace workspace = e.Item;
if (workspace.Active)
{
UpdatePatientInfo(workspace);
}
else
{
Reset();
}
}
/// <summary>
/// Helper method to update the component from the active workspace.
/// </summary>
/// <param name="workspace"></param>
private void UpdatePatientInfo(Workspace workspace)
{
IImageViewer viewer = ImageViewerComponent.GetAsImageViewer(workspace);
if (viewer != null)
{
Patient patient = CollectionUtils.FirstElement<Patient>(viewer.StudyTree.Patients);
this.PatientInfo = string.Format("{0} {1}", patient.PatientId, patient.PatientsName);
_appointments.Items.Clear();
_appointments.Items.AddRange(_calendar.GetEvents(_patientInfo, null, null));
}
else
{
this.PatientInfo = null;
}
}
/// <summary>
/// Helper method to clear all data in the component.
/// </summary>
private void Reset()
{
_appointments.Items.Clear();
this.PatientInfo = null;
this.Comment = null;
this.AppointmentDate = Platform.Time;
this.ShowValidation(false);
}
#region Presentation Model
/// <summary>
/// Gets the model for the appointments table context-menu.
/// </summary>
public ActionModelNode MenuModel
{
get { return _menuModel; }
}
/// <summary>
/// Gets the model for the appointments table toolbar.
/// </summary>
public ActionModelNode ToolbarModel
{
get { return _toolbarModel; }
}
/// <summary>
/// Gets the appointments table.
/// </summary>
public ITable Appointments
{
get { return _appointments; }
}
/// <summary>
/// Gets or sets the current selection in the appointments table.
/// </summary>
public ISelection SelectedAppointment
{
get { return new Selection(_selectedAppointment); }
set
{
if (value.Item != _selectedAppointment)
{
_selectedAppointment = (CalendarEvent)value.Item;
NotifyPropertyChanged("SelectedAppointment");
// also fire the private event, used by the tool context
EventsHelper.Fire(_selectedAppointmentChanged, this, EventArgs.Empty);
}
}
}
/// <summary>
/// Gets the patient information field.
/// </summary>
[ValidateNotNull]
public string PatientInfo
{
get { return _patientInfo; }
private set
{
if (value != _patientInfo)
{
_patientInfo = value;
NotifyPropertyChanged("PatientInfo");
}
}
}
/// <summary>
/// Gets or sets the comment for a follow-up appointment.
/// </summary>
[ValidateNotNull]
public string Comment
{
get { return _comment; }
set
{
if (value != _comment)
{
_comment = value;
this.NotifyPropertyChanged("Comment");
}
}
}
/// <summary>
/// Gets or sets the appointment date for a follow-up appointment.
/// </summary>
[ValidateGreaterThan("CurrentTime", Message="AppointmentMustBeInFuture")]
public DateTime AppointmentDate
{
get { return _appointmentDate; }
set
{
if (value != _appointmentDate)
{
_appointmentDate = value;
this.NotifyPropertyChanged("AppointmentDate");
}
}
}
/// <summary>
/// Gets the current time. This is a reference property used to validate the <see cref="AppointmentDate"/> property.
/// </summary>
public DateTime CurrentTime
{
get { return DateTime.Now; }
}
/// <summary>
/// Adds a follow-up appointment based on the d
/// </summary>
public void AddAppointment()
{
// check for validation errors
if (this.HasValidationErrors)
{
// ensure validation errors are visible to the user, and bail
this.ShowValidation(true);
return;
}
// add the appointment to the calendar
CalendarEvent e = _calendar.AddEvent(_patientInfo, _comment, _appointmentDate, _appointmentDate);
// add the new appointment to the appointments list
_appointments.Items.Add(e);
}
#endregion
}
}
| gpl-3.0 |
gerryai/planning-common | model/src/main/java/org/gerryai/planning/parser/ParserService.java | 2072 | /*
* Gerry AI - Open framework for automated planning
* Copyright (c) 2014 David Edwards <david@more.fool.me.uk>
*
* 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 org.gerryai.planning.parser;
import org.gerryai.planning.model.domain.Domain;
import org.gerryai.planning.model.problem.Problem;
import org.gerryai.planning.parser.error.ParseException;
import java.io.IOException;
import java.io.InputStream;
/**
* Interface for parsing domains and problems described using PDDL.
*/
public interface ParserService {
/**
* Parse an input stream and extract a {@link org.gerryai.planning.model.domain.Domain}.
* @param inputStream the input stream to parse
* @return the result of parsing the file
* @throws java.io.IOException if the input could not be read correctly
* @throws org.gerryai.planning.parser.error.ParseException if there was a syntax error parsing the input
*/
Domain parseDomain(final InputStream inputStream) throws IOException, ParseException;
/**
* Parse an input stream and extract a {@link org.gerryai.planning.model.problem.Problem}.
* @param inputStream the input stream to parse
* @return the result of parsing the file
* @throws java.io.IOException if the input could not be read correctly
* @throws ParseException if there was a syntax error parsing the input
*/
Problem parseProblem(final InputStream inputStream) throws IOException, ParseException;
}
| gpl-3.0 |
emmanuelroussel/stockpile-app | src/store/kits/kits.actions.spec.ts | 1314 | import { TestData } from '../../test-data';
import { createAction } from '../create-action';
import { StoreMock } from '../../mocks';
import { KitsActions } from './kits.actions';
let instance: KitsActions = null;
describe('Kits Actions', () => {
beforeEach(() => {
instance = new KitsActions((<any> new StoreMock));
});
it('is created', () => {
expect(instance).toBeTruthy();
});
it('dispatches action FETCH', () => {
spyOn(instance.store, 'dispatch');
instance.fetchKits();
expect(instance.store.dispatch).toHaveBeenCalledWith(createAction(KitsActions.FETCH));
});
it('dispatches action CREATE', () => {
spyOn(instance.store, 'dispatch');
instance.createKit(TestData.kit);
expect(instance.store.dispatch).toHaveBeenCalledWith(createAction(KitsActions.CREATE, TestData.kit));
});
it('dispatches action UPDATE', () => {
spyOn(instance.store, 'dispatch');
instance.updateKit(TestData.kit);
expect(instance.store.dispatch).toHaveBeenCalledWith(createAction(KitsActions.UPDATE, TestData.kit));
});
it('dispatches action DELETE', () => {
spyOn(instance.store, 'dispatch');
instance.deleteKit(TestData.kit.kitID);
expect(instance.store.dispatch).toHaveBeenCalledWith(createAction(KitsActions.DELETE, TestData.kit.kitID));
});
});
| gpl-3.0 |
zdavis/manifold | api/spec/requests/projects/relationships/resource_imports_spec.rb | 2582 | require "rails_helper"
RSpec.describe "Resource Import API", type: :request do
include_context("authenticated request")
include_context("param helpers")
csv_path = Rails.root.join('spec', 'data','resource_import','resources.csv')
let(:attributes) {
{
source: "attached_data",
data: file_param(csv_path, "text/csv", "resources.csv")
}
}
let(:valid_params) {
build_json_payload(attributes: attributes)
}
let(:project) { FactoryBot.create(:project) }
let(:resource_import) { FactoryBot.create(:resource_import, project: project) }
describe "creates a resource_import model" do
let(:path) { api_v1_project_relationships_resource_imports_path(project) }
let(:api_response) { JSON.parse(response.body) }
before(:each) do
post path, headers: admin_headers, params: valid_params
end
it "sets the creator correctly" do
resource_import = ResourceImport.find api_response["data"]["id"]
expect(resource_import.creator.id).to eq(admin.id)
end
end
describe "updates a resource_import model" do
before(:each) do
@resource_import = FactoryBot.create(:resource_import, project: project)
end
let(:path) { api_v1_project_relationships_resource_import_path(project, @resource_import) }
it "has a 200 SUCCESS status code" do
put path, headers: admin_headers, params: valid_params
expect(response).to have_http_status(200)
end
it "changes the state of the import model" do
valid_params = build_json_payload(attributes: { state: "parsing" })
put path, headers: admin_headers, params: valid_params
@resource_import.reload
expect(@resource_import.state_machine.in_state?(:parsed)).to be true
end
end
describe "sends a single resource import model" do
before(:each) do
@resource_import = FactoryBot.create(:resource_import, project: project)
end
let(:path) { api_v1_project_relationships_resource_import_path(project, @resource_import) }
context "when the user is an admin" do
let(:headers) { admin_headers }
describe "the response" do
it "has a 200 status code" do
get path, headers: headers
expect(response).to have_http_status(200)
end
end
end
context "when the user is a reader" do
let(:headers) { reader_headers }
describe "the response" do
it "has a 403 FORBIDDEN status code" do
get path, headers: headers
expect(response).to have_http_status(403)
end
end
end
end
end
| gpl-3.0 |
jdstrand/snapd | gadget/install/options.go | 1549 | // -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019-2020 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 install
import (
"github.com/snapcore/snapd/asserts"
)
type Options struct {
// Also mount the filesystems after creation
Mount bool
// Encrypt the data partition
Encrypt bool
// KeyFile is the location where the encryption key is written to
KeyFile string
// RecoveryKeyFile is the location where the recovery key is written to
RecoveryKeyFile string
// TPMLockoutAuthFile is the location where the TPM lockout authorization is written to
TPMLockoutAuthFile string
// TPMPolicyUpdateDataFile is the location where the TPM authorization policy update data is written to
TPMPolicyUpdateDataFile string
// KernelPath is the path to the kernel to seal the keyfile to
KernelPath string
// Model is the device model to seal the keyfile to
Model *asserts.Model
// SystemLabel is the recover system label to seal the keyfile to
SystemLabel string
}
| gpl-3.0 |
Georgeto/rmtools | xmatEdit/xmatedit.cpp | 1192 | #include "xmatedit.h"
QTranslator * XmatEdit::german_qt = 0;
QTranslator * XmatEdit::german_app = 0;
QTranslator * XmatEdit::current_qt = 0;
QTranslator * XmatEdit::current_app = 0;
XmatEdit::XmatEdit(int & argc, char * argv[]) : QApplication(argc, argv)
{
delete german_qt;
german_qt = new QTranslator;
german_qt->load("qt_de");
delete german_app;
german_app = new QTranslator;
german_app->load(":/translations/xmatEdit_de");
}
XmatEdit::~XmatEdit() {}
void XmatEdit::setLanguage(const QString & locale)
{
QTranslator * newQtTranslator = 0;
QTranslator * newAppTranslator = 0;
if (locale == "de") {
newQtTranslator = german_qt;
newAppTranslator = german_app;
}
// else...
if (newQtTranslator && newAppTranslator) {
installTranslator(newQtTranslator);
installTranslator(newAppTranslator);
}
if ((current_qt && current_app) && ((current_qt != newQtTranslator) && (current_app != newAppTranslator))) {
removeTranslator(current_qt);
removeTranslator(current_app);
}
current_qt = newQtTranslator;
current_app = newAppTranslator;
}
| gpl-3.0 |
Mikezar/STW6 | ScrewTurnWiki.Core/Tools.cs | 25234 |
using System;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Globalization;
using ScrewTurn.Wiki.PluginFramework;
using System.Reflection;
using System.Net;
namespace ScrewTurn.Wiki {
/// <summary>
/// Contains useful Tools.
/// </summary>
public static class Tools {
/// <summary>
/// Gets all the included files for the HTML Head, such as CSS, JavaScript and Icon pluginAssemblies, for a wiki and namespace.
/// </summary>
/// <param name="wiki">The wiki.</param>
/// <param name="nspace">The namespace (<c>null</c> for the root).</param>
/// <returns>The includes.</returns>
public static string GetIncludes(string wiki, string nspace) {
StringBuilder result = new StringBuilder(300);
string nameTheme = Settings.GetTheme(wiki, nspace);
//result.Append(GetJavaScriptIncludes()); // Moved to Layouts
List<string> cssList = Themes.ListThemeFiles(wiki, nameTheme, ".css");
string firstChunk;
if(cssList != null) {
foreach(string cssFile in cssList) {
if(Path.GetFileName(cssFile).IndexOf("_") != -1) {
firstChunk = Path.GetFileName(cssFile).Substring(0, Path.GetFileName(cssFile).IndexOf("_")).ToLowerInvariant();
if(firstChunk.Equals("screen") || firstChunk.Equals("print") || firstChunk.Equals("all") ||
firstChunk.Equals("aural") || firstChunk.Equals("braille") || firstChunk.Equals("embossed") ||
firstChunk.Equals("handheld") || firstChunk.Equals("projection") || firstChunk.Equals("tty") || firstChunk.Equals("tv")) {
result.Append(@"<link rel=""stylesheet"" media=""" + firstChunk + @""" href=""/" + cssFile + @""" type=""text/css"" />" + "\n");
}
else {
result.Append(@"<link rel=""stylesheet"" href=""/" + cssFile + @""" type=""text/css"" />" + "\n");
}
}
else {
result.Append(@"<link rel=""stylesheet"" href=""/" + cssFile + @""" type=""text/css"" />" + "\n");
}
}
}
List<string> customEditorCss = Themes.ListThemeFiles(wiki, nameTheme, "Editor.css");
if (customEditorCss!= null && customEditorCss.Count>0) result.AppendFormat(@"<link rel=""stylesheet"" href=""/{0}"" type=""text/css"" />" + "\n", customEditorCss[0]);
else result.Append(@"<link rel=""stylesheet"" href=""/Content/Themes/Editor.css"" type=""text/css"" />" + "\n");
// OpenSearch
result.AppendFormat(@"<link rel=""search"" href=""/Search/Opensearch"" type=""application/opensearchdescription+xml"" title=""{0}"" />" + "\n", Settings.GetWikiTitle(wiki) + " - Search");
result.Append(@"<link rel=""stylesheet"" href=""/Content/Themes/prettyPhoto.css"" type=""text/css"" />" + "\n"); // TODO: Move to adjust styles
List<string> jsFiles = Themes.ListThemeFiles(wiki, nameTheme, ".js");
if(jsFiles != null) {
foreach(string jsFile in jsFiles) {
result.Append(@"<script src=""/" + jsFile + @""" type=""text/javascript""></script>" + "\n");
}
}
List<string> iconsList = Themes.ListThemeFiles(wiki, nameTheme, "Icon.");
if(iconsList != null) {
string[] icons = iconsList.ToArray();
if(icons.Length > 0) {
result.Append(@"<link rel=""shortcut icon"" href=""/" + icons[0] + @""" type=""");
switch(icons[0].Substring(icons[0].LastIndexOf('.')).ToLowerInvariant()) {
case ".ico":
result.Append("image/x-icon");
break;
case ".gif":
result.Append("image/gif");
break;
case ".png":
result.Append("image/png");
break;
}
result.Append(@""" />" + "\n");
}
}
// Include HTML Head
result.Append(Settings.GetProvider(wiki).GetMetaDataItem(MetaDataItem.HtmlHead, nspace));
return result.ToString();
}
/// <summary>
/// Gets all the JavaScript files to include.
/// </summary>
/// <returns>The JS files.</returns>
public static string GetJavaScriptIncludes() {
StringBuilder buffer = new StringBuilder(100);
foreach(string js in Directory.GetFiles(GlobalSettings.JsDirectory, "*.js")) {
buffer.Append(@"<script type=""text/javascript"" src=""" + GlobalSettings.JsDirectoryName + "/" + Path.GetFileName(js) + @"""></script>" + "\n");
}
return buffer.ToString();
}
/// <summary>
/// Gets the canonical URL tag for a page.
/// </summary>
/// <param name="requestUrl">The request URL.</param>
/// <param name="currentPageFullName">The full name of the current page.</param>
/// <param name="nspace">The namespace.</param>
/// <returns>The canonical URL, or an empty string if <paramref name="requestUrl"/> is already canonical.</returns>
public static string GetCanonicalUrlTag(string requestUrl, string currentPageFullName, NamespaceInfo nspace) {
string url = "";
string currentWiki = DetectCurrentWiki();
if(nspace == null && currentPageFullName == Settings.GetDefaultPage(currentWiki)) url = Settings.GetMainUrl(currentWiki).ToString();
else url = Settings.GetMainUrl(currentWiki).TrimEnd('/') + "/" + currentPageFullName + GlobalSettings.PageExtension;
// Case sensitive
if(url == requestUrl) return "";
else return "<link rel=\"canonical\" href=\"" + url + "\" />";
}
/// <summary>
/// Converts a byte number into a string, formatted using KB, MB or GB.
/// </summary>
/// <param name="bytes">The # of bytes.</param>
/// <returns>The formatted string.</returns>
public static string BytesToString(long bytes) {
if(bytes < 1024) return bytes.ToString() + " B";
else if(bytes < 1048576) return string.Format("{0:N2} KB", (float)bytes / 1024F);
else if(bytes < 1073741824) return string.Format("{0:N2} MB", (float)bytes / 1048576F);
else return string.Format("{0:N2} GB", (float)bytes / 1073741824F);
}
/// <summary>
/// Computes the Disk Space Usage of a directory.
/// </summary>
/// <param name="dir">The directory.</param>
/// <returns>The used Disk Space, in bytes.</returns>
public static long DiskUsage(string dir) {
string[] files = Directory.GetFiles(dir);
string[] directories = Directory.GetDirectories(dir);
long result = 0;
FileInfo file;
for(int i = 0; i < files.Length; i++) {
file = new FileInfo(files[i]);
result += file.Length;
}
for(int i = 0; i < directories.Length; i++) {
result += DiskUsage(directories[i]);
}
return result;
}
/// <summary>
/// Generates the standard 5-digit Page Version string.
/// </summary>
/// <param name="version">The Page version.</param>
/// <returns>The 5-digit Version string.</returns>
public static string GetVersionString(int version) {
string result = version.ToString();
int len = result.Length;
for(int i = 0; i < 5 - len; i++) {
result = "0" + result;
}
return result;
}
/// <summary>
/// Gets the available Cultures.
/// </summary>
public static string[] AvailableCultures {
get {
// It seems, at least in VS 2008, that for Precompiled Web Sites, the GlobalResources pluginAssemblies that are not the
// default resource (Culture=neutral), get sorted into subdirectories named by the Culture Info name. Every
// assembly in these directories is called "ScrewTurn.Wiki.resources.dll"
// I'm sure it's possible to just use the subdirectory names in the bin directory to get the culture info names,
// however, I'm not sure what other things might get tossed in there by the compiler now or in the future.
// That's why I'm specifically going for the App_GlobalResources.resources.dlls.
// So, get all of the App_GlobalResources.resources.dll pluginAssemblies from bin and recurse subdirectories
string[] dllFiles = Directory.GetFiles(Path.Combine(GlobalSettings.RootDirectory, "bin"), "ScrewTurn.Wiki.resources.dll", SearchOption.AllDirectories);
// List to collect constructed culture names
List<string> cultureNames = new List<string>();
// Manually add en-US culture
CultureInfo enCI = new CultureInfo("en-US");
cultureNames.Add(enCI.Name + "|" + UppercaseInitial(enCI.NativeName) + " - " + enCI.EnglishName);
// For every file we find
// List format: xx-ZZ|Native name (English name)
foreach(string s in dllFiles) {
try {
// Load a reflection only assembly from the filename
Assembly asm = Assembly.ReflectionOnlyLoadFrom(s);
// string for destructive parsing of the assembly's full name
// Which, btw, looks something like this
// App_GlobalResources.resources, Version=0.0.0.0, Culture=zh-cn, PublicKeyToken=null
string fullName = asm.FullName;
// Find the Culture= attribute
int find = fullName.IndexOf("Culture=");
// Remove it and everything prior
fullName = fullName.Substring(find + 8);
// Find the trailing comma
find = fullName.IndexOf(',');
// Remove it and everything after
fullName = fullName.Substring(0, find);
// Fullname should now be the culture info name and we can instantiate the CultureInfo class from it
CultureInfo ci = new CultureInfo(fullName);
// StringBuilders
StringBuilder sb = new StringBuilder();
sb.Append(ci.Name);
sb.Append("|");
sb.Append(UppercaseInitial(ci.NativeName));
sb.Append(" - ");
sb.Append(ci.EnglishName);
// Add the newly constructed Culture string
cultureNames.Add(sb.ToString());
}
catch(Exception ex) {
Log.LogEntry("Error parsing culture info from " + s + Environment.NewLine + ex.Message, EntryType.Error, Log.SystemUsername, null);
}
}
// If for whatever reason every one fails, this will return a 1 element array with the en-US info.
cultureNames.Sort();
return cultureNames.ToArray();
}
}
private static string UppercaseInitial(string value) {
if(value.Length > 0) {
return value[0].ToString().ToUpper(CultureInfo.CurrentCulture) + value.Substring(1);
}
else return "";
}
/// <summary>
/// Gets the current culture.
/// </summary>
public static string CurrentCulture {
get { return CultureInfo.CurrentUICulture.Name; }
}
/// <summary>
/// Get the direction of the current culture.
/// </summary>
/// <returns><c>true</c> if the current culture is RTL, <c>false</c> otherwise.</returns>
public static bool IsRightToLeftCulture() {
return new CultureInfo(CurrentCulture).TextInfo.IsRightToLeft;
}
/// <summary>
/// Computes the Hash of a Username, mixing it with other data, in order to avoid illegal Account activations.
/// </summary>
/// <param name="username">The Username.</param>
/// <param name="email">The email.</param>
/// <param name="dateTime">The date/time.</param>
/// <returns>The secured Hash of the Username.</returns>
public static string ComputeSecurityHash(string username, string email, DateTime dateTime) {
return Hash.ComputeSecurityHash(username, email, dateTime, GlobalSettings.GetMasterPassword());
}
/// <summary>
/// Escapes bad characters in a string (pipes and \n).
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The escaped string.</returns>
public static string EscapeString(string input) {
StringBuilder sb = new StringBuilder(input);
sb.Replace("\r", "");
sb.Replace("\n", "%0A");
sb.Replace("|", "%7C");
return sb.ToString();
}
/// <summary>
/// Unescapes bad characters in a string (pipes and \n).
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The unescaped string.</returns>
public static string UnescapeString(string input) {
StringBuilder sb = new StringBuilder(input);
sb.Replace("%7C", "|");
sb.Replace("%0A", "\n");
return sb.ToString();
}
/// <summary>
/// Generates a random 10-char Password.
/// </summary>
/// <returns>The Password.</returns>
public static string GenerateRandomPassword() {
Random r = new Random();
string password = "";
for(int i = 0; i < 10; i++) {
if(i % 2 == 0)
password += ((char)r.Next(65, 91)).ToString(); // Uppercase letter
else password += ((char)r.Next(97, 123)).ToString(); // Lowercase letter
}
return password;
}
/// <summary>
/// Gets the approximate System Uptime.
/// </summary>
public static TimeSpan SystemUptime {
get {
int t = Environment.TickCount;
if(t < 0) t = t + int.MaxValue;
t = t / 1000;
return TimeSpan.FromSeconds(t);
}
}
/// <summary>
/// Converts a Time Span to string.
/// </summary>
/// <param name="span">The Time Span.</param>
/// <returns>The string.</returns>
public static string TimeSpanToString(TimeSpan span) {
string result = span.Days.ToString() + "d ";
result += span.Hours.ToString() + "h ";
result += span.Minutes.ToString() + "m ";
result += span.Seconds.ToString() + "s";
return result;
}
private static string CleanupPort(string url, string host) {
if(!url.Contains(host)) {
int colonIndex = host.IndexOf(":");
if(colonIndex != -1) {
host = host.Substring(0, colonIndex);
}
}
return host;
}
/// <summary>
/// Automatically replaces the host and port in the URL with those obtained from <see cref="Settings.GetMainUrl"/>.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>The URL with fixed host and port.</returns>
public static Uri FixHost(this Uri url) {
// Make sure the host is replaced only once
string originalUrl = url.ToString();
string originalHost = url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
Uri mainUrl = Settings.GetMainUrlOrDefault(DetectCurrentWiki());
string newHost = mainUrl.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
originalHost = CleanupPort(originalUrl, originalHost);
newHost = CleanupPort(mainUrl.ToString(), newHost);
int hostIndex = originalUrl.IndexOf(originalHost);
string newUrl = originalUrl.Substring(0, hostIndex) + newHost + originalUrl.Substring(hostIndex + originalHost.Length);
return new Uri(newUrl);
}
/// <summary>
/// Gets the current request's URL, with the host already fixed.
/// </summary>
/// <returns>The current URL.</returns>
public static string GetCurrentUrlFixed() {
return HttpContext.Current.Request.Url.FixHost().ToString();
}
/// <summary>
/// Executes URL-encoding, avoiding to use '+' for spaces.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The encoded string.</returns>
public static string UrlEncode(string input) {
if(HttpContext.Current != null && HttpContext.Current.Server != null) return HttpUtility.UrlEncode(input).Replace("+", "%20"); // HttpContext.Current.Server.UrlEncode(input).Replace("+", "%20");
else {
Log.LogEntry("HttpContext.Current or HttpContext.Current.Server were null (Tools.UrlEncode)", EntryType.Warning, Log.SystemUsername, null);
return input;
}
}
/// <summary>
/// Executes URL-decoding, replacing spaces as processed by UrlEncode.
/// </summary>
/// <param name="input">The input string.</param>
/// <returns>The decoded string.</returns>
public static string UrlDecode(string input) {
return HttpContext.Current.Server.UrlDecode(input.Replace("%20", " "));
}
/// <summary>
/// Removes all HTML tags from a text.
/// </summary>
/// <param name="html">The input HTML.</param>
/// <returns>The extracted plain text.</returns>
public static string RemoveHtmlMarkup(string html) {
StringBuilder sb = new StringBuilder(System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", " "));
sb.Replace(" ", " ");
sb.Replace("¶", " ");
sb.Replace(" ", " ");
return sb.ToString();
}
/// <summary>
/// Extracts the directory name from a path used in the Files Storage Providers.
/// </summary>
/// <param name="path">The path, for example '/folder/blah/'.</param>
/// <returns>The directory name, for example 'blah'.</returns>
public static string ExtractDirectoryName(string path) {
path = path.Trim('/');
int idx = path.LastIndexOf("/");
return idx != -1 ? path.Substring(idx + 1) : path;
}
/// <summary>
/// Detects the correct <see cref="T:PageInfo"/> object associated to the current page using the <b>Page</b>, <b>NS</b> and <b>Wiki</b> parameters in the query string.
/// </summary>
/// <param name="loadDefault"><c>true</c> to load the default page of the specified namespace when <b>Page</b> is not specified, <c>false</c> otherwise.</param>
/// <returns>If <b>Page</b> is specified and exists, the correct <see cref="T:PageInfo"/>, otherwise <c>null</c> if <b>loadDefault</b> is <c>false</c>,
/// or the <see cref="T:PageInfo"/> object representing the default page of the specified namespace if <b>loadDefault</b> is <c>true</c>.</returns>
public static string DetectCurrentPage(bool loadDefault) {
string wiki = DetectCurrentWiki();
string nspace = HttpContext.Current.Request["NS"];
NamespaceInfo nsinfo = nspace != null ? Pages.FindNamespace(wiki, nspace) : null;
string page = HttpContext.Current.Request["Page"];
if(string.IsNullOrEmpty(page)) {
if(loadDefault) {
if(nsinfo == null) page = Settings.GetDefaultPage(wiki);
else page = nsinfo.DefaultPageFullName != null ? nsinfo.DefaultPageFullName : "";
}
else return null;
}
string fullName = null;
if(!page.StartsWith(nspace + ".")) fullName = nspace + "." + page;
else fullName = page;
fullName = fullName.Trim('.');
return fullName;
}
/// <summary>
/// Detects the full name of the current page using the <b>Page</b> and <b>NS</b> parameters in the query string.
/// </summary>
/// <returns>The full name of the page, regardless of the existence of the page.</returns>
public static string DetectCurrentFullName() {
string nspace = HttpContext.Current.Request["NS"] != null ? HttpContext.Current.Request["NS"] : "";
string page = HttpContext.Current.Request["Page"] != null ? HttpContext.Current.Request["Page"] : "";
string fullName = null;
if(!page.StartsWith(nspace + ".")) fullName = nspace + "." + page;
else fullName = page;
return fullName.Trim('.');
}
/// <summary>
/// Detects the correct <see cref="T:NamespaceInfo" /> object associated to the current namespace using the <b>NS</b> parameter in the query string.
/// </summary>
/// <param name="wiki">The wiki.</param>
/// <returns>The correct <see cref="T:NamespaceInfo" /> object, or <c>null</c>.</returns>
public static NamespaceInfo DetectCurrentNamespaceInfo(string wiki) {
string nspace = HttpContext.Current.Request["NS"];
NamespaceInfo nsinfo = nspace != null ? Pages.FindNamespace(wiki, nspace) : null;
return nsinfo;
}
/// <summary>
/// Detects the correct <see cref="T:NamespaceInfo" /> object associated to the current namespace using the <b>NS</b> parameter in the query string.
/// </summary>
/// <returns>The correct <see cref="T:NamespaceInfo" /> object, or <c>null</c>.</returns>
public static NamespaceInfo DetectCurrentNamespaceInfo() {
string wiki = DetectCurrentWiki();
return DetectCurrentNamespaceInfo(wiki);
}
/// <summary>
/// Detects the name of the current namespace using the <b>NS</b> parameter in the query string.
/// </summary>
/// <returns>The name of the namespace, or an empty string.</returns>
public static string DetectCurrentNamespace() {
return HttpContext.Current.Request["NS"] != null ? HttpContext.Current.Request["NS"] : "";
}
/// <summary>
/// Detects the name of the current wiki using the <b>Wiki</b> parameter in the query string.
/// </summary>
/// <returns>The name of the wiki, or null.</returns>
public static string DetectCurrentWiki() {
try {
//if (HttpContext.Current.Handler == null) return "root";
return GlobalSettings.Provider.ExtractWikiName(HttpContext.Current.Request.Url.Host);
}
catch(WikiNotFoundException) {
return "root";
}
}
/// <summary>
/// Gets the message ID for HTML anchors.
/// </summary>
/// <param name="messageDateTime">The message date/time.</param>
/// <returns>The ID.</returns>
public static string GetMessageIdForAnchor(DateTime messageDateTime) {
return "MSG_" + messageDateTime.ToString("yyyyMMddHHmmss");
}
/// <summary>
/// Gets the name of a file's directory.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>The name of the item.</returns>
public static string GetDirectoryName(string filename) {
if(filename != null) {
int index = filename.LastIndexOf("/");
if(index > 0) {
string directoryName = filename.Substring(0, index + 1);
if(!directoryName.StartsWith("/")) directoryName = "/" + directoryName;
return directoryName;
}
}
// Assume to navigate in the root directory
return "/";
}
/// <summary>
/// Gets the update status of a component.
/// </summary>
/// <param name="url">The version file URL.</param>
/// <param name="currentVersion">The current version.</param>
/// <param name="newVersion">The new version, if any.</param>
/// <param name="newAssemblyUrl">The URL of the new assembly, if applicable and available.</param>
/// <returns>The update status.</returns>
/// <remarks>This method only works in Full Trust.</remarks>
public static UpdateStatus GetUpdateStatus(string url, string currentVersion, out string newVersion, out string newAssemblyUrl) {
// TODO: Verify usage of WebPermission class
// http://msdn.microsoft.com/en-us/library/system.net.webpermission.aspx
string urlHash = "UpdUrlCache-" + url.GetHashCode().ToString();
try {
string ver = null;
if(HttpContext.Current != null) {
ver = HttpContext.Current.Cache[urlHash] as string;
}
if(ver == null) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
if(res.StatusCode != HttpStatusCode.OK) {
newVersion = null;
newAssemblyUrl = null;
return UpdateStatus.Error;
}
StreamReader sr = new StreamReader(res.GetResponseStream());
ver = sr.ReadToEnd();
sr.Close();
if(HttpContext.Current != null) {
HttpContext.Current.Cache.Add(urlHash, ver, null, DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
string[] lines = ver.Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if(lines.Length == 0) {
newVersion = null;
newAssemblyUrl = null;
return UpdateStatus.Error;
}
string[] versions = lines[0].Split('|');
bool upToDate = false;
for(int i = 0; i < versions.Length; i++) {
ver = versions[i];
if(versions[i].Equals(currentVersion)) {
if(i == versions.Length - 1) upToDate = true;
else upToDate = false;
ver = versions[versions.Length - 1];
break;
}
}
if(upToDate) {
newVersion = null;
newAssemblyUrl = null;
return UpdateStatus.UpToDate;
}
else {
newVersion = ver;
if(lines.Length == 2) newAssemblyUrl = lines[1];
else newAssemblyUrl = null;
return UpdateStatus.NewVersionFound;
}
}
catch(Exception) {
if(HttpContext.Current != null) {
HttpContext.Current.Cache.Add(urlHash, "", null, DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
newVersion = null;
newAssemblyUrl = null;
return UpdateStatus.Error;
}
}
/// <summary>
/// Computes the hash value of a string that is value across application instances and versions.
/// </summary>
/// <param name="value">The string to compute the hash of.</param>
/// <returns>The hash value.</returns>
public static uint HashDocumentNameForTemporaryIndex(string value) {
if(value == null) throw new ArgumentNullException("value");
// sdbm algorithm, borrowed from http://www.cse.yorku.ca/~oz/hash.html
uint hash = 0;
foreach(char c in value) {
// hash(i) = hash(i - 1) * 65599 + str[i]
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
/// <summary>
/// Obfuscates text, replacing each character with its HTML escaped sequence, for example a becomes <c>&#97;</c>.
/// </summary>
/// <param name="input">The input text.</param>
/// <returns>The output obfuscated text.</returns>
public static string ObfuscateText(string input) {
StringBuilder buffer = new StringBuilder(input.Length * 4);
foreach(char c in input) {
buffer.Append("&#" + ((int)c).ToString("D2") + ";");
}
return buffer.ToString();
}
}
/// <summary>
/// Lists legal update statuses.
/// </summary>
public enum UpdateStatus {
/// <summary>
/// Error while retrieving version information.
/// </summary>
Error,
/// <summary>
/// The component is up-to-date.
/// </summary>
UpToDate,
/// <summary>
/// A new version was found.
/// </summary>
NewVersionFound
}
}
| gpl-3.0 |
BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/stripe-5.37.0/lib/stripe/resources/application_fee_refund.rb | 980 | # frozen_string_literal: true
module Stripe
class ApplicationFeeRefund < APIResource
include Stripe::APIOperations::Save
extend Stripe::APIOperations::List
OBJECT_NAME = "fee_refund"
def resource_url
"#{ApplicationFee.resource_url}/#{CGI.escape(fee)}/refunds" \
"/#{CGI.escape(id)}"
end
def self.update(_id, _params = nil, _opts = nil)
raise NotImplementedError,
"Application fee refunds cannot be updated without an " \
"application fee ID. Update an application fee refund using " \
"`ApplicationFee.update_refund('fee_id', 'refund_id', " \
"update_params)`"
end
def self.retrieve(_id, _api_key = nil)
raise NotImplementedError,
"Application fee refunds cannot be retrieved without an " \
"application fee ID. Retrieve an application fee refund using " \
"`ApplicationFee.retrieve_refund('fee_id', 'refund_id')`"
end
end
end
| gpl-3.0 |
laxman-spidey/YouSee.in | yousee_test/donatewaste_graph_total_kg_personal.php | 1150 | <?php
// this file generates Horisontal Bar graph for Waste Donations Received by Items Category in Rs
include("prod_conn.php");
$query = "SELECT
FORMAT(SUM(donationquantity),0) donation_kg,
DATE_FORMAT(MIN(dateofdonation),'%d-%b-%Y') from_date,
DATE_FORMAT(MAX(dateofdonation),'%d-%b-%Y') to_date
FROM donatewaste
WHERE DONOR_ID=".$_SESSION['SESS_DONOR_ID']." AND donationunit=1";
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbdatabase");
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$totaldonation_kg= $row['donation_kg'];
$from_date= $row['from_date'];
$to_date= $row['to_date'];
}
?>
<div align="center" >
<table border="0" style='font-family:"arial"; font-size:12px; width:330px;'>
<th width="50%"></th><th width="50%"></th>
<tr>
<td colspan="2" align="center"><b>My Waste Donations</b><br>from <?php echo $from_date; ?> to <?php echo $to_date; ?></td>
</tr>
<tr>
<td align="right"><img src="images/wastebin.jpg" border="0" /></td>
<td align="left"><h2><?php echo $totaldonation_kg; ?> Kgs</h2></td>
</tr>
</table>
</div>
| gpl-3.0 |
airpaulg/relax-net | RedBranch.Hammock/Document.cs | 2250 | //
// Document.cs
//
// Author:
// Nick Nystrom <nnystrom@gmail.com>
//
// Copyright (c) 2009-2011 Nicholas J. Nystrom
//
// This program 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 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using Newtonsoft.Json;
namespace RedBranch.Hammock
{
public class Document
{
[JsonIgnore] public Session Session { get; set; }
[JsonIgnore] public string Id { get; set; }
[JsonIgnore] public string Revision { get; set; }
[JsonIgnore] public string Location
{
get
{
return Session.Connection.GetDatabaseLocation(Session.Database) +
(Id.StartsWith("_design/")
? "_design/" + Id.Substring(8).Replace("/", "%2F")
: Id.Replace("/", "%2F"));
}
}
public override int GetHashCode()
{
return (Id ?? "/").GetHashCode() ^ (Revision ?? "-").GetHashCode();
}
public override bool Equals(object obj)
{
var d = obj as Document;
return null == d
? base.Equals(obj)
: d.Id == Id &&
d.Revision == Revision;
}
public static string Prefix<TEntity>()
{
return typeof (TEntity).Name.ToLowerInvariant();
}
public static string For<TEntity>(string withId)
{
return string.Format("{0}-{1}", Prefix<TEntity>(), withId);
}
}
public interface IHasDocument
{
[JsonIgnore]
Document Document { get; set; }
}
} | gpl-3.0 |
TheJuiceBTC/BillionDogeHomePage | include/mouseover_js.inc.php | 4604 | <?php
/**
* @version $Id: mouseover_js.inc.php 64 2010-09-12 01:18:42Z ryan $
* @package mds
* @copyright (C) Copyright 2010 Ryan Rhode, All rights reserved.
* @author Ryan Rhode, ryan@milliondollarscript.com
* @license 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/gpl-3.0.html.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Million Dollar Script
* A pixel script for selling pixels on your website.
*
* For instructions see README.txt
*
* Visit our website for FAQs, documentation, a list team members,
* to post any bugs or feature requests, and a community forum:
* http://www.milliondollarscript.com/
*
*/
?>
var strCache = new Array();
var lastStr;
var trip_count = 0;
function getScrollOffest() {
var x,y;
if (self.pageYOffset) // all except Explorer
{
x = self.pageXOffset;
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
x = document.body.scrollLeft;
y = document.body.scrollTop;
}
var pos = new Array();
pos['x'] = x;
pos['y'] = y;
return pos;
}
function sB(e, str, link, aid) {
var bubble = document.getElementById('bubble');
var style = bubble.style
style.visibility='visible';
var offset = getScrollOffest(); // how much the window scrolled?
style.top=e.clientY+10+offset['y']
style.left=e.clientX+10+offset['x']
document.getElementById('content').innerHTML=str;
fillAdContent(aid, document.getElementById('content'));
}
function hI() {
var bubble = document.getElementById('bubble');
var style = bubble.style
style.visibility='hidden';
}
function hideBubble(e) {
//var bubble = document.getElementById('bubble');
//style = bubble.style;
}
function fillAdContent(aid, bubble) {
if (!isBrowserCompatible()) {
return false;
}
// is the content cached?
if (strCache[aid])
{
bubble.innerHTML = strCache[aid];
return true;
}
//////////////////////////////////////////////////
// AJAX Magic.
//////////////////////////////////////////////////
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "<?php echo BASE_HTTP_PATH;?>ga.php?AID="+aid+"<?php
echo "&t=".time(); ?>", true);
//alert("before trup_count:"+trip_count);
if (trip_count != 0){ // trip_count: global variable counts how many times it goes to the server
// waiting state...
return;
}
trip_count++;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
//
//alert(xmlhttp.responseText);
strCache[''+aid] = xmlhttp.responseText
bubble.innerHTML = xmlhttp.responseText;
trip_count--;
}
}
xmlhttp.send(null)
}
function isBrowserCompatible() {
// check if we can XMLHttpRequest
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
if (!xmlhttp) {
return false
}
return true;
}
| gpl-3.0 |
hanaa-abdelgawad/mgc_pos | htdocs/core/lib/usergroups.lib.php | 11101 | <?php
/* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2010-2012 Regis Houssin <regis.houssin@capnetworks.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 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 htdocs/core/lib/usergroups.lib.php
* \brief Ensemble de fonctions de base pour la gestion des utilisaterus et groupes
*/
/**
* Prepare array with list of tabs
*
* @param Object $object Object related to tabs
* @return array Array of tabs to shoc
*/
function user_prepare_head($object)
{
global $langs, $conf, $user;
$langs->load("users");
$canreadperms=true;
if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS))
{
$canreadperms=($user->admin || ($user->id != $object->id && $user->rights->user->user_advance->readperms) || ($user->id == $object->id && $user->rights->user->self_advance->readperms));
}
$h = 0;
$head = array();
$head[$h][0] = DOL_URL_ROOT.'/user/fiche.php?id='.$object->id;
$head[$h][1] = $langs->trans("UserCard");
$head[$h][2] = 'user';
$h++;
if (! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
{
$langs->load("ldap");
$head[$h][0] = DOL_URL_ROOT.'/user/ldap.php?id='.$object->id;
$head[$h][1] = $langs->trans("LDAPCard");
$head[$h][2] = 'ldap';
$h++;
}
if ($canreadperms)
{
$head[$h][0] = DOL_URL_ROOT.'/user/perms.php?id='.$object->id;
$head[$h][1] = $langs->trans("UserRights");
$head[$h][2] = 'rights';
$h++;
}
$head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id;
$head[$h][1] = $langs->trans("UserGUISetup");
$head[$h][2] = 'guisetup';
$h++;
if (! empty($conf->clicktodial->enabled))
{
$head[$h][0] = DOL_URL_ROOT.'/user/clicktodial.php?id='.$object->id;
$head[$h][1] = $langs->trans("ClickToDial");
$head[$h][2] = 'clicktodial';
$h++;
}
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf,$langs,$object,$head,$h,'user');
//Info on users is visible only by internal user
if (empty($user->societe_id))
{
$head[$h][0] = DOL_URL_ROOT.'/user/note.php?id='.$object->id;
$head[$h][1] = $langs->trans("Note");
$head[$h][2] = 'note';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/user/info.php?id='.$object->id;
$head[$h][1] = $langs->trans("Info");
$head[$h][2] = 'info';
$h++;
}
complete_head_from_modules($conf,$langs,$object,$head,$h,'user','remove');
return $head;
}
function group_prepare_head($object)
{
global $langs, $conf, $user;
$canreadperms=true;
if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS))
{
$canreadperms=($user->admin || $user->rights->user->group_advance->readperms);
}
$h = 0;
$head = array();
$head[$h][0] = DOL_URL_ROOT.'/user/group/fiche.php?id='.$object->id;
$head[$h][1] = $langs->trans("GroupCard");
$head[$h][2] = 'group';
$h++;
if (! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE))
{
$langs->load("ldap");
$head[$h][0] = DOL_URL_ROOT.'/user/group/ldap.php?id='.$object->id;
$head[$h][1] = $langs->trans("LDAPCard");
$head[$h][2] = 'ldap';
$h++;
}
if ($canreadperms)
{
$head[$h][0] = DOL_URL_ROOT.'/user/group/perms.php?id='.$object->id;
$head[$h][1] = $langs->trans("GroupRights");
$head[$h][2] = 'rights';
$h++;
}
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf,$langs,$object,$head,$h,'group');
complete_head_from_modules($conf,$langs,$object,$head,$h,'group','remove');
return $head;
}
/**
* Prepare array with list of tabs
*
* @return array Array of tabs to shoc
*/
function user_admin_prepare_head()
{
global $langs, $conf, $user;
$langs->load("users");
$h=0;
$head[$h][0] = DOL_URL_ROOT.'/admin/user.php';
$head[$h][1] = $langs->trans("Parameters");
$head[$h][2] = 'card';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/user/admin/user_extrafields.php';
$head[$h][1] = $langs->trans("ExtraFields");
$head[$h][2] = 'attributes';
$h++;
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf,$langs,$object,$head,$h,'useradmin');
complete_head_from_modules($conf,$langs,$object,$head,$h,'useradmin','remove');
return $head;
}
/**
* Prepare array with list of tabs
*
* @param Object $object Object related to tabs
* @param array $aEntities Entities array
* @return array Array of tabs
*/
function entity_prepare_head($object, $aEntities)
{
global $mc;
$head = array();
foreach($aEntities as $entity)
{
$mc->getInfo($entity);
$head[$entity][0] = $_SERVER['PHP_SELF'].'?id='.$object->id.'&entity='.$entity;
$head[$entity][1] = $mc->label;
$head[$entity][2] = $entity;
}
return $head;
}
/**
* Show list of themes. Show all thumbs of themes
*
* @param User $fuser User concerned or '' for global theme
* @param int $edit 1 to add edit form
* @param boolean $foruserprofile Show for user profile view
* @return void
*/
function show_theme($fuser,$edit=0,$foruserprofile=false)
{
global $conf,$langs,$bc;
//$dirthemes=array(empty($conf->global->MAIN_FORCETHEMEDIR)?'/theme':$conf->global->MAIN_FORCETHEMEDIR.'/theme');
$dirthemes=array('/theme');
if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
{
foreach($conf->modules_parts['theme'] as $reldir)
{
$dirthemes=array_merge($dirthemes,(array) ($reldir.'theme'));
}
}
$dirthemes=array_unique($dirthemes);
// Now dir_themes=array('/themes') or dir_themes=array('/theme','/mymodule/theme')
$selected_theme='';
if (empty($foruserprofile)) $selected_theme=$conf->global->MAIN_THEME;
else $selected_theme=empty($fuser->conf->MAIN_THEME)?'':$fuser->conf->MAIN_THEME;
$colspan=2;
if ($foruserprofile) $colspan=4;
$thumbsbyrow=6;
print '<table class="noborder" width="100%">';
$var=false;
// Title
if ($foruserprofile)
{
print '<tr class="liste_titre"><th width="25%">'.$langs->trans("Parameter").'</th><th width="25%">'.$langs->trans("DefaultValue").'</th>';
print '<th colspan="2"> </th>';
print '</tr>';
print '<tr '.$bc[$var].'>';
print '<td>'.$langs->trans("DefaultSkin").'</td>';
print '<td>'.$conf->global->MAIN_THEME.'</td>';
print '<td align="left" class="nowrap" width="20%"><input '.$bc[$var].' name="check_MAIN_THEME"'.($edit?'':' disabled').' type="checkbox" '.($selected_theme?" checked":"").'> '.$langs->trans("UsePersonalValue").'</td>';
print '<td> </td>';
print '</tr>';
}
else
{
print '<tr class="liste_titre"><th width="35%">'.$langs->trans("DefaultSkin").'</th>';
print '<th align="right">';
$url='http://www.dolistore.com/lang-en/4-skins';
if (preg_match('/fr/i',$langs->defaultlang)) $url='http://www.dolistore.com/lang-fr/4-themes';
//if (preg_match('/es/i',$langs->defaultlang)) $url='http://www.dolistore.com/lang-es/4-themes';
print '<a href="'.$url.'" target="_blank">';
print $langs->trans('DownloadMoreSkins');
print '</a>';
print '</th></tr>';
print '<tr '.$bc[$var].'>';
print '<td>'.$langs->trans("ThemeDir").'</td>';
print '<td>';
foreach($dirthemes as $dirtheme)
{
echo '"'.$dirtheme.'" ';
}
print '</td>';
print '</tr>';
}
$var=!$var;
print '<tr '.$bc[$var].'><td colspan="'.$colspan.'">';
print '<table class="nobordernopadding" width="100%"><tr><td><div align="center">';
$i=0;
foreach($dirthemes as $dir)
{
//print $dirroot.$dir;exit;
$dirtheme=dol_buildpath($dir,0); // This include loop on $conf->file->dol_document_root
$urltheme=dol_buildpath($dir,1);
if (is_dir($dirtheme))
{
$handle=opendir($dirtheme);
if (is_resource($handle))
{
while (($subdir = readdir($handle))!==false)
{
if (is_dir($dirtheme."/".$subdir) && substr($subdir, 0, 1) <> '.'
&& substr($subdir, 0, 3) <> 'CVS' && ! preg_match('/common|phones/i',$subdir))
{
// Disable not stable themes
//if ($conf->global->MAIN_FEATURES_LEVEL < 1 && preg_match('/bureau2crea/i',$subdir)) continue;
print '<div class="inline-block" style="margin-top: 10px; margin-bottom: 10px; margin-right: 20px; margin-left: 20px;">';
$file=$dirtheme."/".$subdir."/thumb.png";
$url=$urltheme."/".$subdir."/thumb.png";
if (! file_exists($file)) $url=$urltheme."/common/nophoto.jpg";
print '<a href="'.$_SERVER["PHP_SELF"].($edit?'?action=edit&theme=':'?theme=').$subdir.(GETPOST("optioncss")?'&optioncss='.GETPOST("optioncss",'alpha',1):'').($fuser?'&id='.$fuser->id:'').'" style="font-weight: normal;" alt="'.$langs->trans("Preview").'">';
if ($subdir == $conf->global->MAIN_THEME) $title=$langs->trans("ThemeCurrentlyActive");
else $title=$langs->trans("ShowPreview");
print '<img src="'.$url.'" border="0" width="80" height="60" alt="'.$title.'" title="'.$title.'" style="margin-bottom: 5px;">';
print '</a><br>';
if ($subdir == $selected_theme)
{
print '<input '.($edit?'':'disabled').' type="radio" '.$bc[$var].' style="border: 0px;" checked name="main_theme" value="'.$subdir.'"> <b>'.$subdir.'</b>';
}
else
{
print '<input '.($edit?'':'disabled').' type="radio" '.$bc[$var].' style="border: 0px;" name="main_theme" value="'.$subdir.'"> '.$subdir;
}
print '</div>';
$i++;
}
}
}
}
}
print '</div></td></tr></table>';
print '</td></tr>';
print '</table>';
}
?>
| gpl-3.0 |
xoreos/xoreos | src/aurora/actionscript/avm_interval.cpp | 2325 | /* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos 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.
*
* xoreos 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 xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* Actionscript native interval functions for AVM.
*/
#include "src/common/uuid.h"
#include "src/aurora/actionscript/avm.h"
#include "src/aurora/actionscript/function.h"
namespace Aurora {
namespace ActionScript {
Variable AVM::setInterval(const std::vector<Variable> arguments) {
// Check for invalid argument sizes.
if (arguments.size() < 2)
throw Common::Exception("AVM::setInterval() Too few arguments given, need at least 3");
FunctionPtr function = arguments[0].as<Function>();
double interval = arguments[1].asNumber();
// If we have more arguments, they should be given to the called function.
std::vector<Variable> functionArguments;
if (arguments.size() > 2) {
std::vector<Variable>::const_iterator iter = arguments.begin();
std::advance(iter, 2);
functionArguments = std::vector<Variable>(iter, arguments.end());
}
auto intervalFun = [this, function, functionArguments]() {
function->call("", *this, functionArguments);
};
uint32_t id = 0;
if (_handler)
id = _handler->setInterval(interval, intervalFun);
return id;
}
Variable AVM::clearInterval(const std::vector<Variable> arguments) {
// Check for invalid argument sizes.
if (arguments.size() != 1)
throw Common::Exception("AVM::clearInterval() Invalid number of arguments, need exactly 1");
uint32_t id = arguments[0].asNumber();
if (_handler)
_handler->clearInterval(id);
return Variable();
}
} // End of namespace ActionScript
} // End of namespace Aurora
| gpl-3.0 |
deesoft/biz3-client | ModuleAsset.php | 618 | <?php
namespace biz\client;
/**
* Description of ModuleAssets
*
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
* @since 1.0
*/
class ModuleAsset extends \yii\web\AssetBundle
{
/**
* @inheritdoc
*/
public $sourcePath = '@biz/client/assets';
/**
* @inheritdoc
*/
public $js = [
'js/master.app.js',
'js/dee.basic.js',
'js/yii.app.js',
'js/angular.app.js',
];
/**
* @inheritdoc
*/
public $depends = [
'yii\web\YiiAsset',
'dee\angular\AngularAsset',
'dee\angular\AngularResourceAsset'
];
} | gpl-3.0 |
ledtvavs/repository.ledtv | zips/addons_xml_generator.py | 2712 | """ downloaded from http://xbmc-addons.googlecode.com/svn/addons/ """
""" addons.xml generator """
import os
import md5
class Generator:
"""
Generates a new addons.xml file from each addons addon.xml file
and a new addons.xml.md5 hash file. Must be run from the root of
the checked-out repo. Only handles single depth folder structure.
"""
def __init__( self ):
# generate files
self._generate_addons_file()
self._generate_md5_file()
# notify user
print "Finished updating addons xml and md5 files"
def _generate_addons_file( self ):
# addon list
addons = os.listdir( "." )
# final addons text
addons_xml = u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<addons>\n"
# loop thru and add each addons addon.xml file
for addon in addons:
try:
# skip any file or .git folder
if ( not os.path.isdir( addon ) or addon == "zips" ): continue
# create path
_path = os.path.join( addon, "addon.xml" )
# split lines for stripping
xml_lines = open( _path, "r" ).read().splitlines()
# new addon
addon_xml = ""
# loop thru cleaning each line
for line in xml_lines:
# skip encoding format line
if ( line.find( "<?xml" ) >= 0 ): continue
# add line
addon_xml += unicode( line.rstrip() + "\n", "utf-8" )
# we succeeded so add to our final addons.xml text
addons_xml += addon_xml.rstrip() + "\n\n"
except Exception, e:
# missing or poorly formatted addon.xml
print "Excluding %s for %s" % ( _path, e, )
# clean and add closing tag
addons_xml = addons_xml.strip() + u"\n</addons>\n"
# save file
self._save_file( addons_xml.encode( "utf-8" ), file="addons.xml" )
def _generate_md5_file( self ):
try:
# create a new md5 hash
m = md5.new( open( "addons.xml" ).read() ).hexdigest()
# save file
self._save_file( m, file="addons.xml.md5" )
except Exception, e:
# oops
print "An error occurred creating addons.xml.md5 file!\n%s" % ( e, )
def _save_file( self, data, file ):
try:
# write data to the file
open( file, "w" ).write( data )
except Exception, e:
# oops
print "An error occurred saving %s file!\n%s" % ( file, e, )
if ( __name__ == "__main__" ):
# start
Generator()
| gpl-3.0 |
GroestlCoin/FoxBot-GRS | src/main/java/co/foxdev/foxbot/permissions/PermissionManager.java | 3010 | /*
* This file is part of Foxbot.
*
* Foxbot 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.
*
* Foxbot 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 Foxbot. If not, see <http://www.gnu.org/licenses/>.
*/
package co.foxdev.foxbot.permissions;
import co.foxdev.foxbot.FoxBot;
import co.foxdev.foxbot.config.yamlconfig.file.FileConfiguration;
import org.pircbotx.User;
import java.util.ArrayList;
import java.util.List;
public class PermissionManager
{
private final FoxBot foxbot;
private List<User> authedUsers = new ArrayList<>();
public PermissionManager(FoxBot foxbot)
{
this.foxbot = foxbot;
}
// Exactly the same as userHasPermission(), except this gives no output.
public boolean userHasQuietPermission(User user, String permission)
{
return checkPerm(user, permission, true);
}
public boolean userHasPermission(User user, String permission)
{
return checkPerm(user, permission, false);
}
private boolean checkPerm(User user, String permission, boolean quiet)
{
String authType = foxbot.getConfig().getMatchUsersByHostmask() ? user.getHostmask() : user.getNick();
FileConfiguration permissions = foxbot.getConfig().getBotPermissions();
if (foxbot.getConfig().getUsersMustBeVerified())
{
if (!authedUsers.contains(user) && user.isVerified())
{
authedUsers.add(user);
}
if (authedUsers.contains(user))
{
if (permissions.getStringList("default").contains(permission))
{
return !permissions.getStringList(authType).contains("-" + permission);
}
return permissions.getStringList(authType).contains(permission) || permissions.getStringList(authType).contains("*");
}
if (!quiet)
{
user.send().notice("You must be logged into nickserv to use bot commands.");
}
return false;
}
if (permissions.getStringList("default").contains(permission))
{
return !permissions.getStringList(authType).contains("-" + permission);
}
return permissions.getStringList(authType).contains(permission) || permissions.getStringList(authType).contains("*");
}
public void removeAuthedUser(User user)
{
if (authedUsers.contains(user))
{
authedUsers.remove(user);
}
}
} | gpl-3.0 |
jembi/openhim-encounter-orchestrator | src/main/java/org/hl7/v3/ActRelationshipReason.java | 771 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ActRelationshipReason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ActRelationshipReason">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="RSON"/>
* <enumeration value="MITGT"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ActRelationshipReason")
@XmlEnum
public enum ActRelationshipReason {
RSON,
MITGT;
public String value() {
return name();
}
public static ActRelationshipReason fromValue(String v) {
return valueOf(v);
}
}
| mpl-2.0 |
usersource/tasks | tasks_phonegap/Tasks/plugins/io.usersource.anno/anno_gec_server/model/user.py | 1735 | __author__ = 'topcircler'
from google.appengine.ext import ndb
from message.user_message import UserMessage
class User(ndb.Model):
"""
Represents user entity.
"""
user_email = ndb.StringProperty() # this field should be unique.
display_name = ndb.StringProperty() # this field should be unique.
password = ndb.StringProperty()
auth_source = ndb.StringProperty() # "Anno" or "Google". If not "Anno", then no password is stored.
@classmethod
def find_user_by_email(cls, email):
return cls.query(User.user_email == email).get()
@classmethod
def find_user_by_display_name(cls, display_name):
return cls.query(User.display_name == display_name).get()
@classmethod
def insert_user(cls, email):
user = User(display_name=email, user_email=email, auth_source='Google')
user.put()
return user
@classmethod
def insert_normal_user(cls, email, username, password):
user = User(user_email=email, display_name=username, password=password, auth_source="Anno")
user.put()
return user
@classmethod
def insert_user(cls, email, username, auth_source):
user = User(user_email=email, display_name=username, auth_source=auth_source)
user.put()
return user
@classmethod
def authenticate(cls, email, password):
query = User.query().filter(cls.user_email == email).filter(cls.password == password)
return query.get() is not None
def to_message(self):
return UserMessage(id=self.key.id(), user_email=self.user_email, display_name=self.display_name,
auth_source=self.auth_source)
| mpl-2.0 |
mozilla/rhino | testsrc/org/mozilla/javascript/tests/Issue129Test.java | 4509 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Token;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.AstRoot;
import org.mozilla.javascript.ast.NodeVisitor;
import org.mozilla.javascript.ast.ParenthesizedExpression;
/** Tests position of ParenthesizedExpression node in source code in different cases. */
public class Issue129Test {
private static final String SOURCE_URI = "issue129test.js";
private Parser parser;
@Before
public void setUp() {
parser = new Parser();
}
@Test
public void testGetPosition() {
String script = "(a);";
AstRoot root = parser.parse(script, SOURCE_URI, 0);
ParenthesizedExprVisitor visitor = new ParenthesizedExprVisitor();
root.visitAll(visitor);
ParenthesizedExpression pe = visitor.getFirstExpression();
assertNotNull(pe);
assertEquals(0, pe.getPosition());
}
@Test
public void testGetLength() {
String script = "(a);";
AstRoot root = parser.parse(script, SOURCE_URI, 0);
ParenthesizedExprVisitor visitor = new ParenthesizedExprVisitor();
root.visitAll(visitor);
ParenthesizedExpression pe = visitor.getFirstExpression();
assertNotNull(pe);
assertEquals(3, pe.getLength());
}
@Test
public void testGetAbsolutePosition() {
String script = "var a = (b).c()";
AstRoot root = parser.parse(script, SOURCE_URI, 0);
ParenthesizedExprVisitor visitor = new ParenthesizedExprVisitor();
root.visitAll(visitor);
ParenthesizedExpression pe = visitor.getFirstExpression();
assertNotNull(pe);
assertEquals(8, pe.getAbsolutePosition());
}
@Test
public void testMultiline() {
String script = "var a =\n" + "b +\n" + "(c +\n" + "d);";
AstRoot root = parser.parse(script, SOURCE_URI, 0);
ParenthesizedExprVisitor visitor = new ParenthesizedExprVisitor();
root.visitAll(visitor);
ParenthesizedExpression pe = visitor.getFirstExpression();
assertNotNull(pe);
assertEquals("(c +\nd)", getFromSource(script, pe));
}
@Test
public void testNested() {
String script = "var a = (b * (c + d));";
AstRoot root = parser.parse(script, SOURCE_URI, 0);
ParenthesizedExprVisitor visitor = new ParenthesizedExprVisitor();
root.visitAll(visitor);
List<ParenthesizedExpression> exprs = visitor.getExpressions();
assertEquals(2, exprs.size());
for (ParenthesizedExpression pe : exprs) {
if (pe.getExpression().getType() == Token.MUL)
assertEquals("(b * (c + d))", getFromSource(script, pe));
else assertEquals("(c + d)", getFromSource(script, pe));
}
}
private String getFromSource(String source, AstNode node) {
return source.substring(
node.getAbsolutePosition(), node.getAbsolutePosition() + node.getLength());
}
/** Visitor stores all visited ParenthesizedExpression nodes. */
private static class ParenthesizedExprVisitor implements NodeVisitor {
private List<ParenthesizedExpression> expressions = new ArrayList<>();
/**
* Gets first encountered ParenthesizedExpression node.
*
* @return First found ParenthesizedExpression node or {@code null} if no nodes of this type
* were found
*/
public ParenthesizedExpression getFirstExpression() {
return expressions.isEmpty() ? null : expressions.get(0);
}
/**
* Gets all found ParenthesizedExpression nodes.
*
* @return Found nodes
*/
public List<ParenthesizedExpression> getExpressions() {
return expressions;
}
@Override
public boolean visit(AstNode node) {
if (node instanceof ParenthesizedExpression)
expressions.add((ParenthesizedExpression) node);
return true;
}
}
}
| mpl-2.0 |
mgk/vault | ui/app/routes/vault/cluster/replication.js | 963 | import Ember from 'ember';
import ClusterRoute from 'vault/mixins/cluster-route';
const { inject } = Ember;
export default Ember.Route.extend(ClusterRoute, {
version: inject.service(),
beforeModel() {
return this.get('version').fetchFeatures().then(() => {
return this._super(...arguments);
});
},
model() {
return this.modelFor('vault.cluster');
},
afterModel(model) {
return Ember.RSVP
.hash({
canEnablePrimary: this.store
.findRecord('capabilities', 'sys/replication/primary/enable')
.then(c => c.get('canUpdate')),
canEnableSecondary: this.store
.findRecord('capabilities', 'sys/replication/secondary/enable')
.then(c => c.get('canUpdate')),
})
.then(({ canEnablePrimary, canEnableSecondary }) => {
Ember.setProperties(model, {
canEnablePrimary,
canEnableSecondary,
});
return model;
});
},
});
| mpl-2.0 |
lamhx393/V9_uit | Android-App/src/com/vp9/util/ParamUtil.java | 11527 | package com.vp9.util;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParamUtil
{
public static int getJsonInt(JSONObject jsonRequest, String code,
int defaultValue) {
int value = defaultValue;
try {
if (jsonRequest != null && jsonRequest.has(code)) {
value = jsonRequest.getInt(code);
}
} catch (JSONException e) {
e.printStackTrace();
return value;
}
return value;
}
public static float getJsonFloat(JSONObject jsonRequest, String code,
float defaultValue) {
float value = defaultValue;
try {
if (jsonRequest != null && jsonRequest.has(code)) {
String strValue = jsonRequest.getString(code);
value = Float.valueOf(strValue);
}
} catch (JSONException e) {
e.printStackTrace();
return value;
}
return value;
}
public static String getJsonString(JSONObject jsonRequest, String code, String defaultValue) {
String value = defaultValue;
try {
if(jsonRequest != null && jsonRequest.has(code)){
value = jsonRequest.getString(code);
}
} catch (JSONException e) {
e.printStackTrace();
return value;
}
return value;
}
public static JSONObject getJson(String body) {
JSONObject jsObj = null;
try {
jsObj = new JSONObject(body);
} catch (JSONException e) {
e.printStackTrace();
return jsObj;
}
return jsObj;
}
public static JSONObject getJsonObject(JSONObject jsonRequest, String code) {
JSONObject jsObj = null;
try {
if(jsonRequest != null && jsonRequest.has(code)){
jsObj = jsonRequest.getJSONObject(code);
}
} catch (JSONException e) {
e.printStackTrace();
return jsObj;
}
return jsObj;
}
public static JSONArray getJSONArray(JSONObject jsonRequest, String code) {
JSONArray jsArray = null;
try {
if(jsonRequest != null && jsonRequest.has(code)){
jsArray = jsonRequest.getJSONArray(code);
}
} catch (JSONException e) {
e.printStackTrace();
return jsArray;
}
return jsArray;
}
public static boolean getJSONBoolean(JSONObject jsonRequest, String code,
boolean defaultValue) {
boolean value = defaultValue;
try {
if(jsonRequest != null && jsonRequest.has(code)){
value = jsonRequest.getBoolean(code);
}
} catch (JSONException e) {
e.printStackTrace();
return value;
}
return value;
}
public static int getValue(Object obj, int defaul)
{
int value = defaul;
if(obj != null)
if(obj instanceof String)
try
{
value = Integer.parseInt(obj.toString());
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Integer)
try
{
value = ((Integer)obj).intValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Long)
try
{
value = ((Long)obj).intValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Double)
try
{
value = ((Double)obj).intValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof BigInteger)
try
{
value = ((BigInteger)obj).intValue();
}
catch(Exception e)
{
value = defaul;
}
return value;
}
public static float getValue(Object obj, float defaul)
{
float value = defaul;
if(obj != null)
if(obj instanceof String)
try
{
value = Float.parseFloat(obj.toString());
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Integer)
try
{
value = ((Integer)obj).floatValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Long)
try
{
value = ((Long)obj).floatValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Double)
try
{
value = ((Double)obj).floatValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof BigInteger)
try
{
value = ((BigInteger)obj).floatValue();
}
catch(Exception e)
{
value = defaul;
}
return value;
}
public static long getValue(Object obj, long defaul)
{
long value = defaul;
if(obj != null)
if(obj instanceof String)
try
{
value = Long.parseLong(obj.toString());
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Long)
try
{
value = ((Long)obj).longValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof Integer)
try
{
value = ((Integer)obj).longValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof BigInteger)
try
{
value = ((BigInteger)obj).longValue();
}
catch(Exception e)
{
value = defaul;
}
return value;
}
public static boolean getValue(Object obj, boolean defaul)
{
boolean value = defaul;
if(obj != null)
if(obj instanceof Boolean)
try
{
value = ((Boolean)obj).booleanValue();
}
catch(Exception e)
{
value = defaul;
}
else
if(obj instanceof String)
try
{
value = Boolean.parseBoolean(obj.toString());
}
catch(Exception e)
{
value = defaul;
}
return value;
}
public static String getValue(Object obj, String defaul)
{
String value = defaul;
if(obj != null)
if(obj instanceof String)
value = ((String)obj).trim();
else
value = obj.toString().trim();
return value;
}
public static int[] converIntArray(String cards, String strSplit)
{
if(cards != null)
{
ArrayList<Integer> intList = new ArrayList<Integer> ();
String strList[] = cards.split(strSplit);
if(strList != null)
{
String as[];
int k = (as = strList).length;
for(int j = 0; j < k; j++)
{
String str = as[j];
try
{
if(str != null)
{
Integer cardCode = Integer.valueOf(str.trim());
intList.add(cardCode);
}
}
catch(Exception e)
{
return null;
}
}
int intArray[] = new int[intList.size()];
for(int i = 0; i < intList.size(); i++)
intArray[i] = ((Integer)intList.get(i)).intValue();
return intArray;
} else
{
return null;
}
} else
{
return null;
}
}
public static int[] converIntArray(String cards, String strSplit, int min, int max)
{
if(cards != null)
{
ArrayList<Integer> intList = new ArrayList<Integer> ();
String strList[] = cards.split(strSplit);
if(strList != null)
{
String as[];
int k = (as = strList).length;
for(int j = 0; j < k; j++)
{
String str = as[j];
try
{
if(str != null)
{
Integer cardCode = Integer.valueOf(str.trim());
if(cardCode.intValue() >= 0 && cardCode.intValue() <= max)
intList.add(cardCode);
}
}
catch(Exception exception) { }
}
int intArray[] = new int[intList.size()];
for(int i = 0; i < intList.size(); i++)
intArray[i] = ((Integer)intList.get(i)).intValue();
return intArray;
} else
{
return null;
}
} else
{
return null;
}
}
public static Date getDate(String strDate)
{
Date date = null;
try
{
if(strDate != null)
{
SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
date = formatter.parse(strDate);
}
}
catch(ParseException e)
{
e.printStackTrace();
}
return date;
}
public static String getDate(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strdate = dateFormat.format(date);
return strdate;
}
public static int[] toIntArray(String videoid_list) {
ArrayList<Integer> intArray = new ArrayList<Integer>();
if(videoid_list != null){
String[] strVideoIds = videoid_list.split(",");
if(strVideoIds != null && strVideoIds.length > 0){
for(int i = 0; i < strVideoIds.length; i++){
intArray.add(ParamUtil.getValue(strVideoIds[i].trim(), -1));
}
}
}
int[] intValues = new int[intArray.size()];
for(int i = 0; i < intArray.size(); i++){
intValues[i] = intArray.get(i);
}
return intValues;
}
} | mpl-2.0 |
mahinthjoe/bedrock | media/js/firefox/os/devices.js | 8708 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// create namespace
if (typeof window.Mozilla === 'undefined') {
window.Mozilla = {};
}
;(function($, Mozilla) {
'use strict';
window.dataLayer = window.dataLayer || [];
var COUNTRY_CODE = '';
var selectedDevice;
// Will be used when color pickers are activated
//var isSmallViewport = $(window).width() < 760;
//var isTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints || navigator.maxTouchPoints || isSmallViewport;
var $purchaseDeviceButtons = $('.purchase-button');
var $locationSelect = $('#location');
var $deviceThumbnails = $('.device-thumbnail');
var $deviceDetailLists = $('.device-detail-list');
var $deviceDetails = $('.device-detail');
var $providerTextSingle = $('#provider-text-single');
var $providerTextMulti = $('#provider-text-multi');
var $providerLinks = $('#provider-links');
// create namespace
if (typeof Mozilla.FxOs === 'undefined') {
Mozilla.FxOs = {};
}
// smooth scrolling for device type nav
$('#device-nav a').on('click', function(e) {
e.preventDefault();
var target = $(this).attr('href');
$('html, body').animate({
scrollTop: $(target).offset().top - 100
}, 400);
});
// select available devices & set modal partner content based on chosen/detected location
var selectDevicesAndSetPartnerContent = function() {
var $provider = $providerLinks.find('.provider[data-country="' + COUNTRY_CODE + '"]');
// de-select all devices
$deviceThumbnails.removeClass('available');
if (COUNTRY_CODE !== '' && $provider.length > 0) {
// make sure all provider links are hidden
$providerLinks.find('.provider').hide();
if ($provider.find('li').length > 1) {
$providerTextSingle.hide();
$providerTextMulti.show();
} else {
$providerTextSingle.show();
$providerTextMulti.hide();
}
// make sure no option is selected
$locationSelect.find('option:selected').prop('selected', false);
// select the current COUNTRY_CODE
$locationSelect.find('option[value="' + COUNTRY_CODE + '"]').prop('selected', 'selected');
$purchaseDeviceButtons.prop('disabled', false);
for (var device in Mozilla.FxOs.Devices) {
if ($.inArray(COUNTRY_CODE, Mozilla.FxOs.Devices[device].countries) > -1) {
$('.device-thumbnail[href="#' + device + '"]').addClass('available');
}
}
// show the provider applicable for the user country.
$provider.show();
} else {
$purchaseDeviceButtons.prop('disabled', true);
}
};
/*
* Track telecom provider link clicks/page exits in Google Analytics
*/
// setup GA event tracking on telecom provider exit links
$('#provider-links a').attr({'data-element-action': 'overlay exit'});
/*
* Disable/enable mozilla-pagers.js
*/
var togglePagers = function(enable) {
if (enable) {
Mozilla.Pager.createPagers();
} else {
Mozilla.Pager.destroyPagers();
}
};
// wire up location select
$locationSelect.on('change', function() {
COUNTRY_CODE = $locationSelect.val();
selectDevicesAndSetPartnerContent();
window.dataLayer.push({
event: 'device-drop-down',
countryCode: COUNTRY_CODE,
nonInteraction: false
});
});
// wire up purchase button
$purchaseDeviceButtons.attr('data-track', 'true').on('click', function(e) {
e.preventDefault();
Mozilla.Modal.createModal(this, $('#get-device'), {
allowScroll: false,
title: '<img src="/media/img/firefox/os/logo/firefox-os-white.png" alt="mozilla" />'
});
});
// wire up thumbnail select
$('.device-thumbnails').on('click', '.device-thumbnail', function(e) {
var $this = $(this);
// make sure device has specs (coming soon devices may not have specs)
var hasSpecs = $this.data('specs') !== false;
if (hasSpecs) {
selectedDevice = $this.attr('href').replace(/#/gi, '');
var $targetDevice = $('#' + selectedDevice);
if (!$targetDevice.is(':visible')) {
$deviceThumbnails.removeClass('selected');
$this.addClass('selected');
$deviceDetailLists.slideUp('fast', function() {
setTimeout(function() {
$deviceDetails.hide();
$targetDevice.show();
$targetDevice.parents('.device-detail-list:first').slideDown('fast');
}, 200);
});
window.dataLayer.push({
'event': 'device-interaction',
'deviceName': selectedDevice + ' Interactions',
'browserAction': 'Open Features',
deviceSelected: selectedDevice
});
}
} else {
e.preventDefault();
}
});
// wire up device detail close
$('.device-detail-close').on('click', function(e) {
e.preventDefault();
$deviceThumbnails.removeClass('selected');
$(this).parents('.device-detail-list:first').slideUp('fast', function() {
$deviceDetails.hide();
});
window.dataLayer.push({
event: 'device-interaction',
deviceName: selectedDevice + ' Interactions',
browserAction: 'Close Features',
deviceSelected: null
});
});
/*
Color pickers disabled until image assets are available
// enable color pickers
$('.color-picker').on('click', 'a', function(e) {
e.preventDefault();
var $this = $(this);
var $phoneImage = $this.parents('.device-details').find('.image img');
$phoneImage.attr('src', $this.data('image'));
});
// enable tooltips on color pickers for non-touch screens
if (!isTouch) {
$('.color-picker a').tipsy();
}
*/
// only if coming from /firefox/os/, detect country
if (/firefox\/os\/$/.test(document.referrer)) {
$.getScript('//geo.mozilla.org/country.js', function() {
var $provider;
try {
COUNTRY_CODE = geoip_country_code().toLowerCase();
} catch (e) {
COUNTRY_CODE = '';
}
$provider = $providerLinks.find('.provider[data-country="' + COUNTRY_CODE + '"]');
if (COUNTRY_CODE !== '' && $provider.length > 0) {
window.dataLayer.push({
event: 'device-drop-down',
countryCode: COUNTRY_CODE,
nonInteraction: true
});
selectDevicesAndSetPartnerContent();
}
});
}
// hide/disable pagers in mobile view
if (typeof matchMedia !== 'undefined') {
var queryIsMobile = matchMedia('(max-width: 480px)');
setTimeout(function() {
if (!queryIsMobile.matches) {
togglePagers(true);
}
}, 500);
queryIsMobile.addListener(function(mq) {
if (mq.matches) {
togglePagers(false);
} else {
togglePagers(true);
}
});
}
// display specific device if in URL hash
if (window.location.hash !== '') {
setTimeout(function() {
var $deviceThumb = $('.device-thumbnail[href="' + window.location.hash + '"]');
if ($deviceThumb.length) {
$deviceThumb.trigger('click');
$('html, body').animate({
scrollTop: $deviceThumb.offset().top
}, 600);
}
}, 500);
}
// GA specific interactions
// track all 'regular' links (non-CTA, non-device)
$('.standard-link').attr('data-track', 'true');
// track mozilla pager tab clicks
$('.pager-tabs').on('click', 'a', function() {
window.dataLayer.push({
event: 'device-interaction',
deviceName: selectedDevice + ' Interactions',
browserAction: $(this).data('label') + ' Tab'
});
});
})(window.jQuery, window.Mozilla);
| mpl-2.0 |
servinglynk/servinglynk-hmis | hmis-model-v2015/src/main/java/com/servinglynk/hmis/warehouse/dao/MedicalassistanceDaoImpl.java | 8902 | /**
*
*/
package com.servinglynk.hmis.warehouse.dao;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.servinglynk.hmis.warehouse.base.util.ErrorType;
import com.servinglynk.hmis.warehouse.domain.ExportDomain;
import com.servinglynk.hmis.warehouse.domain.Sources.Source.Export.MedicalAssistance;
import com.servinglynk.hmis.warehouse.domain.SyncDomain;
import com.servinglynk.hmis.warehouse.enums.DataCollectionStageEnum;
import com.servinglynk.hmis.warehouse.enums.MedicalassistanceAdapEnum;
import com.servinglynk.hmis.warehouse.enums.MedicalassistanceHivaidsassistanceEnum;
import com.servinglynk.hmis.warehouse.enums.MedicalassistanceNoadapreasonEnum;
import com.servinglynk.hmis.warehouse.enums.MedicalassistanceNohivaidsassistancereasonEnum;
import com.servinglynk.hmis.warehouse.model.v2015.Enrollment;
import com.servinglynk.hmis.warehouse.model.v2015.Error2015;
import com.servinglynk.hmis.warehouse.model.v2015.HmisBaseModel;
import com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance;
import com.servinglynk.hmis.warehouse.util.BasicDataGenerator;
/**
* @author Sandeep
*
*/
public class MedicalassistanceDaoImpl extends ParentDaoImpl implements
MedicalassistanceDao {
private static final Logger logger = LoggerFactory
.getLogger(MedicalassistanceDaoImpl.class);
/* (non-Javadoc)
* @see com.servinglynk.hmis.warehouse.dao.ParentDao#hydrate(com.servinglynk.hmis.warehouse.dao.Sources.Source.Export, java.util.Map)
*/
@Override
public void hydrateStaging(ExportDomain domain , Map<String,HmisBaseModel> exportModelMap, Map<String,HmisBaseModel> relatedModelMap) throws Exception {
List<MedicalAssistance> medicalAssistanceList = domain.getExport().getMedicalAssistance();
com.servinglynk.hmis.warehouse.model.v2015.Export exportEntity = (com.servinglynk.hmis.warehouse.model.v2015.Export) getModel(com.servinglynk.hmis.warehouse.model.v2015.Export.class,String.valueOf(domain.getExport().getExportID()),getProjectGroupCode(domain),false,exportModelMap, domain.getUpload().getId());
Data data =new Data();
Map<String,HmisBaseModel> modelMap = getModelMap(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class, getProjectGroupCode(domain));
if(medicalAssistanceList !=null && !medicalAssistanceList.isEmpty())
{
for(MedicalAssistance medicalAssistance : medicalAssistanceList)
{
Medicalassistance medicalassistanceModel = null;
try {
medicalassistanceModel = getModelObject(domain, medicalAssistance,data,modelMap);
medicalassistanceModel.setDateCreatedFromSource(BasicDataGenerator.getLocalDateTime(medicalAssistance.getDateCreated()));
medicalassistanceModel.setDateUpdatedFromSource(BasicDataGenerator.getLocalDateTime(medicalAssistance.getDateUpdated()));
medicalassistanceModel.setAdap(MedicalassistanceAdapEnum.lookupEnum(BasicDataGenerator.getStringValue(medicalAssistance.getADAP())));
medicalassistanceModel.setHivaidsassistance(MedicalassistanceHivaidsassistanceEnum.lookupEnum(BasicDataGenerator.getStringValue(medicalAssistance.getHIVAIDSAssistance())));
medicalassistanceModel.setNoadapreason(MedicalassistanceNoadapreasonEnum.lookupEnum(BasicDataGenerator.getStringValue(medicalAssistance.getNoADAPReason())));
medicalassistanceModel.setNohivaidsassistancereason(MedicalassistanceNohivaidsassistancereasonEnum.lookupEnum(BasicDataGenerator.getStringValue(medicalAssistance.getNoHIVAIDSAssistanceReason())));
Enrollment enrollmentModel = (Enrollment) getModel(Enrollment.class, medicalAssistance.getProjectEntryID(),getProjectGroupCode(domain),true,relatedModelMap, domain.getUpload().getId());
medicalassistanceModel.setEnrollmentid(enrollmentModel);
medicalassistanceModel.setExport(exportEntity);
medicalassistanceModel.setInformationDate(BasicDataGenerator.getLocalDateTime(medicalAssistance.getInformationDate()));
medicalassistanceModel.setDataCollectionStage(DataCollectionStageEnum.lookupEnum(BasicDataGenerator.getStringValue(medicalAssistance.getDataCollectionStage())));
performSaveOrUpdate(medicalassistanceModel);
}catch(Exception e){
String errorMessage = "Exception beause of the medicalAssistance::"+medicalAssistance.getMedicalAssistanceID() +" Exception ::"+e.getMessage();
if(medicalassistanceModel != null){
Error2015 error = new Error2015();
error.model_id = medicalassistanceModel.getId();
error.bulk_upload_ui = domain.getUpload().getId();
error.project_group_code = domain.getUpload().getProjectGroupCode();
error.source_system_id = medicalassistanceModel.getSourceSystemId();
error.type = ErrorType.ERROR;
error.error_description = errorMessage;
error.date_created = medicalassistanceModel.getDateCreated();
performSave(error);
}
logger.error(errorMessage);
}
}
}
hydrateBulkUploadActivityStaging(data.i,data.j,data.ignore, com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class.getSimpleName(), domain,exportEntity);
}
public com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance getModelObject(ExportDomain domain, MedicalAssistance medicalassistance ,Data data, Map<String,HmisBaseModel> modelMap) {
com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance modelFromDB = null;
// We always insert for a Full refresh and update if the record exists for Delta refresh
if(!isFullRefresh(domain))
modelFromDB = (com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance) getModel(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class, medicalassistance.getMedicalAssistanceID(), getProjectGroupCode(domain),false,modelMap, domain.getUpload().getId());
if(modelFromDB == null) {
modelFromDB = new com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance();
modelFromDB.setId(UUID.randomUUID());
modelFromDB.setRecordToBeInserted(true);
}
com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance model = new com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance();
//org.springframework.beans.BeanUtils.copyProperties(modelFromDB, model);
model.setDateUpdatedFromSource(BasicDataGenerator.getLocalDateTime(medicalassistance.getDateUpdated()));
performMatch(domain, modelFromDB, model, data);
hydrateCommonFields(model, domain,medicalassistance.getMedicalAssistanceID(),data);
return model;
}
@Override
public void hydrateHBASE(SyncDomain syncDomain) {
// TODO Auto-generated method stub
}
public com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance createMedicalassistance(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance medicalassistance){
medicalassistance.setId(UUID.randomUUID());
insert(medicalassistance);
return medicalassistance;
}
public com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance updateMedicalassistance(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance medicalassistance){
update(medicalassistance);
return medicalassistance;
}
public void deleteMedicalassistance(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance medicalassistance){
delete(medicalassistance);
}
public com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance getMedicalassistanceById(UUID medicalassistanceId){
DetachedCriteria criteria=DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class);
criteria.add(Restrictions.eq("id", medicalassistanceId));
List<com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance> entities = (List<com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance>) findByCriteria(criteria);
if(!entities.isEmpty()) return entities.get(0);
return null;
}
public List<com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance> getAllEnrollmentMedicalassistances(UUID enrollmentId,Integer startIndex, Integer maxItems){
DetachedCriteria criteria=DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class);
criteria.createAlias("enrollmentid", "enrollmentid");
criteria.add(Restrictions.eq("enrollmentid.id", enrollmentId));
return (List<com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance>) findByCriteria(criteria,startIndex,maxItems);
}
public long getEnrollmentMedicalassistancesCount(UUID enrollmentId){
DetachedCriteria criteria=DetachedCriteria.forClass(com.servinglynk.hmis.warehouse.model.v2015.Medicalassistance.class);
criteria.createAlias("enrollmentid", "enrollmentid");
criteria.add(Restrictions.eq("enrollmentid.id", enrollmentId));
return countRows(criteria);
}
}
| mpl-2.0 |
swatilk/fxa-content-server | app/scripts/models/auth_brokers/fx-ios-v2.js | 1094 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* The auth broker to coordinate authenticating for Sync when
* embedded in the Firefox for iOS 2.0.
*/
define(function (require, exports, module) {
'use strict';
var _ = require('underscore');
var Constants = require('lib/constants');
var FxDesktopV1AuthenticationBroker = require('models/auth_brokers/fx-desktop-v1');
var proto = FxDesktopV1AuthenticationBroker.prototype;
var FxiOSV2AuthenticationBroker = FxDesktopV1AuthenticationBroker.extend({
defaultCapabilities: _.extend({}, proto.defaultCapabilities, {
chooseWhatToSyncCheckbox: false,
chooseWhatToSyncWebV1: {
engines: Constants.DEFAULT_DECLINED_ENGINES
},
convertExternalLinksToText: true,
emailVerificationMarketingSnippet: false,
syncPreferencesNotification: true
}),
type: 'fx-ios-v2'
});
module.exports = FxiOSV2AuthenticationBroker;
});
| mpl-2.0 |
TiWinDeTea/Raoul-the-Game | src/main/java/com/github/tiwindetea/raoulthegame/model/items/StorableObjectType.java | 1462 | //////////////////////////////////////////////////////////////////////////////////
// //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/. //
// //
//////////////////////////////////////////////////////////////////////////////////
package com.github.tiwindetea.raoulthegame.model.items;
/**
* StorableObjectType
*
* @author Lucas LAZARE
*/
public enum StorableObjectType {
/**
* Weapon storable object type.
*/
WEAPON,
/**
* Armor storable object type.
*/
ARMOR,
/**
* Consumable storable object type.
*/
CONSUMABLE;
/**
* Parses a storable object type.
*
* @param str a storable object type's string
* @return the storable object type, or null.
*/
public static StorableObjectType parseStorableObjectType(String str) {
str.toUpperCase();
switch (str) {
case "WEAPON":
return WEAPON;
case "ARMOR":
return ARMOR;
case "CONSUMABLE":
return CONSUMABLE;
default:
return null;
}
}
}
| mpl-2.0 |
legatoproject/legato-docs | 15_01_1/search/files_0.js | 4659 | var searchData=
[
['le_5fantenna_5finterface_2eh',['le_antenna_interface.h',['../le__antenna__interface_8h.html',1,'']]],
['le_5fargs_2eh',['le_args.h',['../le__args_8h.html',1,'']]],
['le_5faudio_5finterface_2eh',['le_audio_interface.h',['../le__audio__interface_8h.html',1,'']]],
['le_5favc_5finterface_2eh',['le_avc_interface.h',['../le__avc__interface_8h.html',1,'']]],
['le_5fbasics_2eh',['le_basics.h',['../le__basics_8h.html',1,'']]],
['le_5fcellnet_5finterface_2eh',['le_cellnet_interface.h',['../le__cellnet__interface_8h.html',1,'']]],
['le_5fcfg_5finterface_2eh',['le_cfg_interface.h',['../le__cfg__interface_8h.html',1,'']]],
['le_5fcfgadmin_5finterface_2eh',['le_cfgAdmin_interface.h',['../le__cfg_admin__interface_8h.html',1,'']]],
['le_5fclock_2eh',['le_clock.h',['../le__clock_8h.html',1,'']]],
['le_5fdata_5finterface_2eh',['le_data_interface.h',['../le__data__interface_8h.html',1,'']]],
['le_5fdir_2eh',['le_dir.h',['../le__dir_8h.html',1,'']]],
['le_5fdoublylinkedlist_2eh',['le_doublyLinkedList.h',['../le__doubly_linked_list_8h.html',1,'']]],
['le_5fecall_5finterface_2eh',['le_ecall_interface.h',['../le__ecall__interface_8h.html',1,'']]],
['le_5feventloop_2eh',['le_eventLoop.h',['../le__event_loop_8h.html',1,'']]],
['le_5ffilelock_2eh',['le_fileLock.h',['../le__file_lock_8h.html',1,'']]],
['le_5ffwupdate_5finterface_2eh',['le_fwupdate_interface.h',['../le__fwupdate__interface_8h.html',1,'']]],
['le_5fgnss_5finterface_2eh',['le_gnss_interface.h',['../le__gnss__interface_8h.html',1,'']]],
['le_5fhashmap_2eh',['le_hashmap.h',['../le__hashmap_8h.html',1,'']]],
['le_5fhex_2eh',['le_hex.h',['../le__hex_8h.html',1,'']]],
['le_5finfo_5finterface_2eh',['le_info_interface.h',['../le__info__interface_8h.html',1,'']]],
['le_5fips_5finterface_2eh',['le_ips_interface.h',['../le__ips__interface_8h.html',1,'']]],
['le_5flog_2eh',['le_log.h',['../le__log_8h.html',1,'']]],
['le_5fmcc_5fcall_5finterface_2eh',['le_mcc_call_interface.h',['../le__mcc__call__interface_8h.html',1,'']]],
['le_5fmcc_5fprofile_5finterface_2eh',['le_mcc_profile_interface.h',['../le__mcc__profile__interface_8h.html',1,'']]],
['le_5fmdc_5finterface_2eh',['le_mdc_interface.h',['../le__mdc__interface_8h.html',1,'']]],
['le_5fmdmdefs_5finterface_2eh',['le_mdmDefs_interface.h',['../le__mdm_defs__interface_8h.html',1,'']]],
['le_5fmem_2eh',['le_mem.h',['../le__mem_8h.html',1,'']]],
['le_5fmessaging_2eh',['le_messaging.h',['../le__messaging_8h.html',1,'']]],
['le_5fmrc_5finterface_2eh',['le_mrc_interface.h',['../le__mrc__interface_8h.html',1,'']]],
['le_5fmutex_2eh',['le_mutex.h',['../le__mutex_8h.html',1,'']]],
['le_5fpath_2eh',['le_path.h',['../le__path_8h.html',1,'']]],
['le_5fpathiter_2eh',['le_pathIter.h',['../le__path_iter_8h.html',1,'']]],
['le_5fpm_5finterface_2eh',['le_pm_interface.h',['../le__pm__interface_8h.html',1,'']]],
['le_5fpos_5finterface_2eh',['le_pos_interface.h',['../le__pos__interface_8h.html',1,'']]],
['le_5fposctrl_5finterface_2eh',['le_posCtrl_interface.h',['../le__pos_ctrl__interface_8h.html',1,'']]],
['le_5fprint_2eh',['le_print.h',['../le__print_8h.html',1,'']]],
['le_5fsaferef_2eh',['le_safeRef.h',['../le__safe_ref_8h.html',1,'']]],
['le_5fsemaphore_2eh',['le_semaphore.h',['../le__semaphore_8h.html',1,'']]],
['le_5fsignals_2eh',['le_signals.h',['../le__signals_8h.html',1,'']]],
['le_5fsim_5finterface_2eh',['le_sim_interface.h',['../le__sim__interface_8h.html',1,'']]],
['le_5fsinglylinkedlist_2eh',['le_singlyLinkedList.h',['../le__singly_linked_list_8h.html',1,'']]],
['le_5fsms_5finterface_2eh',['le_sms_interface.h',['../le__sms__interface_8h.html',1,'']]],
['le_5fsup_5fctrl_5finterface_2eh',['le_sup_ctrl_interface.h',['../le__sup__ctrl__interface_8h.html',1,'']]],
['le_5fsup_5fstate_5finterface_2eh',['le_sup_state_interface.h',['../le__sup__state__interface_8h.html',1,'']]],
['le_5fsup_5fwdog_5finterface_2eh',['le_sup_wdog_interface.h',['../le__sup__wdog__interface_8h.html',1,'']]],
['le_5ftemp_5finterface_2eh',['le_temp_interface.h',['../le__temp__interface_8h.html',1,'']]],
['le_5ftest_2eh',['le_test.h',['../le__test_8h.html',1,'']]],
['le_5fthread_2eh',['le_thread.h',['../le__thread_8h.html',1,'']]],
['le_5ftimer_2eh',['le_timer.h',['../le__timer_8h.html',1,'']]],
['le_5futf8_2eh',['le_utf8.h',['../le__utf8_8h.html',1,'']]],
['le_5fvoicecall_5finterface_2eh',['le_voicecall_interface.h',['../le__voicecall__interface_8h.html',1,'']]],
['le_5fwdog_5finterface_2eh',['le_wdog_interface.h',['../le__wdog__interface_8h.html',1,'']]],
['legato_2eh',['legato.h',['../legato_8h.html',1,'']]]
];
| mpl-2.0 |
koutstore/KS-theme-en | updates/pre-update-data.js | 148 | // This file is used for testing updates before they go live
window.forumactif_edge_version_data = [
'1.0.0-beta',
'1.0.0-beta.1',
'1.0.0'
];
| mpl-2.0 |
sharidas/core | settings/Panels/Admin/Status.php | 1178 | <?php
/**
* @author Martin Mattel <martin.mattel@diemattels.at>
*
* @copyright Copyright (c) 2017, ownCloud GmbH
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Settings\Panels\Admin;
use OCP\Settings\ISettings;
use OCP\Template;
class Status implements ISettings {
public function getPriority() {
return 0;
}
public function getPanel() {
$tmpl = new Template('settings', 'panels/admin/status');
$values = \OCP\Util::getStatusInfo();
$tmpl->assign('showStatus', $values);
return $tmpl;
}
public function getSectionID() {
return 'general';
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/CancerContactSearchCriteriaVo.java | 11051 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo;
public class CancerContactSearchCriteriaVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public CancerContactSearchCriteriaVo()
{
}
public CancerContactSearchCriteriaVo(ims.oncology.vo.beans.CancerContactSearchCriteriaVoBean bean)
{
this.hcplite = bean.getHcpLite() == null ? null : bean.getHcpLite().buildVo();
this.hcpdiscipline = bean.getHCPDiscipline() == null ? null : ims.core.vo.lookups.HcpDisType.buildLookup(bean.getHCPDiscipline());
this.datefrom = bean.getDateFrom() == null ? null : bean.getDateFrom().buildDate();
this.dateto = bean.getDateTo() == null ? null : bean.getDateTo().buildDate();
this.carecontextref = bean.getCareContextRef() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContextRef().getId()), bean.getCareContextRef().getVersion());
this.episodeofcare = bean.getEpisodeOfCare() == null ? null : new ims.core.admin.vo.EpisodeOfCareRefVo(new Integer(bean.getEpisodeOfCare().getId()), bean.getEpisodeOfCare().getVersion());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.oncology.vo.beans.CancerContactSearchCriteriaVoBean bean)
{
this.hcplite = bean.getHcpLite() == null ? null : bean.getHcpLite().buildVo(map);
this.hcpdiscipline = bean.getHCPDiscipline() == null ? null : ims.core.vo.lookups.HcpDisType.buildLookup(bean.getHCPDiscipline());
this.datefrom = bean.getDateFrom() == null ? null : bean.getDateFrom().buildDate();
this.dateto = bean.getDateTo() == null ? null : bean.getDateTo().buildDate();
this.carecontextref = bean.getCareContextRef() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContextRef().getId()), bean.getCareContextRef().getVersion());
this.episodeofcare = bean.getEpisodeOfCare() == null ? null : new ims.core.admin.vo.EpisodeOfCareRefVo(new Integer(bean.getEpisodeOfCare().getId()), bean.getEpisodeOfCare().getVersion());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.oncology.vo.beans.CancerContactSearchCriteriaVoBean bean = null;
if(map != null)
bean = (ims.oncology.vo.beans.CancerContactSearchCriteriaVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.oncology.vo.beans.CancerContactSearchCriteriaVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public boolean getHcpLiteIsNotNull()
{
return this.hcplite != null;
}
public ims.core.vo.HcpLiteVo getHcpLite()
{
return this.hcplite;
}
public void setHcpLite(ims.core.vo.HcpLiteVo value)
{
this.isValidated = false;
this.hcplite = value;
}
public boolean getHCPDisciplineIsNotNull()
{
return this.hcpdiscipline != null;
}
public ims.core.vo.lookups.HcpDisType getHCPDiscipline()
{
return this.hcpdiscipline;
}
public void setHCPDiscipline(ims.core.vo.lookups.HcpDisType value)
{
this.isValidated = false;
this.hcpdiscipline = value;
}
public boolean getDateFromIsNotNull()
{
return this.datefrom != null;
}
public ims.framework.utils.Date getDateFrom()
{
return this.datefrom;
}
public void setDateFrom(ims.framework.utils.Date value)
{
this.isValidated = false;
this.datefrom = value;
}
public boolean getDateToIsNotNull()
{
return this.dateto != null;
}
public ims.framework.utils.Date getDateTo()
{
return this.dateto;
}
public void setDateTo(ims.framework.utils.Date value)
{
this.isValidated = false;
this.dateto = value;
}
public boolean getCareContextRefIsNotNull()
{
return this.carecontextref != null;
}
public ims.core.admin.vo.CareContextRefVo getCareContextRef()
{
return this.carecontextref;
}
public void setCareContextRef(ims.core.admin.vo.CareContextRefVo value)
{
this.isValidated = false;
this.carecontextref = value;
}
public boolean getEpisodeOfCareIsNotNull()
{
return this.episodeofcare != null;
}
public ims.core.admin.vo.EpisodeOfCareRefVo getEpisodeOfCare()
{
return this.episodeofcare;
}
public void setEpisodeOfCare(ims.core.admin.vo.EpisodeOfCareRefVo value)
{
this.isValidated = false;
this.episodeofcare = value;
}
public final String getIItemText()
{
return toString();
}
public final Integer getBoId()
{
return null;
}
public final String getBoClassName()
{
return null;
}
public boolean equals(Object obj)
{
if(obj == null)
return false;
if(!(obj instanceof CancerContactSearchCriteriaVo))
return false;
CancerContactSearchCriteriaVo compareObj = (CancerContactSearchCriteriaVo)obj;
if(this.getHCPDiscipline() == null && compareObj.getHCPDiscipline() != null)
return false;
if(this.getHCPDiscipline() != null && compareObj.getHCPDiscipline() == null)
return false;
if(this.getHCPDiscipline() != null && compareObj.getHCPDiscipline() != null)
return this.getHCPDiscipline().equals(compareObj.getHCPDiscipline());
return super.equals(obj);
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
CancerContactSearchCriteriaVo clone = new CancerContactSearchCriteriaVo();
if(this.hcplite == null)
clone.hcplite = null;
else
clone.hcplite = (ims.core.vo.HcpLiteVo)this.hcplite.clone();
if(this.hcpdiscipline == null)
clone.hcpdiscipline = null;
else
clone.hcpdiscipline = (ims.core.vo.lookups.HcpDisType)this.hcpdiscipline.clone();
if(this.datefrom == null)
clone.datefrom = null;
else
clone.datefrom = (ims.framework.utils.Date)this.datefrom.clone();
if(this.dateto == null)
clone.dateto = null;
else
clone.dateto = (ims.framework.utils.Date)this.dateto.clone();
clone.carecontextref = this.carecontextref;
clone.episodeofcare = this.episodeofcare;
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(CancerContactSearchCriteriaVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A CancerContactSearchCriteriaVo object cannot be compared an Object of type " + obj.getClass().getName());
}
CancerContactSearchCriteriaVo compareObj = (CancerContactSearchCriteriaVo)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getHcpLite() == null && compareObj.getHcpLite() != null)
return -1;
if(this.getHcpLite() != null && compareObj.getHcpLite() == null)
return 1;
if(this.getHcpLite() != null && compareObj.getHcpLite() != null)
retVal = this.getHcpLite().compareTo(compareObj.getHcpLite());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.hcplite != null)
count++;
if(this.hcpdiscipline != null)
count++;
if(this.datefrom != null)
count++;
if(this.dateto != null)
count++;
if(this.carecontextref != null)
count++;
if(this.episodeofcare != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 6;
}
protected ims.core.vo.HcpLiteVo hcplite;
protected ims.core.vo.lookups.HcpDisType hcpdiscipline;
protected ims.framework.utils.Date datefrom;
protected ims.framework.utils.Date dateto;
protected ims.core.admin.vo.CareContextRefVo carecontextref;
protected ims.core.admin.vo.EpisodeOfCareRefVo episodeofcare;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
KentShikama/diaspora | spec/helpers/application_helper_spec.rb | 4517 | # Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
describe ApplicationHelper, :type => :helper do
before do
@user = alice
@person = FactoryGirl.create(:person)
end
describe "#all_services_connected?" do
before do
AppConfig.configured_services = [1, 2, 3]
def current_user
@current_user
end
@current_user = alice
end
after do
AppConfig.configured_services = nil
end
it 'returns true if all networks are connected' do
3.times { |t| @current_user.services << FactoryGirl.build(:service) }
expect(all_services_connected?).to be true
end
it 'returns false if not all networks are connected' do
@current_user.services.delete_all
expect(all_services_connected?).to be false
end
end
describe "#jquery_include_tag" do
describe "with jquery cdn" do
before do
AppConfig.privacy.jquery_cdn = true
end
it 'inclues jquery.js from jquery cdn' do
expect(helper.jquery_include_tag).to match(/jquery\.com/)
end
it 'falls back to asset pipeline on cdn failure' do
expect(helper.jquery_include_tag).to match(/document\.write/)
end
end
describe "without jquery cdn" do
before do
AppConfig.privacy.jquery_cdn = false
end
it 'includes jquery.js from asset pipeline' do
expect(helper.jquery_include_tag).to match(/jquery3\.js/)
expect(helper.jquery_include_tag).not_to match(/jquery\.com/)
end
end
it 'inclues jquery_ujs.js' do
expect(helper.jquery_include_tag).to match(/jquery_ujs\.js/)
end
it "disables ajax caching" do
expect(helper.jquery_include_tag).to match(/jQuery\.ajaxSetup/)
end
end
describe "#donations_enabled?" do
it "returns false when nothing is set" do
expect(helper.donations_enabled?).to be false
end
it "returns true when the paypal donations is enabled" do
AppConfig.settings.paypal_donations.enable = true
expect(helper.donations_enabled?).to be true
end
it "returns true when the liberapay username is set" do
AppConfig.settings.liberapay_username = "foo"
expect(helper.donations_enabled?).to be true
end
it "returns true when the bitcoin_address is set" do
AppConfig.settings.bitcoin_address = "bar"
expect(helper.donations_enabled?).to be true
end
it "returns true when all the donations are enabled" do
AppConfig.settings.paypal_donations.enable = true
AppConfig.settings.liberapay_username = "foo"
AppConfig.settings.bitcoin_address = "bar"
expect(helper.donations_enabled?).to be true
end
end
describe "#changelog_url" do
let(:changelog_url_setting) {
double.tap {|double| allow(AppConfig).to receive(:settings).and_return(double(changelog_url: double)) }
}
it "defaults to master branch changleog" do
expect(changelog_url_setting).to receive(:present?).and_return(false)
expect(AppConfig).to receive(:git_revision).and_return(nil)
expect(changelog_url).to eq("https://github.com/diaspora/diaspora/blob/master/Changelog.md")
end
it "displays the changelog for the current git revision if set" do
expect(changelog_url_setting).to receive(:present?).and_return(false)
expect(AppConfig).to receive(:git_revision).twice.and_return("123")
expect(changelog_url).to eq("https://github.com/diaspora/diaspora/blob/123/Changelog.md")
end
it "displays the configured changelog url if set" do
expect(changelog_url_setting).to receive(:present?).and_return(true)
expect(changelog_url_setting).to receive(:get)
.and_return("https://github.com/diaspora/diaspora/blob/develop/Changelog.md")
expect(AppConfig).not_to receive(:git_revision)
expect(changelog_url).to eq("https://github.com/diaspora/diaspora/blob/develop/Changelog.md")
end
end
describe '#pod_name' do
it 'defaults to Diaspora*' do
expect(pod_name).to match /DIASPORA/i
end
it 'displays the supplied pod_name if it is set' do
AppConfig.settings.pod_name = "Catspora"
expect(pod_name).to match "Catspora"
end
end
describe '#pod_version' do
it 'displays the supplied pod_version if it is set' do
AppConfig.version.number = "0.0.1.0"
expect(pod_version).to match "0.0.1.0"
end
end
end
| agpl-3.0 |
rapidminer/rapidminer-5 | src/com/rapidminer/operator/generator/TransactionClustersExampleSetGenerator.java | 8144 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.generator;
import java.util.ArrayList;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DoubleArrayDataRow;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.io.AbstractExampleSource;
import com.rapidminer.operator.ports.metadata.AttributeMetaData;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.MetaData;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeInt;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.RandomGenerator;
import com.rapidminer.tools.math.container.Range;
/**
* Generates a random example set for testing purposes. The data represents a team profit
* example set.
*
* @author Ingo Mierswa
*/
public class TransactionClustersExampleSetGenerator extends AbstractExampleSource {
/** The parameter name for "The number of generated examples." */
public static final String PARAMETER_NUMBER_TRANSACTIONS = "number_transactions";
/** The parameter name for "The number of generated examples." */
public static final String PARAMETER_NUMBER_CUSTOMERS = "number_customers";
/** The parameter name for "The number of generated examples." */
public static final String PARAMETER_NUMBER_ITEMS = "number_items";
/** The parameter name for "The number of generated examples." */
public static final String PARAMETER_NUMBER_CLUSTERS = "number_clusters";
public TransactionClustersExampleSetGenerator(OperatorDescription description) {
super(description);
}
@Override
public ExampleSet createExampleSet() throws OperatorException {
// init
int numberOfTransactions = getParameterAsInt(PARAMETER_NUMBER_TRANSACTIONS);
int numberOfCustomers = getParameterAsInt(PARAMETER_NUMBER_CUSTOMERS);
int numberOfClusters = getParameterAsInt(PARAMETER_NUMBER_CLUSTERS);
int numberOfItems = getParameterAsInt(PARAMETER_NUMBER_ITEMS);
// create table
List<Attribute> attributes = new ArrayList<Attribute>();
Attribute id = AttributeFactory.createAttribute("Id", Ontology.NOMINAL);
for (int i = 1; i <= numberOfCustomers; i++) {
id.getMapping().mapString("Id " + i);
}
attributes.add(id);
Attribute item = AttributeFactory.createAttribute("Item", Ontology.NOMINAL);
for (int i = 1; i <= numberOfItems; i++) {
item.getMapping().mapString("Item " + i);
}
attributes.add(item);
Attribute amount = AttributeFactory.createAttribute("Amount", Ontology.INTEGER);
attributes.add(amount);
MemoryExampleTable table = new MemoryExampleTable(attributes);
// create data
RandomGenerator random = RandomGenerator.getRandomGenerator(this);
double[][] probs = new double[numberOfClusters][numberOfItems];
int[] maxItems = new int[numberOfClusters];
for (int c = 0; c < numberOfClusters; c++) {
double sum = 0.0d;
for (int i = 0; i < numberOfItems; i++) {
probs[c][i] = random.nextDouble();
sum += probs[c][i];
}
for (int i = 0; i < numberOfItems; i++) {
probs[c][i] /= sum;
}
maxItems[c] = random.nextIntInRange(5, 20);
}
double clusterSize = Math.ceil(numberOfCustomers / (double)numberOfClusters);
for (int n = 0; n < numberOfCustomers; n++) {
double[] values = new double[3]; // values for the data row in the table: [Id, Item, Amount]
values[0] = id.getMapping().mapString("Id " + (n + 1));
int clusterIndex = Math.max(0, Math.min(numberOfClusters - 1, (int)Math.floor((double)(n + 1) / clusterSize)));
double p = random.nextDouble(); // random number in [0.0, 1.0[
double sum = 0.0d;
int itemIndex = 0;
double itemProb = 0.0d;
for (int i = 0; i < probs[clusterIndex].length; i++) {
if (p <= sum) {
itemIndex = i;
itemProb = probs[clusterIndex][i];
break;
}
sum += probs[clusterIndex][i];
}
values[1] = item.getMapping().mapString("Item " + (itemIndex + 1));
values[2] = Math.round(Math.max(1, random.nextGaussian() * itemProb * maxItems[clusterIndex]));
table.addDataRow(new DoubleArrayDataRow(values));
}
for (int n = numberOfCustomers; n < numberOfTransactions; n++) {
double[] values = new double[3];
int idNumber = random.nextIntInRange(1, numberOfCustomers + 1);
values[0] = values[0] = id.getMapping().mapString("Id " + idNumber);
int clusterIndex = Math.max(0, Math.min(numberOfClusters - 1, (int)Math.floor((double)idNumber / clusterSize)));
double p = random.nextDouble();
double sum = 0.0d;
int itemIndex = 0;
double itemProb = 0.0d;
if (random.nextDouble() < 0.05) {
itemIndex = random.nextIntInRange(0, numberOfItems);
} else {
for (int i = 0; i < probs[clusterIndex].length; i++) {
if (p <= sum) {
itemIndex = i;
itemProb = probs[clusterIndex][i];
break;
}
sum += probs[clusterIndex][i];
}
}
values[1] = item.getMapping().mapString("Item " + (itemIndex + 1));
values[2] = Math.round(Math.max(1, random.nextGaussian() * itemProb * maxItems[clusterIndex]));
table.addDataRow(new DoubleArrayDataRow(values));
}
return table.createExampleSet(null, null, id);
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
ParameterType type = new ParameterTypeInt(PARAMETER_NUMBER_TRANSACTIONS, "The number of generated transactions.", 1, Integer.MAX_VALUE, 10000);
type.setExpert(false);
types.add(type);
type = new ParameterTypeInt(PARAMETER_NUMBER_CUSTOMERS, "The number of generated customers.", 1, Integer.MAX_VALUE, 1000);
type.setExpert(false);
types.add(type);
type = new ParameterTypeInt(PARAMETER_NUMBER_ITEMS, "The number of generated items.", 1, Integer.MAX_VALUE, 80);
type.setExpert(false);
types.add(type);
type = new ParameterTypeInt(PARAMETER_NUMBER_CLUSTERS, "The number of generated clusters.", 1, Integer.MAX_VALUE, 10);
type.setExpert(false);
types.add(type);
types.addAll(RandomGenerator.getRandomGeneratorParameters(this));
return types;
}
@Override
public MetaData getGeneratedMetaData() throws OperatorException {
ExampleSetMetaData emd = new ExampleSetMetaData();
String[] possibleValues = new String[getParameterAsInt(PARAMETER_NUMBER_CUSTOMERS)];
for (int i = 0; i < possibleValues.length; i++) {
possibleValues[i] = "Id " + (i + 1);
}
emd.addAttribute(new AttributeMetaData("Id", Attributes.ID_NAME, possibleValues));
possibleValues = new String[getParameterAsInt(PARAMETER_NUMBER_ITEMS)];
for (int i = 0; i < possibleValues.length; i++) {
possibleValues[i] = "Item " + (i + 1);
}
emd.addAttribute(new AttributeMetaData("Item", null, possibleValues));
emd.addAttribute(new AttributeMetaData("Amount", null, Ontology.INTEGER, new Range(0, Double.POSITIVE_INFINITY)));
emd.setNumberOfExamples(getParameterAsInt(PARAMETER_NUMBER_TRANSACTIONS));
return emd;
}
}
| agpl-3.0 |
PowerToChange/pat | app/models/state.rb | 118 | class State < ActiveRecord::Base
load_mappings
include Common::Core::State
include Common::Core::Ca::State
end
| agpl-3.0 |
leftees/galleryplus | tests/unit/service/SearchFolderServiceTest.php | 9739 | <?php
/**
* ownCloud - galleryplus
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Olivier Paroz <owncloud@interfasys.ch>
*
* @copyright Olivier Paroz 2015
*/
namespace OCA\GalleryPlus\Service;
/**
* Class SearchFolderServiceTest
*
* @package OCA\GalleryPlus\Controller
*/
class SearchFolderServiceTest extends \Test\GalleryUnitTest {
/** @var SearchFolderService */
protected $service;
/**
* Test set up
*/
public function setUp() {
parent::setUp();
$this->service = new SearchFolderService (
$this->appName,
$this->environment,
$this->logger
);
}
public function testGetNodeTypeWithBrokenFolder() {
$node = $this->mockBadFile();
$response = self::invokePrivate($this->service, 'getNodeType', [$node]);
$this->assertSame('', $response);
}
public function testGetAllowedSubFolderWithFile() {
$node = $this->mockFile(11335);
$nodeType = $node->getType();
$response = self::invokePrivate($this->service, 'getAllowedSubFolder', [$node, $nodeType]);
$this->assertSame([], $response);
}
/**
* @expectedException \OCA\GalleryPlus\Service\NotFoundServiceException
*/
public function testSendFolderWithNullFolder() {
$path = '';
$node = null;
$locationHasChanged = false;
self::invokePrivate($this->service, 'sendFolder', [$path, $node, $locationHasChanged]);
}
/**
* @expectedException \OCA\GalleryPlus\Service\ForbiddenServiceException
*/
public function testSendFolderWithNonAvailableFolder() {
$path = '';
$nodeId = 94875;
$isReadable = false;
$node = $this->mockFolder('home::user', $nodeId, [], $isReadable);
$locationHasChanged = false;
self::invokePrivate($this->service, 'sendFolder', [$path, $node, $locationHasChanged]);
}
public function testSendFolder() {
$path = '';
$nodeId = 94875;
$files = [];
$node = $this->mockFolder('home::user', $nodeId, $files);
$locationHasChanged = false;
$folder = [$path, $node, $locationHasChanged];
$response = self::invokePrivate($this->service, 'sendFolder', $folder);
$this->assertSame($folder, $response);
}
public function providesSendExternalFolderData() {
return [
['shared::99999'],
['home::user'] // Throws an exception
];
}
/**
* @dataProvider providesSendExternalFolderData
*
* @param $storageId
*/
public function testSendExternalFolder($storageId) {
$expectedException =
new ForbiddenServiceException('Album is private or unavailable');
$path = '';
$nodeId = 94875;
$files = [];
$shared = $this->mockFolder('shared::12345', $nodeId, $files);
$this->mockGetVirtualRootFolderOfSharedFolder($storageId, $shared);
$locationHasChanged = false;
$folder = [$path, $shared, $locationHasChanged];
try {
$response = self::invokePrivate($this->service, 'sendFolder', $folder);
$this->assertSame($folder, $response);
} catch (\Exception $exception) {
$this->assertInstanceOf('\OCA\GalleryPlus\Service\ForbiddenServiceException', $exception);
$this->assertSame($expectedException->getMessage(), $exception->getMessage());
}
}
public function providesNodesData() {
$exception = new NotFoundServiceException('Boom');
return [
[0, $exception],
[1, []]
];
}
/**
* @dataProvider providesNodesData
*
* That's one way of dealing with mixed data instead of writing the same test twice ymmv
*
* @param $subDepth
* @param array|\Exception $nodes
*/
public function testGetNodesWithBrokenListing($subDepth, $nodes) {
$files = null;
$folder = $this->mockBrokenDirectoryListing();
try {
$response = self::invokePrivate($this->service, 'getNodes', [$folder, $subDepth]);
$this->assertSame($nodes, $response);
} catch (\Exception $exception) {
$this->assertInstanceOf('\OCA\GalleryPlus\Service\NotFoundServiceException', $exception);
$this->assertSame($nodes->getMessage(), $exception->getMessage());
}
}
public function providesRecoverFromGetNodesData() {
$caughtException = new \Exception('Nasty');
$newException = new NotFoundServiceException('Boom');
return [
[0, $caughtException, $newException],
[1, $caughtException, []]
];
}
/**
* @dataProvider providesRecoverFromGetNodesData
*
* @param $subDepth
* @param $caughtException
* @param $nodes
*/
public function testRecoverFromGetNodesError($subDepth, $caughtException, $nodes) {
try {
$response = self::invokePrivate(
$this->service, 'recoverFromGetNodesError', [$subDepth, $caughtException]
);
$this->assertSame($nodes, $response);
} catch (\Exception $thisException) {
$this->assertInstanceOf(
'\OCA\GalleryPlus\Service\NotFoundServiceException', $thisException
);
$this->assertSame($caughtException->getMessage(), $thisException->getMessage());
}
}
public function testIsAllowedAndAvailableWithNullFolder() {
$node = null;
$response = self::invokePrivate($this->service, 'isAllowedAndAvailable', [$node]);
$this->assertFalse($response);
}
public function testIsAllowedAndAvailableWithBrokenSetup() {
$node = $this->mockFolder('home::user', 909090, []);
$node->method('isReadable')
->willThrowException(new \Exception('Boom'));
$response = self::invokePrivate($this->service, 'isAllowedAndAvailable', [$node]);
$this->assertFalse($response);
}
public function providesIsAllowedAndAvailableWithMountedFolderData() {
return [
// Mounted, so looking at options
[true, true, true],
[true, false, false],
// Not mounted, so OK
[false, true, true],
[false, false, true]
];
}
/**
* @dataProvider providesIsAllowedAndAvailableWithMountedFolderData
*
* @param bool $mounted
* @param bool $previewsAllowedOnMountedShare
* @param bool $expectedResult
*/
public function testIsAllowedAndAvailableWithMountedFolder(
$mounted, $previewsAllowedOnMountedShare, $expectedResult
) {
$nodeId = 12345;
$files = [];
$isReadable = true;
$mount = $this->mockMountPoint($previewsAllowedOnMountedShare);
$node = $this->mockFolder(
'webdav::user@domain.com/dav', $nodeId, $files, $isReadable, $mounted, $mount
);
$response = self::invokePrivate($this->service, 'isAllowedAndAvailable', [$node]);
$this->assertSame($expectedResult, $response);
}
public function providesIsAllowedAndAvailableData() {
return [
['shared::99999', false, true],
['shared::99999', true, true],
['home::user', false, false],
['home::user', true, true],
];
}
/**
* @dataProvider providesIsAllowedAndAvailableData
*
* @param string $rootStorageId
* @param bool $externalSharesAllowed
* @param bool $expectedResult
*/
public function testIsAllowedAndAvailable(
$rootStorageId, $externalSharesAllowed, $expectedResult
) {
$nodeId = 12345;
$files = [];
$isReadable = true;
$shared = $this->mockFolder('shared::99999', $nodeId, $files, $isReadable);
$this->mockGetVirtualRootFolderOfSharedFolder($rootStorageId, $shared);
$features = $externalSharesAllowed ? ['external_shares'] : [];
self::invokePrivate($this->service, 'features', [$features]);
$response = self::invokePrivate($this->service, 'isAllowedAndAvailable', [$shared]);
$this->assertSame($expectedResult, $response);
}
public function providesLocationChangeData() {
return [
[0, false],
[1, true],
];
}
/**
* @dataProvider providesLocationChangeData
*
* @param int $depth
* @param bool $expectedResult
*/
public function testHasLocationChanged($depth, $expectedResult) {
$response = self::invokePrivate($this->service, 'hasLocationChanged', [$depth]);
$this->assertSame($expectedResult, $response);
}
public function providesValidateLocationData() {
return [
['folder1', 0, 'folder1'],
['completely/bogus/set/of/folders/I/give/up', 4, ''],
];
}
/**
* @dataProvider providesValidateLocationData
*
* @param string $location
* @param int $depth
* @param bool $expectedResult
*/
public function testValidateLocation($location, $depth, $expectedResult) {
$response = self::invokePrivate($this->service, 'validateLocation', [$location, $depth]);
$this->assertSame($expectedResult, $response);
}
public function testFindFolderWithFileLocation() {
$location = 'folder/file1.jpg';
$fileId = 99999;
$file = $this->mockJpgFile($fileId);
$folder = $this->mockFolder('home::user', 10101, [$file]);
$file->method('getParent')
->willReturn($folder);
$this->mockGetFileNodeFromVirtualRoot($location, $file);
$this->mockGetPathFromVirtualRoot($folder, $location);
$locationHasChanged = false;
$expectedResult = [$location, $folder, $locationHasChanged];
$response = self::invokePrivate($this->service, 'findFolder', [$location]);
$this->assertSame($expectedResult, $response);
}
private function mockBrokenDirectoryListing() {
$folder = $this->getMockBuilder('OCP\Files\Folder')
->disableOriginalConstructor()
->getMock();
$folder->method('getDirectoryListing')
->willThrowException(new \Exception('Boom'));
return $folder;
}
private function mockGetVirtualRootFolderOfSharedFolder($storageId, $shared) {
$rootNodeId = 91919191;
$rootFiles = [$shared];
$sharedRoot = $this->mockFolder($storageId, $rootNodeId, $rootFiles);
$this->environment->expects($this->once())
->method('getVirtualRootFolder')
->willReturn($sharedRoot);
}
private function mockMountPoint($previewsAllowed) {
$mountPoint = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
->disableOriginalConstructor()
->getMock();
$mountPoint->method('getOption')
->with(
'previews',
true
)
->willReturn($previewsAllowed);
return $mountPoint;
}
}
| agpl-3.0 |
interjection/infinity-next | app/Events/ThreadNewReply.php | 396 | <?php
namespace App\Events;
use App\Post;
use Illuminate\Queue\SerializesModels;
class ThreadNewReply extends Event
{
use SerializesModels;
/**
* The post the event is being fired on.
*
* @var \App\Post
*/
public $post;
/**
* Create a new event instance.
*/
public function __construct(Post $post)
{
$this->post = $post;
}
}
| agpl-3.0 |
bbguitar/ProjectPier | application/models/config_handlers/general/ConfigHandler.class.php | 2492 | <?php
/**
* Base config handler. Config handlers are used for typecasting and rendering controls
* that represent single config options
*
* @version 1.0
* @http://www.projectpier.org/
*/
abstract class ConfigHandler {
/**
* Config option that this handler is attached to (config options are used for handler contruction)
*
* @var ConfigOption
*/
private $config_option;
/**
* Raw value
*
* @var mixed
*/
private $raw_value;
// ---------------------------------------------------
// Utils and abstract functions
// ---------------------------------------------------
/**
* Get value
*
* @param null
* @return mixed
*/
function getValue() {
return $this->rawToPhp($this->getRawValue());
} // getValue
/**
* Set value value
*
* @param mixed $value
* @return null
*/
function setValue($value) {
$this->setRawValue($this->phpToRaw($value));
} // setValue
/**
* Render form control
*
* @param string $control_name
* @return string
*/
abstract function render($control_name);
/**
* Conver $value to raw value
*
* @param mixed $value
* @return null
*/
protected function phpToRaw($value) {
return $value;
} // phpToRaw
/**
* Convert raw value to php
*
* @param string $value
* @return mixed
*/
protected function rawToPhp($value) {
return $value;
} // rawToPhp
// ---------------------------------------------------
// Getters and setters
// ---------------------------------------------------
/**
* Get config_option
*
* @param null
* @return ConfigOption
*/
function getConfigOption() {
return $this->config_option;
} // getConfigOption
/**
* Set config_option value
*
* @param ConfigOption $value
* @return null
*/
function setConfigOption(ConfigOption $value) {
$this->config_option = $value;
} // setConfigOption
/**
* Get raw_value
*
* @param null
* @return mixed
*/
function getRawValue() {
return $this->raw_value;
} // getRawValue
/**
* Set raw_value value
*
* @param mixed $value
* @return null
*/
function setRawValue($value) {
$this->raw_value = $value;
} // setRawValue
} // ConfigHandler
?>
| agpl-3.0 |
jacklicn/owncloud | apps/firstrunwizard/appinfo/app.php | 1509 | <?php
/**
* ownCloud - firstrunwizard App
*
* @author Frank Karlitschek
* @copyright 2012 Frank Karlitschek karlitschek@kde.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\FirstRunWizard;
use OCP\Util;
Util::addStyle('firstrunwizard', 'colorbox');
Util::addScript('firstrunwizard', 'jquery.colorbox');
Util::addScript('firstrunwizard', 'firstrunwizard');
Util::addStyle('firstrunwizard', 'firstrunwizard');
// only load when the file app displays
$eventDispatcher = \OC::$server->getEventDispatcher();
$eventDispatcher->addListener(
'OCA\Files::loadAdditionalScripts',
function() {
$config = \OC::$server->getConfig();
$userSession = \OC::$server->getUserSession();
$firstRunConfig = new Config($config, $userSession);
if ($userSession->isLoggedIn() && $firstRunConfig->isEnabled()) {
Util::addScript( 'firstrunwizard', 'activate');
}
}
);
| agpl-3.0 |
ewheeler/rapidpro | temba/channels/migrations/0029_auto_20160202_1931.py | 964 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('channels', '0028_channel_uuid_cleanup'),
]
operations = [
migrations.AlterField(
model_name='channel',
name='channel_type',
field=models.CharField(default='A', help_text='Type of this channel, whether Android, Twilio or SMSC', max_length=3, verbose_name='Channel Type', choices=[('A', 'Android'), ('T', 'Twilio'), ('AT', "Africa's Talking"), ('ZV', 'Zenvia'), ('NX', 'Nexmo'), ('IB', 'Infobip'), ('VB', 'Verboice'), ('H9', 'Hub9'), ('VM', 'Vumi'), ('KN', 'Kannel'), ('EX', 'External'), ('TT', 'Twitter'), ('CT', 'Clickatell'), ('PL', 'Plivo'), ('SQ', 'Shaqodoon'), ('HX', 'High Connection'), ('BM', 'Blackmyna'), ('SC', 'SMSCentral'), ('ST', 'Start Mobile'), ('TG', 'Telegram'), ('YO', 'Yo!'), ('M3', 'M3 Tech')]),
),
]
| agpl-3.0 |
pydio/pydio-core | core/src/plugins/editor.eml/i18n/conf/it.php | 1149 | <?php
/*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
$mess=array(
"Email Viewer" => "Visualizzatore Email",
"Email reader, supports eml format and eml mimetypes. Detects if a folder contains only email and display columns accordingly." => "Lettore Email, supporta il formato 'eml' ed il mimetype 'eml'. Individua se una cartella contiene solo email e visualizza le colonne conseguentemente.",
);
| agpl-3.0 |
ArturD/holmes | holmes-classifier/src/main/java/com/wikia/classifier/wikitext/WikiPageSection.java | 313 | package com.wikia.classifier.wikitext;
public class WikiPageSection {
private String title;
public WikiPageSection(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/Admin/src/ims/admin/forms/batchprinting/BaseLogic.java | 4786 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.admin.forms.batchprinting;
public abstract class BaseLogic extends Handlers
{
public final Class getDomainInterface() throws ClassNotFoundException
{
return ims.admin.domain.BatchPrinting.class;
}
public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.admin.domain.BatchPrinting domain)
{
setContext(engine, form);
this.domain = domain;
}
public void clearContextInformation()
{
engine.clearPatientContextInformation();
}
protected final void oncmbTypeValueSet(Object value)
{
java.util.ArrayList listOfValues = this.form.cmbType().getValues();
if(value == null)
{
if(listOfValues != null && listOfValues.size() > 0)
{
for(int x = 0; x < listOfValues.size(); x++)
{
ims.ntpf.vo.lookups.JobType existingInstance = (ims.ntpf.vo.lookups.JobType)listOfValues.get(x);
if(!existingInstance.isActive())
{
bindcmbTypeLookup();
return;
}
}
}
}
else if(value instanceof ims.ntpf.vo.lookups.JobType)
{
ims.ntpf.vo.lookups.JobType instance = (ims.ntpf.vo.lookups.JobType)value;
if(listOfValues != null)
{
if(listOfValues.size() == 0)
bindcmbTypeLookup();
for(int x = 0; x < listOfValues.size(); x++)
{
ims.ntpf.vo.lookups.JobType existingInstance = (ims.ntpf.vo.lookups.JobType)listOfValues.get(x);
if(existingInstance.equals(instance))
return;
}
}
this.form.cmbType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor());
}
}
protected final void bindcmbTypeLookup()
{
this.form.cmbType().clear();
ims.ntpf.vo.lookups.JobTypeCollection lookupCollection = ims.ntpf.vo.lookups.LookupHelper.getJobType(this.domain.getLookupService());
for(int x = 0; x < lookupCollection.size(); x++)
{
this.form.cmbType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor());
}
}
protected final void setcmbTypeLookupValue(int id)
{
ims.ntpf.vo.lookups.JobType instance = ims.ntpf.vo.lookups.LookupHelper.getJobTypeInstance(this.domain.getLookupService(), id);
if(instance != null)
this.form.cmbType().setValue(instance);
}
protected final void defaultcmbTypeLookupValue()
{
this.form.cmbType().setValue((ims.ntpf.vo.lookups.JobType)domain.getLookupService().getDefaultInstance(ims.ntpf.vo.lookups.JobType.class, engine.getFormName().getID(), ims.ntpf.vo.lookups.JobType.TYPE_ID));
}
public final void free()
{
super.free();
domain = null;
}
protected ims.admin.domain.BatchPrinting domain;
}
| agpl-3.0 |
grafana/loki | vendor/github.com/fsouza/fake-gcs-server/fakestorage/mux_tranport.go | 461 | // Copyright 2019 Francisco Souza. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fakestorage
import (
"net/http"
"net/http/httptest"
"github.com/gorilla/mux"
)
type muxTransport struct {
router *mux.Router
}
func (t *muxTransport) RoundTrip(r *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
t.router.ServeHTTP(w, r)
return w.Result(), nil
}
| agpl-3.0 |
govro/ckanext-romania_theme | i18n/check_po_files.py | 4151 | #!/usr/bin/env python
'''Script for checking for common translation mistakes in po files, see:
paster check-po-files --help
for usage.
Requires polib <http://pypi.python.org/pypi/polib>:
pip install polib
'''
import re
import paste.script.command
def simple_conv_specs(s):
'''Return the simple Python string conversion specifiers in the string s.
e.g. ['%s', '%i']
See http://docs.python.org/library/stdtypes.html#string-formatting
'''
simple_conv_specs_re = re.compile('\%\w')
return simple_conv_specs_re.findall(s)
def test_simple_conv_specs():
assert simple_conv_specs("Authorization function not found: %s") == (
['%s'])
assert simple_conv_specs("Problem purging revision %s: %s") == (
['%s', '%s'])
assert simple_conv_specs(
"Cannot create new entity of this type: %s %s") == ['%s', '%s']
assert simple_conv_specs("Could not read parameters: %r") == ['%r']
assert simple_conv_specs("User %r not authorized to edit %r") == (
['%r', '%r'])
assert simple_conv_specs(
"Please <a href=\"%s\">update your profile</a> and add your email "
"address and your full name. "
"%s uses your email address if you need to reset your password.") == (
['%s', '%s'])
assert simple_conv_specs(
"You can use %sMarkdown formatting%s here.") == ['%s', '%s']
assert simple_conv_specs(
"Name must be a maximum of %i characters long") == ['%i']
assert simple_conv_specs("Blah blah %s blah %(key)s blah %i") == (
['%s', '%i'])
def mapping_keys(s):
'''Return a sorted list of the mapping keys in the string s.
e.g. ['%(name)s', '%(age)i']
See http://docs.python.org/library/stdtypes.html#string-formatting
'''
mapping_keys_re = re.compile('\%\([^\)]*\)\w')
return sorted(mapping_keys_re.findall(s))
def test_mapping_keys():
assert mapping_keys(
"You have requested your password on %(site_title)s to be reset.\n"
"\n"
"Please click the following link to confirm this request:\n"
"\n"
" %(reset_link)s\n") == ['%(reset_link)s', '%(site_title)s']
assert mapping_keys(
"The input field %(name)s was not expected.") == ['%(name)s']
assert mapping_keys(
"[1:You searched for \"%(query)s\". ]%(number_of_results)s "
"datasets found.") == ['%(number_of_results)s', '%(query)s']
assert mapping_keys("Blah blah %s blah %(key)s blah %i") == (
['%(key)s']), mapping_keys("Blah blah %s blah %(key)s blah %i")
def replacement_fields(s):
'''Return a sorted list of the Python replacement fields in the string s.
e.g. ['{}', '{2}', '{object}', '{target}']
See http://docs.python.org/library/string.html#formatstrings
'''
repl_fields_re = re.compile('\{[^\}]*\}')
return sorted(repl_fields_re.findall(s))
def test_replacement_fields():
assert replacement_fields(
"{actor} added the tag {object} to the dataset {target}") == (
['{actor}', '{object}', '{target}'])
assert replacement_fields("{actor} updated their profile") == ['{actor}']
class CheckPoFiles(paste.script.command.Command):
usage = "[FILE] ..."
group_name = 'ckan'
summary = 'Check po files for common mistakes'
parser = paste.script.command.Command.standard_parser(verbose=True)
def command(self):
import polib
test_simple_conv_specs()
test_mapping_keys()
test_replacement_fields()
for path in self.args:
print u'Checking file {}'.format(path)
po = polib.pofile(path)
for entry in po.translated_entries():
if not entry.msgstr:
continue
for function in (simple_conv_specs, mapping_keys,
replacement_fields):
if not function(entry.msgid) == function(entry.msgstr):
print " Format specifiers don't match:"
print u' {0} -> {1}'.format(entry.msgid, entry.msgstr)
| agpl-3.0 |
nerzhul/ocsms | lib/vendor/giggsey/locale/data/br.php | 6331 | <?php
/**
* This file has been @generated by a phing task from CLDR version 33.0.0.
* See [README.md](README.md#generating-data) for more information.
*
* @internal Please do not require this file directly.
* It may change location/format between versions
*
* Do not modify this file directly!
*/
return array (
'AC' => 'Enez Ascension',
'AD' => 'Andorra',
'AE' => 'Emirelezhioù Arab Unanet',
'AF' => 'Afghanistan',
'AG' => 'Antigua ha Barbuda',
'AI' => 'Anguilla',
'AL' => 'Albania',
'AM' => 'Armenia',
'AO' => 'Angola',
'AQ' => 'Antarktika',
'AR' => 'Arcʼhantina',
'AS' => 'Samoa Amerikan',
'AT' => 'Aostria',
'AU' => 'Aostralia',
'AW' => 'Aruba',
'AX' => 'Inizi Åland',
'AZ' => 'Azerbaidjan',
'BA' => 'Bosnia ha Herzegovina',
'BB' => 'Barbados',
'BD' => 'Bangladesh',
'BE' => 'Belgia',
'BF' => 'Burkina Faso',
'BG' => 'Bulgaria',
'BH' => 'Bahrein',
'BI' => 'Burundi',
'BJ' => 'Benin',
'BL' => 'Saint Barthélemy',
'BM' => 'Bermuda',
'BN' => 'Brunei',
'BO' => 'Bolivia',
'BQ' => 'Karib Nederlandat',
'BR' => 'Brazil',
'BS' => 'Bahamas',
'BT' => 'Bhoutan',
'BW' => 'Botswana',
'BY' => 'Belarus',
'BZ' => 'Belize',
'CA' => 'Kanada',
'CC' => 'Inizi Kokoz',
'CD' => 'Kongo - Kinshasa',
'CF' => 'Republik Kreizafrikan',
'CG' => 'Kongo - Brazzaville',
'CH' => 'Suis',
'CI' => 'Aod an Olifant',
'CK' => 'Inizi Cook',
'CL' => 'Chile',
'CM' => 'Kameroun',
'CN' => 'Sina',
'CO' => 'Kolombia',
'CR' => 'Costa Rica',
'CU' => 'Kuba',
'CV' => 'Kab-Glas',
'CW' => 'Curaçao',
'CX' => 'Enez Christmas',
'CY' => 'Kiprenez',
'CZ' => 'Tchekia',
'DE' => 'Alamagn',
'DG' => 'Diego Garcia',
'DJ' => 'Djibouti',
'DK' => 'Danmark',
'DM' => 'Dominica',
'DO' => 'Republik Dominikan',
'DZ' => 'Aljeria',
'EA' => 'Ceuta ha Melilla',
'EC' => 'Ecuador',
'EE' => 'Estonia',
'EG' => 'Egipt',
'EH' => 'Sahara ar Cʼhornôg',
'ER' => 'Eritrea',
'ES' => 'Spagn',
'ET' => 'Etiopia',
'FI' => 'Finland',
'FJ' => 'Fidji',
'FK' => 'Inizi Falkland',
'FM' => 'Mikronezia',
'FO' => 'Inizi Faero',
'FR' => 'Frañs',
'GA' => 'Gabon',
'GB' => 'Rouantelezh-Unanet',
'GD' => 'Grenada',
'GE' => 'Jorjia',
'GF' => 'Gwiana cʼhall',
'GG' => 'Gwernenez',
'GH' => 'Ghana',
'GI' => 'Jibraltar',
'GL' => 'Greunland',
'GM' => 'Gambia',
'GN' => 'Ginea',
'GP' => 'Gwadeloup',
'GQ' => 'Ginea ar Cʼheheder',
'GR' => 'Gres',
'GS' => 'Inizi Georgia ar Su hag Inizi Sandwich ar Su',
'GT' => 'Guatemala',
'GU' => 'Guam',
'GW' => 'Ginea-Bissau',
'GY' => 'Guyana',
'HK' => 'Hong Kong RMD Sina',
'HN' => 'Honduras',
'HR' => 'Kroatia',
'HT' => 'Haiti',
'HU' => 'Hungaria',
'IC' => 'Inizi Kanariez',
'ID' => 'Indonezia',
'IE' => 'Iwerzhon',
'IL' => 'Israel',
'IM' => 'Enez Vanav',
'IN' => 'India',
'IO' => 'Tiriad breizhveurat Meurvor Indez',
'IQ' => 'Iraq',
'IR' => 'Iran',
'IS' => 'Island',
'IT' => 'Italia',
'JE' => 'Jerzenez',
'JM' => 'Jamaika',
'JO' => 'Jordania',
'JP' => 'Japan',
'KE' => 'Kenya',
'KG' => 'Kyrgyzstan',
'KH' => 'Kambodja',
'KI' => 'Kiribati',
'KM' => 'Komorez',
'KN' => 'Saint Kitts ha Nevis',
'KP' => 'Korea an Norzh',
'KR' => 'Korea ar Su',
'KW' => 'Koweit',
'KY' => 'Inizi Cayman',
'KZ' => 'Kazakstan',
'LA' => 'Laos',
'LB' => 'Liban',
'LC' => 'Saint Lucia',
'LI' => 'Liechtenstein',
'LK' => 'Sri Lanka',
'LR' => 'Liberia',
'LS' => 'Lesotho',
'LT' => 'Lituania',
'LU' => 'Luksembourg',
'LV' => 'Latvia',
'LY' => 'Libia',
'MA' => 'Maroko',
'MC' => 'Monaco',
'MD' => 'Moldova',
'ME' => 'Montenegro',
'MF' => 'Saint Martin',
'MG' => 'Madagaskar',
'MH' => 'Inizi Marshall',
'MK' => 'Makedonia',
'ML' => 'Mali',
'MM' => 'Myanmar (Birmania)',
'MN' => 'Mongolia',
'MO' => 'Macau RMD Sina',
'MP' => 'Inizi Mariana an Norzh',
'MQ' => 'Martinik',
'MR' => 'Maouritania',
'MS' => 'Montserrat',
'MT' => 'Malta',
'MU' => 'Moris',
'MV' => 'Maldivez',
'MW' => 'Malawi',
'MX' => 'Mecʼhiko',
'MY' => 'Malaysia',
'MZ' => 'Mozambik',
'NA' => 'Namibia',
'NC' => 'Kaledonia Nevez',
'NE' => 'Niger',
'NF' => 'Enez Norfolk',
'NG' => 'Nigeria',
'NI' => 'Nicaragua',
'NL' => 'Izelvroioù',
'NO' => 'Norvegia',
'NP' => 'Nepal',
'NR' => 'Nauru',
'NU' => 'Niue',
'NZ' => 'Zeland-Nevez',
'OM' => 'Oman',
'PA' => 'Panamá',
'PE' => 'Perou',
'PF' => 'Polinezia Cʼhall',
'PG' => 'Papoua Ginea-Nevez',
'PH' => 'Filipinez',
'PK' => 'Pakistan',
'PL' => 'Polonia',
'PM' => 'Sant-Pêr-ha-Mikelon',
'PN' => 'Enez Pitcairn',
'PR' => 'Puerto Rico',
'PS' => 'Tiriadoù Palestina',
'PT' => 'Portugal',
'PW' => 'Palau',
'PY' => 'Paraguay',
'QA' => 'Qatar',
'RE' => 'Ar Reünion',
'RO' => 'Roumania',
'RS' => 'Serbia',
'RU' => 'Rusia',
'RW' => 'Rwanda',
'SA' => 'Arabia Saoudat',
'SB' => 'Inizi Salomon',
'SC' => 'Sechelez',
'SD' => 'Soudan',
'SE' => 'Sveden',
'SG' => 'Singapour',
'SH' => 'Saint-Helena',
'SI' => 'Slovenia',
'SJ' => 'Svalbard',
'SK' => 'Slovakia',
'SL' => 'Sierra Leone',
'SM' => 'San Marino',
'SN' => 'Senegal',
'SO' => 'Somalia',
'SR' => 'Surinam',
'SS' => 'Susoudan',
'ST' => 'São Tomé ha Príncipe',
'SV' => 'Salvador',
'SX' => 'Sint Maarten',
'SY' => 'Siria',
'SZ' => 'Swaziland',
'TA' => 'Tristan da Cunha',
'TC' => 'Inizi Turks ha Caicos',
'TD' => 'Tchad',
'TF' => 'Douaroù aostral Frañs',
'TG' => 'Togo',
'TH' => 'Thailand',
'TJ' => 'Tadjikistan',
'TK' => 'Tokelau',
'TL' => 'Timor-Leste',
'TM' => 'Turkmenistan',
'TN' => 'Tunizia',
'TO' => 'Tonga',
'TR' => 'Turkia',
'TT' => 'Trinidad ha Tobago',
'TV' => 'Tuvalu',
'TW' => 'Taiwan',
'TZ' => 'Tanzania',
'UA' => 'Ukraina',
'UG' => 'Ouganda',
'UM' => 'Inizi diabell ar Stadoù-Unanet',
'US' => 'Stadoù-Unanet',
'UY' => 'Uruguay',
'UZ' => 'Ouzbekistan',
'VA' => 'Vatikan',
'VC' => 'Sant Visant hag ar Grenadinez',
'VE' => 'Venezuela',
'VG' => 'Inizi Gwercʼh Breizh-Veur',
'VI' => 'Inizi Gwercʼh ar Stadoù-Unanet',
'VN' => 'Viêt Nam',
'VU' => 'Vanuatu',
'WF' => 'Wallis ha Futuna',
'WS' => 'Samoa',
'XK' => 'Kosovo',
'YE' => 'Yemen',
'YT' => 'Mayotte',
'ZA' => 'Suafrika',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe',
);
| agpl-3.0 |
cloudbase/coriolis-web | src/components/ui/Dropdowns/NewItemDropdown/NewItemDropdown.tsx | 7381 | /*
Copyright (C) 2017 Cloudbase Solutions SRL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import { Link } from 'react-router-dom'
import { observer } from 'mobx-react'
import styled from 'styled-components'
import autobind from 'autobind-decorator'
import DropdownButton from '@src/components/ui/Dropdowns/DropdownButton'
import { ThemePalette, ThemeProps } from '@src/components/Theme'
import userStore from '@src/stores/UserStore'
import configLoader from '@src/utils/Config'
import { navigationMenu } from '@src/constants'
import migrationImage from './images/migration.svg'
import replicaImage from './images/replica.svg'
import endpointImage from './images/endpoint.svg'
import userImage from './images/user.svg'
import projectImage from './images/project.svg'
import minionPoolImage from './images/minion-pool.svg'
const ICON_MAP = {
migration: migrationImage,
replica: replicaImage,
endpoint: endpointImage,
minionPool: minionPoolImage,
user: userImage,
project: projectImage,
}
const Wrapper = styled.div<any>`
position: relative;
`
const List = styled.div<any>`
cursor: pointer;
background: ${ThemePalette.grayscale[1]};
border-radius: ${ThemeProps.borderRadius};
width: 240px;
position: absolute;
right: 0;
top: 45px;
z-index: 10;
${ThemeProps.boxShadow}
`
const ListItem = styled(Link)`
display: flex;
align-items: center;
border-bottom: 1px solid white;
transition: all ${ThemeProps.animations.swift};
text-decoration: none;
color: ${ThemePalette.black};
&:hover {
background: ${ThemePalette.grayscale[0]};
}
&:last-child {
border-bottom-left-radius: ${ThemeProps.borderRadius};
border-bottom-right-radius: ${ThemeProps.borderRadius};
}
&:first-child {
position: relative;
border-top-left-radius: ${ThemeProps.borderRadius};
border-top-right-radius: ${ThemeProps.borderRadius};
&:after {
content: ' ';
position: absolute;
width: 10px;
height: 10px;
background: ${ThemePalette.grayscale[1]};
border: 1px solid ${ThemePalette.grayscale[1]};
border-color: transparent transparent ${ThemePalette.grayscale[1]} ${ThemePalette.grayscale[1]};
transform: rotate(135deg);
right: 10px;
top: -6px;
transition: all ${ThemeProps.animations.swift};
}
&:hover:after {
background: ${ThemePalette.grayscale[0]};
border: 1px solid ${ThemePalette.grayscale[0]};
border-color: transparent transparent ${ThemePalette.grayscale[0]} ${ThemePalette.grayscale[0]};
}
}
`
const Icon = styled.div<{ iconName: keyof typeof ICON_MAP }>`
min-width: 48px;
height: 48px;
background: url('${props => ICON_MAP[props.iconName]}') no-repeat center;
margin: 16px;
`
const Content = styled.div<any>`
padding-right: 16px;
`
const Title = styled.div<any>`
font-size: 16px;
margin-bottom: 8px;
`
const Description = styled.div<any>`
font-size: 12px;
color: ${ThemePalette.grayscale[4]};
`
export type ItemType = {
href?: string,
iconName: keyof typeof ICON_MAP,
title: string,
description: string,
value?: string,
disabled?: boolean,
requiresAdmin?: boolean,
}
type Props = {
onChange: (item: ItemType) => void,
}
type State = {
showDropdownList: boolean,
}
@observer
class NewItemDropdown extends React.Component<Props, State> {
state = {
showDropdownList: false,
}
itemMouseDown: boolean | undefined
componentDidMount() {
window.addEventListener('mousedown', this.handlePageClick, false)
}
componentWillUnmount() {
window.removeEventListener('mousedown', this.handlePageClick, false)
}
@autobind
handlePageClick() {
if (!this.itemMouseDown) {
this.setState({ showDropdownList: false })
}
}
handleButtonClick() {
this.setState(prev => ({ showDropdownList: !prev.showDropdownList }))
}
handleItemClick(item: ItemType) {
this.setState({ showDropdownList: false })
if (this.props.onChange) {
this.props.onChange(item)
}
}
renderList() {
if (!this.state.showDropdownList) {
return null
}
const isAdmin = userStore.loggedUser ? userStore.loggedUser.isAdmin : false
const disabledPages = configLoader.config ? configLoader.config.disabledPages : []
const items: ItemType[] = [
{
title: 'Migration',
href: '/wizard/migration',
description: 'Migrate VMs between two clouds',
iconName: 'migration',
},
{
title: 'Replica',
href: '/wizard/replica',
description: 'Incrementally replicate VMs between two clouds',
iconName: 'replica',
},
{
title: 'Endpoint',
value: 'endpoint',
description: 'Add connection information for a cloud',
iconName: 'endpoint',
},
{
title: 'Minion Pool',
value: 'minionPool',
description: 'Create a new Coriolis Minion Pool',
iconName: 'minionPool',
},
{
title: 'User',
value: 'user',
description: 'Create a new Coriolis user',
iconName: 'user',
disabled: Boolean(navigationMenu.find(i => i.value === 'users'
&& (disabledPages.find(p => p === 'users') || (i.requiresAdmin && !isAdmin)))),
},
{
title: 'Project',
value: 'project',
description: 'Create a new Coriolis project',
iconName: 'project',
disabled: Boolean(navigationMenu.find(i => i.value === 'projects'
&& (disabledPages.find(p => p === 'users') || (i.requiresAdmin && !isAdmin)))),
},
]
const list = (
<List>
{
items.filter(i => (i.disabled ? !i.disabled : i.requiresAdmin ? isAdmin : true))
.map(item => (
<ListItem
key={item.title}
onMouseDown={() => { this.itemMouseDown = true }}
onMouseUp={() => { this.itemMouseDown = false }}
to={item.href || '#'}
onClick={() => { this.handleItemClick(item) }}
>
<Icon
iconName={item.iconName}
/>
<Content>
<Title>{item.title}</Title>
<Description>{item.description}</Description>
</Content>
</ListItem>
))
}
</List>
)
return list
}
render() {
return (
<Wrapper>
<DropdownButton
onMouseDown={() => { this.itemMouseDown = true }}
onMouseUp={() => { this.itemMouseDown = false }}
onClick={() => this.handleButtonClick()}
value="New"
primary
centered
/>
{this.renderList()}
</Wrapper>
)
}
}
export default NewItemDropdown
| agpl-3.0 |
venturehive/canvas-lms | spec/selenium/grades/pages/gradezilla_grade_detail_tray_page.rb | 4570 | #
# Copyright (C) 2017 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas 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 Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
require_relative '../../common'
class Gradezilla
class GradeDetailTray
class << self
include SeleniumDependencies
def submission_tray_full_content
f('#SubmissionTray__Content')
end
def avatar
f("#SubmissionTray__Avatar")
end
def student_name
f("#SubmissionTray__StudentName")
end
def status_radio_button(type)
fj("label[data-reactid*='#{type}']")
end
def status_radio_button_input(type)
fj("input[value=#{type}]")
end
def late_by_input_css
".SubmissionTray__RadioInput input[id*='NumberInput']"
end
def late_by_hours
fj("label:contains('Hours late')")
end
def late_by_days
fj("label:contains('Days late')")
end
def close_tray_X
fj("button[data-reactid*='closeButton']")
end
def late_penalty_text
f("#late-penalty-value").text
end
def final_grade_text
f("#final-grade-value").text
end
def speedgrader_link
fj("a:contains('SpeedGrader')")
end
def assignment_left_arrow_selector
'#assignment-carousel .left-arrow-button-container button'
end
def assignment_right_arrow_selector
'#assignment-carousel .right-arrow-button-container button'
end
def next_assignment_button
f(assignment_right_arrow_selector)
end
def previous_assignment_button
f(assignment_left_arrow_selector)
end
def assignment_link(assignment_name)
fj("a:contains('#{assignment_name}')")
end
def student_link(student_name)
fj("a:contains(#{student_name})")
end
def navigate_to_next_student_selector
"#student-carousel .right-arrow-button-container button"
end
def navigate_to_previous_student_selector
"#student-carousel .left-arrow-button-container button"
end
def next_student_button
fj(navigate_to_next_student_selector)
end
def previous_student_button
fj(navigate_to_previous_student_selector)
end
def all_comments
f("#SubmissionTray__Comments")
end
def delete_comment_button(comment)
fj("button:contains('Delete Comment: #{comment}')")
end
def comment_author_link
ff("#SubmissionTray__Comments a")
end
def new_comment_input
f("#SubmissionTray__Comments textarea")
end
def comment(comment_to_find)
fj("#SubmissionTray__Comments p:contains('#{comment_to_find}')")
end
def comment_save_button
fj("button:contains('Submit')")
end
def grade_input
f('#grade-detail-tray--grade-input')
end
# methods
def change_status_to(type)
status_radio_button(type).click
driver.action.send_keys(:space).perform
end
def is_radio_button_selected(type)
status_radio_button_input(type).selected?
end
def fetch_late_by_value
fj(late_by_input_css)['value']
end
def edit_late_by_input(value)
fj(late_by_input_css).click
set_value(fj(late_by_input_css), value)
# shifting focus from input = saving the changes
driver.action.send_keys(:tab).perform
wait_for_ajax_requests
end
def edit_grade(new_grade)
grade_input.click
set_value(grade_input, new_grade)
# focus outside the input to save
driver.action.send_keys(:tab).perform
wait_for_ajax_requests
end
def add_new_comment(new_comment)
set_value(new_comment_input, new_comment)
comment_save_button.click
wait_for_ajax_requests
end
def delete_comment(comment)
delete_comment_button(comment).click
accept_alert
end
end
end
end
| agpl-3.0 |