code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
CREATE TABLE "measure_17_percentage_of_families_with_high_out_of_pocket_medical_expenses_metropolitan_status" (
"measure_value" text,
"year" real,
"rural_urban" text,
"income_threshold" text
);
|
talos/docker4data
|
data/socrata/healthmeasures.aspe.hhs.gov/measure_17_percentage_of_families_with_high_out_of_pocket_medical_expenses_metropolitan_status/schema.sql
|
SQL
|
gpl-3.0
| 198
|
#ifndef LIBXMP_MIXER_H
#define LIBXMP_MIXER_H
#define C4_PERIOD 428.0
#define SMIX_NUMVOC 128 /* default number of softmixer voices */
#define SMIX_SHIFT 16
#define SMIX_MASK 0xffff
#define FILTER_SHIFT 16
#define ANTICLICK_SHIFT 3
#ifdef LIBXMP_PAULA_SIMULATOR
#include "paula.h"
#endif
#define SMIX_MIXER(f) void f(struct mixer_voice *vi, int *buffer, \
int count, int vl, int vr, int step, int ramp, int delta_l, int delta_r)
struct mixer_voice {
int chn; /* channel number */
int root; /* */
int note; /* */
#define PAN_SURROUND 0x8000
int pan; /* */
int vol; /* */
double period; /* current period */
double pos; /* position in sample */
int pos0; /* position in sample before mixing */
int fidx; /* mixer function index */
int ins; /* instrument number */
int smp; /* sample number */
int end; /* loop end */
int act; /* nna info & status of voice */
int old_vl; /* previous volume, left channel */
int old_vr; /* previous volume, right channel */
int sleft; /* last left sample output, in 32bit */
int sright; /* last right sample output, in 32bit */
#define VOICE_RELEASE (1 << 0)
#define ANTICLICK (1 << 1)
#define SAMPLE_LOOP (1 << 2)
int flags; /* flags */
void *sptr; /* sample pointer */
#ifdef LIBXMP_PAULA_SIMULATOR
struct paula_state *paula; /* paula simulation state */
#endif
#ifndef LIBXMP_CORE_DISABLE_IT
struct {
int r1; /* filter variables */
int r2;
int l1;
int l2;
int a0;
int b0;
int b1;
int cutoff;
int resonance;
} filter;
#endif
};
int mixer_on (struct context_data *, int, int, int);
void mixer_off (struct context_data *);
void mixer_setvol (struct context_data *, int, int);
void mixer_seteffect (struct context_data *, int, int, int);
void mixer_setpan (struct context_data *, int, int);
int mixer_numvoices (struct context_data *, int);
void mixer_softmixer (struct context_data *);
void mixer_reset (struct context_data *);
void mixer_setpatch (struct context_data *, int, int);
void mixer_voicepos (struct context_data *, int, double);
int mixer_getvoicepos (struct context_data *, int);
void mixer_setnote (struct context_data *, int, int);
void mixer_setperiod (struct context_data *, int, double);
void mixer_release (struct context_data *, int, int);
#endif /* LIBXMP_MIXER_H */
|
DodgeeSoftware/OpenALWrapper
|
_dependencies/libxmp-4.4.0/src/mixer.h
|
C
|
gpl-3.0
| 2,311
|
/*
===========================================================================
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.
===========================================================================
*/
#ifndef __RENDERPROGS_H__
#define __RENDERPROGS_H__
static const int PC_ATTRIB_INDEX_VERTEX = 0;
static const int PC_ATTRIB_INDEX_COLOR = 3;
static const int PC_ATTRIB_INDEX_ST = 8;
static const int PC_ATTRIB_INDEX_TANGENT = 9;
static const int PC_ATTRIB_INDEX_BITANGENT = 10;
static const int PC_ATTRIB_INDEX_NORMAL = 11;
// This enum list corresponds to the global constant register indecies as defined in global.inc for all
// shaders. We used a shared pool to keeps things simple. If something changes here then it also
// needs to change in global.inc and vice versa
enum renderParm_t {
// For backwards compatibility, do not change the order of the first 17 items
RENDERPARM_SCREENCORRECTIONFACTOR = 0,
RENDERPARM_WINDOWCOORD,
RENDERPARM_DIFFUSEMODIFIER,
RENDERPARM_SPECULARMODIFIER,
RENDERPARM_LOCALLIGHTORIGIN,
RENDERPARM_LOCALVIEWORIGIN,
RENDERPARM_LIGHTPROJECTION_S,
RENDERPARM_LIGHTPROJECTION_T,
RENDERPARM_LIGHTPROJECTION_Q,
RENDERPARM_LIGHTFALLOFF_S,
RENDERPARM_BUMPMATRIX_S,
RENDERPARM_BUMPMATRIX_T,
RENDERPARM_DIFFUSEMATRIX_S,
RENDERPARM_DIFFUSEMATRIX_T,
RENDERPARM_SPECULARMATRIX_S,
RENDERPARM_SPECULARMATRIX_T,
RENDERPARM_VERTEXCOLOR_MODULATE,
RENDERPARM_VERTEXCOLOR_ADD,
// The following are new and can be in any order
RENDERPARM_COLOR,
RENDERPARM_VIEWORIGIN,
RENDERPARM_GLOBALEYEPOS,
RENDERPARM_MVPMATRIX_X,
RENDERPARM_MVPMATRIX_Y,
RENDERPARM_MVPMATRIX_Z,
RENDERPARM_MVPMATRIX_W,
RENDERPARM_MODELMATRIX_X,
RENDERPARM_MODELMATRIX_Y,
RENDERPARM_MODELMATRIX_Z,
RENDERPARM_MODELMATRIX_W,
RENDERPARM_PROJMATRIX_X,
RENDERPARM_PROJMATRIX_Y,
RENDERPARM_PROJMATRIX_Z,
RENDERPARM_PROJMATRIX_W,
RENDERPARM_MODELVIEWMATRIX_X,
RENDERPARM_MODELVIEWMATRIX_Y,
RENDERPARM_MODELVIEWMATRIX_Z,
RENDERPARM_MODELVIEWMATRIX_W,
RENDERPARM_TEXTUREMATRIX_S,
RENDERPARM_TEXTUREMATRIX_T,
RENDERPARM_TEXGEN_0_S,
RENDERPARM_TEXGEN_0_T,
RENDERPARM_TEXGEN_0_Q,
RENDERPARM_TEXGEN_0_ENABLED,
RENDERPARM_TEXGEN_1_S,
RENDERPARM_TEXGEN_1_T,
RENDERPARM_TEXGEN_1_Q,
RENDERPARM_TEXGEN_1_ENABLED,
RENDERPARM_WOBBLESKY_X,
RENDERPARM_WOBBLESKY_Y,
RENDERPARM_WOBBLESKY_Z,
RENDERPARM_OVERBRIGHT,
RENDERPARM_ENABLE_SKINNING,
RENDERPARM_ALPHA_TEST,
RENDERPARM_TOTAL,
RENDERPARM_USER = 128,
};
struct glslUniformLocation_t {
int parmIndex;
GLint uniformIndex;
};
/*
================================================================================================
idRenderProgManager
================================================================================================
*/
class idRenderProgManager {
public:
idRenderProgManager();
virtual ~idRenderProgManager();
void Init();
void Shutdown();
void SetRenderParm( renderParm_t rp, const float * value );
void SetRenderParms( renderParm_t rp, const float * values, int numValues );
int FindVertexShader( const char * name );
int FindFragmentShader( const char * name );
void BindShader( int vIndex, int fIndex );
void BindShader_GUI( ) { BindShader_Builtin( BUILTIN_GUI ); }
void BindShader_Color( ) { BindShader_Builtin( BUILTIN_COLOR ); }
void BindShader_Texture( ) { BindShader_Builtin( BUILTIN_TEXTURED ); }
void BindShader_TextureVertexColor() { BindShader_Builtin( BUILTIN_TEXTURE_VERTEXCOLOR ); };
void BindShader_TextureTexGenVertexColor() { BindShader_Builtin( BUILTIN_TEXTURE_TEXGEN_VERTEXCOLOR ); };
void BindShader_Interaction() { BindShader_Builtin( BUILTIN_INTERACTION ); }
void BindShader_InteractionAmbient() { BindShader_Builtin( BUILTIN_INTERACTION_AMBIENT ); }
void BindShader_SimpleShade() { BindShader_Builtin( BUILTIN_SIMPLESHADE ); }
void BindShader_Environment() { BindShader_Builtin( BUILTIN_ENVIRONMENT ); }
void BindShader_BumpyEnvironment() { BindShader_Builtin( BUILTIN_BUMPY_ENVIRONMENT ); }
void BindShader_Depth() { BindShader_Builtin( BUILTIN_DEPTH ); }
void BindShader_Shadow() { BindShader( builtinShaders[BUILTIN_SHADOW], -1 ); }
void BindShader_ShadowDebug() { BindShader_Builtin( BUILTIN_SHADOW_DEBUG ); }
void BindShader_BlendLight() { BindShader_Builtin( BUILTIN_BLENDLIGHT ); }
void BindShader_Fog() { BindShader_Builtin( BUILTIN_FOG ); }
void BindShader_SkyBox() { BindShader_Builtin( BUILTIN_SKYBOX ); }
void BindShader_WobbleSky() { BindShader_Builtin( BUILTIN_WOBBLESKY ); }
void BindShader_StereoDeGhost() { BindShader_Builtin( BUILTIN_STEREO_DEGHOST ); }
void BindShader_StereoWarp() { BindShader_Builtin( BUILTIN_STEREO_WARP ); }
void BindShader_StereoInterlace() { BindShader_Builtin( BUILTIN_STEREO_INTERLACE ); }
void BindShader_PostProcess() { BindShader_Builtin( BUILTIN_POSTPROCESS ); }
void BindShader_MotionBlur() { BindShader_Builtin( BUILTIN_MOTION_BLUR); }
// unbind the currently bound render program
void Unbind();
// this should only be called via the reload shader console command
void LoadAllShaders();
void KillAllShaders();
static const int MAX_GLSL_USER_PARMS = 8;
const char* GetGLSLParmName( int rp ) const;
int GetGLSLCurrentProgram() const { return currentRenderProgram; }
void SetUniformValue( const renderParm_t rp, const float * value );
void CommitUniforms();
int FindGLSLProgram( const char* name, int vIndex, int fIndex );
void ZeroUniforms();
protected:
void LoadVertexShader( int index );
void LoadFragmentShader( int index );
enum {
BUILTIN_GUI,
BUILTIN_COLOR,
BUILTIN_SIMPLESHADE,
BUILTIN_TEXTURED,
BUILTIN_TEXTURE_VERTEXCOLOR,
BUILTIN_TEXTURE_TEXGEN_VERTEXCOLOR,
BUILTIN_INTERACTION,
BUILTIN_INTERACTION_AMBIENT,
BUILTIN_ENVIRONMENT,
BUILTIN_BUMPY_ENVIRONMENT,
BUILTIN_DEPTH,
BUILTIN_SHADOW,
BUILTIN_SHADOW_DEBUG,
BUILTIN_BLENDLIGHT,
BUILTIN_FOG,
BUILTIN_SKYBOX,
BUILTIN_WOBBLESKY,
BUILTIN_POSTPROCESS,
BUILTIN_STEREO_DEGHOST,
BUILTIN_STEREO_WARP,
BUILTIN_STEREO_INTERLACE,
BUILTIN_MOTION_BLUR,
MAX_BUILTINS
};
int builtinShaders[MAX_BUILTINS];
void BindShader_Builtin( int i ) { BindShader( builtinShaders[i], builtinShaders[i] ); }
bool CompileGLSL( GLenum target, const char * name );
GLuint LoadGLSLShader( GLenum target, const char * name, idList<int> & uniforms );
void LoadGLSLProgram( const int programIndex, const int vertexShaderIndex, const int fragmentShaderIndex );
static const GLuint INVALID_PROGID = 0xFFFFFFFF;
struct vertexShader_t {
vertexShader_t() : progId( INVALID_PROGID ) {}
idStr name;
GLuint progId;
idList<int> uniforms;
};
struct fragmentShader_t {
fragmentShader_t() : progId( INVALID_PROGID ) {}
idStr name;
GLuint progId;
idList<int> uniforms;
};
struct glslProgram_t {
glslProgram_t() : progId( INVALID_PROGID ),
vertexShaderIndex( -1 ),
fragmentShaderIndex( -1 ),
vertexUniformArray( -1 ),
fragmentUniformArray( -1 ) {}
idStr name;
GLuint progId;
int vertexShaderIndex;
int fragmentShaderIndex;
GLint vertexUniformArray;
GLint fragmentUniformArray;
idList<glslUniformLocation_t> uniformLocations;
};
int currentRenderProgram;
idList<glslProgram_t> glslPrograms;
idStaticList<idVec4, RENDERPARM_USER + MAX_GLSL_USER_PARMS> glslUniforms;
int currentVertexShader;
int currentFragmentShader;
idList<vertexShader_t> vertexShaders;
idList<fragmentShader_t> fragmentShaders;
};
extern idRenderProgManager renderProgManager;
#endif
|
anonreclaimer/morpheus
|
neo/renderer/RenderProgs.h
|
C
|
gpl-3.0
| 8,883
|
// Java Implementation of Radix Sort
public class Radix_Sort
{
// Function implementing Radix Sort
public static void radix_sort(int input[])
{
int i;
int max = input[0]; // Maximum Element in input array
int size = input.length;
// Find the Maximum element in array
for (i = 1; i < size; i++)
{
if (input[i] > max)
max = input[i];
}
for (int exp = 1; max / exp > 0; exp *= 10)
{
Counting_Sort(input, size, exp); // Subroutine call to Counting_Sort
}
}
// Counting_Sort
public static void Counting_Sort(int input[], int size, int exp)
{
int output[] = new int[size];
int i;
int count[] = new int[10];
for (i = 0; i < size; i++)
count[(input[i] / exp) % 10]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = size - 1; i >= 0; i--)
{
output[count[(input[i] / exp) % 10] - 1] = input[i];
count[(input[i] / exp) % 10]--;
}
for (i = 0; i < size; i++)
input[i] = output[i];
}
// Driver Function
public static void main(String[] args)
{
int i;
int input[] = {1, 123, 458, 789, 85, 25, 75};
radix_sort(input);
// Printing Sorted Array
for (i = 0; i < input.length; i++)
System.out.print(input[i] + " ");
System.out.println();
}
}
/*
Output: 1 25 75 85 123 458 789
*/
|
KavyaSharma/Algo_Ds_Notes
|
Radix_Sort/Radix_Sort.java
|
Java
|
gpl-3.0
| 1,561
|
<html>
<head>
<title> popcnt_array.asm </title>
</head>
<body>
<pre>
segment .text
global popcnt_array ; let the linker know about popcnt_array
popcnt_array:
push r12
push r13
push r14
push r15
xor eax, eax
xor r8d, r8d
xor r9d, r9d
xor r14d, r14d
xor r15d, r15d
.count_more:
popcnt r10, [rcx+r9*8]
add rax, r10
popcnt r11, [rcx+r9*8+8]
add r8, r11
popcnt r12, [rcx+r9*8+16]
add r14, r12
popcnt r13, [rcx+r9*8+24]
add r15, r13
add r9, 4
cmp r9, rdx
jl .count_more
add rax, r8
add rax, r14
add rax, r15
pop r15
pop r14
pop r13
pop r12
ret
</pre>
</body>
</html>
|
tjphilpot/ebe
|
library/Assembly/Windows/Sample_Programs/Chapter_17/popcntinst.asm.html
|
HTML
|
gpl-3.0
| 906
|
/**
* @license Ulakbus-UI
* Copyright (C) 2015 ZetaOps Inc.
* This file is licensed under the GNU General Public License v3
* (GPLv3). See LICENSE.txt for details.
*/
/**
* @ngdoc module
* @name ulakbus.formService
* @module ulakbus.formService
* @description
* The `formService` module provides generic services for auto generated forms.
* @requires ui.bootstrap
* @type {ng.$compileProvider|*}
*/
angular.module('ulakbus.formService', ['ui.bootstrap'])
/**
* Moment.js used for date type conversions.
* there must be no global object, so we change it into a service here.
*/
.service('Moment', function () {
return window.moment;
})
/**
* @memberof ulakbus.formService
* @ngdoc factory
* @name Generator
* @description form service's Generator factory service handles all generic form operations
*/
.factory('Generator', function ($http, $q, $timeout, $sce, $location, $route, $compile, $log, RESTURL, $rootScope, Moment, WSOps, FormConstraints, $uibModal, $filter, Utils) {
var generator = {};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name makeUrl
* @description this function generates url combining backend url and the related object properties for http requests
* @param scope
* @returns {string}
* @param scope
*/
generator.makeUrl = function (scope) {
var getparams = scope.form_params.param ? "?" + scope.form_params.param + "=" + scope.form_params.id : "";
return RESTURL.url + scope.url + getparams;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name generate
* @param scope
* @param data
* @description - generate function is inclusive for form generation
* defines given scope's client_cmd, model, schema, form, token, object_id objects
* @returns {*} scope
* @param scope
* @param data
*/
generator.generate = function (scope, data) {
$log.debug("data before generation:", data);
// if no form in response (in case of list and single item request) return scope
if (!data.forms) {
return scope;
}
// prepare scope form, schema and model from response object
angular.forEach(data.forms, function (value, key) {
scope[key] = data.forms[key];
});
scope.client_cmd = data.client_cmd;
scope.token = data.token;
// initialModel will be used in formDiff when submiting the form to submit only
scope.initialModel = angular.copy(scope.model);
// if fieldset in form, make it collapsable with template
//scope.listnodeform = {};
//scope.isCollapsed = true;
generator.prepareFormItems(scope);
scope.object_id = scope.form_params.object_id;
$log.debug('scope at after generate', scope);
return scope;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name group
* @param scope
* @description group function to group form layout by form meta data for layout
* grouping will use an object like example below when parsing its items.
* @example
* `grouping = [
* {
* "groups": [
* {
* "group_title": "title1",
* "items": ["item1", "item2", "item3", "item4"],
* }
* ],
* "layout": "4",
* "collapse": False
* },
* {
* "groups": [
* {
* "group_title": "title2",
* "items": ["item5", "item6"],
* }
* ],
* "layout": "2",
* "collapse": False
* }]`
*
* @returns {*}
* @param scope
*/
generator.group = function (scope) {
if (!scope.grouping) {
return scope;
}
var newForm = [];
var extractFormItem = function (itemList) {
var extractedList = [];
angular.forEach(itemList, function (value, key) {
var item = getFormItem(value);
if (item) {
extractedList.push(item);
}
});
$log.debug('extractedList: ', extractedList);
return extractedList;
};
var getFormItem = function (item) {
var formItem;
if (scope.form.indexOf(item) > -1) {
formItem = scope.form[scope.form.indexOf(item)];
scope.form.splice(scope.form.indexOf(item), 1);
return formItem;
} else {
angular.forEach(scope.form, function (value, key) {
if (value.key === item) {
formItem = value;
scope.form.splice(key, 1);
return;
}
});
return formItem;
}
};
var makeGroup = function (itemsToGroup) {
var subItems = [];
angular.forEach(itemsToGroup, function (value, key) {
subItems.push({
type: 'fieldset',
items: extractFormItem(value.items),
title: value.group_title
});
});
return subItems;
};
angular.forEach(scope.grouping, function (value, key) {
newForm.push(
{
type: 'fieldset',
items: makeGroup(value.groups),
htmlClass: 'col-md-' + value.layout,
title: value.group_title
}
)
});
if (newForm.length > 0) {
$log.debug('grouped form: ', newForm);
$log.debug('rest of form: ', scope.form);
$log.debug('form united: ', newForm.concat(scope.form));
}
scope.form = newForm.concat(scope.form);
return scope;
};
/**
* @description generates form constraints as async validators
* async validators defined in form_constraints.js
* keys are input names
* @example
* `
* forms.constraints = {
*
* // date field type constraint to greater than certain date
* 'birth_date': {
* cons: 'gt_date',
* val: '22.10.1988',
* val_msg: 'Birthdate must be greater than 22.10.1988'
* },
* // a number field lesser than a certain number
* 'number': {
* cons: 'lt',
* val: 50,
* val_msg: 'number must be lesser than 50'
* },
* // a field lesser than multiple fields' values
* 'some_input': {
* cons: 'lt_m',
* val: ['this', 'and', 'that', 'inputs'],
* val_msg: 'some_input must be lesser than this, and, that, inputs'
* },
* // a field shows some other fields
* 'some_input2': {
* cons: 'selectbox_fields',
* val: [
* {'val1': ['this', 'and']},
* {'val2': ['this2', 'and2']}]
* val_msg: 'some_input2 disables this, and, this, inputs'
* },
* // a field hides some other fields
* 'some_input3': {
* cons: 'checkbox_fields',
* val: [
* {'val1': ['this', 'and']},
* {'val2': ['this2', 'and2']}]
* val_msg: 'some_input2 disables this, and, this, inputs'
* },
* // todo: a field change changes other field or fields values
* }
* `
* @param scope
*/
generator.constraints = function (scope) {
angular.forEach(scope.form, function (v, k) {
try {
var cons = scope.forms.constraints[v] || scope.forms.constraints[v.key];
if (angular.isDefined(cons)) {
if (v.constructor === String) {
scope.form[k] = {
key: v,
validationMessage: {'form_cons': cons.val_msg},
$validators: {
form_cons: function (value) {
return FormConstraints[cons.cons](value, cons.val, v);
}
}
};
} else {
v.key = v.key;
v.validationMessage = angular.extend({'form_cons': cons.val_msg}, v.validationMessage);
v.$validators = angular.extend({
form_cons: function (value) {
return FormConstraints[cons.cons](value, cons.val, v.key);
}
}, v.$asyncValidators);
}
}
} catch (e) {
$log.error(e.message);
}
});
return generator.group(scope);
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name prepareFormItems
* @param scope {Object} given scope on which form items prepared
* @description
* It looks up fields of schema objects and changes their types to proper type for schemaform.
* To prepare items for schemaform loop items of scope.schema.properties by checking index value's `type` key.
*
* If `type` is in `['file', 'select', 'submit', 'date', 'int', 'text_general', 'model', 'ListNode', 'Node']`
* then the item must be converted into the data format which schemaform works with.
*
*
* For listnode, node and model types it uses templates to generate modal. The modal is aa instance of
* ui.bootstraps modal directive.
*
* @returns scope {Object}
*/
generator.prepareFormItems = function (scope) {
angular.forEach(scope.form, function (value, key) {
// parse markdown for help text
if (value.type === 'help'){
var markdown = $filter('markdown');
value.helpvalue = markdown(value.helpvalue);
}
if (value.type === 'select') {
scope.schema.properties[value.key].type = 'select';
scope.schema.properties[value.key].titleMap = value.titleMap;
scope.form[key] = value.key;
}
});
var _buttons = function (scope, v, k) {
var buttonPositions = scope.modalElements ? scope.modalElements.buttonPositions : {
bottom: 'move-to-bottom',
top: 'move-to-top',
none: ''
};
var workOnForm = scope.modalElements ? scope.modalElements.workOnForm : 'formgenerated';
var workOnDiv = scope.modalElements ? scope.modalElements.workOnDiv : '';
var buttonClass = (buttonPositions[v.position] || buttonPositions.bottom);
var redirectTo = scope.modalElements ? false : true;
// in case backend needs styling the buttons
// it needs to send style key with options below
// btn-default btn-primary btn-success btn-info btn warning
// btn-danger is default
scope.form[scope.form.indexOf(k)] = {
type: v.type,
title: v.title,
style: (v.style || "btn-danger") + " hide bottom-margined " + buttonClass,
onClick: function () {
delete scope.form_params.cmd;
delete scope.form_params.flow;
if (v.cmd) {
scope.form_params["cmd"] = v.cmd;
}
if (v.flow) {
scope.form_params["flow"] = v.flow;
}
if (v.wf) {
delete scope.form_params["cmd"];
scope.form_params["wf"] = v.wf;
}
scope.model[k] = 1;
// todo: test it
if (scope.modalElements) {
scope.submitModalForm();
} else {
if (!v.form_validate && angular.isDefined(v.form_validate)) {
generator.submit(scope, redirectTo);
} else {
scope.$broadcast('schemaFormValidate');
if (scope[workOnForm].$valid) {
generator.submit(scope, redirectTo);
scope.$broadcast('disposeModal');
} else {
// focus to first input with validation error
$timeout(function () {
var firsterror = angular.element(document.querySelectorAll('input.ng-invalid'))[0];
firsterror.focus();
});
}
}
}
}
};
// ADD CONSTRAINTS if cons
// replace buttons according to their position values
$timeout(function () {
var selectorBottom = '.buttons-on-bottom' + workOnDiv;
//var selectorTop = '.buttons-on-top'+workOnDiv;
var buttonsToBottom = angular.element(document.querySelector('.' + buttonClass));
angular.element(document.querySelector(selectorBottom)).append(buttonsToBottom);
//var buttonsToTop = angular.element(document.querySelector('.' + buttonClass));
//angular.element(document.querySelector(selectorTop)).append(buttonsToTop);
buttonsToBottom.removeClass('hide');
//buttonsToTop.removeClass('hide');
}, 500);
};
var _numbers = function (scope, v, k) {
v.type = 'number';
v.validationMessage = {'max': 'bu alan -2147483647 ve 2147483647 arasında olmalıdır.'}
v.$validators = {
max: function(value){
return 2147483647>value>-2147483647;
}
};
scope.model[k] = parseInt(scope.model[k]);
};
var _node_default = function (scope, v, k) {
scope[v.type] = scope[v.type] || {};
// no pass by reference
scope[v.type][k] = angular.copy({
title: v.title,
form: [],
schema: {
properties: {},
properties_list: [],
required: [],
title: v.title,
type: "object",
formType: v.type,
model_name: k,
inline_edit: scope.inline_edit
},
buttons: v.buttons,
url: scope.url,
wf: v.wf || scope.wf,
quick_add: v.quick_add,
quick_add_view: v.quick_add_view,
quick_add_model: v.quick_add_model,
quick_add_field: v.quick_add_field,
nodeModelChange: function (item) {
}
});
angular.forEach(v.schema, function (item) {
scope[v.type][k].schema.properties[item.name] = angular.copy(item);
// save properties order in schema
if (item.name != 'idx'){
scope[v.type][k].schema.properties_list.push(scope[v.type][k].schema.properties[item.name]);
}
if (angular.isDefined(item.wf)) {
scope[v.type][k].schema.properties[item.name]['wf'] = angular.copy(item.wf);
}
// prepare required fields
if (item.required === true && item.name !== 'idx') {
scope[v.type][k].schema.required.push(angular.copy(item.name));
}
// idx field must be hidden
if (item.name !== 'idx') {
scope[v.type][k].form.push(item.name);
}
try {
if (item.type === 'date') {
//scope.model[k][item.name] = generator.dateformatter(scope.model[k][item.name]);
}
} catch (e) {
$log.debug('Error: ', e.message);
}
});
$timeout(function () {
if (v.type != 'ListNode') return;
// todo: needs refactor
var list = scope[v.type][k];
list.items = angular.copy(scope.model[k] || []);
angular.forEach(list.items, function (node, fieldName) {
if (!Object.keys(node).length) return;
angular.forEach(node, function (prop, propName) {
var propInSchema = list.schema.properties[propName];
try {
if (propInSchema.type === 'date') {
node[propName] = generator.dateformatter(prop);
list.model[fieldName][propName] = generator.dateformatter(prop);
}
if (propInSchema.type === 'select') {
node[propName] = generator.item_from_array(prop.toString(), list.schema.properties[propName].titleMap)
}
if (propInSchema.titleMap){
node[propName] = {
key: prop,
unicode: generator.item_from_array(prop, propInSchema.titleMap)
};
}
} catch (e) {
$log.debug('Field is not date');
}
});
});
});
scope.model[k] = scope.model[k] || [];
scope[v.type][k].model = scope.model[k];
// lengthModels is length of the listnode models. if greater than 0 show records on template
scope[v.type][k]['lengthModels'] = scope.model[k] ? 1 : 0;
};
var _node_filter_interface = function (scope, v, k) {
var formitem = scope.form[scope.form.indexOf(k)];
var modelScope = {
"form_params": {
wf: v.wf || scope.wf || scope.form_params.wf,
model: v.model_name || v.schema[0].model_name,
cmd: v.list_cmd || 'select_list',
query: ''
}
};
scope.generateTitleMap = function (modelScope) {
generator.get_list(modelScope).then(function (res) {
formitem.titleMap = [];
angular.forEach(res.objects, function (item) {
if (item !== "-1") {
formitem.titleMap.push({
"value": item.key,
"name": item.value
});
}
});
formitem.filteredItems = generator.get_diff_array(angular.copy(formitem.titleMap), angular.copy(formitem.selectedFilteredItems), 1);
})
};
var modelItems = [];
var modelKeys = [];
angular.forEach(scope.model[k], function (value, mkey) {
modelItems.push({
"value": value[v.schema[0].name].key,
"name": value[v.schema[0].name].unicode
});
var modelKey = {};
modelKey[v.schema[0].name] = value[v.schema[0].name].key;
modelKeys.push(modelKey);
});
scope.model[k] = angular.copy(modelKeys);
formitem = {
type: "template",
templateUrl: "shared/templates/multiselect.html",
title: v.title,
// formName will be used in modal return to save item on form
formName: k,
wf: v.wf || scope.wf,
add_cmd: v.add_cmd,
name: v.model_name || v.schema[0].model_name,
model_name: v.model_name || v.schema[0].model_name,
filterValue: '',
selected_item: {},
filteredItems: [],
selectedFilteredItems: modelItems,
titleMap: scope.generateTitleMap(modelScope),
appendFiltered: function (filterValue) {
if (filterValue.length > 2) {
formitem.filteredItems = [];
angular.forEach(formitem.titleMap, function (value, key) {
if (value.name.indexOf(filterValue) > -1) {
formitem.filteredItems.push(formitem.titleMap[key]);
}
});
}
if (filterValue <= 2) {
formitem.filteredItems = formitem.titleMap
}
formitem.filteredItems = generator.get_diff_array(formitem.filteredItems, formitem.selectedFilteredItems);
},
select: function (selectedItemsModel) {
if (!selectedItemsModel) {
return;
}
formitem.selectedFilteredItems = formitem.selectedFilteredItems.concat(selectedItemsModel);
formitem.appendFiltered(formitem.filterValue);
scope.model[k] = (scope.model[k] || []).concat(formitem.dataToModel(selectedItemsModel));
},
deselect: function (selectedFilteredItemsModel) {
if (!selectedFilteredItemsModel) {
return;
}
formitem.selectedFilteredItems = generator.get_diff_array(angular.copy(formitem.selectedFilteredItems), angular.copy(selectedFilteredItemsModel));
formitem.appendFiltered(formitem.filterValue);
formitem.filteredItems = formitem.filteredItems.concat(selectedFilteredItemsModel);
scope.model[k] = generator.get_diff_array(scope.model[k] || [], formitem.dataToModel(selectedFilteredItemsModel));
},
dataToModel: function (data) {
var dataValues = [];
angular.forEach(data, function (value, key) {
var dataKey = {};
dataKey[v.schema[0].name] = value.value;
dataValues.push(dataKey);
});
return dataValues;
}
};
scope.form[scope.form.indexOf(k)] = formitem;
};
// generate_fields covers all field types as functions
var generate_fields = {
button: {default: _buttons},
submit: {default: _buttons},
file: {
default: function (scope, v, k) {
scope.form[scope.form.indexOf(k)] = {
type: "template",
title: v.title,
templateUrl: "shared/templates/filefield.html",
name: k,
key: k,
fileInsert: function () {
$scope.$broadcast('schemaForm.error.' + k, 'tv4-302', true);
},
imageSrc: scope.model[k] ? $rootScope.settings.static_url + scope.model[k] : '',
avatar: k === 'avatar'
};
v.type = 'string';
}
},
select: {
default: function (scope, v, k) {
scope.form[scope.form.indexOf(k)] = {
type: "template",
title: v.title,
templateUrl: "shared/templates/select.html",
name: k,
key: k,
titleMap: v.titleMap
};
}
},
confirm: {
default: function (scope, v, k) {
scope.form[scope.form.indexOf(k)] = {
type: "template",
title: v.title,
confirm_message: v.confirm_message,
templateUrl: "shared/templates/confirm.html",
name: k,
key: k,
style: v.style,
buttons: v.buttons,
modalInstance: "",
// buttons is an object array
//Example:
//buttons: [{
// text: "Button text",
// cmd: "button command",
// style: "btn-warning",
// dismiss: false --> this one is for deciding if the button can dismiss modal
//}]
modalFunction: function(){
delete scope.form_params.cmd;
delete scope.form_params.flow;
if (v.cmd) {
scope.form_params["cmd"] = v.cmd;
}
if (v.flow) {
scope.form_params["flow"] = v.flow;
}
if (v.wf) {
delete scope.form_params["cmd"];
scope.form_params["wf"] = v.wf;
}
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'shared/templates/confirmModalContent.html',
controller: 'ModalController',
resolve: {
items: function(){
var newscope = {
form: {
title: v.title,
confirm_message: v.confirm_message,
buttons: v.buttons,
onClick: function (cmd) {
// send cmd with submit
modalInstance.dismiss();
if (cmd) generator.submit(scope, false);
}
}
};
return newscope;
}
}
});
},
openModal: function(){
var workOnForm = scope.modalElements ? scope.modalElements.workOnForm : 'formgenerated';
if (!v.form_validate && angular.isDefined(v.form_validate)){
this.modalFunction();
}
else{
scope.$broadcast('schemaFormValidate');
if (scope[workOnForm].$valid) {
this.modalFunction();
} else {
// focus to first input with validation error
$timeout(function () {
var firsterror = angular.element(document.querySelectorAll('input.ng-invalid'))[0];
firsterror.focus();
});
}
}
}
};
}
},
date: {
default: function (scope, v, k) {
$log.debug('date:', scope.model[k]);
scope.model[k] = generator.dateformatter(scope.model[k]);
scope.form[scope.form.indexOf(k)] = {
key: k, name: k, title: v.title,
type: 'template',
templateUrl: 'shared/templates/datefield.html',
validationMessage: {
'dateNotValid': "Girdiğiniz tarih geçerli değildir. <i>orn: '01.01.2015'<i/>",
302: 'Bu alan zorunludur.'
},
$asyncValidators: {
'dateNotValid': function (value) {
var deferred = $q.defer();
$timeout(function () {
scope.model[k] = angular.copy(generator.dateformatter(value));
if (scope.schema.required.indexOf(k) > -1) {
deferred.resolve();
}
if (value.constructor === Date) {
deferred.resolve();
}
else {
var dateValue = d = value.split('.');
if (isNaN(Date.parse(value)) || dateValue.length !== 3) {
deferred.reject();
} else {
deferred.resolve();
}
}
});
return deferred.promise;
}
},
disabled: false,
is_disabled: function () {
return this.disabled;
},
status: {opened: false},
open: function ($event) {
this.disabled = true;
// scope.$apply();
scope.model[k] = Moment(scope.model[k], "DD.MM.YYYY").toDate();
var that = this;
$timeout(function () {
that.status.opened = true;
}, 100);
},
format: 'dd.MM.yyyy',
onSelect: function () {
this.disabled = false;
scope.model[k] = angular.copy(generator.dateformatter(scope.model[k]));
}
};
}
},
int: {default: _numbers},
boolean: {
default: function (scope, v, k) {
}
},
string: {
default: function (scope, v, k) {
}
},
typeahead: {
default: function (scope, v, k) {
scope.form[scope.form.indexOf(k)] = {
type: "template",
title: v.title,
titleMap: v.titleMap,
templateUrl: "shared/templates/typeahead.html",
name: k,
key: k,
onDropdownSelect: function (item, inputname) {
scope.model[k] = item.value;
$timeout(function () {
document.querySelector('input[name=' + inputname + ']').value = item.name;
});
}
};
v.type = 'string';
},
custom: function (scope, v, k) {
scope.form[scope.form.indexOf(k)] = {
type: "template",
title: v.title,
widget: v.widget,
getTitleMap: function (viewValue) {
// v.view is where that value will looked up
var searchData = {
"form_params": {
"url": v.wf,
"wf": v.wf,
"view": v.view,
"query": viewValue
}
};
generator.get_list(searchData).then(function (res) {
// response must be in titleMap format
return res;
});
},
templateUrl: "shared/templates/typeahead.html",
name: k,
key: k,
onDropdownSelect: function (item, inputname) {
scope.model[k] = item.value;
$timeout(function () {
document.querySelector('input[name=' + inputname + ']').value = item.name;
});
}
};
v.type = 'string';
}
},
text_general: {
default: function (scope, v, k) {
v.type = 'string',
v["x-schema-form"] = {
"type": "textarea"
}
}
},
float: {default: _numbers},
model: {
default: function (scope, v, k) {
var formitem = scope.form[scope.form.indexOf(k)];
var modelScope = {
"url": v.wf,
"wf": v.wf,
"form_params": {wf: v.wf, model: v.model_name, cmd: v.list_cmd}
};
//scope.$on('refreshTitleMap', function (event, data) {
// todo: write a function to refresh titleMap after new item add to linkedModel
//});
var generateTitleMap = function (modelScope) {
return generator.get_list(modelScope).then(function (res) {
formitem.titleMap = [];
angular.forEach(res.objects, function (item) {
if (item !== -1) {
formitem.titleMap.push({
"value": item.key,
"name": item.value
});
} else {
formitem.focusToInput = true;
}
});
return formitem.titleMap;
});
};
formitem = {
type: "template",
templateUrl: "shared/templates/foreignKey.html",
// formName will be used in modal return to save item on form
formName: k,
title: v.title,
wf: v.wf,
add_cmd: v.add_cmd,
name: k,
key: k,
model_name: v.model_name,
selected_item: {},
titleMap: [],
onSelect: function (item, inputname) {
scope.model[k] = item.value;
$timeout(function () {
document.querySelector('input[name=' + inputname + ']').value = item.name;
});
},
onDropdownSelect: function (item, inputname) {
scope.model[k] = item.value;
$timeout(function () {
document.querySelector('input[name=' + inputname + ']').value = item.name;
});
},
getTitleMap: function (viewValue) {
modelScope.form_params.query = viewValue;
return generateTitleMap(modelScope);
},
getDropdownTitleMap: function () {
delete modelScope.form_params.query;
formitem.gettingTitleMap = true;
generateTitleMap(modelScope)
.then(function (data) {
formitem.titleMap = data;
formitem.gettingTitleMap = false;
});
}
};
scope.form[scope.form.indexOf(k)] = formitem;
// get selected item from titleMap using model value
if (scope.model[k]) {
generator.get_list({
url: 'crud',
form_params: {
wf: v.wf,
model: v.model_name,
object_id: scope.model[k],
cmd: 'object_name'
}
}).then(function (data) {
try {
$timeout(function () {
document.querySelector('input[name=' + k + ']').value = data.object_name;
}, 200);
}
catch (e) {
document.querySelector('input[name=' + k + ']').value = data.object_name;
$log.debug('exception', e);
}
});
}
}
},
Node: {
default: _node_default,
filter_interface: _node_filter_interface
},
ListNode: {
default: _node_default,
filter_interface: _node_filter_interface
}
};
// todo: delete after constraints done
// scope.forms = scope.forms || {};
// scope.forms.constraints = {
// "cinsiyet": {
// "cons": "selectbox_fields",
// "val":
// {'1': ["kiz_kardes_sayisi"], '2': ["erkek_kardes_sayisi"]},
// "val_msg": "Erkek kardes sayisi kiz kardes sayisindan az olamaz."
// }
// };
angular.forEach(scope.schema.properties, function (v, k) {
// generically change _id fields model value
if ('form_params' in scope) {
if (k == scope.form_params.param) {
scope.model[k] = scope.form_params.id;
scope.form.splice(scope.form.indexOf(k), 1);
return;
}
}
try {
generate_fields[v.type][v.widget || 'default'](scope, v, k);
}
catch (e) {
// todo: raise not implemented
console.log(v.type)
}
});
$log.debug('scope at after prepareformitems', scope);
generator.constraints(scope);
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name dateformatter
* @description dateformatter handles all date fields and returns humanized and jquery datepicker format dates
* @param {Object} formObject
* @returns {*}
*/
generator.dateformatter = function (formObject) {
var ndate = new Date(formObject);
if (isNaN(ndate)) {
return '';
} else {
var newdatearray = Moment(ndate).format('DD.MM.YYYY');
$log.debug('date formatted: ', newdatearray);
return newdatearray;
}
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name doItemAction
* @description `mode` could be in ['normal', 'modal', 'new'] . the default mode is 'normal' and it loads data
* on same
* tab without modal. 'modal' will use modal to manipulate data and do all actions in that modal. 'new'
* will be open new page with response data
* @param {Object} $scope
* @param {string} key
* @param {Object} todo
* @param {string} mode
* @returns {*}
*/
generator.doItemAction = function ($scope, key, todo, mode) {
$scope.form_params.cmd = todo.cmd;
$scope.form_params.wf = $scope.wf;
if (todo.wf) {
$scope.url = todo.wf;
$scope.form_params.wf = todo.wf;
delete $scope.token;
delete $scope.form_params.model;
delete $scope.form_params.cmd
}
if (todo.object_key) {
$scope.form_params[todo.object_key] = key;
} else {
$scope.form_params.object_id = key;
}
$scope.form_params.param = $scope.param;
$scope.form_params.id = $scope.param_id;
$scope.form_params.token = $scope.token;
var _do = {
normal: function () {
$log.debug('normal mode starts');
return generator.get_wf($scope);
},
modal: function () {
$log.debug('modal mode starts');
var modalInstance = $uibModal.open({
animation: true,
backdrop: 'static',
keyboard: false,
templateUrl: 'shared/templates/confirmModalContent.html',
controller: 'ModalController',
size: '',
resolve: {
items: function () {
var newscope = {
form: {
buttons: [ { text: "Evet", style: "btn-success", cmd:"confirm" }, { text: "Hayir", "style": "btn-warning", dismiss: true } ],
title: todo.name,
confirm_message: "Islemi onayliyor musunuz?",
onClick: function(cmd){
modalInstance.close();
if (cmd === "confirm" && angular.isDefined(cmd)) {
modalInstance.close();
return generator.get_wf($scope);
}
}
}
}
return newscope;
}
}
});
},
new: function () {
$log.debug('new mode is not not ready');
}
};
return _do[mode]();
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name button_switch
* @description Changes html disabled and enabled attributes of all buttons on current page.
* @param {boolean} position
*/
// todo: remove
generator.button_switch = function (position) {
var buttons = angular.element(document.querySelectorAll('button'));
var positions = {true: "enabled", false: "disabled"};
angular.forEach(buttons, function (button, key) {
button[positions[position]] = true;
});
$log.debug('buttons >> ', positions[position])
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name get_form
* @description Communicates with api with given scope object.
* @param {Object} scope
* @returns {*}
*/
generator.get_form = function (scope) {
if ($rootScope.websocketIsOpen === true) {
return WSOps.request(scope.form_params)
.then(function (data) {
return generator.generate(scope, data);
});
} else {
$timeout(function () {
generator.get_form(scope);
}, 500);
}
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name get_list
* @description gets list of related wf/model
* @param scope
* @returns {*}
*/
generator.get_list = function (scope) {
if ($rootScope.websocketIsOpen === true) {
return WSOps.request(scope.form_params)
.then(function (data) {
return data;
});
} else {
$timeout(function () {
generator.get_list(scope);
}, 500);
}
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name get_wf
* @description get_wf is the main function for client_cmd based api calls
* based on response content it redirects to related path/controller with pathDecider function
* @param scope
* @returns {*}
*/
generator.get_wf = function (scope) {
// todo: remove this condition
if ($rootScope.websocketIsOpen === true) {
WSOps.request(scope.form_params)
.then(function (data) {
return generator.pathDecider(data.client_cmd || ['list'], scope, data);
});
} else {
$timeout(function () {
// todo: loop restrict listen ws open
generator.get_wf(scope);
}, 500);
}
};
/**
* @memberof ulakbus.formService
* @ngdoc property
* @name pageData
* @description pageData object is moving object from response to controller
* with this object controller will not need to call the api for response object to work on to
* @type {{}}
*/
generator.pageData = {};
generator.getPageData = function () {
return generator.pageData;
};
generator.setPageData = function (value) {
generator.pageData = value;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name pathDecider
* @description pathDecider is used to redirect related path by looking up the data in response
* @param {string} client_cmd
* @param {Object} $scope
* @param {Object} data
*/
generator.pathDecider = function (client_cmd, $scope, data) {
//if (client_cmd[0] === 'reload' || client_cmd[0] === 'reset') {
// $rootScope.$broadcast('reload_cmd', $scope.reload_cmd);
// //return;
//}
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name redirectTo
* @description redirectTo function redirects to related controller and path with given data
* before redirect setPageData must be called and pageData need to be defined
* otherwise redirected path will call api for its data
* @param {Object} scope
* @param {string} page
* @return {*}
*/
function redirectTo(scope, page) {
var pathUrl = '/' + scope.form_params.wf;
if (scope.form_params.model) {
pathUrl += '/' + scope.form_params.model + '/do/' + page;
} else {
pathUrl += '/do/' + page;
}
// todo add object url to path
// pathUrl += '/'+scope.form_params.object_id || '';
// if generated path url and the current path is equal route has to be reload
if ($location.path() === pathUrl) {
return $route.reload();
}
else {
$location.path(pathUrl);
}
}
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name dispatchClientCmd
* @description Sets params for scope to the related page and redirect to the page in client_cmd param.
* client_cmd can be in ['list', 'form', 'show', 'reload', 'reset']
*/
function dispatchClientCmd() {
data[$scope.form_params.param] = $scope.form_params.id;
data['model'] = $scope.form_params.model;
data['wf'] = $scope.form_params.wf;
data['param'] = $scope.form_params.param;
data['param_id'] = $scope.form_params.id;
data['pageData'] = true;
//data['second_client_cmd'] = client_cmd[1];
generator.setPageData(data);
redirectTo($scope, client_cmd[0]);
}
dispatchClientCmd();
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name get_diff
* @description returns diff of the second param to first param
* @param {Object} obj1
* @param {Object} obj2
* @returns {Object} diff object of two given objects
*/
generator.get_diff = function (oldObj, newObj) {
var result = {};
angular.forEach(newObj, function (value, key) {
if (oldObj[key]) {
if ((oldObj[key].constructor === newObj[key].constructor) && (newObj[key].constructor === Object || newObj[key].constructor === Array)) {
angular.forEach(value, function (v, k) {
if (oldObj[key][k] != value[k]) {
result[key][k] = angular.copy(value[k]);
}
});
} else {
if (oldObj[key] != newObj[key]) {
result[key] = angular.copy(newObj[key]);
}
}
} else {
result[key] = angular.copy(newObj[key]);
}
});
return result;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name get_diff_array
* @description extracts items of second array from the first array
* @param {Array} array1
* @param {Array} array2
* @param {Number} way
* @returns {Array} diff of arrays
*/
generator.get_diff_array = function (array1, array2, way) {
var result = [];
angular.forEach(array1, function (value, key) {
if (way === 1) {
if (angular.toJson(array2).indexOf(value.value) < 0) {
result.push(value);
}
} else {
if (angular.toJson(array2).indexOf(angular.toJson(value)) < 0) {
result.push(value);
}
}
});
return result;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name item_from_array
* @description gets item unicode name from titleMap
* @param {Object} item
* @param {Array} array
* @returns {*}
*/
generator.item_from_array = function (item, array) {
var result = item;
angular.forEach(array, function (value, key) {
if (value.value === item) {
result = value.name;
}
});
return result;
};
/**
* @memberof ulakbus.formService
* @ngdoc function
* @name submit
* @description Submit function is generic function for submiting forms.
* - redirectTo param is used for redirect if return value will be evaluated in a new page.
* - In case of unformatted date object in any key recursively, it must be converted by convertDate function.
* - ListNode and Node objects get seperated from model in
* {@link prepareFormItems module:ulakbus.formService.function:prepareFormItems} They must be concat to model
* key of scope first.
* - Backend API waits form as model value. So `data.form` key must be set to `$scope.model`
* - Other parameters we pass to backend API are shown in the example below
* ```
* var data = {
"form": $scope.model,
"token": $scope.token,
"model": $scope.form_params.model,
"cmd": $scope.form_params.cmd,
"flow": $scope.form_params.flow,
"object_id": $scope.object_id,
"filter": $scope.filter,
"query": $scope.form_params.query
};
* ```
*
* Special response object process
* -------------------------------
*
* - If response object is a downloadable pdf file, checking from headers `headers('content-type') ===
* "application/pdf"` download using Blob object.
*
* @param {Object} $scope
* @param {Object} redirectTo
* @param {Boolean} dontProcessReply - used in modal forms
* @returns {*}
* @todo diff for all submits to recognize form change. if no change returns to view with no submit
*/
generator.submit = function ($scope, redirectTo, dontProcessReply) {
/**
* In case of unformatted date object in any key recursively, it must be converted.
* @param model
*/
var convertDate = function (model) {
angular.forEach(model, function (value, key) {
if (value && value.constructor === Date) {
model[key] = generator.dateformatter(value);
}
if (value && value.constructor === Object) {
convertDate(value);
}
});
};
angular.forEach($scope.ListNode, function (value, key) {
$scope.model[key] = value.model;
});
angular.forEach($scope.Node, function (value, key) {
$scope.model[key] = value.model;
});
// todo: unused var delete
var send_data = {
"form": $scope.model,
"object_key": $scope.object_key,
"token": $scope.token,
"model": $scope.form_params.model,
"wf": $scope.form_params.wf,
"cmd": $scope.form_params.cmd,
"flow": $scope.form_params.flow,
"object_id": $scope.object_id,
"filter": $scope.filter,
"query": $scope.form_params.query
};
if ($rootScope.websocketIsOpen === true) {
return WSOps.request(send_data)
.then(function (data) {
if (!dontProcessReply){
return generator.pathDecider(data.client_cmd || ['list'], $scope, data);
}
return data;
});
} else {
$timeout(function () {
generator.scope($scope, redirectTo);
}, 500);
}
};
return generator;
})
/**
* @memberof ulakbus.formService
* @ngdoc controller
* @name ModalController
* @description controller for listnode, node and linkedmodel modal and save data of it
* @param {Object} items
* @param {Object} $scope
* @param {Object} $uibModalInstance
* @param {Object} $route
* @returns {Object} returns value for modal
*/
.controller('ModalController', function ($scope, $uibModalInstance, Generator, items, $timeout, Utils) {
angular.forEach(items, function (value, key) {
$scope[key] = items[key];
});
$scope.$on('disposeModal', function () {
$scope.cancel();
});
$scope.$on('modalFormLocator', function (event) {
// fix default model with unicode assign
$timeout(function () {
Utils.iterate($scope.model, function(modelValue, k){
if (angular.isUndefined($scope.edit)) return;
var unicode = $scope.items[$scope.edit][k].unicode;
if (unicode){
document.querySelector('input[name=' + k + ']').value = unicode;
}
})
});
$scope.linkedModelForm = event.targetScope.linkedModelForm;
});
$scope.$on('submitModalForm', function () {
$scope.onSubmit($scope.linkedModelForm);
});
$scope.$on('validateModalDate', function (event, field) {
$scope.$broadcast('schemaForm.error.' + field, 'tv4-302', true);
});
$scope.onSubmit = function (form) {
$scope.$broadcast('schemaFormValidate');
if (form.$valid) {
// send form to modalinstance result function
$uibModalInstance.close($scope);
}
};
$scope.onNodeSubmit = function () {
$scope.$broadcast('schemaFormValidate');
if ($scope.modalForm.$valid) {
$uibModalInstance.close($scope);
}
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
})
/**
* @memberof ulakbus.formService
* @ngdoc directive
* @name modalForNodes
* @description add modal directive for nodes
* @param {Module} $uibModal
* @param {Service} Generator
* @returns {Object} openmodal directive
*/
.directive('modalForNodes', function ($uibModal, Generator, Utils) {
return {
link: function (scope, element, attributes) {
element.on('click', function () {
var modalInstance = $uibModal.open({
animation: true,
backdrop: 'static',
keyboard: false,
templateUrl: 'shared/templates/listnodeModalContent.html',
controller: 'ModalController',
size: 'lg',
resolve: {
items: function () {
var attribs = attributes.modalForNodes.split(',');
// get node from parent scope catch with attribute
var node = angular.copy(scope.$parent[attribs[1]][attribs[0]]);
if (attribs[2] === 'add') {
node.model = {};
}
if (attribs[3]) {
// if listnode catch edit object with index
node.model = node.model[attribs[3]];
}
// tell result.then function which item to edit
node.edit = attribs[3];
scope.node.schema.wf = scope.node.url;
angular.forEach(scope.node.schema.properties, function (value, key) {
if (angular.isDefined(scope.node.schema.properties[key].wf)) {
}
else {
scope.node.schema.properties[key].wf = scope.node.url;
}
scope.node.schema.properties[key].list_cmd = 'select_list';
});
// scope.node.schema.footerButtons = [
// {type: "submit", text:"Onayla", style:"btn-success" },
// {type: "button", text:"Vazgec", style:"btn-danger" },
// ]
var newscope = {
wf: scope.node.wf,
url: scope.node.url,
form_params: {model: scope.node.schema.model_name},
edit: attribs[3]
};
Generator.generate(newscope, {forms: scope.node});
// modal will add only one item to listNode, so just need one model (not array)
newscope.model = newscope.model[node.edit] || {};
return newscope;
}
}
});
modalInstance.result.then(function (childmodel, key) {
var listNodeItem = scope.$parent[childmodel.schema.formType][childmodel.schema.model_name];
if (childmodel.schema.formType === 'Node') {
listNodeItem.model = angular.copy(childmodel.model);
listNodeItem.lengthModels += 1;
}
if (childmodel.schema.formType === 'ListNode') {
// reformat listnode model
var reformattedModel = {};
angular.forEach(childmodel.model, function (value, key) {
if (key.indexOf('_id') > -1) {
// todo: understand why we got object here!
// hack to fix bug with value as object
if (angular.isObject(value) && value.value){
value = value.value;
childmodel.model[key] = value;
}
angular.forEach(childmodel.form, function (v, k) {
if (v.formName === key) {
//if (!childmodel.model[key].key) {
var unicodeValue = v.titleMap.find(function (element, index, array) {
if (element['value'] === value) {
return element;
}
});
if (unicodeValue){
unicodeValue = unicodeValue.name;
reformattedModel[key] = {
"key": value,
"unicode": unicodeValue
}
}
//}
}
});
} else {
reformattedModel[key] = {
"key": key,
"unicode": Generator.item_from_array(value, childmodel.schema.properties[key].titleMap)
};
}
});
if (childmodel.edit) {
listNodeItem.model[childmodel.edit] = childmodel.model;
if (Object.keys(reformattedModel).length > 0) {
listNodeItem.items[childmodel.edit] = reformattedModel;
} else {
listNodeItem.items[childmodel.edit] = angular.copy(childmodel.model);
}
} else {
listNodeItem.model.push(angular.copy(childmodel.model));
if (Object.keys(reformattedModel).length > 0) {
listNodeItem.items.push(reformattedModel);
} else {
listNodeItem.items.push(angular.copy(childmodel.model));
}
}
listNodeItem.lengthModels += 1;
}
});
});
}
};
})
/**
* @memberof ulakbus.formService
* @ngdoc directive
* @name addModalForLinkedModel
* @description add modal directive for linked models
* @param {Module} $uibModal
* @param {Object} $rootScope
* @param {Module} $route
* @param {Service} Generator
* @returns {Object} openmodal directive
*/
.directive('addModalForLinkedModel', function ($uibModal, $rootScope, $route, Generator) {
return {
link: function (scope, element, attributes) {
element.on('click', function () {
var modalInstance = $uibModal.open({
animation: true,
backdrop: 'static',
keyboard: false,
templateUrl: 'shared/templates/linkedModelModalContent.html',
controller: 'ModalController',
size: 'lg',
resolve: {
items: function () {
var formName = attributes.addModalForLinkedModel;
return Generator.get_form({
form_params: {
wf: scope.form.wf,
model: scope.form.model_name,
cmd: scope.form.add_cmd
},
modalElements: {
// define button position properties
buttonPositions: {
bottom: 'move-to-bottom-modal',
top: 'move-to-top-modal',
none: ''
},
workOnForm: 'linkedModelForm',
workOnDiv: '-modal' + formName
},
submitModalForm: function () {
$rootScope.$broadcast('submitModalForm');
},
validateModalDate: function (field) {
$rootScope.$broadcast('validateModalDate', field);
},
formName: formName
});
}
}
});
modalInstance.result.then(function (childscope, key) {
var formName = childscope.formName;
Generator.submit(childscope, false, true).then(
function (data) {
// response data contains object_id and unicode
// scope.form can be reached via prototype chain
var item = {
value: data.forms.model.object_key,
name: data.forms.model.unicode
};
scope.form.titleMap.push(item);
scope.form.onSelect(item, formName);
});
});
});
}
};
})
/**
* @memberof ulakbus.formService
* @ngdoc directive
* @name modalFormLocator
* @description This directive helps to locate form object in modal.
* @returns {Object} form object
*/
.directive('modalFormLocator', function () {
return {
link: function (scope) {
scope.$emit('modalFormLocator');
}
}
});
|
kunthar/ulakbus-ui
|
app/zetalib/form_service.js
|
JavaScript
|
gpl-3.0
| 74,403
|
// Copyright 2015 Urs Fässler, www.bitzgi.ch
// SPDX-License-Identifier: GPL-3.0+
#include "Composition.hpp"
#include "../connection/ConnectionFactory.hpp"
#include "../instance/InstanceFactory.hpp"
#include "../util/stdlist.hpp"
#include "../util/ChildRemover.hpp"
#include "../connection/ConnectionWithPortSpecification.hpp"
#include "../specification/OrSpecification.hpp"
#include <algorithm>
#include <cassert>
Composition::Composition(ICompositionInstance *aSelfInstance) :
selfInstance{aSelfInstance},
instances{InstanceFactory::dispose},
connections{ConnectionFactory::dispose}
{
precondition(aSelfInstance != nullptr);
selfInstance->getPorts().registerObserver(this);
instances.registerObserver(this);
}
Composition::~Composition()
{
instances.unregisterObserver(this);
precondition(connections.empty());
precondition(connectionUnderConstruction == nullptr);
precondition(instances.empty());
precondition(selfInstance == nullptr);
}
ImplementationType Composition::getType() const
{
return ImplementationType::Composition;
}
ICompositionInstance *Composition::getSelfInstance() const
{
return selfInstance;
}
const List<IComponentInstance> &Composition::getInstances() const
{
return instances;
}
List<IComponentInstance> &Composition::getInstances()
{
return instances;
}
void Composition::added(IComponentInstance *instance)
{
instance->getPorts().registerObserver(this);
}
void Composition::removed(IComponentInstance *instance)
{
OrSpecification spec;
for (IPort *port : instance->getPorts()) {
spec.add(new ConnectionWithPortSpecification(port));
}
ChildRemover remover(spec);
accept(remover);
instance->getPorts().unregisterObserver(this);
}
IComponentInstance *Composition::getInstance(const std::string &name) const
{
auto predicate = [&](const IComponentInstance *itr){
return itr->getName() == name;
};
return instances.get(predicate);
}
const List<Connection> &Composition::getConnections() const
{
return connections;
}
List<Connection> &Composition::getConnections()
{
return connections;
}
void Composition::startConnectionConstruction(IPort *startPort, IPort *endPort)
{
precondition(!hasConnectionUnderConstruction());
precondition(startPort != nullptr);
precondition(endPort != nullptr);
connectionUnderConstruction = ConnectionFactory::produceConstruction(startPort, endPort);
checkInvariant();
notify(&CompositionObserver::addConnectionUnderConstruction, connectionUnderConstruction);
}
void Composition::finishConnectionConstruction(IPort *end)
{
precondition(hasConnectionUnderConstruction());
precondition(end != nullptr);
connectionUnderConstruction->replaceEndPort(end);
Connection *connection = connectionUnderConstruction;
connectionUnderConstruction = nullptr;
notify(&CompositionObserver::finishConnectionUnderConstruction, connection);
connections.add(connection);
postcondition(!hasConnectionUnderConstruction());
}
bool Composition::hasConnectionUnderConstruction() const
{
return connectionUnderConstruction != nullptr;
}
Connection *Composition::getConnectionUnderConstruction() const
{
return connectionUnderConstruction;
}
void Composition::removed(InstancePort *port)
{
ConnectionWithPortSpecification spec(port);
ChildRemover remover(spec);
accept(remover);
}
void Composition::checkInvariant()
{
}
void Composition::accept(Visitor &visitor)
{
visitor.visit(*this);
}
void Composition::accept(ConstVisitor &visitor) const
{
visitor.visit(*this);
}
CompositionObserver::~CompositionObserver()
{
}
void CompositionObserver::addConnectionUnderConstruction(Connection *)
{
}
void CompositionObserver::finishConnectionUnderConstruction(Connection *)
{
}
|
ursfassler/evdraw
|
src/core/implementation/Composition.cpp
|
C++
|
gpl-3.0
| 3,733
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kinect_Tools.kinect_tools_dir
{
public class Outil
{
public static void Ecrire_Erreur(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
string err = ex.ToString();
Console.WriteLine(err);
Console.WriteLine(ex.Message);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
}
|
Goldorhack/interactive-board
|
GoldOrHack_Client_01_Wpf/Kinect_Tools/kinect_tools_dir/Outil.cs
|
C#
|
gpl-3.0
| 506
|
package everlife.common.block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class BlockELPlanks extends BlockEL {
public static final PropertyEnum VARIANT = PropertyEnum.create("variant", BlockELPlanks.EnumType.class);
public BlockELPlanks() {
super(Material.wood);
setStepSound(soundTypeWood);
setUnlocalizedName("el_planks");
setHardness(2.0F);
}
@Override
public int damageDropped(IBlockState state) {
return ((BlockELPlanks.EnumType) state.getValue(VARIANT)).getMetadata();
}
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) {
BlockELPlanks.EnumType[] aenumtype = BlockELPlanks.EnumType.values();
int i = aenumtype.length;
for (int j = 0; j < i; ++j) {
BlockELPlanks.EnumType enumtype = aenumtype[j];
list.add(new ItemStack(itemIn, 1, enumtype.getMetadata()));
}
}
@Override
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(VARIANT, BlockELPlanks.EnumType.byMetadata(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return ((BlockELPlanks.EnumType) state.getValue(VARIANT)).getMetadata();
}
protected BlockState createBlockState() {
return new BlockState(this, new IProperty[]{VARIANT});
}
public static enum EnumType implements IStringSerializable {
EVER(0, "ever"),
BLACKWOOD(1, "blackwood");
private static final BlockELPlanks.EnumType[] META_LOOKUP = new BlockELPlanks.EnumType[values().length];
private final int meta;
private final String name;
private final String unlocalizedName;
private EnumType(int meta, String name) {
this(meta, name, name);
}
private EnumType(int meta, String name, String unlocalizedName) {
this.meta = meta;
this.name = name;
this.unlocalizedName = unlocalizedName;
}
public int getMetadata() {
return this.meta;
}
public String toString() {
return this.name;
}
public static BlockELPlanks.EnumType byMetadata(int meta) {
if (meta < 0 || meta >= META_LOOKUP.length) {
meta = 0;
}
return META_LOOKUP[meta];
}
public String getName() {
return this.name;
}
public String getUnlocalizedName() {
return this.unlocalizedName;
}
static {
BlockELPlanks.EnumType[] var0 = values();
int var1 = var0.length;
for (int var2 = 0; var2 < var1; ++var2) {
BlockELPlanks.EnumType var3 = var0[var2];
META_LOOKUP[var3.getMetadata()] = var3;
}
}
}
}
|
CoderAtParadise/EverLife
|
src/main/java/everlife/common/block/BlockELPlanks.java
|
Java
|
gpl-3.0
| 3,372
|
/**
* Copyright (C) 2008 Happy Fish / YuQing
*
* FastDFS may be copied only under the terms of the GNU General
* Public License V3, which may be found in the FastDFS source kit.
* Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
**/
//socketopt.h
#ifndef _SOCKETOPT_H_
#define _SOCKETOPT_H_
#include "common_define.h"
#define FDFS_WRITE_BUFF_SIZE 256 * 1024
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*getnamefunc)(int socket, struct sockaddr *address, \
socklen_t *address_len);
/* ·¢Ëͱ¨Îĵĺ¯ÊýÖ¸ÕëÉùÃ÷ */
typedef int (*tcpsenddatafunc)(int sock, void* data, const int size, \
const int timeout);
/* ½ÓÊÕ±¨Îĵĺ¯ÊýÖ¸ÕëÉùÃ÷ */
typedef int (*tcprecvdata_exfunc)(int sock, void *data, const int size, \
const int timeout, int *count);
/* ¸ù¾ÝsocketÃèÊö·û»ñÈ¡×ÔÉíµÄipµØÖ· */
#define getSockIpaddr(sock, buff, bufferSize) \
getIpaddr(getsockname, sock, buff, bufferSize)
/* ¸ù¾ÝsocketÃèÊö·û»ñÈ¡¶Ô¶ËµÄipµØÖ· */
#define getPeerIpaddr(sock, buff, bufferSize) \
getIpaddr(getpeername, sock, buff, bufferSize)
/** get a line from socket
* parameters:
* sock: the socket
* s: the buffer
* size: buffer size (max bytes can receive)
* timeout: read timeout
* return: error no, 0 success, != 0 fail
*/
int tcpgets(int sock, char *s, const int size, const int timeout);
/** recv data (block mode)
* parameters:
* sock: the socket
* data: the buffer
* size: buffer size (max bytes can receive)
* timeout: read timeout
* count: store the bytes recveived
* return: error no, 0 success, != 0 fail
*/
/*
* ×èÈûģʽ»ñÈ¡tcpÊý¾Ý±¨ÎÄ
* Ä¿±êÊǶÁÈ¡³¤¶ÈΪsizeµÄÊý¾Ý
* count·µ»ØÎªÊµ¼Ê¶ÁÈ¡µ½µÄÊý¾Ý³¤¶È
*/
int tcprecvdata_ex(int sock, void *data, const int size, \
const int timeout, int *count);
/** recv data (non-block mode)
* parameters:
* sock: the socket
* data: the buffer
* size: buffer size (max bytes can receive)
* timeout: read timeout
* count: store the bytes recveived
* return: error no, 0 success, != 0 fail
*/
/*
* ·Ç×èÈûģʽ»ñÈ¡tcpÊý¾Ý±¨ÎÄ
* Ä¿±êÊǶÁÈ¡³¤¶ÈΪsizeµÄÊý¾Ý
* count·µ»ØÎªÊµ¼Ê¶ÁÈ¡µ½µÄÊý¾Ý³¤¶È
*/
int tcprecvdata_nb_ex(int sock, void *data, const int size, \
const int timeout, int *count);
/** send data (block mode)
* parameters:
* sock: the socket
* data: the buffer to send
* size: buffer size
* timeout: write timeout
* return: error no, 0 success, != 0 fail
*/
/* ͨ¹ýtcpÏòsock·¢ËÍÊý¾Ý£¬×èÈûģʽ */
int tcpsenddata(int sock, void* data, const int size, const int timeout);
/** send data (non-block mode)
* parameters:
* sock: the socket
* data: the buffer to send
* size: buffer size
* timeout: write timeout
* return: error no, 0 success, != 0 fail
*/
int tcpsenddata_nb(int sock, void* data, const int size, const int timeout);
/** connect to server by block mode
* parameters:
* sock: the socket
* server_ip: ip address of the server
* server_port: port of the server
* return: error no, 0 success, != 0 fail
*/
int connectserverbyip(int sock, const char *server_ip, const short server_port);
/** connect to server by non-block mode
* parameters:
* sock: the socket
* server_ip: ip address of the server
* server_port: port of the server
* timeout: connect timeout in seconds
* auto_detect: if detect and adjust the block mode of the socket
* return: error no, 0 success, != 0 fail
*/
int connectserverbyip_nb_ex(int sock, const char *server_ip, \
const short server_port, const int timeout, \
const bool auto_detect);
/** connect to server by non-block mode, the socket must be set to non-block
* parameters:
* sock: the socket, must be set to non-block
* server_ip: ip address of the server
* server_port: port of the server
* timeout: connect timeout in seconds
* return: error no, 0 success, != 0 fail
*/
/* ½¨Á¢Óëserver_ip:server_portÖ®¼äµÄ·Ç×èÈûÁ¬½Ó£¬³¬Ê±Ê±¼äΪtimeout */
#define connectserverbyip_nb(sock, server_ip, server_port, timeout) \
connectserverbyip_nb_ex(sock, server_ip, server_port, timeout, false)
/** connect to server by non-block mode, auto detect socket block mode
* parameters:
* sock: the socket, can be block mode
* server_ip: ip address of the server
* server_port: port of the server
* timeout: connect timeout in seconds
* return: error no, 0 success, != 0 fail
*/
#define connectserverbyip_nb_auto(sock, server_ip, server_port, timeout) \
connectserverbyip_nb_ex(sock, server_ip, server_port, timeout, true)
/** accept client connect request
* parameters:
* sock: the server socket
* timeout: read timeout
* err_no: store the error no, 0 for success
* return: client socket, < 0 for error
*/
int nbaccept(int sock, const int timeout, int *err_no);
/** set socket options
* parameters:
* sock: the socket
* timeout: read & write timeout
* return: error no, 0 success, != 0 fail
*/
int tcpsetserveropt(int fd, const int timeout);
/** set socket non-block options
* parameters:
* sock: the socket
* return: error no, 0 success, != 0 fail
*/
int tcpsetnonblockopt(int fd);
/** set socket no delay on send data
* parameters:
* sock: the socket
* timeout: read & write timeout
* return: error no, 0 success, != 0 fail
*/
int tcpsetnodelay(int fd, const int timeout);
/** set socket keep-alive
* parameters:
* sock: the socket
* idleSeconds: max idle time (seconds)
* return: error no, 0 success, != 0 fail
*/
int tcpsetkeepalive(int fd, const int idleSeconds);
/** print keep-alive related parameters
* parameters:
* sock: the socket
* return: error no, 0 success, != 0 fail
*/
int tcpprintkeepalive(int fd);
/** get ip address
* parameters:
* getname: the function name, should be getpeername or getsockname
* sock: the socket
* buff: buffer to store the ip address
* bufferSize: the buffer size (max bytes)
* return: in_addr_t, INADDR_NONE for fail
*/
/*
* ʹÓòÎÊýÖд«ÈëµÄgetnameº¯Êý£¬¸ù¾ÝsocketÃèÊö·û»ñÈ¡¶ÔÓ¦ipµØÖ·
* in_addr_tÀàÐ͵ĵØÖ·Í¨¹ýº¯Êý·µ»Ø
* ×Ö·û´®ÀàÐ͵ĵØÖ··ÅÔÚ´«ÈëµÄbuff×Ö·û´®ÖÐ
*/
in_addr_t getIpaddr(getnamefunc getname, int sock, \
char *buff, const int bufferSize);
/** get hostname by it's ip address
* parameters:
* szIpAddr: the ip address
* buff: buffer to store the hostname
* bufferSize: the buffer size (max bytes)
* return: hostname, empty buffer for error
*/
char *getHostnameByIp(const char *szIpAddr, char *buff, const int bufferSize);
/** get by ip address by it's hostname
* parameters:
* name: the hostname
* buff: buffer to store the ip address
* bufferSize: the buffer size (max bytes)
* return: in_addr_t, INADDR_NONE for fail
*/
in_addr_t getIpaddrByName(const char *name, char *buff, const int bufferSize);
/** bind wrapper
* parameters:
* sock: the socket
* bind_ipaddr: the ip address to bind
* port: the port to bind
* return: error no, 0 success, != 0 fail
*/
int socketBind(int sock, const char *bind_ipaddr, const int port);
/** start a socket server (socket, bind and listen)
* parameters:
* sock: the socket
* bind_ipaddr: the ip address to bind
* port: the port to bind
* err_no: store the error no
* return: >= 0 server socket, < 0 fail
*/
int socketServer(const char *bind_ipaddr, const int port, int *err_no);
#define tcprecvdata(sock, data, size, timeout) \
tcprecvdata_ex(sock, data, size, timeout, NULL)
#define tcpsendfile(sock, filename, file_bytes, timeout, total_send_bytes) \
tcpsendfile_ex(sock, filename, 0, file_bytes, timeout, total_send_bytes)
/* »ñÈ¡tcpÊý¾Ý±¨ÎÄ£¬Ö±µ½¶ÁÈ¡³¤¶ÈΪsizeµÄÊý¾ÝΪֹ */
#define tcprecvdata_nb(sock, data, size, timeout) \
tcprecvdata_nb_ex(sock, data, size, timeout, NULL)
/** send a file
* parameters:
* sock: the socket
* filename: the file to send
* file_offset: file offset, start position
* file_bytes: send file length
* timeout: write timeout
* total_send_bytes: store the send bytes
* return: error no, 0 success, != 0 fail
*/
int tcpsendfile_ex(int sock, const char *filename, const int64_t file_offset, \
const int64_t file_bytes, const int timeout, int64_t *total_send_bytes);
/** receive data to a file
* parameters:
* sock: the socket
* filename: the file to write
* file_bytes: file size (bytes)
* fsync_after_written_bytes: call fsync every x bytes
* timeout: read/recv timeout
* true_file_bytes: store the true file bytes
* return: error no, 0 success, != 0 fail
*/
/*
* ͨ¹ý½¨Á¢Á¬½ÓµÄsock£¬½ÓÊÕÎļþдÈëfilename
* Îļþ´óСΪfile_bytes
* fsync_after_written_bytesÖ¸¶¨Ð´Èë¶àÉÙ×Ö½Úºó£¬Ê¹ÓÃfsyncÇ¿ÖÆË¢Ðµ½´ÅÅÌ
* true_file_bytesΪʵ¼Ê»ñÈ¡µ½µÄÎļþµÄ´óС
*/
int tcprecvfile(int sock, const char *filename, const int64_t file_bytes, \
const int fsync_after_written_bytes, const int timeout, \
int64_t *true_file_bytes);
#define tcprecvinfinitefile(sock, filename, fsync_after_written_bytes, \
timeout, file_bytes) \
tcprecvfile(sock, filename, INFINITE_FILE_SIZE, \
fsync_after_written_bytes, timeout, file_bytes)
/** receive data to a file
* parameters:
* sock: the socket
* filename: the file to write
* file_bytes: file size (bytes)
* fsync_after_written_bytes: call fsync every x bytes
* hash_codes: return hash code of file content
* timeout: read/recv timeout
* return: error no, 0 success, != 0 fail
*/
int tcprecvfile_ex(int sock, const char *filename, const int64_t file_bytes, \
const int fsync_after_written_bytes, \
unsigned int *hash_codes, const int timeout);
/** receive specified data and discard
* parameters:
* sock: the socket
* bytes: data bytes to discard
* timeout: read timeout
* total_recv_bytes: store the total recv bytes
* return: error no, 0 success, != 0 fail
*/
int tcpdiscard(int sock, const int bytes, const int timeout, \
int64_t *total_recv_bytes);
/** get local host ip addresses
* parameters:
* ip_addrs: store the ip addresses
* max_count: max ip address (max ip_addrs elements)
* count: store the ip address count
* return: error no, 0 success, != 0 fail
*/
int getlocaladdrs(char ip_addrs[][IP_ADDRESS_SIZE], \
const int max_count, int *count);
/** get local host ip addresses
* parameters:
* ip_addrs: store the ip addresses
* max_count: max ip address (max ip_addrs elements)
* count: store the ip address count
* return: error no, 0 success, != 0 fail
*/
int getlocaladdrs1(char ip_addrs[][IP_ADDRESS_SIZE], \
const int max_count, int *count);
/** get local host ip addresses by if alias prefix
* parameters:
* if_alias_prefixes: if alias prefixes, such as eth, bond etc.
* prefix_count: if alias prefix count
* ip_addrs: store the ip addresses
* max_count: max ip address (max ip_addrs elements)
* count: store the ip address count
* return: error no, 0 success, != 0 fail
*/
int gethostaddrs(char **if_alias_prefixes, const int prefix_count, \
char ip_addrs[][IP_ADDRESS_SIZE], const int max_count, int *count);
#ifdef __cplusplus
}
#endif
#endif
|
fatedier/studies
|
fastdfs-5.01/common/sockopt.h
|
C
|
gpl-3.0
| 11,673
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Javascript on Fiber: re Module Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../resize.js"></script>
<script type="text/javascript" src="../../navtreedata.js"></script>
<script type="text/javascript" src="../../navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="../../logo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Javascript on Fiber
</div>
<div id="projectbrief">A developement framework of the coroutines based on Google's V8 Engine</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li><a href="../../pages.html"><span>Tutorial</span></a></li>
<li><a href="../../namespaces.html"><span>Module</span></a></li>
<li><a href="../../annotated.html"><span>Object</span></a></li>
<li><a href="https://github.com/xicilion/fibjs"><span>Download</span></a></li>
<li><a href="http://named.cn/fibjs"><span>Forum</span></a></li>
<li><a href="../../../index.html"><span>中文版</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="../../search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('d5/d83/namespacere.html','../../');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">re Module Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Regexp module.
<a href="#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a210fb1ffc2d442367932ea0f831e59e1"><td class="memItemLeft" align="right" valign="top">static <a class="el" href="../../d1/d43/interfaceRegex.html">Regex</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d5/d83/namespacere.html#a210fb1ffc2d442367932ea0f831e59e1">compile</a> (String pattern, String opt="")</td></tr>
<tr class="memdesc:a210fb1ffc2d442367932ea0f831e59e1"><td class="mdescLeft"> </td><td class="mdescRight">Compile and return a template of regexp. <a href="#a210fb1ffc2d442367932ea0f831e59e1">More...</a><br /></td></tr>
<tr class="separator:a210fb1ffc2d442367932ea0f831e59e1"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Regexp module. </p>
</div><h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a210fb1ffc2d442367932ea0f831e59e1"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">static <a class="el" href="../../d1/d43/interfaceRegex.html">Regex</a> re.compile </td>
<td>(</td>
<td class="paramtype">String </td>
<td class="paramname"><em>pattern</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">String </td>
<td class="paramname"><em>opt</em> = <code>""</code> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compile and return a template of regexp. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pattern</td><td>Regexp pattern </td></tr>
<tr><td class="paramname">opt</td><td>Match type, can be "g", "i" or "gi" </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>Return regexp object </dd></dl>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<style type="text/css">
body {
color: #666666;
}
a, .contents a:visited {
color: #3399ee;
}
.icona, #nav-sync {
display:none;
}
.directory td.entry, .directory td.desc {
padding: 8px;
}
</style>
</body>
</html>
|
verdantyang/fibjs_docs
|
html/en/d5/d83/namespacere.html
|
HTML
|
gpl-3.0
| 7,211
|
<?php
namespace Sainsbury\Product\Html;
use Symfony\Component\DomCrawler\Crawler,
Model\Product;
/**
* Description of Parser
*
* @author Kamil Hurajt
*/
class Parser
{
/**
* @var Crawler
*/
protected $crawler;
protected $items;
/**
* @param Crawler $crawler
*/
public function __construct(Crawler $crawler)
{
$this->crawler = $crawler;
$this->loadItems();
}
/**
* @param Crawler $product
* @return Crawler
*/
public function getDetailUrl(Crawler $product)
{
return $product->filter('.productInfo a')->attr('href');
}
/**
* @param Crawler $product
* @return String
*/
public function getUnitPrice(Crawler $product)
{
$price = $product->filter('.pricing p.pricePerUnit')->text();
if(!preg_match("/([0-9\.]+)/i", $price, $matches)){
return null;
}
$price = $matches[0];
return $price;
}
/**
* @param Crawler $product
* @return String
*/
public function getProductName(Crawler $product)
{
return $product->filter('.productInfo a')->text();
}
/**
* Get size in bytes of HTML content
* @param string $url URL adres
* @return string Formated size of page
*/
public function getPageSize($url)
{
$html = file_get_contents($url);
$size = mb_strlen($html, '8bit');
$sizeKb = \Sainsbury\Math::formatBytes($size);
return $sizeKb;
}
/**
* Get products
* @return HTMLDom
*/
public function getProductList()
{
return $this->crawler->filter('.productLister > li');
}
/**
* @return Product[] List of product objects
*/
public function getItems()
{
return $this->items;
}
/**
* Append product into item list
* @todo refactor into non dependable way or using injection
* @param string $name Description
* @param double $price Description
* @param string $size Description
*/
protected function addItem($name, $price, $size)
{
$item = ['name' => trim($name), 'price' => trim($price), 'size' => trim($size)];
$this->items[] = new Product($item);
}
/**
* Load items and append them into items
*/
protected function loadItems()
{
$products = $this->getProductList();
foreach($products as $product){
$nodeHTML = $product->ownerDocument->saveHTML($product);
$product = new Crawler($nodeHTML);
$name = $this->getProductName($product);
$price = $this->getUnitPrice($product);
$detailLink = $this->getDetailUrl($product);
$size = $this->getPageSize($detailLink);
$this->addItem($name, $price, $size);
}
}
}
|
kamilhurajt/snbury
|
src/app/Sainsbury/Product/Html/Parser.php
|
PHP
|
gpl-3.0
| 3,013
|
/*
* Copyright (C) 2014 Thog92
*
* 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 fr.ironcraft.assets;
/**
* @author Thog
*/
public class AssetObject {
private String hash;
private long size;
public String getHash() {
return this.hash;
}
public long getSize() {
return this.size;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if ((o == null) || (getClass() != o.getClass()))
return false;
AssetObject that = (AssetObject) o;
if (this.size != that.size)
return false;
return this.hash.equals(that.hash);
}
@Override
public int hashCode() {
int result = this.hash.hashCode();
result = 31 * result + (int) (this.size ^ this.size >>> 32);
return result;
}
}
|
Thog/Assets
|
src/main/java/fr/ironcraft/assets/AssetObject.java
|
Java
|
gpl-3.0
| 1,344
|
<h2>Random videos</h2>
<?php
foreach ($videos as $video){ ?>
<div class="thumb" style="background-image: url(https://thumbs.gfycat.com/<?=$video->source?>-<?=$config->posterType?>.jpg);">
<a class="thumb-link" href="?v=<?=$video->id?>">
<div class="title"><?=$video->thumbTitle?></div>
</a>
</div>
<?php } ?>
|
BekirUzun/GfycatAlbum
|
views/random.php
|
PHP
|
gpl-3.0
| 313
|
/*******************************************************************
Part of the Fritzing project - http://fritzing.org
Copyright (c) 2007-2014 Fachhochschule Potsdam - http://fh-potsdam.de
Fritzing 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.
Fritzing 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 Fritzing. If not, see <http://www.gnu.org/licenses/>.
********************************************************************
$Revision: 6904 $:
$Author: irascibl@gmail.com $:
$Date: 2013-02-26 16:26:03 +0100 (Di, 26. Feb 2013) $
********************************************************************/
#ifndef INSTALLEDFONTS_H
#define INSTALLEDFONTS_H
#include <QSet>
#include <QString>
#include <QMultiHash>
class InstalledFonts
{
public:
static QSet<QString> InstalledFontsList;
static QMultiHash<QString, QString> InstalledFontsNameMapper; // family name to filename; SVG files seem to have to use filename
// note: these static variables are initialized in fapplication.cpp
};
#endif
|
sirdel/fritzing
|
src/installedfonts.h
|
C
|
gpl-3.0
| 1,434
|
<?php
/**
* OpenEyes
*
* (C) OpenEyes Foundation, 2016
* This file is part of OpenEyes.
* OpenEyes 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.
* OpenEyes 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 OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package OpenEyes
* @link http://www.openeyes.org.uk
* @author OpenEyes <info@openeyes.org.uk>
* @copyright Copyright (c) 2016, OpenEyes Foundation
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
namespace OEModule\OphCoCvi\models;
/**
* This is the model class for table "ophcocvi_clericinfo_preferred_info_fmt".
*
* The followings are the available columns in table:
* @property string $id
* @property string $name
* @property string $code
* @property boolean $require_email
* @property boolean $active
*
* The followings are the available model relations:
*
* @property ElementType $element_type
* @property EventType $eventType
* @property Event $event
* @property User $user
* @property User $usermodified
*/
class OphCoCvi_ClericalInfo_PreferredInfoFmt extends \BaseActiveRecordVersioned
{
/**
* Returns the static model of the specified AR class.
* @return the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'ophcocvi_clericinfo_preferred_info_fmt';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('name', 'safe'),
array('name', 'required'),
array('id, name', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'element_type' => array(
self::HAS_ONE,
'ElementType',
'id',
'on' => "element_type.class_name='" . get_class($this) . "'"
),
'eventType' => array(self::BELONGS_TO, 'EventType', 'event_type_id'),
'event' => array(self::BELONGS_TO, 'Event', 'event_id'),
'user' => array(self::BELONGS_TO, 'User', 'created_user_id'),
'usermodified' => array(self::BELONGS_TO, 'User', 'last_modified_user_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'code' => 'Template Code'
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id, true);
$criteria->compare('name', $this->name, true);
return new CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
));
}
}
|
openeyes/OphCoCvi
|
models/OphCoCvi_ClericalInfo_PreferredInfoFmt.php
|
PHP
|
gpl-3.0
| 3,704
|
from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta):
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__connection_label = connection_label
self.__delta = delta
self.__label_position = None
@property
def description(self):
return "Moved label on connection in diagram {0}".format(self.__diagram_name)
def _do(self, ruler):
self.__label_position = self.__connection_label.get_position(ruler)
self._redo(ruler)
def _redo(self, ruler):
self.__connection_label.move(ruler, self.__label_position + self.__delta)
def _undo(self, ruler):
self.__connection_label.move(ruler, self.__label_position)
def get_updates(self):
yield ConnectionMovedEvent(self.__connection_label.connection)
|
umlfri/umlfri2
|
umlfri2/application/commands/diagram/moveconnectionlabel.py
|
Python
|
gpl-3.0
| 1,001
|
/*
* Cantata
*
* Copyright (c) 2011-2014 Craig Drummond <craig.p.drummond@gmail.com>
*
*/
/*
* Copyright (c) 2008 Sander Knopper (sander AT knopper DOT tk) and
* Roeland Douma (roeland AT rullzer DOT com)
*
* This file is part of QtMPC.
*
* QtMPC 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.
*
* QtMPC 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 QtMPC. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MUSIC_LIBRARY_ITEM_ALBUM_H
#define MUSIC_LIBRARY_ITEM_ALBUM_H
#include <QList>
#include <QVariant>
#include <QSet>
#include "musiclibraryitem.h"
#include "mpd/song.h"
class QPixmap;
class MusicLibraryItemArtist;
class MusicLibraryItemSong;
class MusicLibraryItemAlbum : public MusicLibraryItemContainer
{
public:
static void setSortByDate(bool sd);
static bool sortByDate();
static bool lessThan(const MusicLibraryItem *a, const MusicLibraryItem *b);
MusicLibraryItemAlbum(const QString &data, const QString &original, const QString &mbId, quint32 year, const QString &sort, MusicLibraryItemContainer *parent);
virtual ~MusicLibraryItemAlbum();
QString displayData(bool full=false) const;
#ifdef ENABLE_UBUNTU
const QString & cover() const;
#endif
quint32 year() const { return m_year; }
quint32 totalTime();
quint32 trackCount();
void addTracks(MusicLibraryItemAlbum *other);
bool isSingleTracks() const { return Song::SingleTracks==m_type; }
void setIsSingleTracks();
bool isSingleTrackFile(const Song &s) const { return m_singleTrackFiles.contains(s.file); }
void append(MusicLibraryItem *i);
void remove(int row);
void remove(MusicLibraryItemSong *i);
void removeAll(const QSet<QString> &fileNames);
QMap<QString, Song> getSongs(const QSet<QString> &fileNames) const;
Song::Type songType() const { return m_type; }
Type itemType() const { return Type_Album; }
const MusicLibraryItemSong * getCueFile() const;
const QString & imageUrl() const { return m_imageUrl; }
void setImageUrl(const QString &u) { m_imageUrl=u; }
bool updateYear();
bool containsArtist(const QString &a);
// Return orignal album name. If we are grouping by composer, then album will appear as "Album (Artist)"
const QString & originalName() const { return m_originalName; }
const QString & id() const { return m_id; }
const QString & albumId() const { return m_id.isEmpty() ? m_itemData : m_id; }
const QString & sortString() const { return m_sortString.isEmpty() ? m_itemData : m_sortString; }
bool hasSort() const { return !m_sortString.isEmpty(); }
#ifdef ENABLE_UBUNTU
void setCover(const QString &c) { m_coverName="file://"+c; m_coverRequested=false; }
const QString & coverName() { return m_coverName; }
#endif
Song coverSong() const;
private:
void setYear(const MusicLibraryItemSong *song);
void updateStats();
private:
quint32 m_year;
quint16 m_yearOfTrack;
quint16 m_yearOfDisc;
quint32 m_totalTime;
quint32 m_numTracks;
QString m_originalName;
QString m_sortString;
QString m_id;
mutable Song m_coverSong;
#ifdef ENABLE_UBUNTU
mutable bool m_coverRequested;
mutable QString m_coverName;
#endif
Song::Type m_type;
QSet<QString> m_singleTrackFiles;
QString m_imageUrl;
// m_artists is used to cache the list of artists in a various artists album
// this is built when containsArtist() is called, and is mainly used by the
// context view
QSet<QString> m_artists;
};
#endif
|
google-code/cantata
|
models/musiclibraryitemalbum.h
|
C
|
gpl-3.0
| 4,015
|
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
import urllib
import re
try:
import xml.etree.cElementTree as etree
except ImportError:
import elementtree.ElementTree as etree
import sickbeard
import generic
from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import helpers
class EZRSSProvider(generic.TorrentProvider):
def __init__(self):
self.urls = {'base_url': 'https://www.ezrss.it/'}
self.url = self.urls['base_url']
generic.TorrentProvider.__init__(self, "EZRSS")
self.supportsBacklog = True
self.supportsFrench = False
self.enabled = False
self.ratio = None
self.cache = EZRSSCache(self)
def isEnabled(self):
return self.enabled
def imageName(self):
return 'ezrss.png'
def getQuality(self, item, anime=False):
try:
quality = Quality.sceneQuality(item.filename, anime)
except:
quality = Quality.UNKNOWN
return quality
def findSearchResults(self, show, episodes, search_mode, manualSearch=False, downCurQuality=False):
self.show = show
results = {}
if show.air_by_date or show.sports:
logger.log(self.name + u" doesn't support air-by-date or sports backloging because of limitations on their RSS search.",
logger.WARNING)
return results
results = generic.TorrentProvider.findSearchResults(self, show, episodes, search_mode, manualSearch, downCurQuality)
return results
def _get_season_search_strings(self, ep_obj):
params = {}
params['show_name'] = helpers.sanitizeSceneName(self.show.name, ezrss=True).replace('.', ' ').encode('utf-8')
if ep_obj.show.air_by_date or ep_obj.show.sports:
params['season'] = str(ep_obj.airdate).split('-')[0]
elif ep_obj.show.anime:
params['season'] = "%d" % ep_obj.scene_absolute_number
else:
params['season'] = ep_obj.scene_season
return [params]
def _get_episode_search_strings(self, ep_obj, add_string=''):
params = {}
if not ep_obj:
return params
params['show_name'] = helpers.sanitizeSceneName(self.show.name, ezrss=True).replace('.', ' ').encode('utf-8')
if self.show.air_by_date or self.show.sports:
params['date'] = str(ep_obj.airdate)
elif self.show.anime:
params['episode'] = "%i" % int(ep_obj.scene_absolute_number)
else:
params['season'] = ep_obj.scene_season
params['episode'] = ep_obj.scene_episode
return [params]
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0):
params = {"mode": "rss"}
if search_params:
params.update(search_params)
search_url = self.url + 'search/index.php?' + urllib.urlencode(params)
logger.log(u"Search string: " + search_url, logger.DEBUG)
results = []
for curItem in self.cache.getRSSFeed(search_url, items=['entries'])['entries'] or []:
(title, url) = self._get_title_and_url(curItem)
if title and url:
logger.log(u"RSS Feed provider: [" + self.name + "] Attempting to add item to cache: " + title, logger.DEBUG)
results.append(curItem)
return results
def _get_title_and_url(self, item):
(title, url) = generic.TorrentProvider._get_title_and_url(self, item)
try:
new_title = self._extract_name_from_filename(item.filename)
except:
new_title = None
if new_title:
title = new_title
logger.log(u"Extracted the name " + title + " from the torrent link", logger.DEBUG)
return (title, url)
def _extract_name_from_filename(self, filename):
name_regex = '(.*?)\.?(\[.*]|\d+\.TPB)\.torrent$'
logger.log(u"Comparing " + name_regex + " against " + filename, logger.DEBUG)
match = re.match(name_regex, filename, re.I)
if match:
return match.group(1)
return None
def seedRatio(self):
return self.ratio
class EZRSSCache(tvcache.TVCache):
def __init__(self, provider):
tvcache.TVCache.__init__(self, provider)
# only poll EZRSS every 15 minutes max
self.minTime = 15
def _getRSSData(self):
rss_url = self.provider.url + 'feed/'
logger.log(self.provider.name + " cache update URL: " + rss_url, logger.DEBUG)
return self.getRSSFeed(rss_url)
provider = EZRSSProvider()
|
gylian/sickrage
|
sickbeard/providers/ezrss.py
|
Python
|
gpl-3.0
| 5,370
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2007-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 3 as published by the Free Software Foundation.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#ifndef EIGEN_CONSTANTS_H
#define EIGEN_CONSTANTS_H
/** This value means that a quantity is not known at compile-time, and that instead the value is
* stored in some runtime variable.
*
* Changing the value of Dynamic breaks the ABI, as Dynamic is often used as a template parameter for Matrix.
*/
const int Dynamic = -1;
/** This value means +Infinity; it is currently used only as the p parameter to MatrixBase::lpNorm<int>().
* The value Infinity there means the L-infinity norm.
*/
const int Infinity = -1;
/** \defgroup flags Flags
* \ingroup Core_Module
*
* These are the possible bits which can be OR'ed to constitute the flags of a matrix or
* expression.
*
* It is important to note that these flags are a purely compile-time notion. They are a compile-time property of
* an expression type, implemented as enum's. They are not stored in memory at runtime, and they do not incur any
* runtime overhead.
*
* \sa MatrixBase::Flags
*/
/** \ingroup flags
*
* for a matrix, this means that the storage order is row-major.
* If this bit is not set, the storage order is column-major.
* For an expression, this determines the storage order of
* the matrix created by evaluation of that expression.
* \sa \ref TopicStorageOrders */
const unsigned int RowMajorBit = 0x1;
/** \ingroup flags
*
* means the expression should be evaluated by the calling expression */
const unsigned int EvalBeforeNestingBit = 0x2;
/** \ingroup flags
*
* means the expression should be evaluated before any assignment */
const unsigned int EvalBeforeAssigningBit = 0x4;
/** \ingroup flags
*
* Short version: means the expression might be vectorized
*
* Long version: means that the coefficients can be handled by packets
* and start at a memory location whose alignment meets the requirements
* of the present CPU architecture for optimized packet access. In the fixed-size
* case, there is the additional condition that it be possible to access all the
* coefficients by packets (this implies the requirement that the size be a multiple of 16 bytes,
* and that any nontrivial strides don't break the alignment). In the dynamic-size case,
* there is no such condition on the total size and strides, so it might not be possible to access
* all coeffs by packets.
*
* \note This bit can be set regardless of whether vectorization is actually enabled.
* To check for actual vectorizability, see \a ActualPacketAccessBit.
*/
const unsigned int PacketAccessBit = 0x8;
#ifdef EIGEN_VECTORIZE
/** \ingroup flags
*
* If vectorization is enabled (EIGEN_VECTORIZE is defined) this constant
* is set to the value \a PacketAccessBit.
*
* If vectorization is not enabled (EIGEN_VECTORIZE is not defined) this constant
* is set to the value 0.
*/
const unsigned int ActualPacketAccessBit = PacketAccessBit;
#else
const unsigned int ActualPacketAccessBit = 0x0;
#endif
/** \ingroup flags
*
* Short version: means the expression can be seen as 1D vector.
*
* Long version: means that one can access the coefficients
* of this expression by coeff(int), and coeffRef(int) in the case of a lvalue expression. These
* index-based access methods are guaranteed
* to not have to do any runtime computation of a (row, col)-pair from the index, so that it
* is guaranteed that whenever it is available, index-based access is at least as fast as
* (row,col)-based access. Expressions for which that isn't possible don't have the LinearAccessBit.
*
* If both PacketAccessBit and LinearAccessBit are set, then the
* packets of this expression can be accessed by packet(int), and writePacket(int) in the case of a
* lvalue expression.
*
* Typically, all vector expressions have the LinearAccessBit, but there is one exception:
* Product expressions don't have it, because it would be troublesome for vectorization, even when the
* Product is a vector expression. Thus, vector Product expressions allow index-based coefficient access but
* not index-based packet access, so they don't have the LinearAccessBit.
*/
const unsigned int LinearAccessBit = 0x10;
/** \ingroup flags
*
* Means the expression has a coeffRef() method, i.e. is writable as its individual coefficients are directly addressable.
* This rules out read-only expressions.
*
* Note that DirectAccessBit and LvalueBit are mutually orthogonal, as there are examples of expression having one but note
* the other:
* \li writable expressions that don't have a very simple memory layout as a strided array, have LvalueBit but not DirectAccessBit
* \li Map-to-const expressions, for example Map<const Matrix>, have DirectAccessBit but not LvalueBit
*
* Expressions having LvalueBit also have their coeff() method returning a const reference instead of returning a new value.
*/
const unsigned int LvalueBit = 0x20;
/** \ingroup flags
*
* Means that the underlying array of coefficients can be directly accessed as a plain strided array. The memory layout
* of the array of coefficients must be exactly the natural one suggested by rows(), cols(),
* outerStride(), innerStride(), and the RowMajorBit. This rules out expressions such as Diagonal, whose coefficients,
* though referencable, do not have such a regular memory layout.
*
* See the comment on LvalueBit for an explanation of how LvalueBit and DirectAccessBit are mutually orthogonal.
*/
const unsigned int DirectAccessBit = 0x40;
/** \ingroup flags
*
* means the first coefficient packet is guaranteed to be aligned */
const unsigned int AlignedBit = 0x80;
const unsigned int NestByRefBit = 0x100;
// list of flags that are inherited by default
const unsigned int HereditaryBits = RowMajorBit
| EvalBeforeNestingBit
| EvalBeforeAssigningBit;
/** \defgroup enums Enumerations
* \ingroup Core_Module
*
* Various enumerations used in %Eigen. Many of these are used as template parameters.
*/
/** \ingroup enums
* Enum containing possible values for the \p Mode parameter of
* MatrixBase::selfadjointView() and MatrixBase::triangularView(). */
enum {
/** View matrix as a lower triangular matrix. */
Lower=0x1,
/** View matrix as an upper triangular matrix. */
Upper=0x2,
/** %Matrix has ones on the diagonal; to be used in combination with #Lower or #Upper. */
UnitDiag=0x4,
/** %Matrix has zeros on the diagonal; to be used in combination with #Lower or #Upper. */
ZeroDiag=0x8,
/** View matrix as a lower triangular matrix with ones on the diagonal. */
UnitLower=UnitDiag|Lower,
/** View matrix as an upper triangular matrix with ones on the diagonal. */
UnitUpper=UnitDiag|Upper,
/** View matrix as a lower triangular matrix with zeros on the diagonal. */
StrictlyLower=ZeroDiag|Lower,
/** View matrix as an upper triangular matrix with zeros on the diagonal. */
StrictlyUpper=ZeroDiag|Upper,
/** Used in BandMatrix and SelfAdjointView to indicate that the matrix is self-adjoint. */
SelfAdjoint=0x10
};
/** \ingroup enums
* Enum for indicating whether an object is aligned or not. */
enum {
/** Object is not correctly aligned for vectorization. */
Unaligned=0,
/** Object is aligned for vectorization. */
Aligned=1
};
enum { ConditionalJumpCost = 5 };
/** \ingroup enums
* Enum used by DenseBase::corner() in Eigen2 compatibility mode. */
// FIXME after the corner() API change, this was not needed anymore, except by AlignedBox
// TODO: find out what to do with that. Adapt the AlignedBox API ?
enum CornerType { TopLeft, TopRight, BottomLeft, BottomRight };
/** \ingroup enums
* Enum containing possible values for the \p Direction parameter of
* Reverse, PartialReduxExpr and VectorwiseOp. */
enum DirectionType {
/** For Reverse, all columns are reversed;
* for PartialReduxExpr and VectorwiseOp, act on columns. */
Vertical,
/** For Reverse, all rows are reversed;
* for PartialReduxExpr and VectorwiseOp, act on rows. */
Horizontal,
/** For Reverse, both rows and columns are reversed;
* not used for PartialReduxExpr and VectorwiseOp. */
BothDirections
};
enum ProductEvaluationMode { NormalProduct, CacheFriendlyProduct };
/** \internal \ingroup enums
* Enum to specify how to traverse the entries of a matrix. */
enum {
/** \internal Default traversal, no vectorization, no index-based access */
DefaultTraversal,
/** \internal No vectorization, use index-based access to have only one for loop instead of 2 nested loops */
LinearTraversal,
/** \internal Equivalent to a slice vectorization for fixed-size matrices having good alignment
* and good size */
InnerVectorizedTraversal,
/** \internal Vectorization path using a single loop plus scalar loops for the
* unaligned boundaries */
LinearVectorizedTraversal,
/** \internal Generic vectorization path using one vectorized loop per row/column with some
* scalar loops to handle the unaligned boundaries */
SliceVectorizedTraversal,
/** \internal Special case to properly handle incompatible scalar types or other defecting cases*/
InvalidTraversal
};
/** \internal \ingroup enums
* Enum to specify whether to unroll loops when traversing over the entries of a matrix. */
enum {
/** \internal Do not unroll loops. */
NoUnrolling,
/** \internal Unroll only the inner loop, but not the outer loop. */
InnerUnrolling,
/** \internal Unroll both the inner and the outer loop. If there is only one loop,
* because linear traversal is used, then unroll that loop. */
CompleteUnrolling
};
/** \ingroup enums
* Enum containing possible values for the \p _Options template parameter of
* Matrix, Array and BandMatrix. */
enum {
/** Storage order is column major (see \ref TopicStorageOrders). */
ColMajor = 0,
/** Storage order is row major (see \ref TopicStorageOrders). */
RowMajor = 0x1, // it is only a coincidence that this is equal to RowMajorBit -- don't rely on that
/** \internal Align the matrix itself if it is vectorizable fixed-size */
AutoAlign = 0,
/** \internal Don't require alignment for the matrix itself (the array of coefficients, if dynamically allocated, may still be requested to be aligned) */ // FIXME --- clarify the situation
DontAlign = 0x2
};
/** \ingroup enums
* Enum for specifying whether to apply or solve on the left or right. */
enum {
/** Apply transformation on the left. */
OnTheLeft = 1,
/** Apply transformation on the right. */
OnTheRight = 2
};
/* the following could as well be written:
* enum NoChange_t { NoChange };
* but it feels dangerous to disambiguate overloaded functions on enum/integer types.
* If on some platform it is really impossible to get rid of "unused variable" warnings, then
* we can always come back to that solution.
*/
struct NoChange_t {};
namespace {
EIGEN_UNUSED NoChange_t NoChange;
}
struct Sequential_t {};
namespace {
EIGEN_UNUSED Sequential_t Sequential;
}
struct Default_t {};
namespace {
EIGEN_UNUSED Default_t Default;
}
/** \internal \ingroup enums
* Used in AmbiVector. */
enum {
IsDense = 0,
IsSparse
};
/** \ingroup enums
* Used as template parameter in DenseCoeffBase and MapBase to indicate
* which accessors should be provided. */
enum AccessorLevels {
/** Read-only access via a member function. */
ReadOnlyAccessors,
/** Read/write access via member functions. */
WriteAccessors,
/** Direct read-only access to the coefficients. */
DirectAccessors,
/** Direct read/write access to the coefficients. */
DirectWriteAccessors
};
/** \ingroup enums
* Enum with options to give to various decompositions. */
enum DecompositionOptions {
/** \internal Not used (meant for LDLT?). */
Pivoting = 0x01,
/** \internal Not used (meant for LDLT?). */
NoPivoting = 0x02,
/** Used in JacobiSVD to indicate that the square matrix U is to be computed. */
ComputeFullU = 0x04,
/** Used in JacobiSVD to indicate that the thin matrix U is to be computed. */
ComputeThinU = 0x08,
/** Used in JacobiSVD to indicate that the square matrix V is to be computed. */
ComputeFullV = 0x10,
/** Used in JacobiSVD to indicate that the thin matrix V is to be computed. */
ComputeThinV = 0x20,
/** Used in SelfAdjointEigenSolver and GeneralizedSelfAdjointEigenSolver to specify
* that only the eigenvalues are to be computed and not the eigenvectors. */
EigenvaluesOnly = 0x40,
/** Used in SelfAdjointEigenSolver and GeneralizedSelfAdjointEigenSolver to specify
* that both the eigenvalues and the eigenvectors are to be computed. */
ComputeEigenvectors = 0x80,
/** \internal */
EigVecMask = EigenvaluesOnly | ComputeEigenvectors,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ Ax = \lambda B x \f$. */
Ax_lBx = 0x100,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ ABx = \lambda x \f$. */
ABx_lx = 0x200,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ BAx = \lambda x \f$. */
BAx_lx = 0x400,
/** \internal */
GenEigMask = Ax_lBx | ABx_lx | BAx_lx
};
/** \ingroup enums
* Possible values for the \p QRPreconditioner template parameter of JacobiSVD. */
enum QRPreconditioners {
/** Do not specify what is to be done if the SVD of a non-square matrix is asked for. */
NoQRPreconditioner,
/** Use a QR decomposition without pivoting as the first step. */
HouseholderQRPreconditioner,
/** Use a QR decomposition with column pivoting as the first step. */
ColPivHouseholderQRPreconditioner,
/** Use a QR decomposition with full pivoting as the first step. */
FullPivHouseholderQRPreconditioner
};
#ifdef Success
#error The preprocessor symbol 'Success' is defined, possibly by the X11 header file X.h
#endif
/** \ingroups enums
* Enum for reporting the status of a computation. */
enum ComputationInfo {
/** Computation was successful. */
Success = 0,
/** The provided data did not satisfy the prerequisites. */
NumericalIssue = 1,
/** Iterative procedure did not converge. */
NoConvergence = 2
};
/** \ingroup enums
* Enum used to specify how a particular transformation is stored in a matrix.
* \sa Transform, Hyperplane::transform(). */
enum TransformTraits {
/** Transformation is an isometry. */
Isometry = 0x1,
/** Transformation is an affine transformation stored as a (Dim+1)^2 matrix whose last row is
* assumed to be [0 ... 0 1]. */
Affine = 0x2,
/** Transformation is an affine transformation stored as a (Dim) x (Dim+1) matrix. */
AffineCompact = 0x10 | Affine,
/** Transformation is a general projective transformation stored as a (Dim+1)^2 matrix. */
Projective = 0x20
};
/** \internal \ingroup enums
* Enum used to choose between implementation depending on the computer architecture. */
namespace Architecture
{
enum Type {
Generic = 0x0,
SSE = 0x1,
AltiVec = 0x2,
#if defined EIGEN_VECTORIZE_SSE
Target = SSE
#elif defined EIGEN_VECTORIZE_ALTIVEC
Target = AltiVec
#else
Target = Generic
#endif
};
}
/** \internal \ingroup enums
* Enum used as template parameter in GeneralProduct. */
enum { CoeffBasedProductMode, LazyCoeffBasedProductMode, OuterProduct, InnerProduct, GemvProduct, GemmProduct };
/** \internal \ingroup enums
* Enum used in experimental parallel implementation. */
enum Action {GetAction, SetAction};
/** The type used to identify a dense storage. */
struct Dense {};
/** The type used to identify a matrix expression */
struct MatrixXpr {};
/** The type used to identify an array expression */
struct ArrayXpr {};
#endif // EIGEN_CONSTANTS_H
|
muninnorg/muninn
|
external/Eigen/src/Core/util/Constants.h
|
C
|
gpl-3.0
| 16,916
|
using FemLab
#=
for shape in (TRI3, TRI6, QUAD4, QUAD8, QUAD9)
bl = Block2D( [0 0; 1 1], nx=2, ny=2, shape=shape)
mesh = Mesh(bl, verbose=false)
dom = Domain(mesh)
save(dom, "dom.vtk")
end
rm("dom.vtk")
=#
bl = Block2D( [0 0; 1 1], nx=4, ny=4, shape=QUAD9)
mesh = Mesh(bl, verbose=false)
dom = Domain(mesh)
set_mat(dom.elems[:solids], ElasticSolid(E=100.0, nu=0.2) )
bc1 = NodeBC(:(y==0), ux=0, uy=0)
bc2 = FaceBC(:(y==1), tz=2)
println(dom.nodes)
for node in dom.nodes[1:5]
println(node.dofs)
end
println(dom.elems)
println(dom.elems[:ips])
println(dom)
println(bc1)
println(bc2)
|
RaulDurand/FemLab
|
test/io.jl
|
Julia
|
gpl-3.0
| 606
|
<?php
add_action( 'admin_menu', 'us_options_admin_menu' );
function us_options_admin_menu() {
$usof_page = add_submenu_page( 'us-home', US_THEMENAME, __( 'Theme Options', 'us' ), 'edit_theme_options', 'us-theme-options', 'us_theme_options_page' );
add_action( 'admin_print_scripts-' . $usof_page, 'usof_print_scripts' );
add_action( 'admin_print_styles-' . $usof_page, 'usof_print_styles' );
}
function us_theme_options_page() {
// For notices
echo '<div class="wrap"><h2 class="hidden"></h2>';
global $usof_directory, $usof_options;
usof_load_options_once();
$usof_options = array_merge( usof_defaults(), $usof_options );
$config = us_config( 'theme-options', array() );
echo '<div class="usof-container" data-ajaxurl="' . esc_attr( admin_url( 'admin-ajax.php' ) ) . '">';
echo '<form class="usof-form" method="post" action="#" autocomplete="off">';
// Output _nonce and _wp_http_referer hidden fields for ajax secuirity checks
wp_nonce_field( 'usof-actions' );
echo '<div class="usof-header"><div class="usof-header-logo"><div class="usof-header-logo-text">';
echo US_THEMENAME . ' <span>' . US_THEMEVERSION . '</span></div></div>';
echo '<div class="usof-header-title"><h2>' . __( 'General Settings', 'us' ) . '</h2></div>';
echo '<div class="usof-control for_save status_clear">';
echo '<button class="usof-button type_save" type="button"><span>' . __( 'Save Changes', 'us' ) . '</span>';
echo '<span class="usof-preloader"></span></button>';
echo '<div class="usof-control-message"></div></div></div>';
// Main menu
echo '<div class="usof-nav layout_desktop"><div class="usof-nav-control"></div><ul class="usof-nav-list level_1">';
foreach ( $config as $section_id => &$section ) {
if ( isset( $section['place_if'] ) AND ! $section['place_if'] ) {
continue;
}
if ( ! isset( $active_section ) ) {
$active_section = $section_id;
}
echo '<li class="usof-nav-item level_1 id_' . $section_id . ( ( $section_id == $active_section ) ? ' current' : '' ) . '"';
echo ' data-id="' . $section_id . '">';
echo '<a class="usof-nav-anchor level_1" href="#' . $section_id . '">';
echo '<span class="usof-nav-icon" style="background-image: url(' . $section['icon'] . ')"></span>';
echo '<span class="usof-nav-title">' . $section['title'] . '</span>';
echo '<span class="usof-nav-arrow"></span></a></li>';
}
echo '<ul></div>';
// Content
echo '<div class="usof-content">';
foreach ( $config as $section_id => &$section ) {
if ( isset( $section['place_if'] ) AND ! $section['place_if'] ) {
continue;
}
echo '<section class="usof-section ' . ( ( $section_id == $active_section ) ? 'current' : '' ) . '" data-id="' . $section_id . '">';
echo '<div class="usof-section-header" data-id="' . $section_id . '">';
echo '<h3>' . $section['title'] . '</h3><span class="usof-section-header-control"></span></div>';
echo '<div class="usof-section-content" style="display: ' . ( ( $section_id == $active_section ) ? 'block' : 'none' ) . '">';
if ( isset( $section['fields'] ) ) {
foreach ( $section['fields'] as $field_id => &$field ) {
if ( isset( $field['place_if'] ) AND ! $field['place_if'] ) {
continue;
}
if ( ! isset( $field['type'] ) ) {
if ( WP_DEBUG ) {
wp_die( $field_id . ' has no defined type' );
}
continue;
}
$show_field = ( ! isset( $field['show_if'] ) OR usof_execute_show_if( $field['show_if'] ) );
if ( $field['type'] == 'wrapper_start' ) {
echo '<div class="usof-form-wrapper ' . $field_id . '" data-id="' . $field_id . '" ';
echo 'style="display: ' . ( $show_field ? 'block' : 'none' ) . '">';
if ( isset( $field['show_if'] ) AND is_array( $field['show_if'] ) AND ! empty( $field['show_if'] ) ) {
// Showing conditions
echo '<div class="usof-form-wrapper-showif"' . us_pass_data_to_js( $field['show_if'] ) . '></div>';
}
continue;
} elseif ( $field['type'] == 'wrapper_end' ) {
echo '</div>';
continue;
}
if ( ! file_exists( $usof_directory . '/fields/' . $field['type'] . '.php' ) ) {
continue;
}
$field['std'] = isset( $field['std'] ) ? $field['std'] : NULL;
$value = isset( $usof_options[ $field_id ] ) ? $usof_options[ $field_id ] : $field['std'];
$row_classes = ' type_' . $field['type'];
if ( $field['type'] != 'message' AND ( ! isset( $field['classes'] ) OR strpos( $field['classes'], 'desc_' ) === FALSE ) ) {
$row_classes .= ' desc_3';
}
if ( isset( $field['classes'] ) AND ! empty( $field['classes'] ) ) {
$row_classes .= ' ' . $field['classes'];
}
echo '<div class="usof-form-row' . $row_classes . '" data-id="' . $field_id . '" ';
echo 'style="display: ' . ( $show_field ? 'block' : 'none' ) . '">';
if ( isset( $field['title'] ) AND ! empty( $field['title'] ) ) {
echo '<div class="usof-form-row-title"><span>' . $field['title'] . '</span></div>';
}
echo '<div class="usof-form-row-field">';
// Including the field control itself
include $usof_directory . '/fields/' . $field['type'] . '.php';
if ( isset( $field['description'] ) AND ! empty( $field['description'] ) ) {
echo '<div class="usof-form-row-desc">';
echo '<div class="usof-form-row-desc-icon"></div>';
echo '<div class="usof-form-row-desc-text">' . $field['description'] . '</div>';
echo '</div>';
}
echo '<div class="usof-form-row-state"></div>';
echo '</div>'; // .usof-form-row-field
if ( isset( $field['show_if'] ) AND is_array( $field['show_if'] ) AND ! empty( $field['show_if'] ) ) {
// Showing conditions
echo '<div class="usof-form-row-showif"' . us_pass_data_to_js( $field['show_if'] ) . '></div>';
}
echo '</div>'; // .usof-form-row
}
}
echo '</div></section>';
}
echo '</div>';
// Footer
echo '<div class="usof-footer"><div class="usof-control for_save status_clear">';
echo '<button class="usof-button type_save" type="button"><span>' . __( 'Save Changes', 'us' ) . '</span>';
echo '<span class="usof-preloader"></span></button>';
echo '<div class="usof-control-message"></div></div>';
echo '<div class="usof-control for_reset status_clear">';
echo '<button class="usof-button type_reset" type="button"><span>' . __( 'Reset Options', 'us' ) . '</span>';
echo '<span class="usof-preloader"></span></button>';
echo '<div class="usof-control-message"></div></div>';
echo '<div class="usof-footer-bgscroll"></div></div>';
echo '</form>';
echo '</div>';
echo '</div>';
}
function usof_print_scripts() {
global $usof_directory_uri, $usof_version;
if ( ! did_action( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
wp_enqueue_script( 'usof-colorpicker', $usof_directory_uri . '/js/colpick.js', array( 'jquery' ), '1.0', TRUE );
wp_enqueue_script( 'usof-select2', $usof_directory_uri . '/js/select2.min.js', array( 'jquery' ), '4.0', TRUE );
wp_enqueue_script( 'usof-scripts', $usof_directory_uri . '/js/usof.js', array( 'jquery' ), $usof_version, TRUE );
}
function usof_print_styles() {
global $usof_directory_uri, $usof_version;
wp_enqueue_style( 'usof-colorpicker', $usof_directory_uri . '/css/colpick.css', array(), '1.0' );
wp_enqueue_style( 'usof-select2', $usof_directory_uri . '/css/select2.css', array(), '4.0' );
wp_enqueue_style( 'usof-styles', $usof_directory_uri . '/css/usof.css', array(), $usof_version );
}
/**
* Checks if the showing condition is true
*
* Note: at any possible syntax error we choose to show the field so it will be functional anyway.
*
* @param array $condition Showing condition
*
* @return bool
*/
function usof_execute_show_if( $condition ) {
global $usof_options;
if ( ! is_array( $condition ) OR count( $condition ) < 3 ) {
// Wrong condition
$result = TRUE;
} elseif ( in_array( strtolower( $condition[1] ), array( 'and', 'or' ) ) ) {
// Complex or / and statement
$result = usof_execute_show_if( $condition[0] );
$index = 2;
while ( isset( $condition[ $index ] ) ){
$condition[ $index - 1 ] = strtolower( $condition[ $index - 1 ] );
if ( $condition[ $index - 1 ] == 'and' ) {
$result = ( $result AND usof_execute_show_if( $condition[ $index ] ) );
} elseif ( $condition[ $index - 1 ] == 'or' ) {
$result = ( $result OR usof_execute_show_if( $condition[ $index ] ) );
}
$index = $index + 2;
}
} else {
if ( ! isset( $usof_options[ $condition[0] ] ) ) {
return TRUE;
}
$value = $usof_options[ $condition[0] ];
if ( $condition[1] == '=' ) {
$result = ( $value == $condition[2] );
} elseif ( $condition[1] == '!=' OR $condition[1] == '<>' ) {
$result = ( $value != $condition[2] );
} elseif ( $condition[1] == 'in' ) {
$result = ( ! is_array( $condition[2] ) OR in_array( $value, $condition[2] ) );
} elseif ( $condition[1] == 'not in' ) {
$result = ( ! is_array( $condition[2] ) OR ! in_array( $value, $condition[2] ) );
} elseif ( $condition[1] == '<=' ) {
$result = ( $value <= $condition[2] );
} elseif ( $condition[1] == '<' ) {
$result = ( $value < $condition[2] );
} elseif ( $condition[1] == '>' ) {
$result = ( $value > $condition[2] );
} elseif ( $condition[1] == '>=' ) {
$result = ( $value >= $condition[2] );
} else {
$result = TRUE;
}
}
return $result;
}
|
Fecaje/fecaje.org.br
|
wp-content/themes/Zephyr/framework/vendor/usof/functions/interface.php
|
PHP
|
gpl-3.0
| 9,259
|
"""
Unit tests for the HashTask object
By Simon Jones
26/8/2017
"""
import unittest
from test.TestFunctions import *
from source.HashTask import *
from source.Channel import Channel
class HashTaskUnitTests(unittest.TestCase):
"""
Unit tests for the HashTask object
"""
def setUp(self):
self.task1_t_channel = Channel(True)
self.task1_c_channel = Channel(True)
self.task2_t_channel = Channel(True)
self.task2_c_channel = Channel(True)
self.task1 = spawn_thread(self.task1_c_channel, self.task1_t_channel)
self.task2 = spawn_thread(self.task2_c_channel, self.task2_t_channel)
self.test_filename = "hash_task_unittest_file.log"
file = open(self.test_filename, "w")
file.write("Test Data 123\nHello, world!")
file.close()
print("\nNew Test case:")
def test_spawning_and_joining_tasks(self):
"""
Tests that tasks can be created and joined
:return:
"""
self.task1.start()
self.task2.start()
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 1, TaskMessage.REQUEST, "Hello World Task1")))
self.task2_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 2, TaskMessage.REQUEST, "Hello World Task2")))
# Should be ignored
self.task2_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 2, TaskMessage.RESPONSE, "Hello World Task2")))
delay_do_nothing(1)
self.task1_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 1, TaskMessage.REQUEST)))
self.task2_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 2, TaskMessage.REQUEST)))
self.task1.join()
self.task2.join()
empty_channel(self, self.task1_t_channel.get_in_queue(), 3)
empty_channel(self, self.task2_t_channel.get_in_queue(), 3)
empty_channel(self, self.task1_c_channel.get_in_queue(), 2)
empty_channel(self, self.task2_c_channel.get_in_queue(), 2)
def test_task_errors(self):
"""
Tests that HashTasks can handle errors properly
:return:
"""
self.task1.start()
self.task2.start()
self.task1_t_channel.put(str(TaskMessage("NOT_A_FLAG", 1, TaskMessage.REQUEST, "ERROR_TASK")))
delay_do_nothing()
self.task1_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 1, TaskMessage.REQUEST)))
self.task2_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 2, TaskMessage.REQUEST)))
self.task1.join()
self.task2.join()
empty_channel(self, self.task1_t_channel.get_in_queue(), 3)
empty_channel(self, self.task2_t_channel.get_in_queue(), 1)
empty_channel(self, self.task1_c_channel.get_in_queue(), 2)
empty_channel(self, self.task2_c_channel.get_in_queue(), 2)
def test_another_hash_task_case(self):
"""
Another test for robustness
:return:
"""
self.task1.start()
self.task2.start()
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_HASH, 1, TaskMessage.REQUEST, self.test_filename, 0, 10)))
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_HASH, 1, TaskMessage.REQUEST, self.test_filename, 10, 10)))
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_HASH, 1, TaskMessage.REQUEST, self.test_filename, 20, 10)))
delay_do_nothing(1)
self.task1_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 1, TaskMessage.REQUEST)))
self.task2_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 2, TaskMessage.REQUEST)))
self.task1.join()
self.task2.join()
empty_channel(self, self.task1_t_channel.get_in_queue(), 5)
empty_channel(self, self.task2_t_channel.get_in_queue(), 1)
empty_channel(self, self.task1_c_channel.get_in_queue(), 2)
empty_channel(self, self.task2_c_channel.get_in_queue(), 2)
def test_actions_after_join_are_executes(self):
"""
Tests that the messages received after a join task are executed.
:return:
"""
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 1, TaskMessage.REQUEST, "Echo 1")))
self.task2_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 2, TaskMessage.REQUEST, "Echo 1")))
self.task1_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 1, TaskMessage.REQUEST)))
self.task2_c_channel.put(str(TaskMessage(TaskMessage.FLAG_JOIN, 2, TaskMessage.REQUEST)))
self.task1_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 1, TaskMessage.REQUEST, "Echo 2")))
self.task2_t_channel.put(str(TaskMessage(TaskMessage.FLAG_ECHO, 2, TaskMessage.REQUEST, "Echo 2")))
self.task1.start()
self.task2.start()
delay_do_nothing(1)
self.task1.join()
self.task2.join()
empty_channel(self, self.task1_t_channel.get_in_queue(), 2)
empty_channel(self, self.task2_t_channel.get_in_queue(), 2)
empty_channel(self, self.task1_c_channel.get_in_queue(), 2)
empty_channel(self, self.task2_c_channel.get_in_queue(), 2)
if __name__ == "__main__":
unittest.main()
|
jonesyboynz/DuplicateFileFinder
|
unittests/HashTaskUnitTests.py
|
Python
|
gpl-3.0
| 4,641
|
The programs in here are to test Python stdlib tests in lib/pythonX.Y/test
We'll compile a test, then decompile it and then run the test
|
rocky/python-uncompyle6
|
test/stdlib/README.md
|
Markdown
|
gpl-3.0
| 139
|
package com.jcp83.telegraph;
import java.io.Serializable;
public class RoomInfo implements Serializable
{
private String Name;
public String GetName() { return Name; }
RoomInfo(String Name)
{
this.Name = Name;
}
}
|
Prog63/Telegraph
|
app/src/main/java/com/jcp83/telegraph/RoomInfo.java
|
Java
|
gpl-3.0
| 243
|
#
# Copyright (C) 2013 CAS / FAMU
#
# This file is part of Narra Core.
#
# Narra Core 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.
#
# Narra Core 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 Narra Core. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Michal Mocnak <michal@marigan.net>, Krystof Pesek <krystof.pesek@gmail.com>
#
module Narra
class Identity
include Mongoid::Document
include Mongoid::Timestamps
# Fields
field :provider, type: String
field :uid, type: String
# User relations
belongs_to :user, class_name: 'Narra::User'
# Validations
validates_uniqueness_of :uid, scope: :provider
validates_presence_of :user_id, :uid, :provider
# Find identity from the omniauth hash
def self.find_from_hash(hash)
where(provider: hash[:provider], uid: hash[:uid]).first
end
# Create a new identity from the omniauth hash
def self.create_from_hash(hash, user = nil)
user ||= Narra::User.create_from_hash!(hash)
Narra::Identity.create(:user => user, :uid => hash[:uid], :provider => hash[:provider])
end
end
end
|
CAS-FAMU/narra-core
|
app/models/narra/identity.rb
|
Ruby
|
gpl-3.0
| 1,563
|
/* This file is part of rfGallery.
*
* rfGallery 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.
*
* rfGallery 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 rfGallery. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Michael Hauspie <mickey AT fairy-project DOT org>
*/
body {
font-family: sans-serif;
font-size: small;
color: white;
background: #222222;
}
#content {
width: 90%;
margin-left: auto;
margin-right: auto;
display: block;
}
#copyright {
clear: both;
font-size: xx-small;
text-align: center;
}
a {
text-decoration: none;
color: #AAAAAA;
}
a:hover {
background: #666666;
}
.dirs {
}
.thumb {
text-align: center;
padding: 5px;
display: inline;
float: left;
width: 390px;
height: 340px;
}
.thumb:hover {
background: #666666;
text-align: center;
}
img {
border: none;
}
#title {
font-size: large;
color: white;
text-align: center;
}
.debug {
border: 1px solid black;
background: black;
color: red;
text-align: center;
}
.error {
border: 3px solid red;
background: black;
color: red;
font-size: large;
text-align: center;
}
|
hauspie/rfgallery
|
css/style.css
|
CSS
|
gpl-3.0
| 1,672
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pl_PL">
<context>
<name>EditSiteWidget</name>
<message>
<location filename="../../ui/edit_site_widget.ui" line="14"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="25"/>
<source>Categories:</source>
<translation>Kategorie:</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="32"/>
<source>Site Name:</source>
<translation>Nazwa strony:</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="45"/>
<source><html><head/><body><p>Password Type:</p></body></html></source>
<translation><html><head/><body><p>Typ hasła:</p></body></html></translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="65"/>
<source>Site Counter:<br>(increase to get a <br>new password)</source>
<translation>Licznik strony:<br>(zwiększ, by otrzymać<br> nowe hasło)</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="80"/>
<source>Sample Password:</source>
<translation>Przykładowe hasło:</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="94"/>
<source>Password is determined by the User Name, Master Password, Site Name, Type and Counter</source>
<translation>Hasło jest zależne od nazwy użytkownika, hasła głównego, nazwy strony, typu i licznika</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="106"/>
<source><html><head/><body><p><b>Optional</b></p></body></html></source>
<translation><html><head/><body><p><b>Opcjonalne</b></p></body></html></translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="116"/>
<source>Comment:</source>
<translation>Komentarz:</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="126"/>
<source>Login Name:</source>
<translation>Nazwa logowania:</translation>
</message>
<message>
<location filename="../../ui/edit_site_widget.ui" line="142"/>
<source>Url:</source>
<translation>Adres URL:</translation>
</message>
<message>
<location filename="../../src/edit_site_widget.cpp" line="46"/>
<source>Edit Site</source>
<translation>Edytuj stronę</translation>
</message>
<message>
<location filename="../../src/edit_site_widget.cpp" line="54"/>
<source>New Site</source>
<translation>Nowa strona</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../../ui/main_window.ui" line="14"/>
<source>qMasterPassword</source>
<translation></translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="82"/>
<location filename="../../src/main_window.cpp" line="323"/>
<source>Login</source>
<translation>Zaloguj</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="119"/>
<source>Categories</source>
<translation>Kategorie</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="161"/>
<source>Filter:</source>
<translation>Filtr</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="175"/>
<source>Add Site</source>
<translation>Dodaj stronę</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="185"/>
<source>Edit Site</source>
<translation>Edytuj stronę</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="195"/>
<source>Delete Site</source>
<translation>Usuń stronę</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="252"/>
<source>&Edit</source>
<translation>&Edycja</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="260"/>
<source>&Help</source>
<translation>&Pomoc</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="272"/>
<source>&Settings</source>
<translation>&Ustawienia</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="277"/>
<source>&About</source>
<translation>&O programie</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="282"/>
<source>Shortcuts</source>
<translation>Skróty</translation>
</message>
<message>
<location filename="../../ui/main_window.ui" line="287"/>
<source>Password Generator</source>
<translation>Generator haseł</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="174"/>
<source>&Quit</source>
<translation>&Wyjdź</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="271"/>
<source>Login Failed</source>
<translation>Logowanie nie powiodło się</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="272"/>
<source>Wrong Password</source>
<translation>Niepoprawne hasło</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="275"/>
<location filename="../../src/main_window.cpp" line="982"/>
<source>Logout</source>
<translation>Wyloguj</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="298"/>
<source>HMAC SHA256 function failed</source>
<translation>Funkcja HMAC SHA256 nie powiodła się</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="301"/>
<source>scrypt function failed</source>
<translation>Funkcja scrypt nie powiodła się</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="304"/>
<source>not logged in</source>
<translation>Niezalogowany</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="307"/>
<source>Multithreadding exception</source>
<translation>Błąd wielowątkowości</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="310"/>
<source>Random number generation failed</source>
<translation>Generowanie losowych liczb nie powiodło się</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="313"/>
<source>Cryptographic exception</source>
<translation>Błąd kryptograficzny</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="314"/>
<source>Error: %1.
Should it happen again, then something is seriously wrong with the program installation.</source>
<translation>Błąd: %1.
Jeśli błąd pojawi się kolejny raz, istnieje problem z instalacją programu.</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="344"/>
<source>User exists</source>
<translation>Użytkownik istnieje</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="345"/>
<source>Error: user already exists.</source>
<translation>Błąd: użytkownik już istnieje.</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="380"/>
<source>Delete User</source>
<translation>Usuń użytkownika</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="381"/>
<source>Do you really want to delete the user %1?</source>
<translation>Czy na pewno chcesz usunąć użytkownika %1?</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="561"/>
<source>All</source>
<translation>Wszystkie</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="736"/>
<location filename="../../src/main_window.cpp" line="747"/>
<source> for %1 seconds</source>
<translation>przez %1 sekund</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="737"/>
<source>Copied Password to Clipboard</source>
<translation>Hasło skopiowane do schowka </translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="748"/>
<source>Copied login name to Clipboard</source>
<translation>Skopoiowano nazwę logowania do schowka</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="850"/>
<source>&Hide</source>
<translation>&Ukryj</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="852"/>
<source>&Show</source>
<translation>&Pokaż</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="907"/>
<source>About %1</source>
<translation>O %1</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="966"/>
<source>Copy password of selected item to clipboard</source>
<translation>Skopiuj hasło wybranej pozycji </translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="968"/>
<source>Copy login/user name of selected item to clipboard</source>
<translation>Skopiuj login/nazwę logowania wybranej pozycji</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="970"/>
<source>Auto fill form: select next window and fill in user name (if set) and password</source>
<translation>Automatycznie wypełnij pola: wybierz kolejne okno i wypełnij nazwę użytkownika (jeśli ustawiona) oraz hasło</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="972"/>
<source>Auto fill form (password only)</source>
<translation>Autokatycznie wypełnij pole (tylko hasłem)</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="974"/>
<source>Focus the filter text</source>
<translation>Wybierz tekst filtra</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="976"/>
<source>Select previous item</source>
<translation>Wybierz poprzednią pozycję</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="978"/>
<source>Select next item</source>
<translation>Wybierz następną pozycję</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="980"/>
<source>Open URL of selected item</source>
<translation>Otwórz URL wybranej pozycji</translation>
</message>
</context>
<context>
<name>PasswordGeneratorWidget</name>
<message>
<location filename="../../ui/password_generator_widget.ui" line="14"/>
<source>Password Generator</source>
<translation>Generator haseł</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="22"/>
<source>Method:</source>
<translation>Metoda:</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="33"/>
<source>Characters</source>
<translation>Znaki</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="38"/>
<source>Templates</source>
<translation>Szablony</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="81"/>
<source>a-z</source>
<translation>a-z</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="91"/>
<source>0-9</source>
<translation>0-9</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="101"/>
<source>A-Z</source>
<translation>A-Z</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="114"/>
<source>@&&%?,=:+*$#!'^~;/.</source>
<translation>@&&%?,=:+*$#!'^~;/.</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="124"/>
<source>Select Characters:</source>
<translation>Wybierz znaki:</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="131"/>
<source>Custom Characters:</source>
<translation>Znaki niestandardowe:</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="144"/>
<source>()[]{}<></source>
<translation>()[]{}<></translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="151"/>
<source>_ (Underline)</source>
<translation>_ (Znak podkreślenia)</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="161"/>
<source>(Space)</source>
<translation>(Spacja)</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="168"/>
<source>- (Minus)</source>
<translation>- (Minus)</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="188"/>
<location filename="../../ui/password_generator_widget.ui" line="233"/>
<source>Password Length:</source>
<translation>Długość hasła:</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="259"/>
<source>Add special Character</source>
<translation>Dodaj znak specjalny</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="269"/>
<source>Add Number</source>
<translation>Dodaj cyfry</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="282"/>
<source>Password Strength</source>
<translation>Siła hasła</translation>
</message>
<message>
<location filename="../../ui/password_generator_widget.ui" line="319"/>
<source>Generate</source>
<translation>Wygeneruj</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="80"/>
<source> Bits</source>
<translation> Bity</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="85"/>
<source>Very Weak; might keep out family members</source>
<translation>Bardzo słabe; może najwyżej ochronić przed członkami rodziny</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="87"/>
<source>Weak; should keep out most people, often good for desktop login passwords</source>
<translation>Słabe; powinno chronić przed większością osób, często dobre dla haseł logowania do komputerów</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="89"/>
<source>Reasonable; fairly secure passwords for network and company passwords</source>
<translation>Rozsądne; dosyć bezpieczne hasło dla haseł do sieci i firm</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="91"/>
<source>Strong; can be good for guarding financial information</source>
<translation>Silne; może być stosowane do chronienia finansów</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="93"/>
<source>Very Strong; often overkill</source>
<translation>Bardzo silne; czasami przesada</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="153"/>
<source>Error</source>
<translation>Błąd</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="153"/>
<source>Failed to get random data</source>
<translation>Nie udało się otrzymać losowych danych</translation>
</message>
<message>
<location filename="../../src/password_generator_widget.cpp" line="278"/>
<source><p><b>Method</b><br>The character-based method is purely random for the chosen characters and thus harder to guess.<br>The template-based method on the other hand is a bit less random but its passwords are easier to remember.</p><p><b>Password Strength</b><br>Shows the entropy bits, where an increase of 1 means twice the amount of brute-force attempts is needed.<br>Note that the statement holds for general passwords. A master password in qMasterPassword is harder to crack (compared to for example web passwords), because the algorithm was specifically designed to be CPU intensive.</p></source>
<translation><p><b>Metoda</b><br>Metoda bazowana na znakach jest losowa i dzięki temu hasła są trudniejsze do zgadnięcia.<br>Metoda bazowana na szablonach jest mniej losoba, lecz hasła są łatwiejsze do zapamiętania.</p><p><b>Siła hasła</b><br>Pokazuje bity entropii (losowości), gdzie 1 bit więcej to dwukrotnie większa ilość czasu potrzebna na zgadnięcie hasła metodą brute-force.<br>Należy zauważyć, że ta zasada stosowana jest dla "zwykłych" haseł. Hasło główne w qMasterPassword jest skonstruowane tak, by było trudniejsze do złamania metodą brute-force, gdyż algorytm ten jest bardziej wymagający dla procesora.</p></translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../../src/main_window.cpp" line="143"/>
<source>Site</source>
<translation>Strona</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="144"/>
<source>Login Name</source>
<translation>Nazwa logowania</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="145"/>
<source>Password</source>
<translation>Hasło</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="148"/>
<source>Comment</source>
<translation>Komentarz</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="149"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location filename="../../src/main_window.cpp" line="150"/>
<source>Counter</source>
<translation>Licznik</translation>
</message>
</context>
<context>
<name>SettingsWidget</name>
<message>
<location filename="../../ui/settings_widget.ui" line="14"/>
<source>Settings</source>
<translation>Ustawienia</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="20"/>
<source>General</source>
<translation>Ogólne</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="26"/>
<source>Show Passwords after login</source>
<translation>Pokazuj hasła po zalogowaniu</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="33"/>
<source>Show System Tray Icon</source>
<translation>Pokazuj ikonę w pasku zadań</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="40"/>
<source>Fill Form (Ctrl+V): Hide Window instead of using Alt+Tab</source>
<translation>Wypełnianie pól (Ctrl+V): Ukryj okno zamiast używania Alt+Tab</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="49"/>
<source>Auto logout when Window is hidden.</source>
<translation>Wyoguj automatycznie gdy okno programu jest ukryte.</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="56"/>
<source>Timeout:</source>
<translation>Limit czasu:</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="70"/>
<source>Minutes</source>
<translatorcomment>In edge cases the word needs to be conjugated</translatorcomment>
<translation>Minut</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="94"/>
<source>Clipboard: Clear password after</source>
<translation>Schowek: Wyczyść hasło po</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="114"/>
<source>Seconds</source>
<translation>Sekundach</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="136"/>
<source>Show Identicon. Useful to notice typos in the entered master password.</source>
<translation>Pokazuj ikonę identyfikacyjną. Użyteczne dla zauważania literówek we wprowadzonym haśle.</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="146"/>
<source>Categories</source>
<translation>Kategorie</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="168"/>
<source>Remove</source>
<translation>Usuń</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="178"/>
<source>Add</source>
<translation>Dodaj</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="185"/>
<source>Restore Defaults</source>
<translation>Przywróć domyślne</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="195"/>
<source>Import/Export</source>
<translation>Import/Eksport</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="203"/>
<source>User:</source>
<translation>Użytkownik:</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="230"/>
<source>Import from JSON</source>
<translation>Importuj z JSON</translation>
</message>
<message>
<location filename="../../ui/settings_widget.ui" line="250"/>
<source>Export as JSON</source>
<translation>Eksportuj jako JSON</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="113"/>
<location filename="../../src/settings_widget.cpp" line="146"/>
<source>JSON (*.json)</source>
<translation>JSON</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="127"/>
<location filename="../../src/settings_widget.cpp" line="159"/>
<source>Error Opening File</source>
<translation>Błąd podczas otwierania pliku</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="128"/>
<source>Could not write to file %1</source>
<translation>Zapis do pliku %1 nie powiódł się</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="131"/>
<location filename="../../src/settings_widget.cpp" line="163"/>
<source>Error</source>
<translation>Błąd</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="132"/>
<location filename="../../src/settings_widget.cpp" line="164"/>
<source>unknown error (%1) occurred</source>
<translation>wystąpił nieznany błąd (%1)</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="160"/>
<source>Could not read from file %1</source>
<translation>Odczyt z pliku %1 nie powiódł się</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="210"/>
<source>Personal</source>
<translation>Osobiste</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="211"/>
<source>Work</source>
<translation>Praca</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="212"/>
<source>eShopping</source>
<translation>Zakupy internetowe</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="213"/>
<source>Social Networks</source>
<translation>Media społecznościowe</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="214"/>
<source>Bank</source>
<translation>Bank</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="215"/>
<source>Forum</source>
<translation>Fora</translation>
</message>
<message>
<location filename="../../src/settings_widget.cpp" line="216"/>
<source>eMail</source>
<translation>eMail</translation>
</message>
</context>
<context>
<name>ShortcutsWidget</name>
<message>
<location filename="../../ui/shortcuts_widget.ui" line="14"/>
<source>Keyboard Shortcuts</source>
<translation>Skróty klawiszowe</translation>
</message>
<message>
<location filename="../../ui/shortcuts_widget.ui" line="20"/>
<source>Keyboard shortcuts when a password entry is selected:</source>
<translation>Skróty klawiszowe gdy hasło jest wybrane:</translation>
</message>
<message>
<location filename="../../src/shortcuts_widget.cpp" line="15"/>
<source>Shortcut(s)</source>
<translation>Skrót(y)</translation>
</message>
<message>
<location filename="../../src/shortcuts_widget.cpp" line="16"/>
<source>Description</source>
<translation>Opis</translation>
</message>
</context>
<context>
<name>UserWidget</name>
<message>
<location filename="../../ui/user_widget.ui" line="20"/>
<source>Add User</source>
<translation>Dodaj użytkownika</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="56"/>
<source>Master Password:</source>
<translation>Hasło główne:</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="66"/>
<source>Repeat Password:</source>
<translation>Powtórz hasło:</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="76"/>
<source>User Name:</source>
<translation>Nazwa użytkownika:</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="96"/>
<source>Identicon:</source>
<translation>Ikona identyfikacyjna:</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="112"/>
<source>Generate...</source>
<translation>Wygeneruj...</translation>
</message>
<message>
<location filename="../../ui/user_widget.ui" line="121"/>
<source>Check Password when logging in.
(if enabled, the hash of the
password needs to be stored)</source>
<translation>Sprawdzaj hasło przy logowaniu.
(Gdy włączone, hash hasła
musi być zachowany w pliku)</translation>
</message>
<message>
<location filename="../../src/user_widget.cpp" line="38"/>
<source>Edit User</source>
<translation>Edytuj użytkownika</translation>
</message>
<message>
<location filename="../../src/user_widget.cpp" line="60"/>
<source>Cryptographic exception</source>
<translation>Błąd kryptograficzny</translation>
</message>
<message>
<location filename="../../src/user_widget.cpp" line="61"/>
<source>Failed to generate password hash. password check will be disabled.</source>
<translation>Generowanie hashu hasła nie powiodło się. Sprawdzanie hasła zostanie wyłączone.</translation>
</message>
<message>
<location filename="../../src/user_widget.cpp" line="102"/>
<source><p>The identicon is a visual help calculated from the user name and the master password.</p><p>Remember it and if it is the same when logging in, you most likely didn't make a typo.</p><p>This avoids the need to explicitly store the hash of the password (password check option below).</p><p>It can be disabled under Edit -> Settings.</p></source>
<translation><p>Ikona identyfikacyjna jest graficzną pomocą generowaną z nazwy użytkownika i hasła.</p><p>Zapamiętaj ją. Jeśli jest taka sama przy logowaniu, najprawdopodobniej hasło zostało wpisane poprawnie.</p><p>To daje możliwość uniknięcia przechowywania hashu hasła (opcja sprawdzania hasła poniżej).</p><p>Ikona identyfikacyjna może zostać wyłączona w menu Edycja -> Ustawienia.</p></translation>
</message>
</context>
</TS>
|
bkueng/qMasterPassword
|
data/translations/translation_pl.ts
|
TypeScript
|
gpl-3.0
| 31,528
|
/*!
* \file gnss_sdr_valve_test.cc
* \brief This file implements unit tests for the valve custom block.
* \author Carlos Aviles, 2010. carlos.avilesr(at)googlemail.com
* Carles Fernandez-Prades, 2012. cfernandez(at)cttc.es
*
*
* -------------------------------------------------------------------------
*
* Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors)
*
* GNSS-SDR is a software defined Global Navigation
* Satellite Systems receiver
*
* This file is part of GNSS-SDR.
*
* GNSS-SDR 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.
*
* GNSS-SDR 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 GNSS-SDR. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#include <gnuradio/top_block.h>
#include <gnuradio/analog/sig_source_waveform.h>
#include <gnuradio/analog/sig_source_f.h>
#include <gnuradio/blocks/null_sink.h>
#include <gnuradio/msg_queue.h>
#include "gnss_sdr_valve.h"
TEST(ValveTest, CheckEventSentAfter100Samples)
{
gr::msg_queue::sptr queue = gr::msg_queue::make(0);
gr::top_block_sptr top_block = gr::make_top_block("gnss_sdr_valve_test");
gr::analog::sig_source_f::sptr source = gr::analog::sig_source_f::make(100, gr::analog::GR_CONST_WAVE, 100, 1, 0);
boost::shared_ptr<gr::block> valve = gnss_sdr_make_valve(sizeof(float), 100, queue);
gr::blocks::null_sink::sptr sink = gr::blocks::null_sink::make(sizeof(float));
unsigned int expected0 = 0;
EXPECT_EQ(expected0, queue->count());
top_block->connect(source, 0, valve, 0);
top_block->connect(valve, 0, sink, 0);
top_block->run();
top_block->stop();
unsigned int expected1 = 1;
EXPECT_EQ(expected1, queue->count());
}
|
luis-esteve/gnss-sdr
|
src/tests/unit-tests/signal-processing-blocks/sources/gnss_sdr_valve_test.cc
|
C++
|
gpl-3.0
| 2,235
|
package net.kleditzsch.App.RedisAdmin.View.Dialog.Zset;
/**
* Created by oliver on 02.08.15.
*/
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import net.kleditzsch.Ui.UiDialogHelper;
public class ZSetEditScoreDialogController {
protected Double score = 0.0;
protected boolean isSaveButtonClicked = false;
@FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
@FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
@FXML // fx:id="cancleButton"
private Button cancleButton; // Value injected by FXMLLoader
@FXML // fx:id="scoreField"
private TextField scoreField; // Value injected by FXMLLoader
@FXML
void clickCancleButton(ActionEvent event) {
Stage stage = (Stage) cancleButton.getScene().getWindow();
stage.close();
}
@FXML
void clickSaveButton(ActionEvent event) {
String scoreValue = scoreField.getText();
Double score = 0.0;
try {
score = Double.parseDouble(scoreValue);
} catch (NumberFormatException ex) {
scoreField.setStyle("-fx-border-color: red; -fx-border-width: 1px;");
UiDialogHelper.showErrorDialog("Fehlerhafte Eingaben", null, "Fehlerhafte Eingaben im Formular");
return;
}
//Daten uebernehmen
this.isSaveButtonClicked = true;
this.score = score;
Stage stage = (Stage) cancleButton.getScene().getWindow();
stage.close();
}
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
assert scoreField != null : "fx:id=\"scoreField\" was not injected: check your FXML file 'ZSetEditScoreDialog.fxml'.";
scoreField.textProperty().addListener((observable, oldValue, newValue) -> {
if(newValue == null || newValue.isEmpty()) {
scoreField.setStyle("-fx-border-color: red; -fx-border-width: 1px;");
} else {
try {
Double.parseDouble(newValue);
scoreField.setStyle("-fx-border-width: 0px;");
} catch(NumberFormatException ex) {
scoreField.setStyle("-fx-border-color: red; -fx-border-width: 1px;");
}
}
});
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
scoreField.setText(Double.toString(this.score));
}
public boolean isSaveButtonClicked() {
return isSaveButtonClicked;
}
}
|
agent4788/Redis_Admin
|
src/main/java/net/kleditzsch/App/RedisAdmin/View/Dialog/Zset/ZSetEditScoreDialogController.java
|
Java
|
gpl-3.0
| 2,818
|
<html lang="en">
<head>
<title>Keys - GNU Emacs Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="GNU Emacs Manual">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="User-Input.html#User-Input" title="User Input">
<link rel="next" href="Commands.html#Commands" title="Commands">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This is the `GNU Emacs Manual',
updated for Emacs version 24.3.50.
Copyright (C) 1985--1987, 1993--2013 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License,
Version 1.3 or any later version published by the Free Software
Foundation; with the Invariant Sections being ``The GNU
Manifesto,'' ``Distribution'' and ``GNU GENERAL PUBLIC LICENSE,''
with the Front-Cover texts being ``A GNU Manual,'' and with the
Back-Cover Texts as in (a) below. A copy of the license is
included in the section entitled ``GNU Free Documentation
License.''
(a) The FSF's Back-Cover Text is: ``You have the freedom to copy
and modify this GNU manual. Buying copies from the FSF supports
it in developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="stylesheet" href="aquamacs.css" type="text/css" /></head>
<body>
<div class="node">
<a name="Keys"></a>
<p>
Next: <a rel="next" accesskey="n" href="Commands.html#Commands">Commands</a>,
Previous: <a rel="previous" accesskey="p" href="User-Input.html#User-Input">User Input</a>,
Up: <a rel="up" accesskey="u" href="index.html#Top">Top</a>
<hr>
</div>
<h2 class="chapter">3 Keys</h2>
<p>Some Emacs commands are invoked by just one input event; for
example, <kbd>C-f</kbd> moves forward one character in the buffer. Other
commands take two or more input events to invoke, such as <kbd>C-x
C-f</kbd> and <kbd>C-x 4 C-f</kbd>.
<p><a name="index-key-39"></a><a name="index-key-sequence-40"></a><a name="index-complete-key-41"></a><a name="index-prefix-key-42"></a> A <dfn>key sequence</dfn>, or <dfn>key</dfn> for short, is a sequence of one
or more input events that is meaningful as a unit. If a key sequence
invokes a command, we call it a <dfn>complete key</dfn>; for example,
<kbd>C-f</kbd>, <kbd>C-x C-f</kbd> and <kbd>C-x 4 C-f</kbd> are all complete keys.
If a key sequence isn't long enough to invoke a command, we call it a
<dfn>prefix key</dfn>; from the preceding example, we see that <kbd>C-x</kbd>
and <kbd>C-x 4</kbd> are prefix keys. Every key sequence is either a
complete key or a prefix key.
<p>A prefix key combines with the following input event to make a
longer key sequence. For example, <kbd>C-x</kbd> is a prefix key, so
typing <kbd>C-x</kbd> alone does not invoke a command; instead, Emacs waits
for further input (if you pause for longer than a second, it echoes
the <kbd>C-x</kbd> key to prompt for that input; see <a href="Echo-Area.html#Echo-Area">Echo Area</a>).
<kbd>C-x</kbd> combines with the next input event to make a two-event key
sequence, which could itself be a prefix key (such as <kbd>C-x 4</kbd>), or
a complete key (such as <kbd>C-x C-f</kbd>). There is no limit to the
length of key sequences, but in practice they are seldom longer than
three or four input events.
<p>You can't add input events onto a complete key. For example,
because <kbd>C-f</kbd> is a complete key, the two-event sequence <kbd>C-f
C-k</kbd> is two key sequences, not one.
<p>By default, the prefix keys in Emacs are <kbd>C-c</kbd>, <kbd>C-h</kbd>,
<kbd>C-x</kbd>, <kbd>C-x <RET></kbd>, <kbd>C-x @</kbd>, <kbd>C-x a</kbd>, <kbd>C-x
n</kbd>, <kbd>C-x r</kbd>, <kbd>C-x v</kbd>, <kbd>C-x 4</kbd>, <kbd>C-x 5</kbd>, <kbd>C-x 6</kbd>,
<ESC>, <kbd>M-g</kbd>, and <kbd>M-o</kbd>. (<F1> and <F2> are
aliases for <kbd>C-h</kbd> and <kbd>C-x 6</kbd>.) This list is not cast in
stone; if you customize Emacs, you can make new prefix keys. You
could even eliminate some of the standard ones, though this is not
recommended for most users; for example, if you remove the prefix
definition of <kbd>C-x 4</kbd>, then <kbd>C-x 4 C-f</kbd> becomes an invalid key
sequence. See <a href="Key-Bindings.html#Key-Bindings">Key Bindings</a>.
<p>Typing the help character (<kbd>C-h</kbd> or <F1>) after a prefix key
displays a list of the commands starting with that prefix. The sole
exception to this rule is <ESC>: <kbd><ESC> C-h</kbd> is equivalent
to <kbd>C-M-h</kbd>, which does something else entirely. You can, however,
use <F1> to display a list of commands starting with <ESC>.
</body></html>
|
xfq/aquamacs-emacs
|
aquamacs/doc/Aquamacs Help/Emacs Manual/Keys.html
|
HTML
|
gpl-3.0
| 4,888
|
/*
* Copyright (c) 2012 Dennis Mackay-Fisher
*
* This file is part of PV Scheduler
*
* PV Scheduler is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 3 or later
* as published by the Free Software Foundation.
*
* PV Scheduler 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 PV Scheduler.
* If not, see <http://www.gnu.org/licenses/>.
*/
// Was PVReading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GenericConnector;
using MackayFisher.Utilities;
using PVSettings;
using PVBCInterfaces;
namespace DeviceDataRecorders
{
public abstract class ReadingBase<TDeviceParams> where TDeviceParams : class
{
private bool InDatabaseInternal = false;
public bool InDatabase // true when this value already exists in DB
{
get { return InDatabaseInternal; }
set { InDatabaseInternal = value; }
}
private bool UpdatePendingInternal = false;
public bool UpdatePending // true when database writes are outstanding
{
get { return UpdatePendingInternal; }
protected set
{
UpdatePendingInternal = value;
if (value)
foreach(IDevicePeriodGeneric period in RegisteredPeriods)
period.DayIsDirty();
}
}
public bool AttributeRestoreMode { get; protected set; } // true when loading values from persistent store
protected TDeviceParams DeviceParams;
private List<IDevicePeriodGeneric> RegisteredPeriods;
public ReadingBase() // must call InitialiseBase after this
{
DeviceParams = null;
RegisteredPeriods = new List<IDevicePeriodGeneric>();
}
public void RegisterPeriodInvolvement(IDevicePeriodGeneric period)
{
foreach (IDevicePeriodGeneric rPeriod in RegisteredPeriods)
if (rPeriod == period)
return;
RegisteredPeriods.Add(period);
}
public void DeregisterPeriodInvolvement(IDevicePeriodGeneric period)
{
for (int i = 0; i < RegisteredPeriods.Count; )
{
if (RegisteredPeriods[i] == period)
RegisteredPeriods.RemoveAt(i);
else
i++;
}
}
public static int GetIntervalNo(TimeSpan intervalTime, int intervalSeconds, bool isEndTime = true)
{
Decimal seconds = Math.Round((Decimal)(intervalTime.TotalSeconds), 3); // round to nearest millisecond
int res = (int)Math.Truncate(seconds / intervalSeconds);
if (!isEndTime)
return res;
Decimal rem = seconds % intervalSeconds;
if (rem == 0)
{
if (res > 0)
res--;
}
else
{
int maxRes = (24 * 60 * 60) / intervalSeconds;
if (res >= maxRes)
res--;
}
return res;
}
protected void InitialiseBase(DateTime readingEnd, uint feature, TimeSpan duration, bool readFromDb, TDeviceParams deviceParams)
{
AttributeRestoreMode = readFromDb;
ReadingEndInternal = readingEnd;
FeatureInternal = feature;
Duration = duration;
InDatabase = readFromDb;
UpdatePending = !readFromDb;
DeviceParams = deviceParams;
}
protected void InitialiseBase(DateTime readingEnd, uint feature, DateTime readingStart, bool readFromDb, TDeviceParams deviceParams)
{
AttributeRestoreMode = readFromDb;
ReadingEndInternal = readingEnd;
FeatureInternal = feature;
ReadingStartInternal = readingStart;
DurationInternal = readingEnd - readingStart; ;
InDatabase = readFromDb;
UpdatePending = !readFromDb;
DeviceParams = deviceParams;
}
protected uint FeatureInternal = 0;
public virtual uint Feature
{
get
{
return FeatureInternal;
}
}
protected DateTime ReadingStartInternal = DateTime.Now;
public virtual DateTime ReadingStart
{
get
{
return ReadingStartInternal;
}
}
protected DateTime ReadingEndInternal = DateTime.Now;
public virtual DateTime ReadingEnd
{
get
{
return ReadingEndInternal;
}
}
protected TimeSpan DurationInternal = TimeSpan.Zero;
public virtual TimeSpan Duration
{
get
{
return DurationInternal;
}
set
{
DurationInternal = value;
DurationChanged();
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public virtual double GetModeratedSeconds(int precision)
{
return Math.Round(DurationInternal.TotalSeconds, precision);
}
protected virtual void DurationChanged()
{
ReadingStartInternal = ReadingEndInternal - DurationInternal;
}
public virtual void SetRestoreComplete()
{
AttributeRestoreMode = false;
}
}
public class EnergyParams : IDeviceParams
{
public PVSettings.DeviceType DeviceType { get; set; }
public int QueryInterval { get; set; }
public int DatabaseInterval { get; set; }
public float CalibrationFactor { get; set; }
public EnergyParams()
{
CalibrationFactor = 1.0F;
DeviceType = PVSettings.DeviceType.Unknown;
QueryInterval = 6;
DatabaseInterval = 60;
}
}
public class EnergyReading : ReadingBase<EnergyParams>, IComparable<EnergyReading>, IDeviceReading<EnergyReading, EnergyReading, EnergyParams>, IDeviceHistory
{
public const int EnergyPrecision = 5;
public EnergyReading(DateTime readingEnd, uint feature, TimeSpan duration, EnergyParams deviceParams)
: base()
{
Initialise(readingEnd, feature, duration, false, deviceParams);
}
public EnergyReading(DateTime readingEnd, uint feature, TimeSpan duration, bool readFromDb, EnergyParams deviceParams)
: base()
{
Initialise(readingEnd, feature, duration, readFromDb, deviceParams);
}
public EnergyReading() // Must call Initialise after this
{
}
public void Initialise(DateTime readingEnd, uint feature, TimeSpan duration, bool readFromDb, EnergyParams deviceParams)
{
InitialiseBase(readingEnd, feature, duration, readFromDb, deviceParams);
AveragePower = null;
UseInternalCalibration = false;
EnergyCalibrationFactor = DeviceParams.CalibrationFactor;
}
public void Initialise(DateTime readingEnd, uint feature, DateTime readingStart, bool readFromDb, EnergyParams deviceParams)
{
InitialiseBase(readingEnd, feature, readingStart, readFromDb, deviceParams);
AveragePower = null;
UseInternalCalibration = false;
EnergyCalibrationFactor = DeviceParams.CalibrationFactor;
}
private float EnergyCalibrationFactorInternal = 1.0F;
public float EnergyCalibrationFactor
{
get { return EnergyCalibrationFactorInternal; }
set
{
EnergyCalibrationFactorInternal = value;
if (value != 1.0F)
{
UseInternalCalibration = true;
Calibrate();
}
else UseInternalCalibration = false;
}
}
public bool UseInternalCalibration { get; private set; }
protected override void DurationChanged()
{
if (EnergyDeltaInternal.HasValue)
AveragePower = (int)((EnergyDeltaInternal.Value * 1000.0 * DurationInternal.TotalSeconds) / 60.0);
else
AveragePower = null;
}
// Comparer allows readings to be sorted
public static int Compare(EnergyReading x, EnergyReading y)
{
if (x == null)
if (y == null)
return 0; // both null
else
return -1; // x is null y is not null
else if (y == null)
return 1; // y is null x is not null
if (x.ReadingEndInternal > y.ReadingEndInternal)
return 1;
else if (x.ReadingEndInternal < y.ReadingEndInternal)
return -1;
return 0; // equal
}
public Int32 CompareTo(EnergyReading other)
{
if (ReadingEnd < other.ReadingEnd)
return -1;
else if (ReadingEnd > other.ReadingEnd)
return 1;
else return 0;
}
public bool IsSameReading(EnergyReading other)
{
return (this == other);
}
public Double TotalReadingDelta
{
get
{
return EnergyDelta +
(CalibrationDelta.HasValue ? CalibrationDelta.Value : 0.0) +
(HistEnergyDelta.HasValue ? HistEnergyDelta.Value : 0.0);
}
}
public Double? CalibrateableReadingDelta
{
get
{
if (!EnergyDeltaInternal.HasValue && !HistEnergyDelta.HasValue)
return null;
return EnergyDelta +
(HistEnergyDelta.HasValue ? HistEnergyDelta.Value : 0.0);
}
}
private float? VoltsInternal = null;
public float? Volts
{
get
{
return VoltsInternal;
}
set
{
VoltsInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private float? AmpsInternal = null;
public float? Amps
{
get
{
return AmpsInternal;
}
set
{
AmpsInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private float? FrequencyInternal = null;
public float? Frequency
{
get
{
return FrequencyInternal;
}
set
{
FrequencyInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private int? PowerInternal = null;
public int? Power
{
get
{
if (PowerInternal.HasValue)
return PowerInternal;
else
return AveragePower;
}
set
{
PowerInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public int? AveragePower { get; private set; }
private bool EnergyDeltaCalculatedInternal = true;
public bool EnergyDeltaCalculated
{
get { return EnergyDeltaCalculatedInternal; }
set
{
EnergyDeltaCalculatedInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private Double? EnergyDeltaInternal = null;
public virtual Double EnergyDelta
{
get
{
return EnergyDeltaInternal.HasValue ? EnergyDeltaInternal.Value : 0.0; ;
}
set
{
EnergyDeltaInternal = value;
if (EnergyDeltaInternal.HasValue)
AveragePower = (int)((EnergyDeltaInternal.Value * 1000.0 * DurationInternal.TotalSeconds) / 60.0);
else
AveragePower = null;
if (!AttributeRestoreMode)
{
if (UseInternalCalibration)
Calibrate();
UpdatePending = true;
}
}
}
public void ResetEnergyDelta()
{
EnergyDeltaInternal = null;
if (!AttributeRestoreMode)
{
if (UseInternalCalibration)
Calibrate();
UpdatePending = true;
}
}
private Double? CalibrationDeltaInternal = null;
public Double? CalibrationDelta
{
get
{
return CalibrationDeltaInternal;
}
set
{
bool change = false;
if (value.HasValue && CalibrationDeltaInternal.HasValue)
{
if (CalibrationDeltaInternal.Value != Math.Round(value.Value, 3))
change = true;
}
else
change = value.HasValue != CalibrationDeltaInternal.HasValue;
if (change)
{
CalibrationDeltaInternal = value;
UpdatePending = true;
}
}
}
private void Calibrate()
{
if (!UseInternalCalibration)
return;
Double? newCalc = CalibrateableReadingDelta;
if (newCalc.HasValue)
newCalc = newCalc.Value * EnergyCalibrationFactorInternal - newCalc.Value;
else
newCalc = null;
if (newCalc != CalibrationDeltaInternal)
{
CalibrationDelta = newCalc;
}
}
private Double? HistEnergyDeltaInternal = null;
public Double? HistEnergyDelta
{
get
{
return HistEnergyDeltaInternal;
}
set
{
HistEnergyDeltaInternal = value;
if (!AttributeRestoreMode)
{
if (UseInternalCalibration)
Calibrate();
UpdatePending = true;
}
}
}
private Double? EnergyTotalInternal = null;
public Double? EnergyTotal
{
get
{
return EnergyTotalInternal;
}
set
{
EnergyTotalInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private Double? EnergyTodayInternal = null;
public Double? EnergyToday
{
get
{
return EnergyTodayInternal;
}
set
{
EnergyTodayInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private Int32? ModeInternal = null;
public Int32? Mode
{
get
{
return ModeInternal;
}
set
{
ModeInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
private Int64? ErrorCodeInternal = null;
public Int64? ErrorCode
{
get
{
return ErrorCodeInternal;
}
set
{
ErrorCodeInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public virtual int? MinPower
{
get
{
return MinPowerInternal;
}
set
{
MinPowerInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public virtual int? MaxPower
{
get
{
return MaxPowerInternal;
}
set
{
MaxPowerInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public virtual Double? Temperature
{
get
{
return TemperatureInternal;
}
set
{
TemperatureInternal = value;
if (!AttributeRestoreMode) UpdatePending = true;
}
}
public void ClearHistory()
{
HistEnergyDeltaInternal = null;
}
public EnergyReading FillSmallGap(DateTime outputTime, TimeSpan duration, bool isNext)
{
EnergyReading newRec = Clone(outputTime, duration);
if (EnergyDeltaCalculated)
{
if (isNext)
{
// new EnergyDelta is taken from this reading
EnergyDelta -= newRec.EnergyDelta;
// must reduce new EnergyToday by this EnergyDelta
if (newRec.EnergyToday.HasValue)
newRec.EnergyToday -= EnergyDelta;
// must reduce new EnergyTotal by this EnergyDelta
if (newRec.EnergyTotal.HasValue)
newRec.EnergyTotal -= EnergyDelta;
}
else
{
// must increase new EnergyToday by new EnergyDelta
if (newRec.EnergyToday.HasValue)
newRec.EnergyToday += newRec.EnergyDelta;
// must increase new EnergyTotal by this EnergyDelta
if (newRec.EnergyTotal.HasValue)
newRec.EnergyTotal += newRec.EnergyDelta;
}
}
return newRec;
}
public void CalcFromPrevious(EnergyReading prevReading)
{
if (EnergyDeltaCalculated)
if (prevReading == null)
{
if (EnergyTodayInternal.HasValue)
EnergyDelta = EnergyTodayInternal.Value;
else
EnergyDelta = 0.0;
}
else if (prevReading.EnergyToday.HasValue && EnergyTodayInternal.HasValue)
EnergyDelta = EnergyTodayInternal.Value - prevReading.EnergyToday.Value;
else if (prevReading.EnergyTotal.HasValue && EnergyTotalInternal.HasValue)
EnergyDelta = EnergyTotalInternal.Value - prevReading.EnergyTotal.Value;
}
public void HistoryAdjust_Average(EnergyReading actualTotal, EnergyReading histRecord)
{
Double prorataEnergy = histRecord.EnergyDelta -
(actualTotal.EnergyDelta
+ (actualTotal.HistEnergyDeltaInternal.HasValue ? actualTotal.HistEnergyDeltaInternal.Value : 0.0));
double prorataSeconds = histRecord.Duration.TotalSeconds;
double actualSeconds = actualTotal.GetModeratedSeconds(3);
if (prorataSeconds != actualSeconds)
throw new Exception("EnergyReading.HistoryAdjust_Average - prorataSeconds != acualTotal.Seconds - outputTime: " + ReadingEnd +
" - prorataSeconds: " + prorataSeconds + " - actualTotal.Seconds: " + actualSeconds);
Double adjust = (prorataEnergy * Duration.TotalSeconds) / prorataSeconds;
if (Math.Round(adjust, EnergyPrecision - 2) != 0.0) // damp out adjustment oscilliations
if (HistEnergyDelta.HasValue)
HistEnergyDelta += adjust;
else
HistEnergyDelta = adjust;
}
public void HistoryAdjust_Prorata(EnergyReading actualTotal, EnergyReading histRecord)
{
double thisEnergyDelta = CalibrateableReadingDelta.HasValue ? CalibrateableReadingDelta.Value : 0.0;
if (thisEnergyDelta <= 0.0)
return;
Double prorataEnergy = histRecord.EnergyDelta -
(actualTotal.EnergyDelta
+ (actualTotal.HistEnergyDeltaInternal.HasValue ? actualTotal.HistEnergyDeltaInternal.Value : 0.0));
double prorataSeconds = histRecord.Duration.TotalSeconds;
double scaleFactor = prorataEnergy / thisEnergyDelta;
double actualSeconds = actualTotal.GetModeratedSeconds(3);
if (prorataSeconds != actualSeconds)
throw new Exception("EnergyReading.HistoryAdjust_Prorata - prorataSeconds != acualTotal.Seconds - outputTime: " + ReadingEnd +
" - prorataSeconds: " + prorataSeconds + " - actualTotal.Seconds: " + actualSeconds);
Double adjust = thisEnergyDelta * scaleFactor;
if (Math.Round(adjust, EnergyPrecision - 2) != 0.0) // damp out adjustment oscilliations
if (HistEnergyDelta.HasValue)
HistEnergyDelta += adjust;
else
HistEnergyDelta = adjust;
}
public int Compare(EnergyReading other, int? precision = null)
{
int thisPrecision = (precision.HasValue ? precision.Value : EnergyPrecision) - 2;
double otherEnergy = Math.Round(other.CalibrateableReadingDelta.HasValue ? other.CalibrateableReadingDelta.Value : 0.0, thisPrecision);
double thisEnergy = Math.Round(CalibrateableReadingDelta.HasValue ? CalibrateableReadingDelta.Value : 0.0, thisPrecision);
if (otherEnergy == thisEnergy)
return 0;
if (otherEnergy < thisEnergy)
return -1;
else
return 1;
}
public EnergyReading Clone(DateTime outputTime, TimeSpan duration)
{
EnergyReading newRec = new EnergyReading(outputTime, Feature, duration, true, DeviceParams);
Double factor = (Double)duration.TotalSeconds / DurationInternal.TotalSeconds;
newRec.EnergyTotalInternal = EnergyTotalInternal;
newRec.EnergyTodayInternal = EnergyTodayInternal;
newRec.EnergyDeltaCalculated = EnergyDeltaCalculated;
newRec.EnergyDeltaInternal = EnergyDeltaInternal * factor;
if (CalibrationDeltaInternal.HasValue)
newRec.CalibrationDeltaInternal = CalibrationDeltaInternal * factor;
if (HistEnergyDeltaInternal.HasValue)
newRec.HistEnergyDeltaInternal = HistEnergyDeltaInternal * factor;
newRec.Power = PowerInternal;
newRec.ModeInternal = ModeInternal;
newRec.ErrorCodeInternal = ErrorCodeInternal;
newRec.PowerInternal = PowerInternal;
newRec.VoltsInternal = VoltsInternal;
newRec.AmpsInternal = AmpsInternal;
newRec.FrequencyInternal = FrequencyInternal;
newRec.TemperatureInternal = TemperatureInternal;
newRec.MinPowerInternal = MinPowerInternal;
newRec.MaxPowerInternal = MaxPowerInternal;
// if time is not changed, database presence has not changed
if (outputTime == ReadingEnd)
newRec.InDatabase = InDatabase;
else
newRec.InDatabase = false;
newRec.UpdatePending = true;
newRec.SetRestoreComplete();
Calibrate();
return newRec;
}
public void AccumulateReading(EnergyReading reading)
{
Duration += reading.DurationInternal;
if (reading.Amps.HasValue)
Amps = reading.Amps.Value;
if (reading.Power.HasValue)
Power = reading.Power.Value;
if (reading.MinPower.HasValue)
{
if (MinPower.HasValue)
MinPower = Math.Min(MinPower.Value, reading.MinPower.Value);
else
MinPower = reading.MinPower;
}
if (reading.MaxPower.HasValue)
{
if (MaxPower.HasValue)
MaxPower = Math.Max(MaxPower.Value, reading.MaxPower.Value);
else
MaxPower = reading.MaxPower;
}
if (reading.Volts.HasValue)
Volts = reading.Volts.Value;
if (reading.ErrorCode.HasValue)
ErrorCode = reading.ErrorCode.Value;
if (reading.Mode.HasValue)
Mode = reading.Mode.Value;
if (reading.Temperature.HasValue)
Temperature = reading.Temperature.Value;
if (reading.EnergyToday.HasValue)
EnergyToday = reading.EnergyToday.Value;
if (reading.EnergyTotal.HasValue)
EnergyTotal = reading.EnergyTotal.Value;
EnergyDelta += reading.EnergyDelta;
if (reading.CalibrationDelta.HasValue)
if (CalibrationDelta.HasValue)
CalibrationDelta += reading.CalibrationDelta.Value;
else
CalibrationDelta = reading.CalibrationDelta.Value;
if (reading.HistEnergyDelta.HasValue)
if (HistEnergyDelta.HasValue)
HistEnergyDelta += reading.HistEnergyDelta.Value;
else
HistEnergyDelta = reading.HistEnergyDelta.Value;
EnergyDeltaCalculated = reading.EnergyDeltaCalculated;
if (reading.EnergyToday.HasValue)
if (EnergyToday.HasValue)
EnergyToday = Math.Max(EnergyToday.Value, reading.EnergyToday.Value);
else
EnergyToday = reading.EnergyToday;
if (reading.EnergyTotal.HasValue)
if (EnergyTotal.HasValue)
EnergyTotal = Math.Max(EnergyTotal.Value, reading.EnergyTotal.Value);
else
EnergyTotal = reading.EnergyTotal;
}
//public Double KWHTotalFirst = 0.0;
public Double KWHTotal = 0.0;
private int? MinPowerInternal = null;
private int? MaxPowerInternal = null;
private Double? TemperatureInternal = null;
#region Persistance
private static String InsertDeviceReading_AC =
"INSERT INTO devicereading_energy " +
"( ReadingEnd, Device_Id, Feature, ReadingStart, EnergyTotal, EnergyToday, EnergyDelta, EnergyDeltaCalculated, " +
"CalcEnergyDelta, HistEnergyDelta, Mode, ErrorCode, Power, Volts, " +
"Amps, Frequency, Temperature, " +
"MinPower," +
"MaxPower) " +
"VALUES " +
"(@ReadingEnd, @Device_Id, @Feature, @ReadingStart, @EnergyTotal, @EnergyToday, @EnergyDelta, @EnergyDeltaCalculated, " +
"@CalcEnergyDelta, @HistEnergyDelta, @Mode, @ErrorCode, @Power, @Volts, " +
"@Amps, @Frequency, @Temperature, " +
"@MinPower, " +
"@MaxPower) ";
private static String UpdateDeviceReading_AC =
"UPDATE devicereading_energy set " +
"ReadingStart = @ReadingStart, " +
"EnergyTotal = @EnergyTotal, " +
"EnergyToday = @EnergyToday, " +
"EnergyDelta = @EnergyDelta, " +
"EnergyDeltaCalculated = @EnergyDeltaCalculated, " +
"CalcEnergyDelta = @CalcEnergyDelta, " +
"HistEnergyDelta = @HistEnergyDelta, " +
"Mode = @Mode, " +
"ErrorCode = @ErrorCode, " +
"Power = @Power, " +
"Volts = @Volts, " +
"Amps = @Amps, " +
"Frequency = @Frequency, " +
"Temperature = @Temperature, " +
"MinPower = @MinPower, " +
"MaxPower = @MaxPower " +
"WHERE " +
"ReadingEnd = @ReadingEnd " +
"AND Device_Id = @Device_Id " +
"AND Feature = @Feature ";
private static String DeleteDeviceReading_AC =
"DELETE from devicereading_energy " +
"WHERE " +
"ReadingEnd = @ReadingEnd " +
"AND Device_Id = @Device_Id " +
"AND Feature = @Feature ";
private void SetParametersId(GenCommand cmd, int deviceId)
{
string stage = "Id";
try
{
cmd.AddParameterWithValue("@Device_Id", deviceId);
cmd.AddParameterWithValue("@Feature", (int)FeatureInternal);
cmd.AddParameterWithValue("@ReadingEnd", ReadingEndInternal);
}
catch (Exception e)
{
throw new Exception("SetParametersId - Stage: " + stage + " - Exception: " + e.Message);
}
}
private void SetParameters(GenCommand cmd, int deviceId)
{
string stage = "Device_Id";
try
{
SetParametersId(cmd, deviceId);
stage = "ReadingStart";
cmd.AddParameterWithValue("@ReadingStart", ReadingStartInternal);
stage = "EnergyTotal";
cmd.AddRoundedParameterWithValue("@EnergyTotal", EnergyTotalInternal, EnergyPrecision);
stage = "EnergyToday";
cmd.AddRoundedParameterWithValue("@EnergyToday", EnergyTodayInternal, EnergyPrecision);
stage = "EnergyDelta";
cmd.AddRoundedParameterWithValue("@EnergyDelta", EnergyDeltaInternal, EnergyPrecision);
stage = "EnergyDeltaCalculated";
cmd.AddBooleanParameterWithValue("@EnergyDeltaCalculated", EnergyDeltaCalculatedInternal);
stage = "CalcEnergyDelta";
// use rounding - 6 dp more than adequate - SQLite stores all values as text, too many digits wastes DB space
cmd.AddRoundedParameterWithValue("@CalcEnergyDelta", CalibrationDeltaInternal, EnergyPrecision);
stage = "HistEnergyDelta";
cmd.AddRoundedParameterWithValue("@HistEnergyDelta", HistEnergyDeltaInternal, EnergyPrecision);
stage = "Mode";
cmd.AddParameterWithValue("@Mode", ModeInternal);
stage = "ErrorCode";
if (ErrorCodeInternal.HasValue)
cmd.AddParameterWithValue("@ErrorCode", (long)ErrorCodeInternal.Value);
else
cmd.AddParameterWithValue("@ErrorCode", null);
stage = "Power";
cmd.AddParameterWithValue("@Power", PowerInternal);
stage = "Volts";
cmd.AddRoundedParameterWithValue("@Volts", VoltsInternal, 2);
stage = "Amps";
cmd.AddRoundedParameterWithValue("@Amps", AmpsInternal, 2);
stage = "Frequency";
cmd.AddRoundedParameterWithValue("@Frequency", FrequencyInternal, 1);
stage = "Temp";
cmd.AddRoundedParameterWithValue("@Temperature", TemperatureInternal, 2);
stage = "MinPower";
cmd.AddParameterWithValue("@MinPower", MinPowerInternal);
stage = "MaxPower";
cmd.AddParameterWithValue("@MaxPower", MaxPowerInternal);
}
catch (Exception e)
{
throw new Exception("SetParameters - Stage: " + stage + " - Exception: " + e.Message);
}
}
private bool PersistReadingSub(bool forceAlternate, GenConnection existingCon, int deviceId)
{
string stage = "Init";
GenConnection con = null;
bool haveMutex = false;
bool externalCon = (existingCon != null);
bool useInsert = !InDatabase;
if (forceAlternate)
useInsert = !useInsert;
try
{
GlobalSettings.SystemServices.GetDatabaseMutex();
haveMutex = true;
if (externalCon)
con = existingCon;
else
con = GlobalSettings.TheDB.NewConnection();
GenCommand cmd;
if (useInsert)
cmd = new GenCommand(InsertDeviceReading_AC, con);
else
cmd = new GenCommand(UpdateDeviceReading_AC, con);
SetParameters(cmd, deviceId);
stage = "Execute";
cmd.ExecuteNonQuery();
if (GlobalSettings.SystemServices.LogTrace)
GlobalSettings.LogMessage("EnergyReading.PersistReadingSub - ", (useInsert ? "Insert" : "Update") + " - EnergyTotal: " + EnergyTotal +
" - EnergyToday: " + EnergyToday +
" - Power: " + Power +
" - Calc Adjust: " + CalibrationDelta +
" - Hist Adjust: " + HistEnergyDelta, LogEntryType.Trace);
UpdatePending = false;
InDatabase = true;
return true;
}
catch (Exception e)
{
GlobalSettings.LogMessage("EnergyReading.PersistReadingSub - ", (useInsert ? "Insert" : "Update") + " - Stage: " + stage + " - Exception: " + e.Message, LogEntryType.ErrorMessage);
if (!forceAlternate)
PersistReadingSub(true, con, deviceId);
}
finally
{
if (existingCon == null && con != null)
{
con.Close();
con.Dispose();
}
if (haveMutex)
GlobalSettings.SystemServices.ReleaseDatabaseMutex();
}
return false;
}
public bool DeleteReading(GenConnection existingCon, int deviceId)
{
if (!InDatabase)
return false;
string stage = "Init";
GenConnection con = null;
bool haveMutex = false;
bool externalCon = (existingCon != null);
try
{
GlobalSettings.SystemServices.GetDatabaseMutex();
haveMutex = true;
if (externalCon)
con = existingCon;
else
con = GlobalSettings.TheDB.NewConnection();
GenCommand cmd = new GenCommand(DeleteDeviceReading_AC, con);
SetParametersId(cmd, deviceId);
stage = "Execute";
cmd.ExecuteNonQuery();
if (GlobalSettings.SystemServices.LogTrace)
GlobalSettings.LogMessage("EnergyReading.DeleteReading", "EnergyTotal: " + EnergyTotal +
" - EnergyToday: " + EnergyToday +
" - Power: " + Power +
" - Calc Adjust: " + CalibrationDelta +
" - Hist Adjust: " + HistEnergyDelta, LogEntryType.Trace);
UpdatePending = false;
InDatabase = false;
return true;
}
catch (Exception e)
{
GlobalSettings.LogMessage("EnergyReading.DeleteReadingSub", "Stage: " + stage + " - Exception: " + e.Message, LogEntryType.ErrorMessage);
}
finally
{
if (existingCon == null && con != null)
{
con.Close();
con.Dispose();
}
if (haveMutex)
GlobalSettings.SystemServices.ReleaseDatabaseMutex();
}
return false;
}
public bool PersistReading(GenConnection con, int deviceId)
{
return PersistReadingSub(false, con, deviceId);
}
#endregion Persistance
}
}
|
tectronics/pvbeancounter
|
DeviceDataRecorders/EnergyReading.cs
|
C#
|
gpl-3.0
| 38,253
|
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO 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.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
/**
*
*/
package org.cgiar.ccafs.marlo.data.dao;
import org.cgiar.ccafs.marlo.data.model.CenterLeader;
import java.util.List;
/**
* Modified by @author nmatovu last on Oct 10, 2016
*/
public interface ICenterLeaderDAO {
/**
* This method removes a specific CenterLeader value from the database.
*
* @param researchLeaderId is the CenterLeader identifier.
* @return true if the CenterLeader was successfully deleted, false otherwise.
*/
public void deleteResearchLeader(long researchLeaderId);
/**
* This method validate if the CenterLeader identify with the given id exists in the system.
*
* @param researchLeaderId is a CenterLeader identifier.
* @return true if the crpProgramLeader exists, false otherwise.
*/
public boolean existResearchLeader(long researchLeaderId);
/**
* This method gets a research leader record with the given id or identifier.
*
* @param researchLeaderId the identifier or id used to located the record.
* @return the research leader record.
*/
public CenterLeader find(long researchLeaderId);
/**
* This method gets all the research leaders records that are active in the system
*
* @return a list of research leader records.
*/
public List<CenterLeader> findAll();
/**
* This method saves the information of the given research leader
*
* @param researchLeader - is the research leader object with the new information to be added/updated.
* @return a number greater than 0 representing the new ID assigned by the database, 0 if the research leader was
* updated
* or -1 is some error occurred.
*/
public CenterLeader save(CenterLeader researchLeader);
}
|
CCAFS/MARLO
|
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ICenterLeaderDAO.java
|
Java
|
gpl-3.0
| 2,644
|
#include <QHeaderView>
#include <QJsonObject>
#include <QJsonArray>
#include "ParameterEditor.hpp"
ParameterEditor::ParameterEditor(
QWidget* _parent
) :
QTableWidget(0, 2, _parent)
{
setSelectionBehavior(QAbstractItemView::SelectRows);
horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
setShowGrid(true);
verticalHeader()->hide();
QStringList labels;
labels << tr("Parameter") << tr("Value");
setHorizontalHeaderLabels(labels);
int row = rowCount();
insertRow(row);
setItem(row, 0, new QTableWidgetItem("WorkingDirectory"));
setItem(row, 1, new QTableWidgetItem("\"~/Porcupipelines/ThisStudy\""));
insertRow(rowCount());
connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(checkForEmptyRows(QTableWidgetItem*)));
}
void ParameterEditor::saveToJson(
QJsonObject& o_json
)
{
QJsonArray parameters;
for(int i = 0; i < rowCount(); ++i)
{
QJsonObject keyValuePair;
if(item(i, 0) && item(i, 1))
{
keyValuePair["key"] = item(i, 0)->text();
keyValuePair["value"] = item(i, 1)->text();
parameters.append(keyValuePair);
}
}
o_json["parameters"] = parameters;
}
void ParameterEditor::loadFromJson(
const QJsonObject& _json
)
{
clear();
QStringList labels;
labels << tr("Parameter") << tr("Value");
setHorizontalHeaderLabels(labels);
int row = 0;
foreach (QJsonValue keyValuePair, _json["parameters"].toArray())
{
QJsonObject keyValueObject = keyValuePair.toObject();
setItem(row, 0, new QTableWidgetItem(keyValueObject[ "key" ].toString()));
setItem(row, 1, new QTableWidgetItem(keyValueObject["value"].toString()));
row++;
}
}
QMap<QString, QString> ParameterEditor::getParameters(
)
{
QMap<QString, QString> parameters;
for(int i = 0; i < rowCount() - 1; ++i)
{
QString key = item(i, 0) ? item(i, 0)->text() : "";
QString value = item(i, 1) ? item(i, 1)->text() : "";
if(!key.isEmpty() && !value.isEmpty())
{
parameters[key] = value;
}
}
return parameters;
}
void ParameterEditor::checkForEmptyRows(
QTableWidgetItem* _item
)
{
if(_item->row() == rowCount() - 1 && !_item->text().isEmpty())
{
insertRow(rowCount());
return;
}
// check if entire row is empty
if(_item->row() != rowCount() - 1)
{
for(int j = 0; j < columnCount(); ++j)
{
if(!item(_item->row(), j) || item(_item->row(), j)->text().isEmpty())
{
if(j == columnCount() - 1)
{
removeRow(_item->row());
}
}
else
{
return;
}
}
}
}
|
TimVanMourik/Porcupine
|
src/ParameterEditor/ParameterEditor.cpp
|
C++
|
gpl-3.0
| 2,908
|
/*
* Copyright 2012 Devoteam http://www.devoteam.com
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
*
* This file is part of Multi-Protocol Test Suite (MTS).
*
* Multi-Protocol Test Suite (MTS) 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.
*
* Multi-Protocol Test Suite (MTS) 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 Multi-Protocol Test Suite (MTS).
* If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.devoteam.srit.xmlloader.rtsp;
import com.devoteam.srit.xmlloader.core.protocol.Channel;
import com.devoteam.srit.xmlloader.core.protocol.Msg;
import com.devoteam.srit.xmlloader.core.protocol.StackFactory;
import com.devoteam.srit.xmlloader.tcp.ChannelTcp;
import com.devoteam.srit.xmlloader.udp.ChannelUdp;
public class ChannelRtsp extends Channel
{
private Channel channel = null;
private String transport = null;
// --- constructure --- //
public ChannelRtsp(String name, String aLocalHost, String aLocalPort, String aRemoteHost, String aRemotePort, String aProtocol, String aTransport) throws Exception {
super(name, aLocalHost, aLocalPort, aRemoteHost, aRemotePort, aProtocol);
transport = aTransport;
if(transport.equals(StackFactory.PROTOCOL_TCP))
{
channel = new ChannelTcp(name, aLocalHost, aLocalPort, aRemoteHost, aRemotePort, aProtocol);
}
else
{
channel = new ChannelUdp(name, aLocalHost, aLocalPort, aRemoteHost, aRemotePort, aProtocol, false);
}
}
// --- basic methods --- //
public boolean open() throws Exception {
return channel.open();
}
/** Send a Msg to Channel */
public boolean sendMessage(Msg msg) throws Exception{
if (null == channel)
throw new Exception("Channel is null, has one channel been opened ?");
if (msg.getChannel() == null)
msg.setChannel(this);
channel.sendMessage((MsgRtsp) msg);
return true;
}
public boolean close(){
try {
channel.close();
} catch (Exception e) {
// nothing to do
}
channel = null;
return true;
}
/** Get the transport protocol of this message */
public String getTransport()
{
return transport;
}
}
|
yongs2/mts-project
|
mts/src/main/java/com/devoteam/srit/xmlloader/rtsp/ChannelRtsp.java
|
Java
|
gpl-3.0
| 2,753
|
# Copyright (C) 2013 Andreas Damgaard Pedersen
#
# 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/>.
"""
This file demonstrates writing tests using the unittest module.
These will pass when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""Test that 1 + 1 always equals 2."""
self.assertEqual(1 + 1, 2)
|
Damgaard/account-deleter
|
deleter/tests.py
|
Python
|
gpl-3.0
| 1,050
|
# description
<br>
this is a Dockerfile to make a image where you can run docker commands against the registry of the docker engine of the host
<br>
start with the following command:
<br>
docker run -it -v /var/run/docker.sock:/var/run/docker.sock ubuntu:latest sh -c "apt-get update ; apt-get install docker.io -y ; bash"
|
tschoots/noteoj
|
basic_image/README.md
|
Markdown
|
gpl-3.0
| 328
|
/*
* This file is part of Magenta Engine
*
* Copyright (C) 2018 BlackPhrase
*
* Magenta Engine 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.
*
* Magenta Engine 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 Magenta Engine. If not, see <http://www.gnu.org/licenses/>.
*/
/// @file
#include "WinApplication.hpp"
CWinApplication::CWinApplication(const char *cmdline)
{
msCmdLine[0] = '\0';
for(int i = 0; i < strlen(cmdline); ++i)
strcat(msCmdLine, cmdline);
};
CWinApplication::~CWinApplication() = default;
bool CWinApplication::PostInit()
{
return true;
};
|
projectmagenta/magenta
|
mgt/launcher/win/WinApplication.cpp
|
C++
|
gpl-3.0
| 1,017
|
/***************************************************************************
* The FreeMedForms project is a set of free, open source medical *
* applications. *
* (C) 2008-2016 by Eric MAEKER, MD (France) <eric.maeker@gmail.com> *
* All rights reserved. *
* *
* The FreeAccount plugins are free, open source FreeMedForms' plugins. *
* (C) 2010-2011 by Pierre-Marie Desombre, MD <pm.desombre@medsyn.fr> *
* and Eric Maeker, MD <eric.maeker@gmail.com> *
* All rights reserved. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 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 (COPYING.FREEMEDFORMS file). *
* If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
/***************************************************************************
* Main Developers: Pierre-Marie DESOMBRE <pm.desombre@medsyn.fr>, *
* Eric MAEKER, <eric.maeker@gmail.com> *
* Contributors: *
* NAME <MAIL@ADDRESS.COM> *
***************************************************************************/
#ifndef MOVEMENTSIO_H
#define MOVEMENTSIO_H
#include <accountplugin/account_exporter.h>
#include <QStandardItemModel>
#include <QHash>
namespace AccountDB {
class MovementModel;
}
class ACCOUNT_EXPORT MovementsIODb : public QObject
{
Q_OBJECT
enum Icons
{
ICON_NOT_PREF = 0,
ICON_PREF
};
public:
MovementsIODb(QObject *parent);
~MovementsIODb();
AccountDB::MovementModel *getModelMovements(QString &year);
QStandardItemModel *getMovementsComboBoxModel(QObject *parent);
QStringList getYearComboBoxModel();
QStandardItemModel *getBankComboBoxModel(QObject * parent);
bool insertIntoMovements(QHash<int,QVariant> &hashValues);
bool deleteMovement(int row, const QString & year);
bool validMovement(int row);
int getAvailableMovementId(QString & movementsComboBoxText);
int getTypeOfMovement(QString & movementsComboBoxText);
int getBankId(QString & bankComboBoxText);
QString getBankNameFromId(int id);
QString getUserUid();
QHash<QString,QString> hashChildrenAndParentsAvailableMovements();
bool containsFixAsset(int & row);
private:
QStringList listOfParents();
bool debitOrCreditInBankBalance(const QString & bank, double & value);
AccountDB::MovementModel *m_modelMovements;
QString m_user_uid;
};
#endif
|
maternite/freemedforms
|
plugins/accountplugin/movements/movementsio.h
|
C
|
gpl-3.0
| 3,705
|
#ifndef BOSSBURSTTANK_H_
#define BOSSBURSTTANK_H_
#include "BurstTank.h"
class BossBurstTank : public EnemyTank {
public:
BossBurstTank (Path* p = NULL)
: EnemyTank(BOSS_BCIRCLE_R, new TankAI(new AimPolicy(), p?(MovementPolicy*)new PathPolicy():(MovementPolicy*)new SmartPolicy())) {
setLives(3);
setFirePolicy(new BurstFirePolicy(Difficulty::getInstance()->getEnemiesFireInterval()/2, IN_BURST_INTERVAL, NUM_BURST));
if (p) setPath(p);
}
eTankType getTankType () const { return BOSS_BURST; }
double getInitialFiringDelay () const { return Difficulty::getInstance()->getBossFiringDelay(); }
bool bounce (Entity* e, const Vector2& colPoint) {
return shieldBounce(e, colPoint);
}
Rocket* createRocket(Tank* owner, const Vector2& pos, const Vector2& dir) {
return new Rocket(owner, pos, dir, Difficulty::getInstance()->getEnemiesBurstRocketSpeed(), BOUNCE);
}
};
#endif /* BOSSBURSTTANK_H_ */
|
julienr/zoob
|
project/jni/logic/enemies/BossBurstTank.h
|
C
|
gpl-3.0
| 968
|
/**
* $Id: editor_plugin_src.js,v 1.1 2012/04/05 12:12:25 simoneAdm Exp $
*
* @author Moxiecode
* @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved.
*/
(function() {
var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode;
tinymce.create('tinymce.plugins.TabFocusPlugin', {
init : function(ed, url) {
function tabCancel(ed, e) {
if (e.keyCode === 9)
return Event.cancel(e);
};
function tabHandler(ed, e) {
var x, i, f, el, v;
function find(d) {
f = DOM.getParent(ed.id, 'form');
el = f.elements;
if (f) {
each(el, function(e, i) {
if (e.id == ed.id) {
x = i;
return false;
}
});
if (d > 0) {
for (i = x + 1; i < el.length; i++) {
if (el[i].type != 'hidden')
return el[i];
}
} else {
for (i = x - 1; i >= 0; i--) {
if (el[i].type != 'hidden')
return el[i];
}
}
}
return null;
};
if (e.keyCode === 9) {
v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next')));
if (v.length == 1) {
v[1] = v[0];
v[0] = ':prev';
}
// Find element to focus
if (e.shiftKey) {
if (v[0] == ':prev')
el = find(-1);
else
el = DOM.get(v[0]);
} else {
if (v[1] == ':next')
el = find(1);
else
el = DOM.get(v[1]);
}
if (el) {
if (ed = tinymce.EditorManager.get(el.id || el.name))
ed.focus();
else
window.setTimeout(function() {window.focus();el.focus();}, 10);
return Event.cancel(e);
}
}
};
ed.onKeyUp.add(tabCancel);
if (tinymce.isGecko) {
ed.onKeyPress.add(tabHandler);
ed.onKeyDown.add(tabCancel);
} else
ed.onKeyDown.add(tabHandler);
ed.onInit.add(function() {
each(DOM.select('a:first,a:last', ed.getContainer()), function(n) {
Event.add(n, 'focus', function() {ed.focus();});
});
});
},
getInfo : function() {
return {
longname : 'Tabfocus',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin);
})();
|
xdamsorg/xDams-core
|
src/main/webapp/resources/xd-js/tiny_mce/plugins/tabfocus/editor_plugin_src.js
|
JavaScript
|
gpl-3.0
| 2,461
|
/*********************************************************************
CombLayer : MCNP(X) Input builder
* File: commonBeamInc/GratingUnit.h
*
* Copyright (c) 2004-2018 by Stuart Ansell
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************************/
#ifndef xraySystem_GratingUnit_h
#define xraySystem_GratingUnit_h
class Simulation;
namespace xraySystem
{
class GrateHolder;
/*!
\class GratingUnit
\author S. Ansell
\version 1.0
\date September 2018
\brief Paired Mono-crystal mirror constant exit gap
*/
class GratingUnit :
public attachSystem::ContainedComp,
public attachSystem::FixedRotate,
public attachSystem::ExternalCut,
public attachSystem::CellMap,
public attachSystem::SurfMap
{
private:
double HArm; ///< Rotation arm [flat]
double PArm; ///< rotation arm [vertical]
double zLift; ///< Size of beam lift
double mirrorTheta; ///< Mirror angle
double mWidth; ///< Mirror width
double mThick; ///< Mirror thick
double mLength; ///< Mirror length
double grateTheta; ///< Theta angle for grating
int grateIndex; ///< Offset position of grating
std::array<std::shared_ptr<GrateHolder>,3> grateArray;
double mainGap; ///< Void gap between bars
double mainBarCut; ///< Gap to allow beam
double mainBarXLen; ///< X length of bars (to side support)
double mainBarDepth; ///< Depth Z direction
double mainBarYWidth; ///< Bar extent in beam direction
double slidePlateZGap; ///< lift from the mirror surface
double slidePlateThick; ///< slide bar
double slidePlateWidth; ///< slide bar extra width
double slidePlateLength; ///< slide bar extra length
int mirrorMat; ///< Mirror xstal
int mainMat; ///< Main metal
int slideMat; ///< slide material
void populate(const FuncDataBase&);
void createUnitVector(const attachSystem::FixedComp&,
const long int);
void createSurfaces();
void createObjects(Simulation&);
void createLinks();
public:
GratingUnit(const std::string&);
GratingUnit(const GratingUnit&);
GratingUnit& operator=(const GratingUnit&);
virtual ~GratingUnit();
void createAll(Simulation&,
const attachSystem::FixedComp&,
const long int);
};
}
#endif
|
SAnsell/CombLayer
|
Model/MaxIV/commonBeamInc/GratingUnit.h
|
C
|
gpl-3.0
| 3,054
|
<?php
#error_reporting(E_ALL);
#ini_set('display_errors', true);
/*
Projekt: datenlandkarten
Autor: meisterluk
Datum: 11.02.06
Version: beta
Lizenz: LGPL v3.0
datamaps -- visualize your geo-based statistic data
Copyright (C) 2011 Lukas Prokop, Robert Harm, et al.
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/>.
*/
$root = './';
require_once('global.php');
require_once('lib/lib.php');
$n = new Notifications();
$f = new FileManager($location_creation, $location_raw_data,
$location_pattern_svgs, $n);
$g = new Geo($geo_hierarchy, $f);
$ui = new UserInterface($g, $n);
// special feature: show svg filenames
if ($_GET && $_GET['mode'] == 'show_svg_filenames')
{
header('Content-type: text/plain; charset=utf-8');
$vp = new VisPath();
$vis_path = $g->next($vp);
while ($vis_path !== NULL)
{
$filename = $g->get_filename($vp);
echo $filename."\n";
$vis_path = $g->next($vp);
}
exit;
}
if ($_POST)
{
$_POST = striptease($_POST);
$success = $ui->from_webinterface
($_POST, $color_gradients, $color_allocation);
if ($_GET['debug'] == true)
{
debug_ui($ui);
exit;
}
if ($success)
{
include 'select.php';
exit;
}
}
// Defaultvalues
$defaults = $ui->get_attributes();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="de-DE"
xmlns:og='http://opengraphprotocol.org/schema/'>
<head profile="http://gmpg.org/xfn/11">
<title>Datenlandkarte erstellen » datamaps.eu</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="Hier können Sie selbst datamaps erstellen. Gleichzeitig werden, falls Sie diese Option aktiviert lassen, die Rohdaten der Visualisierung gespeichert und" />
<meta name="keywords" content="Bezirke, Kärnten, Alle, Ebenen, Daten, Bundesländer" />
<meta name="robots" content="index, follow" />
<link rel="canonical" href="http://www.datamaps.eu/erstellen/" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<link rel="stylesheet" href="http://www.datamaps.eu/wp-content/themes/datamaps/style.css" type="text/css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" href="http://www.datamaps.eu/wp-content/themes/datamaps/style.ie6.css" type="text/css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" href="http://www.datamaps.eu/wp-content/themes/datamaps/style.ie7.css" type="text/css" media="screen" /><![endif]-->
<link rel="pingback" href="http://www.datamaps.eu/xmlrpc.php" />
<link rel="alternate" type="application/rss+xml" title="datamaps.eu » Feed" href="http://www.datamaps.eu/feed/" />
<link rel="alternate" type="application/rss+xml" title="datamaps.eu » Kommentar Feed" href="http://www.datamaps.eu/comments/feed/" />
<script type='text/javascript' src='http://www.datamaps.eu/wp-includes/js/swfobject.js?ver=2.2'></script>
<script type='text/javascript' src='http://www.datamaps.eu/wp-includes/js/jquery/jquery.js?ver=1.4.2'></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.datamaps.eu/xmlrpc.php?rsd" />
<link rel='index' title='datamaps.eu' href='http://www.datamaps.eu/' />
<link rel='next' title='Galerie' href='http://www.datamaps.eu/galerie/' />
<!--Facebook Like Button OpenGraph Settings Start-->
<meta property="og:site_name" content="datamaps.eu"/>
<meta property="og:title" content="Datenlandkarte erstellen"/>
<meta property="og:description" content="Hier können Sie selbst Datenlandkarten erstellen"/>
<meta property="og:url" content="http://www.datamaps.eu/erstellen/"/>
<meta property="fb:admins" content="1039929046" />
<meta property="fb:app_id" content="192140977480316" />
<meta property="og:image" content="http://www.datamaps.eu/wp-content/uploads/opengraph.png" />
<meta property="og:type" content="article" />
<!--Facebook Like Button OpenGraph Settings End-->
<link rel="shorturl" href="http://datenlandkarte.at/gs8" />
<script type="text/javascript" src="http://www.datamaps.eu/wp-content/themes/datamaps/script.js"></script>
<script type="text/javascript">
<!--
/*
Javascript App
--------------
1. Fills up <div class="data_*"> for #format and #vis selection.
2. Creates a cache for <div class="data_*"> to not lose the
previous (before changing of #vis) data.
*/
var toggle = true; // toggle for advanced options
var _cache = { };
var old_vis = [];
jQuery(document).ready(function () {
// when format is updated, hide/show elements and write to cache
function update_data()
{
format = get_format();
path = selected2vis();
write_cache();
if (path === undefined)
return false;
jQuery('.data_manual, .data_list, .data_json, .data_kvalloc').hide();
jQuery('.data_' + format).show();
// do not request, if you have it in cache
if (_cache[format + ":" + path])
{
read_cache();
return true;
} else {
jQuery.get('api.php', {'method' : format + '_form',
'vis_path' : path, 'indent' : 12}, write_form);
return true;
}
}
// write message to form as specified by #format
function write_form(msg)
{
error = (msg == '0' || msg == '1');
if (error)
{
jQuery('#error > ul')
.append($('<li>Konnte Geodaten nicht anfragen</li>'));
}
switch (get_format())
{
case 'manual':
if (error)
jQuery('.data_manual').text('');
else
jQuery('.data_manual').html(msg);
break;
case 'list':
if (error) {
jQuery('.data_list').hide();
} else {
jQuery('.data_list').show();
jQuery('#list').text(msg);
}
break;
case 'json':
if (error) {
jQuery('.data_json').hide();
} else {
jQuery('.data_json').show();
jQuery('#json').text(msg);
}
break;
case 'kvalloc':
if (error) {
jQuery('.data_kvalloc').hide();
} else {
jQuery('.data_kvalloc').show();
jQuery('#kvalloc').text(msg);
}
break;
}
read_cache();
}
// get vis_path from #vis selection
function selected2vis()
{
return jQuery('#vis input:checked').attr('id');
}
// read data from cache
function read_cache()
{
vis = selected2vis();
format = get_format();
key = (format + ':' + vis);
// cache is empty at key
if (_cache[key] == undefined)
return;
switch (format)
{
case 'manual':
counter = 0;
for (value in _cache[key])
{
$('#manual_' + counter).val(_cache[key][value]);
counter++;
}
break;
case 'list': case 'json': case 'kvalloc':
jQuery('#' + format).val(_cache[key]);
break;
}
}
// write data to cache
function write_cache()
{
vis = old_vis[0];
format = get_format();
key = (format + ':' + vis);
if (format == undefined || vis == undefined)
return;
switch (format)
{
case 'manual':
_cache[key] = [];
var content_exists = false;
jQuery('*[name=manual[]]').each(function (index) {
value = jQuery(this).val();
_cache[key].push(value);
if (value != "")
content_exists = true;
});
if (!content_exists)
delete _cache[key];
break;
case 'list': case 'json': case 'kvalloc':
if (jQuery('#' + format).val())
{
_cache[key] = '';
_cache[key] = jQuery('#' + format).val();
}
break;
}
}
// push current element to old_vis stack
function push_vis() {
old_vis.push(jQuery('#vis input:checked').attr('id'));
// old_vis always has length 2: old_vis = [previous, current]
if (old_vis.length > 2)
old_vis = old_vis.slice(1);
}
// get format selection
function get_format()
{
return jQuery('#format option:selected').val();
}
jQuery('input, #format').click(function () {
push_vis();
update_data();
});
// Initialization
update_data();
jQuery('.arrow').text('[aufklappen]');
jQuery('#advanced').hide();
jQuery('#advanced_options').click(function () {
jQuery('#advanced').toggle();
if (toggle)
jQuery('.arrow').text('[einklappen]');
else
jQuery('.arrow').text('[aufklappen]');
toggle = (toggle) ? false : true;
});
});
-->
</script>
<style type="text/css">
<!--
.subselect {
margin-left: 10%;
}
.arrow {
font-size: 70%;
}
table {
margin: auto;
width: 100%;
}
#vis {
max-height: 200px;
overflow-y: scroll;
}
input, select {
min-width: 50px;
width: 50%;
}
#vis input, select {
width: 50px;
margin: 0px;
}
textarea {
min-width: 300px;
width: 60%;
}
.big {
font-size: 130%;
padding: 5px;
}
.two_symbols {
width: 30px;
}
.indent {
margin-left: 5% !important;
}
#beta {
margin: 10px;
background-color: #FE9;
padding: 10px;
font-style: italic;
}
.data_list, .data_json, .data_kvalloc {
display: none;
}
-->
</style>
</head>
<body class="page page-id-2 page-template page-template-default">
<div id="art-page-background-middle-texture">
<div id="art-main">
<div class="art-sheet">
<div class="art-sheet-tl"></div>
<div class="art-sheet-tr"></div>
<div class="art-sheet-bl"></div>
<div class="art-sheet-br"></div>
<div class="art-sheet-tc"></div>
<div class="art-sheet-bc"></div>
<div class="art-sheet-cl"></div>
<div class="art-sheet-cr"></div>
<div class="art-sheet-cc"></div>
<div class="art-sheet-body">
<div class="art-header">
<div class="art-header-center">
<div class="art-header-png"></div>
<div class="art-header-jpeg"></div>
</div>
<div class="art-headerobject"></div>
<div class="art-logo">
<h1 id="name-text" class="art-logo-name"><a href="http://www.datamaps.eu/">DataMaps.eu</a></h1>
<h2 id="slogan-text" class="art-logo-text">map your data</h2>
</div>
</div>
<div class="art-nav">
<div class="art-nav-l"></div>
<div class="art-nav-r"></div>
<ul class="art-menu">
<li><a href="http://www.datamaps.eu" title="Startseite"><span class="l"> </span><span class="r"> </span><span class="t">Startseite</span></a>
</li>
<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li class="active"><a class="active" href="http://www.datamaps.eu/erstellen/" title="Datenlandkarte erstellen"><span class="l"> </span><span class="r"> </span><span class="t">Datenlandkarte erstellen</span></a>
</li>
<!--<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li><a href="http://www.datamaps.eu/rohdaten/" title="Rohdaten"><span class="l"> </span><span class="r"> </span><span class="t">Rohdaten</span></a>
</li>-->
<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li><a href="http://www.datamaps.eu/vorlagen/" title="Vorlagen"><span class="l"> </span><span class="r"> </span><span class="t">Vorlagen</span></a>
</li>
<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li><a href="http://www.datamaps.eu/galerie/" title="Galerie"><span class="l"> </span><span class="r"> </span><span class="t">Galerie</span></a>
</li>
<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li><a href="http://www.datamaps.eu/blog/" title="Blog"><span class="l"> </span><span class="r"> </span><span class="t">Blog</span></a>
</li>
<li class="art-menu-li-separator"><span class="art-menu-separator"> </span></li>
<li><a href="http://www.datamaps.eu/impressum/" title="Impressum"><span class="l"> </span><span class="r"> </span><span class="t">Impressum</span></a>
</li>
</ul>
</div>
<div class="art-content-layout">
<div class="art-content-layout-row">
<div class="art-layout-cell art-content">
<div class="art-post post-2 page type-page hentry" id="post-2">
<div class="art-post-body">
<div class="art-post-inner art-article">
<form action="index.php" method="post">
<h2 class="art-postheader">Datenlandkarte erstellen
<div style="float:right;">
<!-- Begin ConveyThis Button -->
<script type="text/javascript">
var conveythis_src = 'de';
</script>
<div class="conveythis">
<a class="conveythis_drop" title="Translate" href="http://www.translation-services-usa.com/"><span class="conveythis_button_1">automatic translation</span></a>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://s1.conveythis.com/e2/_v_3/javascript/e3.js"></script>
<!-- End ConveyThis Button -->
</div>
</h2>
<div class="art-postcontent">
<noscript>
<p>
Dieses Formular arbeitet mit Javascript. Bitte aktivieren
Sie Javascript in ihrem Browser, wenn möglich.
</p>
</noscript>
<?php if (time() < 1309784400 ) { ?>
<p id="beta">
<strong>Hinweis:</strong> <br />
Dieses Werkzeug wurde neu entwickelt und befindet sich nun in der Testphase.<br/>
Bitte Fehler und Wünsche ins
<a href="http://datenlandkarten.uservoice.com/forums/100819-feedback">Feedback-Forum</a>
schreiben oder per E-Mail an <a href="mailto:info@datamaps.eu">info@datamaps.eu</a>
senden. <br /> EntwicklerInnen können den Code auch auf
<a href="https://github.com/meisterluk/datenlandkarte" target="_blank">github</a>
forken und Pull-Requests für Bugfixes erstellen.
</p>
<?php } ?>
<div id="error">
<ul>
<?php
$errors = $n->filter(2);
if (is_array($errors))
foreach ($errors as $err)
{
echo str_repeat(' ', 14).'<li><span style="color:#F00;'.
'font-weight:bold" class="'._et($err[1]).'">Error:</span> '.
_et($err[0]).'</li>'."\n";
}
?>
</ul>
</div>
<!--
<div id="cc_header">
<div id="cc_header_img">
<img src="img/cc.png" alt="Creative Commons" width="64" />
</div>
<div id="cc_header_text">
<p>
<input type="checkbox" name="shareit" id="check_share" checked="<?=_et($defaults['visibility']); ?>" />
<strong><label for="check_share">
Ja, ich möchte meine Daten öffentlich teilen.
</label></strong><br /><br />
Ich stimme zu, dass ich die Daten zuverlässig gesammelt oder
aus einer verlässlichen Quelle gewonnen habe. Ebenso
bestätige ich im zweiteren Fall das Recht zu haben, die
gewonnenen Daten unter der <a href="http://creativecommons.org/licenses/by-sa/3.0/at/">Creative
Commons Namensnennung-Weitergabe unter gleichen
Bedingungen 3.0 Österreich Lizenz</a> weitergeben zu dürfen.
Ich bin damit einverstanden, dass die eingegebenen Daten
langfristig im <a href="/rohdaten">Rohdatenverzeichnis</a> gespeichert werden und der Öffentlichkeit
zugänglich bleiben.<br />
Andernfalls werden die eingegebenen Daten genau für 1 Tag
gespeichert, sind jedoch nicht öffentlich zugänglich.
</p>
</div>
</div>
-->
<table cellpadding="6" id="main_form">
<tr>
<td style="width:45%;">
<strong>Titel:</strong> <br />
<small>Überschrift der Graphik</small>
</td>
<td>
<input type="text" maxlength="50" tabindex="1" name="title" value="<?=_et($defaults['title']); ?>" />
</td>
</tr>
<tr>
<td>
<strong>Untertitel:</strong> <br />
<small>Untertext des Titels</small>
</td>
<td style="width:45%;">
<input type="text" maxlength="120" tabindex="2" name="subtitle" value="<?=_et($defaults['subtitle']); ?>"/>
</td>
</tr>
<tr>
<td>
<strong>Farbrichtung:</strong> <br />
<a href="./theme/farbpalette.png" target="_blank"><small>Beispiele anzeigen</small></a>
</td>
<td>
<select name="grad" style="width:150px">
<?php
foreach ($color_allocation as $key => $c)
{
if ($key === $defaults['grad'])
$ch = ' selected="selected"';
else
$ch = '';
?>
<option value="<?=_et($key); ?>"<?=_et($ch)?>><?=_et($c); ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>
<label for="visibility">
<strong>
Öffentliches Teilen der Daten:
</strong> <br />
<small>
Ich lizensiere die Daten unter
<a href="http://creativecommons.org/licenses/by-sa/3.0/at/">CC By-SA</a>
und stelle sie öffentlich im <a href="http://www.datamaps.eu/rohdaten/" target="_blank">Rohdatenverzeichnis</a> zur Verfügung
</small>
</label>
</td>
<td>
<?php if ($defaults['visibility']) { ?>
<input style="min-width:0px;width:0px;" type="checkbox" name="visibility" id="visibility" checked="checked" />
<?php } else { ?>
<input style="min-width:0px;width:0px;" type="checkbox" name="visibility" id="visibility" />
<?php } ?>
</td>
<tr>
<td colspan="2">
<strong>Welche Vorlage soll verwendet werden?</strong><br/>
<small>
<a href="./vorlagen">Vorlagen, an denen wir arbeiten</a>
</small>
</td>
<tr>
<td colspan="2">
<div id="vis">
<?php
if ($defaults['vis_path'] === '')
echo $g->build_flat_radio_html(18, $default_vis_path);
else
echo $g->build_flat_radio_html(18, $defaults['vis_path']);
?>
</div>
</td>
</tr>
</table>
<div class="big" id="advanced_options">
Erweiterte Optionen <span class="arrow"></span>
</div>
<div class="indent" id="advanced">
<table cellpadding="6" id="sub_form">
<tr>
<td style="width:45%;">
<strong>Autor:</strong> <br />
<small>Ihre Identität oder ihr Nickname</small>
</td>
<td><input type="text" name="author" value="<?=_et($defaults['author']); ?>" /></td>
</tr>
<tr>
<td>
<strong>Quelle:</strong>
</td>
<td><input type="text" name="source" value="<?=_et($defaults['source']); ?>" /></td>
</tr>
<tr>
<td>
<strong>Anzahl der Farben:</strong>
</td>
<td>
<input type="text" name="colors" maxlength="3" value="<?=_et($defaults['colors']); ?>" /></td>
</td>
</tr>
<tr>
<td>
<strong>Farbpalette:</strong> <br />
<small>Statt der Farbrichtung kann man hier auch manuell
eine Farbpalette angeben.<br />
Trennen Sie die Hexfarben mit einem Komma</small>
</td>
<td>
<input type="text" name="palette" value="<?php
if (is_array($defaults['palette']))
echo _et(implode(',', $defaults['palette']));
else
echo _et($defaults['palette']);
?>" /></td>
</td>
</tr>
<tr>
<td>
<strong>Hebefaktor:</strong> <br />
<small>Jeder Wert wirt mit dem Hebefaktor multipliziert.<br />
zB mit dem Hebefaktor 0.01 lässt sich in Prozente umrechnen</small>
</td>
<td><input type="text" name="fac" value="<?=_et(sprintf("%.2f", $defaults['fac'])); ?>" /></td>
</tr>
<tr>
<td>
<strong>Anzahl der Nachkommastellen (0-3):</strong> <br />
<small>... der Zahlen in der Legende</small>
</td>
<td><input type="text" name="dec" maxlength="1" value="<?=_et($defaults['dec']); ?>" /></td>
</tr>
<tr>
<td>
<strong>Eingabeformat:</strong>
</td>
<td>
<select style="width:100px;" name="format" id="format">
<?php
foreach ($formats as $key => $f)
{
if (array_key_exists('format', $_POST) && $_POST['format'] === $key)
echo str_repeat(' ', 20).'<option value="'.
_et($key).'" selected="selected">'._e($f).'</option>'."\n";
else
echo str_repeat(' ', 20).'<option value="'.
_et($key).'">'._e($f).'</option>'."\n";
}
?>
</select>
</td>
</tr>
</table>
</div>
<div class="big">
Daten
</div>
<p class="indent">
<strong>Notiz.</strong>
fehlende Angabe werden weiß dargestellt
</p>
<p class="data_list data_kvalloc indent">
<strong>Notiz.</strong>
In Trennzeichen darf \n für einen Zeilenumbruch verwendet werden.
<span title="\ wird zu \\ und \\\ wird zu \\\\">
Dafür muss jeder Backslashfolge ein weiterer vorangestellt werden.
</span>
</p>
<div class="data_manual indent">
<table style="width:auto;" cellpadding="6">
<?php
$vp = new VisPath();
$i = 0;
foreach ($g->get($vp) as $key => $value) {
$val = array_key_exists('manual'.($i++), $_POST) ? $_POST['manual'.($i++)] : '';
if (!is_int($key))
continue;
?>
<tr>
<td style="text-align:right;"><?=_e($value['name']); ?>:</td>
<td><input type="text" name="manual[]" id="manual_<?=$key; ?>" value="<?=$val; ?>" /></td>
</tr>
<?php } ?>
</table>
</div>
<div class="data_list indent">
<textarea name="list" id="list" rows="5" cols="50"></textarea>
<p>
Trennzeichen:
<input type="text" class="two_symbols" name="list_delim" value="<?=UserInterface::delimiter_to_html($defaults['list_delim']); ?>" size="3" class="delimiter" />
</p>
</div>
<div class="data_json indent">
<textarea name="json" id="json" rows="5" cols="50"></textarea>
</div>
<div class="data_kvalloc indent">
<textarea name="kvalloc" id="kvalloc" rows="5" cols="50"></textarea> <br />
1. Trennzeichen (zw. Schlüssel-Wert-Paar)
<input type="text" class="two_symbols delimiter" name="kvalloc_delim1" value="<?=UserInterface::delimiter_to_html($defaults['kvalloc_delim1']); ?>" size="3" /> <br />
2. Trennzeichen (zw. Schlüssel und Wert)
<input type="text" class="two_symbols delimiter" name="kvalloc_delim2" value="<?=UserInterface::delimiter_to_html($defaults['kvalloc_delim2']); ?>" size="3" />
</div>
<p>
<input type="submit" id="submit" value="Erstellen" />
</p>
</form>
<div class="cleared"></div>
</div>
</div>
<div class="cleared"></div>
</div>
</div>
<div class="cleared"></div>
<div class="art-footer">
<div class="art-footer-t"></div>
<div class="art-footer-l"></div>
<div class="art-footer-b"></div>
<div class="art-footer-r"></div>
<div class="art-footer-body">
<div class="art-footer-text">
<div style="float:left;">
<a href="http://www.open3.at" target="_blank" title="Webseite open3.at aufrufen">
<img src="http://www.datamaps.eu/wp-content/uploads/open3logo.png" alt="Open3 Logo" width="177" height="33" />
</a>
</div>
<p style="float:right;text-align:right;">
<a href="http://www.opendefinition.org/okd/deutsch/" target="_blank" title="Definition 'Offenes Wissen' auf http://opendefinition.org/ anzeigen">
<img src="http://www.datamaps.eu/wp-content/uploads/badge-od.png" alt="Badge OD" width="80" height="15" />
<img src="http://www.datamaps.eu/wp-content/uploads/badge-ok.png" alt="Badge OK" width="80" height="15" />
<img src="http://www.datamaps.eu/wp-content/uploads/badge-oc.png" alt="Badge OC" width="80" height="15" />
</a>
<br />
<a href="/impressum" style="text-decoration:none;" title="Impressum anzeigen">
Ein Projekt von open3, dem Netzwerk zur Förderung von openSociety, openGovernment und OpenData
</a>
</p>
</div>
<div class="cleared"></div>
</div>
</div>
<div class="cleared"></div>
</div>
</div>
<div class="cleared"></div>
<p class="art-page-footer"></p>
</div>
</div><!--MiddleTextureEnd-->
<div id="wp-footer">
</div>
</body>
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://www.ihrwebprofi.at/piwik/" : "http://www.ihrwebprofi.at/piwik/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 10);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://www.ihrwebprofi.at/piwik/piwik.php?idsite=10" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Tag -->
</html>
|
meisterluk/datenlandkarte
|
index.php
|
PHP
|
gpl-3.0
| 30,292
|
# -*- coding: utf-8 -*-
# Copyright 2012 Antoine Bertin <diaoulael@gmail.com>
#
# This file is part of pyextdirect.
#
# pyextdirect 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.
#
# pyextdirect 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 pyextdirect. If not, see <http://www.gnu.org/licenses/>.
__all__ = ['BASIC', 'LOAD', 'SUBMIT', 'STORE_READ', 'STORE_CUD', 'ConfigurationMeta', 'create_configuration', 'expose']
#: Basic method
BASIC = 0
#: DirectLoad method
LOAD = 1
#: DirectSubmit method
SUBMIT = 2
#: DirectStore read method
STORE_READ = 3
#: DirectStore create-update-destroy methods
STORE_CUD = 4
class ConfigurationMeta(type):
"""Each class created with this metaclass will have its exposed methods registered
A method can be exposed with the :func:`expose` decorator
The registration is done by calling :meth:`~Base.register`
"""
def __init__(cls, name, bases, attrs):
for attrname, attrvalue in attrs.iteritems():
if not getattr(attrvalue, 'exposed', False):
continue
cls.register((cls, attrname), getattr(attrvalue, 'exposed_action') or name, getattr(attrvalue, 'exposed_method') or attrname)
return super(ConfigurationMeta, cls).__init__(name, bases, attrs)
def create_configuration(name='Base'):
"""Create a configuration base class
It is built using :class:`ConfigurationMeta`. Subclassing such a base class
will register exposed methods
.. class:: Base
.. attribute:: configuration
Configuration dict that can be used by a Router or the API
.. classmethod:: register(element, action, method)
Register an element in the :attr:`configuration`
:param element: the element to register
:type element: tuple of (class, method name) or function
:param string action: name of the exposed action that will hold the method
:param string method: name of the exposed method
"""
@classmethod
def register(cls, element, action, method):
if not action in cls.configuration:
cls.configuration[action] = {}
if method in cls.configuration[action]:
raise ValueError('Method %s already defined for action %s' % (method, action))
cls.configuration[action][method] = element
return ConfigurationMeta(name, (object,), {'configuration': {}, 'register': register})
def expose(f=None, base=None, action=None, method=None, kind=BASIC):
"""Decorator to expose a function
.. note::
A module function can be decorated but ``base`` parameter has to be specified
:param f: function to expose
:type f: function or None
:param base: base class that can register the function
:param string action: name of the exposed action that will hold the method
:param string method: name of the exposed method
:param kind: kind of the method
:type kind: :data:`BASIC` or :data:`LOAD` or :data:`SUBMIT`
"""
def expose_f(f):
f.exposed = True
f.exposed_action = action
f.exposed_method = method
f.exposed_kind = kind
return f
def register_f(f):
f = expose_f(f)
base.register(f, action or f.__module__, method or f.__name__)
return f
if f is not None: # @expose case (no parameters)
return expose_f(f)
if base is not None: # module-level function case
return register_f
return expose_f
def merge_configurations(configurations):
"""Merge configurations together and raise error if a conflict is detected
:param configurations: configurations to merge together
:type configurations: list of :attr:`~pyextdirect.configuration.Base.configuration` dicts
:return: merged configurations as a single one
:rtype: dict
"""
configuration = {}
for c in configurations:
for k, v in c.iteritems():
if k in configuration:
raise ValueError('%s already in a previous base configuration' % k)
configuration[k] = v
return configuration
|
Diaoul/pyextdirect
|
pyextdirect/configuration.py
|
Python
|
gpl-3.0
| 4,570
|
#PWN Lab
PWN Lab is a collection of Vagrant scripts and boxes to create security training environments. Getting a running environment is as easy as cloning the repository and running `vagrant up`.
## Environments
* **Training** - The PWN Lab training environment is a collection of VMs to hone your hacking skills, test your tools and perform demos.
* **X11** - This VM has a poorly configured X11 server. This replicates poor configurations I've seen on past engagements.
## Prerequisites
In order to use PWN Lab, you'll need to install the following software packages.
1. [VirtualBox](https://www.virtualbox.org/wiki/Downloads) - VirtualBox is a cross-platform virtualization product.
2. [Vagrant](https://www.vagrantup.com/) - Vagrant is a tool for building virtualized environments.
3. [Ansible](http://www.ansible.com/home) - Ansible is used as a provisioner for Vagrant. It performs post-VM creation tasks such as updating to the latest software release.
4. [Git](https://git-scm.com/) - Git is a distributed version control system.
## Installation
1. Clone the pwn_lab training environment `git clone https://github.com/ztgrace/pwn_lab`
2. Change directory into an environment `cd training`
3. Issue the appropriate vagrant commands to instantiate the environment such as `vagrant up`
4. See additional instructions in each environment's README.md
|
ztgrace/pwn_lab
|
README.md
|
Markdown
|
gpl-3.0
| 1,363
|
class IssuesDecorator < ApplicationCollectionDecorator
delegate :current_page, :per_page, :offset, :total_entries, :total_pages
# see #ApplicationCollectionDecorator::new_link
def new_link
super(h.t(:link_new_issue), h.new_issue_path(context[:project].slug), context[:project])
end
def no_data_glyph_name
'issue-opened'
end
def display_collection
super(false, h.t(:text_no_issues))
end
end
|
nmeylan/RORganize
|
app/decorators/issues_decorator.rb
|
Ruby
|
gpl-3.0
| 422
|
/*****************************************************************************
*
* Copyright (C) 2001 Uppsala University and Ericsson AB.
*
* 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
*
* Authors: Erik Nordstr�, <erik.nordstrom@it.uu.se>
*
*****************************************************************************/
#define NS_PORT
#define OMNETPP
#include <sys/types.h>
#ifdef NS_PORT
#ifndef OMNETPP
#include "ns/aodv-uu.h"
#else
#include "../NA_aodv_uu_omnet.h"
#endif
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <netinet/udp.h>
#include "NA_aodv_socket.h"
#include "NA_timer_queue_aodv.h"
#include "NA_aodv_rreq.h"
#include "NA_aodv_rerr.h"
#include "NA_aodv_rrep.h"
#include "NA_params.h"
#include "NA_aodv_hello.h"
#include "NA_aodv_neighbor.h"
#include "NA_debug_aodv.h"
#include "NA_defs_aodv.h"
#endif /* NS_PORT */
#ifndef NS_PORT
#define SO_RECVBUF_SIZE 256*1024
static char recv_buf[RECV_BUF_SIZE];
static char send_buf[SEND_BUF_SIZE];
extern int wait_on_reboot, hello_qual_threshold, ratelimit;
static void aodv_socket_read(int fd);
/* Seems that some libc (for example ulibc) has a bug in the provided
* CMSG_NXTHDR() routine... redefining it here */
static struct cmsghdr *__cmsg_nxthdr_fix(void *__ctl, size_t __size,
struct cmsghdr *__cmsg)
{
struct cmsghdr *__ptr;
__ptr = (struct cmsghdr *) (((unsigned char *) __cmsg) +
CMSG_ALIGN(__cmsg->cmsg_len));
if ((unsigned long) ((char *) (__ptr + 1) - (char *) __ctl) > __size)
return NULL;
return __ptr;
}
struct cmsghdr *cmsg_nxthdr_fix(struct msghdr *__msg, struct cmsghdr *__cmsg)
{
return __cmsg_nxthdr_fix(__msg->msg_control, __msg->msg_controllen, __cmsg);
}
#endif /* NS_PORT */
void NS_CLASS aodv_socket_init()
{
#ifndef NS_PORT
struct sockaddr_in aodv_addr;
struct ifreq ifr;
int i, retval = 0;
int on = 1;
int tos = IPTOS_LOWDELAY;
int bufsize = SO_RECVBUF_SIZE;
socklen_t optlen = sizeof(bufsize);
/* Create a UDP socket */
if (this_host.nif == 0)
{
fprintf(stderr, "No interfaces configured\n");
exit(-1);
}
/* Open a socket for every AODV enabled interface */
for (i = 0; i < MAX_NR_INTERFACES; i++)
{
if (!DEV_NR(i).enabled)
continue;
/* AODV socket */
DEV_NR(i).sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (DEV_NR(i).sock < 0)
{
perror("");
exit(-1);
}
#ifdef CONFIG_GATEWAY
/* Data packet send socket */
DEV_NR(i).psock = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);
if (DEV_NR(i).psock < 0)
{
perror("");
exit(-1);
}
#endif
/* Bind the socket to the AODV port number */
memset(&aodv_addr, 0, sizeof(aodv_addr));
aodv_addr.sin_family = AF_INET;
aodv_addr.sin_port = htons(AODV_PORT);
aodv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
retval = bind(DEV_NR(i).sock, (struct sockaddr *) &aodv_addr,
sizeof(struct sockaddr));
if (retval < 0)
{
perror("Bind failed ");
exit(-1);
}
if (setsockopt(DEV_NR(i).sock, SOL_SOCKET, SO_BROADCAST,
&on, sizeof(int)) < 0)
{
perror("SO_BROADCAST failed ");
exit(-1);
}
memset(&ifr, 0, sizeof(struct ifreq));
strcpy(ifr.ifr_name, DEV_NR(i).ifname);
if (setsockopt(DEV_NR(i).sock, SOL_SOCKET, SO_BINDTODEVICE,
&ifr, sizeof(ifr)) < 0)
{
fprintf(stderr, "SO_BINDTODEVICE failed for %s", DEV_NR(i).ifname);
perror(" ");
exit(-1);
}
if (setsockopt(DEV_NR(i).sock, SOL_SOCKET, SO_PRIORITY,
&tos, sizeof(int)) < 0)
{
perror("Setsockopt SO_PRIORITY failed ");
exit(-1);
}
if (setsockopt(DEV_NR(i).sock, SOL_IP, IP_RECVTTL,
&on, sizeof(int)) < 0)
{
perror("Setsockopt IP_RECVTTL failed ");
exit(-1);
}
if (setsockopt(DEV_NR(i).sock, SOL_IP, IP_PKTINFO,
&on, sizeof(int)) < 0)
{
perror("Setsockopt IP_PKTINFO failed ");
exit(-1);
}
#ifdef CONFIG_GATEWAY
if (setsockopt(DEV_NR(i).psock, SOL_SOCKET, SO_BINDTODEVICE,
&ifr, sizeof(ifr)) < 0)
{
fprintf(stderr, "SO_BINDTODEVICE failed for %s", DEV_NR(i).ifname);
perror(" ");
exit(-1);
}
bufsize = 4 * 65535;
if (setsockopt(DEV_NR(i).psock, SOL_SOCKET, SO_SNDBUF,
(char *) &bufsize, optlen) < 0)
{
DEBUG(LOG_NOTICE, 0, "Could not set send socket buffer size");
}
if (getsockopt(DEV_NR(i).psock, SOL_SOCKET, SO_SNDBUF,
(char *) &bufsize, &optlen) == 0)
{
alog(LOG_NOTICE, 0, __FUNCTION__,
"RAW send socket buffer size set to %d", bufsize);
}
#endif
/* Set max allowable receive buffer size... */
for (;; bufsize -= 1024)
{
if (setsockopt(DEV_NR(i).sock, SOL_SOCKET, SO_RCVBUF,
(char *) &bufsize, optlen) == 0)
{
alog(LOG_NOTICE, 0, __FUNCTION__,
"Receive buffer size set to %d", bufsize);
break;
}
if (bufsize < RECV_BUF_SIZE)
{
alog(LOG_ERR, 0, __FUNCTION__,
"Could not set receive buffer size");
exit(-1);
}
}
retval = attach_callback_func(DEV_NR(i).sock, aodv_socket_read);
if (retval < 0)
{
perror("register input handler failed ");
exit(-1);
}
}
#endif /* NS_PORT */
num_rreq = 0;
num_rerr = 0;
}
void NS_CLASS aodv_socket_process_packet(AODV_msg * aodv_msg, int len,
struct in_addr src,
struct in_addr dst,
int ttl, unsigned int ifindex)
{
/* If this was a HELLO message... Process as HELLO. */
#ifndef OMNETPP
if ((aodv_msg->type == AODV_RREP && ttl == 1 &&
dst.s_addr == AODV_BROADCAST))
{
hello_process((RREP *) aodv_msg, len, ifindex);
return;
}
#else
if ((aodv_msg->type == AODV_RREP && ttl == 0 && // ttl is decremented for ip layer before send to aodv
dst.s_addr == ManetAddress(IPv4Address(AODV_BROADCAST))))
{
hello_process((RREP *) aodv_msg, len, ifindex);
return;
}
#endif
/* Make sure we add/update neighbors */
neighbor_add(aodv_msg, src, ifindex);
/* Check what type of msg we received and call the corresponding
function to handle the msg... */
switch (aodv_msg->type)
{
case AODV_RREQ:
rreq_process((RREQ *) aodv_msg, len, src, dst, ttl, ifindex);
break;
case AODV_RREP:
DEBUG(LOG_DEBUG, 0, "Received RREP");
rrep_process((RREP *) aodv_msg, len, src, dst, ttl, ifindex);
break;
case AODV_RERR:
DEBUG(LOG_DEBUG, 0, "Received RERR");
rerr_process((RERR *) aodv_msg, len, src, dst);
break;
case AODV_RREP_ACK:
DEBUG(LOG_DEBUG, 0, "Received RREP_ACK");
rrep_ack_process((RREP_ack *) aodv_msg, len, src, dst);
break;
default:
alog(LOG_WARNING, 0, __FUNCTION__,
"Unknown msg type %u rcvd from %s to %s", aodv_msg->type,
ip_to_str(src), ip_to_str(dst));
break;
}
}
#ifdef NS_PORT
#ifndef OMNETPP
void NS_CLASS recvAODVUUPacket(Packet * p)
{
int len, i, ttl = 0;
struct in_addr src, dst;
struct hdr_cmn *ch = HDR_CMN(p);
struct hdr_ip *ih = HDR_IP(p);
hdr_aodvuu *ah = HDR_AODVUU(p);
src.s_addr = ih->saddr();
dst.s_addr = ih->daddr();
len = ch->size() - IP_HDR_LEN;
ttl = ih->ttl();
AODV_msg *aodv_msg = (AODV_msg *) recv_buf;
/* Only handle AODVUU packets */
assert(ch->ptype() == PT_AODVUU);
/* Only process incoming packets */
assert(ch->direction() == hdr_cmn::UP);
/* Copy message to receive buffer */
memcpy(recv_buf, ah, RECV_BUF_SIZE);
/* Deallocate packet, we have the information we need... */
Packet::free(p);
/* Ignore messages generated locally */
for (i = 0; i < MAX_NR_INTERFACES; i++)
if (this_host.devs[i].enabled &&
memcmp(&src, &this_host.devs[i].ipaddr,
sizeof(struct in_addr)) == 0)
return;
aodv_socket_process_packet(aodv_msg, len, src, dst, ttl, NS_IFINDEX);
}
#endif /*no omnet++*/
#else
static void aodv_socket_read(int fd)
{
struct in_addr src, dst;
int i, len, ttl = -1;
AODV_msg *aodv_msg;
struct dev_info *dev;
struct msghdr msgh;
struct cmsghdr *cmsg;
struct iovec iov;
char ctrlbuf[CMSG_SPACE(sizeof(int)) +
CMSG_SPACE(sizeof(struct in_pktinfo))];
struct sockaddr_in src_addr;
iov.iov_base = recv_buf;
iov.iov_len = RECV_BUF_SIZE;
msgh.msg_name = &src_addr;
msgh.msg_namelen = sizeof(src_addr);
msgh.msg_iov = &iov;
msgh.msg_iovlen = 1;
msgh.msg_control = ctrlbuf;
msgh.msg_controllen = sizeof(ctrlbuf);
len = recvmsg(fd, &msgh, 0);
if (len < 0)
{
alog(LOG_WARNING, 0, __FUNCTION__, "receive ERROR len=%d!", len);
return;
}
src.s_addr = src_addr.sin_addr.s_addr;
/* Get the ttl and destination address from the control message */
for (cmsg = CMSG_FIRSTHDR(&msgh); cmsg != NULL;
cmsg = CMSG_NXTHDR_FIX(&msgh, cmsg))
{
if (cmsg->cmsg_level == SOL_IP)
{
switch (cmsg->cmsg_type)
{
case IP_TTL:
ttl = *(CMSG_DATA(cmsg));
break;
case IP_PKTINFO:
dst.s_addr =
((struct in_pktinfo *) CMSG_DATA(cmsg))->ipi_addr.s_addr;
}
}
}
if (ttl < 0)
{
DEBUG(LOG_DEBUG, 0, "No TTL, packet ignored!");
return;
}
/* Ignore messages generated locally */
for (i = 0; i < MAX_NR_INTERFACES; i++)
if (this_host.devs[i].enabled &&
memcmp(&src, &this_host.devs[i].ipaddr,
sizeof(struct in_addr)) == 0)
return;
aodv_msg = (AODV_msg *) recv_buf;
dev = devfromsock(fd);
if (!dev)
{
DEBUG(LOG_ERR, 0, "Could not get device info!\n");
return;
}
aodv_socket_process_packet(aodv_msg, len, src, dst, ttl, dev->ifindex);
}
#endif /* NS_PORT */
void NS_CLASS aodv_socket_send(AODV_msg * aodv_msg, struct in_addr dst,
int len, u_int8_t ttl, struct dev_info *dev,double delay)
{
struct timeval now;
int retval = 0;
/* Rate limit stuff: */
#ifdef OMNETPP
if (ttl<=0)
{
delete aodv_msg;
return;
}
#endif
#ifndef NS_PORT
struct sockaddr_in dst_addr;
if (wait_on_reboot && aodv_msg->type == AODV_RREP)
return;
memset(&dst_addr, 0, sizeof(dst_addr));
dst_addr.sin_family = AF_INET;
dst_addr.sin_addr = dst;
dst_addr.sin_port = htons(AODV_PORT);
/* Set ttl */
if (setsockopt(dev->sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
{
alog(LOG_WARNING, 0, __FUNCTION__, "ERROR setting ttl!");
return;
}
#else
/*
NS_PORT: Sending of AODV_msg messages to other AODV-UU routing agents
by encapsulating them in a Packet.
Note: This method is _only_ for sending AODV packets to other routing
agents, _not_ for forwarding "regular" IP packets!
*/
/* If we are in waiting phase after reboot, don't send any RREPs */
if (wait_on_reboot && aodv_msg->type == AODV_RREP)
{
#ifdef OMNETPP
delete aodv_msg;
#endif
return;
}
#ifndef OMNETPP
/*
NS_PORT: Don't allocate packet until now. Otherwise packet uid
(unique ID) space is unnecessarily exhausted at the beginning of
the simulation, resulting in uid:s starting at values greater than 0.
*/
Packet *p = allocpkt();
struct hdr_cmn *ch = HDR_CMN(p);
struct hdr_ip *ih = HDR_IP(p);
hdr_aodvuu *ah = HDR_AODVUU(p);
// Clear AODVUU part of packet
memset(ah, '\0', ah->size());
// Copy message contents into packet
memcpy(ah, aodv_msg, len);
// Set common header fields
ch->ptype() = PT_AODVUU;
ch->direction() = hdr_cmn::DOWN;
ch->size() = IP_HDR_LEN + len;
ch->iface() = -2;
ch->getBitErrorRate() = 0;
ch->prev_hop_ = (nsaddr_t) dev->ipaddr.s_addr;
// Set IP header fields
ih->saddr() = (nsaddr_t) dev->ipaddr.s_addr;
ih->daddr() = (nsaddr_t) dst.s_addr;
ih->ttl() = ttl;
// Note: Port number for routing agents, not AODV port number!
ih->sport() = RT_PORT;
ih->dport() = RT_PORT;
// Fake success
retval = len;
#endif /*omnet++ */
#endif /* NS_PORT */
/* If rate limiting is enabled, check if we are sending either a
RREQ or a RERR. In that case, drop the outgoing control packet
if the time since last transmit of that type of packet is less
than the allowed RATE LIMIT time... */
if (ratelimit)
{
gettimeofday(&now, NULL);
switch (aodv_msg->type)
{
case AODV_RREQ:
if (num_rreq == (RREQ_RATELIMIT - 1))
{
if (timeval_diff(&now, &rreq_ratel[0]) < 1000)
{
DEBUG(LOG_DEBUG, 0, "RATELIMIT: Dropping RREQ %ld ms",
timeval_diff(&now, &rreq_ratel[0]));
#ifdef OMNETPP
delete aodv_msg;
#else
#ifdef NS_PORT
Packet::free(p);
#endif
#endif
return;
}
else
{
memmove(rreq_ratel, &rreq_ratel[1],
sizeof(struct timeval) * (num_rreq - 1));
memcpy(&rreq_ratel[num_rreq - 1], &now,
sizeof(struct timeval));
}
}
else
{
memcpy(&rreq_ratel[num_rreq], &now, sizeof(struct timeval));
num_rreq++;
}
break;
case AODV_RERR:
if (num_rerr == (RERR_RATELIMIT - 1))
{
if (timeval_diff(&now, &rerr_ratel[0]) < 1000)
{
DEBUG(LOG_DEBUG, 0, "RATELIMIT: Dropping RERR %ld ms",
timeval_diff(&now, &rerr_ratel[0]));
#ifdef OMNETPP
delete aodv_msg;
#else
#ifdef NS_PORT
Packet::free(p);
#endif
#endif
return;
}
else
{
memmove(rerr_ratel, &rerr_ratel[1],
sizeof(struct timeval) * (num_rerr - 1));
memcpy(&rerr_ratel[num_rerr - 1], &now,
sizeof(struct timeval));
}
}
else
{
memcpy(&rerr_ratel[num_rerr], &now, sizeof(struct timeval));
num_rerr++;
}
break;
}
}
/* If we broadcast this message we update the time of last broadcast
to prevent unnecessary broadcasts of HELLO msg's */
if (dst.s_addr == ManetAddress(IPv4Address(AODV_BROADCAST)))
{
gettimeofday(&this_host.bcast_time, NULL);
#ifdef NS_PORT
#ifndef OMNETPP
ch->addr_type() = NS_AF_NONE;
sendPacket(p, dst, 0.0);
#else
// IPv4Address desAddIp4(dst.s_addr);
// IPvXAddress destAdd(desAddIp4);
// In the floading proccess the random delay prevent collision for the synchronization between the nodes.
ManetAddress destAdd;
aodv_msg->prevFix=this->isStaticNode();
if (this->isStaticNode())
{
if (dynamic_cast<RREP*>(aodv_msg))
{
dynamic_cast<RREP*>(aodv_msg)->cost += costStatic;
}
else if (dynamic_cast<RREQ*> (aodv_msg))
{
dynamic_cast<RREQ*>(aodv_msg)->cost += costStatic;
}
}
else
{
if (dynamic_cast<RREP*>(aodv_msg))
{
dynamic_cast<RREP*>(aodv_msg)->cost += costMobile;
}
else if (dynamic_cast<RREQ*>(aodv_msg))
{
dynamic_cast<RREQ*>(aodv_msg)->cost += costMobile;
}
}
if (dst.s_addr == ManetAddress(IPv4Address(AODV_BROADCAST)))
{
destAdd = ManetAddress(IPv4Address::ALLONES_ADDRESS);
}
else
{
destAdd = dst.s_addr;
}
if (delay>0)
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654, ttl, delay, dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654, ttl, delay, dev->ipaddr.s_addr);
}
else
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654, ttl, par ("broadcastDelay").doubleValue(), dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654, ttl, par ("broadcastDelay").doubleValue(), dev->ipaddr.s_addr);
}
totalSend++;
// sendToIp(aodv_msg, 654, destAdd, 654,ttl);
#endif /*omnet++ */
#else
retval = sendto(dev->sock, send_buf, len, 0,
(struct sockaddr *) &dst_addr, sizeof(dst_addr));
if (retval < 0)
{
alog(LOG_WARNING, errno, __FUNCTION__, "Failed send to bc %s",
ip_to_str(dst));
return;
}
#endif
}
else
{
#ifdef NS_PORT
#ifndef OMNETPP
ch->addr_type() = NS_AF_INET;
/* We trust the decision of next hop for all AODV messages... */
if (dst.s_addr == AODV_BROADCAST)
sendPacket(p, dst, 0.001 * Random::uniform());
else
sendPacket(p, dst, 0.0);
#else
// IPv4Address desAddIp4(dst.s_addr);
// IPvXAddress destAdd(desAddIp4);
ManetAddress destAdd;
if (dst.s_addr == ManetAddress(IPv4Address(AODV_BROADCAST)))
{
destAdd = ManetAddress(IPv4Address::ALLONES_ADDRESS);
if (delay>0)
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654,ttl,delay,dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654,ttl,delay,dev->ipaddr.s_addr);
}
else
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654,ttl,par("broadcastDelay").doubleValue(),dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654,ttl,par("broadcastDelay").doubleValue(),dev->ipaddr.s_addr);
}
}
else
{
destAdd = dst.s_addr;
if (delay>0)
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654,ttl,delay,dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654,ttl,delay,dev->ipaddr.s_addr);
}
else
{
if (useIndex)
sendToIp(aodv_msg, 654, destAdd, 654,ttl,par("unicastDelay").doubleValue(),dev->ifindex);
else
sendToIp(aodv_msg, 654, destAdd, 654,ttl,par("unicastDelay").doubleValue(),dev->ipaddr.s_addr);
}
}
totalSend++;
#endif
#else
retval = sendto(dev->sock, send_buf, len, 0,
(struct sockaddr *) &dst_addr, sizeof(dst_addr));
if (retval < 0)
{
alog(LOG_WARNING, errno, __FUNCTION__, "Failed send to %s",
ip_to_str(dst));
return;
}
#endif
}
/* Do not print hello msgs... */
if (!(aodv_msg->type == AODV_RREP && (dst.s_addr == ManetAddress(IPv4Address(AODV_BROADCAST)))))
DEBUG(LOG_INFO, 0, "AODV msg to %s ttl=%d retval=%u size=%u",
ip_to_str(dst), ttl, retval, len);
return;
}
#ifndef OMNETPP
AODV_msg *NS_CLASS aodv_socket_new_msg(void)
{
memset(send_buf, '\0', SEND_BUF_SIZE);
return (AODV_msg *) (send_buf);
}
/* Copy an existing AODV message to the send buffer */
AODV_msg *NS_CLASS aodv_socket_queue_msg(AODV_msg * aodv_msg, int size)
{
memcpy((char *) send_buf, aodv_msg, size);
return (AODV_msg *) send_buf;
}
#endif
void aodv_socket_cleanup(void)
{
#ifndef NS_PORT
int i;
for (i = 0; i < MAX_NR_INTERFACES; i++)
{
if (!DEV_NR(i).enabled)
continue;
close(DEV_NR(i).sock);
}
#endif /* NS_PORT */
}
|
robertomagan/neta_v1
|
src/hackedmodules/networklayer/manetrouting/aodv/NA_aodv-uu/NA_aodv_socket.cc
|
C++
|
gpl-3.0
| 21,769
|
# `job_array_example`
Example of using worker's job array feature with a bash script.
## What is it?
1. ``run-array.pbs`: PBS script for worker that runs a Bash script
`power.sh` for each value specified by the `-t` option upon job
submission.
1. `power.sh`: Bash script that reads the content of a file (single
number) and raise 2 to that number, printing the result.
1. `input0.dat`...`input19.dat`: data files
1. `worker-array-power.sh`: Bash script showing how to submit the worker job
using `wsub` with the `-t` options.
|
gjbex/worker
|
examples/job_array_example/README.md
|
Markdown
|
gpl-3.0
| 544
|
! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
! Copyright by The HDF Group. *
! Copyright by the Board of Trustees of the University of Illinois. *
! All rights reserved. *
! *
! This file is part of HDF5. The full HDF5 copyright notice, including *
! terms governing use, modification, and redistribution, is contained in *
! the files COPYING and Copyright.html. COPYING can be found at the root *
! of the source code distribution tree; Copyright.html can be found at the *
! root level of an installed copy of the electronic HDF5 document set and *
! is linked from the top-level documents page. It can also be found at *
! http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
! access to either file, you may request a copy from help@hdfgroup.org. *
! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
!
!
! This file contains FORTRAN90 interfaces for H5I functions
!
MODULE H5Z
USE H5GLOBAL
CONTAINS
!----------------------------------------------------------------------
! Name: h5zunregister_f
!
! Purpose: Unregisters specified filetr
!
! Inputs: filter - filter; may have one of the following values:
! H5Z_FILTER_DEFLATE_F
! H5Z_FILTER_SHUFFLE_F
! H5Z_FILTER_FLETCHER32_F
! Outputs:
! hdferr: - error code
! Success: 0
! Failure: -1
! Optional parameters:
! NONE
!
! Programmer: Elena Pourmal
! March 12, 2003
!
! Modifications:
!
! Comment:
!----------------------------------------------------------------------
SUBROUTINE h5zunregister_f(filter, hdferr)
!
!This definition is needed for Windows DLLs
!DEC$if defined(BUILD_HDF5_DLL)
!DEC$attributes dllexport :: h5zunregister_f
!DEC$endif
!
IMPLICIT NONE
INTEGER, INTENT(IN) :: filter
INTEGER, INTENT(OUT) :: hdferr ! Error code
! INTEGER, EXTERNAL :: h5zunregister_c
! Interface is needed for MS FORTRAN
!
INTERFACE
INTEGER FUNCTION h5zunregister_c (filter)
USE H5GLOBAL
!DEC$IF DEFINED(HDF5F90_WINDOWS)
!MS$ATTRIBUTES C,reference,alias:'_H5ZUNREGISTER_C':: h5zunregister_c
!DEC$ENDIF
INTEGER, INTENT(IN) :: filter
END FUNCTION h5zunregister_c
END INTERFACE
hdferr = h5zunregister_c (filter)
END SUBROUTINE h5zunregister_f
!----------------------------------------------------------------------
! Name: h5zfilter_avail_f
!
! Purpose: Queries if filter is available
!
! Inputs:
! filter - filter
! Outputs:
! status - status; .TRUE. if filter is available,
! .FALSE. otherwise
! hdferr: - error code
! Success: 0
! Failure: -1
! Optional parameters:
! NONE
!
! Programmer: Elena Pourmal
! March 12, 2003
!
! Modifications:
!
!----------------------------------------------------------------------
SUBROUTINE h5zfilter_avail_f(filter, status, hdferr)
!
!This definition is needed for Windows DLLs
!DEC$if defined(BUILD_HDF5_DLL)
!DEC$attributes dllexport :: h5zfilter_avail_f
!DEC$endif
!
IMPLICIT NONE
INTEGER, INTENT(IN) :: filter ! Filter; may be one of the following:
! H5Z_FILTER_DEFLATE_F
! H5Z_FILTER_SHUFFLE_F
! H5Z_FILTER_FLETCHER32_F
LOGICAL, INTENT(OUT) :: status ! Flag, idicates if filter
! is availble not ( TRUE or
! FALSE)
INTEGER, INTENT(OUT) :: hdferr ! Error code
INTEGER :: flag ! "TRUE/FALSE/ERROR from C"
! INTEGER, EXTERNAL :: h5zfilter_avail_c
! MS FORTRAN needs explicit interface for C functions called here.
!
INTERFACE
INTEGER FUNCTION h5zfilter_avail_c(filter, flag)
USE H5GLOBAL
!DEC$IF DEFINED(HDF5F90_WINDOWS)
!MS$ATTRIBUTES C,reference,alias:'_H5ZFILTER_AVAIL_C'::h5zfilter_avail_c
!DEC$ENDIF
INTEGER, INTENT(IN) :: filter
INTEGER :: flag
END FUNCTION h5zfilter_avail_c
END INTERFACE
hdferr = h5zfilter_avail_c(filter, flag)
status = .TRUE.
if (flag .EQ. 0) status = .FALSE.
END SUBROUTINE h5zfilter_avail_f
!----------------------------------------------------------------------
! Name: h5zget_filter_info_f
!
! Purpose: Queries if filter has its encoder and/or decoder
! available
!
! Inputs:
! filter - filter
! Outputs:
! config_flags - Bit vector possibly containing the
! following values:
! H5Z_FILTER_ENCODE_ENABLED_F
! H5Z_FILTER_DECODE_ENABLED_F
! hdferr: - error code
! Success: 0
! Failure: -1
! Optional parameters:
! NONE
!
! Programmer: Nat Furrer and James Laird
! June 16, 2004
!
! Modifications:
!
!----------------------------------------------------------------------
SUBROUTINE h5zget_filter_info_f(filter, config_flags, hdferr)
!
!This definition is needed for Windows DLLs
!DEC$if defined(BUILD_HDF5_DLL)
!DEC$attributes dllexport :: h5zget_filter_info_f
!DEC$endif
!
IMPLICIT NONE
INTEGER, INTENT(IN) :: filter ! Filter; may be one of the following:
! H5Z_FILTER_DEFLATE_F
! H5Z_FILTER_SHUFFLE_F
! H5Z_FILTER_FLETCHER32_F
! H5Z_FILTER_SZIP_F
INTEGER, INTENT(OUT) :: config_flags! Flag, indicates if filter
! has its encoder and/or decoder
! available
INTEGER, INTENT(OUT) :: hdferr ! Error code
! INTEGER, EXTERNAL :: h5zget_filter_info_c
! MS FORTRAN needs explicit interface for C functions called here.
!
INTERFACE
INTEGER FUNCTION h5zget_filter_info_c(filter, config_flags)
USE H5GLOBAL
!DEC$IF DEFINED(HDF5F90_WINDOWS)
!MS$ATTRIBUTES C,reference,alias:'_H5ZGET_FILTER_INFO_C'::h5zget_filter_info_c
!DEC$ENDIF
INTEGER, INTENT(IN) :: filter
INTEGER, INTENT(OUT) :: config_flags
END FUNCTION h5zget_filter_info_c
END INTERFACE
hdferr = h5zget_filter_info_c(filter, config_flags)
END SUBROUTINE h5zget_filter_info_f
END MODULE H5Z
|
glentner/Gadget
|
Source/hdf5-1.6.10/fortran/src/H5Zff.f90
|
FORTRAN
|
gpl-3.0
| 7,405
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package SoftRest.modelos;
/**
*
* @author henvisi
*/
public class TipoPlato {
private int tipoplato_id;
private String tipoplato_nombre;
private double precio;
public TipoPlato() {
}
public TipoPlato(int tipoplato_id, String tipoplato_nombre,double precio) {
this.tipoplato_id = tipoplato_id;
this.tipoplato_nombre = tipoplato_nombre;
this.precio = precio;
}
public int getTipoplato_id() {
return tipoplato_id;
}
public void setTipoplato_id(int tipoplato_id) {
this.tipoplato_id = tipoplato_id;
}
public String getTipoplato_nombre() {
return tipoplato_nombre;
}
public void setTipoplato_nombre(String tipoplato_nombre) {
this.tipoplato_nombre = tipoplato_nombre;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
}
|
henvisi-1994/SoftRest
|
SofRest/src/SoftRest/modelos/TipoPlato.java
|
Java
|
gpl-3.0
| 1,131
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - WATTS, Edward</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>WATTS, Edward<sup><small></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
WATTS, Edward <a href="#sref1a">1a</a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I16576</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">male</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/5/9/d15f6074c8771b1111690af3b95.html" title="Birth">
Birth
<span class="grampsid"> [E16396]</span>
</a>
</td>
<td class="ColumnDate">1832-04-00</td>
<td class="ColumnPlace">
<a href="../../../plc/9/e/d15f5fb63255568f81f47075ce9.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/2/1/d15f6074ae7215e18e54711b012.html">WATTS, Phillip<span class="grampsid"> [I16569]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Mother</td>
<td class="ColumnValue">
<a href="../../../ppl/f/9/d15f6074b285631f726ee99a89f.html">TUCKER, Jane<span class="grampsid"> [I16570]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/f/8/d15f6074baa65922e1a59d64a8f.html">WATTS, Mary Ann<span class="grampsid"> [I16573]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/7/b/d15f6074bec48f9f95926f76b7.html">WATTS, Elizabeth<span class="grampsid"> [I16574]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/2/1/d15f6074c354d33ae514618012.html">WATTS, Ann<span class="grampsid"> [I16575]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/0/3/d15f6074c7c1245ab97feb5ad30.html">WATTS, Edward<span class="grampsid"> [I16576]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/7/c/d15f6074cc046904fd5335833c7.html">WATTS, Phillip<span class="grampsid"> [I16577]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/7/2/d15f6074e4c779a984b4ac7c27.html">WATTS, Edwin<span class="grampsid"> [I16583]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="../../../fam/c/8/d15f6074c9f27106f2a9ecbbd8c.html" title="Family of WATTS, Edward">Family of WATTS, Edward<span class="grampsid"> [F4799]</span></a></td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Attributes</td>
<td class="ColumnValue">
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">1FDF7ADE84CA9E418380A56145387C59DEAE</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</div>
<div class="subsection" id="attributes">
<h4>Attributes</h4>
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">BB8360CA46A3DE40B1EABB2B073B5B25B2E3</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/2/1/d15f6074ae7215e18e54711b012.html">WATTS, Phillip<span class="grampsid"> [I16569]</span></a>
<ol>
<li class="spouse">
<a href="../../../ppl/f/9/d15f6074b285631f726ee99a89f.html">TUCKER, Jane<span class="grampsid"> [I16570]</span></a>
<ol>
<li>
<a href="../../../ppl/f/8/d15f6074baa65922e1a59d64a8f.html">WATTS, Mary Ann<span class="grampsid"> [I16573]</span></a>
</li>
<li>
<a href="../../../ppl/7/b/d15f6074bec48f9f95926f76b7.html">WATTS, Elizabeth<span class="grampsid"> [I16574]</span></a>
</li>
<li>
<a href="../../../ppl/2/1/d15f6074c354d33ae514618012.html">WATTS, Ann<span class="grampsid"> [I16575]</span></a>
</li>
<li class="thisperson">
WATTS, Edward
<ol class="spouselist">
<li class="spouse">
</li>
</ol>
</li>
<li>
<a href="../../../ppl/7/c/d15f6074cc046904fd5335833c7.html">WATTS, Phillip<span class="grampsid"> [I16577]</span></a>
</li>
<li>
<a href="../../../ppl/7/2/d15f6074e4c779a984b4ac7c27.html">WATTS, Edwin<span class="grampsid"> [I16583]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg male AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/0/3/d15f6074c7c1245ab97feb5ad30.html">
WATTS, Edward
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/2/1/d15f6074ae7215e18e54711b012.html">
WATTS, Phillip
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 151px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 156px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 44px; left: 386px;">
<a class="noThumb" href="../../../ppl/4/8/d15f6074a7e4d2e7c3f6051d684.html">
WATTS, Tristram
</a>
</div>
<div class="shadow" style="top: 49px; left: 390px;"></div>
<div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 76px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 81px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 7px; left: 576px;">
<a class="noThumb" href="../../../ppl/d/c/d15f606079f12a40d5b2c741fcd.html">
WATTS, Thomas
</a>
</div>
<div class="shadow" style="top: 12px; left: 580px;"></div>
<div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol3" style="top: 81px; left: 576px;">
<a class="noThumb" href="../../../ppl/e/c/d15f60607e75b514b10306c0fce.html">
KNILL, Prudence
</a>
</div>
<div class="shadow" style="top: 86px; left: 580px;"></div>
<div class="bvline" style="top: 113px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 118px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 81px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol2" style="top: 194px; left: 386px;">
<a class="noThumb" href="../../../ppl/f/5/d15f6074ac3189822d369e57e5f.html">
BAILEY, Anne
</a>
</div>
<div class="shadow" style="top: 199px; left: 390px;"></div>
<div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div>
<div class="boxbg female AncCol1" style="top: 419px; left: 196px;">
<a class="noThumb" href="../../../ppl/f/9/d15f6074b285631f726ee99a89f.html">
TUCKER, Jane
</a>
</div>
<div class="shadow" style="top: 424px; left: 200px;"></div>
<div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 451px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 456px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 344px; left: 386px;">
<a class="noThumb" href="../../../ppl/1/5/d15f6074b6a55b9447334ef5851.html">
TUCKER, Thomas
</a>
</div>
<div class="shadow" style="top: 349px; left: 390px;"></div>
<div class="bvline" style="top: 376px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 381px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 376px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 381px; left: 375px; height: 75px;"></div>
<div class="boxbg female AncCol2" style="top: 494px; left: 386px;">
<a class="noThumb" href="../../../ppl/4/5/d15f6074b8e7be60ef434619754.html">
KNILL, Justina
</a>
</div>
<div class="shadow" style="top: 499px; left: 390px;"></div>
<div class="bvline" style="top: 526px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 531px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 451px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 456px; left: 375px; height: 75px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/7/f/d15f5fd74c3e89723a946a86f7.html" title="Jane Dewing: Descendants of Tristram Watts" name ="sref1">
Jane Dewing: Descendants of Tristram Watts
<span class="grampsid"> [S0311]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
RossGammon/the-gammons.net
|
RossFamilyTree/ppl/0/3/d15f6074c7c1245ab97feb5ad30.html
|
HTML
|
gpl-3.0
| 15,437
|
/*
* This file is part of Audio switch daemon.
* Audio switch daemon 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.
*
* Audio switch daemon 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 Audio switch daemon.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include "help.h"
#include "version.h"
#include "options.h"
#include "arguments.h"
/*
* Parse Arguments, set Flags
*/
void parse_arguments(int argc, char *argv[])
{
int c;
int option_index = 0;
/*Set defaults*/
daemon_flag = 1;
sock_path = "/home/pi/.mpd/socket";
switch_pin = 17;
while(1)
{
static struct option long_options[] =
{
{"no-daemon", no_argument, &daemon_flag, 0},
/* These options don’t set a flag.*/
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{"pin", required_argument, 0, 'p'},
{"socket", required_argument, 0, 's'},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "hvkP:s:p:c:",long_options,
&option_index);
if(c==-1)
break;
switch(c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'h':
print_help();
exit(EXIT_SUCCESS);
break;
case 'v':
print_version();
exit(EXIT_SUCCESS);
break;
case 'p':
switch_pin=eval_pin(atoi(optarg));
break;
case 's':
sock_path = optarg;
case '?':
printf ("Unknown arguments. See asd --help for arguments.\n");
exit(EXIT_FAILURE);
/* getopt_long already printed an error message. */
break;
default:
abort ();
}
}
}
/*
* Check if pin is in usable GPIO range.
* Return default (GPIO 17) if pin is out of range.
* Otherwise return pin
*/
uint8_t eval_pin(int pin)
{
if ( pin < 0 || pin == 5 || pin ==6 || pin == 12 || pin == 13 || pin == 16 || pin == 19 || pin == 20 || pin == 26 || pin > 31)
{
fprintf(stdout,"Invalid pin, using default pin %d\n",DEFAULT_PIN);
return DEFAULT_PIN;
}
else
{
return pin;
}
}
|
fast90/asd
|
src/arguments.c
|
C
|
gpl-3.0
| 3,011
|
/* ATK - Accessibility Toolkit
*
* Copyright (C) 2012 Igalia, S.L.
* Copyright (C) 2014 Chun-wei Fan
*
* Author: Alejandro Piñeiro Iglesias <apinheiro@igalia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#if defined(ATK_DISABLE_SINGLE_INCLUDES) && !defined (__ATK_H_INSIDE__) && !defined (ATK_COMPILATION)
#error "Only <atk/atk.h> can be included directly."
#endif
#ifndef __ATK_VERSION_H__
#define __ATK_VERSION_H__
#include <glib.h>
/**
* ATK_MAJOR_VERSION:
*
* Like atk_get_major_version(), but from the headers used at
* application compile time, rather than from the library linked
* against at application run time.
*
* Since: 2.7.4
*/
#define ATK_MAJOR_VERSION (2)
/**
* ATK_MINOR_VERSION:
*
* Like atk_get_minor_version(), but from the headers used at
* application compile time, rather than from the library linked
* against at application run time.
*
* Since: 2.7.4
*/
#define ATK_MINOR_VERSION (26)
/**
* ATK_MICRO_VERSION:
*
* Like atk_get_micro_version(), but from the headers used at
* application compile time, rather than from the library linked
* against at application run time.
*
* Since: 2.7.4
*/
#define ATK_MICRO_VERSION (1)
/**
* ATK_BINARY_AGE:
*
* Like atk_get_binary_age(), but from the headers used at
* application compile time, rather than from the library linked
* against at application run time.
*
* Since: 2.7.4
*/
#define ATK_BINARY_AGE (22611)
/**
* ATK_INTERFACE_AGE:
*
* Like atk_get_interface_age(), but from the headers used at
* application compile time, rather than from the library linked
* against at application run time.
*
* Since: 2.7.4
*/
#define ATK_INTERFACE_AGE (1)
/**
* ATK_CHECK_VERSION:
* @major: major version (e.g. 1 for version 1.2.5)
* @minor: minor version (e.g. 2 for version 1.2.5)
* @micro: micro version (e.g. 5 for version 1.2.5)
*
* Returns %TRUE if the version of the ATK header files is the same as
* or newer than the passed-in version.
*
* Since: 2.7.4
*/
#define ATK_CHECK_VERSION(major,minor,micro) \
(ATK_MAJOR_VERSION > (major) || \
(ATK_MAJOR_VERSION == (major) && ATK_MINOR_VERSION > (minor)) || \
(ATK_MAJOR_VERSION == (major) && ATK_MINOR_VERSION == (minor) && \
ATK_MICRO_VERSION >= (micro)))
#ifndef _ATK_EXTERN
#define _ATK_EXTERN extern
#endif
/**
* ATK_VERSION_2_2:
*
* A macro that evaluates to the 2.2 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_2 (G_ENCODE_VERSION (2, 2))
/**
* ATK_VERSION_2_4:
*
* A macro that evaluates to the 2.4 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_4 (G_ENCODE_VERSION (2, 4))
/**
* ATK_VERSION_2_6:
*
* A macro that evaluates to the 2.6 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_6 (G_ENCODE_VERSION (2, 6))
/**
* ATK_VERSION_2_8:
*
* A macro that evaluates to the 2.8 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_8 (G_ENCODE_VERSION (2, 8))
/**
* ATK_VERSION_2_10:
*
* A macro that evaluates to the 2.10 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_10 (G_ENCODE_VERSION (2, 10))
/**
* ATK_VERSION_2_12:
*
* A macro that evaluates to the 2.12 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_12 (G_ENCODE_VERSION (2, 12))
/**
* ATK_VERSION_2_14:
*
* A macro that evaluates to the 2.14 version of ATK, in a format
* that can be used by the C pre-processor.
*
* Since: 2.14
*/
#define ATK_VERSION_2_14 (G_ENCODE_VERSION (2, 14))
/* evaluates to the current stable version; for development cycles,
* this means the next stable target
*/
#if (ATK_MINOR_VERSION % 2)
#define ATK_VERSION_CUR_STABLE (G_ENCODE_VERSION (ATK_MAJOR_VERSION, ATK_MINOR_VERSION + 1))
#else
#define ATK_VERSION_CUR_STABLE (G_ENCODE_VERSION (ATK_MAJOR_VERSION, ATK_MINOR_VERSION))
#endif
/* evaluates to the previous stable version */
#if (ATK_MINOR_VERSION % 2)
#define ATK_VERSION_PREV_STABLE (G_ENCODE_VERSION (ATK_MAJOR_VERSION, ATK_MINOR_VERSION - 1))
#else
#define ATK_VERSION_PREV_STABLE (G_ENCODE_VERSION (ATK_MAJOR_VERSION, ATK_MINOR_VERSION - 2))
#endif
/**
* ATK_VERSION_MIN_REQUIRED:
*
* A macro that should be defined by the user prior to including
* the atk/atk.h header.
* The definition should be one of the predefined ATK version
* macros: %ATK_VERSION_2_12, %ATK_VERSION_2_14,...
*
* This macro defines the earliest version of ATK that the package is
* required to be able to compile against.
*
* If the compiler is configured to warn about the use of deprecated
* functions, then using functions that were deprecated in version
* %ATK_VERSION_MIN_REQUIRED or earlier will cause warnings (but
* using functions deprecated in later releases will not).
*
* Since: 2.14
*/
/* If the package sets ATK_VERSION_MIN_REQUIRED to some future
* ATK_VERSION_X_Y value that we don't know about, it will compare as
* 0 in preprocessor tests.
*/
#ifndef ATK_VERSION_MIN_REQUIRED
# define ATK_VERSION_MIN_REQUIRED (ATK_VERSION_CUR_STABLE)
#elif ATK_VERSION_MIN_REQUIRED == 0
# undef ATK_VERSION_MIN_REQUIRED
# define ATK_VERSION_MIN_REQUIRED (ATK_VERSION_CUR_STABLE + 2)
#endif
/**
* ATK_VERSION_MAX_ALLOWED:
*
* A macro that should be defined by the user prior to including
* the atk/atk.h header.
* The definition should be one of the predefined ATK version
* macros: %ATK_VERSION_2_12, %ATK_VERSION_2_14,...
*
* This macro defines the latest version of the ATK API that the
* package is allowed to make use of.
*
* If the compiler is configured to warn about the use of deprecated
* functions, then using functions added after version
* %ATK_VERSION_MAX_ALLOWED will cause warnings.
*
* Unless you are using ATK_CHECK_VERSION() or the like to compile
* different code depending on the ATK version, then this should be
* set to the same value as %ATK_VERSION_MIN_REQUIRED.
*
* Since: 2.14
*/
#if !defined (ATK_VERSION_MAX_ALLOWED) || (ATK_VERSION_MAX_ALLOWED == 0)
# undef ATK_VERSION_MAX_ALLOWED
# define ATK_VERSION_MAX_ALLOWED (ATK_VERSION_CUR_STABLE)
#endif
/* sanity checks */
#if ATK_VERSION_MIN_REQUIRED > ATK_VERSION_CUR_STABLE
#error "ATK_VERSION_MIN_REQUIRED must be <= ATK_VERSION_CUR_STABLE"
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_MIN_REQUIRED
#error "ATK_VERSION_MAX_ALLOWED must be >= ATK_VERSION_MIN_REQUIRED"
#endif
#if ATK_VERSION_MIN_REQUIRED < ATK_VERSION_2_2
#error "ATK_VERSION_MIN_REQUIRED must be >= ATK_VERSION_2_2"
#endif
/* these macros are used to mark deprecated functions, and thus have to be
* exposed in a public header.
*
* do *not* use them in other libraries depending on Atk: use G_DEPRECATED
* and G_DEPRECATED_FOR, or use your own wrappers around them.
*/
#ifdef ATK_DISABLE_DEPRECATION_WARNINGS
#define ATK_DEPRECATED _ATK_EXTERN
#define ATK_DEPRECATED_FOR(f) _ATK_EXTERN
#define ATK_UNAVAILABLE(maj,min) _ATK_EXTERN
#else
#define ATK_DEPRECATED G_DEPRECATED _ATK_EXTERN
#define ATK_DEPRECATED_FOR(f) G_DEPRECATED_FOR(f) _ATK_EXTERN
#define ATK_UNAVAILABLE(maj,min) G_UNAVAILABLE(maj,min) _ATK_EXTERN
#endif
#define ATK_AVAILABLE_IN_ALL _ATK_EXTERN
/* XXX: Every new stable minor release should add a set of macros here */
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_2
# define ATK_DEPRECATED_IN_2_2 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_2_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_2 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_2_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_2
# define ATK_AVAILABLE_IN_2_2 ATK_UNAVAILABLE(2, 2)
#else
# define ATK_AVAILABLE_IN_2_2 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_4
# define ATK_DEPRECATED_IN_2_4 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_4_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_4 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_4_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_4
# define ATK_AVAILABLE_IN_2_4 ATK_UNAVAILABLE(2, 4)
#else
# define ATK_AVAILABLE_IN_2_4 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_6
# define ATK_DEPRECATED_IN_2_6 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_6_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_6 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_6_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_6
# define ATK_AVAILABLE_IN_2_6 ATK_UNAVAILABLE(2, 6)
#else
# define ATK_AVAILABLE_IN_2_6 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_8
# define ATK_DEPRECATED_IN_2_8 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_8_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_8 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_8_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_8
# define ATK_AVAILABLE_IN_2_8 ATK_UNAVAILABLE(2, 8)
#else
# define ATK_AVAILABLE_IN_2_8 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_10
# define ATK_DEPRECATED_IN_2_10 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_10_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_10 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_10_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_10
# define ATK_AVAILABLE_IN_2_10 ATK_UNAVAILABLE(2, 10)
#else
# define ATK_AVAILABLE_IN_2_10 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_12
# define ATK_DEPRECATED_IN_2_12 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_12_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_12 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_12_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_12
# define ATK_AVAILABLE_IN_2_12 ATK_UNAVAILABLE(2, 12)
#else
# define ATK_AVAILABLE_IN_2_12 _ATK_EXTERN
#endif
#if ATK_VERSION_MIN_REQUIRED >= ATK_VERSION_2_14
# define ATK_DEPRECATED_IN_2_14 ATK_DEPRECATED
# define ATK_DEPRECATED_IN_2_14_FOR(f) ATK_DEPRECATED_FOR(f)
#else
# define ATK_DEPRECATED_IN_2_14 _ATK_EXTERN
# define ATK_DEPRECATED_IN_2_14_FOR(f) _ATK_EXTERN
#endif
#if ATK_VERSION_MAX_ALLOWED < ATK_VERSION_2_14
# define ATK_AVAILABLE_IN_2_14 ATK_UNAVAILABLE(2, 14)
#else
# define ATK_AVAILABLE_IN_2_14 _ATK_EXTERN
#endif
ATK_AVAILABLE_IN_2_8
guint atk_get_major_version (void) G_GNUC_CONST;
ATK_AVAILABLE_IN_2_8
guint atk_get_minor_version (void) G_GNUC_CONST;
ATK_AVAILABLE_IN_2_8
guint atk_get_micro_version (void) G_GNUC_CONST;
ATK_AVAILABLE_IN_2_8
guint atk_get_binary_age (void) G_GNUC_CONST;
ATK_AVAILABLE_IN_2_8
guint atk_get_interface_age (void) G_GNUC_CONST;
#define atk_major_version atk_get_major_version ()
#define atk_minor_version atk_get_minor_version ()
#define atk_micro_version atk_get_micro_version ()
#define atk_binary_age atk_get_binary_age ()
#define atk_interface_age atk_get_interface_age ()
#endif /* __ATK_VERSION_H__ */
|
mgood7123/UPM
|
Tests/PACKAGES/hexchat-2.12.4-6-x86_64/usr/include/atk-1.0/atk/atkversion.h
|
C
|
gpl-3.0
| 12,428
|
/*
* Created on 30-ago-2005
*
* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* 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.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
package com.hardcode.gdbms.engine.spatial.fmap;
import java.awt.geom.Rectangle2D;
import com.hardcode.gdbms.driver.exceptions.CloseDriverException;
import com.hardcode.gdbms.driver.exceptions.OpenDriverException;
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
import com.hardcode.gdbms.engine.data.DataSource;
import com.hardcode.gdbms.engine.data.driver.SpatialFileDriver;
import com.hardcode.gdbms.engine.data.file.FileDataWare;
import com.hardcode.gdbms.engine.spatial.Geometry;
import com.hardcode.gdbms.engine.values.Value;
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
import com.iver.cit.gvsig.fmap.core.GeneralPathX;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
import com.iver.cit.gvsig.fmap.layers.VectorialFileAdapter;
public abstract class AbstractFMapFileDriver implements SpatialFileDriver {
private VectorialAdapter adapter;
private DataSource dataSource;
/**
* @throws OpenDriverException TODO
* @see com.hardcode.gdbms.engine.data.driver.FileDriver#open(java.io.File)
*/
public void open(VectorialFileAdapter adapter) throws OpenDriverException {
try {
this.adapter = adapter;
adapter.start();
dataSource = adapter.getRecordset();
dataSource.start();
} catch (ReadDriverException e) {
throw new OpenDriverException(getName(),e);
}
}
/**
* @see com.hardcode.gdbms.engine.data.driver.FileDriver#close()
*/
public void close() throws CloseDriverException {
try{
adapter.stop();
dataSource.stop();
} catch (ReadDriverException e) {
throw new CloseDriverException(getName(),e);
}
}
/**
* @see com.hardcode.gdbms.engine.data.driver.FileDriver#writeFile(com.hardcode.gdbms.engine.data.file.FileDataWare, java.io.File)
*/
public void writeFile(FileDataWare dataWare) throws WriteDriverException {
}
/**
* @see com.hardcode.gdbms.engine.data.driver.FileDriver#createSource(java.lang.String, java.lang.String[], int[])
*/
public void createSource(String path, String[] fieldNames, int[] fieldTypes) throws ReadDriverException {
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long, int)
*/
public Value getFieldValue(long rowIndex, int fieldId) throws ReadDriverException {
return dataSource.getFieldValue(rowIndex, fieldId);
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
*/
public int getFieldCount() throws ReadDriverException {
return dataSource.getFieldCount();
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
*/
public String getFieldName(int fieldId) throws ReadDriverException {
return dataSource.getFieldName(fieldId);
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
*/
public long getRowCount() throws ReadDriverException {
return dataSource.getRowCount();
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
*/
public int getFieldType(int i) throws ReadDriverException {
return dataSource.getFieldType(i);
}
/**
* @see com.hardcode.gdbms.engine.data.driver.SpatialDriver#getFullExtent()
*/
public Rectangle2D getFullExtent() throws ReadDriverException {
return adapter.getFullExtent();
}
/**
* @see com.hardcode.gdbms.engine.data.driver.SpatialDriver#getGeometry(long)
*/
public Geometry getGeometry(long rowIndex) throws ReadDriverException {
try {
return new FMapGeometry(adapter.getShape((int)rowIndex));
} catch (ExpansionFileReadException e) {
throw new ReadDriverException(getName(),e);
}
}
/**
* @see com.hardcode.gdbms.engine.data.driver.SpatialDriver#getJTSGeometry(long)
*/
public com.vividsolutions.jts.geom.Geometry getJTSGeometry(long rowIndex) throws ReadDriverException {
try {
IGeometry ig = adapter.getShape((int)rowIndex);
GeneralPathX gpx = new GeneralPathX();
gpx.append(ig.getPathIterator(null), true);
return FConverter.java2d_to_jts(new FShapeGeneralPathX(gpx, ig.getGeometryType()));
} catch (ExpansionFileReadException e) {
throw new ReadDriverException(getName(),e);
}
}
protected VectorialAdapter getAdapter() {
return adapter;
}
protected DataSource getDataSource() {
return dataSource;
}
/**
* @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldWidth(int)
*/
public int getFieldWidth(int i) throws ReadDriverException {
return dataSource.getFieldWidth(i);
}
}
|
iCarto/siga
|
libGDBMS/src/main/java/com/hardcode/gdbms/engine/spatial/fmap/AbstractFMapFileDriver.java
|
Java
|
gpl-3.0
| 5,851
|
#ifndef PARTICLEHANDLE_H
#define PARTICLEHANDLE_H 1
/**
* @class ParticleHandle
* @brief handles a decay structure to MyKin ploters
*
* @author Paul Seyfert
* @date 2012-01-21
*/
#include <map>
#include <string>
class MyKin;
class ZooP;
class ZooEv;
class TDirectory;
class ParticleHandle {
private:
MyKin* m_kinplot;
std::map<int,ParticleHandle*> map;
bool m_initialised;
void initialise(const ZooP*);
std::string m_prefix;
public:
void Fill(const ZooP*, const ZooEv*, double w=1.);
void Write(TDirectory* dir);
ParticleHandle();
ParticleHandle(std::string prefix);
~ParticleHandle();
};
#endif
|
pseyfert/ZooReaders
|
ZooFunctors/ParticleHandle.h
|
C
|
gpl-3.0
| 651
|
package com.ipac.app.dao;
import java.util.List;
import com.ipac.app.model.Switch;
/**
* Data Access Object for transactional database interactions
*
* @author RMurray
*/
public interface SwitchDao {
/**
* Retrieves ALL switches
*
* @return List<Switch> of switch objects
*/
public List<Switch> getAll();
/**
* Retrieves ONE switch by ID
*
* @param id The ID of the switch to retrieve
* @return Switch object
*/
public Switch getSwitch( Integer id );
}
|
rob-murray/ipac
|
WEBAPP/src/main/java/com/ipac/app/dao/SwitchDao.java
|
Java
|
gpl-3.0
| 530
|
package org.dicadeveloper.weplantaforest.planting.plantbag;
import java.util.ArrayList;
import java.util.List;
import org.dicadeveloper.weplantaforest.common.errorhandling.ErrorCodes;
import org.dicadeveloper.weplantaforest.common.errorhandling.IpatException;
import org.dicadeveloper.weplantaforest.common.errorhandling.IpatPreconditions;
import org.dicadeveloper.weplantaforest.common.support.PriceHelper;
import org.dicadeveloper.weplantaforest.planting.plantbag.SimplePlantBag.SimplePlantPageItem;
import org.dicadeveloper.weplantaforest.projects.ProjectArticle;
import org.dicadeveloper.weplantaforest.projects.ProjectArticleRepository;
import org.dicadeveloper.weplantaforest.projects.ProjectRepository;
import org.dicadeveloper.weplantaforest.trees.TreeRepository;
import org.dicadeveloper.weplantaforest.treetypes.TreeTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.val;
@Service
public class SimplePlantBagHelper extends AbstractPlantBagHelper {
@Autowired
protected SimplePlantBagHelper(ProjectRepository projectRepository, ProjectArticleRepository projectArticleRepository, TreeTypeRepository treeTypeRepository, TreeRepository treeRepository) {
super(projectRepository, projectArticleRepository, treeTypeRepository, treeRepository);
}
public SimplePlantBag createPlantProposalForAmountOfTrees(long targetAmountOfTrees) throws IpatException {
val simplePlantPageData = new SimplePlantBag();
List<ProjectArticle> projectArticles = initialize(targetAmountOfTrees, simplePlantPageData);
IpatPreconditions.checkArgument(projectArticles.size() > 0, ErrorCodes.NO_TREES_TO_PLANT);
ProjectArticle articleWithHighestMarge = findProjectArticleWithHighestMarge(projectArticles);
addItemWithHighestMarge(projectArticles, articleWithHighestMarge, simplePlantPageData);
addFurtherItems(projectArticles, simplePlantPageData);
increaseAmountOfItemWithHighestMargeIfNeeded(articleWithHighestMarge, simplePlantPageData);
return simplePlantPageData;
}
public SimplePlantBag createPlantProposalForAmountOfTrees(String projectName, long targetAmountOfTrees) throws IpatException {
val simplePlantPageData = new SimplePlantBag();
List<ProjectArticle> projectArticles = initialize(projectName, targetAmountOfTrees, simplePlantPageData);
IpatPreconditions.checkArgument(projectArticles.size() > 0, ErrorCodes.NO_TREES_TO_PLANT);
ProjectArticle articleWithHighestMarge = findProjectArticleWithHighestMarge(projectArticles);
addItemWithHighestMarge(projectArticles, articleWithHighestMarge, simplePlantPageData);
addFurtherItems(projectArticles, simplePlantPageData);
increaseAmountOfItemWithHighestMargeIfNeeded(articleWithHighestMarge, simplePlantPageData);
return simplePlantPageData;
}
private List<ProjectArticle> initialize(long targetAmountOfTrees, final SimplePlantBag simplePlantPageData) {
List<ProjectArticle> projectArticles = new ArrayList<>();
List<SimplePlantPageItem> simplePlantPageItems = new ArrayList<>();
simplePlantPageData.setPlantItems(simplePlantPageItems);
simplePlantPageData.setTargetAmountOfTrees(targetAmountOfTrees);
projectArticles = createListOfAllAvailableProjectArticles();
return projectArticles;
}
private List<ProjectArticle> initialize(String projectName, long targetAmountOfTrees, final SimplePlantBag simplePlantPageData) {
List<ProjectArticle> projectArticles = new ArrayList<>();
List<SimplePlantPageItem> simplePlantPageItems = new ArrayList<>();
simplePlantPageData.setPlantItems(simplePlantPageItems);
simplePlantPageData.setTargetAmountOfTrees(targetAmountOfTrees);
projectArticles = createListOfAllAvailableProjectArticles(projectName);
return projectArticles;
}
private void addItemWithHighestMarge(List<ProjectArticle> projectArticles, ProjectArticle article, SimplePlantBag simplePlantPageData) {
long amountOfTreesForHighestMarge = Math.round((simplePlantPageData.getTargetAmountOfTrees() * 0.7));
SimplePlantPageItem itemWithHighestMarge = createPlantItemFromArticle(article);
if (amountOfTreesForHighestMarge <= countTreesRemainingByThisArticle(article)) {
itemWithHighestMarge.setAmount(amountOfTreesForHighestMarge);
} else {
long treesRemaining = countTreesRemainingByThisArticle(article);
itemWithHighestMarge.setAmount(treesRemaining);
}
simplePlantPageData.addPlantItem(itemWithHighestMarge);
projectArticles.remove(article);
}
private void increaseAmountOfItemWithHighestMargeIfNeeded(ProjectArticle article, SimplePlantBag simplePlantPageData) {
if (simplePlantPageData.getDiffToTargetAmount() > 0) {
long diffTotargetAmount = simplePlantPageData.getDiffToTargetAmount();
SimplePlantPageItem plantItemWithHighestMarge = simplePlantPageData.getPlantItems().get(0);
if ((plantItemWithHighestMarge.getAmount() + diffTotargetAmount) <= countTreesRemainingByThisArticle(article)) {
simplePlantPageData.increaseAmountOfPlantItem(plantItemWithHighestMarge, diffTotargetAmount);
} else {
long treesRemaining = countTreesRemainingByThisArticle(article);
long increaseAmountBy = treesRemaining - plantItemWithHighestMarge.getAmount();
simplePlantPageData.increaseAmountOfPlantItem(plantItemWithHighestMarge, increaseAmountBy);
}
}
}
private void addFurtherItems(List<ProjectArticle> projectArticles, SimplePlantBag simplePlantPageData) {
boolean treeCouldBeAdded = false;
do {
treeCouldBeAdded = false;
for (ProjectArticle article : projectArticles) {
if (simplePlantPageData.getDiffToTargetAmount() > 0) {
SimplePlantPageItem plantItemFromArticle = createPlantItemFromArticle(article);
if (simplePlantPageData.containsPlantItem(plantItemFromArticle)) {
SimplePlantPageItem plantItemFromList = simplePlantPageData.getPlantItem(plantItemFromArticle);
long itemAmount = plantItemFromList.getAmount();
if ((itemAmount + 1) <= countTreesRemainingByThisArticle(article)) {
simplePlantPageData.increaseAmountOfPlantItem(plantItemFromList, 1);
treeCouldBeAdded = true;
} else {
// do nothing
}
} else {
simplePlantPageData.addPlantItem(plantItemFromArticle);
treeCouldBeAdded = true;
}
}
}
} while (treeCouldBeAdded);
}
private SimplePlantPageItem createPlantItemFromArticle(ProjectArticle article) {
String treeType = article.getTreeType().getName();
long treePrice = PriceHelper.fromBigDecimalToLong(article.getPrice().getAmount());
String projectName = article.getProject().getName();
SimplePlantPageItem plantPageItem = new SimplePlantPageItem();
plantPageItem.setTreePrice(treePrice);
plantPageItem.setTreeType(treeType);
plantPageItem.setProjectName(projectName);
plantPageItem.setAmount(1);
plantPageItem.setImageFile(article.getTreeType().getImageFile());
return plantPageItem;
}
}
|
Dica-Developer/weplantaforest
|
user/src/main/java/org/dicadeveloper/weplantaforest/planting/plantbag/SimplePlantBagHelper.java
|
Java
|
gpl-3.0
| 7,819
|
import {NgModule, ErrorHandler} from '@angular/core';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {MyApp} from './app.component';
import {Home} from '../pages/Home/Home';
import {GamingPage} from '../pages/gaming/gaming';
import {Page2} from '../pages/page2/page2';
import {BasicModal} from '../components/basic-modal';
@NgModule({
declarations: [
MyApp,
Home,
GamingPage,
Page2,
BasicModal
],
imports: [
IonicModule.forRoot(MyApp, {mode: 'md'})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
Home,
GamingPage,
Page2,
BasicModal
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {
}
|
rockmasterflex69/rockpasta
|
ionicPasta/src/app/app.module.ts
|
TypeScript
|
gpl-3.0
| 730
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the class library */
/* SoPlex --- the Sequential object-oriented simPlex. */
/* */
/* Copyright (C) 1996 Roland Wunderling */
/* 1996-2018 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SoPlex is distributed under the terms of the ZIB Academic Licence. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with SoPlex; see the file COPYING. If not email to soplex@zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file vectorbase.h
* @brief Dense vector.
*/
#ifndef _VECTORBASE_H_
#define _VECTORBASE_H_
#include <assert.h>
#include <string.h>
#include <math.h>
#include <iostream>
namespace soplex
{
template < class R > class SVectorBase;
template < class R > class SSVectorBase;
/**@brief Dense vector.
* @ingroup Algebra
*
* Class VectorBase provides dense linear algebra vectors. It does not provide memory management for the %array of
* values. Instead, the constructor requires a pointer to a memory block large enough to fit the desired dimension of
* Real or Rational values.
*
* After construction, the values of a VectorBase can be accessed with the subscript operator[](). Safety is provided by
* qchecking of array bound when accessing elements with the subscript operator[]() (only when compiled without \c
* -DNDEBUG).
*
* A VectorBase is distinguished from a simple array of %Reals or %Rationals by providing a set of mathematical
* operations. Since VectorBase does not provide any memory management features, no operations are available that would
* require allocation of temporary memory space.
*
* The following mathematical operations are provided by class VectorBase (VectorBase \p a, \p b; R \p x):
*
* <TABLE>
* <TR><TD>Operation</TD><TD>Description </TD><TD></TD> </TR>
* <TR><TD>\c -= </TD><TD>subtraction </TD><TD>\c a \c -= \c b </TD></TR>
* <TR><TD>\c += </TD><TD>addition </TD><TD>\c a \c += \c b </TD></TR>
* <TR><TD>\c * </TD><TD>scalar product</TD>
* <TD>\c x = \c a \c * \c b </TD></TR>
* <TR><TD>\c *= </TD><TD>scaling </TD><TD>\c a \c *= \c x </TD></TR>
* <TR><TD>maxAbs() </TD><TD>infinity norm </TD>
* <TD>\c a.maxAbs() == \f$\|a\|_{\infty}\f$ </TD></TR>
* <TR><TD>minAbs() </TD><TD> </TD>
* <TD>\c a.minAbs() == \f$\min |a_i|\f$ </TD></TR>
*
* <TR><TD>length() </TD><TD>euclidian norm</TD>
* <TD>\c a.length() == \f$\sqrt{a^2}\f$ </TD></TR>
* <TR><TD>length2()</TD><TD>square norm </TD>
* <TD>\c a.length2() == \f$a^2\f$ </TD></TR>
* <TR><TD>multAdd(\c x,\c b)</TD><TD>add scaled vector</TD>
* <TD> \c a += \c x * \c b </TD></TR>
* </TABLE>
*
* When using any of these operations, the vectors involved must be of the same dimension. Also an SVectorBase \c b is
* allowed if it does not contain nonzeros with index greater than the dimension of \c a.q
*/
template < class R >
class VectorBase
{
protected:
// ------------------------------------------------------------------------------------------------------------------
/**@name Data */
//@{
/// Dimension of vector.
int dimen;
/// Values of vector.
/** The memory block pointed to by val must at least have size dimen * sizeof(R). */
R* val;
//@}
public:
// ------------------------------------------------------------------------------------------------------------------
/**@name Construction and assignment */
//@{
/// Constructor.
/** There is no default constructor since the storage for a VectorBase must be provided externally. Storage must be
* passed as a memory block val at construction. It must be large enough to fit at least dimen values.
*/
VectorBase<R>(int p_dimen, R* p_val)
: dimen(p_dimen)
, val(p_val)
{
assert(dimen >= 0);
assert(isConsistent());
}
/// Assignment operator.
template < class S >
VectorBase<R>& operator=(const VectorBase<S>& vec)
{
if( (VectorBase<S>*)this != &vec )
{
assert(dim() == vec.dim());
for( int i = 0; i < dimen; i++ )
val[i] = vec[i];
assert(isConsistent());
}
return *this;
}
/// Assignment operator.
VectorBase<R>& operator=(const VectorBase<R>& vec)
{
if( this != &vec )
{
assert(dim() == vec.dim());
for( int i = 0; i < dimen; i++ )
val[i] = vec[i];
assert(isConsistent());
}
return *this;
}
/// scale and assign
VectorBase<Real>& scaleAssign(int scaleExp, const VectorBase<Real>& vec)
{
if( this != &vec )
{
assert(dim() == vec.dim());
for( int i = 0; i < dimen; i++ )
val[i] = spxLdexp(vec[i], scaleExp);
assert(isConsistent());
}
return *this;
}
/// scale and assign
VectorBase<Real>& scaleAssign(const int* scaleExp, const VectorBase<Real>& vec, bool negateExp = false)
{
if( this != &vec )
{
assert(dim() == vec.dim());
if( negateExp)
{
for( int i = 0; i < dimen; i++ )
val[i] = spxLdexp(vec[i], -scaleExp[i]);
}
else
{
for( int i = 0; i < dimen; i++ )
val[i] = spxLdexp(vec[i], scaleExp[i]);
}
assert(isConsistent());
}
return *this;
}
/// Assignment operator.
/** Assigning an SVectorBase to a VectorBase using operator=() will set all values to 0 except the nonzeros of \p vec.
* This is diffent in method assign().
*/
template < class S >
VectorBase<R>& operator=(const SVectorBase<S>& vec);
/// Assignment operator.
/** Assigning an SSVectorBase to a VectorBase using operator=() will set all values to 0 except the nonzeros of \p
* vec. This is diffent in method assign().
*/
/**@todo do we need this also in non-template version, because SSVectorBase can be automatically cast to VectorBase? */
template < class S >
VectorBase<R>& operator=(const SSVectorBase<S>& vec);
/// Assign values of \p vec.
/** Assigns all nonzeros of \p vec to the vector. All other values remain unchanged. */
template < class S >
VectorBase<R>& assign(const SVectorBase<S>& vec);
/// Assign values of \p vec.
/** Assigns all nonzeros of \p vec to the vector. All other values remain unchanged. */
template < class S >
VectorBase<R>& assign(const SSVectorBase<S>& vec);
//@}
// ------------------------------------------------------------------------------------------------------------------
/**@name Access */
//@{
/// Dimension of vector.
int dim() const
{
return dimen;
}
/// Return \p n 'th value by reference.
R& operator[](int n)
{
assert(n >= 0 && n < dimen);
return val[n];
}
/// Return \p n 'th value.
const R& operator[](int n) const
{
assert(n >= 0 && n < dimen);
return val[n];
}
/// Equality operator.
friend bool operator==(const VectorBase<R>& vec1, const VectorBase<R>& vec2)
{
if( &vec1 == &vec2 )
return true;
else if( vec1.dim() != vec2.dim() )
return false;
else
{
for( int i = 0; i < vec1.dim(); i++ )
{
if( vec1[i] != vec2[i] )
return false;
}
}
return true;
}
//@}
// ------------------------------------------------------------------------------------------------------------------
/**@name Arithmetic operations */
//@{
/// Set vector to 0.
void clear()
{
if( dimen > 0 )
{
for( int i = 0; i < dimen; i++ )
val[i] = 0;
}
}
/// Addition.
template < class S >
VectorBase<R>& operator+=(const VectorBase<S>& vec)
{
assert(dim() == vec.dim());
assert(dim() == dimen);
for( int i = 0; i < dimen; i++ )
val[i] += vec[i];
return *this;
}
/// Addition.
template < class S >
VectorBase<R>& operator+=(const SVectorBase<S>& vec);
/// Addition.
template < class S >
VectorBase<R>& operator+=(const SSVectorBase<S>& vec);
/// Subtraction.
template < class S >
VectorBase<R>& operator-=(const VectorBase<S>& vec)
{
assert(dim() == vec.dim());
assert(dim() == dimen);
for( int i = 0; i < dimen; i++ )
val[i] -= vec[i];
return *this;
}
/// Subtraction.
template < class S >
VectorBase<R>& operator-=(const SVectorBase<S>& vec);
/// Subtraction.
template < class S >
VectorBase<R>& operator-=(const SSVectorBase<S>& vec);
/// Scaling.
template < class S >
VectorBase<R>& operator*=(const S& x)
{
assert(dim() == dimen);
for( int i = 0; i < dimen; i++ )
val[i] *= x;
return *this;
}
/// Division.
template < class S >
VectorBase<R>& operator/=(const S& x)
{
assert(x != 0);
for( int i = 0; i < dim(); i++ )
val[i] /= x;
return *this;
}
/// Inner product.
R operator*(const VectorBase<R>& vec) const
{
assert(vec.dim() == dimen);
R x = 0.0;
for( int i = 0; i < dimen; i++ )
x += val[i] * vec.val[i];
return x;
}
/// Inner product.
R operator*(const SVectorBase<R>& vec) const;
/// Inner product.
R operator*(const SSVectorBase<R>& vec) const;
/// Maximum absolute value, i.e., infinity norm.
R maxAbs() const
{
assert(dim() > 0);
assert(dim() == dimen);
R maxi = 0.0;
for( int i = 0; i < dimen; i++ )
{
R x = spxAbs(val[i]);
if( x > maxi )
maxi = x;
}
assert(maxi >= 0.0);
return maxi;
}
/// Minimum absolute value.
R minAbs() const
{
assert(dim() > 0);
assert(dim() == dimen);
R mini = spxAbs(val[0]);
for( int i = 1; i < dimen; i++ )
{
R x = spxAbs(val[i]);
if( x < mini )
mini = x;
}
assert(mini >= 0.0);
return mini;
}
/// Floating point approximation of euclidian norm (without any approximation guarantee).
Real length() const
{
return spxSqrt((Real)length2());
}
/// Squared norm.
R length2() const
{
return (*this) * (*this);
}
/// Addition of scaled vector.
template < class S, class T >
VectorBase<R>& multAdd(const S& x, const VectorBase<T>& vec)
{
assert(vec.dim() == dimen);
for( int i = 0; i < dimen; i++ )
val[i] += x * vec.val[i];
return *this;
}
/// Addition of scaled vector.
template < class S, class T >
VectorBase<R>& multAdd(const S& x, const SVectorBase<T>& vec);
/// Subtraction of scaled vector.
template < class S, class T >
VectorBase<R>& multSub(const S& x, const SVectorBase<T>& vec);
/// Addition of scaled vector.
template < class S, class T >
VectorBase<R>& multAdd(const S& x, const SSVectorBase<T>& vec);
//@}
// ------------------------------------------------------------------------------------------------------------------
/**@name Utilities */
//@{
/// Conversion to C-style pointer.
/** This function serves for using a VectorBase in an C-style function. It returns a pointer to the first value of
* the array.
*
* @todo check whether this non-const c-style access should indeed be public
*/
R* get_ptr()
{
return val;
}
/// Conversion to C-style pointer.
/** This function serves for using a VectorBase in an C-style function. It returns a pointer to the first value of
* the array.
*/
const R* get_const_ptr() const
{
return val;
}
/// Consistency check.
bool isConsistent() const
{
#ifdef ENABLE_CONSISTENCY_CHECKS
if( dim() > 0 && val == 0 )
return MSGinconsistent("VectorBase");
#endif
return true;
}
//@}
};
/// Assignment operator (specialization for Real).
template <>
inline
VectorBase<Real>& VectorBase<Real>::operator=(const VectorBase<Real>& vec)
{
if( this != &vec )
{
assert(dim() == vec.dim());
memcpy(val, vec.val, (unsigned int)dimen*sizeof(Real));
assert(isConsistent());
}
return *this;
}
/// Assignment operator (specialization for Real).
template <>
template <>
inline
VectorBase<Real>& VectorBase<Real>::operator=(const VectorBase<Rational>& vec)
{
if( (VectorBase<Rational>*)this != &vec )
{
assert(dim() == vec.dim());
for( int i = 0; i < dimen; i++ )
val[i] = Real(vec[i]);
assert(isConsistent());
}
return *this;
}
/// Set vector to 0 (specialization for Real).
template<>
inline
void VectorBase<Real>::clear()
{
if( dimen > 0 )
memset(val, 0, (unsigned int)dimen * sizeof(Real));
}
#ifndef SOPLEX_LEGACY
/// Inner product.
template<>
inline
Rational VectorBase<Rational>::operator*(const VectorBase<Rational>& vec) const
{
assert(vec.dim() == dimen);
if( dimen <= 0 || vec.dim() <= 0 )
return 0;
Rational x = val[0];
x *= vec.val[0];
for( int i = 1; i < dimen && i < vec.dim(); i++ )
x.addProduct(val[i], vec.val[i]);
return x;
}
#endif
} // namespace soplex
#endif // _VECTORBASE_H_
|
LiangliangNan/PolyFit
|
3rd_soplex/src/vectorbase.h
|
C
|
gpl-3.0
| 14,029
|
#pragma once
#define __MILK_HPP
#include "milk/ast/ast_node.hpp"
#include "milk/ast/ast_symbol.hpp"
#include "milk/ast/ast_type.hpp"
#include "milk/ast/ast_expr.hpp"
#include "milk/ast/ast_bin_expr.hpp"
#include "milk/ast/ast_namespace.hpp"
#include "milk/ast/ast_func.hpp"
#include "milk/ast/ast_var.hpp"
#include "milk/ast/ast_str_lit.hpp"
#include "milk/ast/ast_int_lit.hpp"
#include "milk/ast/ast_call.hpp"
#include "milk/ast/ast_sym_ref.hpp"
#include "milk/ast/ast_var_ref.hpp"
#include "milk/ast/ast_stmt.hpp"
#include "milk/ast/ast_block.hpp"
#include "milk/ast/ast_ret_stmt.hpp"
#include "milk/io/file.hpp"
#include "milk/io/file_ref.hpp"
#include "milk/parser/lexer.hpp"
#include "milk/parser/visitor.hpp"
#include "milk/parser/parser.hpp"
|
Richard-W/milk
|
include/milk.hpp
|
C++
|
gpl-3.0
| 753
|
#include "il2cpp-config.h"
#include "icalls/mscorlib/System.Reflection/ParameterInfo.h"
#include "vm/Exception.h"
#include "il2cpp-object-internals.h"
#include "il2cpp-class-internals.h"
namespace il2cpp
{
namespace icalls
{
namespace mscorlib
{
namespace System
{
namespace Reflection
{
int32_t ParameterInfo::GetMetadataToken(Il2CppReflectionParameter* self)
{
//ReturnParameter Parameter infos are constructed at runtime.
if (self->PositionImpl == -1)
return 0x8000000; // This is what mono returns as a fixed value.
Il2CppReflectionMethod* method = (Il2CppReflectionMethod*)self->MemberImpl;
const ::ParameterInfo* info = &method->method->parameters[self->PositionImpl];
return (int32_t)info->token;
}
Il2CppArray* ParameterInfo::GetTypeModifiers(void* /* System.Reflection.ParameterInfo */ self, bool optional)
{
NOT_SUPPORTED_IL2CPP(ParameterInfo::GetTypeModifiers, "This icall is not supported by il2cpp.");
return 0;
}
} /* namespace Reflection */
} /* namespace System */
} /* namespace mscorlib */
} /* namespace icalls */
} /* namespace il2cpp */
|
SelfieSticks/TowerBloCF
|
The Project/Il2CppOutputProject/IL2CPP/libil2cpp/icalls/mscorlib/System.Reflection/ParameterInfo.cpp
|
C++
|
gpl-3.0
| 1,155
|
/*
*
* This file is part of the SIRIUS library for analyzing MS and MS/MS data
*
* Copyright (C) 2013-2020 Kai Dührkop, Markus Fleischauer, Marcus Ludwig, Martin A. Hoffman, Fleming Kretschmer and Sebastian Böcker,
* Chair of Bioinformatics, Friedrich-Schilller University.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 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 General Public License along with SIRIUS. If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>
*/
package de.unijena.bioinf.FragmentationTreeConstruction.computation.scoring;
import de.unijena.bioinf.ChemistryBase.algorithm.ParameterHelper;
import de.unijena.bioinf.ChemistryBase.data.DataDocument;
import de.unijena.bioinf.ChemistryBase.math.ByMedianEstimatable;
import de.unijena.bioinf.ChemistryBase.math.ParetoDistribution;
import de.unijena.bioinf.ChemistryBase.math.RealDistribution;
import de.unijena.bioinf.ChemistryBase.ms.MedianNoiseIntensity;
import de.unijena.bioinf.sirius.ProcessedInput;
import de.unijena.bioinf.sirius.ProcessedPeak;
import java.util.List;
public class ClippedPeakIsNoiseScorer implements PeakScorer {
private ByMedianEstimatable<? extends RealDistribution> distribution;
private double beta;
public ByMedianEstimatable<? extends RealDistribution> getDistribution() {
return distribution;
}
public void setDistribution(ByMedianEstimatable<? extends RealDistribution> distribution) {
this.distribution = distribution;
}
public ClippedPeakIsNoiseScorer() {
this(ParetoDistribution.getMedianEstimator(0.005));
}
public ClippedPeakIsNoiseScorer(ByMedianEstimatable<? extends RealDistribution> distribution) {
this.distribution = distribution;
}
@Override
public void score(List<ProcessedPeak> peaks, ProcessedInput input, double[] scores) {
final RealDistribution estimatedDistribution = distribution.extimateByMedian(
input.getExperimentInformation().getAnnotationOrDefault(MedianNoiseIntensity.class).value);
double maxIntensity = 0d;
for (ProcessedPeak p : input.getMergedPeaks()) maxIntensity = Math.max(p.getRelativeIntensity(), maxIntensity);
if (maxIntensity<=0) return;
final double clipping = 1d - estimatedDistribution.getCumulativeProbability(1d);
for (int i=0; i < peaks.size(); ++i) {
if (peaks.get(i).getRelativeIntensity()<=0) continue;
final double peakIntensity = peaks.get(i).getRelativeIntensity()/maxIntensity;
final double noiseProbability = 1d-estimatedDistribution.getCumulativeProbability(peakIntensity);
final double clippingCorrection = (noiseProbability-clipping+beta)/(1-clipping+beta);
scores[i] -= Math.log(clippingCorrection);
}
}
@Override
public <G, D, L> void importParameters(ParameterHelper helper, DataDocument<G, D, L> document, D dictionary) {
this.distribution = (ByMedianEstimatable<RealDistribution>)helper.unwrap(document, document.getFromDictionary(dictionary, "distribution"));
this.beta = document.getDoubleFromDictionary(dictionary, "beta");
}
@Override
public <G, D, L> void exportParameters(ParameterHelper helper, DataDocument<G, D, L> document, D dictionary) {
document.addToDictionary(dictionary, "distribution", helper.wrap(document,distribution));
document.addToDictionary(dictionary, "beta", beta);
}
}
|
kaibioinfo/sirius
|
fragmentation_tree/fragmentation_tree_construction/src/main/java/de/unijena/bioinf/FragmentationTreeConstruction/computation/scoring/ClippedPeakIsNoiseScorer.java
|
Java
|
gpl-3.0
| 3,944
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Geda3.LineItem.draw – Gschem3 – Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">Geda3.LineItem.draw – Gschem3 Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">Gschem3</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="Geda3.html">Geda3</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="class"><a href="Geda3.LineItem.html">LineItem</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="constant"><a href="Geda3.LineItem.TYPE_ID.html">TYPE_ID</a></li>
<li class="property"><a href="Geda3.LineItem.color.html">color</a></li>
<li class="property"><a href="Geda3.LineItem.line_style.html">line_style</a></li>
<li class="property"><a href="Geda3.LineItem.width.html">width</a></li>
<li class="creation_method"><a href="Geda3.LineItem.LineItem.html">LineItem</a></li>
<li class="creation_method"><a href="Geda3.LineItem.LineItem.with_points.html">LineItem.with_points</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.calculate_bounds.html">calculate_bounds</a></li>
<li class="method"><a href="Geda3.LineItem.create_grips.html">create_grips</a></li>
<li class="virtual_method">draw</li>
<li class="method"><a href="Geda3.LineItem.get_point.html">get_point</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.intersects_box.html">intersects_box</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.invalidate_on.html">invalidate_on</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.mirror_x.html">mirror_x</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.mirror_y.html">mirror_y</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.read_with_params.html">read_with_params</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.rotate.html">rotate</a></li>
<li class="method"><a href="Geda3.LineItem.set_point.html">set_point</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.shortest_distance.html">shortest_distance</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.translate.html">translate</a></li>
<li class="virtual_method"><a href="Geda3.LineItem.write.html">write</a></li>
<li class="field"><a href="Geda3.LineItem.b_x.html">b_x</a></li>
<li class="field"><a href="Geda3.LineItem.b_y.html">b_y</a></li>
</ul>
</div>
<div class="site_content">
<h1 class="main_title">draw</h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="main_code_definition"><span class="main_keyword">public</span> <span class="main_keyword">override</span> <span class="main_keyword">void</span> <b><span class="virtual_method">draw</span></b> (<span class="main_type"><a href="Geda3.SchematicPainter.html" class="abstract_class">SchematicPainter</a></span> painter, <span class="main_basic_type"><span class="struct">bool</span></span> reveal, <span class="main_basic_type"><span class="struct">bool</span></span> selected)
</div>
<div class="description">
<p>Draw this item using the given painter</p>
</div>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="https://wiki.gnome.org/Projects/Valadoc"><kbd>valadoc</kbd></a>
</div>
</body>
</html>
|
ehennes775/gschem3
|
docs/dev/Gschem3/Geda3.LineItem.draw.html
|
HTML
|
gpl-3.0
| 4,060
|
package own.allen.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilelist extends HttpServlet {
/**
* Constructor of the object.
*/
public MyFilelist() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取上传文件的目录
String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload");
//存储要下载的文件名
Map<String,String> fileNameMap = new HashMap<String,String>();
//递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中
listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一个文件也可以代表一个目录
//将Map集合发送到listfile.jsp页面进行显示
request.setAttribute("fileNameMap", fileNameMap);
request.getRequestDispatcher("/test/testDownload.jsp").forward(request, response);
}
/**
* @Method: listfile
* @Description: 递归遍历指定目录下的所有文件
* @Anthor:孤傲苍狼
* @param file 即代表一个文件,也代表一个文件目录
* @param map 存储文件名的Map集合
*/
public void listfile(File file,Map<String,String> map){
//如果file代表的不是一个文件,而是一个目录
if(!file.isFile()){
//列出该目录下的所有文件和目录
File files[] = file.listFiles();
//遍历files[]数组
for(File f : files){
//递归
listfile(f,map);
}
}else{
/**
* 处理文件名,上传后的文件是以uuid_文件名的形式去重新命名的,去除文件名的uuid_部分
file.getName().indexOf("_")检索字符串中第一次出现"_"字符的位置,如果文件名类似于:9349249849-88343-8344_阿_凡_达.avi
那么file.getName().substring(file.getName().indexOf("_")+1)处理之后就可以得到阿_凡_达.avi部分
*/
String realName = file.getName().substring(file.getName().indexOf("_")+1);
//file.getName()得到的是文件的原始名称,这个名称是唯一的,因此可以作为key,realName是处理过后的名称,有可能会重复
map.put(file.getName(), realName);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
|
lzs0420/mytest
|
testForJava/src/own/allen/servlet/MyFilelist.java
|
Java
|
gpl-3.0
| 3,895
|
speaker-test -t sine -f 1000 -l 1
|
cyanboy/IoT-Hackathon
|
sound_check/sound.sh
|
Shell
|
gpl-3.0
| 33
|
package com.system.service;
import com.readinglife.framework.service.IBaseService;
public interface InitService extends IBaseService {
public void initPrivil();
public void initBaseCode();
}
|
a254629486/mis-readinglife
|
src/main/java/com/system/service/InitService.java
|
Java
|
gpl-3.0
| 200
|
/* $Id$ */
/* Copyright (c) 2013-2021 Pierre Pronchery <khorben@defora.org> */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* This file is part of DeforaOS Desktop Player */
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <libintl.h>
#include <gtk/gtk.h>
#include <Desktop.h>
#include "../include/Player.h"
#include "../config.h"
#define _(string) gettext(string)
/* constants */
#ifndef PROGNAME_PLAYERCTL
# define PROGNAME_PLAYERCTL "playerctl"
#endif
#ifndef PREFIX
# define PREFIX "/usr/local"
#endif
#ifndef DATADIR
# define DATADIR PREFIX "/share"
#endif
#ifndef LOCALEDIR
# define LOCALEDIR DATADIR "/locale"
#endif
/* playerctl */
/* private */
/* prototypes */
static int _playerctl(PlayerMessage message, unsigned int arg1);
static int _error(char const * message, int ret);
static int _usage(void);
/* functions */
/* playerctl */
static int _playerctl(PlayerMessage message, unsigned int arg1)
{
desktop_message_send(PLAYER_CLIENT_MESSAGE, message, arg1, 0);
return 0;
}
/* error */
static int _error(char const * message, int ret)
{
fputs(PROGNAME_PLAYERCTL ": ", stderr);
perror(message);
return ret;
}
/* usage */
static int _usage(void)
{
fprintf(stderr, _("Usage: %s -FMmNPRpsu\n"), PROGNAME_PLAYERCTL);
return 1;
}
/* public */
/* functions */
/* main */
int main(int argc, char * argv[])
{
int o;
int message = -1;
unsigned int arg1 = 0;
if(setlocale(LC_ALL, "") == NULL)
_error("setlocale", 1);
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
gtk_init(&argc, &argv);
while((o = getopt(argc, argv, "FMmNPRpsu")) != -1)
switch(o)
{
case 'F':
message = PLAYER_MESSAGE_FORWARD;
arg1 = 0;
break;
case 'm':
message = PLAYER_MESSAGE_MUTE;
arg1 = PLAYER_MUTE_MUTE;
break;
case 'M':
message = PLAYER_MESSAGE_PREVIOUS;
arg1 = 0;
break;
case 'N':
message = PLAYER_MESSAGE_NEXT;
arg1 = 0;
break;
case 'P':
message = PLAYER_MESSAGE_PAUSE;
arg1 = 0;
break;
case 'R':
message = PLAYER_MESSAGE_REWIND;
arg1 = 0;
break;
case 'p':
message = PLAYER_MESSAGE_PLAY;
arg1 = 0;
break;
case 's':
message = PLAYER_MESSAGE_STOP;
arg1 = 0;
break;
case 'u':
message = PLAYER_MESSAGE_MUTE;
arg1 = PLAYER_MUTE_UNMUTE;
break;
default:
return _usage();
}
if(argc != optind || message < 0)
return _usage();
return (_playerctl(message, arg1) == 0) ? 0 : 2;
}
|
DeforaOS/Player
|
src/playerctl.c
|
C
|
gpl-3.0
| 3,776
|
# encoding: utf-8
class ApplicationController < ActionController::Base
include Cms::Controller::Public
helper FormHelper
helper LinkHelper
protect_from_forgery # :secret => '1f0d667235154ecf25eaf90055d99e99'
before_filter :initialize_application
# rescue_from Exception, :with => :rescue_exception
def initialize_application
if Core.publish
Page.mobile = nil
unset_mobile
else
Page.mobile = true if request.mobile?
set_mobile if Page.mobile? && !request.mobile?
end
return false if Core.dispatched?
return Core.dispatched
end
def query(params = nil)
Util::Http::QueryString.get_query(params)
end
def skip_layout
self.class.layout 'base'
end
def send_mail(mail_fr, mail_to, subject, message)
return false if mail_fr.blank?
return false if mail_to.blank?
Sys::Lib::Mailer::Base.deliver_default(mail_fr, mail_to, subject, message)
end
def send_download
#
end
def set_mobile
def request.mobile
Jpmobile::Mobile::Au.new(nil)
end
end
def unset_mobile
def request.mobile
nil
end
end
private
def rescue_action(error)
case error
when ActionController::InvalidAuthenticityToken
http_error(422, "Invalid Authenticity Token")
when ActionView::MissingTemplate
RAILS_ENV == "production" ? http_error(404) : super
else
super
end
end
## Production && local
def rescue_action_in_public(exception)
http_error(500, nil)
end
def http_error(status, message = nil)
erase_render_results rescue nil
Page.error = status
if status == 404
message ||= "ページが見つかりません。"
end
name = ActionController::StatusCodes::STATUS_CODES[status]
name = " #{name}" if name
message = " ( #{message} )" if message
message = "#{status}#{name}#{message}"
if Core.mode =~ /^(admin|script)$/ && status != 404
error_log("#{status} #{request.env['REQUEST_URI']}") if status != 404
return respond_to do |format|
format.html { render :status => status, :text => "<p>#{message}</p>", :layout => "admin/cms/error" }
format.xml { render :status => status, :xml => "<errors><error>#{message}</error></errors>" }
end
end
## Render
html = nil
if Page.site && FileTest.exist?("#{Page.site.public_path}/#{status}.html")
html = ::File.new("#{Page.site.public_path}/#{status}.html").read
elsif Core.site && FileTest.exist?("#{Core.site.public_path}/#{status}.html")
html = ::File.new("#{Core.site.public_path}/#{status}.html").read
elsif FileTest.exist?("#{Rails.public_path}/#{status}.html")
html = ::File.new("#{Rails.public_path}/#{status}.html").read
elsif FileTest.exist?("#{Rails.public_path}/500.html")
html = ::File.new("#{Rails.public_path}/500.html").read
else
html = "<html>\n<head></head>\n<body>\n<p>#{message}</p>\n</body>\n</html>\n"
end
if request.format.to_s =~ /xml/i
render :status => status, :xml => "<errors><error>#{message}</error></errors>"
else
render :status => status, :inline => html
end
end
# def rescue_exception(exception)
# log = exception.to_s
# log += "\n" + exception.backtrace.join("\n") if Rails.env.to_s == 'production'
# error_log(log)
#
# if Core.mode =~ /^(admin|script)$/
# html = %Q(<div style="padding: 0px 20px 10px; color: #e00; font-weight: bold; line-height: 1.8;">)
# html += %Q(エラーが発生しました。<br />#{exception} <#{exception.class}>)
# html += %Q(</div>)
# if Rails.env.to_s != 'production'
# html += %Q(<div style="padding: 15px 20px; border-top: 1px solid #ccc; color: #800; line-height: 1.4;">)
# html += exception.backtrace.join("<br />")
# html += %Q(</div>)
# end
# render :inline => html, :layout => "admin/cms/error", :status => 500
# else
# http_error 500
# end
# end
end
|
yamamoto-febc/jruby-joruri
|
app/controllers/application.rb
|
Ruby
|
gpl-3.0
| 4,020
|
#!/bin/sh
apt-get install build-essential bison m4 texinfo make patch perl sed tar gawk
|
uraymeiviar/artos
|
build/crossbuild/get-prerequisite.sh
|
Shell
|
gpl-3.0
| 88
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using Tools.Extensions;
namespace Tools.Extensions.Tests.DictionaryExtensions
{
[TestFixture]
public class GetValueOrDefaultTests
{
Mock<IDictionary<int, int>> _intDictionaryMock;
int outInt;
[SetUp]
public void Setup()
{
_intDictionaryMock = new Mock<IDictionary<int, int>>();
_intDictionaryMock.Setup(x => x.TryGetValue(It.IsNotIn(1), out outInt))
.Returns(false);
outInt = 1;
List<int> d2 = new List<int>() { 1, 2, 3 };
_intDictionaryMock.Setup(x => x.TryGetValue(1, out outInt))
.Returns(true);
}
[Test]
public void GetValueOrDefault_GivesValueIfKeyExists()
{
const int key = 1;
Assert.That(_intDictionaryMock.Object.GetValueOrDefault(key), Is.EqualTo(outInt));
_intDictionaryMock.Verify(x => x.TryGetValue(key, out outInt), Times.Once);
}
[Test]
public void GetValueOrDefault_GivesDefaultValueIfKeyNotExists()
{
const int key = 2;
Assert.That(_intDictionaryMock.Object.GetValueOrDefault(key), Is.EqualTo(default(int)));
_intDictionaryMock.Verify(x => x.TryGetValue(key, out outInt), Times.Once);
}
[Test]
public void GetValueOrDefault_GivesEnteredDefaultValueIfKeyNotExists()
{
const int defaultValue = 666;
const int key = 2;
Assert.That(_intDictionaryMock.Object.GetValueOrDefault(key, defaultValue), Is.EqualTo(defaultValue));
_intDictionaryMock.Verify(x => x.TryGetValue(key, out outInt), Times.Once);
}
[Test]
public void GetValueOrDefault_RetursNull()
{
const int key = 2;
Assert.That(new Dictionary<int, List<int>>().GetValueOrDefault(key), Is.Null);
Assert.That(new Dictionary<int, List<int>>() { { 1, new List<int>() } }.GetValueOrDefault(1), Is.Not.Null);
}
}
}
|
raarh/c-sharp-extensions
|
Tools.Extensions.Tests/GetValueOrDefaultTests.cs
|
C#
|
gpl-3.0
| 2,150
|
#!/usr/bin/env python
# coding=utf-8
import sys
import argparse
parser = argparse.ArgumentParser(
description='convert a non-standord hostname like xx-xx-[1-3] to a '
'expansion state',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Sample:
$ ./converter.py xxx-xxx-\[1-3\]
xxx-xxx-1
xxx-xxx-2
xxx-xxx-3
Tips: You can pass many args behind the command,and you need to not forget to
escape the character of [ and ]
""")
parser.add_argument(
'hostname_pattern',
help='',
type=str,
nargs='+')
args = parser.parse_args()
if __name__ == '__main__':
for arg in args.hostname_pattern:
basestr=arg.split('-')
prefix='-'.join(basestr[:-2])
range_li=basestr[-2:]
start_num=int(range_li[0][1:])
end_num=int(range_li[1][:-1])
for i in range(start_num,end_num+1):
print prefix + '-' + str(i)
|
supersu097/Mydailytools
|
converter.py
|
Python
|
gpl-3.0
| 905
|
([C++](Cpp.md)) std::ostream\_iterator
=======================================
An [iterator](CppIterator.md).
Example: [CoutVector](CppCoutVector.md)
----------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
` #include <vector> #include <iterator> #include <iostream> #include <ostream> //From http://www.richelbilderbeek.nl/CppCoutVector.htm template <class T> void CoutVector(const std::vector<T>& v) { std::copy(v.begin(),v.end(),std::ostream_iterator<T>(std::cout,"\n")); }`
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
richelbilderbeek/cpp
|
content/CppStdOstream_iterator.md
|
Markdown
|
gpl-3.0
| 1,102
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::LangmuirHinshelwoodReactionRate
Description
Power series reaction rate.
SourceFiles
LangmuirHinshelwoodReactionRateI.H
\*---------------------------------------------------------------------------*/
#ifndef LangmuirHinshelwoodReactionRate_H
#define LangmuirHinshelwoodReactionRate_H
#include "scalarField.H"
#include "typeInfo.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class LangmuirHinshelwoodReactionRate Declaration
\*---------------------------------------------------------------------------*/
class LangmuirHinshelwoodReactionRate
{
// Private data
static const label n_ = 5;
scalar A_[n_];
scalar Ta_[n_];
label co_;
label c3h6_;
label no_;
public:
// Constructors
//- Construct from components
inline LangmuirHinshelwoodReactionRate
(
const scalar A[],
const scalar Ta[],
const label co,
const label c3h6,
const label no
);
//- Construct from Istream
inline LangmuirHinshelwoodReactionRate
(
const speciesTable& species,
Istream& is
);
// Member Functions
//- Return the type name
static word type()
{
return "LangmuirHinshelwood";
}
inline scalar operator()
(
const scalar T,
const scalar p,
const scalarField& c
) const;
// Ostream Operator
inline friend Ostream& operator<<
(
Ostream&,
const LangmuirHinshelwoodReactionRate&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "LangmuirHinshelwoodReactionRateI.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/thermophysicalModels/specie/reaction/reactionRate/LangmuirHinshelwood/LangmuirHinshelwoodReactionRate.H
|
C++
|
gpl-3.0
| 3,344
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Backpack Crud Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the CRUD interface.
| You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
// Forms
'save_action_save_and_new' => 'Enregistrer et créer un nouveau',
'save_action_save_and_edit' => 'Enregistrer et éditer',
'save_action_save_and_back' => 'Enregistrer et retour',
'save_action_changed_notification' => 'Action par défaut changée',
// Create form
'add' => 'Ajouter',
'back_to_all' => 'Retour à la liste ',
'cancel' => 'Annuler',
'add_a_new' => 'Ajouter un nouvel élément ',
// Edit form
'edit' => 'Modifier',
'save' => 'Enregistrer',
// Revisions
'revisions' => 'Historique',
'no_revisions' => 'Pas d’historique',
'created_this' => 'a créé',
'changed_the' => 'a modifié',
'restore_this_value' => 'Restaurer cette valeur',
'from' => 'De',
'to' => 'À',
'undo' => 'Annuler',
'revision_restored' => 'Valeur restaurée',
'guest_user' => 'Utilisateur invité',
// Translatable models
'edit_translations' => 'EDITER LES TRADUCTIONS',
'language' => 'Langue',
// CRUD table view
'all' => 'Tous les ',
'in_the_database' => 'dans la base de données',
'list' => 'Liste',
'actions' => 'Actions',
'preview' => 'Aperçu',
'delete' => 'Supprimer',
'admin' => 'Administration',
'details_row' => 'Ligne de détail. Modifiez la à volonté.',
'details_row_loading_error' => 'Une erreur est survenue en chargeant les détails. Veuillez réessayer.',
// Confirmation messages and bubbles
'delete_confirm' => 'Souhaitez-vous réellement supprimer cet élément?',
'delete_confirmation_title' => 'Élément supprimé',
'delete_confirmation_message' => 'L’élément a été supprimé avec succès.',
'delete_confirmation_not_title' => 'NON supprimé',
'delete_confirmation_not_message' => 'Une erreur est survenue. Votre élément n’a peut-être pas été effacé.',
'delete_confirmation_not_deleted_title' => 'Non supprimé',
'delete_confirmation_not_deleted_message' => 'Aucune modification. Votre élément a été conservé.',
'ajax_error_title' => 'Erreur',
'ajax_error_text' => 'Erreur lors du chargement. Merci de réactualiser la page.',
// DataTables translation
'emptyTable' => 'Aucune donnée à afficher.',
'info' => 'Affichage des éléments _START_ à _END_ sur _TOTAL_',
'infoEmpty' => 'Affichage des éléments 0 à 0 sur 0',
'infoFiltered' => '(filtré à partir de _MAX_ éléments au total)',
'infoPostFix' => '',
'thousands' => ',',
'lengthMenu' => '_MENU_ enregistrements par page',
'loadingRecords' => 'Chargement...',
'processing' => 'Traitement...',
'search' => 'Recherche : ',
'zeroRecords' => 'Aucun enregistrement correspondant trouvé',
'paginate' => [
'first' => 'Premier',
'last' => 'Dernier',
'next' => 'Suivant',
'previous' => 'Précédent',
],
'aria' => [
'sortAscending' => ': activez pour trier la colonne par ordre croissant',
'sortDescending' => ': activez pour trier la colonne par ordre décroissant',
],
'export' => [
'export' => 'Exporter',
'copy' => 'Copier',
'excel' => 'Excel',
'csv' => 'CSV',
'pdf' => 'PDF',
'print' => 'Imprimer',
'column_visibility' => 'Affichage des colonnes',
],
// global crud - errors
'unauthorized_access' => 'Accès non autorisé - vous n’avez pas les droits nécessaires à la consultation de cette page.',
'please_fix' => 'Veuillez corriger les erreurs suivantes :',
// global crud - success / error notification bubbles
'insert_success' => 'L’élément a été ajouté avec succès.',
'update_success' => 'L’élément a été modifié avec succès.',
// CRUD reorder view
'reorder' => 'Réordonner',
'reorder_text' => 'Utilisez le glisser-déposer pour réordonner.',
'reorder_success_title' => 'Fait',
'reorder_success_message' => 'L’ordre a été enregistré.',
'reorder_error_title' => 'Erreur',
'reorder_error_message' => 'L’ordre n’a pas pu être enregistré.',
// CRUD yes/no
'yes' => 'Oui',
'no' => 'Non',
// CRUD filters navbar view
'filters' => 'Filtres',
'toggle_filters' => 'Activer les filtres',
'remove_filters' => 'Retirer les filtres',
// Fields
'browse_uploads' => 'Parcourir les fichier chargés',
'clear' => 'Effacer',
'page_link' => 'Lien de la page',
'page_link_placeholder' => 'http://example.com/votre-page',
'internal_link' => 'Lien interne',
'internal_link_placeholder' => 'Identifiant de lien interne. Ex: \'admin/page\' (sans guillemets) pour \':url\'',
'external_link' => 'Lien externe',
'choose_file' => 'Choisissez un fichier',
//Table field
'table_cant_add' => 'Impossible d’ajouter un nouveau :entity',
'table_max_reached' => 'Nombre maximum :max atteint',
// File manager
'file_manager' => 'Gestionnaire de fichiers',
];
|
lejubila/piGardenWeb
|
vendor/backpack/crud/src/resources/lang/fr_CA/crud.php
|
PHP
|
gpl-3.0
| 6,299
|
import java.util.Iterator;
public class MyArrayList<E> extends MyAbstactList<E>{
public static final int INITIAL_CAPACITY = 16;
private E[] data = (E[]) new Object[INITIAL_CAPACITY];
public MyArrayList() {}
public MyArrayList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
@Override
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--)
data[i + 1] = data[i];
data[index] = e;
size++;
}
private void ensureCapacity() {
if (size >= data.length) {
E[] newData = (E[])(new Object[size * 2 + 1]);
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
}
@Override
public void clear() {
data = (E[])new Object[INITIAL_CAPACITY];
size = 0;
}
@Override
public boolean contains(E e) {
for (int i = 0; i < size; i++)
if (e.equals(data[i])) return true;
return false;
}
@Override
public E get(int index) {
checkIndex(index);
return data[index];
}
private void checkIndex(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index " + index + " out of bounds");
}
@Override
public int indexOf(E e) {
for (int i = 0; i < size; i++)
if (e.equals(data[i])) return i;
return -1;
}
@Override
public int lastIndexOf(E e) {
for (int i = size - 1; i >= 0; i--)
if (e.equals(data[i])) return i;
return -1;
}
@Override
public E remove(int index) {
checkIndex(index);
E e = data[index];
for (int j = index; j < size - 1; j++)
data[j] = data[j + 1];
data[size - 1] = null;
size--;
return e;
}
@Override
public E set(int index, E e) {
checkIndex(index);
E old = data[index];
data[index] = e;
return old;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("[");
for (int i = 0; i < size; i++) {
result.append(data[i]);
if (i < size - 1) result.append(", ");
}
return result.toString() + "]";
}
public void trimToSize() {
if (size != data.length) {
E[] newData = (E[])(new Object[size]);
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
}
@Override
public Iterator<E> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<E> {
private int current = 0;
@Override
public boolean hasNext() {
return (current < size);
}
@Override
public E next() {
return data[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(current);
}
}
}
|
CovertHypnosis/Java
|
Implementing-List/MyArrayList.java
|
Java
|
gpl-3.0
| 2,566
|
const StitchMongoFixture = require('../fixtures/stitch_mongo_fixture');
import {getAuthenticatedClient} from '../testutil';
describe('Values V2', ()=>{
let test = new StitchMongoFixture();
let apps;
let app;
beforeAll(() => test.setup({createApp: false}));
afterAll(() => test.teardown());
beforeEach(async () =>{
let adminClient = await getAuthenticatedClient(test.userData.apiKey.key);
test.groupId = test.userData.group.groupId;
apps = await adminClient.v2().apps(test.groupId);
app = await apps.create({name: 'testname'});
appValues = adminClient.v2().apps(test.groupId).app(app._id).values();
});
afterEach(async () => {
await apps.app(app._id).remove();
});
let appValues;
const testValueName = 'testvaluename';
it('listing values should return empty list', async () => {
let values = await appValues.list();
expect(values).toEqual([]);
});
it('creating value should make it appear in list', async () => {
let value = await appValues.create({name: testValueName});
expect(value.name).toEqual(testValueName);
let values = await appValues.list();
expect(values).toHaveLength(1);
expect(values[0]).toEqual(value);
});
it('fetching a value returns deep value data', async () => {
let value = await appValues.create({name: testValueName, value: 'foo'});
const deepValue = await appValues.value(value._id).get();
expect(deepValue.value).toEqual('foo');
delete deepValue.value;
expect(value).toEqual(deepValue);
});
it('can update a value', async () => {
let value = await appValues.create({name: testValueName, value: 'foo'});
value.value = '"abcdefgh"';
await appValues.value(value._id).update(value);
const deepValue = await appValues.value(value._id).get();
expect(deepValue.value).toEqual('"abcdefgh"');
});
it('can delete a value', async () => {
let value = await appValues.create({name: testValueName});
expect(value.name).toEqual(testValueName);
let values = await appValues.list();
expect(values).toHaveLength(1);
await appValues.value(value._id).remove();
values = await appValues.list();
expect(values).toHaveLength(0);
});
});
|
cassiane/KnowledgePlatform
|
Implementacao/nodejs-tcc/node_modules/mongodb-stitch/test/admin/values.test.js
|
JavaScript
|
gpl-3.0
| 2,204
|
class SubscribeMailer < ApplicationMailer
default from: "info@korolevdmitry.ru"
def subscribe_email(subscriber)
@subscriber = subscriber
mail(to: @subscriber.email, subject: "New subscriber", cc: "8877024@gmail.com")
end
end
|
D7na/portfolio
|
app/mailers/subscribe_mailer.rb
|
Ruby
|
gpl-3.0
| 233
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
//
// Delta Calibrate Menu
//
#include "../../inc/MarlinConfigPre.h"
#if HAS_LCD_MENU && EITHER(DELTA_CALIBRATION_MENU, DELTA_AUTO_CALIBRATION)
#include "menu.h"
#include "../../module/delta.h"
#include "../../module/motion.h"
#if HAS_LEVELING
#include "../../feature/bedlevel/bedlevel.h"
#endif
#if ENABLED(EXTENSIBLE_UI)
#include "../../lcd/extui/ui_api.h"
#endif
void _man_probe_pt(const xy_pos_t &xy) {
if (!ui.wait_for_move) {
ui.wait_for_move = true;
do_blocking_move_to_xy_z(xy, Z_CLEARANCE_BETWEEN_PROBES);
ui.wait_for_move = false;
ui.synchronize();
move_menu_scale = _MAX(PROBE_MANUALLY_STEP, MIN_STEPS_PER_SEGMENT / float(DEFAULT_XYZ_STEPS_PER_UNIT));
ui.goto_screen(lcd_move_z);
}
}
#if ENABLED(DELTA_AUTO_CALIBRATION)
#include "../../gcode/gcode.h"
#if ENABLED(HOST_PROMPT_SUPPORT)
#include "../../feature/host_actions.h" // for host_prompt_do
#endif
float lcd_probe_pt(const xy_pos_t &xy) {
_man_probe_pt(xy);
ui.defer_status_screen();
TERN_(HOST_PROMPT_SUPPORT, host_prompt_do(PROMPT_USER_CONTINUE, PSTR("Delta Calibration in progress"), CONTINUE_STR));
TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired_P(PSTR("Delta Calibration in progress")));
wait_for_user_response();
ui.goto_previous_screen_no_defer();
return current_position.z;
}
#endif
#if ENABLED(DELTA_CALIBRATION_MENU)
#include "../../gcode/queue.h"
void _lcd_calibrate_homing() {
_lcd_draw_homing();
if (all_axes_homed()) ui.goto_previous_screen();
}
void _lcd_delta_calibrate_home() {
queue.inject_P(G28_STR);
ui.goto_screen(_lcd_calibrate_homing);
}
void _goto_tower_a(const float &a) {
xy_pos_t tower_vec = { cos(RADIANS(a)), sin(RADIANS(a)) };
_man_probe_pt(tower_vec * delta_calibration_radius());
}
void _goto_tower_x() { _goto_tower_a(210); }
void _goto_tower_y() { _goto_tower_a(330); }
void _goto_tower_z() { _goto_tower_a( 90); }
void _goto_center() { xy_pos_t ctr{0}; _man_probe_pt(ctr); }
#endif
void lcd_delta_settings() {
auto _recalc_delta_settings = []{
TERN_(HAS_LEVELING, reset_bed_level()); // After changing kinematics bed-level data is no longer valid
recalc_delta_settings();
};
START_MENU();
BACK_ITEM(MSG_DELTA_CALIBRATE);
EDIT_ITEM(float52sign, MSG_DELTA_HEIGHT, &delta_height, delta_height - 10, delta_height + 10, _recalc_delta_settings);
#define EDIT_ENDSTOP_ADJ(LABEL,N) EDIT_ITEM_P(float43, PSTR(LABEL), &delta_endstop_adj.N, -5, 5, _recalc_delta_settings)
EDIT_ENDSTOP_ADJ("Ex", a);
EDIT_ENDSTOP_ADJ("Ey", b);
EDIT_ENDSTOP_ADJ("Ez", c);
EDIT_ITEM(float52sign, MSG_DELTA_RADIUS, &delta_radius, delta_radius - 5, delta_radius + 5, _recalc_delta_settings);
#define EDIT_ANGLE_TRIM(LABEL,N) EDIT_ITEM_P(float43, PSTR(LABEL), &delta_tower_angle_trim.N, -5, 5, _recalc_delta_settings)
EDIT_ANGLE_TRIM("Tx", a);
EDIT_ANGLE_TRIM("Ty", b);
EDIT_ANGLE_TRIM("Tz", c);
EDIT_ITEM(float52sign, MSG_DELTA_DIAG_ROD, &delta_diagonal_rod, delta_diagonal_rod - 5, delta_diagonal_rod + 5, _recalc_delta_settings);
END_MENU();
}
void menu_delta_calibrate() {
const bool all_homed = all_axes_homed();
START_MENU();
BACK_ITEM(MSG_MAIN);
#if ENABLED(DELTA_AUTO_CALIBRATION)
GCODES_ITEM(MSG_DELTA_AUTO_CALIBRATE, PSTR("G33"));
#if ENABLED(EEPROM_SETTINGS)
ACTION_ITEM(MSG_STORE_EEPROM, ui.store_settings);
ACTION_ITEM(MSG_LOAD_EEPROM, ui.load_settings);
#endif
#endif
SUBMENU(MSG_DELTA_SETTINGS, lcd_delta_settings);
#if ENABLED(DELTA_CALIBRATION_MENU)
SUBMENU(MSG_AUTO_HOME, _lcd_delta_calibrate_home);
if (all_homed) {
SUBMENU(MSG_DELTA_CALIBRATE_X, _goto_tower_x);
SUBMENU(MSG_DELTA_CALIBRATE_Y, _goto_tower_y);
SUBMENU(MSG_DELTA_CALIBRATE_Z, _goto_tower_z);
SUBMENU(MSG_DELTA_CALIBRATE_CENTER, _goto_center);
}
#endif
END_MENU();
}
#endif // HAS_LCD_MENU && (DELTA_CALIBRATION_MENU || DELTA_AUTO_CALIBRATION)
|
tetious/Marlin
|
Marlin/src/lcd/menu/menu_delta_calibrate.cpp
|
C++
|
gpl-3.0
| 4,823
|
<!DOCTYPE html>
<html>
<head>
<title>Washington State Courts - Supreme Court Calendar </title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<link rel="icon" type="image/vnd.microsoft.icon" href="//www.courts.wa.gov/favicon.ico">
<noscript>
<link href="/css/layoutStylesv3.css" type=text/css rel=stylesheet />
<link href="/css/stylesheetv2.css" type=text/css rel=stylesheet />
<link href="/css/tabStyles.css" type=text/css rel=stylesheet />
<link href="/css/subsite_stylesv2.css" rel=stylesheet type=text/css />
</noscript>
<script language="JavaScript" src="/includes/AOCScripts.js" type="text/javascript"></script>
<script type="text/javascript" language="JavaScript1.2" src="/includes/stm31.js"></script>
<script src="/scripts/jquery-1.11.2.min.js" type="text/javascript" language="JavaScript"></script>
<script src="/js/modernizr-custom.min.js"></script>
<script src="/js/featureDetection.js"></script>
<script src="/js/jqueryForForm.js" type="text/javascript"></script>
<script src="/js/multiFileUpload.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/css/libraryStylesv2.css" />
<link rel="stylesheet" type="text/css" href="/css/layoutStylesv3.css" />
<link rel="stylesheet" type="text/css" href="/css/stylesheetv2.css" />
<link rel="stylesheet" type="text/css" href="/css/subsite_stylesv2.css" />
</head>
<body>
<div id="topLayout">
<div id="newLayout">
<div id="newPageLayout">
<a name="top"></a>
<div id="topheader">
<div id="left"><a href="/"><img src="/images/waCourtsLogo.png" border="0" alt="Welcome to Washington State Courts" /></a></div>
<div id="right">
<div class="socialMediaBar">
<ul>
<li><a href="/notifications/" title="Sign up for Notifications"><img src="/images/iconEmailBlue.png" alt="Sign up for Email Notifications" border="0" /></a></li>
<li><a href="/notifications/" title="Sign up for Notifications">Get Email Updates</a></li>
<li>|</li>
<li><a href="https://aoc.custhelp.com/"><img src="/images/iconHelp_flatBlueSm2.png" border="0" /></a></li>
<li><a href="https://aoc.custhelp.com/">FAQs & eService Center</a></li>
</ul>
</div>
<div class="topSearchArea">
<form method="post" action="/search/index.cfm?fa=search.start_search">
<input type="text" name="searchTerms" size="36" maxlength="256" placeholder="Search WA Courts Site" class="searchField" value="Search WA Courts Site"
onfocus="if (this.value=='Search WA Courts Site'){this.value='';$(this).css('color','#000000','font-style','normal');}"
onblur="if (this.value==''){this.value='Search WA Courts Site';$(this).css('color', '#bbbbb7');}">
<input type="image" name="btnSearch" class="searchButton" alt="Search" src="/images/iconSearch.png">
</form>
</div>
</div>
</div>
<div id="mainNav">
<ul id="menuBar">
<a href="/forms/" ><li class="menuItem first" >Forms</li></a>
<a href="/court_dir/" ><li class="menuItem" >Court Directory</li></a>
<a href="/opinions/" ><li class="menuItem">Opinions</li></a>
<a href="/court_rules/" ><li class="menuItem">Rules</li></a>
<a href="/appellate_trial_courts/" ><li class="menuItem">Courts</li></a>
<a href="/programs_orgs/" ><li class="menuItem">Programs & Organizations</li></a>
<a href="/newsinfo/index.cfm?fa=newsinfo.displayContent&theFile=content/ResourcesPubsReports" ><li class="menuItem last">Resources</li></a>
</ul>
</div>
<div id="topline">
<div id="left" class="breadcrumb"><a href="/">Courts Home</a> > <a href="/appellate_trial_courts/" class="breadcrumb">Courts</a> > <a href="/appellate_trial_courts/supreme/calendar" class="breadcrumb">Supreme Court Calendar</a></div>
</div>
<a name="body"></a>
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="clear:both;">
<tr>
<td width="10"> </td>
<td valign="top" class="mainPage">
<table width="100%">
<tr>
<td valign="top"><h2>Supreme Court Calendar</h2></td>
<td valign="top" align="right" width="175"><div class="linkBox"><a href="/appellate_trial_courts/coaBriefs/index.cfm?fa=coaBriefs.ScHome&courtId=A08">Supreme Court Briefs</a></div></td>
</tr>
</table>
<HTML>
<HEAD>
<TITLE>Washington State Courts - Supreme Court Calendar - May 29, 1996</TITLE>
</HEAD>
<BODY>
<h2><B>May 29, 1996</B></h2>
<P>
<TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0 WIDTH=100%>
<tr>
<td width=33%><b>9:00 A.M.</b></td>
<td width=30% align="center"><b>Olympia</b></td>
<td width=36% align="right"><b>Wednesday, May 29, 1996</b></td>
</tr>
</TABLE>
<BR>
<TABLE BORDER=1 CELLPADDING=5 CELLSPACING=0 WIDTH=100%>
<tr>
<td width="50%" valign="top"><b>Case No. 1 - 62941-2</b><br>(consol. w/ 62939-1 & 62940-4)</td>
<td width="50%" valign="top"><b><u>Counsel</u></b></td>
</tr>
<tr>
<td width="50%" valign="top">
Ino Ino, Inc.<br>
v.<br>
City of Bellevue
<hr noshade>
Deja-Vu Bellevue<BR>
v.<BR>
City of Bellevue
<hr noshade>
Rhonda Remus, Esmeralda Silva, et al.<BR>
v.<BR>
City of Bellevue
</td>
<td width="50%" valign="top">
Gilbert Levy<BR>
<BR>
Stephen Smith & Robert Mitchell<BR>
<HR noshade>
Jack Burns & John Carroll<BR>
<BR>
Stephen Smith & Robert Mitchell
<hr noshade>
Gilbert Levy<BR>
<BR>
Stephen Smith & Robert Mitchell
</td>
</tr>
</TABLE>
<b>Whether various provisions in Bellevue’s adult cabaret ordinance are valid time, place, and manner restrictions.</b>
<P>
<TABLE BORDER=1 CELLPADDING=5 CELLSPACING=0 WIDTH=100%>
<tr>
<td width="50%" valign="top"><b>Case No. 2 - 63441-6</b><BR>(consol. w/ 63442-4)</td>
<td width="50%" valign="top"><b><u>Counsel</u></b></td>
</tr>
<tr>
<td width="50%" valign="top">
State of Washington<br>
v.<br>
James Delbert Branch
<hr noshade>
State of Washington<BR>
v.<BR>
James Delbert Branch
</td>
<td width="50%" valign="top">
Scott Peterson<BR>
<BR>
Nielsen & Acosta
<hr noshade>
Scott Peterson<BR>
<BR>
Robert Bodkin
</td>
</tr>
</TABLE>
<b>Whether a defendant should be permitted to withdraw his guilty plea because he did not sign the statement of defendant on plea of guilty.</b>
<P>
<hr noshade>
<p>
<B>1:30 P.M.</B>
<p>
<TABLE BORDER=1 CELLPADDING=5 CELLSPACING=0 WIDTH=100%>
<tr>
<td width="50%" valign="top"><b>Case No. 3 - 63330-4 </b></td>
<td width="50%" valign="top"><b><u>Counsel</u></b></td>
</tr>
<tr>
<td width="50%" valign="top">
State of Washington<br>
v.<br>
Gabriel F. Stewart
</td>
<td width="50%" valign="top">
Walt Perry<BR>
<BR>
Craddock Verser
</td>
</tr>
</TABLE>
<b>Whether a defendant’s right to a speedy trial under the criminal rules is violated when the State does not extradite the defendant <b>from another state</b> for trial, and does not comply with a court order to set a new trial date.</b>
<P>
<TABLE BORDER=1 CELLPADDING=5 CELLSPACING=0 WIDTH=100%>
<tr>
<td width="50%" valign="top"><b>Case No. 4 - 63445-9 </b><BR>(consol. w/ 63611-7)</td>
<td width="50%" valign="top"><b><u>Counsel</u></b></td>
</tr>
<tr>
<td width="50%" valign="top">
State of Washington<br>
v.<br>
Thomas Merle Hudson
<hr noshade>
State of Washington<BR>
v.<BR>
Pablo Cintron-Cartegena
</td>
<td width="50%" valign="top">
Kenneth Schiffler<BR>
<BR>
Nielsen & Acosta
<hr noshade>
Brenda Bannon<BR>
<BR>
Mark Watanabe
</td>
</tr>
</TABLE>
<b>Whether under CrR 3.3 and <i><u>State v. Strike</u></i>, 87 Wn.2d 870, 557 P.2d 847 (1976), an out-of-state defendant can be "amendable to process," requiring the State to excercise due deligence in securing his presence.</b>
<P>
<hr noshade>
<p>
<b>These summaries are not formulated by the Court and are provided for the convenience of the public only.</b>
<p>
</BODY>
</td>
<td width="10"> </td>
</tr>
</table>
<div class="footerOuter">
<div class="footerBg">
<div class="footerLayout">
<ul>
<span class="footerHeader">Access Records</span>
<li><a href="/jislink/">JIS LINK</a></li>
<li><a href="http://dw.courts.wa.gov?fa=home.fmcd">Find Your Court Date</a></li>
<li><a href="http://dw.courts.wa.gov">Search Case Records</a></li>
<li><a href="/newsinfo/publication/?fa=newsinfo_publication.recordsRequest">Records Request</a></li>
<li><a href="/jis/">Judicial Info System (JIS)</a></li>
<li><a href="https://odysseyportal.courts.wa.gov/odyportal">Odyssey Portal</a></li>
<li><a href="/caseload">Caseload Reports</a></li>
<li>
</li>
</ul>
<ul>
<span class="footerHeader">Find Resources</span>
<li><a href="/library/">State Law Library</a></li>
<li><a href="/education/">Civic Learning</a></li>
<li><a href="/newsinfo/index.cfm?fa=newsinfo.displayContent&theFile=content/ResourcesPubsReports">Resources, Publications, & Reports</a></li>
<li><a href="/committee/?fa=committee.home&committee_id=143">Court Program Accessibility (ADA)</a></li>
<li><a href="/newsinfo/resources/">Jury Service Information</a></li>
<li><a href="/Whistleblower/">Whistleblower</a></li>
<li><a href="/employ/">Employment</a></li>
<li><a href="/procure/">Procurement</a></li>
</ul>
<ul>
<span class="footerHeader">From the Courts</span>
<li><a href="/forms/">Court Forms</a></li>
<li><a href="/forms/?fa=forms.contribute&formID=16">Domestic Violence Forms</a></li>
<li><a href="/opinions/">Court Opinions</a></li>
<li><a href="/court_rules/">Court Rules</a></li>
<li><a href="/index.cfm?fa=home.contentDisplay&location=PatternJuryInstructions">Pattern Jury Instructions</a></li>
<li><a href="/emergency/">Emergency Procedures</a></li>
<li><a href="/index.cfm?fa=home.courtClosures">Notice of Court Closures</a></li>
</ul>
<ul>
<span class="footerHeader">Get Organizational Information</span>
<li><a href="/appellate_trial_courts/aocwho/">Administrative Office of the Courts</a></li>
<li><a href="/appellate_trial_courts/SupremeCourt/?fa=supremecourt.welcome">Supreme Court</a></li>
<li><a href="/appellate_trial_courts/">Appellate & Trial Courts</a></li>
<li><a href="/programs_orgs/">Programs & Organizations</a></li>
<li><a href="/newsinfo/">Washington Court News</a></li>
<li><a href="/court_dir/">Court Directory</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="stayConnected">
<ul style="float:left;">
<li><span class="stayConnectedHeader">Connect with us</span></li>
<li><a href="https://www.facebook.com/washingtoncourts"><img src="/images/iconFB_gray.png" alt="Find us on Facebook" border="0" /></a></li>
<li><a href="https://twitter.com/WACourts"><img src="/images/iconTwitter_gray.png" alt="Follow us on Twitter" border="0" /></a></li>
<li><a href="http://www.youtube.com/channel/UCx4B3hu7aZGPnYGKwph2M0w"><img src="/images/iconYT_gray.png" alt="Watch our YouTube Channel" border="0" /></a></li>
<li><a href="/notifications/?fa=notifications.rss"><img src="/images/iconRss_gray.png" alt="Use one of our RSS Feeds" border="0" /></a></li>
</ul>
<ul style="float:left; padding: 0 0 0 24px;">
<li><span class="stayConnectedHeader">Need Help?</span></li>
<li><a href="https://aoc.custhelp.com/"><img src="/images/iconHelp_lg.png" border="0"></a></li>
<li><span class="stayConnectedHeader"><a href="https://aoc.custhelp.com/">FAQs & eService Center</a></span></li>
</ul>
</div>
<div class="footerLower">
<ul>
<li class="footerText" style="float:left;"><a href="/?fa=home.notice">Privacy & Disclaimer Notices</a> | <a href="/index.cfm?fa=home.sitemap">Sitemap</a></li>
<li class="sealPos"><img src="/images/footerSeal.png" alt="WA State Seal" ></li>
<li class="footerText" style="float:right;">Copyright AOC © 2014</li>
</ul>
</div>
<div class="accessWA">
<div style="display:inline; padding:0 12px 0 8px;float:left;"><a href="http://access.wa.gov" target="_blank"><img src="/images/AWlogo2_150px.gif" border="0" /></a></div>
<div style="display:inline; padding:8px 0;float:left;">For Washington State laws, visit the <a href="http://www1.leg.wa.gov/Legislature/" class="external" target="_blank" style="text-decoration:underline;">Washington State Legislature</a></div>
<div style="display:inline; padding:8px 0;float:right; font-size:8px">S3</div>
</div>
</div>
</div>
</body>
</html>
|
jeffpar/courtcasts
|
sources/wasc/1996/05/29-docket.html
|
HTML
|
gpl-3.0
| 13,152
|
#!/usr/bin/env python
#
# Generate report in Excel format (from xml input)
#
import sys,os,shelve
import re,dfxml,fiwalk
from bc_utils import filename_from_path
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
def bc_generate_feature_xlsx(PdfReport, data, feature_file):
wb = Workbook()
dest_filename = PdfReport.featuredir +'/'+ (filename_from_path(feature_file))[10:-3] + "xlsx"
row_idx = [2]
ws = wb.worksheets[0]
ws.title = "File Feature Information"
ws.cell('%s%s'%('A', '1')).value = '%s' % "Filename"
ws.cell('%s%s'%('B', '1')).value = '%s' % "Position"
ws.cell('%s%s'%('C', '1')).value = '%s' % "Feature"
linenum=0
for row in data:
# Skip the lines with known text lines to be eliminated
if (re.match("Total features",str(row))):
continue
filename = "Unknown"
feature = "Unknown"
position = "Unknown"
# Some lines in the annotated_xxx.txt have less than three
# columns where filename or feature may be missing.
if len(row) > 3:
filename = row[3]
else:
filename = "Unknown"
if len(row) > 1:
feature = row[1]
else:
feature = "Unknown"
position = row[0]
# If it is a special file, check if the user wants it to
# be repoted. If not, exclude this from the table.
if (PdfReport.bc_config_report_special_files == False) and \
(is_special_file(filename)):
## print("D: File %s is special. So skipping" %(filename))
continue
ws.cell('%s%s'%('A', row_idx[0])).value = '%s' % filename
ws.cell('%s%s'%('B', row_idx[0])).value = '%s' % feature
ws.cell('%s%s'%('C', row_idx[0])).value = '%s' % position
row_idx[0] += 1
wb.save(filename=dest_filename)
|
sesuncedu/bitcurator
|
python/bc_gen_feature_rep_xls.py
|
Python
|
gpl-3.0
| 1,974
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Fetch a row</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.odbc-fetch-object.html">odbc_fetch_object</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.odbc-field-len.html">odbc_field_len</a></div>
<div class="up"><a href="ref.uodbc.html">ODBC Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.odbc-fetch-row" class="refentry">
<div class="refnamediv">
<h1 class="refname">odbc_fetch_row</h1>
<p class="verinfo">(PHP 4, PHP 5)</p><p class="refpurpose"><span class="refname">odbc_fetch_row</span> — <span class="dc-title">Fetch a row</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.odbc-fetch-row-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">bool</span> <span class="methodname"><strong>odbc_fetch_row</strong></span>
( <span class="methodparam"><span class="type">resource</span> <code class="parameter">$result_id</code></span>
[, <span class="methodparam"><span class="type">int</span> <code class="parameter">$row_number</code></span>
] )</div>
<p class="para rdfs-comment">
Fetches a row of the data that was returned by <span class="function"><a href="function.odbc-do.html" class="function">odbc_do()</a></span>
or <span class="function"><a href="function.odbc-exec.html" class="function">odbc_exec()</a></span>. After <span class="function"><strong>odbc_fetch_row()</strong></span>
is called, the fields of that row can be accessed with
<span class="function"><a href="function.odbc-result.html" class="function">odbc_result()</a></span>.
</p>
</div>
<div class="refsect1 parameters" id="refsect1-function.odbc-fetch-row-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<span class="term"><em><code class="parameter">result_id</code></em></span>
<dd>
<p class="para">
The result identifier.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">row_number</code></em></span>
<dd>
<p class="para">
If <em><code class="parameter">row_number</code></em> is not specified,
<span class="function"><strong>odbc_fetch_row()</strong></span> will try to fetch the next row in
the result set. Calls to <span class="function"><strong>odbc_fetch_row()</strong></span> with and
without <em><code class="parameter">row_number</code></em> can be mixed.
</p>
<p class="para">
To step through the result more than once, you can call
<span class="function"><strong>odbc_fetch_row()</strong></span> with
<em><code class="parameter">row_number</code></em> 1, and then continue doing
<span class="function"><strong>odbc_fetch_row()</strong></span> without
<em><code class="parameter">row_number</code></em> to review the result. If a driver
doesn't support fetching rows by number, the
<em><code class="parameter">row_number</code></em> parameter is ignored.
</p>
</dd>
</dt>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-function.odbc-fetch-row-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
Returns <strong><code>TRUE</code></strong> if there was a row, <strong><code>FALSE</code></strong> otherwise.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.odbc-fetch-object.html">odbc_fetch_object</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.odbc-field-len.html">odbc_field_len</a></div>
<div class="up"><a href="ref.uodbc.html">ODBC Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
|
Sliim/sleemacs
|
php-manual/function.odbc-fetch-row.html
|
HTML
|
gpl-3.0
| 4,207
|
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setInterval — rpg-dark-fantasy 1.2 documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="index" title="Index"
href="genindex.html"/>
<link rel="search" title="Search" href="search.html"/>
<link rel="top" title="rpg-dark-fantasy 1.2 documentation" href="index.html"/>
<link rel="next" title="Window" href="Window.html"/>
<link rel="prev" title="Lottery" href="Lottery.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="index.html" class="icon icon-home"> rpg-dark-fantasy
</a>
<div class="version">
1.2
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">Contents:</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="utils.html">utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="Lottery.html">Lottery</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">setInterval</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#threadjob">ThreadJob</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="Window.html">Window</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="index.html">rpg-dark-fantasy</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html">Docs</a> »</li>
<li>setInterval</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/setInterval.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="setinterval">
<h1>setInterval<a class="headerlink" href="#setinterval" title="Permalink to this headline">¶</a></h1>
<div class="section" id="threadjob">
<h2>ThreadJob<a class="headerlink" href="#threadjob" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="setInterval.ThreadJob">
<em class="property">class </em><code class="descclassname">setInterval.</code><code class="descname">ThreadJob</code><span class="sig-paren">(</span><em>callback</em>, <em>interval</em>, <em>times</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/setInterval.html#ThreadJob"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#setInterval.ThreadJob" title="Permalink to this definition">¶</a></dt>
<dd><p>Runs the callback function after interval seconds x times</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>callback</strong> (<em>function</em>) – callback function to invoke</li>
<li><strong>interval</strong> (<em>float</em>) – time in seconds after which are required to fire the callback</li>
<li><strong>time</strong> (<em>int</em>) – number of times callback is invoke</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="Window.html" class="btn btn-neutral float-right" title="Window" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="Lottery.html" class="btn btn-neutral" title="Lottery" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, Loïc Penaud.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'1.2',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html>
|
lpenaud/rpg-dark-fantasy
|
docs/setInterval.html
|
HTML
|
gpl-3.0
| 6,680
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014, 2015, 2016 Adam.Dybbroe
# Author(s):
# Adam.Dybbroe <adam.dybbroe@smhi.se>
# Janne Kotro fmi.fi
# Trygve Aspenes
# 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/>.
"""AAPP Level-1 processing on NOAA and Metop HRPT Direct Readout data. Listens
for pytroll messages from Nimbus (NOAA/Metop file dispatch) and triggers
processing on direct readout HRPT level 0 files (full swaths - no granules at
the moment)
"""
from ConfigParser import RawConfigParser
import os
import sys
import logging
from logging import handlers
from trollsift.parser import compose
sys.path.insert(0, "trollduction/")
sys.path.insert(0, "/home/trygveas/git/trollduction-test/aapp_runner")
from read_aapp_config import read_config_file_options
from tle_satpos_prepare import do_tleing
from tle_satpos_prepare import do_tle_satpos
from do_commutation import do_decommutation
import socket
import netifaces
from helper_functions import run_shell_command
LOG = logging.getLogger(__name__)
# ----------------------------
# Default settings for logging
# ----------------------------
_DEFAULT_TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
_DEFAULT_LOG_FORMAT = '[%(levelname)s: %(asctime)s : %(name)s] %(message)s'
# -------------------------------
# Default settings for satellites
# -------------------------------
SUPPORTED_NOAA_SATELLITES = ['NOAA-19', 'NOAA-18', 'NOAA-16', 'NOAA-15']
SUPPORTED_METOP_SATELLITES = ['Metop-B', 'Metop-A', 'Metop-C']
SUPPORTED_SATELLITES = SUPPORTED_NOAA_SATELLITES + SUPPORTED_METOP_SATELLITES
TLE_SATNAME = {'NOAA-19': 'NOAA 19', 'NOAA-18': 'NOAA 18',
'NOAA-15': 'NOAA 15',
'Metop-A': 'METOP-A', 'Metop-B': 'METOP-B',
'Metop-C': 'METOP-C'}
METOP_NAME = {'metop01': 'Metop-B', 'metop02': 'Metop-A'}
METOP_NAME_INV = {'metopb': 'metop01', 'metopa': 'metop02'}
SATELLITE_NAME = {'NOAA-19': 'noaa19', 'NOAA-18': 'noaa18',
'NOAA-15': 'noaa15', 'NOAA-14': 'noaa14',
'Metop-A': 'metop02', 'Metop-B': 'metop01',
'Metop-C': 'metop03'}
SENSOR_NAMES = ['amsu-a', 'amsu-b', 'mhs', 'avhrr/3', 'hirs/4']
SENSOR_NAME_CONVERTER = {
'amsua': 'amsu-a', 'amsub': 'amsu-b', 'hirs': 'hirs/4',
'mhs': 'mhs', 'avhrr': 'avhrt/3'}
METOP_NUMBER = {'b': '01', 'a': '02'}
"""
These are the standard names used by the various AAPP decommutation scripts.
If you change these, you will also have to change the decommutation scripts.
"""
STD_AAPP_OUTPUT_FILESNAMES = {'amsua_file':'aman.l1b',
'amsub_file':'ambn.l1b',
'hirs_file':'hrsn.l1b',
'avhrr_file':'hrpt.l1b'
}
# FIXME! This variable should be put in the config file:
SATS_ONLY_AVHRR = []
from urlparse import urlparse
import posttroll.subscriber
from posttroll.publisher import Publish
from posttroll.message import Message
from trollduction.helper_functions import overlapping_timeinterval
import tempfile
from glob import glob
# import os
import shutil
# import aapp_stat
import threading
from subprocess import Popen, PIPE
import shlex
# import subrocess
from datetime import timedelta, datetime
from time import time as _time
def get_local_ips():
inet_addrs = [netifaces.ifaddresses(iface).get(netifaces.AF_INET)
for iface in netifaces.interfaces()]
ips = []
for addr in inet_addrs:
if addr is not None:
for add in addr:
ips.append(add['addr'])
return ips
def nonblock_read(output):
"""An attempt to catch any hangup in reading the output (stderr/stdout)
from subprocess"""
import fcntl
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.readline()
except:
return ''
def reset_job_registry(objdict, key, start_end_times):
"""Remove job key from registry"""
LOG.debug("Register: " + str(objdict))
starttime, endtime = start_end_times
if key in objdict:
if objdict[key] and len(objdict[key]) > 0:
objdict[key].remove(start_end_times)
LOG.debug("Release/reset job-key " + str(key) + " " +
str(starttime) + " " + str(endtime) +
" from job registry")
LOG.debug("Register: " + str(objdict))
return
LOG.warning("Nothing to reset/release - " +
"Register didn't contain any entry matching: " +
str(key))
return
class AappLvl1Processor(object):
"""
Container for the Metop/NOAA level-1 processing based on AAPP
"""
def __init__(self, runner_config):
"""
Init with config file options
"""
self.noaa_data_out_dir = runner_config['noaa_data_out_dir']
self.metop_data_out_dir = runner_config['metop_data_out_dir']
self.noaa_run_script = runner_config['aapp_run_noaa_script']
self.metop_run_script = runner_config['aapp_run_metop_script']
self.tle_indir = runner_config['tle_indir']
self.tle_outdir = runner_config['tle_outdir']
self.tle_script = runner_config['tle_script']
self.pps_out_dir = runner_config['pps_out_dir']
self.pps_out_dir_format = runner_config['pps_out_dir_format']
self.aapp_prefix = runner_config['aapp_prefix']
self.aapp_workdir = runner_config['aapp_workdir']
self.aapp_outdir = runner_config['aapp_outdir']
self.aapp_outdir_format = runner_config['aapp_outdir_format']
self.copy_data_directories = runner_config['copy_data_directories']
self.move_data_directory = runner_config['move_data_directory']
self.use_dyn_work_dir = runner_config['use_dyn_work_dir']
self.subscribe_topics = runner_config['subscribe_topics']
self.publish_pps_format = runner_config['publish_pps_format']
self.publish_l1_format = runner_config['publish_l1_format']
self.publish_sift_format = runner_config['publish_sift_format']
self.aapp_log_files_dir = runner_config['aapp_log_files_dir']
self.aapp_log_files_backup = runner_config['aapp_log_files_backup']
self.servername = runner_config['servername']
self.dataserver = runner_config['dataserver']
self.station = runner_config['station']
self.environment = runner_config['environment']
self.locktime_before_rerun = int(
runner_config.get('locktime_before_rerun', 10))
self.passlength_threshold = int(runner_config['passlength_threshold'])
self.fullswath = True # Always a full swath (never HRPT granules)
self.working_dir = None
self.level0_filename = None
self.starttime = None
self.endtime = None
self.platform_name = "Unknown"
self.satnum = "0"
self.orbit = "00000"
self.result_files = None
self.level0files = None
self.lvl1_home = self.pps_out_dir
self.job_register = {}
self.my_env = os.environ.copy()
self.check_and_set_correct_orbit_number = False if runner_config['check_and_set_correct_orbit_number'] == 'False' else True
self.do_ana_correction = False if runner_config['do_ana_correction'] == 'False' else True
self.initialise()
def initialise(self):
"""Initialise the processor """
self.working_dir = None
self.level0_filename = None
self.starttime = None
self.endtime = None
self.platform_name = "Unknown"
self.satnum = "0"
self.orbit = "00000"
self.result_files = []
self.level0files = {}
self.out_dir_config_data = []
def cleanup_aapp_workdir(self):
"""Clean up the AAPP working dir after processing"""
filelist = glob('%s/*' % self.working_dir)
dummy = [os.remove(s) for s in filelist if os.path.isfile(s)]
filelist = glob('%s/*' % self.working_dir)
LOG.info("Number of items left after cleaning working dir = " +
str(len(filelist)))
LOG.debug("Files: " + str(filelist))
shutil.rmtree(self.working_dir)
return
def spack_aapplvl1_files(self, subd):
return spack_aapplvl1_files(self.result_files, self.lvl1_home, subd,
self.satnum)
def pack_aapplvl1_files(self, subd):
""" Copy AAPP lvl1 files to PPS source directory
from input pps sub-directory name generated by crete_pps_subdirname()
Return a dictionary with destination full path filename, sensor name and
data processing level"""
return pack_aapplvl1_files(self.result_files, self.pps_out_dir, subd,
self.satnum)
# def delete_old_log_files(self):
# """
# Clean old AAPP log files
# """
# #older_than = int(self.aapp_log_files_backup)*60*60*24
# LOG.debug("continue...")
# delete_old_dirs(self.aapp_log_files_dir,
# self.aapp_log_files_backup)
# return
def copy_aapplvl1_files(self, subd, out_dir_config_data):
"""Copy AAPP lvl1 files in to data processing level sub-directory
e.g. metop/level1b
Input directory is defined in config file metop_data_out_dir and
noaa_data_out_dir
Return a dictionary with destination full path filename, sensor name and
data processing level
"""
return copy_aapplvl1_files(self.result_files, subd, self.satnum, out_dir_config_data)
def smove_lvl1dir(self):
if len(self.result_files) == 0:
LOG.warning("No files in directory to move!")
return {}
# Get the subdirname:
path = os.path.dirname(self.result_files[0])
subd = os.path.basename(path)
LOG.debug("path = " + str(path))
LOG.debug("lvl1_home = " + str(self.lvl1_home))
try:
shutil.move(path, self.lvl1_home)
except shutil.Error:
LOG.warning("Directory already exists: " + str(subd))
if self.orbit == '00000' or self.orbit == None:
# Extract the orbit number from the sub-dir name:
dummy, dummy, dummy, self.orbit = subd.split('_')
# Return a dict with sensor and level for each filename:
filenames = glob(os.path.join(self.lvl1_home, subd, '*'))
LOG.info(filenames)
retv = {}
for fname in filenames:
mstr = os.path.basename(fname).split('_')[0]
if mstr == 'hrpt':
lvl = '1B'
instr = 'avhrr/3'
else:
lvl = mstr[-2:].upper()
try:
instr = SENSOR_NAME_CONVERTER[mstr[0:-3]]
except KeyError:
LOG.warning("Sensor name will not be converted %s" %
str(mstr[0:-3]))
LOG.debug("mstr = " + str(mstr))
instr = mstr[0:-3]
retv[fname] = {'level': lvl, 'sensor': instr}
LOG.info(str(retv))
return retv
def move_lvl1dir(self, out_dir):
"""Move sub-directory with AAPP level-1b|c|d files
Return a dictionary with sensor and data processing level
for each filename """
if len(self.result_files) == 0:
LOG.warning("No files in directory to move!")
return {}
# Get the subdirname:
path = os.path.dirname(self.result_files[0])
subd = os.path.basename(path)
LOG.debug("path = " + str(path))
LOG.debug("out_dir = " + out_dir)
try:
shutil.move(path, out_dir)
except shutil.Error:
LOG.warning("Directory already exists: " + str(subd))
if self.orbit == '00000' or self.orbit == None:
# Extract the orbit number from the sub-dir name:
dummy, dummy, dummy, self.orbit = subd.split('_')
filenames = glob(os.path.join(out_dir, subd, '*l1*'))
LOG.info(filenames)
retv = {}
for fname in filenames:
mstr = os.path.basename(fname).split('_')[0]
if mstr == 'hrpt':
lvl = '1b'
instr = 'avhrr/3'
else:
lvl = mstr[-2:]
try:
instr = SENSOR_NAME_CONVERTER[mstr[0:-3]]
except KeyError:
LOG.warning("Sensor name will not be converted %s",
str(mstr[0:-3]))
LOG.debug("mstr = " + str(mstr))
instr = mstr[0:-3]
retv[fname] = {'level': lvl, 'sensor': instr}
LOG.info(str(retv))
return retv
def move_aapp_log_files(self):
""" Move AAPP processing log files from AAPP working directory
in to sub-directory (PPS format).
The directory path is defined in config file (aapp_log_files)
"""
try:
filelist = glob('%s/*.log' % self.working_dir)
subd = create_pps_subdirname(self.starttime,
self.platform_name,
self.orbit)
destination = os.path.join(self.aapp_log_files_dir, subd)
LOG.debug("move_aapp_log_files destination: " + destination)
if not os.path.exists(destination):
try:
os.makedirs(destination)
except OSError:
LOG.warning("Can't create directory!")
return False # FIXME: Check!
LOG.debug(
"Created new directory for AAPP log files:" + destination)
for file_name in filelist:
LOG.debug("File_name: " + file_name)
base_filename = os.path.basename(file_name)
dst = os.path.join(destination, base_filename)
LOG.debug("dst: " + dst)
shutil.move(file_name, dst)
except OSError as err:
LOG.error("Moving AAPP log files to " +
destination + " failed ", err)
LOG.info("AAPP log files saved in to " + destination)
return
# def get_old_dirs(self, dir_path, older_than_days):
# """
# return a list of all subfolders under dirPath older than olderThanDays
# """
# older_than_days *= 86400 # convert days to seconds
# present = time.time()
# directories = []
# for root, dirs, files in os.walk(dir_path, topdown=False):
# for name in dirs:
# sub_dir_path = os.path.join(root, name)
# if (present - os.path.getmtime(sub_dir_path)) > older_than_days:
# directories.append(sub_dir_path)
# return directories
def create_scene_id(self, keyname):
# Use sat id, start and end time as the unique identifier of the scene!
if keyname in self.job_register and len(self.job_register[keyname]) > 0:
# Go through list of start,end time tuples and see if the current
# scene overlaps with any:
status = overlapping_timeinterval((self.starttime, self.endtime),
self.job_register[keyname])
if status:
LOG.warning("Processing of scene " + keyname +
" " + str(status[0]) + " " + str(status[1]) +
" with overlapping time has been"
" launched previously")
LOG.info("Skip it...")
return True
else:
LOG.debug(
"No overlap with any recently processed scenes...")
scene_id = (str(self.platform_name) + '_' +
self.starttime.strftime('%Y%m%d%H%M%S') +
'_' + self.endtime.strftime('%Y%m%d%H%M%S'))
LOG.debug("scene_id = " + str(scene_id))
return scene_id
def check_scene_id(self, scene_id):
# Check for keys representing the same scene (slightly different
# start/end times):
LOG.debug("Level-0files = " + str(self.level0files))
time_thr = timedelta(seconds=30)#FIXME configure
for key in self.level0files:
pltrfn, startt, endt = key.split('_')
if not self.platform_name == pltrfn:
continue
t1_ = datetime.strptime(startt, '%Y%m%d%H%M%S')
t2_ = datetime.strptime(endt, '%Y%m%d%H%M%S')
# Get the relative time overlap:
sec_inside = (
min(t2_, self.endtime) - max(t1_, self.starttime)).total_seconds()
dsec = (t2_ - t1_).total_seconds()
if dsec < 0.01:
LOG.warning(
"Something awkward with this scene: start_time = end_time!")
break
elif float(sec_inside / dsec) > 0.85:
# It is the same scene!
LOG.debug(
"It is the same scene,"
" though the file times may deviate a bit...")
scene_id = key
break
elif float(sec_inside / dsec) > 0.01:
LOG.warning("There was an overlap but probably not the " +
"same scene: Time interval = " +
"(%s, %s)",
t1_.strftime('%Y-%m-%d %H:%M:%S'),
t2_.strftime('%Y-%m-%d %H:%M:%S'))
return scene_id
def sensors_to_process(self, msg, sensors):
LOG.debug("Sensor = " + str(msg.data['sensor']))
LOG.debug("type: " + str(type(msg.data['sensor'])))
if isinstance(msg.data['sensor'], (str, unicode)):
sensors.append(msg.data['sensor'])
elif isinstance(msg.data['sensor'], (list, set, tuple)):
sensors.extend(msg.data['sensor'])
else:
sensors = []
LOG.warning('Failed interpreting sensor(s)!')
LOG.info("Sensor(s): " + str(sensors))
sensor_ok = False
for sensor in sensors:
if sensor in SENSOR_NAMES:
sensor_ok = True
break
if not sensor_ok:
LOG.info("No required sensors....")
return False
return True
def available_sensors(self, msg, sensors, scene_id):
if scene_id not in self.level0files:
LOG.debug("Reset level-0 files: scene_id = " + str(scene_id))
self.level0files[scene_id] = []
for sensor in sensors:
item = (self.level0_filename, sensor)
if item not in self.level0files[scene_id]:
self.level0files[scene_id].append(item)
LOG.debug("Appending item to list: " + str(item))
else:
LOG.debug("item already in list: " + str(item))
if len(self.level0files[scene_id]) < 4 and msg.data.get("variant") != "EARS":
LOG.info("Not enough sensor data available yet. " +
"Level-0 files = " +
str(self.level0files[scene_id]))
return False
else:
LOG.info("Level 0 files ready: " + str(self.level0files[scene_id]))
return True
def run(self, msg):
"""Start the AAPP level 1 processing on either a NOAA HRPT file or a
set of Metop HRPT files"""
try:
# Avoid 'collections' and other stuff:
if msg is None or msg.type != 'file':
return True
LOG.debug("Received message: " + str(msg))
# msg.data['platform_name'] = "NOAA-19"
LOG.debug(
"Supported Metop satellites: " + str(SUPPORTED_METOP_SATELLITES))
LOG.debug(
"Supported NOAA satellites: " + str(SUPPORTED_NOAA_SATELLITES))
try:
if (msg.data['platform_name'] not in
SUPPORTED_NOAA_SATELLITES and
msg.data['platform_name'] not in
SUPPORTED_METOP_SATELLITES):
LOG.info("Not a NOAA/Metop scene. Continue...")
return True
# FIXME:
except Exception, err:
LOG.warning(str(err))
return True
self.platform_name = msg.data['platform_name']
LOG.debug("Satellite = " + str(self.platform_name))
LOG.debug("")
LOG.debug("\tMessage:")
LOG.debug(str(msg))
urlobj = urlparse(msg.data['uri'])
url_ip = socket.gethostbyname(urlobj.netloc)
if urlobj.netloc and (url_ip not in get_local_ips()):
LOG.warning("Server %s not the current one: %s",
str(urlobj.netloc),
socket.gethostname())
return True
LOG.info("Ok... " + str(urlobj.netloc))
self.servername = urlobj.netloc
LOG.info("Sat and Sensor: " + str(msg.data['platform_name'])
+ " " + str(msg.data['sensor']))
self.starttime = msg.data['start_time']
try:
self.endtime = msg.data['end_time']
except KeyError:
LOG.warning(
"No end_time in message! Guessing start_time + 14 minutes...")
self.endtime = msg.data[
'start_time'] + timedelta(seconds=60 * 14)
# Test if the scene is longer than minimum required:
pass_length = self.endtime - self.starttime
if pass_length < timedelta(seconds=60 * self.passlength_threshold):
LOG.info("Pass is too short: Length in minutes = %6.1f",
pass_length.seconds / 60.0)
return True
#Due to different ways to start the orbit counting, it might be neccessary
#to correct the orbit number.
#
#Default is to check and correct if neccessary
#Add configuration to turn it off
start_orbnum = None
if self.check_and_set_correct_orbit_number:
try:
import pyorbital.orbital as orb
sat = orb.Orbital(
TLE_SATNAME.get(self.platform_name, self.platform_name), tle_file='')
start_orbnum = sat.get_orbit_number(self.starttime)
except ImportError:
LOG.warning("Failed importing pyorbital, " +
"cannot calculate orbit number")
except AttributeError:
LOG.warning("Failed calculating orbit number using pyorbital")
LOG.warning("platform name = " +
str(TLE_SATNAME.get(self.platform_name,
self.platform_name)) +
" " + str(self.platform_name))
LOG.info(
"Orbit number determined from pyorbital = " + str(start_orbnum))
try:
self.orbit = int(msg.data['orbit_number'])
except KeyError:
LOG.warning("No orbit_number in message! Set to none...")
self.orbit = None
if self.check_and_set_correct_orbit_number:
if start_orbnum and self.orbit != start_orbnum:
LOG.warning("Correcting orbit number: Orbit now = " +
str(start_orbnum) + " Before = " + str(self.orbit))
self.orbit = start_orbnum
else:
LOG.debug("Orbit number in message determined " +
"to be okay and not changed...")
if self.platform_name in SUPPORTED_METOP_SATELLITES:
metop_id = SATELLITE_NAME[self.platform_name].split('metop')[1]
self.satnum = METOP_NUMBER.get(metop_id, metop_id)
else:
self.satnum = SATELLITE_NAME[self.platform_name].strip('noaa')
year = self.starttime.year
keyname = str(self.platform_name)
LOG.debug("Keyname = " + str(keyname))
LOG.debug("Start: job register = " + str(self.job_register))
scene_id = self.create_scene_id(keyname)
#This means(from the create_scene_id) skipping this scene_is as it is already processed within a onfigured interval
#See create_scene_id for detailed info
if scene_id == True:
return True
scene_id = self.check_scene_id(scene_id)
LOG.debug("scene_id = " + str(scene_id))
if scene_id in self.level0files:
LOG.debug("Level-0 files = " + str(self.level0files[scene_id]))
else:
LOG.debug("scene_id = %s: No level-0 files yet...", str(scene_id))
self.level0_filename = urlobj.path
dummy, fname = os.path.split(self.level0_filename)
sensors = []
if not self.sensors_to_process(msg, sensors):
return True
if not self.available_sensors(msg, sensors, scene_id):
return True
#Need to do this here to add up all sensors for METOP
for (file,instr) in self.level0files[scene_id]:
if instr not in sensors:
LOG.debug("Adding instrumet to sensors list: {}".format(instr))
sensors.append(str(instr))
if not self.working_dir and self.use_dyn_work_dir:
try:
self.working_dir = tempfile.mkdtemp(dir=self.aapp_workdir)
except OSError:
self.working_dir = tempfile.mkdtemp()
finally:
LOG.info("Create new working dir...")
elif not self.working_dir:
self.working_dir = self.aapp_workdir
LOG.info("Working dir = " + str(self.working_dir))
# AAPP requires ENV variables
#my_env = os.environ.copy()
#my_env['AAPP_PREFIX'] = self.aapp_prefix
if self.use_dyn_work_dir:
self.my_env['DYN_WRK_DIR'] = self.working_dir
LOG.info("working dir: self.working_dir = " + str(self.working_dir))
LOG.info("Using AAPP_PREFIX:" + str(self.aapp_prefix))
for envkey in self.my_env:
LOG.debug("ENV: " + str(envkey) + " " + str(self.my_env[envkey]))
aapp_outdir_config_format = ""
if self.platform_name in SUPPORTED_SATELLITES:
LOG.info("This is a supported scene. Start the AAPP processing!")
# FIXME: LOG.info("Process the scene " +
# self.platform_name + self.orbit)
# TypeError: coercing to Unicode: need string or buffer, int
# found
LOG.info("Process the file " + str(self.level0_filename))
"""
COnfiguration for the various AAPP processing
This dict is passed to each module doing the actual processing.
The processing of each level is overridden by the available sensors retrived from the message
Meaning if processing of avhrr is set to True in the configuration but is not a mandatory sensor,
nor contained in the sensor list, then the processing av avhrr is overridden and set to False.
"""
process_config = {}
try:
process_config['platform'] = SATELLITE_NAME.get(self.platform_name,self.platform_name)
process_config['orbit_number'] = int(msg.data['orbit_number'])
process_config['working_directory'] = self.working_dir
process_config['process_amsua'] = False
process_config['process_amsub'] = False
process_config['process_hirs'] = False
process_config['process_avhrr'] = False
process_config['process_msu'] = False
process_config['process_dcs'] = False
process_config['process_ana'] = self.do_ana_correction
process_config['a_tovs'] = list("ATOVS")
process_config['hirs_file'] = STD_AAPP_OUTPUT_FILESNAMES['hirs_file']
process_config['amsua_file'] = STD_AAPP_OUTPUT_FILESNAMES['amsua_file']
process_config['amsub_file'] = STD_AAPP_OUTPUT_FILESNAMES['amsub_file']
process_config['avhrr_file'] = STD_AAPP_OUTPUT_FILESNAMES['avhrr_file']
process_config['calibration_location'] = "-c -l"
except KeyError as ke:
LOG.error("Could not initialize one or more process config parameters: {}.".format(ke))
return True #Meaning: can not process this.
print str(self.level0files[scene_id])
if 'metop' in process_config['platform']:
sensor_filename = {}
for (fname, instr) in self.level0files[scene_id]:
sensor_filename[instr] = fname
for instr in sensor_filename.keys():
print "instr: ",instr
if instr not in SENSOR_NAMES:
LOG.error("Sensor name mismatch! name = " + str(instr))
return True
if "avhrr/3" in sensor_filename:
process_config['input_avhrr_file'] = sensor_filename['avhrr/3']
if "amsu-a" in sensor_filename:
process_config['input_amsua_file'] = sensor_filename['amsu-a']
if "mhs" in sensor_filename:
process_config['input_amsub_file'] = sensor_filename['mhs']
if "hirs/4" in sensor_filename:
process_config['input_hirs_file'] = sensor_filename['hirs/4']
_platform = SATELLITE_NAME.get(self.platform_name,self.platform_name)
#DO tle
tle_proc_ok = True
if not do_tleing(self.starttime, _platform, self.working_dir, self.tle_indir):
LOG.warning("Tleing failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
tle_proc_ok = False
#DO tle satpos
satpos_proc_ok = True
if not do_tle_satpos(self.starttime, _platform, self.tle_indir):
LOG.warning("Tle satpos failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
satpos_proc_ok = False
#DO decom
decom_proc_ok = True
if not do_decommutation(process_config, sensors, self.starttime, self.level0_filename):
LOG.warning("The decommutaion failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
decom_proc_ok = False
return True #Meaning can not complete this and skip the rest of the processing
#DO HIRS
hirs_proc_ok = True
from do_hirs_calibration import do_hirs_calibration
if not do_hirs_calibration(process_config, self.starttime):
LOG.warning("Tle hirs calibration and location failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
hirs_proc_ok = False
#DO ATOVS
atovs_proc_ok = True
from do_atovs_calibration import do_atovs_calibration
if not do_atovs_calibration(process_config, self.starttime):
LOG.warning("The (A)TOVS calibration and location failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
atovs_proc_ok = False
#DO AVHRR
avhrr_proc_ok = True
from do_avhrr_calibration import do_avhrr_calibration
if not do_avhrr_calibration(process_config, self.starttime):
LOG.warning("The avhrr calibration and location failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
avhrr_proc_ok = False
#Do Preprocessing
atovpp_proc_ok = True
from do_atovpp_and_avh2hirs_processing import do_atovpp_and_avh2hirs_processing
if not do_atovpp_and_avh2hirs_processing(process_config, self.starttime):
LOG.warning("The preprocessing atovin, atopp and/or avh2hirs failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
atovpp_proc_ok = False
#DO IASI
iasi_proc_ok = True
from do_iasi_calibration import do_iasi_calibration
if not do_iasi_calibration(process_config, self.starttime):
LOG.warning("The iasi calibration and location failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
iasi_proc_ok = False
#DO ANA
ana_proc_ok = True
from do_ana_correction import do_ana_correction
if not do_ana_correction(process_config, self.starttime):
LOG.warning("The ana attitude correction failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
ana_proc_ok = False
#FIXME
#Need a general check to fail run of some of the AAPP scripts fails fatal.
#This is fallback choice if configured dir format fails
aapp_outdir_pps_format = os.path.join(self.aapp_outdir,"{0:}_{1:%Y%m%d}_{1:%H%M}_{2:05d}"\
.format(SATELLITE_NAME.get(self.platform_name, self.platform_name),
self.starttime,
int(msg.data['orbit_number'])))
#Make a copy of the msg.data so new needed variables can be added to this as needed
self.out_dir_config_data = msg.data
self.out_dir_config_data['satellite_name'] = SATELLITE_NAME.get(self.platform_name, self.platform_name)
self.out_dir_config_data['orbit_number'] = int(msg.data['orbit_number'])
try:
aapp_outdir_config_format = compose(self.aapp_outdir_format,self.out_dir_config_data)
except KeyError as ke:
LOG.warning("Unknown Key used in format: {}. Check spelling and/or availability.".format(self.aapp_outdir_format))
LOG.warning("Available keys are:")
for key in self.out_dir_config_data:
LOG.warning("{} = {}".format(key,self.out_dir_config_data[key]))
LOG.warning("Will continue with directory name format as used by SAFNWC PPS...")
aapp_outdir_config_format = aapp_outdir_pps_format
except ValueError as ve:
LOG.warning("value error : {}".format(ve))
LOG.warning("aapp_outdir_format : {}".format(self.aapp_outdir_format))
LOG.warning("out_dir_config_data: {}".format(self.out_dir_config_data))
aapp_outdir_config_format = os.path.join(self.aapp_outdir,aapp_outdir_config_format)
LOG.info("aapp outdir config format: " + aapp_outdir_config_format)
if not os.path.exists(aapp_outdir_config_format):
LOG.info("Create selected aapp_outdir: {}".format(aapp_outdir_config_format))
try:
os.mkdir(aapp_outdir_config_format)
except OSError as oe:
LOG.error("Could not create directory: {} with {}".format(aapp_outdir_config_format,oe))
else:
#FIXME Should we delete this directory if exists?
LOG.warning("The selected AAPP outdir for this processing exists already: " + aapp_outdir_config_format +". This can cause problems ....")
#Rename standard AAPP output file names to usefull ones
#and move files to final location.
from rename_aapp_filenames import rename_aapp_filenames
if not rename_aapp_filenames(process_config, self.starttime, aapp_outdir_config_format):
LOG.warning("The rename of standard aapp filenames to practical ones failed for some reason. It might be that the processing can continue")
LOG.warning("Please check the previous log carefully to see if this is an error you can accept.")
else:
LOG.warning("This satellite: {}, is not supported.".format(self.platform_name))
LOG.warning("Must be one of: {}".format("".join(SUPPORTED_SATELLITES)))
# Add to job register to avoid this to be run again
if keyname not in self.job_register.keys():
self.job_register[keyname] = []
self.job_register[keyname].append((self.starttime, self.endtime))
LOG.debug("End: job register = " + str(self.job_register))
# Block any future run on this scene for time_to_block_before_rerun
# (e.g. 10) minutes from now:
t__ = threading.Timer(self.locktime_before_rerun,
reset_job_registry, args=(self.job_register,
str(self.platform_name),
(self.starttime,
self.endtime)))
t__.start()
LOG.debug("After timer call: job register = " + str(self.job_register))
LOG.info("Ready with AAPP level-1 processing on NOAA scene: " + str(fname))
LOG.info("working dir: self.working_dir = " + str(self.working_dir))
globstr = os.path.join(self.aapp_outdir,
str(SATELLITE_NAME.get(self.platform_name, self.platform_name)) +
"_*" + str(int(msg.data['orbit_number'])))
globstr = aapp_outdir_config_format
LOG.debug("Glob string = " + str(globstr))
dirlist = glob(globstr)
if len(dirlist) != 1:
LOG.error("Cannot find output files in working dir!")
self.result_files = []
else:
self.result_files = get_aapp_lvl1_files(dirlist[0], msg.data['platform_name'])
LOG.info("Output files: " + str(self.result_files))
except:
LOG.exception("Failed in run...")
raise
return False
def aapp_rolling_runner(runner_config):
"""The AAPP runner. Listens and triggers processing on Metop/NOAA HRPT
level 0 files dispatched from reception."""
LOG.info("*** Start the NOAA/Metop HRPT AAPP runner:")
LOG.info("-" * 50)
os.environ["AAPP_PREFIX"] = runner_config['aapp_prefix']
aapp_atovs_conf = runner_config['aapp_prefix'] + "/ATOVS_ENV7"
status, returncode, out, err = run_shell_command("bash -c \"source {}\";env".format(aapp_atovs_conf))
if not status:
print "Command failed"
else:
for line in out.splitlines():
if line:
(key,_,value) = line.partition("=")
os.environ[key]=value
# init
aapp_proc = AappLvl1Processor(runner_config)
with posttroll.subscriber.Subscribe('',
aapp_proc.subscribe_topics,
True) as subscr:
with Publish('aapp_runner', 0) as publisher:
while True:
skip_rest = False
aapp_proc.initialise()
for msg in subscr.recv(timeout=90):
status = aapp_proc.run(msg)
if not status:
#skip_rest = True
break # end the loop and reinitialize!
if skip_rest:
skip_rest = False
continue
tobj = aapp_proc.starttime
LOG.info("Time used in sub-dir name: " +
str(tobj.strftime("%Y-%m-%d %H:%M")))
#Start internal distribution of data
#Copy data to destinations if configured
if runner_config['copy_data_directories']:
for dest_dir in runner_config['copy_data_directories'].split(','):
level1_files = aapp_proc.copy_aapplvl1_files(dest_dir, aapp_proc.out_dir_config_data)
publish_level1(publisher,
aapp_proc.servername,
aapp_proc.station,
aapp_proc.environment,
aapp_proc.publish_pps_format,
level1_files,
aapp_proc.orbit,
aapp_proc.starttime,
aapp_proc.endtime,
msg.data,
aapp_proc.publish_sift_format)
#move data to last destination if configured
if runner_config['move_data_directory']:
try:
move_dir = compose(runner_config['move_data_directory'],aapp_proc.out_dir_config_data)
except KeyError as ke:
LOG.warning("Unknown Key used in format: {}. Check spelling and/or availability.".format(runner_config['move_data_directory']))
LOG.warning("Available keys are:")
for key in aapp_proc-out_dir_config_data:
LOG.warning("{} = {}".format(key,aapp_proc.out_dir_config_data[key]))
LOG.error("Skipping this directory ... ")
continue
except TypeError as te:
LOG.error("Type Error: {}".format(te))
LOG.debug("Move into directory: {}".format(runner_config['move_data_directory']))
level1_files = aapp_proc.move_lvl1dir(runner_config['move_data_directory'])
publish_level1(publisher,
aapp_proc.servername,
aapp_proc.station,
aapp_proc.environment,
aapp_proc.publish_pps_format,
level1_files,
aapp_proc.orbit,
aapp_proc.starttime,
aapp_proc.endtime,
msg.data,
aapp_proc.publish_sift_format)
if False:
# Site specific processing
LOG.info("Station = " + str(aapp_proc.station))
if ('norrkoping' in aapp_proc.station or
'nkp' in aapp_proc.station):
if aapp_proc.platform_name.startswith('Metop'):
subd = create_pps_subdirname(tobj, aapp_proc.platform_name,
aapp_proc.orbit)
LOG.info("Create sub-directory for level-1 files: " +
str(subd))
level1_files = aapp_proc.smove_lvl1dir()
# level1_files = aapp_proc.spack_aapplvl1_files(subd)
else:
LOG.info("Move sub-directory with NOAA level-1 files")
LOG.debug(
"Orbit BEFORE call to move_lvl1dir: " + str(aapp_proc.orbit))
level1_files = aapp_proc.smove_lvl1dir()
LOG.debug(
"Orbit AFTER call to smove_lvl1dir: " + str(aapp_proc.orbit))
publish_level1(publisher,
aapp_proc.servername,
aapp_proc.station,
aapp_proc.environment,
aapp_proc.publish_pps_format,
level1_files,
aapp_proc.orbit,
aapp_proc.starttime,
aapp_proc.endtime,
msg.data)
elif (aapp_proc.station == 'helsinki' or
aapp_proc.station == 'kumpula'):
data_out_dir = ""
LOG.debug("aapp_proc.platform_name" +
aapp_proc.platform_name)
if (aapp_proc.platform_name.startswith('Metop') and
aapp_proc.metop_data_out_dir):
data_out_dir = aapp_proc.metop_data_out_dir
if (aapp_proc.platform_name.startswith('NOAA') and
aapp_proc.noaa_data_out_dir):
data_out_dir = aapp_proc.noaa_data_out_dir
LOG.debug("DATA_OUT_DIR:" + data_out_dir)
if aapp_proc.pps_out_dir:
subd = create_pps_subdirname(tobj,
aapp_proc.platform_name,
aapp_proc.orbit)
LOG.info("Created PPS sub-directory "
"for level-1 files: " + str(subd))
level1_files = aapp_proc.pack_aapplvl1_files(subd)
if level1_files is not None:
LOG.debug("PPS_OUT_DIR: level1_files: ")
for file_line in level1_files:
LOG.debug(str(file_line))
publish_level1(publisher,
aapp_proc.servername,
aapp_proc.station,
aapp_proc.environment,
aapp_proc.publish_pps_format,
level1_files,
aapp_proc.orbit,
aapp_proc.starttime,
aapp_proc.endtime,
msg.data)
else:
LOG.error("No files copied to " + subd)
# FIXED: If 'NoneType' object is not iterable
# = no files to publish!
if data_out_dir:
LOG.info("Copying level-1 files to " + data_out_dir)
level1_files = aapp_proc.copy_aapplvl1_files(
data_out_dir)
if level1_files is not None:
LOG.debug("aapp_proc.publish_l1_format:" +
aapp_proc.publish_l1_format)
LOG.debug("level1_files: ")
publish_level1(publisher,
aapp_proc.servername,
aapp_proc.station,
aapp_proc.environment,
aapp_proc.publish_l1_format,
level1_files,
aapp_proc.orbit,
aapp_proc.starttime,
aapp_proc.endtime,
msg.data)
else:
LOG.error("Nofile copied to " + data_out_dir)
#End site specific part.
if (aapp_proc.working_dir and
not aapp_proc.aapp_log_files_dir == ""):
LOG.info("Move AAPP log files")
aapp_proc.move_aapp_log_files()
LOG.info("Cleaning old log files...")
path_to_clean = aapp_proc.aapp_log_files_dir
older_than_days = int(aapp_proc.aapp_log_files_backup)
cleanup(older_than_days, path_to_clean)
LOG.info("Cleaning up directory " +
str(aapp_proc.working_dir))
# aapp_proc.cleanup_aapp_workdir()
elif aapp_proc.working_dir:
LOG.info("NOT Cleaning up directory %s",
aapp_proc.working_dir)
# aapp_proc.cleanup_aapp_workdir()
#LOG.info("Do the tleing now that aapp has finished...")
#do_tleing(aapp_proc.aapp_prefix,
# aapp_proc.tle_indir, aapp_proc.tle_outdir,
# aapp_proc.tle_script)
#LOG.info("...tleing done")
return
def publish_level1(publisher,
server,
env,
station,
publish_format,
result_files,
orbit, start_t, end_t, mda, publish_sift_format):
"""Publish the messages that AAPP lvl1 files are ready
"""
# Now publish:
for key in result_files:
resultfile = key
LOG.debug("File: " + str(os.path.basename(resultfile)))
filename = os.path.split(resultfile)[1]
to_send = mda.copy()
to_send['uri'] = ('ssh://%s%s' % (server, resultfile))
to_send['filename'] = filename
to_send['uid'] = filename
to_send['sensor'] = result_files[key]['sensor']
to_send['orbit_number'] = int(orbit)
to_send['format'] = publish_format
to_send['type'] = 'Binary'
to_send['data_processing_level'] = result_files[key]['level'].upper()
LOG.debug('level in message: ' + str(to_send['data_processing_level']))
to_send['start_time'], to_send['end_time'] = start_t, end_t
to_send['station'] = station
to_send['env'] = env
try:
publish_to = compose(publish_sift_format,to_send)
except KeyError as ke:
LOG.warning("Unknown Key used in format: {}. Check spelling and/or availability.".format(publish_sift_format))
LOG.warning("Available keys are:")
for key in to_send:
LOG.warning("{} = {}".format(key,to_send[key]))
LOG.error("Can not publish these data!")
return
except ValueError as ve:
LOG.error("Value Error: {}".format(ve))
return
LOG.debug("Publish to:{}".format(publish_to))
msg = Message(publish_to, "file", to_send).encode()
#msg = Message('/' + str(to_send['format']) + '/' +
# str(to_send['data_processing_level']) +
# '/' + station + '/' + env +
# '/polar/direct_readout/',
# "file", to_send).encode()
LOG.debug("sending: " + str(msg))
publisher.send(msg)
def get_aapp_lvl1_files(level1_dir, satid):
"""Get the aapp level-1 filenames for the NOAA/Metop direct readout
swath"""
if satid in SUPPORTED_METOP_SATELLITES:
lvl1_files = (glob(os.path.join(level1_dir, '*.l1b')) +
glob(os.path.join(level1_dir, '*.l1c')) +
glob(os.path.join(level1_dir, '*.l1d')))
else:
lvl1_files = (glob(os.path.join(level1_dir, "*%s*.l1b"
% (SATELLITE_NAME.get(satid, satid)))) +
glob(os.path.join(level1_dir, "*%s*.l1c"
% (SATELLITE_NAME.get(satid, satid)))) +
glob(os.path.join(level1_dir, "*%s*.l1d"
% (SATELLITE_NAME.get(satid, satid)))))
return lvl1_files
# FIXME:
# if MODE == 'SMHI_MODE':
# if satid in SUPPORTED_METOP_SATELLITES:
# # Level 1b/c data:
# lvl1_files = (glob(os.path.join(level1_dir, '*.l1b')) +
# glob(os.path.join(level1_dir, '*.l1c')) +
# glob(os.path.join(level1_dir, '*.l1d')))
# else:
# # SUBDIR example: noaa18_20140826_1108_47748
# LOG.debug(
# 'level1_dir = ' + str(level1_dir) + ' satid = ' + str(satid))
# # /home/users/satman/tmp/hrpt_noaa18_20150421_1425_51109.l1b
# matchstr = os.path.join(
# level1_dir, + '*' + SATELLITE_NAME.get(satid, satid) + '_????????_????_?????/') + '*'
# LOG.debug(matchstr)
# lvl1_files = glob(matchstr)
# LOG.debug('get_aapp_lvl1_files: ' + str(lvl1_files))
# if MODE == 'test':
# # AAPP convention
# LOG.debug('
# get_aapp_lvl1_files: ' + str(lvl1_files))
def create_pps_subdirname(obstime, satid, orbnum):
"""Generate the pps subdirectory name from the start observation time, ex.:
'noaa19_20120405_0037_02270'"""
return (SATELLITE_NAME.get(satid, satid) +
obstime.strftime('_%Y%m%d_%H%M_') +
'%.5d' % orbnum)
def spack_aapplvl1_files(aappfiles, base_dir, subdir, satnum):
"""Copy the AAPP lvl1 files to the sub-directory under the pps directory
structure"""
# aman => amsua
# ambn => amsub (satnum <= 17)
# ambn => mhs (satnum > 17)
# hrsn => hirs
# msun => msu
# Store the sensor name and the level corresponding to the file:
sensor_and_level = {}
name_converter = {'avhr': 'avhrr',
'aman': 'amsua',
'hrsn': 'hirs',
'msun': 'msu',
'hrpt': 'hrpt'
}
not_considered = ['dcsn', 'msun']
path = os.path.join(base_dir, subdir)
if not os.path.exists(path):
os.mkdir(path)
LOG.info("Number of AAPP lvl1 files: " + str(len(aappfiles)))
# retvl = []
for aapp_file in aappfiles:
fname = os.path.basename(aapp_file)
in_name, ext = fname.split('.')
if in_name in not_considered:
continue
if in_name == 'ambn':
instr = 'mhs'
try:
if int(satnum) <= 17:
instr = 'amsub'
except ValueError:
pass
firstname = instr + ext
level = ext.strip('l').upper()
elif in_name == 'hrpt':
firstname = name_converter.get(in_name)
instr = 'avhrr/3'
# Could also be 'avhrr'. Will anyhow be converted below...
level = '1B'
else:
instr = name_converter.get(in_name, in_name)
LOG.debug("Sensor = " + str(instr) + " from " + str(in_name))
firstname = instr + ext
level = ext.strip('l').upper()
newfilename = os.path.join(path, "%s_%s.%s" % (firstname,
subdir, ext))
LOG.info("Copy aapp-file to destination: " + newfilename)
shutil.copy(aapp_file, newfilename)
# retvl.append(newfilename)
sensor_and_level[newfilename] = {
'sensor': SENSOR_NAME_CONVERTER.get(instr, instr),
'level': level}
return sensor_and_level
# return retvl
def pack_aapplvl1_files(aappfiles, base_dir, subdir, satnum):
"""
Copy the AAPP lvl1 files to the sub-directory under the pps directory
structure
"""
# aman => amsua
# ambn => amsub (satnum <= 17)
# ambn => mhs (satnum > 17)
# hrsn => hirs
# msun => msu
# Store the sensor name and the level corresponding to the file:
sensor_and_level = {}
# name_converter = {'avhr': 'avhrr',
# 'aman': 'amsua',
# 'hrsn': 'hirs',
# 'msun': 'msu',
# 'hrpt': 'hrpt'
# }
# not_considered = ['dcsn', 'msun']
LOG.debug(" pack_aapplvl1_files subdir: " + subdir)
path = os.path.join(base_dir, subdir)
LOG.debug("path: " + path)
if not os.path.exists(path):
LOG.debug("mkdir")
os.makedirs(path)
# FIXME: OSError: [Errno 2] No such file or directory:
LOG.info("Number of AAPP lvl1 files: " + str(len(aappfiles)))
for aapp_file in aappfiles:
LOG.debug("Processing aapp_file: " + aapp_file)
# fname = os.path.basename(aapp_file)
filename = os.path.basename(aapp_file)
in_name, ext = filename.split('.')
#
# if in_name in not_considered:
# LOG.debug("File NOT consired: " + in_name)
# continue
if in_name.startswith('mhs'):
instr = 'mhs'
try:
if int(satnum) <= 17 and int(satnum) >= 15:
instr = 'amsub'
except ValueError:
pass
# firstname = instr + ext
# level = ext.strip('l')
elif in_name.startswith('hrpt'):
# firstname = name_converter.get(in_name)
instr = 'avhrr/3'
# Could also be 'avhrr'. Will anyhow be converted below...
# level = '1b'
elif in_name.startswith('hirs'):
instr = 'hirs'
elif in_name.startswith('amsua'):
instr = 'amsua'
elif in_name.startswith('amsub'):
instr = 'amsub'
else:
LOG.debug("File not consired: " + filename)
continue
# instr = name_converter.get(in_name, in_name)
# LOG.debug("Sensor = " + str(instr) + " from " + str(in_name))
# firstname = instr + ext
# level = ext.strip('l')
level = ext.strip('l')
# LOG.debug("Firstname " + firstname)
# newfilename = os.path.join(path, "%s_%s.%s" % (firstname,
# subdir, ext))
newfilename = os.path.join(path, filename)
LOG.info("Copy aapp-file to destination: " + newfilename)
shutil.copy(aapp_file, newfilename)
sensor_and_level[newfilename] = {
'sensor': SENSOR_NAME_CONVERTER.get(instr, instr),
'level': level}
return sensor_and_level
# AAPP output:
# METOP:
# hrpt_M01_20150428_1857_13540.l1b amsual1b_M01_20150428_1857_13540.l1b
# NOAA:
# hrpt_noaa18_20150428_1445_51208.l1b hirsl1b_noaa18_20150428_1445_51208.l1b
#
def copy_aapplvl1_files(aappfiles, output_data_basepath, satnum, out_dir_config_data):
"""
Copy AAPP lvl1 files to the sub-directories (level1b,
level1c, level1d)
Metop data under the metop_data_out
and in case of Noaa data under the directory noaa_data_out
Output format is defined in scripts AAPP_RUN_NOAA and AAPP_RUN_METOP
"""
LOG.info("Start copy level1 files to directory")
# Store the sensor name and the level corresponding to the file:
sensor_and_level = {}
# name_converter = {'avhr': 'avhrr',
# 'aman': 'amsua',
# 'hrsn': 'hirs',
# 'msun': 'msu',
# 'hrpt': 'hrpt'
# }
dir_name_converter = {'l1b': 'level1b',
'l1c': 'level1c',
'l1d': 'level1d'
}
# not_considered = ['dcsn', 'msun']
if len(aappfiles) == 0:
LOG.warning("No files in input directory to copy!")
return
errors = []
for aapp_file in aappfiles:
filename = os.path.basename(aapp_file)
in_name, ext = filename.split('.')
LOG.debug("in_name: " + in_name)
# if in_name in not_considered:
# LOG.debug("File NOT consired:" + in_name)
# continue
if in_name.startswith('mhs'):
instr = 'mhs'
try:
if int(satnum) <= 17 and int(satnum) >= 15:
instr = 'amsub'
except ValueError:
pass
# firstname = instr + ext
# level = ext.strip('l')
elif in_name.startswith('hrpt'):
# firstname = name_converter.get(in_name)
instr = 'avhrr/3'
# Could also be 'avhrr'. Will anyhow be converted below...
# level = '1b'
elif in_name.startswith('hirs'):
instr = 'hirs'
elif in_name.startswith('amsua'):
instr = 'amsua'
elif in_name.startswith('amsub'):
instr = 'amsub'
else:
LOG.debug("File not consired:" + filename)
continue
# level = '1c'
# instr = name_converter.get(in_name, in_name)
LOG.debug("Sensor = " + str(instr) + " from " + str(in_name))
# firstname = instr + ext
# level = ext.strip('l')
level = ext.strip('l')
# LOG.debug("Firstname " + firstname)
out_dir_config_data['level_of_data'] = dir_name_converter.get(ext)
try:
directory = compose(output_data_basepath, out_dir_config_data)
except KeyError as ke:
LOG.warning("Unknown Key used in format: {}. Check spelling and/or availability.".format(output_data_basepath))
LOG.warning("Available keys are:")
for key in out_dir_config_data:
LOG.warning("{} = {}".format(key,out_dir_config_data[key]))
LOG.error("Skipping this directory ... ")
return
LOG.debug("Copy into directory: {}".format(directory))
if not os.path.exists(directory):
LOG.info("Create new directory:" + directory)
try:
os.makedirs(directory)
except OSError as err:
# FIXME: error or fatal?
LOG.error("Couldn't make new directory " + directory + err)
return
else:
LOG.info("Directory already exists.")
destination_file = os.path.join(directory, filename)
LOG.debug("Destination_file: " + destination_file)
try:
shutil.copy(aapp_file, destination_file)
except (IOError, os.error) as err:
errors.append((aapp_file, destination_file, str(err)))
LOG.error(in_name + "copy failed %s", err.strerror)
# except Error as err:
# errors.extend(err.args[0])
if errors:
LOG.error("Too many errors!")
sensor_and_level[destination_file] = {
'sensor': SENSOR_NAME_CONVERTER.get(instr, instr),
'level': level}
LOG.debug("--------------------------")
for key in sensor_and_level:
LOG.debug("Filename: " + key)
LOG.info("All files copied.")
return sensor_and_level
def read_arguments():
"""
Read command line arguments
Return
name of the station, environment, config file and log file
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config_file',
type=str,
dest='config_file',
default='',
help="The file containing " +
"configuration parameters e.g. aapp_runner.cfg")
parser.add_argument("-s", "--station",
help="Name of the station",
dest="station",
type=str,
default="unknown")
parser.add_argument("-e", "--environment",
dest="environment",
type=str,
help="Name of the environment (e.g. dev, test, oper)")
parser.add_argument("-v", "--verbose",
help="print debug messages too",
action="store_true")
parser.add_argument("-l", "--log", help="File to log to",
type=str,
default=None)
args = parser.parse_args()
if args.config_file == '':
print "Configuration file required! aapp_runner.py <file>"
sys.exit()
if args.station == '':
print "Station required! Use command-line switch -s <station>"
sys.exit()
else:
station = args.station.lower()
if not args.environment:
print ("Environment required! " +
"Use command-line switch -e <environment> e.g. de, test")
sys.exit()
else:
env = args.environment.lower()
if 'template' in args.config_file:
print "Template file given as master config, aborting!"
sys.exit()
return station, env, args.config_file, args.log
def remove(path):
"""
Remove the file or directory
"""
if os.path.isdir(path):
try:
os.rmdir(path)
LOG.debug("Removing dir: " + path)
except OSError:
LOG.warning("Unable to remove folder: " + path)
else:
try:
if os.path.exists(path):
LOG.debug("Removing file:" + path)
os.remove(path)
except OSError:
LOG.debug("Unable to remove file: " + path)
def cleanup(number_of_days, path):
"""
Removes files from the passed in path that are older than or equal
to number_of_days
"""
time_in_secs = _time() - number_of_days * 24 * 60 * 60
for root, dirs, files in os.walk(path, topdown=False):
LOG.debug("root dirs files: " + root)
for file_ in files:
full_path = os.path.join(root, file_)
stat = os.stat(full_path)
if stat.st_mtime <= time_in_secs:
LOG.debug("Removing: " + full_path)
remove(full_path)
if not os.listdir(root):
LOG.debug("Removing root: " + root)
remove(root)
def delete_old_dirs(dir_path, older_than_days):
"""
Delete old directories
"""
LOG.debug("delete_old_dirs in progress..." + older_than_days)
older_than = older_than_days * 86400 # convert days to seconds
time_now = _time()
LOG.debug("after: " + dir_path)
for path, folders, files in os.walk(dir_path):
LOG.debug("path, folders, files:" + path + folders + files)
for folder in folders[:]:
folder_path = os.path.join(path, folder)
if (time_now - os.path.getmtime(folder_path)) > older_than:
yield folder_path
LOG.debug("Deleting folder " + folder)
# folders.remove(folder)
if __name__ == "__main__":
# Read config file
#
# pylint: disable=C0103
# C0103: Invalid name "%s" (should match %s)
# Used when the name doesn't match the regular expression
# associated to its type (constant, variable, class...).
config = RawConfigParser()
(station_name, environment, config_filename, log_file) = read_arguments()
if not os.path.isfile(config_filename):
# config.read(config_filename)
# else:
print "ERROR: ", config_filename, ": No such config file."
sys.exit()
run_options = read_config_file_options(config_filename,
station_name, environment)
if not isinstance(run_options, dict):
print "Reading config file failed: ", config_filename
sys.exit()
# Logging
config.read(config_filename)
logging_cfg = dict(config.items("logging"))
print "----------------------------------------\n"
print logging_cfg
if log_file is not None:
try:
ndays = int(logging_cfg["log_rotation_days"])
ncount = int(logging_cfg["log_rotation_backup"])
except KeyError as err:
print err.args, \
"is missing. Please, check your config file",\
config_filename
raise IOError("Log file was given but doesn't " +
"know how to backup and rotate")
handler = handlers.TimedRotatingFileHandler(log_file,
when='midnight',
interval=ndays,
backupCount=ncount,
encoding=None,
delay=False,
utc=True)
handler.doRollover()
else:
handler = logging.StreamHandler(sys.stderr)
if (logging_cfg["logging_mode"] and
logging_cfg["logging_mode"] == "DEBUG"):
loglevel = logging.DEBUG
else:
loglevel = logging.INFO
handler.setLevel(loglevel)
logging.getLogger('').setLevel(loglevel)
logging.getLogger('').addHandler(handler)
formatter = logging.Formatter(fmt=_DEFAULT_LOG_FORMAT,
datefmt=_DEFAULT_TIME_FORMAT)
handler.setFormatter(formatter)
logging.getLogger('posttroll').setLevel(logging.INFO)
LOG = logging.getLogger('aapp_runner')
if run_options['pps_out_dir'] == '':
LOG.warning("No pps_out_dir specified.")
for key in run_options:
print key, "=", run_options[key]
aapp_rolling_runner(run_options)
|
TAlonglong/trollduction-test
|
aapp_runner/aapp_dr_runner.py
|
Python
|
gpl-3.0
| 72,713
|
using System;
using System.Linq;
using KMCCC.Authentication;
using KMCCC.Launcher;
using OrigindLauncher.Resources.Configs;
namespace OrigindLauncher.Resources.Client
{
public class GameManager
{
public static bool IsRunning { get; private set; }
public event Action<LaunchHandle, int> OnGameExit;
public event Action<LaunchHandle, string> OnGameLog;
public event Action<LaunchResult> OnError;
public LaunchResult Run()
{
var launchercore =
LauncherCore.Create(new LauncherCoreCreationOption(javaPath: Config.Instance.JavaPath));
launchercore.GameLog += OnGameLog;
launchercore.GameExit += (handle, i) =>
{
OnGameExit?.Invoke(handle, i);
IsRunning = false;
};
var launchOptions = new LaunchOptions
{
Version = launchercore.GetVersion(Definitions.ClientName),
Authenticator = new OfflineAuthenticator(Config.Instance.PlayerAccount.Username),
Mode = LaunchMode.BmclMode,
MaxMemory = Config.Instance.MaxMemory
};
var result = launchercore.Launch(launchOptions, x =>
{
if (Config.Instance.JavaArguments.Contains("G1GC"))
x.CGCEnabled = false;
x.AdvencedArguments.Add(Config.Instance.JavaArguments);
});
IsRunning = true;
if (!result.Success)
{
OnError?.Invoke(result);
IsRunning = false;
}
return result;
/*
result.Handle.GetPrivateField<Process>(nameof(Process)).Exited += (sender, args) =>
{
IsRunning = false;
OnGameExit?.Invoke();
};
*/
}
}
}
|
The-GregTech-Team/OrigindLauncher
|
OrigindLauncher.Resources/Client/GameManager.cs
|
C#
|
gpl-3.0
| 1,909
|
package com.keniobyte.bruino.minsegapp.features.section_list_missing.missing_report;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author bruino
* @version 11/01/17.
*/
public interface IMissingReportInteractor {
void sendMissingReport(JSONObject missingReport, final OnSendReportFinishedListener listener) throws JSONException;
interface OnSendReportFinishedListener {
void sendMissingReportError();
//TODO: To implement in MinSegBe.
//void missingReportCoolDown();
void onSuccess();
}
}
|
Keniobyte/PoliceReportsMobile
|
app/src/main/java/com/keniobyte/bruino/minsegapp/features/section_list_missing/missing_report/IMissingReportInteractor.java
|
Java
|
gpl-3.0
| 560
|
# coding: utf-8
import time
import config_mqtt
class Asynch_result:
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mqtt.ASYNCH_RESULT_TIMEOUT):
# time.sleep(config_mqtt.ASYNCH_RESULT_WAIT_BEFORE_GET)
start_time = time.time()
request = self._requests_need_result.get(self.correlation_id)
if request:
while True:
current_time = time.time()
if request.get('is_replied'):
result = request.get('result')
# self._requests_need_result.pop(self.correlation_id)
return result
else:
if current_time - start_time > timeout: # timeout
# self._requests_need_result.pop(self.correlation_id)
raise Exception('Timeout: no result returned for request with correlation_id {}'.format(self.correlation_id))
else:
self.yield_to()
else:
raise Exception('No such request for request with correlation_id {}'.format(self.correlation_id))
|
Wei1234c/Elastic_Network_of_Things_with_MQTT_and_MicroPython
|
codes/node/asynch_result.py
|
Python
|
gpl-3.0
| 1,312
|
% \documentclass[10pt]{scrartcl}
\documentclass[10pt,twocolumn]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{authoraftertitle}
\setlength{\parindent}{0cm}
\setlength{\parskip}{3mm}
\setlength{\textheight}{23.8cm}
\setlength{\headheight}{1cm}
\setlength{\topmargin}{-10mm}
\setlength{\oddsidemargin}{0cm}
\setlength{\evensidemargin}{0cm}
\setlength{\textwidth}{16cm}
\setlength{\columnsep}{8mm}
\usepackage{multicol}
\usepackage{colortbl}
\usepackage{xcolor}
\definecolor{grau}{gray}{0.95}
\definecolor{dunkelgrau}{gray}{0.85}
\usepackage[normal]{caption}
\usepackage{lipsum}
\setlength{\parindent}{5mm}
\setlength{\parskip}{0mm}
\usepackage{float}
\restylefloat{figure}
\renewcommand{\topfraction}{0.75}
\renewcommand{\textfraction}{0.2}
%###########################################################
% die Sachen mit der Kopfzeile
\usepackage{lastpage}
\usepackage{fancyhdr}
\fancyhf{} % leere alle Felder
\fancyhead[R]{\footnotesize Phillip Schichtel: phillip.dhbw@schich.tel \\ Jonas Dann: jonas.chr.dann@gmail.com}
\fancyhead[L]{\footnotesize Ausgewählte Methoden der
Datenanalyse, \\ Modellierung und Simulation - Schattenberechnung} % Titel des Aufsatzes
\fancyfoot[C]{\footnotesize \thepage/\pageref{LastPage}}
% \fancyfoot[C]{\footnotesize \thepage}
\renewcommand{\headrulewidth}{0.4pt} % obere Trennlinie
\pagestyle{fancy}
%###########################################################
\title{Schattenberechnung im zweidimensionalen Raum}
\newcommand{\ownsection}[1]{\begin{center}\LARGE\bf#1\end{center}}
\begin{document}
\twocolumn[
\ownsection{\MyTitle}
\begin{center}
Phillip Schichtel (phillip.dhbw@schich.tel) \\
Jonas Dann (jonas.chr.dann@gmail.com) \\
Mannheim, November \the\year
\end{center}
\vspace*{5mm}
]
% \begin{multicols}{2}
\input{content/intro.tex}
\input{content/methods.tex}
\input{content/execution.tex}
\input{content/results.tex}
\input{content/discussion.tex}
\begin{thebibliography}{99}
\bibitem{monaco2014}Monaco: {\it http://www.monacoismine.com/} 22.11.2014
\bibitem{raytracing2014}Wikipedia\,Raytracing: {\it http://de.wikipedia.org/wiki/Raytracing} 22.11.2014
\bibitem{shadowmap2014}Wikipedia\,Shadow\,Mapping: {\it http://de.wikipedia.org/wiki/Shadow\_Mapping} 22.11.2014
\bibitem{shadowvol2014}Wikipedia\,Shadow\,Volume: {\it http://en.wikipedia.org/wiki/Shadow\_volume} 22.11.2014
\end{thebibliography}
\end{document}
|
Banana4Life/ShadowArea
|
paper/shadows.tex
|
TeX
|
gpl-3.0
| 2,522
|
/**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2013 Medical Physics Department, CHU of Liege,
* Belgium
*
* 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.
*
* In addition, as a special exception, the copyright holders of this
* program give permission to link the code of its release with the
* OpenSSL project's "OpenSSL" library (or with modified versions of it
* that use the same license as the "OpenSSL" library), and distribute
* the linked executables. You must obey the GNU General Public License
* in all respects for all of the code used other than "OpenSSL". If you
* modify file(s) with this exception, you may extend this exception to
* your version of the file(s), but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files
* in the program, then also delete it here.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include "DicomUserConnection.h"
#include "../../Core/OrthancException.h"
#include "../ToDcmtkBridge.h"
#include "../FromDcmtkBridge.h"
#include <dcmtk/dcmdata/dcistrmb.h>
#include <dcmtk/dcmdata/dcistrmf.h>
#include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmnet/diutil.h>
#include <set>
#ifdef _WIN32
/**
* "The maximum length, in bytes, of the string returned in the buffer
* pointed to by the name parameter is dependent on the namespace provider,
* but this string must be 256 bytes or less.
* http://msdn.microsoft.com/en-us/library/windows/desktop/ms738527(v=vs.85).aspx
**/
#define HOST_NAME_MAX 256
#endif
namespace Orthanc
{
struct DicomUserConnection::PImpl
{
// Connection state
T_ASC_Network* net_;
T_ASC_Parameters* params_;
T_ASC_Association* assoc_;
bool IsOpen() const
{
return assoc_ != NULL;
}
void CheckIsOpen() const;
void Store(DcmInputStream& is);
};
static void Check(const OFCondition& cond)
{
if (cond.bad())
{
throw OrthancException("DicomUserConnection: " + std::string(cond.text()));
}
}
void DicomUserConnection::PImpl::CheckIsOpen() const
{
if (!IsOpen())
{
throw OrthancException("DicomUserConnection: First open the connection");
}
}
void DicomUserConnection::CheckIsOpen() const
{
pimpl_->CheckIsOpen();
}
void DicomUserConnection::CopyParameters(const DicomUserConnection& other)
{
Close();
localAet_ = other.localAet_;
distantAet_ = other.distantAet_;
distantHost_ = other.distantHost_;
distantPort_ = other.distantPort_;
}
void DicomUserConnection::SetupPresentationContexts()
{
// The preferred abstract syntax
std::string preferredSyntax = UID_LittleEndianImplicitTransferSyntax;
// Fallback abstract syntaxes
std::set<std::string> abstractSyntaxes;
abstractSyntaxes.insert(UID_LittleEndianExplicitTransferSyntax);
abstractSyntaxes.insert(UID_BigEndianExplicitTransferSyntax);
abstractSyntaxes.insert(UID_LittleEndianImplicitTransferSyntax);
abstractSyntaxes.erase(preferredSyntax);
assert(abstractSyntaxes.size() == 2);
// Transfer syntaxes for C-ECHO, C-FIND and C-MOVE
std::vector<std::string> transferSyntaxes;
transferSyntaxes.push_back(UID_VerificationSOPClass);
transferSyntaxes.push_back(UID_FINDPatientRootQueryRetrieveInformationModel);
transferSyntaxes.push_back(UID_FINDStudyRootQueryRetrieveInformationModel);
transferSyntaxes.push_back(UID_MOVEStudyRootQueryRetrieveInformationModel);
// TODO: Allow the set below to be configured
std::set<std::string> uselessSyntaxes;
uselessSyntaxes.insert(UID_BlendingSoftcopyPresentationStateStorage);
uselessSyntaxes.insert(UID_GrayscaleSoftcopyPresentationStateStorage);
uselessSyntaxes.insert(UID_ColorSoftcopyPresentationStateStorage);
uselessSyntaxes.insert(UID_PseudoColorSoftcopyPresentationStateStorage);
// Add the transfer syntaxes for C-STORE
for (int i = 0; i < numberOfDcmShortSCUStorageSOPClassUIDs - 1; i++)
{
// Test to make some room to allow the ECHO and FIND requests
if (uselessSyntaxes.find(dcmShortSCUStorageSOPClassUIDs[i]) == uselessSyntaxes.end())
{
transferSyntaxes.push_back(dcmShortSCUStorageSOPClassUIDs[i]);
}
}
// Flatten the fallback abstract syntaxes array
const char* asPreferred[1] = { preferredSyntax.c_str() };
const char* asFallback[2];
std::set<std::string>::const_iterator it = abstractSyntaxes.begin();
asFallback[0] = it->c_str();
it++;
asFallback[1] = it->c_str();
unsigned int presentationContextId = 1;
for (size_t i = 0; i < transferSyntaxes.size(); i++)
{
Check(ASC_addPresentationContext(pimpl_->params_, presentationContextId,
transferSyntaxes[i].c_str(), asPreferred, 1));
presentationContextId += 2;
Check(ASC_addPresentationContext(pimpl_->params_, presentationContextId,
transferSyntaxes[i].c_str(), asFallback, 2));
presentationContextId += 2;
}
}
void DicomUserConnection::PImpl::Store(DcmInputStream& is)
{
CheckIsOpen();
DcmFileFormat dcmff;
Check(dcmff.read(is, EXS_Unknown, EGL_noChange, DCM_MaxReadLength));
// Figure out which SOP class and SOP instance is encapsulated in the file
DIC_UI sopClass;
DIC_UI sopInstance;
if (!DU_findSOPClassAndInstanceInDataSet(dcmff.getDataset(), sopClass, sopInstance))
{
throw OrthancException("DicomUserConnection: Unable to find the SOP class and instance");
}
// Figure out which of the accepted presentation contexts should be used
int presID = ASC_findAcceptedPresentationContextID(assoc_, sopClass);
if (presID == 0)
{
const char *modalityName = dcmSOPClassUIDToModality(sopClass);
if (!modalityName) modalityName = dcmFindNameOfUID(sopClass);
if (!modalityName) modalityName = "unknown SOP class";
throw OrthancException("DicomUserConnection: No presentation context for modality " +
std::string(modalityName));
}
// Prepare the transmission of data
T_DIMSE_C_StoreRQ req;
memset(&req, 0, sizeof(req));
req.MessageID = assoc_->nextMsgID++;
strcpy(req.AffectedSOPClassUID, sopClass);
strcpy(req.AffectedSOPInstanceUID, sopInstance);
req.DataSetType = DIMSE_DATASET_PRESENT;
req.Priority = DIMSE_PRIORITY_MEDIUM;
// Finally conduct transmission of data
T_DIMSE_C_StoreRSP rsp;
DcmDataset* statusDetail = NULL;
Check(DIMSE_storeUser(assoc_, presID, &req,
NULL, dcmff.getDataset(), /*progressCallback*/ NULL, NULL,
/*opt_blockMode*/ DIMSE_BLOCKING, /*opt_dimse_timeout*/ 0,
&rsp, &statusDetail, NULL));
if (statusDetail != NULL)
{
delete statusDetail;
}
}
static void FindCallback(
/* in */
void *callbackData,
T_DIMSE_C_FindRQ *request, /* original find request */
int responseCount,
T_DIMSE_C_FindRSP *response, /* pending response received */
DcmDataset *responseIdentifiers /* pending response identifiers */
)
{
DicomFindAnswers& answers = *(DicomFindAnswers*) callbackData;
if (responseIdentifiers != NULL)
{
DicomMap m;
FromDcmtkBridge::Convert(m, *responseIdentifiers);
answers.Add(m);
}
}
void DicomUserConnection::Find(DicomFindAnswers& result,
FindRootModel model,
const DicomMap& fields)
{
CheckIsOpen();
const char* sopClass;
std::auto_ptr<DcmDataset> dataset(ToDcmtkBridge::Convert(fields));
switch (model)
{
case FindRootModel_Patient:
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0052), "PATIENT");
sopClass = UID_FINDPatientRootQueryRetrieveInformationModel;
// Accession number
if (!fields.HasTag(0x0008, 0x0050))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0050), "");
// Patient ID
if (!fields.HasTag(0x0010, 0x0020))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0010, 0x0020), "");
break;
case FindRootModel_Study:
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0052), "STUDY");
sopClass = UID_FINDStudyRootQueryRetrieveInformationModel;
// Accession number
if (!fields.HasTag(0x0008, 0x0050))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0050), "");
// Study instance UID
if (!fields.HasTag(0x0020, 0x000d))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0020, 0x000d), "");
break;
case FindRootModel_Series:
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0052), "SERIES");
sopClass = UID_FINDStudyRootQueryRetrieveInformationModel;
// Accession number
if (!fields.HasTag(0x0008, 0x0050))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0050), "");
// Study instance UID
if (!fields.HasTag(0x0020, 0x000d))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0020, 0x000d), "");
// Series instance UID
if (!fields.HasTag(0x0020, 0x000e))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0020, 0x000e), "");
break;
case FindRootModel_Instance:
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0052), "INSTANCE");
sopClass = UID_FINDStudyRootQueryRetrieveInformationModel;
// Accession number
if (!fields.HasTag(0x0008, 0x0050))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0050), "");
// Study instance UID
if (!fields.HasTag(0x0020, 0x000d))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0020, 0x000d), "");
// Series instance UID
if (!fields.HasTag(0x0020, 0x000e))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0020, 0x000e), "");
// SOP Instance UID
if (!fields.HasTag(0x0008, 0x0018))
DU_putStringDOElement(dataset.get(), DcmTagKey(0x0008, 0x0018), "");
break;
default:
throw OrthancException(ErrorCode_ParameterOutOfRange);
}
// Figure out which of the accepted presentation contexts should be used
int presID = ASC_findAcceptedPresentationContextID(pimpl_->assoc_, sopClass);
if (presID == 0)
{
throw OrthancException("DicomUserConnection: The C-FIND command is not supported by the distant AET");
}
T_DIMSE_C_FindRQ request;
memset(&request, 0, sizeof(request));
request.MessageID = pimpl_->assoc_->nextMsgID++;
strcpy(request.AffectedSOPClassUID, sopClass);
request.DataSetType = DIMSE_DATASET_PRESENT;
request.Priority = DIMSE_PRIORITY_MEDIUM;
T_DIMSE_C_FindRSP response;
DcmDataset* statusDetail = NULL;
OFCondition cond = DIMSE_findUser(pimpl_->assoc_, presID, &request, dataset.get(),
FindCallback, &result,
/*opt_blockMode*/ DIMSE_BLOCKING, /*opt_dimse_timeout*/ 0,
&response, &statusDetail);
if (statusDetail)
{
delete statusDetail;
}
Check(cond);
}
void DicomUserConnection::FindPatient(DicomFindAnswers& result,
const DicomMap& fields)
{
// Only keep the filters from "fields" that are related to the patient
DicomMap s;
fields.ExtractPatientInformation(s);
Find(result, FindRootModel_Patient, s);
}
void DicomUserConnection::FindStudy(DicomFindAnswers& result,
const DicomMap& fields)
{
// Only keep the filters from "fields" that are related to the study
DicomMap s;
fields.ExtractStudyInformation(s);
s.CopyTagIfExists(fields, DICOM_TAG_PATIENT_ID);
s.CopyTagIfExists(fields, DICOM_TAG_ACCESSION_NUMBER);
Find(result, FindRootModel_Study, s);
}
void DicomUserConnection::FindSeries(DicomFindAnswers& result,
const DicomMap& fields)
{
// Only keep the filters from "fields" that are related to the series
DicomMap s;
fields.ExtractSeriesInformation(s);
s.CopyTagIfExists(fields, DICOM_TAG_PATIENT_ID);
s.CopyTagIfExists(fields, DICOM_TAG_ACCESSION_NUMBER);
s.CopyTagIfExists(fields, DICOM_TAG_STUDY_INSTANCE_UID);
Find(result, FindRootModel_Series, s);
}
void DicomUserConnection::FindInstance(DicomFindAnswers& result,
const DicomMap& fields)
{
// Only keep the filters from "fields" that are related to the instance
DicomMap s;
fields.ExtractInstanceInformation(s);
s.CopyTagIfExists(fields, DICOM_TAG_PATIENT_ID);
s.CopyTagIfExists(fields, DICOM_TAG_ACCESSION_NUMBER);
s.CopyTagIfExists(fields, DICOM_TAG_STUDY_INSTANCE_UID);
s.CopyTagIfExists(fields, DICOM_TAG_SERIES_INSTANCE_UID);
Find(result, FindRootModel_Instance, s);
}
void DicomUserConnection::Move(const std::string& targetAet,
const DicomMap& fields)
{
CheckIsOpen();
const char* sopClass = UID_MOVEStudyRootQueryRetrieveInformationModel;
std::auto_ptr<DcmDataset> dataset(ToDcmtkBridge::Convert(fields));
// Figure out which of the accepted presentation contexts should be used
int presID = ASC_findAcceptedPresentationContextID(pimpl_->assoc_, sopClass);
if (presID == 0)
{
throw OrthancException("DicomUserConnection: The C-MOVE command is not supported by the distant AET");
}
T_DIMSE_C_MoveRQ request;
memset(&request, 0, sizeof(request));
request.MessageID = pimpl_->assoc_->nextMsgID++;
strcpy(request.AffectedSOPClassUID, sopClass);
request.DataSetType = DIMSE_DATASET_PRESENT;
request.Priority = DIMSE_PRIORITY_MEDIUM;
strncpy(request.MoveDestination, targetAet.c_str(), sizeof(DIC_AE) / sizeof(char));
T_DIMSE_C_MoveRSP response;
DcmDataset* statusDetail = NULL;
DcmDataset* responseIdentifiers = NULL;
OFCondition cond = DIMSE_moveUser(pimpl_->assoc_, presID, &request, dataset.get(),
NULL, NULL,
/*opt_blockMode*/ DIMSE_BLOCKING, /*opt_dimse_timeout*/ 0,
pimpl_->net_, NULL, NULL,
&response, &statusDetail, &responseIdentifiers);
if (statusDetail)
{
delete statusDetail;
}
if (responseIdentifiers)
{
delete responseIdentifiers;
}
Check(cond);
}
DicomUserConnection::DicomUserConnection() : pimpl_(new PImpl)
{
localAet_ = "STORESCU";
distantAet_ = "ANY-SCP";
distantPort_ = 104;
distantHost_ = "127.0.0.1";
pimpl_->net_ = NULL;
pimpl_->params_ = NULL;
pimpl_->assoc_ = NULL;
}
DicomUserConnection::~DicomUserConnection()
{
Close();
}
void DicomUserConnection::SetLocalApplicationEntityTitle(const std::string& aet)
{
Close();
localAet_ = aet;
}
void DicomUserConnection::SetDistantApplicationEntityTitle(const std::string& aet)
{
Close();
distantAet_ = aet;
}
void DicomUserConnection::SetDistantHost(const std::string& host)
{
if (host.size() > HOST_NAME_MAX - 10)
{
throw OrthancException("Distant host name is too long");
}
Close();
distantHost_ = host;
}
void DicomUserConnection::SetDistantPort(uint16_t port)
{
Close();
distantPort_ = port;
}
void DicomUserConnection::Open()
{
Close();
Check(ASC_initializeNetwork(NET_REQUESTOR, 0, /*opt_acse_timeout*/ 30, &pimpl_->net_));
Check(ASC_createAssociationParameters(&pimpl_->params_, /*opt_maxReceivePDULength*/ ASC_DEFAULTMAXPDU));
// Set this application's title and the called application's title in the params
Check(ASC_setAPTitles(pimpl_->params_, localAet_.c_str(), distantAet_.c_str(), NULL));
// Set the network addresses of the local and distant entities
char localHost[HOST_NAME_MAX];
gethostname(localHost, HOST_NAME_MAX - 1);
char distantHostAndPort[HOST_NAME_MAX];
#ifdef _MSC_VER
_snprintf
#else
snprintf
#endif
(distantHostAndPort, HOST_NAME_MAX - 1, "%s:%d", distantHost_.c_str(), distantPort_);
Check(ASC_setPresentationAddresses(pimpl_->params_, localHost, distantHostAndPort));
// Set various options
Check(ASC_setTransportLayerType(pimpl_->params_, /*opt_secureConnection*/ false));
SetupPresentationContexts();
// Do the association
Check(ASC_requestAssociation(pimpl_->net_, pimpl_->params_, &pimpl_->assoc_));
if (ASC_countAcceptedPresentationContexts(pimpl_->params_) == 0)
{
throw OrthancException("DicomUserConnection: No Acceptable Presentation Contexts");
}
}
void DicomUserConnection::Close()
{
if (pimpl_->assoc_ != NULL)
{
ASC_releaseAssociation(pimpl_->assoc_);
ASC_destroyAssociation(&pimpl_->assoc_);
pimpl_->assoc_ = NULL;
pimpl_->params_ = NULL;
}
else
{
if (pimpl_->params_ != NULL)
{
ASC_destroyAssociationParameters(&pimpl_->params_);
pimpl_->params_ = NULL;
}
}
if (pimpl_->net_ != NULL)
{
ASC_dropNetwork(&pimpl_->net_);
pimpl_->net_ = NULL;
}
}
bool DicomUserConnection::IsOpen() const
{
return pimpl_->IsOpen();
}
void DicomUserConnection::Store(const char* buffer, size_t size)
{
// Prepare an input stream for the memory buffer
DcmInputBufferStream is;
if (size > 0)
is.setBuffer(buffer, size);
is.setEos();
pimpl_->Store(is);
}
void DicomUserConnection::Store(const std::string& buffer)
{
if (buffer.size() > 0)
Store(reinterpret_cast<const char*>(&buffer[0]), buffer.size());
else
Store(NULL, 0);
}
void DicomUserConnection::StoreFile(const std::string& path)
{
// Prepare an input stream for the file
DcmInputFileStream is(path.c_str());
pimpl_->Store(is);
}
bool DicomUserConnection::Echo()
{
CheckIsOpen();
DIC_US status;
Check(DIMSE_echoUser(pimpl_->assoc_, pimpl_->assoc_->nextMsgID++,
/*opt_blockMode*/ DIMSE_BLOCKING, /*opt_dimse_timeout*/ 0,
&status, NULL));
return status == STATUS_Success;
}
void DicomUserConnection::MoveSeries(const std::string& targetAet,
const DicomMap& findResult)
{
DicomMap simplified;
simplified.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, findResult.GetValue(DICOM_TAG_STUDY_INSTANCE_UID));
simplified.SetValue(DICOM_TAG_SERIES_INSTANCE_UID, findResult.GetValue(DICOM_TAG_SERIES_INSTANCE_UID));
Move(targetAet, simplified);
}
void DicomUserConnection::MoveSeries(const std::string& targetAet,
const std::string& studyUid,
const std::string& seriesUid)
{
DicomMap map;
map.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, studyUid);
map.SetValue(DICOM_TAG_SERIES_INSTANCE_UID, seriesUid);
Move(targetAet, map);
}
void DicomUserConnection::MoveInstance(const std::string& targetAet,
const DicomMap& findResult)
{
DicomMap simplified;
simplified.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, findResult.GetValue(DICOM_TAG_STUDY_INSTANCE_UID));
simplified.SetValue(DICOM_TAG_SERIES_INSTANCE_UID, findResult.GetValue(DICOM_TAG_SERIES_INSTANCE_UID));
simplified.SetValue(DICOM_TAG_SOP_INSTANCE_UID, findResult.GetValue(DICOM_TAG_SOP_INSTANCE_UID));
Move(targetAet, simplified);
}
void DicomUserConnection::MoveInstance(const std::string& targetAet,
const std::string& studyUid,
const std::string& seriesUid,
const std::string& instanceUid)
{
DicomMap map;
map.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, studyUid);
map.SetValue(DICOM_TAG_SERIES_INSTANCE_UID, seriesUid);
map.SetValue(DICOM_TAG_SOP_INSTANCE_UID, instanceUid);
Move(targetAet, map);
}
void DicomUserConnection::SetConnectionTimeout(uint32_t seconds)
{
dcmConnectionTimeout.set(seconds);
}
}
|
amirkogithub/orthanc
|
OrthancServer/DicomProtocol/DicomUserConnection.cpp
|
C++
|
gpl-3.0
| 20,983
|
package uk.co.robbie_wilson.moddedtoolkit.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class Reload implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
if(label.equalsIgnoreCase("mtreload")){
}
return false;
}
}
|
robbo5899/Modded-Toolkit
|
src/main/java/uk/co/robbie_wilson/moddedtoolkit/commands/Reload.java
|
Java
|
gpl-3.0
| 432
|
/*
* This file is part of KNLMeansCL,
* Copyright(C) 2015-2020 Edoardo Brunetti.
*
* KNLMeansCL 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.
*
* KNLMeansCL 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 KNLMeansCL. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __OCL_UTILS_H
#define __OCL_UTILS_H
#define CL_TARGET_OPENCL_VERSION 120
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
//////////////////////////////////////////
// Type Definition
#define OCL_UTILS_DEVICE_TYPE_CPU (1 << 0)
#define OCL_UTILS_DEVICE_TYPE_GPU (1 << 1)
#define OCL_UTILS_DEVICE_TYPE_ACCELERATOR (1 << 2)
#define OCL_UTILS_DEVICE_TYPE_AUTO (1 << 3)
#define OCL_UTILS_MALLOC_ERROR 1
#define OCL_UTILS_NO_DEVICE_AVAILABLE 2
#define OCL_UTILS_INVALID_DEVICE_TYPE 3
#define OCL_UTILS_INVALID_VALUE 4
#define OCL_UTILS_OPENCL_1_0 10
#define OCL_UTILS_OPENCL_1_1 11
#define OCL_UTILS_OPENCL_1_2 12
#define OCL_UTILS_OPENCL_2_0 20
#define OCL_UTILS_OPENCL_2_1 21
#define OCL_UTILS_OPENCL_2_2 22
//////////////////////////////////////////
// Functions
const char* oclUtilsErrorToString(
cl_int err
);
cl_int oclUtilsCheckPlatform(
cl_platform_id platofrm,
bool *compatible
);
cl_int oclUtilsCheckDevice(
cl_device_id device,
bool *compatible
);
cl_int oclUtilsGetIDs(
cl_device_type device_type,
cl_uint shf_device,
cl_platform_id *platform,
cl_device_id *device
);
cl_int oclUtilsGetPlaformDeviceIDs(
cl_uint device_type,
cl_uint shf_device,
cl_platform_id *platform,
cl_device_id *device
);
void oclUtilsDebugInfo(
cl_platform_id platform,
cl_device_id device,
cl_program program,
cl_int errcode
);
#endif //__OCLUTILS_H__
|
Khanattila/KNLMeansCL
|
KNLMeansCL/shared/ocl_utils.h
|
C
|
gpl-3.0
| 2,383
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Define all the backup steps that will be used by the backup_url_activity_task
*
* @package mod_url
* @copyright 2010 onwards Andrew Davis
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Define the complete url structure for backup, with file and id annotations
*/
class backup_url_activity_structure_step extends backup_activity_structure_step {
protected function define_structure() {
//the URL module stores no user info
// Define each element separated
$url = new backup_nested_element('url', array('id'), array(
'name', 'intro', 'introformat', 'externalurl',
'display', 'displayoptions', 'parameters', 'timemodified'));
// Build the tree
//nothing here for URLs
// Define sources
$url->set_source_table('url', array('id' => backup::VAR_ACTIVITYID));
// Define id annotations
//module has no id annotations
// Define file annotations
$url->annotate_files('mod_url', 'intro', null); // This file area hasn't itemid
// Return the root element (url), wrapped into standard activity structure
return $this->prepare_activity_structure($url);
}
}
|
murilotimo/moodle
|
mod/url/backup/moodle2/backup_url_stepslib.php
|
PHP
|
gpl-3.0
| 2,028
|
###
# Copyright 2016 - 2022 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md
###
module HudTwentyTwentyToTwentyTwentyTwo::Export
class Csv < Transforms
include HudTwentyTwentyToTwentyTwentyTwo::Kiba::CsvBase
end
end
|
greenriver/hmis-warehouse
|
drivers/hud_twenty_twenty_to_twenty_twenty_two/app/models/hud_twenty_twenty_to_twenty_twenty_two/export/csv.rb
|
Ruby
|
gpl-3.0
| 299
|
#!/usr/bin/env ruby -w -rbork
# bork is copyright (c) 2012 Noel R. Cower.
#
# This file is part of bork.
#
# bork 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.
#
# bork 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 bork. If not, see <http://www.gnu.org/licenses/>.
require 'bork/aux'
require 'bork/hub'
module Bork
module Commands
class AddCommand
def self.command
:add
end
def run args, options = {}
files = nil
tags = nil
station = nil
begin
files, tags = Bork.extract_file_tag_arguments args
station = Bork::Station.new options[:station]
rescue RuntimeError => ex
puts "bork-add: #{ex}"
exit 1
end
if tags.empty?
puts "bork-add: No tags specified."
exit 1
elsif files.empty?
puts "bork-add: No files specified."
exit 1
end
files.map {
|file_path|
station.index_file! file_path, options
}.each {
|hash|
station.tag_hash! tags, hash, options
}
end
def help_string
''
end
Bork::Hub.default_hub.add_command_class self
if __FILE__ == $0
self.new.run ARGV
end
end # AddCommand
end # Commands
end # Bork
|
nilium/bork
|
lib/bork/commands/add.rb
|
Ruby
|
gpl-3.0
| 1,773
|
#ifndef __DV_TEST_CONF_H__
#define __DV_TEST_CONF_H__
#include <netinet/in.h>
#include "dv_server_conf.h"
#define DV_CONF_BACKEND_ADDR_MAX_NUM 128
typedef struct _dv_backend_addr_t {
char ba_addr[DV_IP_ADDRESS_LEN];
dv_u16 ba_port;
} dv_backend_addr_t;
typedef struct _dv_test_conf_t {
dv_backend_addr_t cf_backend_addrs[DV_CONF_BACKEND_ADDR_MAX_NUM];
dv_u16 cf_backend_addr_num;
dv_u16 cf_curr;
} dv_test_conf_t;
typedef struct _dv_test_conf_parse_t {
char *cp_name;
int cp_type;
int (*cp_parser)(dv_backend_addr_t *addr, json_object *param);
} dv_test_conf_parse_t;
extern dv_test_conf_t dv_test_conf;
extern int dv_test_conf_parse(dv_srv_conf_t *conf, char *file);
#endif
|
jasonchin221/DoveVPN
|
test/src/dv_test_conf.h
|
C
|
gpl-3.0
| 778
|
#!/bin/bash
sudo apt-get build-dep emacs
sudo apt-get install libjansson-dev valgrind fonts-firacode
## On Linux Mint, at least, these are not installed when the above is done. Curious.
## On other systems, it can't hurt.
sudo apt-get install texinfo libxpm-dev libjpeg-dev libgif-dev libtiff-dev libtinfo-dev
|
wdenton/conforguration
|
conforg/scripts/emacs-install-requirements.sh
|
Shell
|
gpl-3.0
| 311
|
var __v=[
{
"Id": 2478,
"Panel": 1245,
"Name": "number",
"Sort": 0,
"Str": ""
}
]
|
zuiwuchang/king-document
|
data/panels/1245.js
|
JavaScript
|
gpl-3.0
| 101
|
/**
* This file is part of the Amacube-Remix_WBList Roundcube plugin
* Copyright (C) 2015, Tony VanGerpen <Tony.VanGerpen@hotmail.com>
*
* A Roundcube plugin to let users manage whitelist/blacklist (which must be stored in a database)
* Based heavily on the amacube plugin by Alexander Köb (https://github.com/akoeb/amacube)
*
* Licensed under the GNU General Public License version 3.
* See the COPYING file in parent directory for a full license statement.
*/
li#settingstabpluginamacuberemixwblist a.amacube_remix_wblist { background-position: 6px -1554px; }
li#settingstabpluginamacuberemixwblist.selected a.amacube_remix_wblist { background-position: 6px -1578px; }
|
tvangerpen/amacube-remix
|
amacube_remix_wblist/styles/amacube_remix_wblist.icon.css
|
CSS
|
gpl-3.0
| 676
|
[](https://travis-ci.org/zertrin/duplicity-backup)
# duplicity-backup.sh
This bash script was designed to automate and simplify the remote backup process of [duplicity](http://duplicity.nongnu.org/) on Amazon S3 primarily. Other backup destinations are possible (Google Cloud Storage, FTP, SFTP, SCP, rsync, file...), i.e. any of duplicity's supported outputs.
After your script is configured, you can easily backup, restore, verify and clean (either via cron or manually) your data without having to remember lots of different command options and passphrases.
Most importantly, you can easily backup the script and your gpg key in a convenient passphrase-encrypted file. This comes in in handy if/when your machine ever does go belly up.
Optionally, you can set up an email address where the log file will be sent, which is useful when the script is used via cron.
This version is a rewriting of the code originally written by [Damon Timm](https://github.com/thornomad), including many patches that have been brought to the original scripts by various forks on Github. Thanks to all the contributors!
More information about this script is available at https://zertrin.org/projects/duplicity-backup/
The original version of the code is available at https://github.com/theterran/dt-s3-backup
## duplicity-backup.sh IS NOT duplicity
It is only a wrapper script for duplicity written in bash!
This means the following:
* You need to install AND configure duplicity BEFORE using duplicity-backup.sh
* [The official documentation of duplicity](http://duplicity.nongnu.org/duplicity.1.html) is relevant to duplicity-backup.sh too. Virtually any option supported by duplicity can be specified in the config file of duplicity-backup.sh. See the `STATIC_OPTIONS`, `CLEAN_UP_TYPE` and `CLEAN_UP_VARIABLE` parameters in particular.
* Before asking something about duplicity-backup.sh, ensure that your question isn’t actually concerning duplicity ;) First, make sure you can perform a backup with duplicity without using this script. If you can't make the backup work with duplicity alone, the problem is probably concerning duplicity and not this script. If you manage to make a backup with duplicity alone but not with this script, then there is probably a problem with duplicity-backup.sh.
* In particular, to the question "_Does duplicity-backup.sh support the backend XXX_" (with XXX being for example Amazon Glacier), the answer is always the same: "_duplicity-backup.sh uses duplicity, so ask the developers of duplicity ;) Once it's in duplicity, it's automatically available to duplicity-backup.sh_"
## Contributing
The development version of the code is available at https://github.com/zertrin/duplicity-backup in the `dev` branch. It is a bleeding-edge version with the latests changes that have not yet been tested a lot, but that's the best starting point to contribute.
Pull requests are welcome! However please **always use individual feature branches for each pull request**. I may not accept a pull request from a master or dev branch.
Here is how to do it:
Fork the repository first and then clone your fork on your machine:
git clone git@github.com:YOURNAME/duplicity-backup.git
cd duplicity-backup
Add a remote for the upstream repository:
git remote add upstream git@github.com:zertrin/duplicity-backup.git
git fetch upstream
Create a new topic branch for the changes you want to make, based on the `dev` branch from upstream:
git checkout -b my-fix-1 upstream/dev
Make your changes, test them, commit them and push them to Github:
git push origin my-fix-1
Open a Pull request from `YOURNAME:my-fix-1` to `zertrin:dev`.
If you want to open another pull request for another change which is independant of the previous one, just create another topic branch based on master (`git checkout -b my-fix-2 upstream/dev`)
## Installation
### 1. Get the script
You can clone the repository (which makes it easy to get future updates):
git clone https://github.com/zertrin/duplicity-backup.git duplicity-backup
If you prefer the stable version do:
git checkout stable
... or if you want the latest version (might still have bugs), then:
git checkout master
... or if you like living on the edge, you can stay at the development version which is automatically cloned.
Or just download the ZIP file:
* For the stable branch: https://github.com/zertrin/duplicity-backup/archive/stable.zip
* For the normal branch: https://github.com/zertrin/duplicity-backup/archive/master.zip
### 2. Configure the script
This script requires user configuration. Instructions are in the config file itself and should be self-explanatory. You SHOULD NOT edit the example config file `duplicity-backup.conf.example`, but instead make a copy of it (for example to `/etc/duplicity-backup.conf`) and edit this one.
Be sure to replace all the *foobar* values with your real ones. Almost every value needs to be configured in someway.
The script looks for its configuration by reading the path to the config file specified by the command line option `-c` or `--config` (see [Usage](#usage))
If no config file was given on the command line, the script will try to find the file specified in the `CONFIG` parameter at the beginning of the script (default: `duplicity-backup.conf` in the script's directory).
So be sure to either:
* specify the configuration file path on the command line with the -c option **[recommended]**
* or to edit the `CONFIG` parameter in the script to match the actual location of your config file. **[deprecated]** _(will be removed in future versions of the script)_
NOTE: to ease future updates of the script, you may prefer NOT to edit the script at all and to specify systematically the path to your config file on the command line with the `-c` or `--config` option.
You can use one copy of the script and call it with different config file for different backup scenarios. It is designed to run as a cron job and will log information to a text file (including remote file sizes, if you use Amazon S3 and have `s3cmd` installed).
### Misc
Be sure to make the script executable if needed (`chmod +x`) before you hit the gas.
## Upgrade
### 1. Get the new version
If you got the script by cloning the repository, upgrading is easy:
git pull
else just download again the ZIP archive an extract it over the existing folder. (Don't forget to keep a backup of the previous folder to be able to rollback easily if needed)
### 2. Adapt the config file if needed
Then compare the example config file (`duplicity-backup.conf.example`) with your modified version (for example `/etc/duplicity-backup.conf`) and adapt your copy to reflect the changes in the example file.
Thare are many ways to do so, here are some examples (adapt the path to your actual files):
diff duplicity-backup.conf.example /etc/duplicity-backup.conf
vimdiff duplicity-backup.conf.example /etc/duplicity-backup.conf
## Dependancies
* [duplicity](http://duplicity.nongnu.org/)
* Basic utilities like: [bash](https://www.gnu.org/software/bash/), [which](http://unixhelp.ed.ac.uk/CGI/man-cgi?which), [find](https://www.gnu.org/software/findutils/) and [tee](http://linux.die.net/man/1/tee) (should already be available on most Linux systems)
* [gpg](https://www.gnupg.org/) *`optional`* (if using encryption)
* [mailx](http://linux.die.net/man/1/mailx) *`optional`* (if sending mail is activated in the script)
For the [Amazon S3](https://aws.amazon.com/s3/) storage backend *`optional`*
* [s3cmd](http://s3tools.org/s3cmd) *`optional`*
For the [Google Cloud Storage](https://cloud.google.com/storage/) storage backend *`optional`*
* [boto](https://github.com/boto/boto) (may already have been installed with duplicity)
* [gsutil](https://cloud.google.com/storage/docs/gsutil) *`optional`*
## Usage
duplicity-backup.sh [options]
Options:
-c, --config CONFIG_FILE specify the config file to use
-b, --backup runs an incremental backup
-f, --full forces a full backup
-v, --verify verifies the backup
-l, --list-current-files lists the files currently backed up in the archive
-s, --collection-status show all the backup sets in the archive
--restore [PATH] restores the entire backup to [path]
--restore-file [FILE_TO_RESTORE] [DESTINATION]
restore a specific file
--restore-dir [DIR_TO_RESTORE] [DESTINATION]
restore a specific directory
-t, --time TIME specify the time from which to restore or list files
(see duplicity man page for the format)
--backup-script automatically backup the script and secret key(s) to
the current working directory
-n, --dry-run perform a trial run with no changes made
-d, --debug echo duplicity commands to logfile
## Usage Examples
**View help:**
duplicity-backup.sh
**Run an incremental backup:**
duplicity-backup.sh [-c config_file] --backup
**Force a one-off full backup:**
duplicity-backup.sh [-c config_file] --full
**Restore your entire backup:**
# You will be prompted for a restore directory
duplicity-backup.sh [-c config_file] --restore
# You can also provide a restore folder on the command line.
duplicity-backup.sh [-c config_file] --restore /home/user/restore-folder
**Restore a specific file or directory in the backup:**
Note that the commands `--restore-file` and `--restore-dir` are equivalent.
# You will be prompted for a file to restore to the current directory
duplicity-backup.sh [-c config_file] --restore-file
# Restores the file img/mom.jpg to the current directory
duplicity-backup.sh [-c config_file] --restore-file img/mom.jpg
# Restores the file img/mom.jpg to /home/user/i-love-mom.jpg
duplicity-backup.sh [-c config_file] --restore-file img/mom.jpg /home/user/i-love-mom.jpg
# Restores the directory rel/dir/path to /target/restorepath
duplicity-backup.sh [-c config_file] --restore-dir rel/dir/path /target/restorepath
**List files in the remote archive**
duplicity-backup.sh [-c config_file] --list-current-files
**See the collection status (i.e. all the backup sets in the remote archive)**
duplicity-backup.sh [-c config_file] --collection-status
**Verify the backup**
duplicity-backup.sh [-c config_file] --verify
**Backup the script and gpg key in a encrypted tarfile (for safekeeping)**
duplicity-backup.sh [-c config_file] --backup-script
## Cron Usage Example
41 3 * * * /absolute/path/to/duplicity-backup.sh -c /etc/duplicity-backup.conf -b
## Known issues
If your system's locale is not english, an error can happen when duplicity is trying to encrypt the files with gpg. This problem concerns duplicity and has been reported upstream ([see bug report](https://bugs.launchpad.net/duplicity/+bug/510625)). A simple workaround is to set the following environement variable: `LANG=C`. For example: `LANG=C duplicity-backup.sh [-c config_file] ...` or in the cron `41 3 * * * LANG=C /absolute/path/to/duplicity-backup.sh -c /etc/duplicity-backup.conf -b`
## Troubleshooting
This script attempts to simplify the task of running a duplicity command; if you are having any problems with the script the first step is to determine if the script is generating an incorrect command or if duplicity itself is causing your error.
To see exactly what is happening when you run duplicity-backup, either pass the option `-d` or `--debug` on the command line, or head to the bottom of the configuration file and uncomment the `ECHO=$(which echo)` variable.
This will stop the script from running and will, instead, output the generated command into your log file. You can then check to see if what is being generated is causing an error or if it is duplicity causing you woe.
You can also try the `-n` or `--dry-run` option. This will make duplicity to calculate what would be done, but does not perform any backend actions. Together with info verbosity level (-v8) duplicity will list all files that will be affected. This way you will know exactly which files will be backed up or restored.
## Wish List
* Backup to multiple destinations with one config file
* Show backup-ed files in today incremental backup email
###### Thanks to all the [contributors](https://github.com/zertrin/duplicity-backup/graphs/contributors) for their help.
|
fnfc/duplicity-backup
|
README.md
|
Markdown
|
gpl-3.0
| 12,758
|
<p>Symbiose est un projet libre et open-source de WebOS.<br />
<a href="http://symbiose.fr.cr/">http://symbiose.fr.cr/</a><br /><br />
<a href="http://www.w3.org/html/logo/"><img src="http://www.w3.org/html/logo/badge/html5-badge-h-css3-multimedia-performance-semantics-storage.png" height="32" alt="HTML5 Powered with CSS3 / Styling, Multimedia, Performance & Integration, Semantics, and Offline & Storage" title="HTML5 Powered with CSS3 / Styling, Multimedia, Performance & Integration, Semantics, and Offline & Storage" /></a></p>
|
MatiasNAmendola/gnome-web
|
usr/share/docs/webos/about.html
|
HTML
|
gpl-3.0
| 549
|
<ul class="nav nav-tabs">
{% for resource_category in all_resource_categories %}
{% if category and resource_category == category %}
<li class="active">
{% else %}
<li>
{% endif %}
<a href="{{ resource_category.get_absolute_url }}{% if date %}?year={{ date.year }}&month={{ date.month }}&day={{ date.day }}{% endif %}">
{{ resource_category.name }}
</a>
</li>
{% endfor %}
</ul>
|
BdEINSALyon/resa
|
bookings/templates/bookings/resource/resource_category_nav.html
|
HTML
|
gpl-3.0
| 466
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.