repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
kz26/uchicago-hvz | uchicagohvz/game/dorm_migrations/0003_populate_dorms.py | 774 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
DORMS = (
("BS", "Blackstone"),
("BR", "Breckinridge"),
("BV", "Broadview"),
("BJ", "Burton-Judson Courts"),
("IH", "International House"),
("MC", "Maclean"),
("MAX", "Max Palevsky"),
("NG", "New Graduate Residence Hall"),
("SH", "Snell-Hitchcock"),
("SC", "South Campus"),
("ST", "Stony Island"),
("OFF", "Off campus"),
("NC", "North Campus")
)
def populate_dorms(apps, schema_editor):
Dorm = apps.get_model('game', 'Dorm')
for dorm in DORMS:
Dorm.objects.create(name=dorm[1])
class Migration(migrations.Migration):
dependencies = [
('game', '0002_dorm'),
]
operations = [
migrations.RunPython(populate_dorms)
]
| mit |
AbdulBasitBashir/learn-angular2 | step4_making_components/app.js | 1473 | /// <reference path="typings/angular2/angular2.d.ts" />
if (typeof __decorate !== "function") __decorate = function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
if (typeof __metadata !== "function") __metadata = function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var angular2_1 = require('angular2/angular2');
var ChildComponent_1 = require('ChildComponent');
var ParentComponent = (function () {
function ParentComponent() {
this.message = "I'm the parent";
}
ParentComponent = __decorate([
angular2_1.Component({
selector: 'parent'
}),
angular2_1.View({
template: "\n <h1>{{ message }}</h1>\n <child></child>\n ",
directives: [ChildComponent_1.ChildComponent]
}),
__metadata('design:paramtypes', [])
], ParentComponent);
return ParentComponent;
})();
angular2_1.bootstrap(ParentComponent);
| mit |
jianjunz/online-judge-solutions | leetcode/1558-course-schedule-iv.py | 1256 | import queue
class Solution:
@lru_cache(maxsize=None)
def prerequisiteList(self, i):
if i not in self.pre:
return []
answer=[]
preQueue=queue.Queue()
for x in self.pre[i]:
preQueue.put(x)
answer.append(x)
while not preQueue.empty():
current=preQueue.get()
newPre=self.prerequisiteList(current)
for y in newPre:
if y not in answer:
answer.append(y)
preQueue.put(y)
return answer
def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
self.pre={}
for p in prerequisites:
if p[1] not in self.pre:
self.pre[p[1]]=[p[0]]
else:
self.pre[p[1]].append(p[0])
print(self.pre)
completePre=[None]*n
for i in range(n):
completePre[i]=self.prerequisiteList(i)
print(completePre)
answer=[]
for q in queries:
preOfQ=completePre[q[1]]
answer.append(q[0] in preOfQ)
return answer
| mit |
lunaczp/learning | language/c/testPhpSrc/php-5.6.17/ext/xsl/tests/xsltprocessor_transformToXML_nullparam.phpt | 1280 | --TEST--
Check XSLTProcessor::transformToXml() with null parameter
--CREDITS--
Rodrigo Prado de Jesus <royopa [at] gmail [dot] com>
--SKIPIF--
<?php extension_loaded('xsl') or die('skip xsl extension is not available'); ?>
--FILE--
<?php
$xml = <<<EOB
<allusers>
<user>
<uid>bob</uid>
</user>
<user>
<uid>joe</uid>
</user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="allusers">
<html><body>
<h2>Users</h2>
<table>
<xsl:for-each select="user">
<tr><td>
<xsl:value-of
select="php:function('ucfirst',string(uid))"/>
</td></tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = new DOMDocument('1.0', 'utf-8');
$xmldoc->loadXML($xml);
$xsldoc = new DOMDocument('1.0', 'utf-8');
$xsldoc->loadXML($xsl);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML(null);
?>
--EXPECTF--
Warning: XSLTProcessor::transformToXml() expects parameter 1 to be object, null given in %s on line %i
| mit |
qgrid/ng2 | packages/qgrid-core/src/command-bag/edit.cell.enter.command.js | 2802 | import { Command } from '../command/command';
import { editCellShortcutFactory } from '../edit/edit.cell.shortcut.factory';
import { editCellContextFactory } from '../edit/edit.cell.context.factory';
import { Keyboard } from '../keyboard/keyboard';
export const EDIT_CELL_ENTER_COMMAND_KEY = commandKey('edit.cell.enter.command');
export class EditCellEnterCommand extends Command {
constructor(plugin) {
const { model, view } = plugin;
const getShortcut = editCellShortcutFactory(plugin);
super({
key: EDIT_CELL_ENTER_COMMAND_KEY,
priority: 1,
stopPropagate: true,
shortcut: getShortcut('enter'),
canExecute: cell => {
cell = cell || model.navigation().cell;
const canEdit =
cell
&& cell.column.canEdit
&& (cell.column.category === 'control' || model.edit().mode === 'cell')
&& model.edit().status === 'view';
if (canEdit) {
const clientContext = editCellContextFactory(
cell,
cell.value,
cell.label,
editLet.tag
);
return model.edit().enter.canExecute(clientContext) === true;
}
return false;
},
execute: cell => {
const editLet = view.edit.cell;
cell = cell || model.navigation().cell;
if (cell) {
const clientContext = editCellContextFactory(
cell,
cell.value,
cell.label,
editLet.tag
);
if (model.edit().enter.execute(clientContext) !== false) {
const td = table.body.cell(cell.rowIndex, cell.columnIndex).model();
editLet.editor = new CellEditor(td);
const keyCode = this.shortcut.keyCode();
if (source === 'keyboard' && Keyboard.isPrintable(keyCode)) {
const parse = parseFactory(cell.column.type, cell.column.editor);
const value = Keyboard.stringify(keyCode);
const typedValue = parse(value);
if (typedValue !== null) {
editLet.value = typedValue;
}
}
editLet.mode(editLet.editor.td, 'edit');
return true;
}
}
return false;
}
});
}
}
| mit |
leonardofaria/sisate | application/views/perfis/form.php | 941 | <?php echo validation_errors(); ?>
<?php echo form_open('', array('class' => 'form-horizontal', 'data-toggle' => 'validator')); ?>
<div class="panel panel-default">
<div class="panel-heading">Preencha os dados abaixo: </div>
<div class="panel-body">
<div class="form-group">
<?php echo form_label('Nome', 'nome', array('class' => 'col-sm-2 control-label')); ?>
<div class="col-sm-4">
<?php echo form_input(array('id' => 'nome', 'name' => 'nome', 'value' => set_value('nome'), 'class' => 'form-control', 'data-error' => 'Campo obrigatório', 'required' => 'required')); ?>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<?php echo form_submit(array('name' => 'save', 'value' => 'Salvar', 'class' => 'btn btn-lg btn-primary')); ?>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div> | mit |
nanoframework/nf-interpreter | targets/win32/nanoCLR/Memory.cpp | 1470 | //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "stdafx.h"
// using namespace Microsoft::SPOT::Emulator;
// From minheap.cpp
static unsigned char *s_Memory_Start = NULL;
static unsigned int s_Memory_Length = 1024 * 1024 * 10;
void HeapLocation(unsigned char *&BaseAddress, unsigned int &SizeInBytes)
{
if (!s_Memory_Start)
{
s_Memory_Start =
(unsigned char *)::VirtualAlloc(NULL, s_Memory_Length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (s_Memory_Start)
{
memset(s_Memory_Start, 0xEA, s_Memory_Length);
}
HalSystemConfig.RAM1.Base = (unsigned int)(size_t)s_Memory_Start;
HalSystemConfig.RAM1.Size = (unsigned int)(size_t)s_Memory_Length;
}
BaseAddress = s_Memory_Start;
SizeInBytes = s_Memory_Length;
}
static unsigned char *s_CustomHeap_Start = NULL;
void CustomHeapLocation(unsigned char *&BaseAddress, unsigned int &SizeInBytes)
{
if (!s_CustomHeap_Start)
{
s_CustomHeap_Start =
(unsigned char *)::VirtualAlloc(NULL, s_Memory_Length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (s_CustomHeap_Start)
{
memset(s_CustomHeap_Start, 0xEA, s_Memory_Length);
}
}
BaseAddress = s_CustomHeap_Start;
SizeInBytes = s_Memory_Length;
}
| mit |
M4573R/competitive-programming-archive | uva/volume-009/password_search.cpp | 1000 | #include <iostream>
#include <map>
#include <string>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int password_size;
while (cin >> password_size)
{
string message;
cin >> message;
map<string, unsigned int> frequencies;
for (string::size_type i {0}; i < message.size() - password_size; ++i)
{
++frequencies[message.substr(i, password_size)];
}
string password {frequencies.begin()->first};
for (const auto& substring_and_frequency : frequencies)
{
string substring {substring_and_frequency.first};
unsigned int frequency {substring_and_frequency.second};
if (frequencies[password] < frequency)
{
password = substring;
}
}
cout << password << '\n';
}
return 0;
}
| mit |
nikolalosic/este-app--assignment | src/native/auth/SignOut.react.js | 759 | import Component from 'react-pure-render/component';
import React, { PropTypes } from 'react';
import buttonsMessages from '../../common/app/buttonsMessages';
import { Button, Text } from '../app/components';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { signOut } from '../../common/auth/actions';
class SignOut extends Component {
static propTypes = {
signOut: PropTypes.func.isRequired
};
render() {
const { signOut } = this.props;
return (
<FormattedMessage {...buttonsMessages.signOut}>
{message =>
<Button onPress={signOut}><Text>{message}</Text></Button>
}
</FormattedMessage>
);
}
}
export default connect(null, { signOut })(SignOut);
| mit |
kangmin2z/dev_ci4 | system/Helpers/form_helper.php | 22277 | <?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2017 British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2014-2017 British Columbia Institute of Technology (https://bcit.ca/)
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 3.0.0
* @filesource
*/
use Config\Services;
//--------------------------------------------------------------------
if ( ! function_exists('form_open'))
{
/**
* Form Declaration
*
* Creates the opening portion of the form.
*
* @param string $action the URI segments of the form destination
* @param array $attributes a key/value pair of attributes
* @param array $hidden a key/value pair hidden data
*
* @return string
*/
function form_open(string $action = '', array $attributes = [], array $hidden = []): string
{
// If no action is provided then set to the current url
if ( ! $action)
{
helper('url');
$action = current_url(true);
} // If an action is not a full URL then turn it into one
elseif (strpos($action, '://') === false)
{
helper('url');
$action = site_url($action);
}
$attributes = stringify_attributes($attributes);
if (stripos($attributes, 'method=') === false)
{
$attributes .= ' method="post"';
}
if (stripos($attributes, 'accept-charset=') === false)
{
$config = new \Config\App();
$attributes .= ' accept-charset="' . strtolower($config->charset) . '"';
}
$form = '<form action="' . $action . '"' . $attributes . ">\n";
// Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
$before = (new \Config\Filters())->globals['before'];
if ((in_array('csrf', $before) || array_key_exists('csrf', $before)) && strpos($action, base_url()) !== false && ! stripos($form, 'method="get"')
)
{
$hidden[csrf_token()] = csrf_hash();
}
if (is_array($hidden))
{
foreach ($hidden as $name => $value)
{
$form .= '<input type="hidden" name="' . $name . '" value="' . $value . '" style="display: none;" />' . "\n";
}
}
return $form;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_open_multipart'))
{
/**
* Form Declaration - Multipart type
*
* Creates the opening portion of the form, but with "multipart/form-data".
*
* @param string $action The URI segments of the form destination
* @param array $attributes A key/value pair of attributes
* @param array $hidden A key/value pair hidden data
*
* @return string
*/
function form_open_multipart(string $action = '', array $attributes = [], array $hidden = []): string
{
if (is_string($attributes))
{
$attributes .= ' enctype="multipart/form-data"';
}
else
{
$attributes['enctype'] = 'multipart/form-data';
}
return form_open($action, $attributes, $hidden);
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_hidden'))
{
/**
* Hidden Input Field
*
* Generates hidden fields. You can pass a simple key/value string or
* an associative array with multiple values.
*
* @param mixed $name Field name
* @param string|array $value Field value
* @param bool $recursing
*
* @return string
*/
function form_hidden($name, $value, bool $recursing = false): string
{
static $form;
if ($recursing === false)
{
$form = "\n";
}
if (is_array($name))
{
foreach ($name as $key => $val)
{
form_hidden($key, $val, true);
}
return $form;
}
if ( ! is_array($value))
{
$form .= '<input type="hidden" name="' . $name . '" value="' . $value . "\" />\n";
}
else
{
foreach ($value as $k => $v)
{
$k = is_int($k) ? '' : $k;
form_hidden($name . '[' . $k . ']', $v, true);
}
}
return $form;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_input'))
{
/**
* Text Input Field. If 'type' is passed in the $type field, it will be
* used as the input type, for making 'email', 'phone', etc input fields.
*
* @param mixed $data
* @param string $value
* @param mixed $extra
* @param string $type
*
* @return string
*/
function form_input($data = '', string $value = '', $extra = '', string $type = 'text'): string
{
$defaults = [
'type' => $type,
'name' => is_array($data) ? '' : $data,
'value' => $value,
];
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . " />\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_password'))
{
/**
* Password Field
*
* Identical to the input function but adds the "password" type
*
* @param mixed $data
* @param string $value
* @param mixed $extra
*
* @return string
*/
function form_password($data = '', string $value = '', $extra = ''): string
{
is_array($data) OR $data = ['name' => $data];
$data['type'] = 'password';
return form_input($data, $value, $extra);
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_upload'))
{
/**
* Upload Field
*
* Identical to the input function but adds the "file" type
*
* @param mixed
* @param string
* @param mixed
*
* @return string
*/
function form_upload($data = '', string $value = '', $extra = ''): string
{
$defaults = ['type' => 'file', 'name' => ''];
is_array($data) OR $data = ['name' => $data];
$data['type'] = 'file';
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . " />\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_textarea'))
{
/**
* Textarea field
*
* @param mixed $data
* @param string $value
* @param mixed $extra
*
* @return string
*/
function form_textarea($data = '', string $value = '', $extra = ''): string
{
$defaults = [
'name' => is_array($data) ? '' : $data,
'cols' => '40',
'rows' => '10',
];
if ( ! is_array($data) OR ! isset($data['value']))
{
$val = $value;
}
else
{
$val = $data['value'];
unset($data['value']); // textareas don't use the value attribute
}
return '<textarea ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . '>'
. htmlspecialchars($val)
. "</textarea>\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_multiselect'))
{
/**
* Multi-select menu
*
* @param string
* @param array
* @param mixed
* @param mixed
*
* @return string
*/
function form_multiselect(string $name = '', array $options = [], array $selected = [], $extra = ''): string
{
$extra = stringify_attributes($extra);
if (stripos($extra, 'multiple') === false)
{
$extra .= ' multiple="multiple"';
}
return form_dropdown($name, $options, $selected, $extra);
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_dropdown'))
{
/**
* Drop-down Menu
*
* @param mixed $data
* @param mixed $options
* @param mixed $selected
* @param mixed $extra
*
* @return string
*/
function form_dropdown($data = '', $options = [], $selected = [], $extra = ''): string
{
$defaults = [];
if (is_array($data))
{
if (isset($data['selected']))
{
$selected = $data['selected'];
unset($data['selected']); // select tags don't have a selected attribute
}
if (isset($data['options']))
{
$options = $data['options'];
unset($data['options']); // select tags don't use an options attribute
}
}
else
{
$defaults = ['name' => $data];
}
is_array($selected) OR $selected = [$selected];
is_array($options) OR $options = [$options];
// If no selected state was submitted we will attempt to set it automatically
if (empty($selected))
{
if (is_array($data))
{
if (isset($data['name'], $_POST[$data['name']]))
{
$selected = [$_POST[$data['name']]];
}
}
elseif (isset($_POST[$data]))
{
$selected = [$_POST[$data]];
}
}
$extra = stringify_attributes($extra);
$multiple = (count($selected) > 1 && stripos($extra, 'multiple') === false) ? ' multiple="multiple"' : '';
$form = '<select ' . rtrim(parse_form_attributes($data, $defaults)) . $extra . $multiple . ">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val))
{
if (empty($val))
{
continue;
}
$form .= '<optgroup label="' . $key . "\">\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = in_array($optgroup_key, $selected) ? ' selected="selected"' : '';
$form .= '<option value="' . htmlspecialchars($optgroup_key) . '"' . $sel . '>'
. (string) $optgroup_val . "</option>\n";
}
$form .= "</optgroup>\n";
}
else
{
$form .= '<option value="' . htmlspecialchars($key) . '"'
. (in_array($key, $selected) ? ' selected="selected"' : '') . '>'
. (string) $val . "</option>\n";
}
}
return $form . "</select>\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_checkbox'))
{
/**
* Checkbox Field
*
* @param mixed $data
* @param string $value
* @param bool $checked
* @param mixed $extra
*
* @return string
*/
function form_checkbox($data = '', string $value = '', bool $checked = false, $extra = ''): string
{
$defaults = ['type' => 'checkbox', 'name' => ( ! is_array($data) ? $data : ''), 'value' => $value];
if (is_array($data) && array_key_exists('checked', $data))
{
$checked = $data['checked'];
if ($checked == false)
{
unset($data['checked']);
}
else
{
$data['checked'] = 'checked';
}
}
if ($checked == true)
{
$defaults['checked'] = 'checked';
}
else
{
unset($defaults['checked']);
}
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . " />\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_radio'))
{
/**
* Radio Button
*
* @param mixed $data
* @param string $value
* @param bool $checked
* @param mixed $extra
*
* @return string
*/
function form_radio($data = '', string $value = '', bool $checked = false, $extra = ''): string
{
is_array($data) OR $data = ['name' => $data];
$data['type'] = 'radio';
return form_checkbox($data, $value, $checked, $extra);
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_submit'))
{
/**
* Submit Button
*
* @param mixed $data
* @param string $value
* @param mixed $extra
*
* @return string
*/
function form_submit($data = '', string $value = '', $extra = ''): string
{
$defaults = [
'type' => 'submit',
'name' => is_array($data) ? '' : $data,
'value' => $value,
];
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . " />\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_reset'))
{
/**
* Reset Button
*
* @param mixed $data
* @param string $value
* @param mixed $extra
*
* @return string
*/
function form_reset($data = '', string $value = '', $extra = ''): string
{
$defaults = [
'type' => 'reset',
'name' => is_array($data) ? '' : $data,
'value' => $value,
];
return '<input ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . " />\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_button'))
{
/**
* Form Button
*
* @param mixed $data
* @param string $content
* @param mixed $extra
*
* @return string
*/
function form_button($data = '', string $content = '', $extra = ''): string
{
$defaults = [
'name' => is_array($data) ? '' : $data,
'type' => 'button',
];
if (is_array($data) && isset($data['content']))
{
$content = $data['content'];
unset($data['content']); // content is not an attribute
}
return '<button ' . parse_form_attributes($data, $defaults) . stringify_attributes($extra) . '>'
. $content
. "</button>\n";
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_label'))
{
/**
* Form Label Tag
*
* @param string $label_text The text to appear onscreen
* @param string $id The id the label applies to
* @param array $attributes Additional attributes
*
* @return string
*/
function form_label(string $label_text = '', string $id = '', array $attributes = []): string
{
$label = '<label';
if ($id !== '')
{
$label .= ' for="' . $id . '"';
}
if (is_array($attributes) && count($attributes) > 0)
{
foreach ($attributes as $key => $val)
{
$label .= ' ' . $key . '="' . $val . '"';
}
}
return $label . '>' . $label_text . '</label>';
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_datalist'))
{
/**
* Datalist
*
* The <datalist> element specifies a list of pre-defined options for an <input> element.
* Users will see a drop-down list of pre-defined options as they input data.
* The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.
*
* @param string $name
* @param string $value
* @param array $options
*
* @return string
*/
function form_datalist($name, $value, $options)
{
$data = [
'type' => 'text',
'name' => $name,
'list' => $name . '_list',
'value' => $value,
];
$out = form_input($data) . "\n";
$out .= "<datalist id='" . $name . '_list' . "'>";
foreach ($options as $option)
{
$out .= "<option value='$option'>" . "\n";
}
$out .= "</datalist>" . "\n";
return $out;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_fieldset'))
{
/**
* Fieldset Tag
*
* Used to produce <fieldset><legend>text</legend>. To close fieldset
* use form_fieldset_close()
*
* @param string $legend_text The legend text
* @param array $attributes Additional attributes
*
* @return string
*/
function form_fieldset(string $legend_text = '', array $attributes = []): string
{
$fieldset = '<fieldset' . stringify_attributes($attributes) . ">\n";
if ($legend_text !== '')
{
return $fieldset . '<legend>' . $legend_text . "</legend>\n";
}
return $fieldset;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_fieldset_close'))
{
/**
* Fieldset Close Tag
*
* @param string $extra
*
* @return string
*/
function form_fieldset_close(string $extra = ''): string
{
return '</fieldset>' . $extra;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('form_close'))
{
/**
* Form Close Tag
*
* @param string $extra
*
* @return string
*/
function form_close(string $extra = ''): string
{
return '</form>' . $extra;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('set_value'))
{
/**
* Form Value
*
* Grabs a value from the POST array for the specified field so you can
* re-populate an input field or textarea
*
* @param string $field Field name
* @param string $default Default value
* @param bool $html_escape Whether to escape HTML special characters or not
*
* @return string
*/
function set_value(string $field, string $default = '', bool $html_escape = true): string
{
$request = Services::request();
// Try any old input data we may have first
$value = $request->getOldInput($field);
if ($value === null)
{
$value = $request->getPost($field) ?? $default;
}
return ($html_escape) ? esc($value, 'html') : $value;
}
}
//--------------------------------------------------------------------
if ( ! function_exists('set_select'))
{
/**
* Set Select
*
* Let's you set the selected value of a <select> menu via data in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @param string $field
* @param string $value
* @param bool $default
*
* @return string
*/
function set_select(string $field, string $value = '', bool $default = false): string
{
$request = Services::request();
// Try any old input data we may have first
$input = $request->getOldInput($field);
if ($input === null)
{
$input = $request->getPost($field);
}
if ($input === null)
{
return ($default === true) ? ' selected="selected"' : '';
}
if (is_array($input))
{
$value = (string) $value;
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as &$v)
{
if ($value === $v)
{
return ' selected="selected"';
}
}
return '';
}
return ($input === $value) ? ' selected="selected"' : '';
}
}
//--------------------------------------------------------------------
if ( ! function_exists('set_checkbox'))
{
/**
* Set Checkbox
*
* Let's you set the selected value of a checkbox via the value in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @param string $field
* @param string $value
* @param bool $default
*
* @return string
*/
function set_checkbox(string $field, string $value = '', bool $default = false): string
{
// Form inputs are always strings ...
$value = (string) $value;
$request = Services::request();
// Try any old input data we may have first
$input = $request->getOldInput($field);
if ($input === null)
{
$input = $request->getPost($field);
}
if (is_array($input))
{
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as &$v)
{
if ($value === $v)
{
return ' checked="checked"';
}
}
return '';
}
// Unchecked checkbox and radio inputs are not even submitted by browsers ...
if ($_POST)
{
return ($input === $value) ? ' checked="checked"' : '';
}
return ($default === true) ? ' checked="checked"' : '';
}
}
//--------------------------------------------------------------------
if ( ! function_exists('set_radio'))
{
/**
* Set Radio
*
* Let's you set the selected value of a radio field via info in the POST array.
* If Form Validation is active it retrieves the info from the validation class
*
* @param string $field
* @param string $value
* @param bool $default
*
* @return string
*/
function set_radio(string $field, string $value = '', bool $default = false): string
{
// Form inputs are always strings ...
$value = (string) $value;
$request = Services::request();
// Try any old input data we may have first
$input = $request->getOldInput($field);
if ($input === null)
{
$input = $request->getPost($field) ?? $default;
}
if (is_array($input))
{
// Note: in_array('', array(0)) returns TRUE, do not use it
foreach ($input as &$v)
{
if ($value === $v)
{
return ' checked="checked"';
}
}
return '';
}
// Unchecked checkbox and radio inputs are not even submitted by browsers ...
if ($_POST)
{
return ($input === $value) ? ' checked="checked"' : '';
}
return ($default === true) ? ' checked="checked"' : '';
}
}
//--------------------------------------------------------------------
if ( ! function_exists('parse_form_attributes'))
{
/**
* Parse the form attributes
*
* Helper function used by some of the form helpers
*
* @param array $attributes List of attributes
* @param array $default Default values
*
* @return string
*/
function parse_form_attributes($attributes, $default): string
{
if (is_array($attributes))
{
foreach ($default as $key => $val)
{
if (isset($attributes[$key]))
{
$default[$key] = $attributes[$key];
unset($attributes[$key]);
}
}
if (! empty($attributes))
{
$default = array_merge($default, $attributes);
}
}
$att = '';
foreach ($default as $key => $val)
{
if ($key === 'value')
{
$val = esc($val, 'html');
}
elseif ($key === 'name' && ! strlen($default['name']))
{
continue;
}
$att .= $key . '="' . $val . '" ';
}
return $att;
}
//--------------------------------------------------------------------
}
| mit |
bosha/torhandlers | examples/ajax_weblog/forms.py | 336 | # -*- coding: utf-8 -*-
__author__ = 'Alex Bo'
__email__ = 'bosha@the-bosha.ru'
from wtforms import Form, validators, StringField, IntegerField, TextAreaField
class addCoreForm(Form):
title = StringField('Title', [validators.required(), validators.Length(max=500)])
content = TextAreaField('Content', [validators.required()])
| mit |
Lemoncode/react-typescript-samples | old_class_components_samples/10 LoaderSpinner/src/components/repos/repoHeader.tsx | 230 | import * as React from 'react';
export const RepoHeader: React.StatelessComponent<{}> = () => {
return (
<tr>
<th>id</th>
<th>Name</th>
<th>Description</th>
</tr>
);
};
| mit |
Cobase/cobase | src/Cobase/DemoBundle/Service/CatService.php | 948 | <?php
namespace Cobase\DemoBundle\Service;
use Cobase\DemoBundle\Form\Model\CatModel;
use Cobase\DemoBundle\Form\Type\CatType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormFactory;
class CatService
{
/**
* @var FormFactory
*/
protected $formFactory;
/**
* @param FormFactory $formFactory
*/
public function __construct(FormFactory $formFactory)
{
$this->formFactory = $formFactory;
}
/**
* @param CatModel $catModel
* @return Form
*/
public function getCatForm(CatModel $catModel)
{
return $this->formFactory->create(
new CatType(get_class($catModel)), $catModel
);
}
/**
* @param Form $form
*
* @return string
*/
public function patCatByForm(Form $form)
{
$catModel = $form->getData();
return str_repeat($catModel->getName() . " ", $catModel->getAge() );
}
} | mit |
bartwronski/CSharpRenderer | PostEffects/LuminanceCalculation.cs | 6828 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
namespace CSharpRenderer
{
class LuminanceCalculations
{
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance4x4;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance16x16;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance32x32;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance64x64;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance128x128;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorLuminance256x256;
RenderTargetSet.RenderTargetDescriptor m_RTDescriptorFinalLuminance;
RenderTargetSet m_FinalLuminance;
public LuminanceCalculations(SlimDX.Direct3D11.Device device, int resolutionX, int resolutionY)
{
Format luminanceFormat = Format.R16_Float;
m_RTDescriptorLuminance4x4 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 4,
m_Width = resolutionX / 4
};
m_RTDescriptorLuminance16x16 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 16,
m_Width = resolutionX / 16
};
m_RTDescriptorLuminance32x32 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 32,
m_Width = resolutionX / 32
};
m_RTDescriptorLuminance64x64 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 64,
m_Width = resolutionX / 64
};
m_RTDescriptorLuminance128x128 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 128,
m_Width = resolutionX / 128
};
m_RTDescriptorLuminance256x256 = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = luminanceFormat,
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = resolutionY / 256,
m_Width = resolutionX / 256
};
m_RTDescriptorFinalLuminance = new RenderTargetSet.RenderTargetDescriptor()
{
m_Format = Format.R32_Float, // to be able to read and write at the same time...
m_HasDepth = false,
m_NumSurfaces = 1,
m_Height = 1,
m_Width = 1
};
m_FinalLuminance = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorFinalLuminance);
}
public RenderTargetSet ExecutePass(DeviceContext context, RenderTargetSet source)
{
RenderTargetSet[] luminanceTargets = new RenderTargetSet[6];
luminanceTargets[0] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance4x4);
luminanceTargets[1] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance16x16);
luminanceTargets[2] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance32x32);
luminanceTargets[3] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance64x64);
luminanceTargets[4] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance128x128);
luminanceTargets[5] = RenderTargetManager.RequestRenderTargetFromPool(m_RTDescriptorLuminance256x256);
using (new GpuProfilePoint(context, "Calculate luminance"))
{
source.BindSRV(context, 0);
luminanceTargets[0].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample4x4CalculateLuminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[0].BindSRV(context, 0);
luminanceTargets[1].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample4x4Luminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[1].BindSRV(context, 0);
luminanceTargets[2].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample2x2Luminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[2].BindSRV(context, 0);
luminanceTargets[3].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample2x2Luminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[3].BindSRV(context, 0);
luminanceTargets[4].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample2x2Luminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[4].BindSRV(context, 0);
luminanceTargets[5].BindAsRenderTarget(context);
PostEffectHelper.RenderFullscreenTriangle(context, "Downsample2x2Luminance");
RenderTargetSet.BindNull(context);
ContextHelper.ClearSRVs(context);
luminanceTargets[5].BindSRV(context, 0);
context.ComputeShader.SetUnorderedAccessView(m_FinalLuminance.m_RenderTargets[0].m_UnorderedAccessView, 0);
ShaderManager.ExecuteComputeForSize(context, 1, 1, 1, "FinalCalculateAverageLuminance");
ContextHelper.ClearSRVs(context);
ContextHelper.ClearCSContext(context);
}
foreach (var lt in luminanceTargets)
{
RenderTargetManager.ReleaseRenderTargetToPool(lt);
}
return m_FinalLuminance;
}
}
}
| mit |
lionfire/Core | src/LionFire.Vos.Abstractions/Exceptions/VosException.cs | 402 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LionFire.ObjectBus;
namespace LionFire.Vos
{
[Serializable]
public class VosException : Exception
{
public VosException() { }
public VosException(string message) : base(message) { }
public VosException(string message, Exception inner) : base(message, inner) { }
}
}
| mit |
hdm-project/robot-ide | elements/game-runner.js | 1369 | const html = require('choo/html')
const sf = require('sheetify')
const gameView = require('./game')
const { speedSliderView, playButtonView } = require('./runtime-controls')
const gameStatsView = require('./game-stats')
const gameRunnerPrefix = sf`
:host {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
:host > .controls {
display: flex;
flex-direction: row;
align-items: center;
height: 50px;
border-bottom: 1px solid grey;
}
:host > .game {
position: relative;
height: calc(100% - 50px);
}
`
function gameRunnerView ({
game, clock,
onStart, onStop, onChangeSpeed
}) {
const gameHtml = gameView({
state: game,
progress: clock.progress
})
const playButtonHtml = playButtonView({
isRunning: clock.isRunning,
onStart,
onStop
})
const speedSliderHtml = speedSliderView({
min: 100,
max: 1000,
intervalDuration: clock.intervalDuration,
onChange: onChangeSpeed
})
const gameStatsHtml = gameStatsView({
game,
progress: clock.progress
})
return html`
<div class="${gameRunnerPrefix}">
<div class="controls">
${playButtonHtml}
${speedSliderHtml}
</div>
<div class="game">
${gameHtml}
${gameStatsHtml}
</div>
</div>
`
}
module.exports = gameRunnerView
| mit |
mariaiemoli/progetto | bifurcation/src/TriangleData.cc | 2936 |
#include <iostream>
#include "../include/TriangleData.h"
/**************************************************************************/
/* TriangleData.cc */
/* Classe che contiene i dati principali per costrire il triangolo */
/**************************************************************************/
// Definition of the static variable edge
const size_type TriangleData::M_edge[3][2] = {{0, 1}, {1, 2}, {2, 0}};
//COSTRUTTORI
TriangleData::TriangleData()
{
M_point.clear();
M_point.resize(3);
}// costruttore vuoto
TriangleData::TriangleData(PointData & a, PointData & b, PointData & c)
{
M_point.clear();
M_point.push_back(a);
M_point.push_back(b);
M_point.push_back(c);
}//costruttore dati i punti
TriangleData::TriangleData(const TriangleData & t)
{
M_point[0]=t.M_point[ 0 ];
M_point[1]=t.M_point[ 1 ];
M_point[2]=t.M_point[ 2 ];
}//Da triangolo
void TriangleData::setPoint(size_type i, PointData const & p)
{
M_point[i] = p;
return;
}//setPoint
scalar_type TriangleData::measure() const
{
const TriangleData & t = *this;
return -0.5 * ( t[1][0] * (t[2][1] - t[0][1]) +
t[2][0] * (t[0][1] - t[1][1]) +
t[0][0] * (t[1][1] - t[2][1]) );
}//measure
size_type TriangleData::size () const
{
return M_point.size();
}
PointData & TriangleData::edgePoint(size_type edgenum, size_type endnum)
{
return M_point[M_edge[edgenum][endnum]];
}//edgePoint
const PointData & TriangleData::edgePoint(size_type edgenum, size_type endnum) const
{
return M_point[M_edge[edgenum][endnum]];
}//edgePoint
PointData TriangleData::baricenter()const
{
PointData tmp(M_point[0]);
tmp += M_point[1];
tmp += M_point[2];
return tmp * (1./3.0);
}//baricenter
size_type TriangleData::edge(size_type i, size_type j)
{
return M_edge[i][j];
}//edge
PointData TriangleData::edgeMean(size_type edgeNum)const
{
PointData tmp(M_point[edge(edgeNum,0)]+M_point[edge(edgeNum,1)]);
return tmp *0.5;
}//edgeMedium
Vector2d TriangleData::c(size_type edgeNum) const
{
PointData baric = this->baricenter();
PointData eMean= this->edgeMean(edgeNum);
return eMean.asVector()-baric.asVector();
}//c
Vector2d TriangleData::unscaledNormal(size_type edgeNum) const
{
PointData const & a=this->edgePoint(edgeNum,0);
PointData const & b=this->edgePoint(edgeNum,1);
return Vector2d(a.y()-b.y(),b.x()-a.x());
}//unscaledNormal
TriangleData & TriangleData::operator =(const TriangleData & t)
{
if (this !=&t)
{
M_point[0] = t.M_point[0];
M_point[1] = t.M_point[1];
M_point[2] = t.M_point[2];
}
return *this;
}// operator =
std::ostream & operator <<(std::ostream & stream, TriangleData const & t)
{
stream<<" ************* TRIANGLE POINTS ********"<<std::endl;
for (size_type i=0;i<3;++i)
{
stream<< t.M_point[i]<<std::endl;
}
stream<<"****************************************"<<std::endl;
return stream;
}// operator <<
| mit |
designrad/Jotunheimen-tracking | JotunheimenPlaces/src/constants/taxEuro.js | 341 | /**
* Tax Euro
*/
export default [
{"name": "Up to 10 500"},
{"name": "10 500 - 21 200"},
{"name": "21 200 - 31 700"},
{"name": "31 700 - 42 300"},
{"name": "42 300 - 53 000"},
{"name": "53 000 - 63 500"},
{"name": "63 500 - 74 000"},
{"name": "74 000 - 84 700"},
{"name": "84 700 - 95 200"},
{"name": "Over 95 200"}
]; | mit |
MelissaChan/Crawler2015 | src/SimpleBFSCrawler/LinkFilter.java | 102 | package SimpleBFSCrawler;
public interface LinkFilter {
public boolean accept(String url);
}
| mit |
Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/jshint/node_modules/lodash/internal/baseMatchesProperty.js | 1434 | var baseGet = require('./baseGet'),
baseIsEqual = require('./baseIsEqual'),
baseSlice = require('./baseSlice'),
isArray = require('../lang/isArray'),
isKey = require('./isKey'),
isStrictComparable = require('./isStrictComparable'),
last = require('../array/last'),
toObject = require('./toObject'),
toPath = require('./toPath');
/**
* The base implementation of `_.matchesProperty` which does not which does
* not clone `value`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} value The value to compare.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, value) {
var isArr = isArray(path),
isCommon = isKey(path) && isStrictComparable(value),
pathKey = (path + '');
path = toPath(path);
return function(object) {
if (object == null) {
return false;
}
var key = pathKey;
object = toObject(object);
if ((isArr || !isCommon) && !(key in object)) {
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
if (object == null) {
return false;
}
key = last(path);
object = toObject(object);
}
return object[key] === value
? (value !== undefined || (key in object))
: baseIsEqual(value, object[key], null, true);
};
}
module.exports = baseMatchesProperty;
| mit |
AndrewTBurks/EnglewoodSocialServices | data/processCensusDataToBlocks.js | 1457 | // based on and replaces processCensusDataToGrid.js
let fs = require('fs');
let _ = require('lodash');
// load data of Englewood community area and census blocks
let blockBoundaries,censusData;
blockBoundaries = JSON.parse(fs.readFileSync('EnglewoodCensusBlockBoundaries.geojson').toString());
censusData = JSON.parse(fs.readFileSync('EnglewoodCensusDataFull.json').toString());
let propertyNames = {};
let dataExample = censusData[Object.keys(censusData)[0]];
_.forEach(Object.keys(dataExample.data), (key) => {
propertyNames[key] = Object.keys(dataExample.data[key]);
});
// fs.writeFile("mapTypeNames.json", JSON.stringify(propertyNames));
function getFeatureDataForBlock(blockID){
let censusObject = censusData[blockID];
if(!censusObject){
throw `No data at block ${blockID}`;
}
let featureData = {}, statistics = censusObject.data;
for (let propertyType of Object.keys(propertyNames)) {
featureData[propertyType] = {};
for (let propertySubtype of propertyNames[propertyType]) {
featureData[propertyType][propertySubtype] = parseInt(statistics[propertyType][propertySubtype]);
}
}
return featureData;
}
// attach census data for every black
for(let block of blockBoundaries.features){
block.properties.census = getFeatureDataForBlock(block.properties.geoid10);
}
// output population data in grid
fs.writeFileSync("allDataBlocks.geojson", JSON.stringify(blockBoundaries)); | mit |
vladcalin/pymicroservice | docs/conf.py | 9939 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# gemstone documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 25 14:52:22 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
import gemstone
sys.path.insert(0, os.path.abspath('.'))
autoclass_content = 'both'
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.viewcode'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'gemstone'
copyright = '2016, Vlad Calin'
author = 'Vlad Calin'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = gemstone.__version__
# The full version, including alpha/beta/rc tags.
release = gemstone.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'gemstone v0.1'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'pymicroservicedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'gemstone.tex', 'gemstone Documentation',
'Vlad Calin', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'gemstone', 'gemstone Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'gemstone', 'gemstone Documentation',
author, 'gemstone', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
viewcode_import = True | mit |
gbritt/optobot | bot/slack_clients.py | 2473 |
import logging
import re
import time
import json
import argparse
import os
from slacker import Slacker
from slackclient import SlackClient
logger = logging.getLogger(__name__)
class SlackClients(object):
def __init__(self, token):
self.token = token
# Slacker is a Slack Web API Client
self.web = Slacker(token)
# SlackClient is a Slack Websocket RTM API Client
self.rtm = SlackClient(token)
def bot_user_id(self):
return self.rtm.server.login_data['self']['id']
def is_message_from_me(self, user):
return user == self.rtm.server.login_data['self']['id']
def is_bot_mention(self, message):
bot_user_name = self.rtm.server.login_data['self']['id']
if re.search("@{}".format(bot_user_name), message):
return True
else:
return False
def send_user_typing_pause(self, channel_id, sleep_time=3.0):
user_typing_json = {"type": "typing", "channel": channel_id}
self.rtm.server.send_to_websocket(user_typing_json)
time.sleep(sleep_time)
def upload_file(self,file,channel_id):
#self.rtm.api_call('')
self.rtm.api_call('files.upload', channel = channel_id)
#this is not working
def get_chat_history(self,channel_id, pageSize = 100):
'''
channels = slack.channels.list().body['channels']
messages = []
lastTimestamp = None
response = channel.history(
channel = channel_id
latest = lastTimestamp
oldest = 0
count = pageSize
).body
messages.extend(response['messages'])
return messages
'''
#history = self.rtm.api_call('channels.history', channel = channel_id)
channelHistory = self.rtm.api_call('channels.history', channel = channel_id)
return channelHistory
'''
with open(channelHistory, 'r') as handle:
parsed = json.load(handle)
'''
'''
with open(fileName, 'w') as outFile:
print("writing {0} records to {1}".format(len(messages), fileName))
json.dump({'channel_info': channelInfo, 'messages': messages }, outFile, indent=4)
channels = slack.channels.list().body['channels']
return (channel['name'])
#print self.rtm.api_call("chat.post_Message", as_user = "true:", #channel = channel_id, text = test)
#self.trm.server.send_to_websocket
'''
| mit |
OpenWebslides/OpenWebslides | client/flow-typed/npm/eslint-config-prettier_vx.x.x.js | 1783 | // flow-typed signature: 4ea4ff80a06e219117081ccbc8589fb0
// flow-typed version: <<STUB>>/eslint-config-prettier_v^2.0.0/flow_v0.49.1
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-config-prettier'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'eslint-config-prettier' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'eslint-config-prettier/bin/cli' {
declare module.exports: any;
}
declare module 'eslint-config-prettier/bin/validators' {
declare module.exports: any;
}
declare module 'eslint-config-prettier/flowtype' {
declare module.exports: any;
}
declare module 'eslint-config-prettier/react' {
declare module.exports: any;
}
// Filename aliases
declare module 'eslint-config-prettier/bin/cli.js' {
declare module.exports: $Exports<'eslint-config-prettier/bin/cli'>;
}
declare module 'eslint-config-prettier/bin/validators.js' {
declare module.exports: $Exports<'eslint-config-prettier/bin/validators'>;
}
declare module 'eslint-config-prettier/flowtype.js' {
declare module.exports: $Exports<'eslint-config-prettier/flowtype'>;
}
declare module 'eslint-config-prettier/index' {
declare module.exports: $Exports<'eslint-config-prettier'>;
}
declare module 'eslint-config-prettier/index.js' {
declare module.exports: $Exports<'eslint-config-prettier'>;
}
declare module 'eslint-config-prettier/react.js' {
declare module.exports: $Exports<'eslint-config-prettier/react'>;
}
| mit |
makmu/outlook-matters | OutlookMatters.Core/Mattermost/v3/Interface/Team.cs | 912 | using Newtonsoft.Json;
namespace OutlookMatters.Core.Mattermost.v3.Interface
{
public class Team
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
protected bool Equals(Team other)
{
return string.Equals(Id, other.Id) && string.Equals(Name, other.Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Team) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Id != null ? Id.GetHashCode() : 0)*397) ^ (Name != null ? Name.GetHashCode() : 0);
}
}
}
} | mit |
rpetersburg/FiberProperties | scripts/quantification_plots.py | 628 | from fiber_properties import FiberImage
# image = 'C:/Libraries/Box Sync/ExoLab/Fiber_Characterization/Image Analysis/data/' \
# + 'modal_noise/coupled_fibers/200-200um_test2/agitated_both/nf_obj.pkl'
image = 'C:/Libraries/Box Sync/ExoLab/Fiber_Characterization/Image Analysis/data/modal_noise/Kris_data/rectangular_100x300um/coupled_agitation/nf_obj.pkl'
im_obj = FiberImage(image)
# im_obj.get_modal_noise(method='fft', new=True, show_image=True)
im_obj.set_modal_noise(method='filter', new=True, show_image=False, kernel_size=31)
# print im_obj.get_modal_noise(method='filter')
im_obj.save_object(image) | mit |
anhstudios/swganh | data/scripts/templates/object/tangible/lair/base/shared_poi_all_lair_thicket_small_fog_mustard.py | 466 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/lair/base/shared_poi_all_lair_thicket_small_fog_mustard.iff"
result.attribute_template_id = -1
result.stfName("lair_n","thicket")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | mit |
zyklus/fuse4js | fuse4js.cc | 25571 | /*
*
* fuse4js.cc
*
* Copyright (c) 2012 - 2014 by VMware, Inc. All Rights Reserved.
* http://www.vmware.com
* Refer to LICENSE.txt for details of distribution and use.
*
*/
/*
* Include nan for version compatibility
*/
#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <cstring>
using v8::FunctionTemplate;
using v8::Handle;
using v8::Object;
using v8::String;
#define FUSE_USE_VERSION 26
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <sys/time.h>
#ifdef HAVE_SETXATTR
#include <sys/xattr.h>
#endif
#include <fuse.h>
#include <semaphore.h>
#include <string>
#include <iostream>
#include <sstream>
#include <stdlib.h>
using namespace v8;
// ---------------------------------------------------------------------------
static struct {
bool enableFuseDebug;
char **extraArgv;
size_t extraArgc;
uv_async_t async;
sem_t *psem;
pthread_t fuse_thread;
std::string root;
Persistent<Object> handlers;
Persistent<Object> nodeBuffer;
Persistent<Function> GetAttrFunc;
Persistent<Function> ReadDirFunc;
Persistent<Function> ReadLinkFunc;
Persistent<Function> StatfsFunc;
Persistent<Function> OpenCreateFunc;
Persistent<Function> ReadFunc;
Persistent<Function> WriteFunc;
Persistent<Function> GenericFunc;
} f4js;
enum fuseop_t {
OP_GETATTR = 0,
OP_TRUNCATE,
OP_READDIR,
OP_READLINK,
OP_CHMOD,
OP_SETXATTR,
OP_STATFS,
OP_OPEN,
OP_READ,
OP_WRITE,
OP_RELEASE,
OP_CREATE,
OP_UNLINK,
OP_RENAME,
OP_MKDIR,
OP_RMDIR,
OP_INIT,
OP_DESTROY
};
const char* fuseop_names[] = {
"getattr",
"truncate",
"readdir",
"readlink",
"chmod",
"setxattr",
"statfs",
"open",
"read",
"write",
"release",
"create",
"unlink",
"rename",
"mkdir",
"rmdir",
"init",
"destroy"
};
static struct {
enum fuseop_t op;
const char *in_path;
struct fuse_file_info *info;
union {
struct {
struct stat *stbuf;
} getattr;
struct {
size_t size;
} truncate;
struct {
void *buf;
fuse_fill_dir_t filler;
} readdir;
struct {
struct statvfs *buf;
} statfs;
struct {
char *dstBuf;
size_t len;
} readlink;
struct {
mode_t mode;
} chmod;
#ifdef __APPLE__
struct {
const char *name;
const char *value;
size_t size;
int position;
uint32_t options;
} setxattr;
#else
struct {
const char *name;
const char *value;
size_t size;
int flags;
} setxattr;
#endif
struct {
off_t offset;
size_t len;
char *dstBuf;
const char *srcBuf;
} rw;
struct {
const char *dst;
} rename;
struct {
mode_t mode;
} create_mkdir;
} u;
int retval;
} f4js_cmd;
// ---------------------------------------------------------------------------
std::string f4js_semaphore_name()
{
std::ostringstream o;
o << "fuse4js" << getpid();
return o.str();
}
// ---------------------------------------------------------------------------
static int f4js_rpc(enum fuseop_t op, const char *path)
{
f4js_cmd.op = op;
f4js_cmd.in_path = path;
uv_async_send(&f4js.async);
sem_wait(f4js.psem);
return f4js_cmd.retval;
}
// ---------------------------------------------------------------------------
static int f4js_getattr(const char *path, struct stat *stbuf)
{
f4js_cmd.u.getattr.stbuf = stbuf;
return f4js_rpc(OP_GETATTR, path);
}
// ---------------------------------------------------------------------------
static int f4js_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
f4js_cmd.u.readdir.buf = buf;
f4js_cmd.u.readdir.filler = filler;
return f4js_rpc(OP_READDIR, path);
}
// ---------------------------------------------------------------------------
static int f4js_readlink(const char *path, char *buf, size_t len)
{
f4js_cmd.u.readlink.dstBuf = buf;
f4js_cmd.u.readlink.len = len;
return f4js_rpc(OP_READLINK, path);
}
// ---------------------------------------------------------------------------
static int f4js_chmod(const char *path, mode_t mode)
{
f4js_cmd.u.chmod.mode = mode;
return f4js_rpc(OP_CHMOD, path);
}
// ---------------------------------------------------------------------------
#ifdef __APPLE__
static int f4js_setxattr(const char *path, const char* name, const char* value, size_t size, int position, uint32_t options)
{
f4js_cmd.u.setxattr.name = name;
f4js_cmd.u.setxattr.value = value;
f4js_cmd.u.setxattr.size = size;
f4js_cmd.u.setxattr.position = position;
f4js_cmd.u.setxattr.options = options;
return f4js_rpc(OP_SETXATTR, path);
}
#else
static int f4js_setxattr(const char *path, const char* name, const char* value, size_t size, int flags)
{
f4js_cmd.u.setxattr.name = name;
f4js_cmd.u.setxattr.value = value;
f4js_cmd.u.setxattr.size = size;
f4js_cmd.u.setxattr.flags = flags;
return f4js_rpc(OP_SETXATTR, path);
}
#endif
// ---------------------------------------------------------------------------
static int f4js_statfs(const char *path, struct statvfs *buf)
{
f4js_cmd.u.statfs.buf = buf;
return f4js_rpc(OP_STATFS, path);
}
// ---------------------------------------------------------------------------
int f4js_open(const char *path, struct fuse_file_info *info)
{
f4js_cmd.info = info;
return f4js_rpc(OP_OPEN, path);
}
// ---------------------------------------------------------------------------
int f4js_read (const char *path,
char *buf,
size_t len,
off_t offset,
struct fuse_file_info *info)
{
f4js_cmd.info = info;
f4js_cmd.u.rw.offset = offset;
f4js_cmd.u.rw.len = len;
f4js_cmd.u.rw.dstBuf = buf;
return f4js_rpc(OP_READ, path);
}
// ---------------------------------------------------------------------------
int f4js_write (const char *path,
const char *buf,
size_t len,
off_t offset,
struct fuse_file_info * info)
{
f4js_cmd.info = info;
f4js_cmd.u.rw.offset = offset;
f4js_cmd.u.rw.len = len;
f4js_cmd.u.rw.srcBuf = buf;
return f4js_rpc(OP_WRITE, path);
}
// ---------------------------------------------------------------------------
int f4js_release (const char *path, struct fuse_file_info *info)
{
f4js_cmd.info = info;
return f4js_rpc(OP_RELEASE, path);
}
// ---------------------------------------------------------------------------
int f4js_create (const char *path,
mode_t mode,
struct fuse_file_info *info)
{
f4js_cmd.info = info;
f4js_cmd.u.create_mkdir.mode = mode;
return f4js_rpc(OP_CREATE, path);
}
// ---------------------------------------------------------------------------
int f4js_utimens (const char *,
const struct timespec tv[2])
{
return 0; // stub out for now to make "touch" command succeed
}
// ---------------------------------------------------------------------------
int f4js_unlink (const char *path)
{
return f4js_rpc(OP_UNLINK, path);
}
// ---------------------------------------------------------------------------
int f4js_rename (const char *src, const char *dst)
{
f4js_cmd.u.rename.dst = dst;
return f4js_rpc(OP_RENAME, src);
}
// ---------------------------------------------------------------------------
int f4js_mkdir (const char *path, mode_t mode)
{
f4js_cmd.u.create_mkdir.mode = mode;
return f4js_rpc(OP_MKDIR, path);
}
// ---------------------------------------------------------------------------
int f4js_rmdir (const char *path)
{
return f4js_rpc(OP_RMDIR, path);
}
// ---------------------------------------------------------------------------
int f4js_truncate (const char *path, off_t size) {
f4js_cmd.u.truncate.size = size;
return f4js_rpc(OP_TRUNCATE, path);
}
// ---------------------------------------------------------------------------
void* f4js_init(struct fuse_conn_info *conn)
{
// We currently always return NULL
f4js_rpc(OP_INIT, "");
return NULL;
}
// ---------------------------------------------------------------------------
void f4js_destroy (void *data)
{
// We currently ignore the data pointer, which init() always sets to NULL
f4js_rpc(OP_DESTROY, "");
}
// ---------------------------------------------------------------------------
void *fuse_thread(void *)
{
struct fuse_operations ops = { 0 };
ops.truncate = f4js_truncate;
ops.getattr = f4js_getattr;
ops.readdir = f4js_readdir;
ops.readlink = f4js_readlink;
ops.chmod = f4js_chmod;
ops.setxattr = f4js_setxattr;
ops.statfs = f4js_statfs;
ops.open = f4js_open;
ops.read = f4js_read;
ops.write = f4js_write;
ops.release = f4js_release;
ops.create = f4js_create;
ops.utimens = f4js_utimens;
ops.unlink = f4js_unlink;
ops.rename = f4js_rename;
ops.mkdir = f4js_mkdir;
ops.rmdir = f4js_rmdir;
ops.init = f4js_init;
ops.destroy = f4js_destroy;
const char* debugOption = f4js.enableFuseDebug? "-d":"-f";
char *argv[] = { (char*)"dummy", (char*)"-s", (char*)debugOption, (char*)f4js.root.c_str() };
int initialArgc = sizeof(argv) / sizeof(char*);
char **argvIncludingExtraArgs = (char**)malloc(sizeof(char*) * (initialArgc + f4js.extraArgc));
memcpy(argvIncludingExtraArgs, argv, sizeof(argv));
memcpy(argvIncludingExtraArgs + initialArgc, f4js.extraArgv, sizeof(char*) * f4js.extraArgc);
if (fuse_main((initialArgc + f4js.extraArgc), argvIncludingExtraArgs, &ops, NULL)) {
// Error occured
f4js_destroy(NULL);
}
return NULL;
}
// ---------------------------------------------------------------------------
void ConvertDate(Handle<Object> &stat,
std::string name,
struct timespec *out)
{
Local<Value> prop = stat->Get(NanNew<String>(name.c_str()));
if (!prop->IsUndefined() && prop->IsDate()) {
Local<Date> date = Local<Date>::Cast(prop);
double dateVal = date->NumberValue(); // total milliseconds
time_t seconds = (time_t)(dateVal / 1000.0);
time_t milliseconds = dateVal - (1000.0 * seconds); // remainder
time_t nanoseconds = milliseconds * 1000000.0;
out->tv_sec = seconds;
out->tv_nsec = nanoseconds;
}
}
// ---------------------------------------------------------------------------
NAN_METHOD(ProcessReturnValue)
{
if (args.Length() >= 1 && args[0]->IsNumber()) {
Local<Number> retval = Local<Number>::Cast(args[0]);
f4js_cmd.retval = (int)retval->Value();
}
}
// ---------------------------------------------------------------------------
NAN_METHOD(GetAttrCompletion)
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval == 0 && args.Length() >= 2 && args[1]->IsObject()) {
memset(f4js_cmd.u.getattr.stbuf, 0, sizeof(*f4js_cmd.u.getattr.stbuf));
Handle<Object> stat = Handle<Object>::Cast(args[1]);
Local<Value> prop = stat->Get(NanNew<String>("size"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.getattr.stbuf->st_size = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("mode"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.getattr.stbuf->st_mode = (mode_t)num->Value();
}
prop = stat->Get(NanNew<String>("nlink"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.getattr.stbuf->st_nlink = (mode_t)num->Value();
}
prop = stat->Get(NanNew<String>("uid"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.getattr.stbuf->st_uid = (uid_t)num->Value();
}
prop = stat->Get(NanNew<String>("gid"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.getattr.stbuf->st_gid = (gid_t)num->Value();
}
struct stat *stbuf = f4js_cmd.u.getattr.stbuf;
#ifdef __APPLE__
ConvertDate(stat, "mtime", &stbuf->st_mtimespec);
ConvertDate(stat, "ctime", &stbuf->st_ctimespec);
ConvertDate(stat, "atime", &stbuf->st_atimespec);
#else
ConvertDate(stat, "mtime", &stbuf->st_mtim);
ConvertDate(stat, "ctime", &stbuf->st_ctim);
ConvertDate(stat, "atime", &stbuf->st_atim);
#endif
}
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(ReadDirCompletion)
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval == 0 && args.Length() >= 2 && args[1]->IsArray()) {
Handle<Array> ar = Handle<Array>::Cast(args[1]);
for (uint32_t i = 0; i < ar->Length(); i++) {
Local<Value> el = ar->Get(i);
if (!el->IsUndefined() && el->IsString()) {
Local<String> name = Local<String>::Cast(el);
String::Utf8Value av(name);
struct stat st;
memset(&st, 0, sizeof(st)); // structure not used. Zero everything.
if (f4js_cmd.u.readdir.filler(f4js_cmd.u.readdir.buf, *av, &st, 0))
break;
}
}
}
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD( StatfsCompletion )
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval == 0 && args.Length() >= 2 && args[1]->IsObject()) {
memset(f4js_cmd.u.statfs.buf, 0, sizeof(*f4js_cmd.u.statfs.buf));
Handle<Object> stat = Handle<Object>::Cast(args[1]);
Local<Value> prop = stat->Get(NanNew<String>("bsize"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_bsize = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("frsize"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_frsize = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("blocks"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_blocks = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("bfree"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_bfree = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("bavail"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_bavail = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("files"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_files = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("ffree"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_ffree = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("favail"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_favail = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("fsid"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_fsid = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("flag"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_flag = (off_t)num->Value();
}
prop = stat->Get(NanNew<String>("namemax"));
if (!prop->IsUndefined() && prop->IsNumber()) {
Local<Number> num = Local<Number>::Cast(prop);
f4js_cmd.u.statfs.buf->f_namemax = (off_t)num->Value();
}
}
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD( ReadLinkCompletion)
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval == 0 && args.Length() >= 2 && args[1]->IsString()) {
String::Utf8Value av(args[1]);
size_t len = std::min((size_t)av.length() + 1, f4js_cmd.u.readlink.len);
strncpy(f4js_cmd.u.readlink.dstBuf, *av, len);
// terminate string even when it is truncated
f4js_cmd.u.readlink.dstBuf[f4js_cmd.u.readlink.len - 1] = '\0';
}
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(GenericCompletion)
{
NanScope();
bool exiting = (f4js_cmd.op == OP_DESTROY);
ProcessReturnValue(args);
sem_post(f4js.psem);
if (exiting) {
pthread_join(f4js.fuse_thread, NULL);
uv_unref((uv_handle_t*) &f4js.async);
sem_close(f4js.psem);
sem_unlink(f4js_semaphore_name().c_str());
}
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(OpenCreateCompletion)
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval == 0 && args.Length() >= 2 && args[1]->IsNumber()) {
Local<Number> fileHandle = Local<Number>::Cast(args[1]);
f4js_cmd.info->fh = (uint64_t)fileHandle->Value(); // save the file handle
} else {
f4js_cmd.info->fh = 0;
}
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(ReadCompletion)
{
NanScope();
ProcessReturnValue(args);
if (f4js_cmd.retval >= 0) {
char *buffer_data = node::Buffer::Data(NanNew(f4js.nodeBuffer));
if ((size_t)f4js_cmd.retval > f4js_cmd.u.rw.len) {
f4js_cmd.retval = f4js_cmd.u.rw.len;
}
memcpy(f4js_cmd.u.rw.dstBuf, buffer_data, f4js_cmd.retval);
}
NanDisposePersistent(f4js.nodeBuffer);
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(WriteCompletion)
{
NanScope();
ProcessReturnValue(args);
NanDisposePersistent(f4js.nodeBuffer);
sem_post(f4js.psem);
NanReturnUndefined();
}
// ---------------------------------------------------------------------------
// Called from the main thread.
static void DispatchOp(uv_async_t* handle, int status)
{
NanScope();
std::string symName(fuseop_names[f4js_cmd.op]);
f4js_cmd.retval = -EPERM;
int argc = 0;
Handle<Value> argv[6];
Local<String> path = NanNew<String>(f4js_cmd.in_path);
argv[argc++] = path;
switch (f4js_cmd.op) {
case OP_INIT:
case OP_DESTROY:
f4js_cmd.retval = 0; // Will be used as the return value of OP_INIT.
--argc; // Ugly. Remove the first argument (path) because not needed.
argv[argc++] = NanNew(f4js.GenericFunc);
break;
case OP_TRUNCATE:
argv[argc++] = NanNew((double)f4js_cmd.u.truncate.size);
break;
case OP_GETATTR:
argv[argc++] = NanNew(f4js.GetAttrFunc);
break;
case OP_READDIR:
argv[argc++] = NanNew(f4js.ReadDirFunc);
break;
case OP_READLINK:
argv[argc++] = NanNew(f4js.ReadLinkFunc);
break;
case OP_CHMOD:
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.chmod.mode);
break;
case OP_SETXATTR:
argv[argc++] = NanNew<String>(f4js_cmd.u.setxattr.name);
argv[argc++] = NanNew<String>(f4js_cmd.u.setxattr.value);
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.setxattr.size);
#ifdef __APPLE__
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.setxattr.position);
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.setxattr.options);
#else
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.setxattr.flags);
#endif
break;
case OP_STATFS:
--argc; // Ugly. Remove the first argument (path) because not needed.
argv[argc++] = NanNew(f4js.StatfsFunc);
break;
case OP_RENAME:
argv[argc++] = NanNew<String>(f4js_cmd.u.rename.dst);
argv[argc++] = NanNew(f4js.GenericFunc);
break;
case OP_OPEN:
argv[argc++] = NanNew<Number>((double)f4js_cmd.info->flags);
argv[argc++] = NanNew(f4js.OpenCreateFunc);
break;
case OP_CREATE:
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.create_mkdir.mode);
argv[argc++] = NanNew(f4js.OpenCreateFunc);
break;
case OP_MKDIR:
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.create_mkdir.mode);
argv[argc++] = NanNew(f4js.GenericFunc);
break;
case OP_READ:
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.rw.offset);
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.rw.len);
NanAssignPersistent(f4js.nodeBuffer, NanNewBufferHandle(f4js_cmd.u.rw.len));
argv[argc++] = NanNew(f4js.nodeBuffer);
argv[argc++] = NanNew<Number>((double)f4js_cmd.info->fh); // optional file handle returned by open()
argv[argc++] = NanNew(f4js.ReadFunc);
break;
case OP_WRITE:
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.rw.offset);
argv[argc++] = NanNew<Number>((double)f4js_cmd.u.rw.len);
NanAssignPersistent(f4js.nodeBuffer, NanNewBufferHandle((char*)f4js_cmd.u.rw.srcBuf, f4js_cmd.u.rw.len));
argv[argc++] = NanNew(f4js.nodeBuffer);
argv[argc++] = NanNew<Number>((double)f4js_cmd.info->fh); // optional file handle returned by open()
argv[argc++] = NanNew(f4js.WriteFunc);
break;
case OP_RELEASE:
argv[argc++] = NanNew<Number>((double)f4js_cmd.info->fh); // optional file handle returned by open()
argv[argc++] = NanNew(f4js.GenericFunc);
break;
default:
argv[argc++] = NanNew(f4js.GenericFunc);
break;
}
Local<Function> handler = Local<Function>::Cast(
NanNew(f4js.handlers)->Get(NanNew<String>(symName.c_str()))
);
if (handler->IsUndefined()) {
sem_post(f4js.psem);
return;
}
handler->Call(NanGetCurrentContext()->Global(), argc, argv);
// NanReturnUndefined();
}
// ---------------------------------------------------------------------------
NAN_METHOD(Start)
{
NanScope();
if (args.Length() < 2) {
NanThrowTypeError("Wrong number of arguments");
NanReturnUndefined();
}
if (!args[0]->IsString() || !args[1]->IsObject()) {
NanThrowTypeError("Wrong argument types");
NanReturnUndefined();
}
String::Utf8Value av(args[0]);
char *root = *av;
if (root == NULL) {
NanThrowTypeError("Path is incorrect");
NanReturnUndefined();
}
f4js.enableFuseDebug = false;
if (args.Length() >= 3) {
Local <Boolean> debug = args[2]->ToBoolean();
f4js.enableFuseDebug = debug->BooleanValue();
}
f4js.extraArgc = 0;
if (args.Length() >= 4) {
if (!args[3]->IsArray()) {
NanThrowTypeError("Wrong argument types");
NanReturnUndefined();
}
Handle<Array> mountArgs = Handle<Array>::Cast(args[3]);
f4js.extraArgv = (char**)malloc(mountArgs->Length() * sizeof(char*));
int argLen = 0;
int argSize = 0;
for (uint32_t i = 0; i < mountArgs->Length(); i++) {
Local<Value> arg = mountArgs->Get(i);
if (!arg->IsUndefined() && arg->IsString()) {
Local<String> stringArg = Local<String>::Cast(arg);
char *handle = *NanAsciiString(stringArg);
argLen = std::strlen(handle)+1;
argSize = argLen * sizeof(char);
f4js.extraArgv[f4js.extraArgc] = (char*)malloc(argSize);
memcpy(f4js.extraArgv[f4js.extraArgc], (void *) handle, argSize);
f4js.extraArgc++;
}
}
}
f4js.root = root;
NanAssignPersistent( f4js.handlers, Local<Object>::Cast(args[1]) );
f4js.psem = sem_open(f4js_semaphore_name().c_str(), O_CREAT, S_IRUSR | S_IWUSR, 0);
if (f4js.psem == SEM_FAILED)
{
std::cerr << "Error: semaphore creation failed - " << strerror(errno) << "\n";
exit(-1);
}
// NanSetPrototypeTemplate()
// f4js.GetAttrFunc = Persistent<Function>::New(FunctionTemplate::New(GetAttrCompletion)->GetFunction());
NanAssignPersistent(f4js.GetAttrFunc, NanNew<FunctionTemplate>(GetAttrCompletion)->GetFunction() );
NanAssignPersistent(f4js.ReadDirFunc, NanNew<FunctionTemplate>(ReadDirCompletion)->GetFunction());
NanAssignPersistent(f4js.ReadLinkFunc, NanNew<FunctionTemplate>(ReadLinkCompletion)->GetFunction());
NanAssignPersistent(f4js.StatfsFunc, NanNew<FunctionTemplate>(StatfsCompletion)->GetFunction());
NanAssignPersistent(f4js.OpenCreateFunc, NanNew<FunctionTemplate>(OpenCreateCompletion)->GetFunction());
NanAssignPersistent(f4js.ReadFunc, NanNew<FunctionTemplate>(ReadCompletion)->GetFunction());
NanAssignPersistent(f4js.WriteFunc, NanNew<FunctionTemplate>(WriteCompletion)->GetFunction());
NanAssignPersistent(f4js.GenericFunc, NanNew<FunctionTemplate>(GenericCompletion)->GetFunction());
uv_async_init(uv_default_loop(), &f4js.async, (uv_async_cb) DispatchOp);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&f4js.fuse_thread, &attr, fuse_thread, NULL);
NanReturnValue(NanNew<String>("dummy"));
}
// ---------------------------------------------------------------------------
void init(Handle<Object> target)
{
target->Set(NanNew<String>("start"), NanNew<FunctionTemplate>(Start)->GetFunction());
}
// ---------------------------------------------------------------------------
NODE_MODULE(fuse4js, init)
| mit |
Gnucki/danf | test/fixture/app/b.js | 299 | 'use strict';
var B = function() {
B.Parent.call(this);
};
B.defineExtendedClass('a');
B.prototype.b = function() {
this._b++;
return B.Parent.prototype.b.call(this);
};
B.prototype.c = function() {
this._c++;
return B.Parent.prototype.c.call(this);
};
module.exports = B; | mit |
alekitto/jymfony | src/Component/DateTime/namespace-stub.js | 349 | /*
* NOT TO BE REQUIRED!
*/
/**
* @namespace
*/
Jymfony.Component.DateTime = {
/**
* @namespace
*/
Exception: {},
/**
* @namespace
*/
Formatter: {},
/**
* @namespace
*/
Internal: {},
/**
* @namespace
*/
Parser: {},
/**
* @namespace
*/
Struct: {},
};
| mit |
SergiosLen/LocalSupport | spec/services/accept_proposed_organisation_spec.rb | 4174 | require 'rails_helper'
describe AcceptProposedOrganisation do
let!(:proposed_org){FactoryGirl.create(:orphan_proposed_organisation, email: email)}
let(:subject){AcceptProposedOrganisation.new(proposed_org).run}
context 'organisation can be accepted' do
shared_examples 'acceptance steps' do
it 'associates the user with the organisation' do
subject
expect(User.find_by(email: email).organisation).to eq Organisation.find(proposed_org.id)
end
it 'promotes the proposed org to org' do
expect(->{subject}).to change(Organisation, :count).by 1
end
it 'has one less proposed organisation' do
expect(->{subject}).to change(ProposedOrganisation, :count).by(-1)
end
it 'sends an email' do
expect(->{subject}).to change{ActionMailer::Base.deliveries.size}.by(1)
end
it 'returns the accepted org on the result' do
expect(subject.accepted_org).to eq Organisation.find_by(name: proposed_org.name)
end
it 'returns nil as not accepted organisation on the result' do
expect(subject.not_accepted_org).to be nil
end
end
context 'proposed organisation email is not registered' do
let(:email){'user@email.com'}
it 'creates a user' do
expect(->{subject}).to change(User, :count).by 1
end
it 'returns an invitation sent result' do
expect(subject.status).to eq(AcceptProposedOrganisation::Response::INVITATION_SENT)
end
it_behaves_like 'acceptance steps'
end
context 'proposed organisation email is a registered user' do
let(:email){'user@email.com'}
let!(:user){FactoryGirl.create(:user, email: email)}
it 'returns a notification sent result' do
expect(subject.status).to eq(AcceptProposedOrganisation::Response::NOTIFICATION_SENT)
end
it_behaves_like 'acceptance steps'
end
end
context 'organisation cannot be accepted' do
shared_examples 'non acceptance steps' do
it 'does not promote the proposed org to org' do
expect(->{subject}).to change(Organisation, :count).by 0
end
it 'has the same number of proposed organisations' do
expect(->{subject}).to change(ProposedOrganisation, :count).by 0
end
it 'does not send an email' do
expect(->{subject}).not_to change{ActionMailer::Base.deliveries.size}
end
it 'does not return accepted org on the result' do
expect(subject.accepted_org).to be nil
end
it 'converts organisation back and returns it on the result' do
expect(subject.not_accepted_org.type).to eq('ProposedOrganisation')
end
end
context 'proposed organisation has no email' do
let!(:proposed_org){FactoryGirl.create(:orphan_proposed_organisation, email: '')}
it 'returns a notification sent result' do
expect(subject.status).to eq(AcceptProposedOrganisation::Response::NO_EMAIL)
end
it_behaves_like 'non acceptance steps'
end
context 'proposed organisation has invalid email' do
let!(:proposed_org){FactoryGirl.create(:orphan_proposed_organisation, email: 'invalidemail.com')}
it 'returns a notification sent result' do
expect(subject.status).to eq(AcceptProposedOrganisation::Response::INVALID_EMAIL)
end
it_behaves_like 'non acceptance steps'
end
context 'proposed organisation contains other error' do
let(:email){'user@email.com'}
before(:each) do
other_response = double(status: InviteUnregisteredUserFromProposedOrg::Response::OTHER_FAILURE, error_msg: 'Unverified')
allow(InviteUnregisteredUserFromProposedOrg).to receive_message_chain(:new, :run).and_return(other_response)
allow(other_response).to receive(:success?).and_return(false)
end
it 'returns a notification sent result' do
expect(subject.status).to eq(AcceptProposedOrganisation::Response::OTHER_ERROR)
end
it_behaves_like 'non acceptance steps'
end
end
end
| mit |
dgetux/capi5k-openstack-ready | xpm_modules/capi5k-puppetcluster/roles_definition.rb | 181 | # define your capistrano roles here.
#
# role :myrole do
# role_myrole
# end
#
role :puppet_master do
role_puppet_master
end
role :puppet_clients do
role_puppet_clients
end
| mit |
bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/ControlPointRelativePosition.php | 838 | <?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class ControlPointRelativePosition extends AbstractTag
{
protected $Id = '300A,02D2';
protected $Name = 'ControlPointRelativePosition';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Control Point Relative Position';
}
| mit |
variar/contest-template | external/tbb/src/test/test_tick_count.cpp | 8669 | /*
Copyright (c) 2005-2017 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "tbb/tick_count.h"
#include "harness_assert.h"
//! Assert that two times in seconds are very close.
void AssertNear( double x, double y ) {
ASSERT( -1.0E-10 <= x-y && x-y <=1.0E-10, NULL );
}
//! Test arithmetic operators on tick_count::interval_t
void TestArithmetic( const tbb::tick_count& t0, const tbb::tick_count& t1, const tbb::tick_count& t2 ) {
tbb::tick_count::interval_t i= t1-t0;
tbb::tick_count::interval_t j = t2-t1;
tbb::tick_count::interval_t k = t2-t0;
AssertSameType( tbb::tick_count::interval_t(), i-j );
AssertSameType( tbb::tick_count::interval_t(), i+j );
ASSERT( i.seconds()>1E-9, NULL );
ASSERT( j.seconds()>1E-9, NULL );
ASSERT( k.seconds()>2E-9, NULL );
AssertNear( (i+j).seconds(), k.seconds() );
AssertNear( (k-j).seconds(), i.seconds() );
AssertNear( ((k-j)+(j-i)).seconds(), k.seconds()-i.seconds() );
tbb::tick_count::interval_t sum;
sum += i;
sum += j;
AssertNear( sum.seconds(), k.seconds() );
sum -= i;
AssertNear( sum.seconds(), j.seconds() );
sum -= j;
AssertNear( sum.seconds(), 0.0 );
}
//------------------------------------------------------------------------
// Test for overhead in calls to tick_count
//------------------------------------------------------------------------
//! Wait for given duration.
/** The duration parameter is in units of seconds. */
static void WaitForDuration( double duration ) {
tbb::tick_count start = tbb::tick_count::now();
while( (tbb::tick_count::now()-start).seconds() < duration )
continue;
}
#include "harness.h"
//! Test that average timer overhead is within acceptable limit.
/** The 'tolerance' value inside the test specifies the limit. */
void TestSimpleDelay( int ntrial, double duration, double tolerance ) {
double total_worktime = 0;
// Iteration -1 warms up the code cache.
for( int trial=-1; trial<ntrial; ++trial ) {
tbb::tick_count t0 = tbb::tick_count::now();
if( duration ) WaitForDuration(duration);
tbb::tick_count t1 = tbb::tick_count::now();
if( trial>=0 ) {
total_worktime += (t1-t0).seconds();
}
}
// Compute average worktime and average delta
double worktime = total_worktime/ntrial;
double delta = worktime-duration;
REMARK("worktime=%g delta=%g tolerance=%g\n", worktime, delta, tolerance);
// Check that delta is acceptable
if( delta<0 )
REPORT("ERROR: delta=%g < 0\n",delta);
if( delta>tolerance )
REPORT("%s: delta=%g > %g=tolerance where duration=%g\n",delta>3*tolerance?"ERROR":"Warning",delta,tolerance,duration);
}
//------------------------------------------------------------------------
// Test for subtracting calls to tick_count from different threads.
//------------------------------------------------------------------------
#include "tbb/atomic.h"
static tbb::atomic<int> Counter1, Counter2;
static tbb::atomic<bool> Flag1, Flag2;
static tbb::tick_count *tick_count_array;
static double barrier_time;
struct TickCountDifferenceBody {
TickCountDifferenceBody( int num_threads ) {
Counter1 = Counter2 = num_threads;
Flag1 = Flag2 = false;
}
void operator()( int id ) const {
bool last = false;
// The first barrier.
if ( --Counter1 == 0 ) last = true;
while ( !last && !Flag1.load<tbb::acquire>() ) __TBB_Pause( 1 );
// Save a time stamp of the first barrier releasing.
tick_count_array[id] = tbb::tick_count::now();
// The second barrier.
if ( --Counter2 == 0 ) Flag2.store<tbb::release>(true);
// The last thread should release threads from the first barrier after it reaches the second
// barrier to avoid a deadlock.
if ( last ) Flag1.store<tbb::release>(true);
// After the last thread releases threads from the first barrier it waits for a signal from
// the second barrier.
while ( !Flag2.load<tbb::acquire>() ) __TBB_Pause( 1 );
if ( last )
// We suppose that the barrier time is a time interval between the moment when the last
// thread reaches the first barrier and the moment when the same thread is released from
// the second barrier. This time is not accurate time of two barriers but it is
// guaranteed that it does not exceed it.
barrier_time = (tbb::tick_count::now() - tick_count_array[id]).seconds() / 2;
}
~TickCountDifferenceBody() {
ASSERT( Counter1 == 0 && Counter2 == 0, NULL );
}
};
//! Test that two tick_count values recorded on different threads can be meaningfully subtracted.
void TestTickCountDifference( int n ) {
const double tolerance = 3E-4;
tick_count_array = new tbb::tick_count[n];
int num_trials = 0;
tbb::tick_count start_time = tbb::tick_count::now();
do {
NativeParallelFor( n, TickCountDifferenceBody( n ) );
if ( barrier_time > tolerance )
// The machine seems to be oversubscibed so skip the test.
continue;
for ( int i = 0; i < n; ++i ) {
for ( int j = 0; j < i; ++j ) {
double diff = (tick_count_array[i] - tick_count_array[j]).seconds();
if ( diff < 0 ) diff = -diff;
if ( diff > tolerance )
REPORT( "Warning: cross-thread tick_count difference = %g > %g = tolerance\n", diff, tolerance );
ASSERT( diff < 3 * tolerance, "Too big difference." );
}
}
// During 5 seconds we are trying to get 10 successful trials.
} while ( ++num_trials < 10 && (tbb::tick_count::now() - start_time).seconds() < 5 );
REMARK( "Difference test time: %g sec\n", (tbb::tick_count::now() - start_time).seconds() );
ASSERT( num_trials == 10, "The machine seems to be heavily oversubscibed, difference test was skipped." );
delete[] tick_count_array;
}
void TestResolution() {
static double target_value = 0.314159265358979323846264338327950288419;
static double step_value = 0.00027182818284590452353602874713526624977572;
static int range_value = 100;
double avg_diff = 0.0;
double max_diff = 0.0;
for( int i = -range_value; i <= range_value; ++i ) {
double my_time = target_value + step_value * i;
tbb::tick_count::interval_t t0(my_time);
double interval_time = t0.seconds();
avg_diff += (my_time - interval_time);
if ( max_diff < my_time-interval_time) max_diff = my_time-interval_time;
// time always truncates
ASSERT(interval_time >= 0 && my_time - interval_time < tbb::tick_count::resolution(), "tick_count resolution out of range");
}
avg_diff = (avg_diff/(2*range_value+1))/tbb::tick_count::resolution();
max_diff /= tbb::tick_count::resolution();
REMARK("avg_diff = %g ticks, max_diff = %g ticks\n", avg_diff, max_diff);
}
#include "tbb/tbb_thread.h"
int TestMain () {
// Increased tolerance for Virtual Machines
double tolerance_multiplier = Harness::GetEnv( "VIRTUAL_MACHINE" ) ? 50. : 1.;
REMARK( "tolerance_multiplier = %g \n", tolerance_multiplier );
tbb::tick_count t0 = tbb::tick_count::now();
TestSimpleDelay(/*ntrial=*/1000000,/*duration=*/0, /*tolerance=*/2E-6 * tolerance_multiplier);
tbb::tick_count t1 = tbb::tick_count::now();
TestSimpleDelay(/*ntrial=*/1000, /*duration=*/0.001,/*tolerance=*/5E-6 * tolerance_multiplier);
tbb::tick_count t2 = tbb::tick_count::now();
TestArithmetic(t0,t1,t2);
TestResolution();
int num_threads = tbb::tbb_thread::hardware_concurrency();
ASSERT( num_threads > 0, "tbb::thread::hardware_concurrency() has returned an incorrect value" );
if ( num_threads > 1 ) {
REMARK( "num_threads = %d\n", num_threads );
TestTickCountDifference( num_threads );
} else {
REPORT( "Warning: concurrency is too low for TestTickCountDifference ( num_threads = %d )\n", num_threads );
}
return Harness::Done;
}
| mit |
toddthomas/signed_xml | lib/signed_xml/base64_transform.rb | 133 | require 'base64'
module SignedXml
class Base64Transform
def apply(input)
Base64.encode64(input).chomp
end
end
end
| mit |
inikoo/fact | libs/yui/yui3-gallery/src/gallery-advanced-number-format/lang/gallery-advanced-number-format_de-LI.js | 37494 | {
"ADP_currencyISO" : "Andorranische Pesete",
"ADP_currencySingular" : "Andorranische Peseten",
"ADP_currencySymbol" : "ADP",
"AED_currencyISO" : "UAE Dirham",
"AED_currencySingular" : "UAE Dirham",
"AED_currencySymbol" : "AED",
"AFA_currencyISO" : "Afghani (1927-2002)",
"AFA_currencySingular" : "Afghani (1927-2002)",
"AFA_currencySymbol" : "AFA",
"AFN_currencyISO" : "Afghani",
"AFN_currencySingular" : "Afghani",
"AFN_currencySymbol" : "Af",
"ALK_currencyISO" : "Afghani",
"ALK_currencySingular" : "Afghani",
"ALK_currencySymbol" : "Af",
"ALL_currencyISO" : "Lek",
"ALL_currencySingular" : "Albanische Lek",
"ALL_currencySymbol" : "ALL",
"AMD_currencyISO" : "Dram",
"AMD_currencySingular" : "Armenische Dram",
"AMD_currencySymbol" : "AMD",
"ANG_currencyISO" : "Niederl. Antillen Gulden",
"ANG_currencySingular" : "Niederländische-Antillen-Gulden",
"ANG_currencySymbol" : "NAf.",
"AOA_currencyISO" : "Kwanza",
"AOA_currencySingular" : "Angolanische Kwanza",
"AOA_currencySymbol" : "Kz",
"AOK_currencyISO" : "Angolanischer Kwanza (1977-1990)",
"AOK_currencySingular" : "Angolanische Kwanza (AOK)",
"AOK_currencySymbol" : "AOK",
"AON_currencyISO" : "Neuer Kwanza",
"AON_currencySingular" : "Angolanische Neue Kwanza (AON)",
"AON_currencySymbol" : "AON",
"AOR_currencyISO" : "Kwanza Reajustado",
"AOR_currencySingular" : "Angolanische Kwanza Reajustado (AOR)",
"AOR_currencySymbol" : "AOR",
"ARA_currencyISO" : "Argentinischer Austral",
"ARA_currencySingular" : "Argentinische Austral",
"ARA_currencySymbol" : "₳",
"ARL_currencyISO" : "ARL",
"ARL_currencySingular" : "Argentinische Austral",
"ARL_currencySymbol" : "$L",
"ARM_currencyISO" : "ARM",
"ARM_currencySingular" : "Argentinische Austral",
"ARM_currencySymbol" : "m$n",
"ARP_currencyISO" : "Argentinischer Peso (1983-1985)",
"ARP_currencySingular" : "Argentinische Peso (ARP)",
"ARP_currencySymbol" : "ARP",
"ARS_currencyISO" : "Argentinischer Peso",
"ARS_currencySingular" : "Argentinische Peso",
"ARS_currencySymbol" : "AR$",
"ATS_currencyISO" : "Österreichischer Schilling",
"ATS_currencySingular" : "Österreichische Schilling",
"ATS_currencySymbol" : "öS",
"AUD_currencyISO" : "Australischer Dollar",
"AUD_currencySingular" : "Australische Dollar",
"AUD_currencySymbol" : "AU$",
"AWG_currencyISO" : "Aruba Florin",
"AWG_currencySingular" : "Aruba Florin",
"AWG_currencySymbol" : "Afl.",
"AZM_currencyISO" : "Aserbaidschan-Manat (1993-2006)",
"AZM_currencySingular" : "Aserbaidschan-Manat (AZM)",
"AZM_currencySymbol" : "AZM",
"AZN_currencyISO" : "Aserbaidschan-Manat",
"AZN_currencySingular" : "Aserbaidschan-Manat",
"AZN_currencySymbol" : "man.",
"BAD_currencyISO" : "Bosnien und Herzegowina Dinar",
"BAD_currencySingular" : "Bosnien und Herzegowina Dinar",
"BAD_currencySymbol" : "BAD",
"BAM_currencyISO" : "Konvertierbare Mark",
"BAM_currencySingular" : "Bosnien und Herzegowina Konvertierbare Mark",
"BAM_currencySymbol" : "KM",
"BAN_currencyISO" : "Konvertierbare Mark",
"BAN_currencySingular" : "Bosnien und Herzegowina Konvertierbare Mark",
"BAN_currencySymbol" : "KM",
"BBD_currencyISO" : "Barbados-Dollar",
"BBD_currencySingular" : "Barbados-Dollar",
"BBD_currencySymbol" : "Bds$",
"BDT_currencyISO" : "Taka",
"BDT_currencySingular" : "Taka",
"BDT_currencySymbol" : "Tk",
"BEC_currencyISO" : "Belgischer Franc (konvertibel)",
"BEC_currencySingular" : "Belgische Franc (konvertibel)",
"BEC_currencySymbol" : "BEC",
"BEF_currencyISO" : "Belgischer Franc",
"BEF_currencySingular" : "Belgische Franc",
"BEF_currencySymbol" : "BF",
"BEL_currencyISO" : "Belgischer Finanz-Franc",
"BEL_currencySingular" : "Belgische Finanz-Franc",
"BEL_currencySymbol" : "BEL",
"BGL_currencyISO" : "Lew (1962-1999)",
"BGL_currencySingular" : "Bulgarische Lew",
"BGL_currencySymbol" : "BGL",
"BGM_currencyISO" : "Lew (1962-1999)",
"BGM_currencySingular" : "Bulgarische Lew",
"BGM_currencySymbol" : "BGL",
"BGN_currencyISO" : "Lew",
"BGN_currencySingular" : "Bulgarische Lew (BGN)",
"BGN_currencySymbol" : "BGN",
"BGO_currencyISO" : "Lew",
"BGO_currencySingular" : "Bulgarische Lew (BGN)",
"BGO_currencySymbol" : "BGN",
"BHD_currencyISO" : "Bahrain-Dinar",
"BHD_currencySingular" : "Bahrain-Dinar",
"BHD_currencySymbol" : "BD",
"BIF_currencyISO" : "Burundi-Franc",
"BIF_currencySingular" : "Burundi-Franc",
"BIF_currencySymbol" : "FBu",
"BMD_currencyISO" : "Bermuda-Dollar",
"BMD_currencySingular" : "Bermuda-Dollar",
"BMD_currencySymbol" : "BD$",
"BND_currencyISO" : "Brunei-Dollar",
"BND_currencySingular" : "Brunei-Dollar",
"BND_currencySymbol" : "BN$",
"BOB_currencyISO" : "Boliviano",
"BOB_currencySingular" : "Boliviano",
"BOB_currencySymbol" : "Bs",
"BOL_currencyISO" : "Boliviano",
"BOL_currencySingular" : "Boliviano",
"BOL_currencySymbol" : "Bs",
"BOP_currencyISO" : "Bolivianischer Peso",
"BOP_currencySingular" : "Bolivianische Peso",
"BOP_currencySymbol" : "$b.",
"BOV_currencyISO" : "Mvdol",
"BOV_currencySingular" : "Bolivianische Mvdol",
"BOV_currencySymbol" : "BOV",
"BRB_currencyISO" : "Brasilianischer Cruzeiro Novo (1967-1986)",
"BRB_currencySingular" : "Brasilianische Cruzeiro Novo (BRB)",
"BRB_currencySymbol" : "BRB",
"BRC_currencyISO" : "Brasilianischer Cruzado",
"BRC_currencySingular" : "Brasilianische Cruzado",
"BRC_currencySymbol" : "BRC",
"BRE_currencyISO" : "Brasilianischer Cruzeiro (1990-1993)",
"BRE_currencySingular" : "Brasilianische Cruzeiro (BRE)",
"BRE_currencySymbol" : "BRE",
"BRL_currencyISO" : "Real",
"BRL_currencySingular" : "Brasilianische Real",
"BRL_currencySymbol" : "R$",
"BRN_currencyISO" : "Brasilianischer Cruzado Novo",
"BRN_currencySingular" : "Brasilianische Cruzado Novo",
"BRN_currencySymbol" : "BRN",
"BRR_currencyISO" : "Brasilianischer Cruzeiro",
"BRR_currencySingular" : "Brasilianische Cruzeiro",
"BRR_currencySymbol" : "BRR",
"BRZ_currencyISO" : "Brasilianischer Cruzeiro",
"BRZ_currencySingular" : "Brasilianische Cruzeiro",
"BRZ_currencySymbol" : "BRR",
"BSD_currencyISO" : "Bahama-Dollar",
"BSD_currencySingular" : "Bahama-Dollar",
"BSD_currencySymbol" : "BS$",
"BTN_currencyISO" : "Ngultrum",
"BTN_currencySingular" : "Bhutanische Ngultrum",
"BTN_currencySymbol" : "Nu.",
"BUK_currencyISO" : "Birmanischer Kyat",
"BUK_currencySingular" : "Birmanische Kyat",
"BUK_currencySymbol" : "BUK",
"BWP_currencyISO" : "Pula",
"BWP_currencySingular" : "Botswanische Pula",
"BWP_currencySymbol" : "BWP",
"BYB_currencyISO" : "Belarus Rubel (alt)",
"BYB_currencySingular" : "Belarus-Rubel (BYB)",
"BYB_currencySymbol" : "BYB",
"BYR_currencyISO" : "Belarus Rubel (neu)",
"BYR_currencySingular" : "Belarus-Rubel",
"BYR_currencySymbol" : "BYR",
"BZD_currencyISO" : "Belize-Dollar",
"BZD_currencySingular" : "Belize-Dollar",
"BZD_currencySymbol" : "BZ$",
"CAD_currencyISO" : "Kanadischer Dollar",
"CAD_currencySingular" : "Kanadische Dollar",
"CAD_currencySymbol" : "CA$",
"CDF_currencyISO" : "Franc congolais",
"CDF_currencySingular" : "Franc congolais",
"CDF_currencySymbol" : "CDF",
"CHE_currencyISO" : "WIR-Euro",
"CHE_currencySingular" : "Franc congolais",
"CHE_currencySymbol" : "CHE",
"CHF_currencyISO" : "Schweizer Franken",
"CHF_currencySingular" : "Schweizer Franken",
"CHF_currencySymbol" : "CHF",
"CHW_currencyISO" : "WIR Franken",
"CHW_currencySingular" : "WIR Franken",
"CHW_currencySymbol" : "CHW",
"CLE_currencyISO" : "CLE",
"CLE_currencySingular" : "WIR Franken",
"CLE_currencySymbol" : "Eº",
"CLF_currencyISO" : "Unidades de Fomento",
"CLF_currencySingular" : "Chilenische Unidades de Fomento",
"CLF_currencySymbol" : "CLF",
"CLP_currencyISO" : "Chilenischer Peso",
"CLP_currencySingular" : "Chilenische Pesos",
"CLP_currencySymbol" : "CL$",
"CNX_currencyISO" : "Chilenischer Peso",
"CNX_currencySingular" : "Chilenische Pesos",
"CNX_currencySymbol" : "CL$",
"CNY_currencyISO" : "Renminbi Yuan",
"CNY_currencySingular" : "Renminbi Yuan",
"CNY_currencySymbol" : "CN¥",
"COP_currencyISO" : "Kolumbianischer Peso",
"COP_currencySingular" : "Kolumbianische Pesos",
"COP_currencySymbol" : "CO$",
"COU_currencyISO" : "Unidad de Valor Real",
"COU_currencySingular" : "Unidad de Valor Real",
"COU_currencySymbol" : "COU",
"CRC_currencyISO" : "Costa Rica Colon",
"CRC_currencySingular" : "Costa Rica Colon",
"CRC_currencySymbol" : "₡",
"CSD_currencyISO" : "Alter Serbischer Dinar",
"CSD_currencySingular" : "Alte Serbische Dinar",
"CSD_currencySymbol" : "CSD",
"CSK_currencyISO" : "Tschechoslowakische Krone",
"CSK_currencySingular" : "Tschechoslowakische Kronen",
"CSK_currencySymbol" : "CSK",
"CUC_currencyISO" : "CUC",
"CUC_currencySingular" : "Tschechoslowakische Kronen",
"CUC_currencySymbol" : "CUC$",
"CUP_currencyISO" : "Kubanischer Peso",
"CUP_currencySingular" : "Kubanische Pesos",
"CUP_currencySymbol" : "CU$",
"CVE_currencyISO" : "Kap Verde Escudo",
"CVE_currencySingular" : "Kap Verde Escudo",
"CVE_currencySymbol" : "CV$",
"CYP_currencyISO" : "Zypern-Pfund",
"CYP_currencySingular" : "Zypern Pfund",
"CYP_currencySymbol" : "CY£",
"CZK_currencyISO" : "Tschechische Krone",
"CZK_currencySingular" : "Tschechische Kronen",
"CZK_currencySymbol" : "Kč",
"DDM_currencyISO" : "Mark der DDR",
"DDM_currencySingular" : "Mark der DDR",
"DDM_currencySymbol" : "DDM",
"DEM_currencyISO" : "Deutsche Mark",
"DEM_currencySingular" : "Deutsche Mark",
"DEM_currencySymbol" : "DM",
"DJF_currencyISO" : "Dschibuti-Franc",
"DJF_currencySingular" : "Dschibuti-Franc",
"DJF_currencySymbol" : "Fdj",
"DKK_currencyISO" : "Dänische Krone",
"DKK_currencySingular" : "Dänische Kronen",
"DKK_currencySymbol" : "Dkr",
"DOP_currencyISO" : "Dominikanischer Peso",
"DOP_currencySingular" : "Dominikanische Pesos",
"DOP_currencySymbol" : "RD$",
"DZD_currencyISO" : "Algerischer Dinar",
"DZD_currencySingular" : "Algerische Dinar",
"DZD_currencySymbol" : "DA",
"ECS_currencyISO" : "Ecuadorianischer Sucre",
"ECS_currencySingular" : "Ecuadorianische Sucre",
"ECS_currencySymbol" : "ECS",
"ECV_currencyISO" : "Verrechnungseinheit für EC",
"ECV_currencySingular" : "Verrechnungseinheiten für EC",
"ECV_currencySymbol" : "ECV",
"EEK_currencyISO" : "Estnische Krone",
"EEK_currencySingular" : "Estnische Kronen",
"EEK_currencySymbol" : "Ekr",
"EGP_currencyISO" : "Ägyptisches Pfund",
"EGP_currencySingular" : "Ägyptische Pfund",
"EGP_currencySymbol" : "EG£",
"ERN_currencyISO" : "Nakfa",
"ERN_currencySingular" : "Eritreische Nakfa",
"ERN_currencySymbol" : "Nfk",
"ESA_currencyISO" : "Spanische Peseta (A-Konten)",
"ESA_currencySingular" : "Spanische Peseten (A-Konten)",
"ESA_currencySymbol" : "ESA",
"ESB_currencyISO" : "Spanische Peseta (konvertibel)",
"ESB_currencySingular" : "Spanische Peseten (konvertibel)",
"ESB_currencySymbol" : "ESB",
"ESP_currencyISO" : "Spanische Peseta",
"ESP_currencySingular" : "Spanische Peseten",
"ESP_currencySymbol" : "Pts",
"ETB_currencyISO" : "Birr",
"ETB_currencySingular" : "Äthiopische Birr",
"ETB_currencySymbol" : "Br",
"EUR_currencyISO" : "Euro",
"EUR_currencySingular" : "Euro",
"EUR_currencySymbol" : "€",
"FIM_currencyISO" : "Finnische Mark",
"FIM_currencySingular" : "Finnische Mark",
"FIM_currencySymbol" : "mk",
"FJD_currencyISO" : "Fidschi-Dollar",
"FJD_currencySingular" : "Fidschi Dollar",
"FJD_currencySymbol" : "FJ$",
"FKP_currencyISO" : "Falkland-Pfund",
"FKP_currencySingular" : "Falkland Pfund",
"FKP_currencySymbol" : "FK£",
"FRF_currencyISO" : "Französischer Franc",
"FRF_currencySingular" : "Französische Franc",
"FRF_currencySymbol" : "₣",
"GBP_currencyISO" : "Pfund Sterling",
"GBP_currencySingular" : "Pfund Sterling",
"GBP_currencySymbol" : "£",
"GEK_currencyISO" : "Georgischer Kupon Larit",
"GEK_currencySingular" : "Georgische Kupon Larit",
"GEK_currencySymbol" : "GEK",
"GEL_currencyISO" : "Georgischer Lari",
"GEL_currencySingular" : "Georgische Lari",
"GEL_currencySymbol" : "GEL",
"GHC_currencyISO" : "Cedi",
"GHC_currencySingular" : "Cedi",
"GHC_currencySymbol" : "₵",
"GHS_currencyISO" : "Ghanaische Cedi",
"GHS_currencySingular" : "Cedi",
"GHS_currencySymbol" : "GH₵",
"GIP_currencyISO" : "Gibraltar-Pfund",
"GIP_currencySingular" : "Gibraltar Pfund",
"GIP_currencySymbol" : "GI£",
"GMD_currencyISO" : "Dalasi",
"GMD_currencySingular" : "Gambische Dalasi",
"GMD_currencySymbol" : "GMD",
"GNF_currencyISO" : "Guinea-Franc",
"GNF_currencySingular" : "Guinea Franc",
"GNF_currencySymbol" : "FG",
"GNS_currencyISO" : "Guineischer Syli",
"GNS_currencySingular" : "Guineische Syli",
"GNS_currencySymbol" : "GNS",
"GQE_currencyISO" : "Ekwele",
"GQE_currencySingular" : "Äquatorialguinea-Ekwele",
"GQE_currencySymbol" : "GQE",
"GRD_currencyISO" : "Griechische Drachme",
"GRD_currencySingular" : "Griechische Drachmen",
"GRD_currencySymbol" : "₯",
"GTQ_currencyISO" : "Quetzal",
"GTQ_currencySingular" : "Quetzal",
"GTQ_currencySymbol" : "GTQ",
"GWE_currencyISO" : "Portugiesisch Guinea Escudo",
"GWE_currencySingular" : "Portugiesisch Guinea Escudo",
"GWE_currencySymbol" : "GWE",
"GWP_currencyISO" : "Guinea Bissau Peso",
"GWP_currencySingular" : "Guinea-Bissau Pesos",
"GWP_currencySymbol" : "GWP",
"GYD_currencyISO" : "Guyana-Dollar",
"GYD_currencySingular" : "Guyana Dollar",
"GYD_currencySymbol" : "GY$",
"HKD_currencyISO" : "Hongkong-Dollar",
"HKD_currencySingular" : "Hongkong-Dollar",
"HKD_currencySymbol" : "HK$",
"HNL_currencyISO" : "Lempira",
"HNL_currencySingular" : "Lempira",
"HNL_currencySymbol" : "HNL",
"HRD_currencyISO" : "Kroatischer Dinar",
"HRD_currencySingular" : "Kroatische Dinar",
"HRD_currencySymbol" : "HRD",
"HRK_currencyISO" : "Kuna",
"HRK_currencySingular" : "Kuna",
"HRK_currencySymbol" : "kn",
"HTG_currencyISO" : "Gourde",
"HTG_currencySingular" : "Gourde",
"HTG_currencySymbol" : "HTG",
"HUF_currencyISO" : "Forint",
"HUF_currencySingular" : "Forint",
"HUF_currencySymbol" : "Ft",
"IDR_currencyISO" : "Rupiah",
"IDR_currencySingular" : "Rupiah",
"IDR_currencySymbol" : "Rp",
"IEP_currencyISO" : "Irisches Pfund",
"IEP_currencySingular" : "Irische Pfund",
"IEP_currencySymbol" : "IR£",
"ILP_currencyISO" : "Israelisches Pfund",
"ILP_currencySingular" : "Israelische Pfund",
"ILP_currencySymbol" : "I£",
"ILR_currencyISO" : "Israelisches Pfund",
"ILR_currencySingular" : "Israelische Pfund",
"ILR_currencySymbol" : "I£",
"ILS_currencyISO" : "Schekel",
"ILS_currencySingular" : "Neue Schekel",
"ILS_currencySymbol" : "₪",
"INR_currencyISO" : "Indische Rupie",
"INR_currencySingular" : "Indische Rupien",
"INR_currencySymbol" : "Rs",
"IQD_currencyISO" : "Irak Dinar",
"IQD_currencySingular" : "Irak Dinar",
"IQD_currencySymbol" : "IQD",
"IRR_currencyISO" : "Rial",
"IRR_currencySingular" : "Rial",
"IRR_currencySymbol" : "IRR",
"ISJ_currencyISO" : "Rial",
"ISJ_currencySingular" : "Rial",
"ISJ_currencySymbol" : "IRR",
"ISK_currencyISO" : "Isländische Krone",
"ISK_currencySingular" : "Isländische Kronen",
"ISK_currencySymbol" : "Ikr",
"ITL_currencyISO" : "Italienische Lira",
"ITL_currencySingular" : "Italienische Lire",
"ITL_currencySymbol" : "IT₤",
"JMD_currencyISO" : "Jamaika-Dollar",
"JMD_currencySingular" : "Jamaika Dollar",
"JMD_currencySymbol" : "J$",
"JOD_currencyISO" : "Jordanischer Dinar",
"JOD_currencySingular" : "Jordanische Dinar",
"JOD_currencySymbol" : "JD",
"JPY_currencyISO" : "Yen",
"JPY_currencySingular" : "Yen",
"JPY_currencySymbol" : "¥",
"KES_currencyISO" : "Kenia-Schilling",
"KES_currencySingular" : "Kenia Schilling",
"KES_currencySymbol" : "Ksh",
"KGS_currencyISO" : "Som",
"KGS_currencySingular" : "Som",
"KGS_currencySymbol" : "KGS",
"KHR_currencyISO" : "Riel",
"KHR_currencySingular" : "Riel",
"KHR_currencySymbol" : "KHR",
"KMF_currencyISO" : "Komoren Franc",
"KMF_currencySingular" : "Komoren-Franc",
"KMF_currencySymbol" : "CF",
"KPW_currencyISO" : "Nordkoreanischer Won",
"KPW_currencySingular" : "Nordkoreanische Won",
"KPW_currencySymbol" : "KPW",
"KRH_currencyISO" : "Nordkoreanischer Won",
"KRH_currencySingular" : "Nordkoreanische Won",
"KRH_currencySymbol" : "KPW",
"KRO_currencyISO" : "Nordkoreanischer Won",
"KRO_currencySingular" : "Nordkoreanische Won",
"KRO_currencySymbol" : "KPW",
"KRW_currencyISO" : "Südkoreanischer Won",
"KRW_currencySingular" : "Südkoreanische Won",
"KRW_currencySymbol" : "₩",
"KWD_currencyISO" : "Kuwait Dinar",
"KWD_currencySingular" : "Kuwait Dinar",
"KWD_currencySymbol" : "KD",
"KYD_currencyISO" : "Kaiman-Dollar",
"KYD_currencySingular" : "Kaiman-Dollar",
"KYD_currencySymbol" : "KY$",
"KZT_currencyISO" : "Tenge",
"KZT_currencySingular" : "Tenge",
"KZT_currencySymbol" : "KZT",
"LAK_currencyISO" : "Kip",
"LAK_currencySingular" : "Kip",
"LAK_currencySymbol" : "₭",
"LBP_currencyISO" : "Libanesisches Pfund",
"LBP_currencySingular" : "Libanesische Pfund",
"LBP_currencySymbol" : "LB£",
"LKR_currencyISO" : "Sri Lanka Rupie",
"LKR_currencySingular" : "Sri Lanka Rupie",
"LKR_currencySymbol" : "SLRs",
"LRD_currencyISO" : "Liberianischer Dollar",
"LRD_currencySingular" : "Liberianische Dollar",
"LRD_currencySymbol" : "L$",
"LSL_currencyISO" : "Loti",
"LSL_currencySingular" : "Loti",
"LSL_currencySymbol" : "LSL",
"LTL_currencyISO" : "Litauischer Litas",
"LTL_currencySingular" : "Litauische Litas",
"LTL_currencySymbol" : "Lt",
"LTT_currencyISO" : "Litauischer Talonas",
"LTT_currencySingular" : "Litauische Talonas",
"LTT_currencySymbol" : "LTT",
"LUC_currencyISO" : "Luxemburgischer Franc (konvertibel)",
"LUC_currencySingular" : "Luxemburgische Franc (konvertibel)",
"LUC_currencySymbol" : "LUC",
"LUF_currencyISO" : "Luxemburgischer Franc",
"LUF_currencySingular" : "Luxemburgische Franc",
"LUF_currencySymbol" : "LUF",
"LUL_currencyISO" : "Luxemburgischer Finanz-Franc",
"LUL_currencySingular" : "Luxemburgische Finanz-Franc",
"LUL_currencySymbol" : "LUL",
"LVL_currencyISO" : "Lettischer Lats",
"LVL_currencySingular" : "Lettische Lats",
"LVL_currencySymbol" : "Ls",
"LVR_currencyISO" : "Lettischer Rubel",
"LVR_currencySingular" : "Lettische Rubel",
"LVR_currencySymbol" : "LVR",
"LYD_currencyISO" : "Libyscher Dinar",
"LYD_currencySingular" : "Libysche Dinar",
"LYD_currencySymbol" : "LD",
"MAD_currencyISO" : "Marokkanischer Dirham",
"MAD_currencySingular" : "Marokkanische Dirham",
"MAD_currencySymbol" : "MAD",
"MAF_currencyISO" : "Marokkanischer Franc",
"MAF_currencySingular" : "Marokkanische Franc",
"MAF_currencySymbol" : "MAF",
"MCF_currencyISO" : "Marokkanischer Franc",
"MCF_currencySingular" : "Marokkanische Franc",
"MCF_currencySymbol" : "MAF",
"MDC_currencyISO" : "Marokkanischer Franc",
"MDC_currencySingular" : "Marokkanische Franc",
"MDC_currencySymbol" : "MAF",
"MDL_currencyISO" : "Moldau Leu",
"MDL_currencySingular" : "Moldau Leu",
"MDL_currencySymbol" : "MDL",
"MGA_currencyISO" : "Madagaskar Ariary",
"MGA_currencySingular" : "Madagaskar Ariary",
"MGA_currencySymbol" : "MGA",
"MGF_currencyISO" : "Madagaskar-Franc",
"MGF_currencySingular" : "Madagaskar-Franc",
"MGF_currencySymbol" : "MGF",
"MKD_currencyISO" : "Denar",
"MKD_currencySingular" : "Denar",
"MKD_currencySymbol" : "MKD",
"MKN_currencyISO" : "Denar",
"MKN_currencySingular" : "Denar",
"MKN_currencySymbol" : "MKD",
"MLF_currencyISO" : "Malischer Franc",
"MLF_currencySingular" : "Malische Franc",
"MLF_currencySymbol" : "MLF",
"MMK_currencyISO" : "Kyat",
"MMK_currencySingular" : "Kyat",
"MMK_currencySymbol" : "MMK",
"MNT_currencyISO" : "Tugrik",
"MNT_currencySingular" : "Tugrik",
"MNT_currencySymbol" : "₮",
"MOP_currencyISO" : "Pataca",
"MOP_currencySingular" : "Pataca",
"MOP_currencySymbol" : "MOP$",
"MRO_currencyISO" : "Ouguiya",
"MRO_currencySingular" : "Ouguiya",
"MRO_currencySymbol" : "UM",
"MTL_currencyISO" : "Maltesische Lira",
"MTL_currencySingular" : "Maltesische Lira",
"MTL_currencySymbol" : "Lm",
"MTP_currencyISO" : "Maltesisches Pfund",
"MTP_currencySingular" : "Maltesische Pfund",
"MTP_currencySymbol" : "MT£",
"MUR_currencyISO" : "Mauritius-Rupie",
"MUR_currencySingular" : "Mauritius Rupie",
"MUR_currencySymbol" : "MURs",
"MVP_currencyISO" : "Mauritius-Rupie",
"MVP_currencySingular" : "Mauritius Rupie",
"MVP_currencySymbol" : "MURs",
"MVR_currencyISO" : "Rufiyaa",
"MVR_currencySingular" : "Rufiyaa",
"MVR_currencySymbol" : "MVR",
"MWK_currencyISO" : "Malawi Kwacha",
"MWK_currencySingular" : "Malawi-Kwacha",
"MWK_currencySymbol" : "MWK",
"MXN_currencyISO" : "Mexikanischer Peso",
"MXN_currencySingular" : "Mexikanische Pesos",
"MXN_currencySymbol" : "MX$",
"MXP_currencyISO" : "Mexikanischer Silber-Peso (1861-1992)",
"MXP_currencySingular" : "Mexikanische Silber-Pesos (MXP)",
"MXP_currencySymbol" : "MXP",
"MXV_currencyISO" : "Mexican Unidad de Inversion (UDI)",
"MXV_currencySingular" : "Mexikanische Unidad de Inversion (UDI)",
"MXV_currencySymbol" : "MXV",
"MYR_currencyISO" : "Malaysischer Ringgit",
"MYR_currencySingular" : "Malaysische Ringgit",
"MYR_currencySymbol" : "RM",
"MZE_currencyISO" : "Mosambikanischer Escudo",
"MZE_currencySingular" : "Mozambikanische Escudo",
"MZE_currencySymbol" : "MZE",
"MZM_currencyISO" : "Alter Metical",
"MZM_currencySingular" : "Alte Metical",
"MZM_currencySymbol" : "Mt",
"MZN_currencyISO" : "Metical",
"MZN_currencySingular" : "Metical",
"MZN_currencySymbol" : "MTn",
"NAD_currencyISO" : "Namibia-Dollar",
"NAD_currencySingular" : "Namibia-Dollar",
"NAD_currencySymbol" : "N$",
"NGN_currencyISO" : "Naira",
"NGN_currencySingular" : "Naira",
"NGN_currencySymbol" : "₦",
"NIC_currencyISO" : "Cordoba",
"NIC_currencySingular" : "Cordoba",
"NIC_currencySymbol" : "NIC",
"NIO_currencyISO" : "Gold-Cordoba",
"NIO_currencySingular" : "Gold-Cordoba",
"NIO_currencySymbol" : "C$",
"NLG_currencyISO" : "Holländischer Gulden",
"NLG_currencySingular" : "Holländische Gulden",
"NLG_currencySymbol" : "fl",
"NOK_currencyISO" : "Norwegische Krone",
"NOK_currencySingular" : "Norwegische Kronen",
"NOK_currencySymbol" : "Nkr",
"NPR_currencyISO" : "Nepalesische Rupie",
"NPR_currencySingular" : "Nepalesische Rupien",
"NPR_currencySymbol" : "NPRs",
"NZD_currencyISO" : "Neuseeland-Dollar",
"NZD_currencySingular" : "Neuseeland-Dollar",
"NZD_currencySymbol" : "NZ$",
"OMR_currencyISO" : "Rial Omani",
"OMR_currencySingular" : "Rial Omani",
"OMR_currencySymbol" : "OMR",
"PAB_currencyISO" : "Balboa",
"PAB_currencySingular" : "Balboa",
"PAB_currencySymbol" : "B/.",
"PEI_currencyISO" : "Peruanischer Inti",
"PEI_currencySingular" : "Peruanische Inti",
"PEI_currencySymbol" : "I/.",
"PEN_currencyISO" : "Neuer Sol",
"PEN_currencySingular" : "Neue Sol",
"PEN_currencySymbol" : "S/.",
"PES_currencyISO" : "Sol",
"PES_currencySingular" : "Sol",
"PES_currencySymbol" : "PES",
"PGK_currencyISO" : "Kina",
"PGK_currencySingular" : "Kina",
"PGK_currencySymbol" : "PGK",
"PHP_currencyISO" : "Philippinischer Peso",
"PHP_currencySingular" : "Philippinische Peso",
"PHP_currencySymbol" : "₱",
"PKR_currencyISO" : "Pakistanische Rupie",
"PKR_currencySingular" : "Pakistanische Rupien",
"PKR_currencySymbol" : "PKRs",
"PLN_currencyISO" : "Zloty",
"PLN_currencySingular" : "Zloty",
"PLN_currencySymbol" : "zł",
"PLZ_currencyISO" : "Zloty (1950-1995)",
"PLZ_currencySingular" : "Zloty (PLZ)",
"PLZ_currencySymbol" : "PLZ",
"PTE_currencyISO" : "Portugiesischer Escudo",
"PTE_currencySingular" : "Portugiesische Escudo",
"PTE_currencySymbol" : "Esc",
"PYG_currencyISO" : "Guarani",
"PYG_currencySingular" : "Guarani",
"PYG_currencySymbol" : "₲",
"QAR_currencyISO" : "Katar Riyal",
"QAR_currencySingular" : "Katar Riyal",
"QAR_currencySymbol" : "QR",
"RHD_currencyISO" : "Rhodesischer Dollar",
"RHD_currencySingular" : "Rhodesische Dollar",
"RHD_currencySymbol" : "RH$",
"ROL_currencyISO" : "Leu",
"ROL_currencySingular" : "Leu",
"ROL_currencySymbol" : "ROL",
"RON_currencyISO" : "Rumänischer Leu",
"RON_currencySingular" : "Rumänische Leu",
"RON_currencySymbol" : "RON",
"RSD_currencyISO" : "Serbischer Dinar",
"RSD_currencySingular" : "Serbische Dinar",
"RSD_currencySymbol" : "din.",
"RUB_currencyISO" : "Russischer Rubel (neu)",
"RUB_currencySingular" : "Russische Rubel (neu)",
"RUB_currencySymbol" : "RUB",
"RUR_currencyISO" : "Russischer Rubel (alt)",
"RUR_currencySingular" : "Russische Rubel (alt)",
"RUR_currencySymbol" : "RUR",
"RWF_currencyISO" : "Ruanda-Franc",
"RWF_currencySingular" : "Ruanda-Franc",
"RWF_currencySymbol" : "RWF",
"SAR_currencyISO" : "Saudi Riyal",
"SAR_currencySingular" : "Saudi Riyal",
"SAR_currencySymbol" : "SR",
"SBD_currencyISO" : "Salomonen-Dollar",
"SBD_currencySingular" : "Salomonen-Dollar",
"SBD_currencySymbol" : "SI$",
"SCR_currencyISO" : "Seychellen-Rupie",
"SCR_currencySingular" : "Seychellen-Rupien",
"SCR_currencySymbol" : "SRe",
"SDD_currencyISO" : "Sudanesischer Dinar",
"SDD_currencySingular" : "Sudanesische Dinar",
"SDD_currencySymbol" : "LSd",
"SDG_currencyISO" : "Sudanesisches Pfund",
"SDG_currencySingular" : "Sudanesische Pfund",
"SDG_currencySymbol" : "SDG",
"SDP_currencyISO" : "Sudanesisches Pfund (alt)",
"SDP_currencySingular" : "Sudanesische Pfund (alt)",
"SDP_currencySymbol" : "SDP",
"SEK_currencyISO" : "Schwedische Krone",
"SEK_currencySingular" : "Schwedische Kronen",
"SEK_currencySymbol" : "Skr",
"SGD_currencyISO" : "Singapur-Dollar",
"SGD_currencySingular" : "Singapur-Dollar",
"SGD_currencySymbol" : "S$",
"SHP_currencyISO" : "St. Helena Pfund",
"SHP_currencySingular" : "St. Helena-Pfund",
"SHP_currencySymbol" : "SH£",
"SIT_currencyISO" : "Tolar",
"SIT_currencySingular" : "Tolar",
"SIT_currencySymbol" : "SIT",
"SKK_currencyISO" : "Slowakische Krone",
"SKK_currencySingular" : "Slowakische Kronen",
"SKK_currencySymbol" : "Sk",
"SLL_currencyISO" : "Leone",
"SLL_currencySingular" : "Leone",
"SLL_currencySymbol" : "Le",
"SOS_currencyISO" : "Somalia-Schilling",
"SOS_currencySingular" : "Somalia-Schilling",
"SOS_currencySymbol" : "Ssh",
"SRD_currencyISO" : "Surinamischer Dollar",
"SRD_currencySingular" : "Surinamische Dollar",
"SRD_currencySymbol" : "SR$",
"SRG_currencyISO" : "Suriname Gulden",
"SRG_currencySingular" : "Suriname-Gulden",
"SRG_currencySymbol" : "Sf",
"SSP_currencyISO" : "Suriname Gulden",
"SSP_currencySingular" : "Suriname-Gulden",
"SSP_currencySymbol" : "Sf",
"STD_currencyISO" : "Dobra",
"STD_currencySingular" : "Dobra",
"STD_currencySymbol" : "Db",
"SUR_currencyISO" : "Sowjetischer Rubel",
"SUR_currencySingular" : "Sowjetische Rubel",
"SUR_currencySymbol" : "SUR",
"SVC_currencyISO" : "El Salvador Colon",
"SVC_currencySingular" : "El Salvador-Colon",
"SVC_currencySymbol" : "SV₡",
"SYP_currencyISO" : "Syrisches Pfund",
"SYP_currencySingular" : "Syrische Pfund",
"SYP_currencySymbol" : "SY£",
"SZL_currencyISO" : "Lilangeni",
"SZL_currencySingular" : "Lilangeni",
"SZL_currencySymbol" : "SZL",
"THB_currencyISO" : "Baht",
"THB_currencySingular" : "Baht",
"THB_currencySymbol" : "฿",
"TJR_currencyISO" : "Tadschikistan Rubel",
"TJR_currencySingular" : "Tadschikistan-Rubel",
"TJR_currencySymbol" : "TJR",
"TJS_currencyISO" : "Tadschikistan Somoni",
"TJS_currencySingular" : "Tadschikistan-Somoni",
"TJS_currencySymbol" : "TJS",
"TMM_currencyISO" : "Turkmenistan-Manat",
"TMM_currencySingular" : "Turkmenistan-Manat",
"TMM_currencySymbol" : "TMM",
"TMT_currencyISO" : "Turkmenistan-Manat",
"TMT_currencySingular" : "Turkmenistan-Manat",
"TMT_currencySymbol" : "TMM",
"TND_currencyISO" : "Tunesischer Dinar",
"TND_currencySingular" : "Tunesische Dinar",
"TND_currencySymbol" : "DT",
"TOP_currencyISO" : "Paʻanga",
"TOP_currencySingular" : "Paʻanga",
"TOP_currencySymbol" : "T$",
"TPE_currencyISO" : "Timor-Escudo",
"TPE_currencySingular" : "Timor-Escudo",
"TPE_currencySymbol" : "TPE",
"TRL_currencyISO" : "Alte Türkische Lira",
"TRL_currencyPlural" : "Alte Türkische Lire",
"TRL_currencySingular" : "Alte Türkische Lira",
"TRL_currencySymbol" : "TRL",
"TRY_currencyISO" : "Türkische Lira",
"TRY_currencyPlural" : "Türkische Lira",
"TRY_currencySingular" : "Türkische Lira",
"TRY_currencySymbol" : "TL",
"TTD_currencyISO" : "Trinidad- und Tobago-Dollar",
"TTD_currencyPlural" : "Türkische Lira",
"TTD_currencySingular" : "Trinidad und Tobago-Dollar",
"TTD_currencySymbol" : "TT$",
"TWD_currencyISO" : "Neuer Taiwan-Dollar",
"TWD_currencyPlural" : "Türkische Lira",
"TWD_currencySingular" : "Neuer Taiwan Dollar",
"TWD_currencySymbol" : "NT$",
"TZS_currencyISO" : "Tansania-Schilling",
"TZS_currencyPlural" : "Türkische Lira",
"TZS_currencySingular" : "Tansania-Schilling",
"TZS_currencySymbol" : "TSh",
"UAH_currencyISO" : "Hryvnia",
"UAH_currencyPlural" : "Türkische Lira",
"UAH_currencySingular" : "Hryvnia",
"UAH_currencySymbol" : "₴",
"UAK_currencyISO" : "Ukrainischer Karbovanetz",
"UAK_currencyPlural" : "Türkische Lira",
"UAK_currencySingular" : "Ukrainische Karbovanetz",
"UAK_currencySymbol" : "UAK",
"UGS_currencyISO" : "Uganda-Schilling (1966-1987)",
"UGS_currencyPlural" : "Türkische Lira",
"UGS_currencySingular" : "Uganda-Schilling (UGS)",
"UGS_currencySymbol" : "UGS",
"UGX_currencyISO" : "Uganda-Schilling",
"UGX_currencyPlural" : "Türkische Lira",
"UGX_currencySingular" : "Uganda-Schilling",
"UGX_currencySymbol" : "USh",
"USD_currencyISO" : "US-Dollar",
"USD_currencyPlural" : "Türkische Lira",
"USD_currencySingular" : "US-Dollar",
"USD_currencySymbol" : "$",
"USN_currencyISO" : "US Dollar (Nächster Tag)",
"USN_currencyPlural" : "Türkische Lira",
"USN_currencySingular" : "US-Dollar (Nächster Tag)",
"USN_currencySymbol" : "USN",
"USS_currencyISO" : "US Dollar (Gleicher Tag)",
"USS_currencyPlural" : "Türkische Lira",
"USS_currencySingular" : "US-Dollar (Gleicher Tag)",
"USS_currencySymbol" : "USS",
"UYI_currencyISO" : "UYU",
"UYI_currencyPlural" : "Türkische Lira",
"UYI_currencySingular" : "US-Dollar (Gleicher Tag)",
"UYI_currencySymbol" : "UYI",
"UYP_currencyISO" : "Uruguayischer Neuer Peso (1975-1993)",
"UYP_currencyPlural" : "Türkische Lira",
"UYP_currencySingular" : "Uruguayische Pesos (UYP)",
"UYP_currencySymbol" : "UYP",
"UYU_currencyISO" : "Uruguayischer Peso",
"UYU_currencyPlural" : "Türkische Lira",
"UYU_currencySingular" : "Uruguayische Pesos",
"UYU_currencySymbol" : "$U",
"UZS_currencyISO" : "Usbekistan Sum",
"UZS_currencyPlural" : "Türkische Lira",
"UZS_currencySingular" : "Usbekistan-Sum",
"UZS_currencySymbol" : "UZS",
"VEB_currencyISO" : "Bolivar",
"VEB_currencyPlural" : "Türkische Lira",
"VEB_currencySingular" : "Bolivar",
"VEB_currencySymbol" : "VEB",
"VEF_currencyISO" : "Bolívar Fuerte",
"VEF_currencyPlural" : "Türkische Lira",
"VEF_currencySingular" : "Bolivar",
"VEF_currencySymbol" : "Bs.F.",
"VND_currencyISO" : "Dong",
"VND_currencyPlural" : "Türkische Lira",
"VND_currencySingular" : "Dong",
"VND_currencySymbol" : "₫",
"VNN_currencyISO" : "Dong",
"VNN_currencyPlural" : "Türkische Lira",
"VNN_currencySingular" : "Dong",
"VNN_currencySymbol" : "₫",
"VUV_currencyISO" : "Vatu",
"VUV_currencyPlural" : "Türkische Lira",
"VUV_currencySingular" : "Vatu",
"VUV_currencySymbol" : "VT",
"WST_currencyISO" : "Tala",
"WST_currencyPlural" : "Türkische Lira",
"WST_currencySingular" : "Tala",
"WST_currencySymbol" : "WS$",
"XAF_currencyISO" : "CFA Franc (Äquatorial)",
"XAF_currencyPlural" : "Türkische Lira",
"XAF_currencySingular" : "CFA-Franc (BEAC)",
"XAF_currencySymbol" : "FCFA",
"XAG_currencyISO" : "Unze Silber",
"XAG_currencyPlural" : "Silber",
"XAG_currencySingular" : "Unze Silber",
"XAG_currencySymbol" : "XAG",
"XAU_currencyISO" : "Unze Gold",
"XAU_currencyPlural" : "Gold",
"XAU_currencySingular" : "Unze Gold",
"XAU_currencySymbol" : "XAU",
"XBA_currencyISO" : "Europäische Rechnungseinheit",
"XBA_currencyPlural" : "Gold",
"XBA_currencySingular" : "Europäische Rechnungseinheiten",
"XBA_currencySymbol" : "XBA",
"XBB_currencyISO" : "Europäische Währungseinheit (XBB)",
"XBB_currencyPlural" : "Gold",
"XBB_currencySingular" : "Europäische Währungseinheiten (XBB)",
"XBB_currencySymbol" : "XBB",
"XBC_currencyISO" : "Europäische Rechnungseinheit (XBC)",
"XBC_currencyPlural" : "Gold",
"XBC_currencySingular" : "Europäische Rechnungseinheiten (XBC)",
"XBC_currencySymbol" : "XBC",
"XBD_currencyISO" : "Europäische Rechnungseinheit (XBD)",
"XBD_currencyPlural" : "Gold",
"XBD_currencySingular" : "Europäische Rechnungseinheiten (XBD)",
"XBD_currencySymbol" : "XBD",
"XCD_currencyISO" : "Ostkaribischer Dollar",
"XCD_currencyPlural" : "Gold",
"XCD_currencySingular" : "Ostkaribische Dollar",
"XCD_currencySymbol" : "EC$",
"XDR_currencyISO" : "Sonderziehungsrechte",
"XDR_currencyPlural" : "Gold",
"XDR_currencySingular" : "Sonderziehungsrechte",
"XDR_currencySymbol" : "XDR",
"XEU_currencyISO" : "Europäische Währungseinheit (XEU)",
"XEU_currencyPlural" : "Gold",
"XEU_currencySingular" : "Europäische Währungseinheiten (XEU)",
"XEU_currencySymbol" : "XEU",
"XFO_currencyISO" : "Französischer Gold-Franc",
"XFO_currencyPlural" : "Gold",
"XFO_currencySingular" : "Französische Gold-Franc",
"XFO_currencySymbol" : "XFO",
"XFU_currencyISO" : "Französischer UIC-Franc",
"XFU_currencyPlural" : "Gold",
"XFU_currencySingular" : "Französische UIC-Franc",
"XFU_currencySymbol" : "XFU",
"XOF_currencyISO" : "CFA Franc (West)",
"XOF_currencyPlural" : "Gold",
"XOF_currencySingular" : "CFA-Franc (BCEAO)",
"XOF_currencySymbol" : "CFA",
"XPD_currencyISO" : "Unze Palladium",
"XPD_currencyPlural" : "Palladium",
"XPD_currencySingular" : "Unze Palladium",
"XPD_currencySymbol" : "XPD",
"XPF_currencyISO" : "CFP Franc",
"XPF_currencyPlural" : "Palladium",
"XPF_currencySingular" : "CFP-Franc",
"XPF_currencySymbol" : "CFPF",
"XPT_currencyISO" : "Unze Platin",
"XPT_currencyPlural" : "Platin",
"XPT_currencySingular" : "Unze Platin",
"XPT_currencySymbol" : "XPT",
"XRE_currencyISO" : "RINET Funds",
"XRE_currencyPlural" : "Platin",
"XRE_currencySingular" : "RINET Funds",
"XRE_currencySymbol" : "XRE",
"XSU_currencyISO" : "RINET Funds",
"XSU_currencyPlural" : "Platin",
"XSU_currencySingular" : "RINET Funds",
"XSU_currencySymbol" : "XRE",
"XTS_currencyISO" : "Testwährung",
"XTS_currencyPlural" : "Platin",
"XTS_currencySingular" : "Testwährung",
"XTS_currencySymbol" : "XTS",
"XUA_currencyISO" : "Testwährung",
"XUA_currencyPlural" : "Platin",
"XUA_currencySingular" : "Testwährung",
"XUA_currencySymbol" : "XTS",
"XXX_currencyISO" : "Unbekannte Währung",
"XXX_currencyPlural" : "Unbekannte Währung",
"XXX_currencySingular" : "Unbekannte Währung",
"XXX_currencySymbol" : "XXX",
"YDD_currencyISO" : "Jemen-Dinar",
"YDD_currencyPlural" : "Unbekannte Währung",
"YDD_currencySingular" : "Jemen-Dinar",
"YDD_currencySymbol" : "YDD",
"YER_currencyISO" : "Jemen-Rial",
"YER_currencyPlural" : "Unbekannte Währung",
"YER_currencySingular" : "Jemen-Rial",
"YER_currencySymbol" : "YR",
"YUD_currencyISO" : "Jugoslawischer Dinar (1966-1990)",
"YUD_currencyPlural" : "Unbekannte Währung",
"YUD_currencySingular" : "Jugoslawische Dinar",
"YUD_currencySymbol" : "YUD",
"YUM_currencyISO" : "Neuer Dinar",
"YUM_currencyPlural" : "Unbekannte Währung",
"YUM_currencySingular" : "Jugoslawische Neue Dinar",
"YUM_currencySymbol" : "YUM",
"YUN_currencyISO" : "Jugoslawischer Dinar (konvertibel)",
"YUN_currencyPlural" : "Unbekannte Währung",
"YUN_currencySingular" : "Jugoslawische Dinar (konvertibel)",
"YUN_currencySymbol" : "YUN",
"YUR_currencyISO" : "Jugoslawischer Dinar (konvertibel)",
"YUR_currencyPlural" : "Unbekannte Währung",
"YUR_currencySingular" : "Jugoslawische Dinar (konvertibel)",
"YUR_currencySymbol" : "YUN",
"ZAL_currencyISO" : "Südafrikanischer Rand (Finanz)",
"ZAL_currencyPlural" : "Südafrikanischer Rand (Finanz)",
"ZAL_currencySingular" : "Südafrikanischer Rand (Finanz)",
"ZAL_currencySymbol" : "ZAL",
"ZAR_currencyISO" : "Südafrikanischer Rand",
"ZAR_currencyPlural" : "Rand",
"ZAR_currencySingular" : "Südafrikanischer Rand",
"ZAR_currencySymbol" : "R",
"ZMK_currencyISO" : "Kwacha",
"ZMK_currencyPlural" : "Rand",
"ZMK_currencySingular" : "Kwacha",
"ZMK_currencySymbol" : "ZK",
"ZRN_currencyISO" : "Neuer Zaire",
"ZRN_currencyPlural" : "Rand",
"ZRN_currencySingular" : "Neue Zaire",
"ZRN_currencySymbol" : "NZ",
"ZRZ_currencyISO" : "Zaire",
"ZRZ_currencyPlural" : "Rand",
"ZRZ_currencySingular" : "Zaire",
"ZRZ_currencySymbol" : "ZRZ",
"ZWD_currencyISO" : "Simbabwe-Dollar",
"ZWD_currencyPlural" : "Rand",
"ZWD_currencySingular" : "Simbabwe-Dollar",
"ZWD_currencySymbol" : "Z$",
"ZWL_currencyISO" : "Simbabwe-Dollar",
"ZWL_currencyPlural" : "Rand",
"ZWL_currencySingular" : "Simbabwe-Dollar",
"ZWL_currencySymbol" : "Z$",
"ZWR_currencyISO" : "Simbabwe-Dollar",
"ZWR_currencyPlural" : "Rand",
"ZWR_currencySingular" : "Simbabwe-Dollar",
"ZWR_currencySymbol" : "Z$",
"currencyFormat" : "¤ #,##0.00",
"currencyPatternPlural" : "{0} {1}",
"currencyPatternSingular" : "{0} {1}",
"decimalFormat" : "#,##0.###",
"decimalSeparator" : ".",
"defaultCurrency" : "CHF",
"exponentialSymbol" : "E",
"groupingSeparator" : "'",
"infinitySign" : "∞",
"minusSign" : "-",
"nanSymbol" : "NaN",
"numberZero" : "0",
"perMilleSign" : "‰",
"percentFormat" : "#,##0 %",
"percentSign" : "%",
"plusSign" : "+",
"scientificFormat" : "#E0"
}
| mit |
aikramer2/spaCy | spacy/lang/id/punctuation.py | 2125 | # coding: utf8
from __future__ import unicode_literals
from ..punctuation import TOKENIZER_PREFIXES, TOKENIZER_SUFFIXES, TOKENIZER_INFIXES
from ..char_classes import merge_chars, split_chars, _currency, _units
from ..char_classes import LIST_PUNCT, LIST_ELLIPSES, LIST_QUOTES
from ..char_classes import QUOTES, ALPHA, ALPHA_LOWER, ALPHA_UPPER, HYPHENS
_units = (_units + 's bit Gbps Mbps mbps Kbps kbps ƒ ppi px '
'Hz kHz MHz GHz mAh '
'ratus rb ribu ribuan '
'juta jt jutaan mill?iar million bil[l]?iun bilyun billion '
)
_currency = (_currency + r' USD Rp IDR RMB SGD S\$')
_months = ('Januari Februari Maret April Mei Juni Juli Agustus September '
'Oktober November Desember January February March May June '
'July August October December Jan Feb Mar Jun Jul Aug Sept '
'Oct Okt Nov Des ')
UNITS = merge_chars(_units)
CURRENCY = merge_chars(_currency)
HTML_PREFIX = r'<(b|strong|i|em|p|span|div|br)\s?/>|<a([^>]+)>'
HTML_SUFFIX = r'</(b|strong|i|em|p|span|div|a)>'
MONTHS = merge_chars(_months)
LIST_CURRENCY = split_chars(_currency)
TOKENIZER_PREFIXES.remove('#') # hashtag
_prefixes = TOKENIZER_PREFIXES + LIST_CURRENCY + [HTML_PREFIX] + ['/', '—']
_suffixes = TOKENIZER_SUFFIXES + [r'\-[Nn]ya', '-[KkMm]u', '[—-]'] + [
r'(?<={c})(?:[0-9]+)'.format(c=CURRENCY),
r'(?<=[0-9])(?:{u})'.format(u=UNITS),
r'(?<=[0-9])%',
r'(?<=[0-9{a}]{h})(?:[\.,:-])'.format(a=ALPHA, h=HTML_SUFFIX),
r'(?<=[0-9{a}])(?:{h})'.format(a=ALPHA, h=HTML_SUFFIX),
]
_infixes = TOKENIZER_INFIXES + [
r'(?<=[0-9])[\\/](?=[0-9%-])',
r'(?<=[0-9])%(?=[{a}0-9/])'.format(a=ALPHA),
r'(?<={u})[\/-](?=[0-9])'.format(u=UNITS),
r'(?<={m})[\/-](?=[0-9])'.format(m=MONTHS),
r'(?<=[0-9\)][\.,])"(?=[0-9])',
r'(?<=[{a}\)][\.,\'])["—](?=[{a}])'.format(a=ALPHA),
r'(?<=[{a}])-(?=[0-9])'.format(a=ALPHA),
r'(?<=[0-9])-(?=[{a}])'.format(a=ALPHA),
r'(?<=[{a}])[\/-](?={c}{a})'.format(a=ALPHA, c=CURRENCY),
]
TOKENIZER_PREFIXES = _prefixes
TOKENIZER_SUFFIXES = _suffixes
TOKENIZER_INFIXES = _infixes
| mit |
ricardomccerqueira/sgrid | node_modules/grunt-ruby-haml/test/expected/01_straight.js | 410 | define(function() { return function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml">\n <head>\n <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />\n <title>TEST</title>\n </head>\n <body>\n <h1>Just testing</h1>\n </body>\n</html>';
}
return __p;
}}); | mit |
devmars/javapractice | NetBeansProjects/practice/src/bufferedio/BufferedByteStream.java | 1450 | /*
* 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 bufferedio;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Buffered I/O stream
*
* Buffered input streams read data from a memory area known as a buffer; the
* native input API is called only when the buffer is empty. Similarly, buffered
* output streams write data to a buffer, and the native output API is called
* only when the buffer is full.
*
* @author mars
*/
public class BufferedByteStream {
public static void main(String[] args) throws IOException {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream("/home/mars/NetBeansProjects/practice/src/unbufferedio/xanadu.txt"));
out = new BufferedOutputStream(new FileOutputStream("/home/mars/NetBeansProjects/practice/src/bufferedio/bufferedbytes.txt"));
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
| mit |
sloncho/Nancy | src/Nancy/Diagnostics/Modules/InteractiveModule.cs | 4942 | namespace Nancy.Diagnostics.Modules
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Nancy.Helpers;
public class InteractiveModule : DiagnosticModule
{
private readonly IInteractiveDiagnostics interactiveDiagnostics;
public InteractiveModule(IInteractiveDiagnostics interactiveDiagnostics)
:base ("/interactive")
{
this.interactiveDiagnostics = interactiveDiagnostics;
Get("/", _ =>
{
return View["InteractiveDiagnostics"];
});
Get("/providers", _ =>
{
var providers = this.interactiveDiagnostics
.AvailableDiagnostics
.Select(p => new
{
p.Name,
p.Description,
Type = p.GetType().Name,
p.GetType().Namespace,
Assembly = p.GetType().Assembly.GetName().Name
})
.ToArray();
return this.Response.AsJson(providers);
});
Get("/providers/{providerName}", ctx =>
{
var providerName =
HttpUtility.UrlDecode((string)ctx.providerName);
var diagnostic =
this.interactiveDiagnostics.GetDiagnostic(providerName);
if (diagnostic == null)
{
return HttpStatusCode.NotFound;
}
var methods = diagnostic.Methods
.Select(m => new
{
m.MethodName,
ReturnType = m.ReturnType.ToString(),
m.Description,
Arguments = m.Arguments.Select(a => new
{
ArgumentName = a.Item1,
ArgumentType = a.Item2.ToString()
})
})
.ToArray();
return this.Response.AsJson(methods);
});
Get("/providers/{providerName}/{methodName}", ctx =>
{
var providerName =
HttpUtility.UrlDecode((string)ctx.providerName);
var methodName =
HttpUtility.UrlDecode((string)ctx.methodName);
var method =
this.interactiveDiagnostics.GetMethod(providerName, methodName);
if (method == null)
{
return HttpStatusCode.NotFound;
}
object[] arguments =
GetArguments(method, this.Request.Query);
return this.Response.AsJson(new { Result = this.interactiveDiagnostics.ExecuteDiagnostic(method, arguments) });
});
Get<Response>("/templates/{providerName}/{methodName}", ctx =>
{
var providerName =
HttpUtility.UrlDecode((string)ctx.providerName);
var methodName =
HttpUtility.UrlDecode((string)ctx.methodName);
var method =
this.interactiveDiagnostics.GetMethod(providerName, methodName);
if (method == null)
{
return HttpStatusCode.NotFound;
}
var template =
this.interactiveDiagnostics.GetTemplate(method);
if (template == null)
{
return HttpStatusCode.NotFound;
}
return template;
});
}
private static object[] GetArguments(InteractiveDiagnosticMethod method, dynamic query)
{
var arguments = new List<object>();
foreach (var argument in method.Arguments)
{
arguments.Add(ConvertArgument((string)query[argument.Item1].Value, argument.Item2));
}
return arguments.ToArray();
}
private static object ConvertArgument(string value, Type destinationType)
{
var converter =
TypeDescriptor.GetConverter(destinationType);
if (converter == null || !converter.CanConvertFrom(typeof(string)))
{
return null;
}
try
{
return converter.ConvertFrom(value);
}
catch (FormatException)
{
return null;
}
}
}
} | mit |
yaal-fr/ysvgmaps | node_modules/riot/node_modules/riot-cli/lib/Task.js | 4220 | 'use strict'
const
helpers = require('./helpers'),
path = require('path'),
sh = require('shelljs'),
compiler = global.compiler || require('riot-compiler'),
constants = require('./const'),
NO_FILE_FOUND = constants.NO_FILE_FOUND,
PREPROCESSOR_NOT_REGISTERED = constants.PREPROCESSOR_NOT_REGISTERED
/**
* Base class that will extended to handle all the cli tasks
*/
class Task {
constructor(opt) {
// Run only once
/* istanbul ignore next */
if (this.called) return
this.called = true
this.error = null
// create a regex to figure out whether our user
// wants to compile a single tag or some tags in a folder
this.extRegex = new RegExp(`\\.${opt.ext || 'tag' }$`)
// make sure the parsers object is always valid
opt.parsers = helpers.extend(
compiler.parsers,
opt.parsers || {}
)
if (opt.compiler) {
// validate the compiler options
const err = this.validate(opt.compiler, opt.parsers)
if (err) return this.handleError(err, opt.isCli)
} else {
// make sure to set always the compiler options
opt.compiler = {}
}
if (opt.stdin) {
if (opt.from) {
helpers.log('Stdin will be used instead of the files/dirs specified.')
delete opt.stdin
}
} else {
// Resolve to absolute paths
opt.from = path.resolve(opt.from)
// Check if the path exsists
if (!sh.test('-e', opt.from)) return this.handleError(NO_FILE_FOUND, opt.isCli)
}
if (opt.stdout) {
if (opt.to) {
helpers.log('Stdout will be used instead of the files/dirs specified.')
delete opt.to
}
} else {
// If no target dir, default to source dir
const from = opt.from || ''
opt.to = opt.to || (this.extRegex.test(from) ? path.dirname(from) : from)
// Resolve to absolute paths
opt.to = path.resolve(opt.to)
}
/**
* Determine the input/output types
* f: file
* d: directory
* s: stdin/stdout
*/
const
isFile = !opt.stdout && /\.(js|html|css)$/.test(opt.to),
flowIn = opt.stdin ? 's' : this.extRegex.test(opt.from) ? 'f' : 'd',
flowOut = opt.stdout ? 's' : opt.stdin || isFile ? 'f' : 'd'
// 'ff', 'fd', 'fs', 'df', 'dd', 'ds', 'sf' or 'ss'
// note that 'sd' is an imposible combination
opt.flow = flowIn + flowOut
if (opt.stdin && !opt.stdout && !isFile) {
opt.to = path.join(opt.to, `output.${opt.export || 'js'}`)
helpers.log(`Destination is rewrited: ${opt.to}`)
}
// each run method could return different stuff
return this.run(opt)
}
/**
* Check whether a parser has been correctly registered and It can be loaded
* @param { String } type - parser scope html|javascript|css
* @param { String } id - parser id, the require() call
* @param { Object } parsers - custom parser options
* @returns { String|Null } get the error message when the parser can not be loaded
*/
findParser(type, id, parsers) {
var error
// is it a default a default compiler parser?
// if not check if it has bee manually registered
if (!compiler.parsers[type][id] && !parsers[type][id])
error = PREPROCESSOR_NOT_REGISTERED(type, id)
else
try {
compiler.parsers._req(id, true)
} catch (e) {
error = e.toString()
}
return typeof error == 'string' ? error : null
}
/**
* Validate the compiler options checking whether the local dependencies
* are installed
* @param { Object } opt - compiler options
* @param { Object } parsers - custom parser options
* @returns {String|Null} - false if there are no errors
*/
validate(opt, parsers) {
var template = opt.template,
type = opt.type,
style = opt.style,
error = null
if (template)
error = this.findParser('html', template, parsers)
if (type && !error)
error = this.findParser('js', type, parsers)
if (style && !error)
error = this.findParser('css', style, parsers)
return error
}
handleError(msg, isCli) {
this.error = msg
if (isCli) helpers.err(this.error)
return this.error
}
}
module.exports = Task
| mit |
gastrodia/wasp-ui-editor | src/components/inspector/ComponentSelector.ts | 1934 | import $ = require('jquery');
import WOZLLA = require('wozllajs');
import {Component, View, ViewEncapsulation, coreDirectives} from 'angular2/angular2';
import angular2 = require('angular2/angular2');
import ng2Helper = require('../ng2-library/ng2Helper');
import BasicPanel = require('./panel/BasicPanel');
import Dialog = require('../dark-ui/dialog/Dialog');
import TransformPanel = require('./panel/TransformPanel');
import ComponentPanel = require('./panel/ComponentPanel');
var CompFactory = WOZLLA.component.ComponentFactory;
import {
eventDispatcher,
getCurrentProjectPath,
handleAddComponent
} from '../project/project';
const tpl = require('./component-selector.html');
const css = require('./component-selector.css');
@Component({
selector: 'component-selector'
})
@View({
template: tpl,
styles: [css],
directives: [Dialog, coreDirectives],
encapsulation: ViewEncapsulation.NONE
})
class ComponentSelector {
$root;
$selectedItem;
constructor() {
this.$root = $('component-selector');
this.$root.hide();
}
getComponentNames():string[] {
var ret = [];
CompFactory.eachComponent((name:string) => {
ret.push(name);
});
return ret;
}
onItemClick(e) {
this.$selectedItem && this.$selectedItem.removeClass('selected');
this.$selectedItem = $(e.target);
this.$selectedItem.addClass('selected');
}
onItemDblClick(e) {
this.onConfirmSelect();
}
onClick(e) {
var $target = $(e.target);
if($target.hasClass('ok')) {
this.onConfirmSelect();
} else if($target.hasClass('cancel')) {
$('component-selector').hide();
}
}
onConfirmSelect() {
if(!this.$selectedItem) return;
this.$root.hide();
handleAddComponent(this.$selectedItem.text().trim());
}
}
export = ComponentSelector;
| mit |
cebor/gui-project | app/scripts/filters/symbolresolver.js | 1198 | 'use strict';
angular.module('stockApp')
/**
* Filter: resolve stock symbols to real names
* @param symbol String/String[]
* @return String/String[]
*/
.filter('symbolResolver', function () {
function resolve(symbol) {
switch (symbol) {
case "MSFT":
return "Microsoft";
case "KO":
return "Coca-Cola";
case "YHOO":
return "Yahoo!";
case "UNIA.AS":
return "UNILEVER";
case "GOOGL":
return "Google";
case "AAPL":
return "Apple";
case "NSU.DE":
return "Audi AG";
case "SSU.DE":
return "Samsung";
case "NTDOF":
return "Nintendo";
case "BMW.DE":
return "BMW AG";
case "SIE.DE":
return "Siemens AG";
case "DAI.DE":
return "Daimler AG";
default:
return symbol;
}
}
return function (input) {
if(angular.isArray(input)) {
var output = [];
angular.forEach(input, function (value) {
output.push(resolve(value));
});
return output;
}
return resolve(input);
};
});
| mit |
cmccullough2/cmv-wab-widgets | wab/2.2/widgets/Geoprocessing/nls/sr/strings.js | 1153 | define({
"_widgetLabel": "Geoprocesiranje",
"_featureAction_ReceiveFeatureSet": "Podesi kao unos od ",
"requiredInfo": "je obavezno.",
"drawnOnMap": "Rezultat je nacrtan na mapi.",
"noToolConfig": "Nema dostupnih unapred konfigurisanih zadataka geoprocesiranja.",
"useUrlForGPInput": "URL adresa",
"useUploadForGPInput": "Otpremi datoteku",
"selectFileToUpload": "Izaberite datoteku...",
"rasterFormat": "Format rasterskih podataka",
"noFileSelected": "Nema izabrane datoteke!",
"uploadSuccess": "Uspešno otpremanje datoteke!",
"showLayerContent": "Prikaži sadržaj sloja",
"invalidUrl": "Nevažeća URL adresa servisa geoobjekata",
"urlPlaceholder": "URL adresa seta geoobjekata",
"addShapefile": "Dodaj datoteku „shapefile“",
"generateShapefileError": "Generiši grešku datoteke „shapefile“, proverite: ",
"cleared": "Rezultat je obrisan.",
"enlargeView": "Uveličaj prikaz",
"exportOutput": "Izvezi",
"emptyResult": "Rezultat je prazan.",
"useSelectedFeatureset": "Koristite rezultujući geoobjekat/geoobjekte.",
"closeSelectedFeatureset": "Obrišite i koristite konfigurisanu opciju unosa."
}); | mit |
QiV/fest-dom-loader | events/onclosetag/htmlTags.js | 524 | var shortTags = {
area: true,
base: true,
br: true,
col: true,
command: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
wbr: true
};
module.exports = function(node, parser) {
parser.nodeNamesStack.pop();
if (!(node.name in shortTags)) {
if (parser.lang === 'Xslate') {
parser.source.push('</#>'.replace('#', node.name));
} else {
parser.source.push('"</#>"'.replace('#', node.name));
}
}
};
| mit |
ibnoe/erp | application/views/journal/view_receipt_cheque_schedule.php | 3461 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<?php $this->load->view('includes/head');?>
<style>
label{
color: #FF0000;
width: 350px;
}
input{
height: 20px;
}
</style>
<script type="text/javascript">
$(function () {
$('.checkall').click(function () {
$(this).parents('#content').find(':checkbox').attr('checked', this.checked);
});
});
</script>
</head>
<body>
<div class="container">
<!-- Headers Starts -->
<div id="header" class="column span-24">
<?php $this->load->view('includes/header');?>
</div>
<!-- Headers Ends -->
<!-- Navigation Start -->
<div id="nav" class="span-24 last">
<?php $this->load->view('includes/menu');?>
</div>
<!-- Navigation End -->
<!-- Main Area/Content Starts -->
<div id="content" class="span-24">
<div >
<h2>Receipt- Cheque Schedule List</h2>
<?php foreach ($accounts as $row){
$acc_name[ $row['id'] ] = $row['account_name'];
}?>
<hr>
<?php if(count($records) > 0) { ?>
<form autocomplete="off" class="myform" id="myForm" enctype="multipart/form-data" action="<?php echo base_url();?>journal/change_receipt_cheque_status" method="post" name="myForm">
<?php if($level==1){?><button class="" name="cancel">Cancel</button><?php }?>
<?php if($level==1){?><button class="" name="cleared">Cleared</button><?php }?>
<?php if($level==1){?><button class="" name="dishonered">Dishonered</button><br><?php }?>
<table class="gtable" align="center" id="gtable">
<thead>
<tr>
<th>Sl</th>
<th><input type="checkbox" class="checkall"></th>
<th>Cheque Date</th>
<th>Cheque#</th>
<th>Bank</th>
<th>Amount</th>
<th>Receipt From</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><input type="checkbox" name="id[]" value="<?php echo $row['cheque_id']; ?>"/></td>
<input type="hidden" name="cheque[]" value="<?php echo $row['cheque_number'];?>" >
<input type="hidden" name="cheque_date[]" value="<?php echo $row['cheque_date'];?>" >
<input type="hidden" name="bank_name[]" value="<?php echo $row['bank_name'];?>" >
<input type="hidden" name="amount[]" value="<?php echo $row['amount'];?>" >
<input type="hidden" name="cr_side[]" value="<?php echo $row['cr_side'];?>" >
<td><?php echo date("d-m-Y", strtotime($row['cheque_date']));?></td>
<td><?php echo $row['cheque_number'];?></td>
<td><?php echo $row['bank_name']; ?></td>
<td><?php echo number_format( $row['amount'], 2 ) ;?></td>
<td><?php echo $acc_name[$row['cr_side']];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php } ?>
</form>
</div>
</div>
<!-- End of Main Area/Content -->
<!-- Footer -->
<div id="footer" class="span-24">
<?php $this->load->view('includes/footer');?>
</div>
<!-- Footer Ends -->
</div><!-- Container Ends -->
</body>
</html> | mit |
mirakui/ec2ssh | lib/ec2ssh/ssh_config.rb | 2095 | require 'time'
require 'pathname'
module Ec2ssh
class SshConfig
HEADER = "### EC2SSH BEGIN ###"
FOOTER = "### EC2SSH END ###"
attr_reader :path, :sections
def initialize(path=nil)
@path = path || "#{ENV['HOME']}/.ssh/config"
@sections = {}
end
def parse!
return unless mark_exist?
ec2_config = config_src.match(/#{HEADER}\n(.*)#{FOOTER}/m).to_s
current_section = 'default'
@sections[current_section] = Section.new('default')
ec2_config.split(/\n+/).each do |line|
if line =~ /#{Section::HEADER} (.+)/
current_section = $1
@sections[current_section] ||= Section.new(current_section)
elsif line =~ /^#/ # ignore
elsif line =~ /^$/ # ignore
else
@sections[current_section].append("#{line}\n")
end
end
end
def append_mark!
replace! ""
File.open(@path, "a") do |f|
f.puts wrap("")
end
end
def mark_exist?
config_src =~ /#{HEADER}\n.*#{FOOTER}\n/m
end
def replace!(str)
save! config_src.gsub(/#{HEADER}\n.*#{FOOTER}\n/m, str)
end
def config_src
unless File.exist?(@path)
File.open(@path, "w", 0600).close()
end
@config_src ||= File.open(@path, "r") do |f|
f.read
end
end
def save!(str)
File.open(@path, "w") do |f|
f.puts str
end
end
def wrap(text)
return <<-END
#{HEADER}
# Generated by ec2ssh http://github.com/mirakui/ec2ssh
# DO NOT edit this block!
# Updated #{Time.now.iso8601}
#{text}
#{FOOTER}
END
end
class Section
HEADER = "# section:"
attr_accessor :name
attr_reader :text
def initialize(name, text = '')
@name = name
@text = text
end
def append(text)
@text << text
end
def replace!(text)
@text = text
end
def to_s
if text.empty?
""
else
<<-EOS
#{HEADER} #{@name}
#{@text}
EOS
end
end
end
end
end
| mit |
Menkachev/Software-University | Programing Basics - October 2016/04. Loops - November 12, 2016/02. Numbers Ending in 7/Properties/AssemblyInfo.cs | 1458 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02. Numbers Ending in 7")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. Numbers Ending in 7")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bc4b225c-5022-4f7b-b4e9-ea8f3afcf340")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
miclip/NJsonApiCore | src/NJsonApiCore/IRelationshipMapping.cs | 1851 |
using NJsonApi.Infrastructure;
using System;
using System.Reflection;
namespace NJsonApi
{
public interface IRelationshipMapping
{
string RelationshipName { get; set; }
Type ParentType { get; set; }
Type RelatedBaseType { get; set; }
string RelatedBaseResourceType { get; set; }
bool IsCollection { get; set; }
ResourceInclusionRules InclusionRule { get; set; }
IResourceMapping ResourceMapping { get; set; }
IPropertyHandle RelatedCollectionProperty { get; set; }
Func<object, object> RelatedResource { get; }
Func<object, object> RelatedResourceId { get; }
string ParentResourceNavigationPropertyName { get; }
Type ParentResourceNavigationPropertyType { get; }
}
public enum ResourceInclusionRules
{
/// <summary>
/// For to-one relationships, the related resource will be included unless it's reference is null and simultaneously it's ID is not null.
/// For to-many relationships, the related resources will be included only if the collection instance is not null.
/// Recommended rule.
/// </summary>
Smart,
/// <summary>
/// The related resource(s) will not be included.
/// Use if precisely controlling the returned object graph is inconvenient or impossible.
/// </summary>
ForceOmit,
/// <summary>
/// The related resource(s) will always be included.
/// With this option, the serializer assumes related instances are loaded correctly and any missing instance will result in null being serialized.
/// Not recommended for to-one relationships, since forgeting to load the related resource may lead to inconsistent link vs. resource linkage output.
/// </summary>
ForceInclude
}
} | mit |
zqzhang/iotivity-node | tests/tests/API Start Stack.js | 392 | var testUtils = require( "../assert-to-console" );
console.log( JSON.stringify( { assertionCount: 1 } ) );
require( "../../index" )().configure().then(
function() {
testUtils.assert( "ok", true, "Stack started successfully" );
process.exit( 0 );
},
function( error ) {
testUtils.assert( "ok", false, "Stack failed to start with code: " + error.result );
process.exit( 0 );
} );
| mit |
hakandilek/publicplay | app/views/html/helper/H.java | 4375 | package views.html.helper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import models.Post;
import models.User;
import org.ocpsoft.prettytime.PrettyTime;
import play.api.templates.Html;
import play.i18n.Lang;
import play.i18n.Messages;
import play.mvc.Http.Request;
import com.avaje.ebean.Page;
import scala.collection.mutable.StringBuilder;
/**
* HTML Utils
*
* @author hakan
*/
public class H {
private final static Map<String, PrettyTime> prettyTimes = new HashMap<String, PrettyTime>();
private final static PrettyTime prettyTimeDefault = new PrettyTime(Locale.ENGLISH);
private final static DateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
static {
prettyTimes.put(Locale.ENGLISH.getLanguage(), new PrettyTime(Locale.ENGLISH));
prettyTimes.put(new Locale("tr").getLanguage(), new PrettyTime(new Locale("tr")));
}
/**
* textual representation of the given object
*
* @param s
* object to display
* @return HTML output
*/
public static Html string(Object s) {
return new Html(new StringBuilder(s + ""));
}
/**
* prettifies the given date using Prettytime library
*
* @param d
* date to show
* @return HTML output
*/
public static Html prettify(Date d) {
if (d == null)
return new Html(new StringBuilder());
String language = getLang().language();
PrettyTime pt = prettyTimes.get(language);
if (pt == null)
pt = prettyTimeDefault;
String s = pt.format(d);
return new Html(new StringBuilder(s));
}
/**
* simplifies the given date using a simple format
*
* @param d
* date to show
* @return HTML output
*/
public static Html simplify(Date d) {
if (d == null)
return new Html(new StringBuilder());
String s = simpleDateFormat.format(d);
return new Html(new StringBuilder(s));
}
/**
* Sanitizes and replaces the given text to be used in an URL
*
* @param s
* url to sanitize
* @return sanitized URL
*/
public static String sanitizeURL(String s) {
if (s == null)
return "";
s = s.replaceAll("[\u00df]", "ss");
s = s.replaceAll("[\u00E4\u00C4]", "ae");
s = s.replaceAll("[\u011E\u011F]", "g");
s = s.replaceAll("[\u015E\u015F]", "s");
s = s.replaceAll("[\u00C7\u00E7]", "c");
s = s.replaceAll("[\u00F6\u00D6]", "o");
s = s.replaceAll("[\u00FC\u00DC]", "u");
s = s.replaceAll("[\u20AC]", "euro");
s = s.replaceAll("[\u0024]", "dollar");
s = s.replaceAll("[^A-Za-z0-9]", "_");
s = s.toLowerCase(Locale.ENGLISH);
return s;
}
public static <T> Html paging(Page<T> page) {
if (page == null)
return new Html(new StringBuilder());
Lang lang = getLang();
int pageIndex = page.getPageIndex() + 1;
int totalPage = page.getTotalPageCount();
return new Html(new StringBuilder(Messages.get(lang, "displaying_num_of_num_pages", pageIndex, totalPage)));
}
public static String getProfileImageURLWithNormalSize(User user) {
return user.getProfileImageURL() + "?type=normal";
}
public static String formatDateToDayAndYear(Date dateToFormat) {
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
return df.format(dateToFormat);
}
public static String subStringWithGivenLength(String stringToCut, int length) {
if (stringToCut.length() <= length) {
return stringToCut;
} else {
return stringToCut.substring(0, length);
}
}
public static String getKeywordsFromTopPage(Page<Post> topPostPage) {
String keyword = null;
for (Post post : topPostPage.getList()) {
keyword += post.getTitle() + " ";
}
keyword += Messages.get("Project_definition_keywords");
return subStringWithGivenLength(keyword.replace(" ", ","), 300);
}
private static Lang getLang() {
Lang lang = null;
if (play.mvc.Http.Context.current.get() != null) {
lang = play.mvc.Http.Context.Implicit.lang();
} else {
Locale defaultLocale = Locale.getDefault();
lang = new Lang(new play.api.i18n.Lang(defaultLocale.getLanguage(), defaultLocale.getCountry()));
}
return lang;
}
public static Html requestUrl() {
StringBuilder sb = new StringBuilder();
Request req = play.mvc.Http.Context.current().request();
if (req != null) {
sb.append("http://").append(req.host()).append(req.uri());
}
return new Html(sb);
}
}
| mit |
spierepf/mpf | mpf/devices/flipper.py | 10363 | """ Contains the base class for flippers."""
# flipper.py
# Mission Pinball Framework
# Written by Brian Madden & Gabe Knuth
# Released under the MIT License. (See license info at the end of this file.)
# Documentation and more info at http://missionpinball.com/mpf
from mpf.system.device import Device
class Flipper(Device):
"""Represents a flipper in a pinball machine. Subclass of Device.
Contains several methods for actions that can be performed on this flipper,
like :meth:`enable`, :meth:`disable`, etc.
Flippers have several options, including player buttons, EOS swtiches,
multiple coil options (pulsing, hold coils, etc.)
More details: http://missionpinball.com/docs/devices/flippers/
Args:
machine: A reference to the machine controller instance.
name: A string of the name you'll refer to this flipper object as.
config: A dictionary that holds the configuration values which specify
how this flipper should be configured. If this is None, it will use
the system config settings that were read in from the config files
when the machine was reset.
collection: A reference to the collection list this device will be added
to.
"""
config_section = 'flippers'
collection = 'flippers'
class_label = 'flipper'
def __init__(self, machine, name, config, collection=None, validate=True):
super(Flipper, self).__init__(machine, name, config, collection,
validate=validate)
# todo convert to dict
self.no_hold = False
self.strength = 100
self.inverted = False
self.rules = dict()
self.rules['a'] = False
self.rules['b'] = False
# self.rules['c'] = False
self.rules['d'] = False
self.rules['e'] = False
self.rules['h'] = False
self.flipper_coils = []
self.flipper_coils.append(self.config['main_coil'].name)
if self.config['hold_coil']:
self.flipper_coils.append(self.config['hold_coil'].name)
self.flipper_switches = []
self.flipper_switches.append(self.config['activation_switch'].name)
self.platform = self.config['main_coil'].platform
if self.debug:
self.log.debug('Platform Driver: %s', self.platform)
def enable(self, **kwargs):
"""Enables the flipper by writing the necessary hardware rules to the
hardware controller.
The hardware rules for coils can be kind of complex given all the
options, so we've mapped all the options out here. We literally have
methods to enable the various rules based on the rule letters here,
which we've implemented below. Keeps it easy to understand. :)
Note there's a platform feature saved at:
self.machine.config['platform']['hw_enable_auto_disable']. If True, it
means that the platform hardware rules will automatically disable a coil
that has been enabled when the trigger switch is disabled. If False, it
means the hardware platform needs its own rule to disable the coil when
the switch is disabled. Methods F and G below check for that feature
setting and will not be applied to the hardware if it's True.
Two coils, using EOS switch to indicate the end of the power stroke:
Rule Type Coil Switch Action
A. Enable Main Button active
D. Enable Hold Button active
E. Disable Main EOS active
One coil, using EOS switch
Rule Type Coil Switch Action
A. Enable Main Button active
H. PWM Main EOS active
Two coils, not using EOS switch:
Rule Type Coil Switch Action
B. Pulse Main Button active
D. Enable Hold Button active
One coil, not using EOS switch
Rule Type Coil Switch Action
C. Pulse/PWM Main button active
Use EOS switch for safety (for platforms that support mutiple switch
rules). Note that this rule is the letter "i", not a numeral 1.
I. Enable power if button is active and EOS is not active
"""
# todo disable first to clear any old rules?
self.log.debug('Enabling flipper with config: %s', self.config)
# Apply the proper hardware rules for our config
if not self.config['hold_coil']: # single coil
self._enable_single_coil_rule()
elif not self.config['use_eos']: # two coils, no eos
self._enable_main_coil_pulse_rule()
self._enable_hold_coil_rule()
elif self.config['use_eos']: # two coils, cutoff main on EOS
self._enable_main_coil_eos_cutoff_rule()
self._enable_hold_coil_rule()
# todo detect bad EOS and program around it
def enable_no_hold(self): # todo niy
"""Enables the flippers in 'no hold' mode.
No Hold is a novelty mode where the flippers to not stay up even when
the buttons are held in.
This mode is not yet implemented.
"""
self.no_hold = True
self.enable()
def enable_partial_power(self, percent): # todo niy
"""Enables flippers which operated at less than full power.
This is a novelty mode, like "weak flippers" from the Wizard of Oz.
Args:
percent: A floating point value between 0 and 1.0 which represents the
percentage of power the flippers will be enabled at.
This mode is not yet implemented.
"""
self.power = percent
self.enable()
def disable(self, **kwargs):
"""Disables the flipper.
This method makes it so the cabinet flipper buttons no longer control
the flippers. Used when no game is active and when the player has
tilted.
"""
if self.flipper_switches:
self.log.debug("Disabling")
for switch in self.flipper_switches:
self.platform.clear_hw_rule(switch)
def _enable_single_coil_rule(self):
self.log.debug('Enabling single coil rule')
self.platform.set_hw_rule(
sw_name=self.config['activation_switch'].name,
sw_activity=1,
driver_name=self.config['main_coil'].name,
driver_action='hold',
disable_on_release=True,
**self.config)
self.rules['a'] = True
def _enable_main_coil_pulse_rule(self):
self.log.debug('Enabling main coil pulse rule')
self.platform.set_hw_rule(
sw_name=self.config['activation_switch'].name,
sw_activity=1,
driver_name=self.config['main_coil'].name,
driver_action='pulse',
disable_on_release=True,
**self.config)
self.rules['b'] = True
def _enable_hold_coil_rule(self):
self.log.debug('Enabling hold coil rule')
self.platform.set_hw_rule(
sw_name=self.config['activation_switch'].name,
sw_activity=1,
driver_name=self.config['hold_coil'].name,
driver_action='hold',
disable_on_release=True,
**self.config)
self.rules['d'] = True
def _enable_main_coil_eos_cutoff_rule(self):
self.log.debug('Enabling main coil EOS cutoff rule')
self.platform.set_hw_rule(
sw_name=self.config['eos_switch'],
sw_activity=1,
driver_name=self.config['main_coil'].name,
driver_action='disable',
**self.config)
self.rules['e'] = True
def sw_flip(self):
"""Activates the flipper via software as if the flipper button was
pushed.
This is needed because the real flipper activations are handled in
hardware, so if you want to flip the flippers with the keyboard or OSC
interfaces, you have to call this method.
Note this method will keep this flipper enabled until you call
sw_release().
"""
# todo add support for other types of flipper coils
# Send the activation switch press to the switch controller
self.machine.switch_controller.process_switch(
name=self.config['activation_switch'].name,
state=1,
logical=True)
if self.rules['c']: # pulse/pwm main
coil = self.config['main_coil'].config
coil.pwm(
on_ms=coil.config['pwm_on'],
off_ms=coil.config['pwm_off'],
orig_on_ms=coil.config['pulse_ms']
)
def sw_release(self):
"""Deactives the flipper via software as if the flipper button was
released. See the documentation for sw_flip() for details.
"""
# Send the activation switch release to the switch controller
self.machine.switch_controller.process_switch(
name=self.config['activation_switch'].name,
state=0,
logical=True)
# disable the flipper coil(s)
for coil in self.flipper_coils:
coil.disable()
# The MIT License (MIT)
# Copyright (c) 2013-2015 Brian Madden and Gabe Knuth
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
| mit |
phani00/tovp | tovp/attachments/forms.py | 633 | from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from attachments.models import Attachment
class AttachmentForm(forms.ModelForm):
attachment_file = forms.FileField(label=_('Upload attachment'))
class Meta:
model = Attachment
fields = ('attachment_type', 'attachment_file', 'description')
def save(self, request, obj, *args, **kwargs):
self.instance.content_type = ContentType.objects.get_for_model(obj)
self.instance.object_id = obj.id
super(AttachmentForm, self).save(*args, **kwargs)
| mit |
tv42/webut | webut/navi/inavi.py | 2173 | from zope.interface import Interface, Attribute
from twisted import plugin
class INavigable(Interface):
"""
A navigable resource.
Normally, an INavigable should also implement IResource.
The biggest requirement for navigability is the ability
to list the child resources.
"""
def listChildren(ctx):
"""
List children.
Note that you are given no guarantees that locateChild will be
able to find all these children, and vice versa locateChild
may find children not listed here. See getChildren for that.
@return: a Deferred list names of the children.
"""
def getChildren(ctx):
"""
Get children.
Note that you are given no guarantees that a locateChild ran
at a later time will be able to find all these children, and
vice versa locateChild may find children not listed here. But
as they are returned at the same time, the results are valid
*right now*.
@return: a Deferred list of tuples [ (name, IResource), ... ]
"""
def locateChild(ctx, segments):
"""
See C{nevow.inevow.IResource.locateChild}.
"""
class INavigationPlugin(plugin.IPlugin):
"""
A twisted plugin to be loaded as part of the resource tree.
To have plugins on multiple levels, use subclasses to categorize
the plugins.
"""
name = Attribute("""
Path segment where to place this plugin.
This is a single segment, relative to whatever parent loaded the
plugin.
""")
def getResource(ctx):
"""
Returns an Deferred that will result in IResource or None.
IResources may additionally have attributes
title and description.
"""
pass
# optional
priority = Attribute("""
Priority for sorting plugins in navigation.
Defaults to 50.
""")
class INavigationElement(Interface):
title = Attribute("""
Title of the element, for use in links and such. At most a few words.
""")
description = Attribute("""
Short description of the element, for tooltips etc. About one sentence.
""")
| mit |
BenaroyaResearch/bripipetools | bripipetools/postprocessing/cleanup.py | 3906 | """
Clean up & organize outputs from processing workflow batch.
"""
import logging
import os
import re
import zipfile
import shutil
logger = logging.getLogger(__name__)
class OutputCleaner(object):
"""
Moves, renames, and deletes individual output files from a workflow
processing batch for a selected project.
"""
def __init__(self, path):
logger.debug("creating `OutputCleaner` instance for '{}'".format(path))
self.path = path
self.output_types = self._get_output_types()
def _get_output_types(self):
"""
Identify the types of outputs included for the project.
"""
out_types = ['qc', 'metrics', 'counts', 'alignments', 'logs']
logging.debug("subfolders in project folder: {}"
.format(os.listdir(self.path)))
return [f for f in os.listdir(self.path)
if f.lower() in out_types]
def _get_output_paths(self, output_type):
"""
Return full path for individual output files.
"""
logging.debug("locating output files of type '{}'".format(output_type))
output_root = os.path.join(self.path, output_type)
return [os.path.join(self.path, root, f)
for root, dirs, files in os.walk(output_root)
for f in files
if not re.search('(DS_Store|_old)', f)]
def _unzip_output(self, path):
"""
Unzip the contents of a compressed output file.
"""
logging.debug("extracting contents of '{}' to '{}'"
.format(path, os.path.dirname(path)))
paths = []
with zipfile.ZipFile(path) as zf:
logger.debug("zip folder contents: {}".format(zf.namelist()))
for f in zf.namelist():
if f != './':
paths.append(zf.extract(f, os.path.dirname(path)))
logging.debug("unzipped the following files: {}".format(paths))
return paths
def _unnest_output(self, path):
"""
Unnest files in a subfolder by concatenating filenames and
moving up one level.
"""
logging.debug("unnesting output '{}' from subfolder '{}'"
.format(path, os.path.dirname(path)))
prefix = os.path.dirname(path)
if re.search('.zip$', path):
logging.debug("unzipping contents of '{}' before unnesting"
.format(path))
for p in self._unzip_output(path):
shutil.move(p, '{}_{}'.format(prefix, os.path.basename(p)))
try:
shutil.rmtree(os.path.splitext(path)[0])
except OSError:
pass
else:
shutil.move(path, '{}_{}'.format(prefix, os.path.basename(path)))
def _recode_output(self, path, output_type):
"""
Rename file according to template.
"""
filename_map = {'QC': ('fastqc_data.txt', 'fastqc_qc.txt')}
swap = filename_map[output_type]
newpath = re.sub(swap[0], swap[1], path)
logging.debug("renaming '{}' to '{}'".format(path, newpath))
shutil.move(path, newpath)
return newpath
def clean_outputs(self):
"""
Walk through output types to unzip, unnest, and rename files.
"""
for output_type in self.output_types:
if output_type == 'QC':
outputs = self._get_output_paths(output_type)
for o in outputs:
outregex = re.compile(output_type + '$')
if not outregex.search(os.path.dirname(o)):
self._unnest_output(o)
for o in os.listdir(os.path.join(self.path, output_type)):
self._recode_output(
os.path.join(self.path, output_type, o),
output_type
)
| mit |
RichardHowells/Dnn.Platform | DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs | 55912 | #region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using log4net.Util;
using log4net.Core;
using System.Threading;
namespace log4net.Appender
{
#if CONFIRM_WIN32_FILE_SHAREMODES
// The following sounds good, and I though it was the case, but after
// further testing on Windows I have not been able to confirm it.
/// On the Windows platform if another process has a write lock on the file
/// that is to be deleted, but allows shared read access to the file then the
/// file can be moved, but cannot be deleted. If the other process also allows
/// shared delete access to the file then the file will be deleted once that
/// process closes the file. If it is necessary to open the log file or any
/// of the backup files outside of this appender for either read or
/// write access please ensure that read and delete share modes are enabled.
#endif
/// <summary>
/// Appender that rolls log files based on size or date or both.
/// </summary>
/// <remarks>
/// <para>
/// RollingFileAppender can roll log files based on size or date or both
/// depending on the setting of the <see cref="RollingStyle"/> property.
/// When set to <see cref="RollingMode.Size"/> the log file will be rolled
/// once its size exceeds the <see cref="MaximumFileSize"/>.
/// When set to <see cref="RollingMode.Date"/> the log file will be rolled
/// once the date boundary specified in the <see cref="DatePattern"/> property
/// is crossed.
/// When set to <see cref="RollingMode.Composite"/> the log file will be
/// rolled once the date boundary specified in the <see cref="DatePattern"/> property
/// is crossed, but within a date boundary the file will also be rolled
/// once its size exceeds the <see cref="MaximumFileSize"/>.
/// When set to <see cref="RollingMode.Once"/> the log file will be rolled when
/// the appender is configured. This effectively means that the log file can be
/// rolled once per program execution.
/// </para>
/// <para>
/// A of few additional optional features have been added:
/// <list type="bullet">
/// <item>Attach date pattern for current log file <see cref="StaticLogFileName"/></item>
/// <item>Backup number increments for newer files <see cref="CountDirection"/></item>
/// <item>Infinite number of backups by file size <see cref="MaxSizeRollBackups"/></item>
/// </list>
/// </para>
///
/// <note>
/// <para>
/// For large or infinite numbers of backup files a <see cref="CountDirection"/>
/// greater than zero is highly recommended, otherwise all the backup files need
/// to be renamed each time a new backup is created.
/// </para>
/// <para>
/// When Date/Time based rolling is used setting <see cref="StaticLogFileName"/>
/// to <see langword="true"/> will reduce the number of file renamings to few or none.
/// </para>
/// </note>
///
/// <note type="caution">
/// <para>
/// Changing <see cref="StaticLogFileName"/> or <see cref="CountDirection"/> without clearing
/// the log file directory of backup files will cause unexpected and unwanted side effects.
/// </para>
/// </note>
///
/// <para>
/// If Date/Time based rolling is enabled this appender will attempt to roll existing files
/// in the directory without a Date/Time tag based on the last write date of the base log file.
/// The appender only rolls the log file when a message is logged. If Date/Time based rolling
/// is enabled then the appender will not roll the log file at the Date/Time boundary but
/// at the point when the next message is logged after the boundary has been crossed.
/// </para>
///
/// <para>
/// The <see cref="RollingFileAppender"/> extends the <see cref="FileAppender"/> and
/// has the same behavior when opening the log file.
/// The appender will first try to open the file for writing when <see cref="ActivateOptions"/>
/// is called. This will typically be during configuration.
/// If the file cannot be opened for writing the appender will attempt
/// to open the file again each time a message is logged to the appender.
/// If the file cannot be opened for writing when a message is logged then
/// the message will be discarded by this appender.
/// </para>
/// <para>
/// When rolling a backup file necessitates deleting an older backup file the
/// file to be deleted is moved to a temporary name before being deleted.
/// </para>
///
/// <note type="caution">
/// <para>
/// A maximum number of backup files when rolling on date/time boundaries is not supported.
/// </para>
/// </note>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Aspi Havewala</author>
/// <author>Douglas de la Torre</author>
/// <author>Edward Smit</author>
public class RollingFileAppender : FileAppender
{
#region Public Enums
/// <summary>
/// Style of rolling to use
/// </summary>
/// <remarks>
/// <para>
/// Style of rolling to use
/// </para>
/// </remarks>
public enum RollingMode
{
/// <summary>
/// Roll files once per program execution
/// </summary>
/// <remarks>
/// <para>
/// Roll files once per program execution.
/// Well really once each time this appender is
/// configured.
/// </para>
/// <para>
/// Setting this option also sets <c>AppendToFile</c> to
/// <c>false</c> on the <c>RollingFileAppender</c>, otherwise
/// this appender would just be a normal file appender.
/// </para>
/// </remarks>
Once = 0,
/// <summary>
/// Roll files based only on the size of the file
/// </summary>
Size = 1,
/// <summary>
/// Roll files based only on the date
/// </summary>
Date = 2,
/// <summary>
/// Roll files based on both the size and date of the file
/// </summary>
Composite = 3
}
#endregion
#region Protected Enums
/// <summary>
/// The code assumes that the following 'time' constants are in a increasing sequence.
/// </summary>
/// <remarks>
/// <para>
/// The code assumes that the following 'time' constants are in a increasing sequence.
/// </para>
/// </remarks>
protected enum RollPoint
{
/// <summary>
/// Roll the log not based on the date
/// </summary>
InvalidRollPoint =-1,
/// <summary>
/// Roll the log for each minute
/// </summary>
TopOfMinute = 0,
/// <summary>
/// Roll the log for each hour
/// </summary>
TopOfHour = 1,
/// <summary>
/// Roll the log twice a day (midday and midnight)
/// </summary>
HalfDay = 2,
/// <summary>
/// Roll the log each day (midnight)
/// </summary>
TopOfDay = 3,
/// <summary>
/// Roll the log each week
/// </summary>
TopOfWeek = 4,
/// <summary>
/// Roll the log each month
/// </summary>
TopOfMonth = 5
}
#endregion Protected Enums
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RollingFileAppender" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Default constructor.
/// </para>
/// </remarks>
public RollingFileAppender()
{
}
/// <summary>
/// Cleans up all resources used by this appender.
/// </summary>
~RollingFileAppender()
{
#if !NETCF
if (m_mutexForRolling != null)
{
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
m_mutexForRolling.Dispose();
#else
m_mutexForRolling.Close();
#endif
m_mutexForRolling = null;
}
#endif
}
#endregion Public Instance Constructors
#region Public Instance Properties
#if !NET_1_0 && !CLI_1_0 && !NETCF
/// <summary>
/// Gets or sets the strategy for determining the current date and time. The default
/// implementation is to use LocalDateTime which internally calls through to DateTime.Now.
/// DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying
/// <see cref="RollingFileAppender.UniversalDateTime"/>.
/// </summary>
/// <value>
/// An implementation of the <see cref="RollingFileAppender.IDateTime"/> interface which returns the current date and time.
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the <see cref="RollingFileAppender.IDateTime"/> used to return the current date and time.
/// </para>
/// <para>
/// There are two built strategies for determining the current date and time,
/// <see cref="RollingFileAppender.LocalDateTime"/>
/// and <see cref="RollingFileAppender.UniversalDateTime"/>.
/// </para>
/// <para>
/// The default strategy is <see cref="RollingFileAppender.LocalDateTime"/>.
/// </para>
/// </remarks>
#else
/// <summary>
/// Gets or sets the strategy for determining the current date and time. The default
/// implementation is to use LocalDateTime which internally calls through to DateTime.Now.
/// </summary>
/// <value>
/// An implementation of the <see cref="RollingFileAppender.IDateTime"/> interface which returns the current date and time.
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the <see cref="RollingFileAppender.IDateTime"/> used to return the current date and time.
/// </para>
/// <para>
/// The default strategy is <see cref="RollingFileAppender.LocalDateTime"/>.
/// </para>
/// </remarks>
#endif
public IDateTime DateTimeStrategy
{
get { return m_dateTime; }
set { m_dateTime = value; }
}
/// <summary>
/// Gets or sets the date pattern to be used for generating file names
/// when rolling over on date.
/// </summary>
/// <value>
/// The date pattern to be used for generating file names when rolling
/// over on date.
/// </value>
/// <remarks>
/// <para>
/// Takes a string in the same format as expected by
/// <see cref="log4net.DateFormatter.SimpleDateFormatter" />.
/// </para>
/// <para>
/// This property determines the rollover schedule when rolling over
/// on date.
/// </para>
/// </remarks>
public string DatePattern
{
get { return m_datePattern; }
set { m_datePattern = value; }
}
/// <summary>
/// Gets or sets the maximum number of backup files that are kept before
/// the oldest is erased.
/// </summary>
/// <value>
/// The maximum number of backup files that are kept before the oldest is
/// erased.
/// </value>
/// <remarks>
/// <para>
/// If set to zero, then there will be no backup files and the log file
/// will be truncated when it reaches <see cref="MaxFileSize"/>.
/// </para>
/// <para>
/// If a negative number is supplied then no deletions will be made. Note
/// that this could result in very slow performance as a large number of
/// files are rolled over unless <see cref="CountDirection"/> is used.
/// </para>
/// <para>
/// The maximum applies to <b>each</b> time based group of files and
/// <b>not</b> the total.
/// </para>
/// </remarks>
public int MaxSizeRollBackups
{
get { return m_maxSizeRollBackups; }
set { m_maxSizeRollBackups = value; }
}
/// <summary>
/// Gets or sets the maximum size that the output file is allowed to reach
/// before being rolled over to backup files.
/// </summary>
/// <value>
/// The maximum size in bytes that the output file is allowed to reach before being
/// rolled over to backup files.
/// </value>
/// <remarks>
/// <para>
/// This property is equivalent to <see cref="MaximumFileSize"/> except
/// that it is required for differentiating the setter taking a
/// <see cref="long"/> argument from the setter taking a <see cref="string"/>
/// argument.
/// </para>
/// <para>
/// The default maximum file size is 10MB (10*1024*1024).
/// </para>
/// </remarks>
public long MaxFileSize
{
get { return m_maxFileSize; }
set { m_maxFileSize = value; }
}
/// <summary>
/// Gets or sets the maximum size that the output file is allowed to reach
/// before being rolled over to backup files.
/// </summary>
/// <value>
/// The maximum size that the output file is allowed to reach before being
/// rolled over to backup files.
/// </value>
/// <remarks>
/// <para>
/// This property allows you to specify the maximum size with the
/// suffixes "KB", "MB" or "GB" so that the size is interpreted being
/// expressed respectively in kilobytes, megabytes or gigabytes.
/// </para>
/// <para>
/// For example, the value "10KB" will be interpreted as 10240 bytes.
/// </para>
/// <para>
/// The default maximum file size is 10MB.
/// </para>
/// <para>
/// If you have the option to set the maximum file size programmatically
/// consider using the <see cref="MaxFileSize"/> property instead as this
/// allows you to set the size in bytes as a <see cref="Int64"/>.
/// </para>
/// </remarks>
public string MaximumFileSize
{
get { return m_maxFileSize.ToString(NumberFormatInfo.InvariantInfo); }
set { m_maxFileSize = OptionConverter.ToFileSize(value, m_maxFileSize + 1); }
}
/// <summary>
/// Gets or sets the rolling file count direction.
/// </summary>
/// <value>
/// The rolling file count direction.
/// </value>
/// <remarks>
/// <para>
/// Indicates if the current file is the lowest numbered file or the
/// highest numbered file.
/// </para>
/// <para>
/// By default newer files have lower numbers (<see cref="CountDirection" /> < 0),
/// i.e. log.1 is most recent, log.5 is the 5th backup, etc...
/// </para>
/// <para>
/// <see cref="CountDirection" /> >= 0 does the opposite i.e.
/// log.1 is the first backup made, log.5 is the 5th backup made, etc.
/// For infinite backups use <see cref="CountDirection" /> >= 0 to reduce
/// rollover costs.
/// </para>
/// <para>The default file count direction is -1.</para>
/// </remarks>
public int CountDirection
{
get { return m_countDirection; }
set { m_countDirection = value; }
}
/// <summary>
/// Gets or sets the rolling style.
/// </summary>
/// <value>The rolling style.</value>
/// <remarks>
/// <para>
/// The default rolling style is <see cref="RollingMode.Composite" />.
/// </para>
/// <para>
/// When set to <see cref="RollingMode.Once"/> this appender's
/// <see cref="FileAppender.AppendToFile"/> property is set to <c>false</c>, otherwise
/// the appender would append to a single file rather than rolling
/// the file each time it is opened.
/// </para>
/// </remarks>
public RollingMode RollingStyle
{
get { return m_rollingStyle; }
set
{
m_rollingStyle = value;
switch (m_rollingStyle)
{
case RollingMode.Once:
m_rollDate = false;
m_rollSize = false;
this.AppendToFile = false;
break;
case RollingMode.Size:
m_rollDate = false;
m_rollSize = true;
break;
case RollingMode.Date:
m_rollDate = true;
m_rollSize = false;
break;
case RollingMode.Composite:
m_rollDate = true;
m_rollSize = true;
break;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether to preserve the file name extension when rolling.
/// </summary>
/// <value>
/// <c>true</c> if the file name extension should be preserved.
/// </value>
/// <remarks>
/// <para>
/// By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup.
/// However, under Windows the new file name will loose any program associations as the
/// extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or
/// file.curSizeRollBackup.log to maintain any program associations.
/// </para>
/// </remarks>
public bool PreserveLogFileNameExtension
{
get { return m_preserveLogFileNameExtension; }
set { m_preserveLogFileNameExtension = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to always log to
/// the same file.
/// </summary>
/// <value>
/// <c>true</c> if always should be logged to the same file, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// By default file.log is always the current file. Optionally
/// file.log.yyyy-mm-dd for current formatted datePattern can by the currently
/// logging file (or file.log.curSizeRollBackup or even
/// file.log.yyyy-mm-dd.curSizeRollBackup).
/// </para>
/// <para>
/// This will make time based rollovers with a large number of backups
/// much faster as the appender it won't have to rename all the backups!
/// </para>
/// </remarks>
public bool StaticLogFileName
{
get { return m_staticLogFileName; }
set { m_staticLogFileName = value; }
}
#endregion Public Instance Properties
#region Private Static Fields
/// <summary>
/// The fully qualified type of the RollingFileAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(RollingFileAppender);
#endregion Private Static Fields
#region Override implementation of FileAppender
/// <summary>
/// Sets the quiet writer being used.
/// </summary>
/// <remarks>
/// This method can be overridden by sub classes.
/// </remarks>
/// <param name="writer">the writer to set</param>
override protected void SetQWForFiles(TextWriter writer)
{
QuietWriter = new CountingQuietTextWriter(writer, ErrorHandler);
}
/// <summary>
/// Write out a logging event.
/// </summary>
/// <param name="loggingEvent">the event to write to file.</param>
/// <remarks>
/// <para>
/// Handles append time behavior for RollingFileAppender. This checks
/// if a roll over either by date (checked first) or time (checked second)
/// is need and then appends to the file last.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
AdjustFileBeforeAppend();
base.Append(loggingEvent);
}
/// <summary>
/// Write out an array of logging events.
/// </summary>
/// <param name="loggingEvents">the events to write to file.</param>
/// <remarks>
/// <para>
/// Handles append time behavior for RollingFileAppender. This checks
/// if a roll over either by date (checked first) or time (checked second)
/// is need and then appends to the file last.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent[] loggingEvents)
{
AdjustFileBeforeAppend();
base.Append(loggingEvents);
}
/// <summary>
/// Performs any required rolling before outputting the next event
/// </summary>
/// <remarks>
/// <para>
/// Handles append time behavior for RollingFileAppender. This checks
/// if a roll over either by date (checked first) or time (checked second)
/// is need and then appends to the file last.
/// </para>
/// </remarks>
virtual protected void AdjustFileBeforeAppend()
{
// reuse the file appenders locking model to lock the rolling
#if !NETCF
try
{
// if rolling should be locked, acquire the lock
if (m_mutexForRolling != null)
{
m_mutexForRolling.WaitOne();
}
#endif
if (m_rollDate)
{
DateTime n = m_dateTime.Now;
if (n >= m_nextCheck)
{
m_now = n;
m_nextCheck = NextCheckDate(m_now, m_rollPoint);
RollOverTime(true);
}
}
if (m_rollSize)
{
if ((File != null) && ((CountingQuietTextWriter)QuietWriter).Count >= m_maxFileSize)
{
RollOverSize();
}
}
#if !NETCF
}
finally
{
// if rolling should be locked, release the lock
if (m_mutexForRolling != null)
{
m_mutexForRolling.ReleaseMutex();
}
}
#endif
}
/// <summary>
/// Creates and opens the file for logging. If <see cref="StaticLogFileName"/>
/// is false then the fully qualified name is determined and used.
/// </summary>
/// <param name="fileName">the name of the file to open</param>
/// <param name="append">true to append to existing file</param>
/// <remarks>
/// <para>This method will ensure that the directory structure
/// for the <paramref name="fileName"/> specified exists.</para>
/// </remarks>
override protected void OpenFile(string fileName, bool append)
{
lock(this)
{
fileName = GetNextOutputFileName(fileName);
// Calculate the current size of the file
long currentCount = 0;
if (append)
{
using(SecurityContext.Impersonate(this))
{
if (System.IO.File.Exists(fileName))
{
currentCount = (new FileInfo(fileName)).Length;
}
}
}
else
{
if (LogLog.IsErrorEnabled)
{
// Internal check that the file is not being overwritten
// If not Appending to an existing file we should have rolled the file out of the
// way. Therefore we should not be over-writing an existing file.
// The only exception is if we are not allowed to roll the existing file away.
if (m_maxSizeRollBackups != 0 && FileExists(fileName))
{
LogLog.Error(declaringType, "RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile ["+fileName+"] already exists.");
}
}
}
if (!m_staticLogFileName)
{
m_scheduledFilename = fileName;
}
// Open the file (call the base class to do it)
base.OpenFile(fileName, append);
// Set the file size onto the counting writer
((CountingQuietTextWriter)QuietWriter).Count = currentCount;
}
}
/// <summary>
/// Get the current output file name
/// </summary>
/// <param name="fileName">the base file name</param>
/// <returns>the output file name</returns>
/// <remarks>
/// The output file name is based on the base fileName specified.
/// If <see cref="StaticLogFileName"/> is set then the output
/// file name is the same as the base file passed in. Otherwise
/// the output file depends on the date pattern, on the count
/// direction or both.
/// </remarks>
protected string GetNextOutputFileName(string fileName)
{
if (!m_staticLogFileName)
{
fileName = fileName.Trim();
if (m_rollDate)
{
fileName = CombinePath(fileName, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo));
}
if (m_countDirection >= 0)
{
fileName = CombinePath(fileName, "." + m_curSizeRollBackups);
}
}
return fileName;
}
#endregion
#region Initialize Options
/// <summary>
/// Determines curSizeRollBackups (only within the current roll point)
/// </summary>
private void DetermineCurSizeRollBackups()
{
m_curSizeRollBackups = 0;
string fullPath = null;
string fileName = null;
using(SecurityContext.Impersonate(this))
{
fullPath = System.IO.Path.GetFullPath(m_baseFileName);
fileName = System.IO.Path.GetFileName(fullPath);
}
ArrayList arrayFiles = GetExistingFiles(fullPath);
InitializeRollBackups(fileName, arrayFiles);
LogLog.Debug(declaringType, "curSizeRollBackups starts at ["+m_curSizeRollBackups+"]");
}
/// <summary>
/// Generates a wildcard pattern that can be used to find all files
/// that are similar to the base file name.
/// </summary>
/// <param name="baseFileName"></param>
/// <returns></returns>
private string GetWildcardPatternForFile(string baseFileName)
{
if (m_preserveLogFileNameExtension)
{
return Path.GetFileNameWithoutExtension(baseFileName) + "*" + Path.GetExtension(baseFileName);
}
else
{
return baseFileName + '*';
}
}
/// <summary>
/// Builds a list of filenames for all files matching the base filename plus a file
/// pattern.
/// </summary>
/// <param name="baseFilePath"></param>
/// <returns></returns>
private ArrayList GetExistingFiles(string baseFilePath)
{
ArrayList alFiles = new ArrayList();
string directory = null;
using(SecurityContext.Impersonate(this))
{
string fullPath = Path.GetFullPath(baseFilePath);
directory = Path.GetDirectoryName(fullPath);
if (Directory.Exists(directory))
{
string baseFileName = Path.GetFileName(fullPath);
string[] files = Directory.GetFiles(directory, GetWildcardPatternForFile(baseFileName));
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
string curFileName = Path.GetFileName(files[i]);
if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFileName)))
{
alFiles.Add(curFileName);
}
}
}
}
}
LogLog.Debug(declaringType, "Searched for existing files in ["+directory+"]");
return alFiles;
}
/// <summary>
/// Initiates a roll over if needed for crossing a date boundary since the last run.
/// </summary>
private void RollOverIfDateBoundaryCrossing()
{
if (m_staticLogFileName && m_rollDate)
{
if (FileExists(m_baseFileName))
{
DateTime last;
using(SecurityContext.Impersonate(this)) {
#if !NET_1_0 && !CLI_1_0 && !NETCF
if (DateTimeStrategy is UniversalDateTime)
{
last = System.IO.File.GetLastWriteTimeUtc(m_baseFileName);
}
else
{
#endif
last = System.IO.File.GetLastWriteTime(m_baseFileName);
#if !NET_1_0 && !CLI_1_0 && !NETCF
}
#endif
}
LogLog.Debug(declaringType, "["+last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"] vs. ["+m_now.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"]");
if (!(last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))))
{
m_scheduledFilename = CombinePath(m_baseFileName, last.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo));
LogLog.Debug(declaringType, "Initial roll over to ["+m_scheduledFilename+"]");
RollOverTime(false);
LogLog.Debug(declaringType, "curSizeRollBackups after rollOver at ["+m_curSizeRollBackups+"]");
}
}
}
}
/// <summary>
/// Initializes based on existing conditions at time of <see cref="ActivateOptions"/>.
/// </summary>
/// <remarks>
/// <para>
/// Initializes based on existing conditions at time of <see cref="ActivateOptions"/>.
/// The following is done
/// <list type="bullet">
/// <item>determine curSizeRollBackups (only within the current roll point)</item>
/// <item>initiates a roll over if needed for crossing a date boundary since the last run.</item>
/// </list>
/// </para>
/// </remarks>
protected void ExistingInit()
{
DetermineCurSizeRollBackups();
RollOverIfDateBoundaryCrossing();
// If file exists and we are not appending then roll it out of the way
if (AppendToFile == false)
{
bool fileExists = false;
string fileName = GetNextOutputFileName(m_baseFileName);
using(SecurityContext.Impersonate(this))
{
fileExists = System.IO.File.Exists(fileName);
}
if (fileExists)
{
if (m_maxSizeRollBackups == 0)
{
LogLog.Debug(declaringType, "Output file ["+fileName+"] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file.");
}
else
{
LogLog.Debug(declaringType, "Output file ["+fileName+"] already exists. Not appending to file. Rolling existing file out of the way.");
RollOverRenameFiles(fileName);
}
}
}
}
/// <summary>
/// Does the work of bumping the 'current' file counter higher
/// to the highest count when an incremental file name is seen.
/// The highest count is either the first file (when count direction
/// is greater than 0) or the last file (when count direction less than 0).
/// In either case, we want to know the highest count that is present.
/// </summary>
/// <param name="baseFile"></param>
/// <param name="curFileName"></param>
private void InitializeFromOneFile(string baseFile, string curFileName)
{
if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFile)) == false)
{
// This is not a log file, so ignore
return;
}
if (curFileName.Equals(baseFile))
{
// Base log file is not an incremented logfile (.1 or .2, etc)
return;
}
// Only look for files in the current roll point
if (m_rollDate && !m_staticLogFileName)
{
string date = m_dateTime.Now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
string prefix = m_preserveLogFileNameExtension ? Path.GetFileNameWithoutExtension(baseFile) + date : baseFile + date;
string suffix = m_preserveLogFileNameExtension ? Path.GetExtension(baseFile) : "";
if (!curFileName.StartsWith(prefix) || !curFileName.EndsWith(suffix))
{
LogLog.Debug(declaringType, "Ignoring file ["+curFileName+"] because it is from a different date period");
return;
}
}
try
{
// Bump the counter up to the highest count seen so far
int backup = GetBackUpIndex(curFileName);
// caution: we might get a false positive when certain
// date patterns such as yyyyMMdd are used...those are
// valid number but aren't the kind of back up index
// we're looking for
if (backup > m_curSizeRollBackups)
{
if (0 == m_maxSizeRollBackups)
{
// Stay at zero when zero backups are desired
}
else if (-1 == m_maxSizeRollBackups)
{
// Infinite backups, so go as high as the highest value
m_curSizeRollBackups = backup;
}
else
{
// Backups limited to a finite number
if (m_countDirection >= 0)
{
// Go with the highest file when counting up
m_curSizeRollBackups = backup;
}
else
{
// Clip to the limit when counting down
if (backup <= m_maxSizeRollBackups)
{
m_curSizeRollBackups = backup;
}
}
}
LogLog.Debug(declaringType, "File name [" + curFileName + "] moves current count to [" + m_curSizeRollBackups + "]");
}
}
catch(FormatException)
{
// This happens when file.log -> file.log.yyyy-MM-dd which is normal
// when staticLogFileName == false
LogLog.Debug(declaringType, "Encountered a backup file not ending in .x ["+curFileName+"]");
}
}
/// <summary>
/// Attempts to extract a number from the end of the file name that indicates
/// the number of the times the file has been rolled over.
/// </summary>
/// <remarks>
/// Certain date pattern extensions like yyyyMMdd will be parsed as valid backup indexes.
/// </remarks>
/// <param name="curFileName"></param>
/// <returns></returns>
private int GetBackUpIndex(string curFileName)
{
int backUpIndex = -1;
string fileName = curFileName;
if (m_preserveLogFileNameExtension)
{
fileName = Path.GetFileNameWithoutExtension(fileName);
}
int index = fileName.LastIndexOf(".");
if (index > 0)
{
// if the "yyyy-MM-dd" component of file.log.yyyy-MM-dd is passed to TryParse
// it will gracefully fail and return backUpIndex will be 0
SystemInfo.TryParse(fileName.Substring(index + 1), out backUpIndex);
}
return backUpIndex;
}
/// <summary>
/// Takes a list of files and a base file name, and looks for
/// 'incremented' versions of the base file. Bumps the max
/// count up to the highest count seen.
/// </summary>
/// <param name="baseFile"></param>
/// <param name="arrayFiles"></param>
private void InitializeRollBackups(string baseFile, ArrayList arrayFiles)
{
if (null != arrayFiles)
{
string baseFileLower = baseFile.ToLower(System.Globalization.CultureInfo.InvariantCulture);
foreach(string curFileName in arrayFiles)
{
InitializeFromOneFile(baseFileLower, curFileName.ToLower(System.Globalization.CultureInfo.InvariantCulture));
}
}
}
/// <summary>
/// Calculates the RollPoint for the datePattern supplied.
/// </summary>
/// <param name="datePattern">the date pattern to calculate the check period for</param>
/// <returns>The RollPoint that is most accurate for the date pattern supplied</returns>
/// <remarks>
/// Essentially the date pattern is examined to determine what the
/// most suitable roll point is. The roll point chosen is the roll point
/// with the smallest period that can be detected using the date pattern
/// supplied. i.e. if the date pattern only outputs the year, month, day
/// and hour then the smallest roll point that can be detected would be
/// and hourly roll point as minutes could not be detected.
/// </remarks>
private RollPoint ComputeCheckPeriod(string datePattern)
{
// s_date1970 is 1970-01-01 00:00:00 this is UniversalSortableDateTimePattern
// (based on ISO 8601) using universal time. This date is used for reference
// purposes to calculate the resolution of the date pattern.
// Get string representation of base line date
string r0 = s_date1970.ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
// Check each type of rolling mode starting with the smallest increment.
for(int i = (int)RollPoint.TopOfMinute; i <= (int)RollPoint.TopOfMonth; i++)
{
// Get string representation of next pattern
string r1 = NextCheckDate(s_date1970, (RollPoint)i).ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
LogLog.Debug(declaringType, "Type = ["+i+"], r0 = ["+r0+"], r1 = ["+r1+"]");
// Check if the string representations are different
if (r0 != null && r1 != null && !r0.Equals(r1))
{
// Found highest precision roll point
return (RollPoint)i;
}
}
return RollPoint.InvalidRollPoint; // Deliberately head for trouble...
}
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// Sets initial conditions including date/time roll over information, first check,
/// scheduledFilename, and calls <see cref="ExistingInit"/> to initialize
/// the current number of backups.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
if (m_dateTime == null)
{
m_dateTime = new LocalDateTime();
}
if (m_rollDate && m_datePattern != null)
{
m_now = m_dateTime.Now;
m_rollPoint = ComputeCheckPeriod(m_datePattern);
if (m_rollPoint == RollPoint.InvalidRollPoint)
{
throw new ArgumentException("Invalid RollPoint, unable to parse ["+m_datePattern+"]");
}
// next line added as this removes the name check in rollOver
m_nextCheck = NextCheckDate(m_now, m_rollPoint);
}
else
{
if (m_rollDate)
{
ErrorHandler.Error("Either DatePattern or rollingStyle options are not set for ["+Name+"].");
}
}
if (SecurityContext == null)
{
SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
using(SecurityContext.Impersonate(this))
{
// Must convert the FileAppender's m_filePath to an absolute path before we
// call ExistingInit(). This will be done by the base.ActivateOptions() but
// we need to duplicate that functionality here first.
base.File = ConvertToFullPath(base.File.Trim());
// Store fully qualified base file name
m_baseFileName = base.File;
}
#if !NETCF
// initialize the mutex that is used to lock rolling
m_mutexForRolling = new Mutex(false, m_baseFileName.Replace("\\", "_").Replace(":", "_").Replace("/", "_"));
#endif
if (m_rollDate && File != null && m_scheduledFilename == null)
{
m_scheduledFilename = CombinePath(File, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo));
}
ExistingInit();
base.ActivateOptions();
}
#endregion
#region Roll File
/// <summary>
///
/// </summary>
/// <param name="path1"></param>
/// <param name="path2">.1, .2, .3, etc.</param>
/// <returns></returns>
private string CombinePath(string path1, string path2)
{
string extension = Path.GetExtension(path1);
if (m_preserveLogFileNameExtension && extension.Length > 0)
{
return Path.Combine(Path.GetDirectoryName(path1), Path.GetFileNameWithoutExtension(path1) + path2 + extension);
}
else
{
return path1 + path2;
}
}
/// <summary>
/// Rollover the file(s) to date/time tagged file(s).
/// </summary>
/// <param name="fileIsOpen">set to true if the file to be rolled is currently open</param>
/// <remarks>
/// <para>
/// Rollover the file(s) to date/time tagged file(s).
/// Resets curSizeRollBackups.
/// If fileIsOpen is set then the new file is opened (through SafeOpenFile).
/// </para>
/// </remarks>
protected void RollOverTime(bool fileIsOpen)
{
if (m_staticLogFileName)
{
// Compute filename, but only if datePattern is specified
if (m_datePattern == null)
{
ErrorHandler.Error("Missing DatePattern option in rollOver().");
return;
}
// is the new file name equivalent to the 'current' one
// something has gone wrong if we hit this -- we should only
// roll over if the new file will be different from the old
string dateFormat = m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
if (m_scheduledFilename.Equals(CombinePath(File, dateFormat)))
{
ErrorHandler.Error("Compare " + m_scheduledFilename + " : " + CombinePath(File, dateFormat));
return;
}
if (fileIsOpen)
{
// close current file, and rename it to datedFilename
this.CloseFile();
}
// we may have to roll over a large number of backups here
for (int i = 1; i <= m_curSizeRollBackups; i++)
{
string from = CombinePath(File, "." + i);
string to = CombinePath(m_scheduledFilename, "." + i);
RollFile(from, to);
}
RollFile(File, m_scheduledFilename);
}
// We've cleared out the old date and are ready for the new
m_curSizeRollBackups = 0;
// new scheduled name
m_scheduledFilename = CombinePath(File, m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo));
if (fileIsOpen)
{
// This will also close the file. This is OK since multiple close operations are safe.
SafeOpenFile(m_baseFileName, false);
}
}
/// <summary>
/// Renames file <paramref name="fromFile"/> to file <paramref name="toFile"/>.
/// </summary>
/// <param name="fromFile">Name of existing file to roll.</param>
/// <param name="toFile">New name for file.</param>
/// <remarks>
/// <para>
/// Renames file <paramref name="fromFile"/> to file <paramref name="toFile"/>. It
/// also checks for existence of target file and deletes if it does.
/// </para>
/// </remarks>
protected void RollFile(string fromFile, string toFile)
{
if (FileExists(fromFile))
{
// Delete the toFile if it exists
DeleteFile(toFile);
// We may not have permission to move the file, or the file may be locked
try
{
LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]");
using(SecurityContext.Impersonate(this))
{
System.IO.File.Move(fromFile, toFile);
}
}
catch(Exception moveEx)
{
ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure);
}
}
else
{
LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist");
}
}
/// <summary>
/// Test if a file exists at a specified path
/// </summary>
/// <param name="path">the path to the file</param>
/// <returns>true if the file exists</returns>
/// <remarks>
/// <para>
/// Test if a file exists at a specified path
/// </para>
/// </remarks>
protected bool FileExists(string path)
{
using(SecurityContext.Impersonate(this))
{
return System.IO.File.Exists(path);
}
}
/// <summary>
/// Deletes the specified file if it exists.
/// </summary>
/// <param name="fileName">The file to delete.</param>
/// <remarks>
/// <para>
/// Delete a file if is exists.
/// The file is first moved to a new filename then deleted.
/// This allows the file to be removed even when it cannot
/// be deleted, but it still can be moved.
/// </para>
/// </remarks>
protected void DeleteFile(string fileName)
{
if (FileExists(fileName))
{
// We may not have permission to delete the file, or the file may be locked
string fileToDelete = fileName;
// Try to move the file to temp name.
// If the file is locked we may still be able to move it
string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending";
try
{
using(SecurityContext.Impersonate(this))
{
System.IO.File.Move(fileName, tempFileName);
}
fileToDelete = tempFileName;
}
catch(Exception moveEx)
{
LogLog.Debug(declaringType, "Exception while moving file to be deleted [" + fileName + "] -> [" + tempFileName + "]", moveEx);
}
// Try to delete the file (either the original or the moved file)
try
{
using(SecurityContext.Impersonate(this))
{
System.IO.File.Delete(fileToDelete);
}
LogLog.Debug(declaringType, "Deleted file [" + fileName + "]");
}
catch(Exception deleteEx)
{
if (fileToDelete == fileName)
{
// Unable to move or delete the file
ErrorHandler.Error("Exception while deleting file [" + fileToDelete + "]", deleteEx, ErrorCode.GenericFailure);
}
else
{
// Moved the file, but the delete failed. File is probably locked.
// The file should automatically be deleted when the lock is released.
LogLog.Debug(declaringType, "Exception while deleting temp file [" + fileToDelete + "]", deleteEx);
}
}
}
}
/// <summary>
/// Implements file roll base on file size.
/// </summary>
/// <remarks>
/// <para>
/// If the maximum number of size based backups is reached
/// (<c>curSizeRollBackups == maxSizeRollBackups</c>) then the oldest
/// file is deleted -- its index determined by the sign of countDirection.
/// If <c>countDirection</c> < 0, then files
/// {<c>File.1</c>, ..., <c>File.curSizeRollBackups -1</c>}
/// are renamed to {<c>File.2</c>, ...,
/// <c>File.curSizeRollBackups</c>}. Moreover, <c>File</c> is
/// renamed <c>File.1</c> and closed.
/// </para>
/// <para>
/// A new file is created to receive further log output.
/// </para>
/// <para>
/// If <c>maxSizeRollBackups</c> is equal to zero, then the
/// <c>File</c> is truncated with no backup files created.
/// </para>
/// <para>
/// If <c>maxSizeRollBackups</c> < 0, then <c>File</c> is
/// renamed if needed and no files are deleted.
/// </para>
/// </remarks>
protected void RollOverSize()
{
this.CloseFile(); // keep windows happy.
LogLog.Debug(declaringType, "rolling over count ["+((CountingQuietTextWriter)QuietWriter).Count+"]");
LogLog.Debug(declaringType, "maxSizeRollBackups ["+m_maxSizeRollBackups+"]");
LogLog.Debug(declaringType, "curSizeRollBackups ["+m_curSizeRollBackups+"]");
LogLog.Debug(declaringType, "countDirection ["+m_countDirection+"]");
RollOverRenameFiles(File);
if (!m_staticLogFileName && m_countDirection >= 0)
{
m_curSizeRollBackups++;
}
// This will also close the file. This is OK since multiple close operations are safe.
SafeOpenFile(m_baseFileName, false);
}
/// <summary>
/// Implements file roll.
/// </summary>
/// <param name="baseFileName">the base name to rename</param>
/// <remarks>
/// <para>
/// If the maximum number of size based backups is reached
/// (<c>curSizeRollBackups == maxSizeRollBackups</c>) then the oldest
/// file is deleted -- its index determined by the sign of countDirection.
/// If <c>countDirection</c> < 0, then files
/// {<c>File.1</c>, ..., <c>File.curSizeRollBackups -1</c>}
/// are renamed to {<c>File.2</c>, ...,
/// <c>File.curSizeRollBackups</c>}.
/// </para>
/// <para>
/// If <c>maxSizeRollBackups</c> is equal to zero, then the
/// <c>File</c> is truncated with no backup files created.
/// </para>
/// <para>
/// If <c>maxSizeRollBackups</c> < 0, then <c>File</c> is
/// renamed if needed and no files are deleted.
/// </para>
/// <para>
/// This is called by <see cref="RollOverSize"/> to rename the files.
/// </para>
/// </remarks>
protected void RollOverRenameFiles(string baseFileName)
{
// If maxBackups <= 0, then there is no file renaming to be done.
if (m_maxSizeRollBackups != 0)
{
if (m_countDirection < 0)
{
// Delete the oldest file, to keep Windows happy.
if (m_curSizeRollBackups == m_maxSizeRollBackups)
{
DeleteFile(CombinePath(baseFileName, "." + m_maxSizeRollBackups));
m_curSizeRollBackups--;
}
// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
for (int i = m_curSizeRollBackups; i >= 1; i--)
{
RollFile((CombinePath(baseFileName, "." + i)), (CombinePath(baseFileName, "." + (i + 1))));
}
m_curSizeRollBackups++;
// Rename fileName to fileName.1
RollFile(baseFileName, CombinePath(baseFileName, ".1"));
}
else
{
// countDirection >= 0
if (m_curSizeRollBackups >= m_maxSizeRollBackups && m_maxSizeRollBackups > 0)
{
// delete the first and keep counting up.
int oldestFileIndex = m_curSizeRollBackups - m_maxSizeRollBackups;
// If static then there is 1 file without a number, therefore 1 less archive
if (m_staticLogFileName)
{
oldestFileIndex++;
}
// If using a static log file then the base for the numbered sequence is the baseFileName passed in
// If not using a static log file then the baseFileName will already have a numbered postfix which
// we must remove, however it may have a date postfix which we must keep!
string archiveFileBaseName = baseFileName;
if (!m_staticLogFileName)
{
if (m_preserveLogFileNameExtension)
{
string extension = Path.GetExtension(archiveFileBaseName);
string baseName = Path.GetFileNameWithoutExtension(archiveFileBaseName);
int lastDotIndex = baseName.LastIndexOf(".");
if (lastDotIndex >= 0)
{
archiveFileBaseName = baseName.Substring(0, lastDotIndex) + extension;
}
}
else
{
int lastDotIndex = archiveFileBaseName.LastIndexOf(".");
if (lastDotIndex >= 0)
{
archiveFileBaseName = archiveFileBaseName.Substring(0, lastDotIndex);
}
}
}
// Delete the archive file
DeleteFile(CombinePath(archiveFileBaseName, "." + oldestFileIndex));
}
if (m_staticLogFileName)
{
m_curSizeRollBackups++;
RollFile(baseFileName, CombinePath(baseFileName, "." + m_curSizeRollBackups));
}
}
}
}
#endregion
#region NextCheckDate
/// <summary>
/// Get the start time of the next window for the current rollpoint
/// </summary>
/// <param name="currentDateTime">the current date</param>
/// <param name="rollPoint">the type of roll point we are working with</param>
/// <returns>the start time for the next roll point an interval after the currentDateTime date</returns>
/// <remarks>
/// <para>
/// Returns the date of the next roll point after the currentDateTime date passed to the method.
/// </para>
/// <para>
/// The basic strategy is to subtract the time parts that are less significant
/// than the rollpoint from the current time. This should roll the time back to
/// the start of the time window for the current rollpoint. Then we add 1 window
/// worth of time and get the start time of the next window for the rollpoint.
/// </para>
/// </remarks>
protected DateTime NextCheckDate(DateTime currentDateTime, RollPoint rollPoint)
{
// Local variable to work on (this does not look very efficient)
DateTime current = currentDateTime;
// Do slightly different things depending on what the type of roll point we want.
switch(rollPoint)
{
case RollPoint.TopOfMinute:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(1);
break;
case RollPoint.TopOfHour:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(-current.Minute);
current = current.AddHours(1);
break;
case RollPoint.HalfDay:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(-current.Minute);
if (current.Hour < 12)
{
current = current.AddHours(12 - current.Hour);
}
else
{
current = current.AddHours(-current.Hour);
current = current.AddDays(1);
}
break;
case RollPoint.TopOfDay:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(-current.Minute);
current = current.AddHours(-current.Hour);
current = current.AddDays(1);
break;
case RollPoint.TopOfWeek:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(-current.Minute);
current = current.AddHours(-current.Hour);
current = current.AddDays(7 - (int)current.DayOfWeek);
break;
case RollPoint.TopOfMonth:
current = current.AddMilliseconds(-current.Millisecond);
current = current.AddSeconds(-current.Second);
current = current.AddMinutes(-current.Minute);
current = current.AddHours(-current.Hour);
current = current.AddDays(1 - current.Day); /* first day of month is 1 not 0 */
current = current.AddMonths(1);
break;
}
return current;
}
#endregion
#region Private Instance Fields
/// <summary>
/// This object supplies the current date/time. Allows test code to plug in
/// a method to control this class when testing date/time based rolling. The default
/// implementation uses the underlying value of DateTime.Now.
/// </summary>
private IDateTime m_dateTime = null;
/// <summary>
/// The date pattern. By default, the pattern is set to <c>".yyyy-MM-dd"</c>
/// meaning daily rollover.
/// </summary>
private string m_datePattern = ".yyyy-MM-dd";
/// <summary>
/// The actual formatted filename that is currently being written to
/// or will be the file transferred to on roll over
/// (based on staticLogFileName).
/// </summary>
private string m_scheduledFilename = null;
/// <summary>
/// The timestamp when we shall next recompute the filename.
/// </summary>
private DateTime m_nextCheck = DateTime.MaxValue;
/// <summary>
/// Holds date of last roll over
/// </summary>
private DateTime m_now;
/// <summary>
/// The type of rolling done
/// </summary>
private RollPoint m_rollPoint;
/// <summary>
/// The default maximum file size is 10MB
/// </summary>
private long m_maxFileSize = 10*1024*1024;
/// <summary>
/// There is zero backup files by default
/// </summary>
private int m_maxSizeRollBackups = 0;
/// <summary>
/// How many sized based backups have been made so far
/// </summary>
private int m_curSizeRollBackups = 0;
/// <summary>
/// The rolling file count direction.
/// </summary>
private int m_countDirection = -1;
/// <summary>
/// The rolling mode used in this appender.
/// </summary>
private RollingMode m_rollingStyle = RollingMode.Composite;
/// <summary>
/// Cache flag set if we are rolling by date.
/// </summary>
private bool m_rollDate = true;
/// <summary>
/// Cache flag set if we are rolling by size.
/// </summary>
private bool m_rollSize = true;
/// <summary>
/// Value indicating whether to always log to the same file.
/// </summary>
private bool m_staticLogFileName = true;
/// <summary>
/// Value indicating whether to preserve the file name extension when rolling.
/// </summary>
private bool m_preserveLogFileNameExtension = false;
/// <summary>
/// FileName provided in configuration. Used for rolling properly
/// </summary>
private string m_baseFileName;
#if !NETCF
/// <summary>
/// A mutex that is used to lock rolling of files.
/// </summary>
private Mutex m_mutexForRolling;
#endif
#endregion Private Instance Fields
#region Static Members
/// <summary>
/// The 1st of January 1970 in UTC
/// </summary>
private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1);
#endregion
#region DateTime
/// <summary>
/// This interface is used to supply Date/Time information to the <see cref="RollingFileAppender"/>.
/// </summary>
/// <remarks>
/// This interface is used to supply Date/Time information to the <see cref="RollingFileAppender"/>.
/// Used primarily to allow test classes to plug themselves in so they can
/// supply test date/times.
/// </remarks>
public interface IDateTime
{
/// <summary>
/// Gets the <i>current</i> time.
/// </summary>
/// <value>The <i>current</i> time.</value>
/// <remarks>
/// <para>
/// Gets the <i>current</i> time.
/// </para>
/// </remarks>
DateTime Now { get; }
}
/// <summary>
/// Default implementation of <see cref="IDateTime"/> that returns the current time.
/// </summary>
private class LocalDateTime : IDateTime
{
/// <summary>
/// Gets the <b>current</b> time.
/// </summary>
/// <value>The <b>current</b> time.</value>
/// <remarks>
/// <para>
/// Gets the <b>current</b> time.
/// </para>
/// </remarks>
public DateTime Now
{
get { return DateTime.Now; }
}
}
#if !NET_1_0 && !CLI_1_0 && !NETCF
/// <summary>
/// Implementation of <see cref="IDateTime"/> that returns the current time as the coordinated universal time (UTC).
/// </summary>
private class UniversalDateTime : IDateTime
{
/// <summary>
/// Gets the <b>current</b> time.
/// </summary>
/// <value>The <b>current</b> time.</value>
/// <remarks>
/// <para>
/// Gets the <b>current</b> time.
/// </para>
/// </remarks>
public DateTime Now
{
get { return DateTime.UtcNow; }
}
}
#endif
#endregion DateTime
}
}
| mit |
ZjMNZHgG5jMXw/goa | goagen/gen_main/generator.go | 12978 | package genmain
import (
"bufio"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"net"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/goadesign/goa/design"
"github.com/goadesign/goa/goagen/codegen"
"github.com/goadesign/goa/goagen/utils"
)
//NewGenerator returns an initialized instance of a JavaScript Client Generator
func NewGenerator(options ...Option) *Generator {
g := &Generator{OutDir: "."}
for _, option := range options {
option(g)
}
return g
}
// Generator is the application code generator.
type Generator struct {
API *design.APIDefinition // The API definition
OutDir string // Path to output directory
DesignPkg string // Path to design package, only used to mark generated files.
Target string // Name of generated "app" package
Force bool // Whether to override existing files
Regen bool // Whether to regenerate scaffolding in place, maintaining controller implementation
genfiles []string // Generated files
}
// Generate is the generator entry point called by the meta generator.
func Generate() (files []string, err error) {
var (
outDir, toolDir, designPkg, target, ver string
force, notool, regen bool
)
set := flag.NewFlagSet("main", flag.PanicOnError)
set.StringVar(&outDir, "out", "", "")
set.StringVar(&designPkg, "design", "", "")
set.StringVar(&target, "pkg", "app", "")
set.StringVar(&ver, "version", "", "")
set.StringVar(&toolDir, "tooldir", "tool", "")
set.BoolVar(¬ool, "notool", false, "")
set.BoolVar(&force, "force", false, "")
set.BoolVar(®en, "regen", false, "")
set.Bool("notest", false, "")
set.Parse(os.Args[1:])
if err := codegen.CheckVersion(ver); err != nil {
return nil, err
}
target = codegen.Goify(target, false)
g := &Generator{OutDir: outDir, DesignPkg: designPkg, Target: target, Force: force, Regen: regen, API: design.Design}
return g.Generate()
}
func extractControllerBody(filename string) (map[string]string, []*ast.ImportSpec, error) {
// First check if a file is there. If not, return empty results to let generation proceed.
if _, e := os.Stat(filename); e != nil {
return map[string]string{}, []*ast.ImportSpec{}, nil
}
fset := token.NewFileSet()
pfile, err := parser.ParseFile(fset, filename, nil, parser.ImportsOnly)
if err != nil {
return nil, nil, err
}
f, err := os.Open(filename)
if err != nil {
return nil, nil, err
}
defer f.Close()
var (
inBlock bool
block []string
)
actionImpls := map[string]string{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
match := linePattern.FindStringSubmatch(line)
if len(match) == 3 {
switch match[2] {
case "start":
inBlock = true
case "end":
inBlock = false
actionImpls[match[1]] = strings.Join(block, "\n")
block = []string{}
}
continue
}
if inBlock {
block = append(block, line)
}
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return actionImpls, pfile.Imports, nil
}
// GenerateController generates the controller corresponding to the given
// resource and returns the generated filename.
func GenerateController(force, regen bool, appPkg, outDir, pkg, name string, r *design.ResourceDefinition) (filename string, err error) {
filename = filepath.Join(outDir, codegen.SnakeCase(name)+".go")
var (
actionImpls map[string]string
extractedImports []*ast.ImportSpec
)
if regen {
actionImpls, extractedImports, err = extractControllerBody(filename)
if err != nil {
return "", err
}
os.Remove(filename)
}
if force {
os.Remove(filename)
}
if _, e := os.Stat(filename); e == nil {
return "", nil
}
if err = os.MkdirAll(outDir, 0755); err != nil {
return "", err
}
var file *codegen.SourceFile
file, err = codegen.SourceFileFor(filename)
if err != nil {
return "", err
}
defer func() {
file.Close()
if err == nil {
err = file.FormatCode()
}
}()
elems := strings.Split(appPkg, "/")
pkgName := elems[len(elems)-1]
var imp string
if _, err := codegen.PackageSourcePath(appPkg); err == nil {
imp = appPkg
} else {
imp, err = codegen.PackagePath(outDir)
if err != nil {
return "", err
}
imp = path.Join(filepath.ToSlash(imp), appPkg)
}
imports := []*codegen.ImportSpec{
codegen.SimpleImport("io"),
codegen.SimpleImport("github.com/goadesign/goa"),
codegen.SimpleImport(imp),
codegen.SimpleImport("golang.org/x/net/websocket"),
}
for _, imp := range extractedImports {
// This may introduce duplicate imports of the defaults, but
// that'll get worked out by Format later.
var cgimp *codegen.ImportSpec
path := strings.Trim(imp.Path.Value, `"`)
if imp.Name != nil {
cgimp = codegen.NewImport(imp.Name.Name, path)
} else {
cgimp = codegen.SimpleImport(path)
}
imports = append(imports, cgimp)
}
funcs := funcMap(pkgName, actionImpls)
if err = file.WriteHeader("", pkg, imports); err != nil {
return "", err
}
if err = file.ExecuteTemplate("controller", ctrlT, funcs, r); err != nil {
return "", err
}
err = r.IterateActions(func(a *design.ActionDefinition) error {
if a.WebSocket() {
return file.ExecuteTemplate("actionWS", actionWST, funcs, a)
}
return file.ExecuteTemplate("action", actionT, funcs, a)
})
if err != nil {
return "", err
}
return
}
// Generate produces the skeleton main.
func (g *Generator) Generate() (_ []string, err error) {
if g.API == nil {
return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
}
go utils.Catch(nil, func() { g.Cleanup() })
defer func() {
if err != nil {
g.Cleanup()
}
}()
if g.Target == "" {
g.Target = "app"
}
codegen.Reserved[g.Target] = true
mainFile := filepath.Join(g.OutDir, "main.go")
if g.Force {
os.Remove(mainFile)
}
_, err = os.Stat(mainFile)
if err != nil {
// ensure that the output directory exists before creating a new main
if err = os.MkdirAll(g.OutDir, 0755); err != nil {
return nil, err
}
if err = g.createMainFile(mainFile, funcMap(g.Target, nil)); err != nil {
return nil, err
}
}
err = g.API.IterateResources(func(r *design.ResourceDefinition) error {
filename, err := GenerateController(g.Force, g.Regen, g.Target, g.OutDir, "main", r.Name, r)
if err != nil {
return err
}
g.genfiles = append(g.genfiles, filename)
return nil
})
if err != nil {
return
}
return g.genfiles, nil
}
// Cleanup removes all the files generated by this generator during the last invokation of Generate.
func (g *Generator) Cleanup() {
for _, f := range g.genfiles {
os.Remove(f)
}
g.genfiles = nil
}
func (g *Generator) createMainFile(mainFile string, funcs template.FuncMap) (err error) {
var file *codegen.SourceFile
file, err = codegen.SourceFileFor(mainFile)
if err != nil {
return err
}
defer func() {
file.Close()
if err == nil {
err = file.FormatCode()
}
}()
g.genfiles = append(g.genfiles, mainFile)
funcs["getPort"] = func(hostport string) string {
_, port, err := net.SplitHostPort(hostport)
if err != nil {
return "8080"
}
return port
}
outPkg, err := codegen.PackagePath(g.OutDir)
if err != nil {
return err
}
appPkg := path.Join(outPkg, "app")
imports := []*codegen.ImportSpec{
codegen.SimpleImport("time"),
codegen.SimpleImport("github.com/goadesign/goa"),
codegen.SimpleImport("github.com/goadesign/goa/middleware"),
codegen.SimpleImport(appPkg),
}
file.Write([]byte("//go:generate goagen bootstrap -d " + g.DesignPkg + "\n\n"))
if err = file.WriteHeader("", "main", imports); err != nil {
return err
}
tls := false
for _, scheme := range g.API.Schemes {
if scheme == "https" {
tls = true
}
}
data := map[string]interface{}{
"Name": g.API.Name,
"API": g.API,
"TLS": tls,
}
err = file.ExecuteTemplate("main", mainT, funcs, data)
return
}
// tempCount is the counter used to create unique temporary variable names.
var tempCount int
// tempvar generates a unique temp var name.
func tempvar() string {
tempCount++
if tempCount == 1 {
return "c"
}
return fmt.Sprintf("c%d", tempCount)
}
func okResp(a *design.ActionDefinition, appPkg string) map[string]interface{} {
var ok *design.ResponseDefinition
for _, resp := range a.Responses {
if resp.Status == 200 {
ok = resp
break
}
}
if ok == nil {
return nil
}
var mt *design.MediaTypeDefinition
var ok2 bool
if mt, ok2 = design.Design.MediaTypes[design.CanonicalIdentifier(ok.MediaType)]; !ok2 {
return nil
}
view := ok.ViewName
if view == "" {
view = design.DefaultView
}
pmt, _, err := mt.Project(view)
if err != nil {
return nil
}
var typeref string
if pmt.IsError() {
typeref = `goa.ErrInternal("not implemented")`
} else {
name := codegen.GoTypeRef(pmt, pmt.AllRequired(), 1, false)
var pointer string
if strings.HasPrefix(name, "*") {
name = name[1:]
pointer = "*"
}
typeref = fmt.Sprintf("%s%s.%s", pointer, appPkg, name)
if strings.HasPrefix(typeref, "*") {
typeref = "&" + typeref[1:]
}
typeref += "{}"
}
var nameSuffix string
if view != "default" {
nameSuffix = codegen.Goify(view, true)
}
return map[string]interface{}{
"Name": ok.Name + nameSuffix,
"GoType": codegen.GoNativeType(pmt),
"TypeRef": typeref,
}
}
// funcMap creates the funcMap used to render the controller code.
func funcMap(appPkg string, actionImpls map[string]string) template.FuncMap {
return template.FuncMap{
"tempvar": tempvar,
"okResp": okResp,
"targetPkg": func() string { return appPkg },
"actionBody": func(name string) string {
body, ok := actionImpls[name]
if !ok {
return defaultActionBody
}
return body
},
"printResp": func(name string) bool {
_, ok := actionImpls[name]
return !ok
},
}
}
var linePattern = regexp.MustCompile(`^\s*// ([^:]+): (\w+)_implement\s*$`)
const defaultActionBody = `// Put your logic here`
const ctrlT = `// {{ $ctrlName := printf "%s%s" (goify .Name true) "Controller" }}{{ $ctrlName }} implements the {{ .Name }} resource.
type {{ $ctrlName }} struct {
*goa.Controller
}
// New{{ $ctrlName }} creates a {{ .Name }} controller.
func New{{ $ctrlName }}(service *goa.Service) *{{ $ctrlName }} {
return &{{ $ctrlName }}{Controller: service.NewController("{{ $ctrlName }}")}
}
`
const actionT = `
{{- $ctrlName := printf "%s%s" (goify .Parent.Name true) "Controller" -}}
{{- $actionDescr := printf "%s_%s" $ctrlName (goify .Name true) -}}
// {{ goify .Name true }} runs the {{ .Name }} action.
func (c *{{ $ctrlName }}) {{ goify .Name true }}(ctx *{{ targetPkg }}.{{ goify .Name true }}{{ goify .Parent.Name true }}Context) error {
// {{ $actionDescr }}: start_implement
{{ actionBody $actionDescr }}
{{ if printResp $actionDescr }}
{{ $ok := okResp . targetPkg }}{{ if $ok }} res := {{ $ok.TypeRef }}
{{ end }} return {{ if $ok }}ctx.{{ $ok.Name }}(res){{ else }}nil{{ end }}
{{ end }} // {{ $actionDescr }}: end_implement
}
`
const actionWST = `
{{- $ctrlName := printf "%s%s" (goify .Parent.Name true) "Controller" -}}
{{- $actionDescr := printf "%s_%s" $ctrlName (goify .Name true) -}}
// {{ goify .Name true }} runs the {{ .Name }} action.
func (c *{{ $ctrlName }}) {{ goify .Name true }}(ctx *{{ targetPkg }}.{{ goify .Name true }}{{ goify .Parent.Name true }}Context) error {
c.{{ goify .Name true }}WSHandler(ctx).ServeHTTP(ctx.ResponseWriter, ctx.Request)
return nil
}
// {{ goify .Name true }}WSHandler establishes a websocket connection to run the {{ .Name }} action.
func (c *{{ $ctrlName }}) {{ goify .Name true }}WSHandler(ctx *{{ targetPkg }}.{{ goify .Name true }}{{ goify .Parent.Name true }}Context) websocket.Handler {
return func(ws *websocket.Conn) {
// {{ $actionDescr }}: start_implement
{{ actionBody $actionDescr }}
{{ if printResp $actionDescr }}
ws.Write([]byte("{{ .Name }} {{ .Parent.Name }}"))
// Dummy echo websocket server
io.Copy(ws, ws)
{{ end }} // {{ $actionDescr }}: end_implement
}
}`
const mainT = `
func main() {
// Create service
service := goa.New({{ printf "%q" .Name }})
// Mount middleware
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest(true))
service.Use(middleware.ErrorHandler(service, true))
service.Use(middleware.Recover())
{{ $api := .API }}
{{ range $name, $res := $api.Resources }}{{ $name := goify $res.Name true }} // Mount "{{$res.Name}}" controller
{{ $tmp := tempvar }}{{ $tmp }} := New{{ $name }}Controller(service)
{{ targetPkg }}.Mount{{ $name }}Controller(service, {{ $tmp }})
{{ end }}
{{ if .TLS }}
// Start service
if err := service.ListenAndServeTLS(":{{ getPort .API.Host }}", "cert.pem", "key.pem"); err != nil {
service.LogError("startup", "err", err)
}
{{ else }}
// Start service
if err := service.ListenAndServe(":{{ getPort .API.Host }}"); err != nil {
service.LogError("startup", "err", err)
}
{{ end }}
}
`
| mit |
belgattitude/soluble-metadata | src/Soluble/Metadata/Exception/UnsupportedFeatureException.php | 178 | <?php
declare(strict_types=1);
/**
* @author Vanvelthem Sébastien
*/
namespace Soluble\Metadata\Exception;
class UnsupportedFeatureException extends \RuntimeException
{
}
| mit |
zcodes/symfony | src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php | 3832 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Session\Storage;
/**
* MockFileSessionStorage is used to mock sessions for
* functional testing when done in a single PHP process.
*
* No PHP session is actually started since a session can be initialized
* and shutdown only once per PHP execution cycle and this class does
* not pollute any session related globals, including session_*() functions
* or session.* PHP ini directives.
*
* @author Drak <drak@zikula.org>
*/
class MockFileSessionStorage extends MockArraySessionStorage
{
private $savePath;
/**
* @param string $savePath Path of directory to save session files
* @param string $name Session name
*/
public function __construct(string $savePath = null, string $name = 'MOCKSESSID', MetadataBag $metaBag = null)
{
if (null === $savePath) {
$savePath = sys_get_temp_dir();
}
if (!is_dir($savePath) && !@mkdir($savePath, 0777, true) && !is_dir($savePath)) {
throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $savePath));
}
$this->savePath = $savePath;
parent::__construct($name, $metaBag);
}
/**
* {@inheritdoc}
*/
public function start()
{
if ($this->started) {
return true;
}
if (!$this->id) {
$this->id = $this->generateId();
}
$this->read();
$this->started = true;
return true;
}
/**
* {@inheritdoc}
*/
public function regenerate($destroy = false, $lifetime = null)
{
if (!$this->started) {
$this->start();
}
if ($destroy) {
$this->destroy();
}
return parent::regenerate($destroy, $lifetime);
}
/**
* {@inheritdoc}
*/
public function save()
{
if (!$this->started) {
throw new \RuntimeException('Trying to save a session that was not started yet or was already closed');
}
$data = $this->data;
foreach ($this->bags as $bag) {
if (empty($data[$key = $bag->getStorageKey()])) {
unset($data[$key]);
}
}
if ([$key = $this->metadataBag->getStorageKey()] === array_keys($data)) {
unset($data[$key]);
}
try {
if ($data) {
file_put_contents($this->getFilePath(), serialize($data));
} else {
$this->destroy();
}
} finally {
$this->data = $data;
}
// this is needed for Silex, where the session object is re-used across requests
// in functional tests. In Symfony, the container is rebooted, so we don't have
// this issue
$this->started = false;
}
/**
* Deletes a session from persistent storage.
* Deliberately leaves session data in memory intact.
*/
private function destroy(): void
{
if (is_file($this->getFilePath())) {
unlink($this->getFilePath());
}
}
/**
* Calculate path to file.
*/
private function getFilePath(): string
{
return $this->savePath.'/'.$this->id.'.mocksess';
}
/**
* Reads session from storage and loads session.
*/
private function read(): void
{
$filePath = $this->getFilePath();
$this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : [];
$this->loadSession();
}
}
| mit |
vlcheong/spring-employee | src/main/webapp/assets/jquery.inputmask/dist/inputmask/inputmask.numeric.extensions.js | 28728 | /*!
* inputmask.numeric.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2015 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.64-166
*/
!function(factory) {
"function" == typeof define && define.amd ? define([ "jquery", "./inputmask" ], factory) : "object" == typeof exports ? module.exports = factory(require("jquery"), require("./inputmask")) : factory(jQuery);
}(function($) {
return Inputmask.extendAliases({
numeric: {
mask: function(opts) {
function autoEscape(txt) {
for (var escapedTxt = "", i = 0; i < txt.length; i++) escapedTxt += opts.definitions[txt[i]] ? "\\" + txt[i] : txt[i];
return escapedTxt;
}
if (0 !== opts.repeat && isNaN(opts.integerDigits) && (opts.integerDigits = opts.repeat),
opts.repeat = 0, opts.groupSeparator === opts.radixPoint && ("." === opts.radixPoint ? opts.groupSeparator = "," : "," === opts.radixPoint ? opts.groupSeparator = "." : opts.groupSeparator = ""),
" " === opts.groupSeparator && (opts.skipOptionalPartCharacter = void 0), opts.autoGroup = opts.autoGroup && "" !== opts.groupSeparator,
opts.autoGroup && ("string" == typeof opts.groupSize && isFinite(opts.groupSize) && (opts.groupSize = parseInt(opts.groupSize)),
isFinite(opts.integerDigits))) {
var seps = Math.floor(opts.integerDigits / opts.groupSize), mod = opts.integerDigits % opts.groupSize;
opts.integerDigits = parseInt(opts.integerDigits) + (0 === mod ? seps - 1 : seps),
opts.integerDigits < 1 && (opts.integerDigits = "*");
}
opts.placeholder.length > 1 && (opts.placeholder = opts.placeholder.charAt(0)),
opts.radixFocus = opts.radixFocus && "" !== opts.placeholder && opts.integerOptional === !0,
opts.definitions[";"] = opts.definitions["~"], opts.definitions[";"].definitionSymbol = "~",
opts.numericInput === !0 && (opts.radixFocus = !1, opts.digitsOptional = !1, isNaN(opts.digits) && (opts.digits = 2),
opts.decimalProtect = !1);
var mask = autoEscape(opts.prefix);
return mask += "[+]", mask += opts.integerOptional === !0 ? "~{1," + opts.integerDigits + "}" : "~{" + opts.integerDigits + "}",
void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0) && (mask += opts.digitsOptional ? "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]" : (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}"),
"" !== opts.negationSymbol.back && (mask += "[-]"), mask += autoEscape(opts.suffix),
opts.greedy = !1, mask;
},
placeholder: "",
greedy: !1,
digits: "*",
digitsOptional: !0,
radixPoint: ".",
radixFocus: !0,
groupSize: 3,
groupSeparator: "",
autoGroup: !1,
allowPlus: !0,
allowMinus: !0,
negationSymbol: {
front: "-",
back: ""
},
integerDigits: "+",
integerOptional: !0,
prefix: "",
suffix: "",
rightAlign: !0,
decimalProtect: !0,
min: void 0,
max: void 0,
step: 1,
insertMode: !0,
autoUnmask: !1,
unmaskAsNumber: !1,
postFormat: function(buffer, pos, reformatOnly, opts) {
opts.numericInput === !0 && (buffer = buffer.reverse(), isFinite(pos) && (pos = buffer.join("").length - pos - 1));
var i, l, suffixStripped = !1;
buffer.length >= opts.suffix.length && buffer.join("").indexOf(opts.suffix) === buffer.length - opts.suffix.length && (buffer.length = buffer.length - opts.suffix.length,
suffixStripped = !0), pos = pos >= buffer.length ? buffer.length - 1 : pos < opts.prefix.length ? opts.prefix.length : pos;
var needsRefresh = !1, charAtPos = buffer[pos];
if ("" === opts.groupSeparator || opts.numericInput !== !0 && -1 !== $.inArray(opts.radixPoint, buffer) && pos > $.inArray(opts.radixPoint, buffer) || new RegExp("[" + Inputmask.escapeRegex(opts.negationSymbol.front) + "+]").test(charAtPos)) {
if (suffixStripped) for (i = 0, l = opts.suffix.length; l > i; i++) buffer.push(opts.suffix.charAt(i));
return {
pos: pos
};
}
var cbuf = buffer.slice();
charAtPos === opts.groupSeparator && (cbuf.splice(pos--, 1), charAtPos = cbuf[pos]),
reformatOnly ? charAtPos !== opts.radixPoint && (cbuf[pos] = "?") : cbuf.splice(pos, 0, "?");
var bufVal = cbuf.join(""), bufValOrigin = bufVal;
if (bufVal.length > 0 && opts.autoGroup || reformatOnly && -1 !== bufVal.indexOf(opts.groupSeparator)) {
var escapedGroupSeparator = Inputmask.escapeRegex(opts.groupSeparator);
needsRefresh = 0 === bufVal.indexOf(opts.groupSeparator), bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), "");
var radixSplit = bufVal.split(opts.radixPoint);
if (bufVal = "" === opts.radixPoint ? bufVal : radixSplit[0], bufVal !== opts.prefix + "?0" && bufVal.length >= opts.groupSize + opts.prefix.length) for (var reg = new RegExp("([-+]?[\\d?]+)([\\d?]{" + opts.groupSize + "})"); reg.test(bufVal); ) bufVal = bufVal.replace(reg, "$1" + opts.groupSeparator + "$2"),
bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
"" !== opts.radixPoint && radixSplit.length > 1 && (bufVal += opts.radixPoint + radixSplit[1]);
}
for (needsRefresh = bufValOrigin !== bufVal, buffer.length = bufVal.length, i = 0,
l = bufVal.length; l > i; i++) buffer[i] = bufVal.charAt(i);
var newPos = $.inArray("?", buffer);
if (-1 === newPos && charAtPos === opts.radixPoint && (newPos = $.inArray(opts.radixPoint, buffer)),
reformatOnly ? buffer[newPos] = charAtPos : buffer.splice(newPos, 1), !needsRefresh && suffixStripped) for (i = 0,
l = opts.suffix.length; l > i; i++) buffer.push(opts.suffix.charAt(i));
return {
pos: opts.numericInput && isFinite(pos) ? buffer.join("").length - newPos - 1 : newPos,
refreshFromBuffer: needsRefresh,
buffer: opts.numericInput === !0 ? buffer.reverse() : buffer
};
},
onBeforeWrite: function(e, buffer, caretPos, opts) {
if (e && ("blur" === e.type || "checkval" === e.type)) {
var maskedValue = buffer.join(""), processValue = maskedValue.replace(opts.prefix, "");
if (processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""),
"," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")),
isFinite(processValue) && isFinite(opts.min) && parseFloat(processValue) < parseFloat(opts.min)) return $.extend(!0, {
refreshFromBuffer: !0,
buffer: (opts.prefix + opts.min).split("")
}, opts.postFormat((opts.prefix + opts.min).split(""), 0, !0, opts));
if (opts.numericInput !== !0) {
var tmpBufSplit = "" !== opts.radixPoint ? buffer.join("").split(opts.radixPoint) : [ buffer.join("") ], matchRslt = tmpBufSplit[0].match(opts.regex.integerPart(opts)), matchRsltDigits = 2 === tmpBufSplit.length ? tmpBufSplit[1].match(opts.regex.integerNPart(opts)) : void 0;
if (matchRslt) {
matchRslt[0] !== opts.negationSymbol.front + "0" && matchRslt[0] !== opts.negationSymbol.front && "+" !== matchRslt[0] || void 0 !== matchRsltDigits && !matchRsltDigits[0].match(/^0+$/) || buffer.splice(matchRslt.index, 1);
var radixPosition = $.inArray(opts.radixPoint, buffer);
if (-1 !== radixPosition) {
if (isFinite(opts.digits) && !opts.digitsOptional) {
for (var i = 1; i <= opts.digits; i++) (void 0 === buffer[radixPosition + i] || buffer[radixPosition + i] === opts.placeholder.charAt(0)) && (buffer[radixPosition + i] = "0");
return {
refreshFromBuffer: maskedValue !== buffer.join(""),
buffer: buffer
};
}
if (radixPosition === buffer.length - opts.suffix.length - 1) return buffer.splice(radixPosition, 1),
{
refreshFromBuffer: !0,
buffer: buffer
};
}
}
}
}
if (opts.autoGroup) {
var rslt = opts.postFormat(buffer, caretPos - 1, !0, opts);
return rslt.caret = caretPos <= opts.prefix.length ? rslt.pos : rslt.pos + 1, rslt;
}
},
regex: {
integerPart: function(opts) {
return new RegExp("[" + Inputmask.escapeRegex(opts.negationSymbol.front) + "+]?\\d+");
},
integerNPart: function(opts) {
return new RegExp("[\\d" + Inputmask.escapeRegex(opts.groupSeparator) + "]+");
}
},
signHandler: function(chrs, maskset, pos, strict, opts) {
if (!strict && opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) {
var matchRslt = maskset.buffer.join("").match(opts.regex.integerPart(opts));
if (matchRslt && matchRslt[0].length > 0) return maskset.buffer[matchRslt.index] === ("-" === chrs ? "+" : opts.negationSymbol.front) ? "-" === chrs ? "" !== opts.negationSymbol.back ? {
pos: matchRslt.index,
c: opts.negationSymbol.front,
remove: matchRslt.index,
caret: pos,
insert: {
pos: maskset.buffer.length - opts.suffix.length - 1,
c: opts.negationSymbol.back
}
} : {
pos: matchRslt.index,
c: opts.negationSymbol.front,
remove: matchRslt.index,
caret: pos
} : "" !== opts.negationSymbol.back ? {
pos: matchRslt.index,
c: "+",
remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ],
caret: pos
} : {
pos: matchRslt.index,
c: "+",
remove: matchRslt.index,
caret: pos
} : maskset.buffer[matchRslt.index] === ("-" === chrs ? opts.negationSymbol.front : "+") ? "-" === chrs && "" !== opts.negationSymbol.back ? {
remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ],
caret: pos - 1
} : {
remove: matchRslt.index,
caret: pos - 1
} : "-" === chrs ? "" !== opts.negationSymbol.back ? {
pos: matchRslt.index,
c: opts.negationSymbol.front,
caret: pos + 1,
insert: {
pos: maskset.buffer.length - opts.suffix.length,
c: opts.negationSymbol.back
}
} : {
pos: matchRslt.index,
c: opts.negationSymbol.front,
caret: pos + 1
} : {
pos: matchRslt.index,
c: chrs,
caret: pos + 1
};
}
return !1;
},
radixHandler: function(chrs, maskset, pos, strict, opts) {
if (!strict && (-1 !== $.inArray(chrs, [ ",", "." ]) && (chrs = opts.radixPoint),
chrs === opts.radixPoint && void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0))) {
var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join("").match(opts.regex.integerPart(opts));
if (-1 !== radixPos && maskset.validPositions[radixPos]) return maskset.validPositions[radixPos - 1] ? {
caret: radixPos + 1
} : {
pos: integerValue.index,
c: integerValue[0],
caret: radixPos + 1
};
if (!integerValue || "0" === integerValue[0] && integerValue.index + 1 !== pos) return maskset.buffer[integerValue ? integerValue.index : pos] = "0",
{
pos: (integerValue ? integerValue.index : pos) + 1,
c: opts.radixPoint
};
}
return !1;
},
leadingZeroHandler: function(chrs, maskset, pos, strict, opts) {
if (opts.numericInput === !0) {
if ("0" === maskset.buffer[maskset.buffer.length - opts.prefix.length - 1]) return {
pos: pos,
remove: maskset.buffer.length - opts.prefix.length - 1
};
} else {
var matchRslt = maskset.buffer.join("").match(opts.regex.integerNPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
if (matchRslt && !strict && (-1 === radixPosition || radixPosition >= pos)) if (0 === matchRslt[0].indexOf("0")) {
pos < opts.prefix.length && (pos = matchRslt.index);
var _radixPosition = $.inArray(opts.radixPoint, maskset._buffer), digitsMatch = maskset._buffer && maskset.buffer.slice(radixPosition).join("") === maskset._buffer.slice(_radixPosition).join("") || 0 === parseInt(maskset.buffer.slice(radixPosition + 1).join("")), integerMatch = maskset._buffer && maskset.buffer.slice(matchRslt.index, radixPosition).join("") === maskset._buffer.slice(opts.prefix.length, _radixPosition).join("") || "0" === maskset.buffer.slice(matchRslt.index, radixPosition).join("");
if (-1 === radixPosition || digitsMatch && integerMatch) return maskset.buffer.splice(matchRslt.index, 1),
pos = pos > matchRslt.index ? pos - 1 : matchRslt.index, {
pos: pos,
remove: matchRslt.index
};
if (matchRslt.index + 1 === pos || "0" === chrs) return maskset.buffer.splice(matchRslt.index, 1),
pos = matchRslt.index, {
pos: pos,
remove: matchRslt.index
};
} else if ("0" === chrs && pos <= matchRslt.index && matchRslt[0] !== opts.groupSeparator) return !1;
}
return !0;
},
postValidation: function(buffer, opts) {
var isValid = !0, maskedValue = buffer.join(""), processValue = maskedValue.replace(opts.prefix, "");
return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""),
"," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")),
processValue = processValue.replace(new RegExp("^" + Inputmask.escapeRegex(opts.negationSymbol.front)), "-"),
processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.negationSymbol.back) + "$"), ""),
processValue = processValue === opts.negationSymbol.front ? processValue + "0" : processValue,
isFinite(processValue) && (isFinite(opts.max) && (isValid = parseFloat(processValue) <= parseFloat(opts.max)),
isValid && isFinite(opts.min) && (0 >= processValue || processValue.toString().length >= opts.min.toString().length) && (isValid = parseFloat(processValue) >= parseFloat(opts.min),
isValid || (isValid = $.extend(!0, {
refreshFromBuffer: !0,
buffer: (opts.prefix + opts.min).split("")
}, opts.postFormat((opts.prefix + opts.min).split(""), 0, !0, opts)), isValid.refreshFromBuffer = !0))),
isValid;
},
definitions: {
"~": {
validator: function(chrs, maskset, pos, strict, opts) {
var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
if (!isValid && (isValid = opts.radixHandler(chrs, maskset, pos, strict, opts),
!isValid && (isValid = strict ? new RegExp("[0-9" + Inputmask.escapeRegex(opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs),
isValid === !0 && (isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts),
isValid === !0)))) {
var radixPosition = $.inArray(opts.radixPoint, maskset.buffer);
isValid = -1 !== radixPosition && opts.digitsOptional === !1 && pos > radixPosition && !strict ? {
pos: pos,
remove: pos
} : {
pos: pos
};
}
return isValid;
},
cardinality: 1,
prevalidator: null
},
"+": {
validator: function(chrs, maskset, pos, strict, opts) {
var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
return !isValid && (strict && opts.allowMinus && chrs === opts.negationSymbol.front || opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) && (isValid = "-" === chrs ? "" !== opts.negationSymbol.back ? {
pos: pos,
c: "-" === chrs ? opts.negationSymbol.front : "+",
caret: pos + 1,
insert: {
pos: maskset.buffer.length,
c: opts.negationSymbol.back
}
} : {
pos: pos,
c: "-" === chrs ? opts.negationSymbol.front : "+",
caret: pos + 1
} : !0), isValid;
},
cardinality: 1,
prevalidator: null,
placeholder: ""
},
"-": {
validator: function(chrs, maskset, pos, strict, opts) {
var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
return !isValid && strict && opts.allowMinus && chrs === opts.negationSymbol.back && (isValid = !0),
isValid;
},
cardinality: 1,
prevalidator: null,
placeholder: ""
},
":": {
validator: function(chrs, maskset, pos, strict, opts) {
var isValid = opts.signHandler(chrs, maskset, pos, strict, opts);
if (!isValid) {
var radix = "[" + Inputmask.escapeRegex(opts.radixPoint) + ",\\.]";
isValid = new RegExp(radix).test(chrs), isValid && maskset.validPositions[pos] && maskset.validPositions[pos].match.placeholder === opts.radixPoint && (isValid = {
caret: pos + 1
});
}
return isValid ? {
c: opts.radixPoint
} : isValid;
},
cardinality: 1,
prevalidator: null,
placeholder: function(opts) {
return opts.radixPoint;
}
}
},
onUnMask: function(maskedValue, unmaskedValue, opts) {
var processValue = maskedValue.replace(opts.prefix, "");
return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""),
opts.unmaskAsNumber ? (processValue = processValue.replace(Inputmask.escapeRegex.call(this, opts.radixPoint), "."),
Number(processValue)) : processValue;
},
isComplete: function(buffer, opts) {
var maskedValue = buffer.join(""), bufClone = buffer.slice();
if (opts.postFormat(bufClone, 0, !0, opts), bufClone.join("") !== maskedValue) return !1;
var processValue = maskedValue.replace(opts.prefix, "");
return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""),
"," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")),
isFinite(processValue);
},
onBeforeMask: function(initialValue, opts) {
if ("" !== opts.radixPoint && isFinite(initialValue)) initialValue = initialValue.toString().replace(".", opts.radixPoint); else {
var kommaMatches = initialValue.match(/,/g), dotMatches = initialValue.match(/\./g);
dotMatches && kommaMatches ? dotMatches.length > kommaMatches.length ? (initialValue = initialValue.replace(/\./g, ""),
initialValue = initialValue.replace(",", opts.radixPoint)) : kommaMatches.length > dotMatches.length ? (initialValue = initialValue.replace(/,/g, ""),
initialValue = initialValue.replace(".", opts.radixPoint)) : initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "") : initialValue = initialValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), "");
}
if (0 === opts.digits && (-1 !== initialValue.indexOf(".") ? initialValue = initialValue.substring(0, initialValue.indexOf(".")) : -1 !== initialValue.indexOf(",") && (initialValue = initialValue.substring(0, initialValue.indexOf(",")))),
"" !== opts.radixPoint && isFinite(opts.digits) && -1 !== initialValue.indexOf(opts.radixPoint)) {
var valueParts = initialValue.split(opts.radixPoint), decPart = valueParts[1].match(new RegExp("\\d*"))[0];
if (parseInt(opts.digits) < decPart.toString().length) {
var digitsFactor = Math.pow(10, parseInt(opts.digits));
initialValue = initialValue.replace(Inputmask.escapeRegex(opts.radixPoint), "."),
initialValue = Math.round(parseFloat(initialValue) * digitsFactor) / digitsFactor,
initialValue = initialValue.toString().replace(".", opts.radixPoint);
}
}
return initialValue.toString();
},
canClearPosition: function(maskset, position, lvp, strict, opts) {
var positionInput = maskset.validPositions[position].input, canClear = positionInput !== opts.radixPoint || null !== maskset.validPositions[position].match.fn && opts.decimalProtect === !1 || isFinite(positionInput) || position === lvp || positionInput === opts.groupSeparator || positionInput === opts.negationSymbol.front || positionInput === opts.negationSymbol.back;
if (canClear && isFinite(positionInput)) {
var matchRslt, radixPos = $.inArray(opts.radixPoint, maskset.buffer), radixInjection = !1;
if (void 0 === maskset.validPositions[radixPos] && (maskset.validPositions[radixPos] = {
input: opts.radixPoint
}, radixInjection = !0), !strict && maskset.buffer) {
matchRslt = maskset.buffer.join("").substr(0, position).match(opts.regex.integerNPart(opts));
var pos = position + 1, isNull = null == matchRslt || 0 === parseInt(matchRslt[0].replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""));
if (isNull) for (;maskset.validPositions[pos] && (maskset.validPositions[pos].input === opts.groupSeparator || "0" === maskset.validPositions[pos].input); ) delete maskset.validPositions[pos],
pos++;
}
var buffer = [];
for (var vp in maskset.validPositions) void 0 !== maskset.validPositions[vp].input && buffer.push(maskset.validPositions[vp].input);
if (radixInjection && delete maskset.validPositions[radixPos], radixPos > 0 && (matchRslt = buffer.join("").match(opts.regex.integerNPart(opts)),
matchRslt && radixPos >= position)) if (0 === matchRslt[0].indexOf("0")) canClear = matchRslt.index !== position || "0" === opts.placeholder; else {
var intPart = parseInt(matchRslt[0].replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""));
10 > intPart && maskset.validPositions[position] && "0" !== opts.placeholder && (maskset.validPositions[position].input = "0",
maskset.p = opts.prefix.length + 1, canClear = !1);
}
}
return canClear;
},
onKeyDown: function(e, buffer, caretPos, opts) {
var $input = $(this);
if (e.ctrlKey) switch (e.keyCode) {
case Inputmask.keyCode.UP:
$input.val(parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step)), $input.triggerHandler("setvalue.inputmask");
break;
case Inputmask.keyCode.DOWN:
$input.val(parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step)), $input.triggerHandler("setvalue.inputmask");
}
}
},
currency: {
prefix: "$ ",
groupSeparator: ",",
alias: "numeric",
placeholder: "0",
autoGroup: !0,
digits: 2,
digitsOptional: !1,
clearMaskOnLostFocus: !1
},
decimal: {
alias: "numeric"
},
integer: {
alias: "numeric",
digits: 0,
radixPoint: ""
},
percentage: {
alias: "numeric",
digits: 2,
radixPoint: ".",
placeholder: "0",
autoGroup: !1,
min: 0,
max: 100,
suffix: " %",
allowPlus: !1,
allowMinus: !1
}
}), Inputmask;
}); | mit |
maurer/tiamat | samples/Juliet/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_open_33.cpp | 3863 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_open_33.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-33.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sinks: open
* BadSink : Open the file named in data using open()
* Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#define OPEN _open
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif
namespace CWE36_Absolute_Path_Traversal__char_file_open_33
{
#ifndef OMITBAD
void bad()
{
char * data;
char * &dataRef = data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
{
char * data = dataRef;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char * &dataRef = data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
{
char * data = dataRef;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_file_open_33; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| mit |
SlexAxton/abusing-preprocessor-asts | example/app.js | 1469 |
/**
* Module dependencies.
*/
var express = require('express')
, http = require('http')
, fs = require('fs')
, path = require('path');
// Pull out our custom preprocessor
var mycssparser = require('./mycssparser');
// Boring Express stuff
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3001);
app.use(express.favicon());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
// Return our index.html file on the root url
app.get('/', function(req, res) {
// Set headers for good luck.
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(fs.readFileSync('./index.html', 'utf8'));
});
// Set the style data for our
// variables in our preprocessor
var styleData = {
"bg-color": "#1C3146",
"border-color": "#425466",
"app-width": "960px",
"big-border-radius": "30px",
"header-color": "#FF8F4F"
};
// Generate CSS on the fly when we hit it
app.get(/(.*)\.css$/, function(req, res) {
res.setHeader('Content-Type', 'text/css; charset=utf-8');
res.end(mycssparser.parse(__dirname + req.params + '.mycss', styleData).css);
});
// Generate the CSS data when we hit it
app.get(/(.*)\.css\.json$/, function(req, res) {
res.json(mycssparser.parse(__dirname + req.params + '.mycss', styleData).data);
});
// Serve the app
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
| mit |
vincent03460/fxcmiscc | lib/symfony/helper/DateHelper.php | 4490 | <?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* DateHelper.
*
* @package symfony
* @subpackage helper
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: DateHelper.php 3815 2007-04-18 16:44:39Z fabien $
*/
function format_daterange($start_date, $end_date, $format = 'd', $full_text, $start_text, $end_text, $culture = null, $charset = null)
{
if ($start_date != '' && $end_date != '')
{
return sprintf($full_text, format_date($start_date, $format, $culture, $charset), format_date($end_date, $format, $culture, $charset));
}
else if ($start_date != '')
{
return sprintf($start_text, format_date($start_date, $format, $culture, $charset));
}
else if ($end_date != '')
{
return sprintf($end_text, format_date($end_date, $format, $culture, $charset));
}
}
function format_date($date, $format = 'd', $culture = null, $charset = null)
{
static $dateFormats = array();
if (is_null($date))
{
return null;
}
if (!$culture)
{
$culture = sfContext::getInstance()->getUser()->getCulture();
}
if (!$charset)
{
$charset = sfConfig::get('sf_charset');
}
if (!isset($dateFormats[$culture]))
{
$dateFormats[$culture] = new sfDateFormat($culture);
}
return $dateFormats[$culture]->format($date, $format, null, $charset);
}
function format_datetime($date, $format = 'F', $culture = null, $charset = null)
{
return format_date($date, $format, $culture, $charset);
}
function distance_of_time_in_words($from_time, $to_time = null, $include_seconds = false)
{
$to_time = $to_time? $to_time: time();
$distance_in_minutes = floor(abs($to_time - $from_time) / 60);
$distance_in_seconds = floor(abs($to_time - $from_time));
$string = '';
$parameters = array();
if ($distance_in_minutes <= 1)
{
if (!$include_seconds)
{
$string = $distance_in_minutes == 0 ? 'less than a minute' : '1 minute';
}
else
{
if ($distance_in_seconds <= 5)
{
$string = 'less than 5 seconds';
}
else if ($distance_in_seconds >= 6 && $distance_in_seconds <= 10)
{
$string = 'less than 10 seconds';
}
else if ($distance_in_seconds >= 11 && $distance_in_seconds <= 20)
{
$string = 'less than 20 seconds';
}
else if ($distance_in_seconds >= 21 && $distance_in_seconds <= 40)
{
$string = 'half a minute';
}
else if ($distance_in_seconds >= 41 && $distance_in_seconds <= 59)
{
$string = 'less than a minute';
}
else
{
$string = '1 minute';
}
}
}
else if ($distance_in_minutes >= 2 && $distance_in_minutes <= 44)
{
$string = '%minutes% minutes';
$parameters['%minutes%'] = $distance_in_minutes;
}
else if ($distance_in_minutes >= 45 && $distance_in_minutes <= 89)
{
$string = 'about 1 hour';
}
else if ($distance_in_minutes >= 90 && $distance_in_minutes <= 1439)
{
$string = 'about %hours% hours';
$parameters['%hours%'] = round($distance_in_minutes / 60);
}
else if ($distance_in_minutes >= 1440 && $distance_in_minutes <= 2879)
{
$string = '1 day';
}
else if ($distance_in_minutes >= 2880 && $distance_in_minutes <= 43199)
{
$string = '%days% days';
$parameters['%days%'] = round($distance_in_minutes / 1440);
}
else if ($distance_in_minutes >= 43200 && $distance_in_minutes <= 86399)
{
$string = 'about 1 month';
}
else if ($distance_in_minutes >= 86400 && $distance_in_minutes <= 525959)
{
$string = '%months% months';
$parameters['%months%'] = round($distance_in_minutes / 43200);
}
else if ($distance_in_minutes >= 525960 && $distance_in_minutes <= 1051919)
{
$string = 'about 1 year';
}
else
{
$string = 'over %years% years';
$parameters['%years%'] = round($distance_in_minutes / 525960);
}
if (sfConfig::get('sf_i18n'))
{
use_helper('I18N');
return __($string, $parameters);
}
else
{
return strtr($string, $parameters);
}
}
// Like distance_of_time_in_words, but where to_time is fixed to time()
function time_ago_in_words($from_time, $include_seconds = false)
{
return distance_of_time_in_words($from_time, time(), $include_seconds);
}
| mit |
weckx/ZfcDatagrid | src/ZfcDatagrid/Column/Action/AbstractAction.php | 7843 | <?php
namespace ZfcDatagrid\Column\Action;
use ZfcDatagrid\Column;
use ZfcDatagrid\Column\AbstractColumn;
use ZfcDatagrid\Filter;
abstract class AbstractAction
{
const ROW_ID_PLACEHOLDER = ':rowId:';
/**
*
* @var \ZfcDatagrid\Column\AbstractColumn[]
*/
protected $linkColumnPlaceholders = [];
/**
*
* @var array
*/
protected $htmlAttributes = [];
/**
*
* @var string
*/
protected $showOnValueOperator = 'OR';
/**
*
* @var array
*/
protected $showOnValues = [];
public function __construct()
{
$this->setLink('#');
}
/**
* Set the link
*
* @param string $href
*/
public function setLink($href)
{
$this->setAttribute('href', $href);
}
/**
*
* @return string
*/
public function getLink()
{
return $this->getAttribute('href');
}
/**
* This is needed public for rowClickAction...
*
* @param array $row
* @return string
*/
public function getLinkReplaced(array $row)
{
$link = $this->getLink();
// Replace placeholders
if (strpos($this->getLink(), self::ROW_ID_PLACEHOLDER) !== false) {
$id = '';
if (isset($row['idConcated'])) {
$id = $row['idConcated'];
}
$link = str_replace(self::ROW_ID_PLACEHOLDER, $id, $link);
}
foreach ($this->getLinkColumnPlaceholders() as $col) {
$link = str_replace(':' . $col->getUniqueId() . ':', $row[$col->getUniqueId()], $link);
}
return $link;
}
/**
* Get the column row value placeholder
* $action->setLink('/myLink/something/id/'.$action->getRowIdPlaceholder().'/something/'.$action->getColumnRowPlaceholder($myCol));
*
* @param AbstractColumn $col
* @return string
*/
public function getColumnValuePlaceholder(AbstractColumn $col)
{
$this->linkColumnPlaceholders[] = $col;
return ':' . $col->getUniqueId() . ':';
}
/**
*
* @return \ZfcDatagrid\Column\AbstractColumn[]
*/
public function getLinkColumnPlaceholders()
{
return $this->linkColumnPlaceholders;
}
/**
* Returns the rowId placeholder
* Can be used e.g.
* $action->setLink('/myLink/something/id/'.$action->getRowIdPlaceholder());
*
* @return string
*/
public function getRowIdPlaceholder()
{
return self::ROW_ID_PLACEHOLDER;
}
/**
* Set a HTML attributes
*
* @param string $name
* @param string $value
*/
public function setAttribute($name, $value)
{
$this->htmlAttributes[$name] = (string) $value;
}
/**
* Get a HTML attribute
*
* @param string $name
* @return string
*/
public function getAttribute($name)
{
if (isset($this->htmlAttributes[$name])) {
return $this->htmlAttributes[$name];
}
return '';
}
/**
* Removes an HTML attribute
*
* @param string $name
*/
public function removeAttribute($name)
{
if (isset($this->htmlAttributes[$name])) {
unset($this->htmlAttributes[$name]);
}
}
/**
* Get all HTML attributes
*
* @return array
*/
public function getAttributes()
{
return $this->htmlAttributes;
}
/**
* Get the string version of the attributes
*
* @param array $row
* @return string
*/
protected function getAttributesString(array $row)
{
$attributes = [];
foreach ($this->getAttributes() as $attrKey => $attrValue) {
if ('href' === $attrKey) {
$attrValue = $this->getLinkReplaced($row);
}
$attributes[] = $attrKey . '="' . $attrValue . '"';
}
return implode(' ', $attributes);
}
/**
* Set the title attribute
*
* @param string $name
*/
public function setTitle($name)
{
$this->setAttribute('title', $name);
}
/**
* Get the title attribute
*
* @return string
*/
public function getTitle()
{
return $this->getAttribute('title');
}
/**
* Add a css class
*
* @param string $className
*/
public function addClass($className)
{
$attr = $this->getAttribute('class');
if ($attr != '') {
$attr .= ' ';
}
$attr .= (string) $className;
$this->setAttribute('class', $attr);
}
/**
* Display the values with AND or OR (if multiple showOnValues are defined)
*
* @param string $operator
*/
public function setShowOnValueOperator($operator = 'OR')
{
if ($operator != 'AND' && $operator != 'OR') {
throw new \InvalidArgumentException('not allowed operator: "' . $operator . '" (AND / OR is allowed)');
}
$this->showOnValueOperator = (string) $operator;
}
/**
* Get the show on value operator, e.g.
* OR, AND
*
* @return string
*/
public function getShowOnValueOperator()
{
return $this->showOnValueOperator;
}
/**
* Show this action only on the values defined
*
* @param Column\AbstractColumn $col
* @param string $value
* @param string $comparison
*/
public function addShowOnValue(Column\AbstractColumn $col, $value = null, $comparison = Filter::EQUAL)
{
$this->showOnValues[] = [
'column' => $col,
'value' => $value,
'comparison' => $comparison,
];
}
/**
*
* @return array
*/
public function getShowOnValues()
{
return $this->showOnValues;
}
/**
*
* @return boolean
*/
public function hasShowOnValues()
{
if (count($this->showOnValues) > 0) {
return true;
}
return false;
}
/**
* Display this action on this row?
*
* @param array $row
* @return boolean
*/
public function isDisplayed(array $row)
{
if ($this->hasShowOnValues() === false) {
return true;
}
$isDisplayed = false;
foreach ($this->getShowOnValues() as $rule) {
$value = '';
if (isset($row[$rule['column']->getUniqueId()])) {
$value = $row[$rule['column']->getUniqueId()];
}
if ($rule['value'] instanceof AbstractColumn) {
if (isset($row[$rule['value']->getUniqueId()])) {
$ruleValue = $row[$rule['value']->getUniqueId()];
} else {
$ruleValue = '';
}
} else {
$ruleValue = $rule['value'];
}
$isDisplayedMatch = Filter::isApply($value, $ruleValue, $rule['comparison']);
if ($this->getShowOnValueOperator() == 'OR' && true === $isDisplayedMatch) {
// For OR one match is enough
return true;
} elseif ($this->getShowOnValueOperator() == 'AND' && false === $isDisplayedMatch) {
return false;
} else {
$isDisplayed = $isDisplayedMatch;
}
}
return $isDisplayed;
}
/**
* Get the HTML from the type
*
* @return string
*/
abstract protected function getHtmlType();
/**
*
* @param array $row
* @return string
*/
public function toHtml(array $row)
{
return '<a ' . $this->getAttributesString($row) . '>' . $this->getHtmlType() . '</a>';
}
}
| mit |
Mitali-Sodhi/CodeLingo | Dataset/cpp/FutexTest.cpp | 1500 | /*
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/detail/Futex.h"
#include "folly/test/DeterministicSchedule.h"
#include <thread>
#include <gflags/gflags.h>
#include <gtest/gtest.h>
using namespace folly::detail;
using namespace folly::test;
typedef DeterministicSchedule DSched;
template <template<typename> class Atom>
void run_basic_tests() {
Futex<Atom> f(0);
EXPECT_FALSE(f.futexWait(1));
EXPECT_EQ(f.futexWake(), 0);
auto thr = DSched::thread([&]{
EXPECT_TRUE(f.futexWait(0));
});
while (f.futexWake() != 1) {
std::this_thread::yield();
}
DSched::join(thr);
}
TEST(Futex, basic_live) {
run_basic_tests<std::atomic>();
}
TEST(Futex, basic_deterministic) {
DSched sched(DSched::uniform(0));
run_basic_tests<DeterministicAtomic>();
}
int main(int argc, char ** argv) {
testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
return RUN_ALL_TESTS();
}
| mit |
vkuskov/Entitas-CSharp | PerformanceTests/PerformanceTests/Entity/EntityReplaceComponent.cs | 1150 | using Entitas;
using System.Collections.Generic;
public class EntityReplaceComponent : IPerformanceTest {
const int n = 1000000;
Pool _pool;
Entity _e;
public void Before() {
_pool = Helper.CreatePool();
_pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentA }));
_pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentB }));
_pool.GetGroup(Matcher.AllOf(new [] { CP.ComponentC }));
_pool.GetGroup(Matcher.AllOf(new [] {
CP.ComponentA,
CP.ComponentB
}));
_pool.GetGroup(Matcher.AllOf(new [] {
CP.ComponentA,
CP.ComponentC
}));
_pool.GetGroup(Matcher.AllOf(new [] {
CP.ComponentB,
CP.ComponentC
}));
_pool.GetGroup(Matcher.AllOf(new [] {
CP.ComponentA,
CP.ComponentB,
CP.ComponentC
}));
_e = _pool.CreateEntity();
_e.AddComponent(CP.ComponentA, new ComponentA());
}
public void Run() {
for (int i = 0; i < n; i++) {
_e.ReplaceComponent(CP.ComponentA, new ComponentA());
}
}
}
| mit |
iocast/vectorformats | vectorformats/formats/ogr.py | 7000 | import simplejson
from ..feature import Feature
from .format import Format
try:
import osgeo.ogr as ogr
except ImportError:
import ogr
class OGR(Format):
"""OGR reading and writing."""
ds = None
driver = "Memory"
dsname = "VectorFormats_output"
layername = "features"
save_on_encode = False
def encode(self, features, **kwargs):
self.ds = ogr.GetDriverByName(self.driver).CreateDataSource(self.dsname)
layer = self.ds.CreateLayer(self.layername)
props = []
for feature in features:
for prop, value in feature.properties.items():
if not prop: continue
if prop not in props:
props.append(prop)
prop = str(prop)
defn = ogr.FieldDefn(prop)
defn.SetWidth(len(value))
layer.CreateField(defn)
for feature in features:
f = ogr.Feature(feature_def=layer.GetLayerDefn())
for prop, value in feature.properties.items():
prop = str(prop)
if isinstance(value, unicode):
value = value.encode("utf-8", "replace")
f.SetField(prop, value)
g = self.CreateGeometryFromJson(simplejson.dumps(feature.geometry))
f.SetGeometryDirectly(g)
layer.CreateFeature(f)
if self.save_on_encode:
layer.SyncToDisk()
return layer
def decode(self, layer):
features = []
layer.ResetReading()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFID()
geometry = self.ExportToJson(feature.GetGeometryRef())
props = {}
for i in range(feature.GetFieldCount()):
props[feature.GetFieldDefnRef(i).GetName()] = feature.GetFieldAsString(i)
features.append(Feature(id, geometry, props))
feature = layer.GetNextFeature()
return features
def CreateGeometryFromJson(self, input):
try:
input['type']
except TypeError:
try:
import simplejson
except ImportError:
raise ImportError, "You must have 'simplejson' installed to be able to use this functionality"
input = simplejson.loads(input)
types = { 'Point': ogr.wkbPoint,
'LineString': ogr.wkbLineString,
'Polygon': ogr.wkbPolygon,
'MultiPoint': ogr.wkbMultiPoint,
'MultiLineString': ogr.wkbMultiLineString,
'MultiPolygon': ogr.wkbMultiPolygon,
'GeometryCollection': ogr.wkbGeometryCollection
}
type = input['type']
gtype = types[type]
geometry = ogr.Geometry(type=gtype)
coordinates = input['coordinates']
if type == 'Point':
geometry.AddPoint_2D(coordinates[0], coordinates[1])
elif type == 'MultiPoint':
for point in coordinates:
gring = ogr.Geometry(type=ogr.wkbPoint)
gring.AddPoint_2D(point[0], point[1])
geometry.AddGeometry(gring)
elif type == 'LineString':
for coordinate in coordinates:
geometry.AddPoint_2D(coordinate[0], coordinate[1])
elif type == 'MultiLineString':
for ring in coordinates:
gring = ogr.Geometry(type=ogr.wkbLineString)
for coordinate in ring:
gring.AddPoint_2D(coordinate[0], coordinate[1])
geometry.AddGeometry(gring)
elif type == 'Polygon':
for ring in coordinates:
gring = ogr.Geometry(type=ogr.wkbLinearRing)
for coordinate in ring:
gring.AddPoint_2D(coordinate[0], coordinate[1])
geometry.AddGeometry(gring)
elif type == 'MultiPolygon':
for poly in coordinates:
gpoly = ogr.Geometry(type=ogr.wkbPolygon)
for ring in poly:
gring = ogr.Geometry(type=ogr.wkbLinearRing)
for coordinate in ring:
gring.AddPoint_2D(coordinate[0], coordinate[1])
gpoly.AddGeometry(gring)
geometry.AddGeometry(gpoly)
return geometry
def ExportToJson(self, geometry):
def get_coordinates(geometry):
gtype = geometry.GetGeometryType()
geom_count = geometry.GetGeometryCount()
coordinates = []
if gtype == ogr.wkbPoint or gtype == ogr.wkbPoint25D:
return [geometry.GetX(0), geometry.GetY(0)]
if gtype == ogr.wkbMultiPoint or gtype == ogr.wkbMultiPoint25D:
geom_count = geometry.GetGeometryCount()
for g in range(geom_count):
geom = geometry.GetGeometryRef(g)
coordinates.append(get_coordinates(geom))
return coordinates
if gtype == ogr.wkbLineString or gtype == ogr.wkbLineString25D:
points = []
point_count = geometry.GetPointCount()
for i in range(point_count):
points.append([geometry.GetX(i), geometry.GetY(i)])
return points
if gtype == ogr.wkbMultiLineString or gtype == ogr.wkbMultiLineString25D:
coordinates = []
geom_count = geometry.GetGeometryCount()
for g in range(geom_count):
geom = geometry.GetGeometryRef(g)
coordinates.append(get_coordinates(geom))
return coordinates
if gtype == ogr.wkbPolygon or gtype == ogr.wkbPolygon25D:
geom = geometry.GetGeometryRef(0)
coordinates = get_coordinates(geom)
return [coordinates]
if gtype == ogr.wkbMultiPolygon or gtype == ogr.wkbMultiPolygon25D:
coordinates = []
geom_count = geometry.GetGeometryCount()
for g in range(geom_count):
geom = geometry.GetGeometryRef(g)
coordinates.append(get_coordinates(geom))
return coordinates
types = { ogr.wkbPoint:'Point',
ogr.wkbLineString: 'LineString',
ogr.wkbPolygon: 'Polygon',
ogr.wkbMultiPoint: 'MultiPoint',
ogr.wkbMultiLineString: 'MultiLineString',
ogr.wkbMultiPolygon: 'MultiPolygon',
ogr.wkbGeometryCollection: 'GeometryCollection'
}
output = {'type': types[geometry.GetGeometryType()],
'coordinates': get_coordinates(geometry)}
return output
| mit |
SvenVandenbrande/Emby.Plugins | XmlMetadata/Savers/XmlSaverHelpers.cs | 27617 | //using MediaBrowser.Controller.Configuration;
//using MediaBrowser.Controller.Entities;
//using MediaBrowser.Controller.Entities.Movies;
//using MediaBrowser.Controller.Entities.TV;
//using MediaBrowser.Controller.Library;
//using MediaBrowser.Controller.Persistence;
//using MediaBrowser.Controller.Playlists;
//using MediaBrowser.Model.Entities;
//using System;
//using System.Collections.Generic;
//using System.Globalization;
//using System.IO;
//using System.Linq;
//using System.Security;
//using System.Text;
//using System.Xml;
//using MediaBrowser.Model.IO;
//namespace XmlMetadata
//{
// /// <summary>
// /// Class XmlHelpers
// /// </summary>
// public static class XmlSaverHelpers
// {
// private static readonly Dictionary<string, string> CommonTags = new[] {
// "Added",
// "AspectRatio",
// "AudioDbAlbumId",
// "AudioDbArtistId",
// "AwardSummary",
// "BirthDate",
// "Budget",
// // Deprecated. No longer saving in this field.
// "certification",
// "Chapters",
// "ContentRating",
// "Countries",
// "CustomRating",
// "CriticRating",
// "CriticRatingSummary",
// "DeathDate",
// "DisplayOrder",
// "EndDate",
// "Genres",
// "Genre",
// "GamesDbId",
// // Deprecated. No longer saving in this field.
// "IMDB_ID",
// "IMDB",
// // Deprecated. No longer saving in this field.
// "IMDbId",
// "Language",
// "LocalTitle",
// "OriginalTitle",
// "LockData",
// "LockedFields",
// "Format3D",
// "Metascore",
// // Deprecated. No longer saving in this field.
// "MPAARating",
// "MPAADescription",
// "MusicBrainzArtistId",
// "MusicBrainzAlbumArtistId",
// "MusicBrainzAlbumId",
// "MusicBrainzReleaseGroupId",
// // Deprecated. No longer saving in this field.
// "MusicbrainzId",
// "Overview",
// "ShortOverview",
// "Persons",
// "PlotKeywords",
// "PremiereDate",
// "ProductionYear",
// "Rating",
// "Revenue",
// "RottenTomatoesId",
// "RunningTime",
// // Deprecated. No longer saving in this field.
// "Runtime",
// "SortTitle",
// "Studios",
// "Tags",
// // Deprecated. No longer saving in this field.
// "TagLine",
// "Taglines",
// "TMDbCollectionId",
// "TMDbId",
// // Deprecated. No longer saving in this field.
// "Trailer",
// "Trailers",
// "TVcomId",
// "TvDbId",
// "Type",
// "TVRageId",
// "VoteCount",
// "Website",
// "Zap2ItId",
// "CollectionItems",
// "PlaylistItems",
// "Shares"
// }.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
// /// <summary>
// /// The us culture
// /// </summary>
// private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
// /// <summary>
// /// Saves the specified XML.
// /// </summary>
// /// <param name="xml">The XML.</param>
// /// <param name="path">The path.</param>
// /// <param name="xmlTagsUsed">The XML tags used.</param>
// public static void Save(StringBuilder xml, string path, List<string> xmlTagsUsed, IServerConfigurationManager config, IFileSystem fileSystem)
// {
// if (fileSystem.FileExists(path))
// {
// var position = xml.ToString().LastIndexOf("</", StringComparison.OrdinalIgnoreCase);
// xml.Insert(position, GetCustomTags(path, xmlTagsUsed));
// }
// var xmlDocument = new XmlDocument();
// xmlDocument.LoadXml(xml.ToString());
// //Add the new node to the document.
// xmlDocument.InsertBefore(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xmlDocument.DocumentElement);
// fileSystem.CreateDirectory(Path.GetDirectoryName(path));
// var wasHidden = false;
// var file = new FileInfo(path);
// // This will fail if the file is hidden
// if (file.Exists)
// {
// if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
// {
// file.Attributes &= ~FileAttributes.Hidden;
// wasHidden = true;
// }
// }
// using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
// {
// using (var streamWriter = new StreamWriter(filestream, Encoding.UTF8))
// {
// xmlDocument.Save(streamWriter);
// }
// }
// if (wasHidden || config.Configuration.SaveMetadataHidden)
// {
// file.Refresh();
// // Add back the attribute
// file.Attributes |= FileAttributes.Hidden;
// }
// }
// /// <summary>
// /// Gets the custom tags.
// /// </summary>
// /// <param name="path">The path.</param>
// /// <param name="xmlTagsUsed">The XML tags used.</param>
// /// <returns>System.String.</returns>
// private static string GetCustomTags(string path, List<string> xmlTagsUsed)
// {
// var settings = new XmlReaderSettings
// {
// CheckCharacters = false,
// IgnoreProcessingInstructions = true,
// IgnoreComments = true,
// ValidationType = ValidationType.None
// };
// var builder = new StringBuilder();
// using (var streamReader = new StreamReader(path, Encoding.UTF8))
// {
// // Use XmlReader for best performance
// using (var reader = XmlReader.Create(streamReader, settings))
// {
// reader.MoveToContent();
// // Loop through each element
// while (reader.Read())
// {
// if (reader.NodeType == XmlNodeType.Element)
// {
// var name = reader.Name;
// if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
// {
// builder.AppendLine(reader.ReadOuterXml());
// }
// else
// {
// reader.Skip();
// }
// }
// }
// }
// }
// return builder.ToString();
// }
// /// <summary>
// /// Adds the common nodes.
// /// </summary>
// /// <param name="item">The item.</param>
// /// <param name="builder">The builder.</param>
// public static void AddCommonNodes(BaseItem item, ILibraryManager libraryManager, StringBuilder builder)
// {
// if (!string.IsNullOrEmpty(item.OfficialRating))
// {
// builder.Append("<ContentRating>" + SecurityElement.Escape(item.OfficialRating) + "</ContentRating>");
// }
// if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
// {
// builder.Append("<MPAADescription>" + SecurityElement.Escape(item.OfficialRatingDescription) + "</MPAADescription>");
// }
// builder.Append("<Added>" + SecurityElement.Escape(item.DateCreated.ToLocalTime().ToString("G")) + "</Added>");
// builder.Append("<LockData>" + item.IsLocked.ToString().ToLower() + "</LockData>");
// if (item.LockedFields.Count > 0)
// {
// builder.Append("<LockedFields>" + string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()) + "</LockedFields>");
// }
// if (!string.IsNullOrEmpty(item.DisplayMediaType))
// {
// builder.Append("<Type>" + SecurityElement.Escape(item.DisplayMediaType) + "</Type>");
// }
// if (item.CriticRating.HasValue)
// {
// builder.Append("<CriticRating>" + SecurityElement.Escape(item.CriticRating.Value.ToString(UsCulture)) + "</CriticRating>");
// }
// if (!string.IsNullOrEmpty(item.CriticRatingSummary))
// {
// builder.Append("<CriticRatingSummary><![CDATA[" + item.CriticRatingSummary + "]]></CriticRatingSummary>");
// }
// if (!string.IsNullOrEmpty(item.Overview))
// {
// builder.Append("<Overview><![CDATA[" + item.Overview + "]]></Overview>");
// }
// if (!string.IsNullOrEmpty(item.OriginalTitle))
// {
// builder.Append("<OriginalTitle>" + SecurityElement.Escape(item.OriginalTitle) + "</OriginalTitle>");
// }
// if (!string.IsNullOrEmpty(item.ShortOverview))
// {
// builder.Append("<ShortOverview><![CDATA[" + item.ShortOverview + "]]></ShortOverview>");
// }
// if (!string.IsNullOrEmpty(item.CustomRating))
// {
// builder.Append("<CustomRating>" + SecurityElement.Escape(item.CustomRating) + "</CustomRating>");
// }
// if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
// {
// builder.Append("<LocalTitle>" + SecurityElement.Escape(item.Name) + "</LocalTitle>");
// }
// if (!string.IsNullOrEmpty(item.ForcedSortName))
// {
// builder.Append("<SortTitle>" + SecurityElement.Escape(item.ForcedSortName) + "</SortTitle>");
// }
// if (item.PremiereDate.HasValue)
// {
// if (item is Person)
// {
// builder.Append("<BirthDate>" + SecurityElement.Escape(item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd")) + "</BirthDate>");
// }
// else if (!(item is Episode))
// {
// builder.Append("<PremiereDate>" + SecurityElement.Escape(item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd")) + "</PremiereDate>");
// }
// }
// if (item.EndDate.HasValue)
// {
// if (item is Person)
// {
// builder.Append("<DeathDate>" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "</DeathDate>");
// }
// else if (!(item is Episode))
// {
// builder.Append("<EndDate>" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "</EndDate>");
// }
// }
// var hasTrailers = item as IHasTrailers;
// if (hasTrailers != null)
// {
// if (hasTrailers.RemoteTrailers.Count > 0)
// {
// builder.Append("<Trailers>");
// foreach (var trailer in hasTrailers.RemoteTrailers)
// {
// builder.Append("<Trailer>" + SecurityElement.Escape(trailer.Url) + "</Trailer>");
// }
// builder.Append("</Trailers>");
// }
// }
// var hasDisplayOrder = item as IHasDisplayOrder;
// if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
// {
// builder.Append("<DisplayOrder>" + SecurityElement.Escape(hasDisplayOrder.DisplayOrder) + "</DisplayOrder>");
// }
// var hasMetascore = item as IHasMetascore;
// if (hasMetascore != null && hasMetascore.Metascore.HasValue)
// {
// builder.Append("<Metascore>" + SecurityElement.Escape(hasMetascore.Metascore.Value.ToString(UsCulture)) + "</Metascore>");
// }
// var hasAwards = item as IHasAwards;
// if (hasAwards != null && !string.IsNullOrEmpty(hasAwards.AwardSummary))
// {
// builder.Append("<AwardSummary>" + SecurityElement.Escape(hasAwards.AwardSummary) + "</AwardSummary>");
// }
// var hasBudget = item as IHasBudget;
// if (hasBudget != null)
// {
// if (hasBudget.Budget.HasValue)
// {
// builder.Append("<Budget>" + SecurityElement.Escape(hasBudget.Budget.Value.ToString(UsCulture)) + "</Budget>");
// }
// if (hasBudget.Revenue.HasValue)
// {
// builder.Append("<Revenue>" + SecurityElement.Escape(hasBudget.Revenue.Value.ToString(UsCulture)) + "</Revenue>");
// }
// }
// if (item.CommunityRating.HasValue)
// {
// builder.Append("<Rating>" + SecurityElement.Escape(item.CommunityRating.Value.ToString(UsCulture)) + "</Rating>");
// }
// if (item.VoteCount.HasValue)
// {
// builder.Append("<VoteCount>" + SecurityElement.Escape(item.VoteCount.Value.ToString(UsCulture)) + "</VoteCount>");
// }
// if (item.ProductionYear.HasValue && !(item is Person))
// {
// builder.Append("<ProductionYear>" + SecurityElement.Escape(item.ProductionYear.Value.ToString(UsCulture)) + "</ProductionYear>");
// }
// if (!string.IsNullOrEmpty(item.HomePageUrl))
// {
// builder.Append("<Website>" + SecurityElement.Escape(item.HomePageUrl) + "</Website>");
// }
// var hasAspectRatio = item as IHasAspectRatio;
// if (hasAspectRatio != null)
// {
// if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
// {
// builder.Append("<AspectRatio>" + SecurityElement.Escape(hasAspectRatio.AspectRatio) + "</AspectRatio>");
// }
// }
// if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
// {
// builder.Append("<Language>" + SecurityElement.Escape(item.PreferredMetadataLanguage) + "</Language>");
// }
// if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
// {
// builder.Append("<CountryCode>" + SecurityElement.Escape(item.PreferredMetadataCountryCode) + "</CountryCode>");
// }
// // Use original runtime here, actual file runtime later in MediaInfo
// var runTimeTicks = item.RunTimeTicks;
// if (runTimeTicks.HasValue)
// {
// var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
// builder.Append("<RunningTime>" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "</RunningTime>");
// }
// var imdb = item.GetProviderId(MetadataProviders.Imdb);
// if (!string.IsNullOrEmpty(imdb))
// {
// builder.Append("<IMDB>" + SecurityElement.Escape(imdb) + "</IMDB>");
// }
// var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
// if (!string.IsNullOrEmpty(tmdb))
// {
// builder.Append("<TMDbId>" + SecurityElement.Escape(tmdb) + "</TMDbId>");
// }
// if (!(item is Series))
// {
// var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
// if (!string.IsNullOrEmpty(tvdb))
// {
// builder.Append("<TvDbId>" + SecurityElement.Escape(tvdb) + "</TvDbId>");
// }
// }
// var externalId = item.GetProviderId(MetadataProviders.Tvcom);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<TVcomId>" + SecurityElement.Escape(externalId) + "</TVcomId>");
// }
// externalId = item.GetProviderId(MetadataProviders.RottenTomatoes);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<RottenTomatoesId>" + SecurityElement.Escape(externalId) + "</RottenTomatoesId>");
// }
// externalId = item.GetProviderId(MetadataProviders.Zap2It);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<Zap2ItId>" + SecurityElement.Escape(externalId) + "</Zap2ItId>");
// }
// externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbum);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<MusicBrainzAlbumId>" + SecurityElement.Escape(externalId) + "</MusicBrainzAlbumId>");
// }
// externalId = item.GetProviderId(MetadataProviders.MusicBrainzAlbumArtist);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<MusicBrainzAlbumArtistId>" + SecurityElement.Escape(externalId) + "</MusicBrainzAlbumArtistId>");
// }
// externalId = item.GetProviderId(MetadataProviders.MusicBrainzArtist);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<MusicBrainzArtistId>" + SecurityElement.Escape(externalId) + "</MusicBrainzArtistId>");
// }
// externalId = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<MusicBrainzReleaseGroupId>" + SecurityElement.Escape(externalId) + "</MusicBrainzReleaseGroupId>");
// }
// externalId = item.GetProviderId(MetadataProviders.Gamesdb);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<GamesDbId>" + SecurityElement.Escape(externalId) + "</GamesDbId>");
// }
// externalId = item.GetProviderId(MetadataProviders.TmdbCollection);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<TMDbCollectionId>" + SecurityElement.Escape(externalId) + "</TMDbCollectionId>");
// }
// externalId = item.GetProviderId(MetadataProviders.AudioDbArtist);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<AudioDbArtistId>" + SecurityElement.Escape(externalId) + "</AudioDbArtistId>");
// }
// externalId = item.GetProviderId(MetadataProviders.AudioDbAlbum);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<AudioDbAlbumId>" + SecurityElement.Escape(externalId) + "</AudioDbAlbumId>");
// }
// externalId = item.GetProviderId(MetadataProviders.TvRage);
// if (!string.IsNullOrEmpty(externalId))
// {
// builder.Append("<TVRageId>" + SecurityElement.Escape(externalId) + "</TVRageId>");
// }
// if (!string.IsNullOrWhiteSpace(item.Tagline))
// {
// builder.Append("<Taglines>");
// builder.Append("<Tagline>" + SecurityElement.Escape(item.Tagline) + "</Tagline>");
// builder.Append("</Taglines>");
// }
// if (item.Genres.Count > 0)
// {
// builder.Append("<Genres>");
// foreach (var genre in item.Genres)
// {
// builder.Append("<Genre>" + SecurityElement.Escape(genre) + "</Genre>");
// }
// builder.Append("</Genres>");
// }
// if (item.Studios.Count > 0)
// {
// builder.Append("<Studios>");
// foreach (var studio in item.Studios)
// {
// builder.Append("<Studio>" + SecurityElement.Escape(studio) + "</Studio>");
// }
// builder.Append("</Studios>");
// }
// if (item.Tags.Count > 0)
// {
// builder.Append("<Tags>");
// foreach (var tag in item.Tags)
// {
// builder.Append("<Tag>" + SecurityElement.Escape(tag) + "</Tag>");
// }
// builder.Append("</Tags>");
// }
// if (item.Keywords.Count > 0)
// {
// builder.Append("<PlotKeywords>");
// foreach (var tag in item.Keywords)
// {
// builder.Append("<PlotKeyword>" + SecurityElement.Escape(tag) + "</PlotKeyword>");
// }
// builder.Append("</PlotKeywords>");
// }
// var people = libraryManager.GetPeople(item);
// if (people.Count > 0)
// {
// builder.Append("<Persons>");
// foreach (var person in people)
// {
// builder.Append("<Person>");
// builder.Append("<Name>" + SecurityElement.Escape(person.Name) + "</Name>");
// builder.Append("<Type>" + SecurityElement.Escape(person.Type) + "</Type>");
// builder.Append("<Role>" + SecurityElement.Escape(person.Role) + "</Role>");
// if (person.SortOrder.HasValue)
// {
// builder.Append("<SortOrder>" + SecurityElement.Escape(person.SortOrder.Value.ToString(UsCulture)) + "</SortOrder>");
// }
// builder.Append("</Person>");
// }
// builder.Append("</Persons>");
// }
// var boxset = item as BoxSet;
// if (boxset != null)
// {
// AddLinkedChildren(boxset, builder, "CollectionItems", "CollectionItem");
// }
// var playlist = item as Playlist;
// if (playlist != null)
// {
// AddLinkedChildren(playlist, builder, "PlaylistItems", "PlaylistItem");
// }
// var hasShares = item as IHasShares;
// if (hasShares != null)
// {
// AddShares(hasShares, builder);
// }
// }
// public static void AddShares(IHasShares item, StringBuilder builder)
// {
// builder.Append("<Shares>");
// foreach (var share in item.Shares)
// {
// builder.Append("<Share>");
// builder.Append("<UserId>" + SecurityElement.Escape(share.UserId) + "</UserId>");
// builder.Append("<CanEdit>" + SecurityElement.Escape(share.CanEdit.ToString().ToLower()) + "</CanEdit>");
// builder.Append("</Share>");
// }
// builder.Append("</Shares>");
// }
// public static void AddChapters(Video item, StringBuilder builder, IItemRepository repository)
// {
// var chapters = repository.GetChapters(item.Id);
// builder.Append("<Chapters>");
// foreach (var chapter in chapters)
// {
// builder.Append("<Chapter>");
// builder.Append("<Name>" + SecurityElement.Escape(chapter.Name) + "</Name>");
// var time = TimeSpan.FromTicks(chapter.StartPositionTicks);
// var ms = Convert.ToInt64(time.TotalMilliseconds);
// builder.Append("<StartPositionMs>" + SecurityElement.Escape(ms.ToString(UsCulture)) + "</StartPositionMs>");
// builder.Append("</Chapter>");
// }
// builder.Append("</Chapters>");
// }
// /// <summary>
// /// Appends the media info.
// /// </summary>
// /// <typeparam name="T"></typeparam>
// public static void AddMediaInfo<T>(T item, StringBuilder builder, IItemRepository itemRepository)
// where T : BaseItem
// {
// var video = item as Video;
// if (video != null)
// {
// //AddChapters(video, builder, itemRepository);
// if (video.Video3DFormat.HasValue)
// {
// switch (video.Video3DFormat.Value)
// {
// case Video3DFormat.FullSideBySide:
// builder.Append("<Format3D>FSBS</Format3D>");
// break;
// case Video3DFormat.FullTopAndBottom:
// builder.Append("<Format3D>FTAB</Format3D>");
// break;
// case Video3DFormat.HalfSideBySide:
// builder.Append("<Format3D>HSBS</Format3D>");
// break;
// case Video3DFormat.HalfTopAndBottom:
// builder.Append("<Format3D>HTAB</Format3D>");
// break;
// }
// }
// }
// }
// public static void AddLinkedChildren(Folder item, StringBuilder builder, string pluralNodeName, string singularNodeName)
// {
// var items = item.LinkedChildren
// .Where(i => i.Type == LinkedChildType.Manual)
// .ToList();
// if (items.Count == 0)
// {
// return;
// }
// builder.Append("<" + pluralNodeName + ">");
// foreach (var link in items)
// {
// builder.Append("<" + singularNodeName + ">");
// if (!string.IsNullOrWhiteSpace(link.Path))
// {
// builder.Append("<Path>" + SecurityElement.Escape((link.Path)) + "</Path>");
// }
// builder.Append("</" + singularNodeName + ">");
// }
// builder.Append("</" + pluralNodeName + ">");
// }
// }
//}
| mit |
SuperGlueFx/SuperGlue | src/SuperGlue.MetaData/SetMetaData.cs | 1612 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using SuperGlue.Configuration;
namespace SuperGlue.MetaData
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class SetMetaData
{
private readonly AppFunc _next;
public SetMetaData(AppFunc next)
{
if (next == null)
throw new ArgumentNullException(nameof(next));
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
var metaData = new Dictionary<string, object>();
var oldMetaData = environment.GetMetaData();
foreach (var item in oldMetaData.MetaData)
metaData[item.Key] = item.Value;
var metaDataSuppliers = environment.ResolveAll<ISupplyRequestMetaData>();
foreach (var supplier in metaDataSuppliers.Where(supplier => supplier.CanHandleChain(environment.GetCurrentChain().Name)))
{
var data = await supplier.GetMetaData(environment).ConfigureAwait(false);
foreach (var item in data)
metaData[item.Key] = item.Value;
}
environment[MetaDataEnvironmentExtensions.MetaDataConstants.RequestMetaData] = new RequestMetaData(new ReadOnlyDictionary<string, object>(metaData));
await _next(environment).ConfigureAwait(false);
environment[MetaDataEnvironmentExtensions.MetaDataConstants.RequestMetaData] = oldMetaData;
}
}
} | mit |
elix/elix | src/base/CarouselWithThumbnails.js | 991 | import Carousel from "./Carousel.js";
import { defaultState, render, state } from "./internal.js";
/**
* Carousel showing a thumbnail for each image
*
* @inherits Carousel
* @part {img} proxy
*/
class CarouselWithThumbnails extends Carousel {
// @ts-ignore
get [defaultState]() {
return Object.assign(super[defaultState], {
proxyListOverlap: false,
proxyPartType: "img",
});
}
[render](/** @type {ChangedFlags} */ changed) {
super[render](changed);
/** @type {Element[]} */ const proxies = this[state].proxies;
if ((changed.items || changed.proxies) && proxies) {
// Update thumbnails.
const { items } = this[state];
proxies.forEach((proxy, index) => {
/** @type {any} */ const item = items[index];
/** @type {any} */ const cast = proxy;
if (item && typeof item.src === "string" && "src" in cast) {
cast.src = item.src;
}
});
}
}
}
export default CarouselWithThumbnails;
| mit |
vagrant-libvirt/vagrant-libvirt | lib/vagrant-libvirt/cap/mount_9p.rb | 1543 | # frozen_string_literal: true
require 'digest/md5'
require 'vagrant/util/retryable'
module VagrantPlugins
module ProviderLibvirt
module Cap
class Mount9P
extend Vagrant::Util::Retryable
def self.mount_9p_shared_folder(machine, folders)
folders.each do |_name, opts|
# Expand the guest path so we can handle things like "~/vagrant"
expanded_guest_path = machine.guest.capability(
:shell_expand_guest_path, opts[:guestpath]
)
# Do the actual creating and mounting
machine.communicate.sudo("mkdir -p #{expanded_guest_path}")
# Mount
mount_tag = Digest::MD5.new.update(opts[:hostpath]).to_s[0, 31]
mount_opts = '-o trans=virtio'
mount_opts += ",access=#{opts[:owner]}" if opts[:owner]
mount_opts += ",version=#{opts[:version]}" if opts[:version]
mount_opts += ",#{opts[:mount_opts]}" if opts[:mount_opts]
mount_command = "mount -t 9p #{mount_opts} '#{mount_tag}' #{expanded_guest_path}"
retryable(on: Vagrant::Errors::LinuxMountFailed,
tries: 5,
sleep: 3) do
machine.communicate.sudo('modprobe 9p')
machine.communicate.sudo('modprobe 9pnet_virtio')
machine.communicate.sudo(mount_command,
error_class: Vagrant::Errors::LinuxMountFailed)
end
end
end
end
end
end
end
| mit |
nithishj/rewardsvipclub | application/models/events_admin_model.php | 2934 | <?php
Class events_admin_model extends CI_Model
{
function addevent($userid,$eventname,$eventdescription,$iconid,$eventdate)
{
$a=array("UserId"=>$userid,"EventName"=>$eventname,"EventDescription"=>$eventdescription,"IconId"=>$iconid,"EventDate"=>$eventdate);
$q=$this->db->insert('event',$a);
if($q)
return array("Message"=>"success","code"=>200);
}
function editevent($eventid,$userid,$eventname,$eventdescription,$iconid,$eventdate)
{
$a=array("UserId"=>$userid,"EventName"=>$eventname,"EventDescription"=>$eventdescription,"IconId"=>$iconid,"EventDate"=>$eventdate);
$this->db->where("EventId",$eventid);
$q=$this->db->update('event',$a);
if($q)
return array("Message"=>"success","code"=>200);
}
function deleteevent($eventid)
{
$this->db->where('EventId', $eventid);
$q=$this->db->delete('event');
if($q)
return array("Message"=>"success","code"=>200);
}
function getevents($id)
{
$base=base_url('icons').'/';
if(empty($id))
$q=$this->db->query("select up.user_name,ev.EventId,ev.UserId,ev.EventName,ev.EventDescription,Ic.IconId,case when (ev.IconId!=0) then concat('$base',Ic.IconName) else '' END as Icon,ev.EventDate from event ev inner join user_profile up on ev.UserId=up.user_id left join icon Ic on ev.IconId=Ic.IconId order by ev.EventId desc");
else
$q=$this->db->query("select up.user_name,ev.EventId,ev.UserId,ev.EventName,ev.EventDescription,Ic.IconId,case when (ev.IconId!=0) then concat('$base',Ic.IconName) else '' END as Icon,ev.EventDate from event ev inner join user_profile up on ev.UserId=up.user_id left join icon Ic on ev.IconId=Ic.IconId where ev.EventId='$id'");
if($q->num_rows()>0)
return $q->result();
else
return array();
}
function geticons($userid,$type)
{
$base=base_url('icons').'/';
if(empty($userid) && empty($type))
{
$q=$this->db->query("select IconId,concat('$base',IconName) as Icon from icon");
if($q->num_rows()>0)
return $q->result_array();
else
return array();
}
else
{
$tmp=array();
if($type=="general")
{
$q=$this->db->query("select IconId,concat('$base',IconName) as Icon from icon order by IconType desc");
}
else if($type=="emoji")
{
$q=$this->db->query("select IconId,concat('$base',IconName) as Icon from icon order by IconType");
}
$a=$q->result();
$ids_q=$this->db->query("select IconId from IconHistory where UserId='$userid' order by IconHistoryId desc");
if($ids_q->num_rows()>0)
{
$ids_r=$ids_q->result();
foreach($ids_r as $val)
{
foreach($a as $key => $org)
{
if($val->IconId==$org->IconId)
{
$parray=array("IconId"=>$org->IconId,"Icon"=>$org->Icon);
array_push($tmp,$parray);
unset($a[$key]);
}
}
}
foreach($a as $org)
{
$parray=array("IconId"=>$org->IconId,"Icon"=>$org->Icon);
array_push($tmp,$parray);
}
return $tmp;
}
else
return $a;
}
}
} | mit |
curtisalexander/learning | elm/elm-tutorial/node_modules/elm-webpack-loader/example/src/index.js | 119 | 'use strict';
require('./index.html');
var Elm = require('./Main');
Elm.Main.embed(document.getElementById('main'));
| mit |
babelshift/Steam.Models | src/Steam.Models/DOTA2/LiveLeagueGameScoreboardModel.cs | 336 | namespace Steam.Models.DOTA2
{
public class LiveLeagueGameScoreboardModel
{
public double Duration { get; set; }
public uint RoshanRespawnTimer { get; set; }
public LiveLeagueGameTeamRadiantDetailModel Radiant { get; set; }
public LiveLeagueGameTeamDireDetailModel Dire { get; set; }
}
} | mit |
uspgamedev/3D-experiment | externals/Ogre/RenderSystems/GLES2/src/OgreGLES2Texture.cpp | 23248 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Texture.h"
#include "OgreGLES2PixelFormat.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreGLES2Support.h"
#include "OgreGLES2StateCacheManager.h"
#include "OgreRoot.h"
namespace Ogre {
static inline void doImageIO(const String &name, const String &group,
const String &ext,
vector<Image>::type &images,
Resource *r)
{
size_t imgIdx = images.size();
images.push_back(Image());
DataStreamPtr dstream =
ResourceGroupManager::getSingleton().openResource(
name, group, true, r);
images[imgIdx].load(dstream, ext);
size_t w = 0, h = 0;
// Scale to nearest power of 2
w = GLES2PixelUtil::optionalPO2(images[imgIdx].getWidth());
h = GLES2PixelUtil::optionalPO2(images[imgIdx].getHeight());
if((images[imgIdx].getWidth() != w) || (images[imgIdx].getHeight() != h))
images[imgIdx].resize(w, h);
}
GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader, GLES2Support& support)
: Texture(creator, name, handle, group, isManual, loader),
mTextureID(0), mGLSupport(support)
{
}
GLES2Texture::~GLES2Texture()
{
// have to call this here rather than in Resource destructor
// since calling virtual methods in base destructors causes crash
if (isLoaded())
{
unload();
}
else
{
freeInternalResources();
}
}
GLenum GLES2Texture::getGLES2TextureTarget(void) const
{
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
return GL_TEXTURE_2D;
case TEX_TYPE_CUBE_MAP:
return GL_TEXTURE_CUBE_MAP;
#if OGRE_NO_GLES3_SUPPORT == 0
case TEX_TYPE_3D:
return GL_TEXTURE_3D;
case TEX_TYPE_2D_ARRAY:
return GL_TEXTURE_2D_ARRAY;
#endif
default:
return 0;
};
}
void GLES2Texture::_createGLTexResource()
{
// Convert to nearest power-of-two size if required
mWidth = GLES2PixelUtil::optionalPO2(mWidth);
mHeight = GLES2PixelUtil::optionalPO2(mHeight);
mDepth = GLES2PixelUtil::optionalPO2(mDepth);
// Adjust format if required
mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage);
GLenum texTarget = getGLES2TextureTarget();
// Check requested number of mipmaps
size_t maxMips = GLES2PixelUtil::getMaxMipmaps(mWidth, mHeight, mDepth, mFormat);
if(PixelUtil::isCompressed(mFormat) && (mNumMipmaps == 0))
mNumRequestedMipmaps = 0;
mNumMipmaps = mNumRequestedMipmaps;
if (mNumMipmaps > maxMips)
mNumMipmaps = maxMips;
// Generate texture name
OGRE_CHECK_GL_ERROR(glGenTextures(1, &mTextureID));
// Set texture type
mGLSupport.getStateCacheManager()->bindGLTexture(texTarget, mTextureID);
// If we can do automip generation and the user desires this, do so
mMipmapsHardwareGenerated =
Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_AUTOMIPMAP) && !PixelUtil::isCompressed(mFormat);
if(mGLSupport.checkExtension("GL_APPLE_texture_max_level") || gleswIsSupported(3, 0))
mGLSupport.getStateCacheManager()->setTexParameteri(texTarget, GL_TEXTURE_MAX_LEVEL_APPLE, mNumMipmaps);
// Set some misc default parameters, these can of course be changed later
mGLSupport.getStateCacheManager()->setTexParameteri(texTarget,
GL_TEXTURE_MIN_FILTER, (mUsage & TU_AUTOMIPMAP) ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST);
mGLSupport.getStateCacheManager()->setTexParameteri(texTarget,
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
mGLSupport.getStateCacheManager()->setTexParameteri(texTarget,
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
mGLSupport.getStateCacheManager()->setTexParameteri(texTarget,
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Set up texture swizzling
#if OGRE_NO_GLES3_SUPPORT == 0
if(gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_GREEN));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_BLUE));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_ALPHA));
if(mFormat == PF_L8 || mFormat == PF_L16)
{
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED));
OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_RED));
}
}
#endif
// Allocate internal buffer so that glTexSubImageXD can be used
// Internal format
GLenum format = GLES2PixelUtil::getGLOriginFormat(mFormat);
GLenum internalformat = GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma);
uint32 width = mWidth;
uint32 height = mHeight;
uint32 depth = mDepth;
if (PixelUtil::isCompressed(mFormat))
{
// Compressed formats
GLsizei size = static_cast<GLsizei>(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat));
// Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not
// accept a 0 pointer like normal glTexImageXD
// Run through this process for every mipmap to pregenerate mipmap pyramid
uint8* tmpdata = new uint8[size];
memset(tmpdata, 0, size);
for (uint8 mip = 0; mip <= mNumMipmaps; mip++)
{
#if OGRE_DEBUG_MODE
LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
" Width: " + StringConverter::toString(width) +
" Height: " + StringConverter::toString(height) +
" Internal Format: " + StringConverter::toString(internalformat, 0, ' ', std::ios::hex) +
" Format: " + StringConverter::toString(format, 0, ' ', std::ios::hex)
);
#endif
size = static_cast<GLsizei>(PixelUtil::getMemorySize(width, height, depth, mFormat));
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_2D,
mip,
internalformat,
width, height,
0,
size,
tmpdata));
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat,
width, height, 0,
size, tmpdata));
}
break;
#if OGRE_NO_GLES3_SUPPORT == 0
case TEX_TYPE_2D_ARRAY:
case TEX_TYPE_3D:
glCompressedTexImage3D(getGLES2TextureTarget(), mip, format,
width, height, depth, 0,
size, tmpdata);
break;
#endif
default:
break;
};
if(width > 1)
{
width = width / 2;
}
if(height > 1)
{
height = height / 2;
}
if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY)
{
depth = depth / 2;
}
}
delete [] tmpdata;
}
else
{
#if OGRE_NO_GLES3_SUPPORT == 0
#if OGRE_DEBUG_MODE
LogManager::getSingleton().logMessage("GLES2Texture::create - Name: " + mName +
" ID: " + StringConverter::toString(mTextureID) +
" Width: " + StringConverter::toString(width) +
" Height: " + StringConverter::toString(height) +
" Internal Format: " + StringConverter::toString(internalformat, 0, ' ', std::ios::hex));
#endif
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
case TEX_TYPE_2D_RECT:
OGRE_CHECK_GL_ERROR(glTexStorage2D(GL_TEXTURE_2D, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height)));
break;
case TEX_TYPE_CUBE_MAP:
OGRE_CHECK_GL_ERROR(glTexStorage2D(GL_TEXTURE_CUBE_MAP, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height)));
break;
case TEX_TYPE_2D_ARRAY:
OGRE_CHECK_GL_ERROR(glTexStorage3D(GL_TEXTURE_2D_ARRAY, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height), GLsizei(depth)));
break;
case TEX_TYPE_3D:
OGRE_CHECK_GL_ERROR(glTexStorage3D(GL_TEXTURE_3D, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height), GLsizei(depth)));
break;
}
#else
GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat);
// Run through this process to pregenerate mipmap pyramid
for(size_t mip = 0; mip <= mNumMipmaps; mip++)
{
#if OGRE_DEBUG_MODE
LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
" Name: " + mName +
" ID: " + StringConverter::toString(mTextureID) +
" Width: " + StringConverter::toString(width) +
" Height: " + StringConverter::toString(height) +
" Internal Format: " + StringConverter::toString(internalformat, 0, ' ', std::ios::hex) +
" Format: " + StringConverter::toString(format, 0, ' ', std::ios::hex) +
" Datatype: " + StringConverter::toString(datatype, 0, ' ', std::ios::hex)
);
#endif
// Normal formats
switch(mTextureType)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
#if OGRE_PLATFORM == OGRE_PLATFORM_NACL
if(internalformat != format)
{
LogManager::getSingleton().logMessage("glTexImage2D: format != internalFormat, "
"format=" + StringConverter::toString(format) +
", internalFormat=" + StringConverter::toString(internalformat));
}
#endif
OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_2D,
mip,
internalformat,
width, height,
0,
format,
datatype, 0));
break;
case TEX_TYPE_CUBE_MAP:
for(int face = 0; face < 6; face++) {
OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat,
width, height, 0,
format, datatype, 0));
}
break;
default:
break;
};
if (width > 1)
{
width = width / 2;
}
if (height > 1)
{
height = height / 2;
}
}
#endif
}
}
// Creation / loading methods
void GLES2Texture::createInternalResourcesImpl(void)
{
_createGLTexResource();
_createSurfaceList();
// Get final internal format
mFormat = getBuffer(0,0)->getFormat();
}
void GLES2Texture::createRenderTexture(void)
{
// Create the GL texture
// This already does everything necessary
createInternalResources();
}
void GLES2Texture::prepareImpl()
{
if (mUsage & TU_RENDERTARGET) return;
String baseName, ext;
size_t pos = mName.find_last_of(".");
baseName = mName.substr(0, pos);
if (pos != String::npos)
{
ext = mName.substr(pos+1);
}
LoadedImages loadedImages = LoadedImages(new vector<Image>::type());
if (mTextureType == TEX_TYPE_1D || mTextureType == TEX_TYPE_2D ||
mTextureType == TEX_TYPE_2D_ARRAY || mTextureType == TEX_TYPE_3D)
{
doImageIO(mName, mGroup, ext, *loadedImages, this);
// If this is a volumetric texture set the texture type flag accordingly.
// If this is a cube map, set the texture type flag accordingly.
if ((*loadedImages)[0].hasFlag(IF_CUBEMAP))
mTextureType = TEX_TYPE_CUBE_MAP;
// If this is a volumetric texture set the texture type flag accordingly.
if((*loadedImages)[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY)
mTextureType = TEX_TYPE_3D;
// If PVRTC and 0 custom mipmap disable auto mip generation and disable software mipmap creation
if (PixelUtil::isCompressed((*loadedImages)[0].getFormat()))
{
size_t imageMips = (*loadedImages)[0].getNumMipmaps();
if (imageMips == 0)
{
mNumMipmaps = mNumRequestedMipmaps = imageMips;
// Disable flag for auto mip generation
mUsage &= ~TU_AUTOMIPMAP;
}
}
}
else if (mTextureType == TEX_TYPE_CUBE_MAP)
{
if(getSourceFileType() == "dds")
{
// XX HACK there should be a better way to specify whether
// all faces are in the same file or not
doImageIO(mName, mGroup, ext, *loadedImages, this);
}
else
{
vector<Image>::type images(6);
ConstImagePtrList imagePtrs;
static const String suffixes[6] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
for(size_t i = 0; i < 6; i++)
{
String fullName = baseName + suffixes[i];
if (!ext.empty())
fullName = fullName + "." + ext;
// find & load resource data intro stream to allow resource
// group changes if required
doImageIO(fullName, mGroup, ext, *loadedImages, this);
}
}
}
else
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"**** Unknown texture type ****",
"GLES2Texture::prepare");
}
mLoadedImages = loadedImages;
}
void GLES2Texture::unprepareImpl()
{
mLoadedImages.setNull();
}
void GLES2Texture::loadImpl()
{
if (mUsage & TU_RENDERTARGET)
{
createRenderTexture();
return;
}
// Now the only copy is on the stack and will be cleaned in case of
// exceptions being thrown from _loadImages
LoadedImages loadedImages = mLoadedImages;
mLoadedImages.setNull();
// Call internal _loadImages, not loadImage since that's external and
// will determine load status etc again
ConstImagePtrList imagePtrs;
for (size_t i = 0; i < loadedImages->size(); ++i)
{
imagePtrs.push_back(&(*loadedImages)[i]);
}
_loadImages(imagePtrs);
if (mUsage & TU_AUTOMIPMAP)
{
OGRE_CHECK_GL_ERROR(glGenerateMipmap(getGLES2TextureTarget()));
}
}
void GLES2Texture::freeInternalResourcesImpl()
{
mSurfaceList.clear();
OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID));
mGLSupport.getStateCacheManager()->invalidateStateForTexture( mTextureID );
mTextureID = 0;
}
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
void GLES2Texture::notifyOnContextLost()
{
if (!mIsManual)
{
freeInternalResources();
}
else
{
OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID));
mTextureID = 0;
}
}
void GLES2Texture::notifyOnContextReset()
{
if (!mIsManual)
{
reload();
}
else
{
preLoadImpl();
_createGLTexResource();
for(size_t i = 0; i < mSurfaceList.size(); i++)
{
static_cast<GLES2TextureBuffer*>(mSurfaceList[i].getPointer())->updateTextureId(mTextureID);
}
if (mLoader)
{
mLoader->loadResource(this);
}
postLoadImpl();
}
}
#endif
void GLES2Texture::_createSurfaceList()
{
mSurfaceList.clear();
// For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr
bool wantGeneratedMips = (mUsage & TU_AUTOMIPMAP)!=0;
// Do mipmapping in software? (uses GLU) For some cards, this is still needed. Of course,
// only when mipmap generation is desired.
bool doSoftware = wantGeneratedMips && !mMipmapsHardwareGenerated && getNumMipmaps();
for (size_t face = 0; face < getNumFaces(); face++)
{
uint32 width = mWidth;
uint32 height = mHeight;
uint32 depth = mDepth;
for (uint8 mip = 0; mip <= getNumMipmaps(); mip++)
{
GLES2HardwarePixelBuffer *buf = OGRE_NEW GLES2TextureBuffer(mName,
getGLES2TextureTarget(),
mTextureID,
width, height, depth,
GLES2PixelUtil::getClosestGLInternalFormat(mFormat, mHwGamma),
GLES2PixelUtil::getGLOriginDataType(mFormat),
static_cast<GLint>(face),
mip,
static_cast<HardwareBuffer::Usage>(mUsage),
doSoftware && mip==0, mHwGamma, mFSAA);
mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf));
// Check for error
if (buf->getWidth() == 0 ||
buf->getHeight() == 0 ||
buf->getDepth() == 0)
{
OGRE_EXCEPT(
Exception::ERR_RENDERINGAPI_ERROR,
"Zero sized texture surface on texture "+getName()+
" face "+StringConverter::toString(face)+
" mipmap "+StringConverter::toString(mip)+
". The GL driver probably refused to create the texture.",
"GLES2Texture::_createSurfaceList");
}
}
}
}
HardwarePixelBufferSharedPtr GLES2Texture::getBuffer(size_t face, size_t mipmap)
{
if (face >= getNumFaces())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Face index out of range",
"GLES2Texture::getBuffer");
}
if (mipmap > mNumMipmaps)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Mipmap index out of range",
"GLES2Texture::getBuffer");
}
unsigned long idx = face * (mNumMipmaps + 1) + mipmap;
assert(idx < mSurfaceList.size());
return mSurfaceList[idx];
}
}
| mit |
mattpodwysocki/jsconf.co-2015-workshop | lessons/node_modules/rx/src/core/perf/operators/repeat.js | 1814 | var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RepeatObservable(value, repeatCount, scheduler);
};
| mit |
purgesoftwares/purges | frontend/wp-content/themes/circleflip/woocommerce/cart/shipping-calculator.php | 3717 | <?php
/**
* Shipping Calculator
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.8
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
if ( get_option( 'woocommerce_enable_shipping_calc' ) === 'no' || ! WC()->cart->needs_shipping() )
return;
?>
<?php do_action( 'woocommerce_before_shipping_calculator' ); ?>
<div class="span6 grid2">
<form class="shipping_calculator" action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post">
<h3><?php _e( 'Calculate Shipping', 'woocommerce' ); ?></h3>
<section class="shipping-calculator-form">
<p class="form-row form-row-wide selectOverlay">
<span class="icon-down-open"></span>
<select name="calc_shipping_country" id="calc_shipping_country" class="country_to_state" rel="calc_shipping_state">
<option value=""><?php _e( 'Select a country…', 'woocommerce' ); ?></option>
<?php
foreach( WC()->countries->get_shipping_countries() as $key => $value )
echo '<option value="' . esc_attr( $key ) . '"' . selected( WC()->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
?>
</select>
</p>
<p class="form-row form-row-wide shopState grid2">
<?php
$current_cc = WC()->customer->get_shipping_country();
$current_r = WC()->customer->get_shipping_state();
$states = WC()->countries->get_states( $current_cc );
// Hidden Input
if ( is_array( $states ) && empty( $states ) ) {
?><input type="hidden" name="calc_shipping_state" id="calc_shipping_state" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>" /><?php
// Dropdown Input
} elseif ( is_array( $states ) ) {
?><span>
<select name="calc_shipping_state" id="calc_shipping_state" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>">
<option value=""><?php _e( 'Select a state…', 'woocommerce' ); ?></option>
<?php
foreach ( $states as $ckey => $cvalue )
echo '<option value="' . esc_attr( $ckey ) . '" ' . selected( $current_r, $ckey, false ) . '>' . esc_html( $cvalue ) .'</option>';
?>
</select>
</span><?php
// Standard Input
} else {
?><input type="text" class="input-text" value="<?php echo esc_attr( $current_r ); ?>" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>" name="calc_shipping_state" id="calc_shipping_state" /><?php
}
?>
</p>
<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_city', false ) ) : ?>
<p class="form-row form-row-wide shopState grid2">
<input type="text" class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_city() ); ?>" placeholder="<?php _e( 'City', 'woocommerce' ); ?>" name="calc_shipping_city" id="calc_shipping_city" />
</p>
<?php endif; ?>
<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_postcode', true ) ) : ?>
<p class="form-row form-row-wide shopState grid2">
<input type="text" class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_postcode() ); ?>" placeholder="<?php _e( 'Postcode / Zip', 'woocommerce' ); ?>" name="calc_shipping_postcode" id="calc_shipping_postcode" />
</p>
<?php endif; ?>
<p><button type="submit" name="calc_shipping" value="1" class="btnStyle2 red right button"><span><?php _e( 'Update Totals', 'woocommerce' ); ?></span><span class="btnAfter"></span><span class="btnBefore"></span></button></p>
<?php wp_nonce_field( 'woocommerce-cart' ); ?>
</section>
</form>
</div>
<?php do_action( 'woocommerce_after_shipping_calculator' ); ?> | mit |
Serabe/ember.js | packages/ember-metal/lib/error_handler.js | 470 | let onerror;
export const onErrorTarget = {
get onerror() {
return onerror;
},
};
// Ember.onerror getter
export function getOnerror() {
return onerror;
}
// Ember.onerror setter
export function setOnerror(handler) {
onerror = handler;
}
let dispatchOverride;
// allows testing adapter to override dispatch
export function getDispatchOverride() {
return dispatchOverride;
}
export function setDispatchOverride(handler) {
dispatchOverride = handler;
}
| mit |
cdnjs/cdnjs | ajax/libs/tsparticles/1.39.1/tsparticles.updater.life.js | 172059 | (function webpackUniversalModuleDefinition(root, factory) {
if (typeof exports === "object" && typeof module === "object") module.exports = factory(); else if (typeof define === "function" && define.amd) define([], factory); else {
var a = factory();
for (var i in a) (typeof exports === "object" ? exports : root)[i] = a[i];
}
})(window, (function() {
return function() {
"use strict";
var __webpack_require__ = {};
!function() {
__webpack_require__.d = function(exports, definition) {
for (var key in definition) {
if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, {
enumerable: true,
get: definition[key]
});
}
}
};
}();
!function() {
__webpack_require__.o = function(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
}();
!function() {
__webpack_require__.r = function(exports) {
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, {
value: "Module"
});
}
Object.defineProperty(exports, "__esModule", {
value: true
});
};
}();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
loadLifeUpdater: function() {
return loadLifeUpdater;
}
});
class Circle_Circle extends(null && Range){
constructor(x, y, radius) {
super(x, y);
this.radius = radius;
}
contains(point) {
return getDistance(point, this.position) <= this.radius;
}
intersects(range) {
const rect = range;
const circle = range;
const pos1 = this.position;
const pos2 = range.position;
const xDist = Math.abs(pos2.x - pos1.x);
const yDist = Math.abs(pos2.y - pos1.y);
const r = this.radius;
if (circle.radius !== undefined) {
const rSum = r + circle.radius;
const dist = Math.sqrt(xDist * xDist + yDist + yDist);
return rSum > dist;
} else if (rect.size !== undefined) {
const w = rect.size.width;
const h = rect.size.height;
const edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2);
if (xDist > r + w || yDist > r + h) {
return false;
}
if (xDist <= w || yDist <= h) {
return true;
}
return edges <= r * r;
}
return false;
}
}
class CircleWarp_CircleWarp extends(null && Circle){
constructor(x, y, radius, canvasSize) {
super(x, y, radius);
this.canvasSize = canvasSize;
this.canvasSize = {
height: canvasSize.height,
width: canvasSize.width
};
}
contains(point) {
if (super.contains(point)) {
return true;
}
const posNE = {
x: point.x - this.canvasSize.width,
y: point.y
};
if (super.contains(posNE)) {
return true;
}
const posSE = {
x: point.x - this.canvasSize.width,
y: point.y - this.canvasSize.height
};
if (super.contains(posSE)) {
return true;
}
const posSW = {
x: point.x,
y: point.y - this.canvasSize.height
};
return super.contains(posSW);
}
intersects(range) {
if (super.intersects(range)) {
return true;
}
const rect = range;
const circle = range;
const newPos = {
x: range.position.x - this.canvasSize.width,
y: range.position.y - this.canvasSize.height
};
if (circle.radius !== undefined) {
const biggerCircle = new Circle(newPos.x, newPos.y, circle.radius * 2);
return super.intersects(biggerCircle);
} else if (rect.size !== undefined) {
const rectSW = new Rectangle(newPos.x, newPos.y, rect.size.width * 2, rect.size.height * 2);
return super.intersects(rectSW);
}
return false;
}
}
class Constants_Constants {}
Constants_Constants.generatedAttribute = "generated";
Constants_Constants.randomColorValue = "random";
Constants_Constants.midColorValue = "mid";
Constants_Constants.touchEndEvent = "touchend";
Constants_Constants.mouseDownEvent = "mousedown";
Constants_Constants.mouseUpEvent = "mouseup";
Constants_Constants.mouseMoveEvent = "mousemove";
Constants_Constants.touchStartEvent = "touchstart";
Constants_Constants.touchMoveEvent = "touchmove";
Constants_Constants.mouseLeaveEvent = "mouseleave";
Constants_Constants.mouseOutEvent = "mouseout";
Constants_Constants.touchCancelEvent = "touchcancel";
Constants_Constants.resizeEvent = "resize";
Constants_Constants.visibilityChangeEvent = "visibilitychange";
Constants_Constants.noPolygonDataLoaded = "No polygon data loaded.";
Constants_Constants.noPolygonFound = "No polygon found, you need to specify SVG url in config.";
function manageListener(element, event, handler, add, options) {
if (add) {
let addOptions = {
passive: true
};
if (typeof options === "boolean") {
addOptions.capture = options;
} else if (options !== undefined) {
addOptions = options;
}
element.addEventListener(event, handler, addOptions);
} else {
const removeOptions = options;
element.removeEventListener(event, handler, removeOptions);
}
}
class EventListeners_EventListeners {
constructor(container) {
this.container = container;
this.canPush = true;
this.mouseMoveHandler = e => this.mouseTouchMove(e);
this.touchStartHandler = e => this.mouseTouchMove(e);
this.touchMoveHandler = e => this.mouseTouchMove(e);
this.touchEndHandler = () => this.mouseTouchFinish();
this.mouseLeaveHandler = () => this.mouseTouchFinish();
this.touchCancelHandler = () => this.mouseTouchFinish();
this.touchEndClickHandler = e => this.mouseTouchClick(e);
this.mouseUpHandler = e => this.mouseTouchClick(e);
this.mouseDownHandler = () => this.mouseDown();
this.visibilityChangeHandler = () => this.handleVisibilityChange();
this.themeChangeHandler = e => this.handleThemeChange(e);
this.oldThemeChangeHandler = e => this.handleThemeChange(e);
this.resizeHandler = () => this.handleWindowResize();
}
addListeners() {
this.manageListeners(true);
}
removeListeners() {
this.manageListeners(false);
}
manageListeners(add) {
var _a;
const container = this.container;
const options = container.actualOptions;
const detectType = options.interactivity.detectsOn;
let mouseLeaveEvent = Constants.mouseLeaveEvent;
if (detectType === "window") {
container.interactivity.element = window;
mouseLeaveEvent = Constants.mouseOutEvent;
} else if (detectType === "parent" && container.canvas.element) {
const canvasEl = container.canvas.element;
container.interactivity.element = (_a = canvasEl.parentElement) !== null && _a !== void 0 ? _a : canvasEl.parentNode;
} else {
container.interactivity.element = container.canvas.element;
}
const mediaMatch = !isSsr() && typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)");
if (mediaMatch) {
if (mediaMatch.addEventListener !== undefined) {
manageListener(mediaMatch, "change", this.themeChangeHandler, add);
} else if (mediaMatch.addListener !== undefined) {
if (add) {
mediaMatch.addListener(this.oldThemeChangeHandler);
} else {
mediaMatch.removeListener(this.oldThemeChangeHandler);
}
}
}
const interactivityEl = container.interactivity.element;
if (!interactivityEl) {
return;
}
const html = interactivityEl;
if (options.interactivity.events.onHover.enable || options.interactivity.events.onClick.enable) {
manageListener(interactivityEl, Constants.mouseMoveEvent, this.mouseMoveHandler, add);
manageListener(interactivityEl, Constants.touchStartEvent, this.touchStartHandler, add);
manageListener(interactivityEl, Constants.touchMoveEvent, this.touchMoveHandler, add);
if (!options.interactivity.events.onClick.enable) {
manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndHandler, add);
} else {
manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndClickHandler, add);
manageListener(interactivityEl, Constants.mouseUpEvent, this.mouseUpHandler, add);
manageListener(interactivityEl, Constants.mouseDownEvent, this.mouseDownHandler, add);
}
manageListener(interactivityEl, mouseLeaveEvent, this.mouseLeaveHandler, add);
manageListener(interactivityEl, Constants.touchCancelEvent, this.touchCancelHandler, add);
}
if (container.canvas.element) {
container.canvas.element.style.pointerEvents = html === container.canvas.element ? "initial" : "none";
}
if (options.interactivity.events.resize) {
if (typeof ResizeObserver !== "undefined") {
if (this.resizeObserver && !add) {
if (container.canvas.element) {
this.resizeObserver.unobserve(container.canvas.element);
}
this.resizeObserver.disconnect();
delete this.resizeObserver;
} else if (!this.resizeObserver && add && container.canvas.element) {
this.resizeObserver = new ResizeObserver((entries => {
const entry = entries.find((e => e.target === container.canvas.element));
if (!entry) {
return;
}
this.handleWindowResize();
}));
this.resizeObserver.observe(container.canvas.element);
}
} else {
manageListener(window, Constants.resizeEvent, this.resizeHandler, add);
}
}
if (document) {
manageListener(document, Constants.visibilityChangeEvent, this.visibilityChangeHandler, add, false);
}
}
handleWindowResize() {
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
delete this.resizeTimeout;
}
this.resizeTimeout = setTimeout((async () => {
var _a;
return await ((_a = this.container.canvas) === null || _a === void 0 ? void 0 : _a.windowResize());
}), 500);
}
handleVisibilityChange() {
const container = this.container;
const options = container.actualOptions;
this.mouseTouchFinish();
if (!options.pauseOnBlur) {
return;
}
if (document === null || document === void 0 ? void 0 : document.hidden) {
container.pageHidden = true;
container.pause();
} else {
container.pageHidden = false;
if (container.getAnimationStatus()) {
container.play(true);
} else {
container.draw(true);
}
}
}
mouseDown() {
const interactivity = this.container.interactivity;
if (interactivity) {
const mouse = interactivity.mouse;
mouse.clicking = true;
mouse.downPosition = mouse.position;
}
}
mouseTouchMove(e) {
var _a, _b, _c, _d, _e, _f, _g;
const container = this.container;
const options = container.actualOptions;
if (((_a = container.interactivity) === null || _a === void 0 ? void 0 : _a.element) === undefined) {
return;
}
container.interactivity.mouse.inside = true;
let pos;
const canvas = container.canvas.element;
if (e.type.startsWith("mouse")) {
this.canPush = true;
const mouseEvent = e;
if (container.interactivity.element === window) {
if (canvas) {
const clientRect = canvas.getBoundingClientRect();
pos = {
x: mouseEvent.clientX - clientRect.left,
y: mouseEvent.clientY - clientRect.top
};
}
} else if (options.interactivity.detectsOn === "parent") {
const source = mouseEvent.target;
const target = mouseEvent.currentTarget;
const canvasEl = container.canvas.element;
if (source && target && canvasEl) {
const sourceRect = source.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
const canvasRect = canvasEl.getBoundingClientRect();
pos = {
x: mouseEvent.offsetX + 2 * sourceRect.left - (targetRect.left + canvasRect.left),
y: mouseEvent.offsetY + 2 * sourceRect.top - (targetRect.top + canvasRect.top)
};
} else {
pos = {
x: (_b = mouseEvent.offsetX) !== null && _b !== void 0 ? _b : mouseEvent.clientX,
y: (_c = mouseEvent.offsetY) !== null && _c !== void 0 ? _c : mouseEvent.clientY
};
}
} else {
if (mouseEvent.target === container.canvas.element) {
pos = {
x: (_d = mouseEvent.offsetX) !== null && _d !== void 0 ? _d : mouseEvent.clientX,
y: (_e = mouseEvent.offsetY) !== null && _e !== void 0 ? _e : mouseEvent.clientY
};
}
}
} else {
this.canPush = e.type !== "touchmove";
const touchEvent = e;
const lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
const canvasRect = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
pos = {
x: lastTouch.clientX - ((_f = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _f !== void 0 ? _f : 0),
y: lastTouch.clientY - ((_g = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _g !== void 0 ? _g : 0)
};
}
const pxRatio = container.retina.pixelRatio;
if (pos) {
pos.x *= pxRatio;
pos.y *= pxRatio;
}
container.interactivity.mouse.position = pos;
container.interactivity.status = Constants.mouseMoveEvent;
}
mouseTouchFinish() {
const interactivity = this.container.interactivity;
if (interactivity === undefined) {
return;
}
const mouse = interactivity.mouse;
delete mouse.position;
delete mouse.clickPosition;
delete mouse.downPosition;
interactivity.status = Constants.mouseLeaveEvent;
mouse.inside = false;
mouse.clicking = false;
}
mouseTouchClick(e) {
const container = this.container;
const options = container.actualOptions;
const mouse = container.interactivity.mouse;
mouse.inside = true;
let handled = false;
const mousePosition = mouse.position;
if (mousePosition === undefined || !options.interactivity.events.onClick.enable) {
return;
}
for (const [, plugin] of container.plugins) {
if (plugin.clickPositionValid !== undefined) {
handled = plugin.clickPositionValid(mousePosition);
if (handled) {
break;
}
}
}
if (!handled) {
this.doMouseTouchClick(e);
}
mouse.clicking = false;
}
doMouseTouchClick(e) {
const container = this.container;
const options = container.actualOptions;
if (this.canPush) {
const mousePos = container.interactivity.mouse.position;
if (mousePos) {
container.interactivity.mouse.clickPosition = {
x: mousePos.x,
y: mousePos.y
};
} else {
return;
}
container.interactivity.mouse.clickTime = (new Date).getTime();
const onClick = options.interactivity.events.onClick;
if (onClick.mode instanceof Array) {
for (const mode of onClick.mode) {
this.handleClickMode(mode);
}
} else {
this.handleClickMode(onClick.mode);
}
}
if (e.type === "touchend") {
setTimeout((() => this.mouseTouchFinish()), 500);
}
}
handleThemeChange(e) {
const mediaEvent = e;
const themeName = mediaEvent.matches ? this.container.options.defaultDarkTheme : this.container.options.defaultLightTheme;
const theme = this.container.options.themes.find((theme => theme.name === themeName));
if (theme && theme.default.auto) {
this.container.loadTheme(themeName);
}
}
handleClickMode(mode) {
const container = this.container;
const options = container.actualOptions;
const pushNb = options.interactivity.modes.push.quantity;
const removeNb = options.interactivity.modes.remove.quantity;
switch (mode) {
case "push":
{
if (pushNb > 0) {
const pushOptions = options.interactivity.modes.push;
const group = itemFromArray([ undefined, ...pushOptions.groups ]);
const groupOptions = group !== undefined ? container.actualOptions.particles.groups[group] : undefined;
container.particles.push(pushNb, container.interactivity.mouse, groupOptions, group);
}
break;
}
case "remove":
container.particles.removeQuantity(removeNb);
break;
case "bubble":
container.bubble.clicking = true;
break;
case "repulse":
container.repulse.clicking = true;
container.repulse.count = 0;
for (const particle of container.repulse.particles) {
particle.velocity.setTo(particle.initialVelocity);
}
container.repulse.particles = [];
container.repulse.finish = false;
setTimeout((() => {
if (!container.destroyed) {
container.repulse.clicking = false;
}
}), options.interactivity.modes.repulse.duration * 1e3);
break;
case "attract":
container.attract.clicking = true;
container.attract.count = 0;
for (const particle of container.attract.particles) {
particle.velocity.setTo(particle.initialVelocity);
}
container.attract.particles = [];
container.attract.finish = false;
setTimeout((() => {
if (!container.destroyed) {
container.attract.clicking = false;
}
}), options.interactivity.modes.attract.duration * 1e3);
break;
case "pause":
if (container.getAnimationStatus()) {
container.pause();
} else {
container.play();
}
break;
}
for (const [, plugin] of container.plugins) {
if (plugin.handleClickMode) {
plugin.handleClickMode(mode);
}
}
}
}
class InteractionManager_InteractionManager {
constructor(container) {
this.container = container;
this.externalInteractors = [];
this.particleInteractors = [];
this.init();
}
init() {
const interactors = Plugins.getInteractors(this.container, true);
for (const interactor of interactors) {
switch (interactor.type) {
case 0:
this.externalInteractors.push(interactor);
break;
case 1:
this.particleInteractors.push(interactor);
break;
}
}
}
externalInteract(delta) {
for (const interactor of this.externalInteractors) {
if (interactor.isEnabled()) {
interactor.interact(delta);
}
}
}
particlesInteract(particle, delta) {
for (const interactor of this.externalInteractors) {
interactor.reset(particle);
}
for (const interactor of this.particleInteractors) {
if (interactor.isEnabled(particle)) {
interactor.interact(particle, delta);
}
}
}
}
function applyDistance(particle) {
const initialPosition = particle.initialPosition;
const {dx: dx, dy: dy} = getDistances(initialPosition, particle.position);
const dxFixed = Math.abs(dx), dyFixed = Math.abs(dy);
const hDistance = particle.retina.maxDistance.horizontal;
const vDistance = particle.retina.maxDistance.vertical;
if (!hDistance && !vDistance) {
return;
}
if ((hDistance && dxFixed >= hDistance || vDistance && dyFixed >= vDistance) && !particle.misplaced) {
particle.misplaced = !!hDistance && dxFixed > hDistance || !!vDistance && dyFixed > vDistance;
if (hDistance) {
particle.velocity.x = particle.velocity.y / 2 - particle.velocity.x;
}
if (vDistance) {
particle.velocity.y = particle.velocity.x / 2 - particle.velocity.y;
}
} else if ((!hDistance || dxFixed < hDistance) && (!vDistance || dyFixed < vDistance) && particle.misplaced) {
particle.misplaced = false;
} else if (particle.misplaced) {
const pos = particle.position, vel = particle.velocity;
if (hDistance && (pos.x < initialPosition.x && vel.x < 0 || pos.x > initialPosition.x && vel.x > 0)) {
vel.x *= -Math.random();
}
if (vDistance && (pos.y < initialPosition.y && vel.y < 0 || pos.y > initialPosition.y && vel.y > 0)) {
vel.y *= -Math.random();
}
}
}
class ParticlesMover_ParticlesMover {
constructor(container) {
this.container = container;
}
move(particle, delta) {
if (particle.destroyed) {
return;
}
this.moveParticle(particle, delta);
this.moveParallax(particle);
}
moveParticle(particle, delta) {
var _a, _b, _c;
var _d, _e;
const particleOptions = particle.options;
const moveOptions = particleOptions.move;
if (!moveOptions.enable) {
return;
}
const container = this.container, slowFactor = this.getProximitySpeedFactor(particle), baseSpeed = ((_a = (_d = particle.retina).moveSpeed) !== null && _a !== void 0 ? _a : _d.moveSpeed = getRangeValue(moveOptions.speed) * container.retina.pixelRatio) * container.retina.reduceFactor, moveDrift = (_b = (_e = particle.retina).moveDrift) !== null && _b !== void 0 ? _b : _e.moveDrift = getRangeValue(particle.options.move.drift) * container.retina.pixelRatio, maxSize = getRangeMax(particleOptions.size.value) * container.retina.pixelRatio, sizeFactor = moveOptions.size ? particle.getRadius() / maxSize : 1, diffFactor = 2, speedFactor = sizeFactor * slowFactor * (delta.factor || 1) / diffFactor, moveSpeed = baseSpeed * speedFactor;
this.applyPath(particle, delta);
const gravityOptions = moveOptions.gravity;
const gravityFactor = gravityOptions.enable && gravityOptions.inverse ? -1 : 1;
if (gravityOptions.enable && moveSpeed) {
particle.velocity.y += gravityFactor * (gravityOptions.acceleration * delta.factor) / (60 * moveSpeed);
}
if (moveDrift && moveSpeed) {
particle.velocity.x += moveDrift * delta.factor / (60 * moveSpeed);
}
const decay = particle.moveDecay;
if (decay != 1) {
particle.velocity.multTo(decay);
}
const velocity = particle.velocity.mult(moveSpeed);
const maxSpeed = (_c = particle.retina.maxSpeed) !== null && _c !== void 0 ? _c : container.retina.maxSpeed;
if (gravityOptions.enable && gravityOptions.maxSpeed > 0 && (!gravityOptions.inverse && velocity.y >= 0 && velocity.y >= maxSpeed || gravityOptions.inverse && velocity.y <= 0 && velocity.y <= -maxSpeed)) {
velocity.y = gravityFactor * maxSpeed;
if (moveSpeed) {
particle.velocity.y = velocity.y / moveSpeed;
}
}
const zIndexOptions = particle.options.zIndex, zVelocityFactor = (1 - particle.zIndexFactor) ** zIndexOptions.velocityRate;
if (moveOptions.spin.enable) {
this.spin(particle, moveSpeed);
} else {
if (zVelocityFactor != 1) {
velocity.multTo(zVelocityFactor);
}
particle.position.addTo(velocity);
if (moveOptions.vibrate) {
particle.position.x += Math.sin(particle.position.x * Math.cos(particle.position.y));
particle.position.y += Math.cos(particle.position.y * Math.sin(particle.position.x));
}
}
applyDistance(particle);
}
spin(particle, moveSpeed) {
const container = this.container;
if (!particle.spin) {
return;
}
const updateFunc = {
x: particle.spin.direction === "clockwise" ? Math.cos : Math.sin,
y: particle.spin.direction === "clockwise" ? Math.sin : Math.cos
};
particle.position.x = particle.spin.center.x + particle.spin.radius * updateFunc.x(particle.spin.angle);
particle.position.y = particle.spin.center.y + particle.spin.radius * updateFunc.y(particle.spin.angle);
particle.spin.radius += particle.spin.acceleration;
const maxCanvasSize = Math.max(container.canvas.size.width, container.canvas.size.height);
if (particle.spin.radius > maxCanvasSize / 2) {
particle.spin.radius = maxCanvasSize / 2;
particle.spin.acceleration *= -1;
} else if (particle.spin.radius < 0) {
particle.spin.radius = 0;
particle.spin.acceleration *= -1;
}
particle.spin.angle += moveSpeed / 100 * (1 - particle.spin.radius / maxCanvasSize);
}
applyPath(particle, delta) {
const particlesOptions = particle.options;
const pathOptions = particlesOptions.move.path;
const pathEnabled = pathOptions.enable;
if (!pathEnabled) {
return;
}
const container = this.container;
if (particle.lastPathTime <= particle.pathDelay) {
particle.lastPathTime += delta.value;
return;
}
const path = container.pathGenerator.generate(particle);
particle.velocity.addTo(path);
if (pathOptions.clamp) {
particle.velocity.x = clamp(particle.velocity.x, -1, 1);
particle.velocity.y = clamp(particle.velocity.y, -1, 1);
}
particle.lastPathTime -= particle.pathDelay;
}
moveParallax(particle) {
const container = this.container;
const options = container.actualOptions;
if (isSsr() || !options.interactivity.events.onHover.parallax.enable) {
return;
}
const parallaxForce = options.interactivity.events.onHover.parallax.force;
const mousePos = container.interactivity.mouse.position;
if (!mousePos) {
return;
}
const canvasCenter = {
x: container.canvas.size.width / 2,
y: container.canvas.size.height / 2
};
const parallaxSmooth = options.interactivity.events.onHover.parallax.smooth;
const factor = particle.getRadius() / parallaxForce;
const tmp = {
x: (mousePos.x - canvasCenter.x) * factor,
y: (mousePos.y - canvasCenter.y) * factor
};
particle.offset.x += (tmp.x - particle.offset.x) / parallaxSmooth;
particle.offset.y += (tmp.y - particle.offset.y) / parallaxSmooth;
}
getProximitySpeedFactor(particle) {
const container = this.container;
const options = container.actualOptions;
const active = isInArray("slow", options.interactivity.events.onHover.mode);
if (!active) {
return 1;
}
const mousePos = this.container.interactivity.mouse.position;
if (!mousePos) {
return 1;
}
const particlePos = particle.getPosition();
const dist = getDistance(mousePos, particlePos);
const radius = container.retina.slowModeRadius;
if (dist > radius) {
return 1;
}
const proximityFactor = dist / radius || 0;
const slowFactor = options.interactivity.modes.slow.factor;
return proximityFactor / slowFactor;
}
}
const plugins = null && [];
const interactorsInitializers = new Map;
const updatersInitializers = new Map;
const interactors = new Map;
const updaters = new Map;
const presets = new Map;
const drawers = new Map;
const pathGenerators = new Map;
class Plugins_Plugins {
static getPlugin(plugin) {
return plugins.find((t => t.id === plugin));
}
static addPlugin(plugin) {
if (!Plugins_Plugins.getPlugin(plugin.id)) {
plugins.push(plugin);
}
}
static getAvailablePlugins(container) {
const res = new Map;
for (const plugin of plugins) {
if (!plugin.needsPlugin(container.actualOptions)) {
continue;
}
res.set(plugin.id, plugin.getPlugin(container));
}
return res;
}
static loadOptions(options, sourceOptions) {
for (const plugin of plugins) {
plugin.loadOptions(options, sourceOptions);
}
}
static getPreset(preset) {
return presets.get(preset);
}
static addPreset(presetKey, options, override = false) {
if (override || !Plugins_Plugins.getPreset(presetKey)) {
presets.set(presetKey, options);
}
}
static addShapeDrawer(type, drawer) {
if (!Plugins_Plugins.getShapeDrawer(type)) {
drawers.set(type, drawer);
}
}
static getShapeDrawer(type) {
return drawers.get(type);
}
static getSupportedShapes() {
return drawers.keys();
}
static getPathGenerator(type) {
return pathGenerators.get(type);
}
static addPathGenerator(type, pathGenerator) {
if (!Plugins_Plugins.getPathGenerator(type)) {
pathGenerators.set(type, pathGenerator);
}
}
static getInteractors(container, force = false) {
let res = interactors.get(container);
if (!res || force) {
res = [ ...interactorsInitializers.values() ].map((t => t(container)));
interactors.set(container, res);
}
return res;
}
static addInteractor(name, initInteractor) {
interactorsInitializers.set(name, initInteractor);
}
static getUpdaters(container, force = false) {
let res = updaters.get(container);
if (!res || force) {
res = [ ...updatersInitializers.values() ].map((t => t(container)));
updaters.set(container, res);
}
return res;
}
static addParticleUpdater(name, initUpdater) {
updatersInitializers.set(name, initUpdater);
}
}
class QuadTree_QuadTree {
constructor(rectangle, capacity) {
this.rectangle = rectangle;
this.capacity = capacity;
this.points = [];
this.divided = false;
}
subdivide() {
const x = this.rectangle.position.x;
const y = this.rectangle.position.y;
const w = this.rectangle.size.width;
const h = this.rectangle.size.height;
const capacity = this.capacity;
this.northEast = new QuadTree_QuadTree(new Rectangle(x, y, w / 2, h / 2), capacity);
this.northWest = new QuadTree_QuadTree(new Rectangle(x + w / 2, y, w / 2, h / 2), capacity);
this.southEast = new QuadTree_QuadTree(new Rectangle(x, y + h / 2, w / 2, h / 2), capacity);
this.southWest = new QuadTree_QuadTree(new Rectangle(x + w / 2, y + h / 2, w / 2, h / 2), capacity);
this.divided = true;
}
insert(point) {
var _a, _b, _c, _d, _e;
if (!this.rectangle.contains(point.position)) {
return false;
}
if (this.points.length < this.capacity) {
this.points.push(point);
return true;
}
if (!this.divided) {
this.subdivide();
}
return (_e = ((_a = this.northEast) === null || _a === void 0 ? void 0 : _a.insert(point)) || ((_b = this.northWest) === null || _b === void 0 ? void 0 : _b.insert(point)) || ((_c = this.southEast) === null || _c === void 0 ? void 0 : _c.insert(point)) || ((_d = this.southWest) === null || _d === void 0 ? void 0 : _d.insert(point))) !== null && _e !== void 0 ? _e : false;
}
queryCircle(position, radius) {
return this.query(new Circle(position.x, position.y, radius));
}
queryCircleWarp(position, radius, containerOrSize) {
const container = containerOrSize;
const size = containerOrSize;
return this.query(new CircleWarp(position.x, position.y, radius, container.canvas !== undefined ? container.canvas.size : size));
}
queryRectangle(position, size) {
return this.query(new Rectangle(position.x, position.y, size.width, size.height));
}
query(range, found) {
var _a, _b, _c, _d;
const res = found !== null && found !== void 0 ? found : [];
if (!range.intersects(this.rectangle)) {
return [];
} else {
for (const p of this.points) {
if (!range.contains(p.position) && getDistance(range.position, p.position) > p.particle.getRadius()) {
continue;
}
res.push(p.particle);
}
if (this.divided) {
(_a = this.northEast) === null || _a === void 0 ? void 0 : _a.query(range, res);
(_b = this.northWest) === null || _b === void 0 ? void 0 : _b.query(range, res);
(_c = this.southEast) === null || _c === void 0 ? void 0 : _c.query(range, res);
(_d = this.southWest) === null || _d === void 0 ? void 0 : _d.query(range, res);
}
}
return res;
}
}
class Canvas_Canvas {
constructor(container) {
this.container = container;
this.size = {
height: 0,
width: 0
};
this.context = null;
this.generatedCanvas = false;
}
init() {
this.resize();
this.initStyle();
this.initCover();
this.initTrail();
this.initBackground();
this.paint();
}
loadCanvas(canvas) {
var _a;
if (this.generatedCanvas) {
(_a = this.element) === null || _a === void 0 ? void 0 : _a.remove();
}
this.generatedCanvas = canvas.dataset && Constants.generatedAttribute in canvas.dataset ? canvas.dataset[Constants.generatedAttribute] === "true" : this.generatedCanvas;
this.element = canvas;
this.originalStyle = deepExtend({}, this.element.style);
this.size.height = canvas.offsetHeight;
this.size.width = canvas.offsetWidth;
this.context = this.element.getContext("2d");
this.container.retina.init();
this.initBackground();
}
destroy() {
var _a;
if (this.generatedCanvas) {
(_a = this.element) === null || _a === void 0 ? void 0 : _a.remove();
}
this.draw((ctx => {
clear(ctx, this.size);
}));
}
paint() {
const options = this.container.actualOptions;
this.draw((ctx => {
if (options.backgroundMask.enable && options.backgroundMask.cover && this.coverColor) {
clear(ctx, this.size);
this.paintBase(getStyleFromRgb(this.coverColor, this.coverColor.a));
} else {
this.paintBase();
}
}));
}
clear() {
const options = this.container.actualOptions;
const trail = options.particles.move.trail;
if (options.backgroundMask.enable) {
this.paint();
} else if (trail.enable && trail.length > 0 && this.trailFillColor) {
this.paintBase(getStyleFromRgb(this.trailFillColor, 1 / trail.length));
} else {
this.draw((ctx => {
clear(ctx, this.size);
}));
}
}
async windowResize() {
if (!this.element) {
return;
}
const container = this.container;
this.resize();
const needsRefresh = container.updateActualOptions();
container.particles.setDensity();
for (const [, plugin] of container.plugins) {
if (plugin.resize !== undefined) {
plugin.resize();
}
}
if (needsRefresh) {
await container.refresh();
}
}
resize() {
if (!this.element) {
return;
}
const container = this.container;
const pxRatio = container.retina.pixelRatio;
const size = container.canvas.size;
const oldSize = {
width: size.width,
height: size.height
};
size.width = this.element.offsetWidth * pxRatio;
size.height = this.element.offsetHeight * pxRatio;
this.element.width = size.width;
this.element.height = size.height;
if (this.container.started) {
this.resizeFactor = {
width: size.width / oldSize.width,
height: size.height / oldSize.height
};
}
}
drawConnectLine(p1, p2) {
this.draw((ctx => {
var _a;
const lineStyle = this.lineStyle(p1, p2);
if (!lineStyle) {
return;
}
const pos1 = p1.getPosition();
const pos2 = p2.getPosition();
drawConnectLine(ctx, (_a = p1.retina.linksWidth) !== null && _a !== void 0 ? _a : this.container.retina.linksWidth, lineStyle, pos1, pos2);
}));
}
drawGrabLine(particle, lineColor, opacity, mousePos) {
const container = this.container;
this.draw((ctx => {
var _a;
const beginPos = particle.getPosition();
drawGrabLine(ctx, (_a = particle.retina.linksWidth) !== null && _a !== void 0 ? _a : container.retina.linksWidth, beginPos, mousePos, lineColor, opacity);
}));
}
drawParticle(particle, delta) {
var _a, _b, _c, _d, _e, _f;
if (particle.spawning || particle.destroyed) {
return;
}
const pfColor = particle.getFillColor();
const psColor = (_a = particle.getStrokeColor()) !== null && _a !== void 0 ? _a : pfColor;
if (!pfColor && !psColor) {
return;
}
let [fColor, sColor] = this.getPluginParticleColors(particle);
const pOptions = particle.options;
const twinkle = pOptions.twinkle.particles;
const twinkling = twinkle.enable && Math.random() < twinkle.frequency;
if (!fColor || !sColor) {
const twinkleRgb = colorToHsl(twinkle.color);
if (!fColor) {
fColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : pfColor ? pfColor : undefined;
}
if (!sColor) {
sColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : psColor ? psColor : undefined;
}
}
const options = this.container.actualOptions;
const zIndexOptions = particle.options.zIndex;
const zOpacityFactor = (1 - particle.zIndexFactor) ** zIndexOptions.opacityRate;
const radius = particle.getRadius();
const opacity = twinkling ? twinkle.opacity : (_d = (_b = particle.bubble.opacity) !== null && _b !== void 0 ? _b : (_c = particle.opacity) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 1;
const strokeOpacity = (_f = (_e = particle.stroke) === null || _e === void 0 ? void 0 : _e.opacity) !== null && _f !== void 0 ? _f : opacity;
const zOpacity = opacity * zOpacityFactor;
const fillColorValue = fColor ? getStyleFromHsl(fColor, zOpacity) : undefined;
if (!fillColorValue && !sColor) {
return;
}
this.draw((ctx => {
const zSizeFactor = (1 - particle.zIndexFactor) ** zIndexOptions.sizeRate;
const zStrokeOpacity = strokeOpacity * zOpacityFactor;
const strokeColorValue = sColor ? getStyleFromHsl(sColor, zStrokeOpacity) : fillColorValue;
if (radius <= 0) {
return;
}
const container = this.container;
for (const updater of container.particles.updaters) {
if (updater.beforeDraw) {
updater.beforeDraw(particle);
}
}
drawParticle(this.container, ctx, particle, delta, fillColorValue, strokeColorValue, options.backgroundMask.enable, options.backgroundMask.composite, radius * zSizeFactor, zOpacity, particle.options.shadow, particle.gradient);
for (const updater of container.particles.updaters) {
if (updater.afterDraw) {
updater.afterDraw(particle);
}
}
}));
}
drawPlugin(plugin, delta) {
this.draw((ctx => {
drawPlugin(ctx, plugin, delta);
}));
}
drawParticlePlugin(plugin, particle, delta) {
this.draw((ctx => {
drawParticlePlugin(ctx, plugin, particle, delta);
}));
}
initBackground() {
const options = this.container.actualOptions;
const background = options.background;
const element = this.element;
const elementStyle = element === null || element === void 0 ? void 0 : element.style;
if (!elementStyle) {
return;
}
if (background.color) {
const color = colorToRgb(background.color);
elementStyle.backgroundColor = color ? getStyleFromRgb(color, background.opacity) : "";
} else {
elementStyle.backgroundColor = "";
}
elementStyle.backgroundImage = background.image || "";
elementStyle.backgroundPosition = background.position || "";
elementStyle.backgroundRepeat = background.repeat || "";
elementStyle.backgroundSize = background.size || "";
}
draw(cb) {
if (!this.context) {
return;
}
return cb(this.context);
}
initCover() {
const options = this.container.actualOptions;
const cover = options.backgroundMask.cover;
const color = cover.color;
const coverRgb = colorToRgb(color);
if (coverRgb) {
this.coverColor = {
r: coverRgb.r,
g: coverRgb.g,
b: coverRgb.b,
a: cover.opacity
};
}
}
initTrail() {
const options = this.container.actualOptions;
const trail = options.particles.move.trail;
const fillColor = colorToRgb(trail.fillColor);
if (fillColor) {
const trail = options.particles.move.trail;
this.trailFillColor = {
r: fillColor.r,
g: fillColor.g,
b: fillColor.b,
a: 1 / trail.length
};
}
}
getPluginParticleColors(particle) {
let fColor;
let sColor;
for (const [, plugin] of this.container.plugins) {
if (!fColor && plugin.particleFillColor) {
fColor = colorToHsl(plugin.particleFillColor(particle));
}
if (!sColor && plugin.particleStrokeColor) {
sColor = colorToHsl(plugin.particleStrokeColor(particle));
}
if (fColor && sColor) {
break;
}
}
return [ fColor, sColor ];
}
initStyle() {
const element = this.element, options = this.container.actualOptions;
if (!element) {
return;
}
const originalStyle = this.originalStyle;
if (options.fullScreen.enable) {
this.originalStyle = deepExtend({}, element.style);
element.style.setProperty("position", "fixed", "important");
element.style.setProperty("z-index", options.fullScreen.zIndex.toString(10), "important");
element.style.setProperty("top", "0", "important");
element.style.setProperty("left", "0", "important");
element.style.setProperty("width", "100%", "important");
element.style.setProperty("height", "100%", "important");
} else if (originalStyle) {
element.style.position = originalStyle.position;
element.style.zIndex = originalStyle.zIndex;
element.style.top = originalStyle.top;
element.style.left = originalStyle.left;
element.style.width = originalStyle.width;
element.style.height = originalStyle.height;
}
for (const key in options.style) {
if (!key || !options.style) {
continue;
}
const value = options.style[key];
if (!value) {
continue;
}
element.style.setProperty(key, value, "important");
}
}
paintBase(baseColor) {
this.draw((ctx => {
paintBase(ctx, this.size, baseColor);
}));
}
lineStyle(p1, p2) {
return this.draw((ctx => {
const options = this.container.actualOptions;
const connectOptions = options.interactivity.modes.connect;
return gradient(ctx, p1, p2, connectOptions.links.opacity);
}));
}
}
class Trail_Trail {
constructor() {
this.delay = 1;
this.pauseOnStop = false;
this.quantity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.delay !== undefined) {
this.delay = data.delay;
}
if (data.quantity !== undefined) {
this.quantity = data.quantity;
}
if (data.particles !== undefined) {
this.particles = deepExtend({}, data.particles);
}
if (data.pauseOnStop !== undefined) {
this.pauseOnStop = data.pauseOnStop;
}
}
}
class Modes_Modes {
constructor() {
this.attract = new Attract;
this.bounce = new Bounce;
this.bubble = new Bubble;
this.connect = new Connect;
this.grab = new Grab;
this.light = new Light;
this.push = new Push;
this.remove = new Remove;
this.repulse = new Repulse;
this.slow = new Slow;
this.trail = new Trail;
}
load(data) {
if (data === undefined) {
return;
}
this.attract.load(data.attract);
this.bubble.load(data.bubble);
this.connect.load(data.connect);
this.grab.load(data.grab);
this.light.load(data.light);
this.push.load(data.push);
this.remove.load(data.remove);
this.repulse.load(data.repulse);
this.slow.load(data.slow);
this.trail.load(data.trail);
}
}
class Interactivity_Interactivity {
constructor() {
this.detectsOn = "window";
this.events = new Events;
this.modes = new Modes;
}
get detect_on() {
return this.detectsOn;
}
set detect_on(value) {
this.detectsOn = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
const detectsOn = (_a = data.detectsOn) !== null && _a !== void 0 ? _a : data.detect_on;
if (detectsOn !== undefined) {
this.detectsOn = detectsOn;
}
this.events.load(data.events);
this.modes.load(data.modes);
if (((_c = (_b = data.modes) === null || _b === void 0 ? void 0 : _b.slow) === null || _c === void 0 ? void 0 : _c.active) === true) {
if (this.events.onHover.mode instanceof Array) {
if (this.events.onHover.mode.indexOf("slow") < 0) {
this.events.onHover.mode.push("slow");
}
} else if (this.events.onHover.mode !== "slow") {
this.events.onHover.mode = [ this.events.onHover.mode, "slow" ];
}
}
}
}
class ManualParticle_ManualParticle {
load(data) {
var _a, _b;
if (!data) {
return;
}
if (data.position !== undefined) {
this.position = {
x: (_a = data.position.x) !== null && _a !== void 0 ? _a : 50,
y: (_b = data.position.y) !== null && _b !== void 0 ? _b : 50
};
}
if (data.options !== undefined) {
this.options = deepExtend({}, data.options);
}
}
}
class ColorAnimation_ColorAnimation {
constructor() {
this.count = 0;
this.enable = false;
this.offset = 0;
this.speed = 1;
this.sync = true;
}
load(data) {
if (data === undefined) {
return;
}
if (data.count !== undefined) {
this.count = data.count;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.offset !== undefined) {
this.offset = setRangeValue(data.offset);
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
class HslAnimation_HslAnimation {
constructor() {
this.h = new ColorAnimation;
this.s = new ColorAnimation;
this.l = new ColorAnimation;
}
load(data) {
if (!data) {
return;
}
this.h.load(data.h);
this.s.load(data.s);
this.l.load(data.l);
}
}
class AnimatableColor_AnimatableColor extends(null && OptionsColor){
constructor() {
super();
this.animation = new HslAnimation;
}
static create(source, data) {
const color = new AnimatableColor_AnimatableColor;
color.load(source);
if (data !== undefined) {
if (typeof data === "string" || data instanceof Array) {
color.load({
value: data
});
} else {
color.load(data);
}
}
return color;
}
load(data) {
super.load(data);
if (!data) {
return;
}
const colorAnimation = data.animation;
if (colorAnimation !== undefined) {
if (colorAnimation.enable !== undefined) {
this.animation.h.load(colorAnimation);
} else {
this.animation.load(data.animation);
}
}
}
}
class AnimatableGradient_AnimatableGradient {
constructor() {
this.angle = new GradientAngle;
this.colors = [];
this.type = "random";
}
load(data) {
if (!data) {
return;
}
this.angle.load(data.angle);
if (data.colors !== undefined) {
this.colors = data.colors.map((s => {
const tmp = new AnimatableGradientColor;
tmp.load(s);
return tmp;
}));
}
if (data.type !== undefined) {
this.type = data.type;
}
}
}
class GradientAngle {
constructor() {
this.value = 0;
this.animation = new GradientAngleAnimation;
this.direction = "clockwise";
}
load(data) {
if (!data) {
return;
}
this.animation.load(data.animation);
if (data.value !== undefined) {
this.value = data.value;
}
if (data.direction !== undefined) {
this.direction = data.direction;
}
}
}
class GradientColorOpacity {
constructor() {
this.value = 0;
this.animation = new GradientColorOpacityAnimation;
}
load(data) {
if (!data) {
return;
}
this.animation.load(data.animation);
if (data.value !== undefined) {
this.value = setRangeValue(data.value);
}
}
}
class AnimatableGradientColor {
constructor() {
this.stop = 0;
this.value = new AnimatableColor;
}
load(data) {
if (!data) {
return;
}
if (data.stop !== undefined) {
this.stop = data.stop;
}
this.value = AnimatableColor.create(this.value, data.value);
if (data.opacity !== undefined) {
this.opacity = new GradientColorOpacity;
if (typeof data.opacity === "number") {
this.opacity.value = data.opacity;
} else {
this.opacity.load(data.opacity);
}
}
}
}
class GradientAngleAnimation {
constructor() {
this.count = 0;
this.enable = false;
this.speed = 0;
this.sync = false;
}
load(data) {
if (!data) {
return;
}
if (data.count !== undefined) {
this.count = data.count;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
class GradientColorOpacityAnimation {
constructor() {
this.count = 0;
this.enable = false;
this.speed = 0;
this.sync = false;
this.startValue = "random";
}
load(data) {
if (!data) {
return;
}
if (data.count !== undefined) {
this.count = data.count;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
if (data.startValue !== undefined) {
this.startValue = data.startValue;
}
}
}
class ValueWithRandom_ValueWithRandom {
constructor() {
this.random = new Random;
this.value = 0;
}
load(data) {
if (!data) {
return;
}
if (typeof data.random === "boolean") {
this.random.enable = data.random;
} else {
this.random.load(data.random);
}
if (data.value !== undefined) {
this.value = setRangeValue(data.value, this.random.enable ? this.random.minimumValue : undefined);
}
}
}
class BounceFactor_BounceFactor extends(null && ValueWithRandom){
constructor() {
super();
this.random.minimumValue = .1;
this.value = 1;
}
}
class Bounce_Bounce {
constructor() {
this.horizontal = new BounceFactor;
this.vertical = new BounceFactor;
}
load(data) {
if (!data) {
return;
}
this.horizontal.load(data.horizontal);
this.vertical.load(data.vertical);
}
}
class Collisions_Collisions {
constructor() {
this.bounce = new Bounce;
this.enable = false;
this.mode = "bounce";
this.overlap = new CollisionsOverlap;
}
load(data) {
if (data === undefined) {
return;
}
this.bounce.load(data.bounce);
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
this.overlap.load(data.overlap);
}
}
class SplitFactor_SplitFactor extends(null && ValueWithRandom){
constructor() {
super();
this.value = 3;
}
}
class SplitRate_SplitRate extends(null && ValueWithRandom){
constructor() {
super();
this.value = {
min: 4,
max: 9
};
}
}
class Split_Split {
constructor() {
this.count = 1;
this.factor = new SplitFactor;
this.rate = new SplitRate;
this.sizeOffset = true;
}
load(data) {
if (!data) {
return;
}
if (data.count !== undefined) {
this.count = data.count;
}
this.factor.load(data.factor);
this.rate.load(data.rate);
if (data.particles !== undefined) {
this.particles = deepExtend({}, data.particles);
}
if (data.sizeOffset !== undefined) {
this.sizeOffset = data.sizeOffset;
}
}
}
class Destroy_Destroy {
constructor() {
this.mode = "none";
this.split = new Split;
}
load(data) {
if (!data) {
return;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
this.split.load(data.split);
}
}
class LifeDelay_LifeDelay extends(null && ValueWithRandom){
constructor() {
super();
this.sync = false;
}
load(data) {
if (!data) {
return;
}
super.load(data);
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
class LifeDuration_LifeDuration extends(null && ValueWithRandom){
constructor() {
super();
this.random.minimumValue = 1e-4;
this.sync = false;
}
load(data) {
if (data === undefined) {
return;
}
super.load(data);
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
class Life_Life {
constructor() {
this.count = 0;
this.delay = new LifeDelay;
this.duration = new LifeDuration;
}
load(data) {
if (data === undefined) {
return;
}
if (data.count !== undefined) {
this.count = data.count;
}
this.delay.load(data.delay);
this.duration.load(data.duration);
}
}
class PathDelay_PathDelay extends(null && ValueWithRandom){
constructor() {
super();
}
}
class Path_Path {
constructor() {
this.clamp = true;
this.delay = new PathDelay;
this.enable = false;
this.options = {};
}
load(data) {
if (data === undefined) {
return;
}
if (data.clamp !== undefined) {
this.clamp = data.clamp;
}
this.delay.load(data.delay);
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.generator = data.generator;
if (data.options) {
this.options = deepExtend(this.options, data.options);
}
}
}
class Spin_Spin {
constructor() {
this.acceleration = 0;
this.enable = false;
}
load(data) {
if (!data) {
return;
}
if (data.acceleration !== undefined) {
this.acceleration = setRangeValue(data.acceleration);
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.position = data.position ? deepExtend({}, data.position) : undefined;
}
}
class Move_Move {
constructor() {
this.angle = new MoveAngle;
this.attract = new Attract;
this.decay = 0;
this.distance = {};
this.direction = "none";
this.drift = 0;
this.enable = false;
this.gravity = new MoveGravity;
this.path = new Path;
this.outModes = new OutModes;
this.random = false;
this.size = false;
this.speed = 2;
this.spin = new Spin;
this.straight = false;
this.trail = new Trail;
this.vibrate = false;
this.warp = false;
}
get collisions() {
return false;
}
set collisions(value) {}
get bounce() {
return this.collisions;
}
set bounce(value) {
this.collisions = value;
}
get out_mode() {
return this.outMode;
}
set out_mode(value) {
this.outMode = value;
}
get outMode() {
return this.outModes.default;
}
set outMode(value) {
this.outModes.default = value;
}
get noise() {
return this.path;
}
set noise(value) {
this.path = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
if (data.angle !== undefined) {
if (typeof data.angle === "number") {
this.angle.value = data.angle;
} else {
this.angle.load(data.angle);
}
}
this.attract.load(data.attract);
if (data.decay !== undefined) {
this.decay = data.decay;
}
if (data.direction !== undefined) {
this.direction = data.direction;
}
if (data.distance !== undefined) {
this.distance = typeof data.distance === "number" ? {
horizontal: data.distance,
vertical: data.distance
} : deepExtend({}, data.distance);
}
if (data.drift !== undefined) {
this.drift = setRangeValue(data.drift);
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.gravity.load(data.gravity);
const outMode = (_a = data.outMode) !== null && _a !== void 0 ? _a : data.out_mode;
if (data.outModes !== undefined || outMode !== undefined) {
if (typeof data.outModes === "string" || data.outModes === undefined && outMode !== undefined) {
this.outModes.load({
default: (_b = data.outModes) !== null && _b !== void 0 ? _b : outMode
});
} else {
this.outModes.load(data.outModes);
}
}
this.path.load((_c = data.path) !== null && _c !== void 0 ? _c : data.noise);
if (data.random !== undefined) {
this.random = data.random;
}
if (data.size !== undefined) {
this.size = data.size;
}
if (data.speed !== undefined) {
this.speed = setRangeValue(data.speed);
}
this.spin.load(data.spin);
if (data.straight !== undefined) {
this.straight = data.straight;
}
this.trail.load(data.trail);
if (data.vibrate !== undefined) {
this.vibrate = data.vibrate;
}
if (data.warp !== undefined) {
this.warp = data.warp;
}
}
}
class Opacity_Opacity extends(null && ValueWithRandom){
constructor() {
super();
this.animation = new OpacityAnimation;
this.random.minimumValue = .1;
this.value = 1;
}
get anim() {
return this.animation;
}
set anim(value) {
this.animation = value;
}
load(data) {
var _a;
if (!data) {
return;
}
super.load(data);
const animation = (_a = data.animation) !== null && _a !== void 0 ? _a : data.anim;
if (animation !== undefined) {
this.animation.load(animation);
this.value = setRangeValue(this.value, this.animation.enable ? this.animation.minimumValue : undefined);
}
}
}
class OrbitRotation_OrbitRotation extends(null && ValueWithRandom){
constructor() {
super();
this.value = 45;
this.random.enable = false;
this.random.minimumValue = 0;
}
load(data) {
if (data === undefined) {
return;
}
super.load(data);
}
}
class Orbit_Orbit {
constructor() {
this.animation = new AnimationOptions;
this.enable = false;
this.opacity = 1;
this.rotation = new OrbitRotation;
this.width = 1;
}
load(data) {
if (data === undefined) {
return;
}
this.animation.load(data.animation);
this.rotation.load(data.rotation);
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
if (data.width !== undefined) {
this.width = data.width;
}
if (data.radius !== undefined) {
this.radius = data.radius;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
}
}
class Repulse_Repulse extends(null && ValueWithRandom){
constructor() {
super();
this.enabled = false;
this.distance = 1;
this.duration = 1;
this.factor = 1;
this.speed = 1;
}
load(data) {
super.load(data);
if (!data) {
return;
}
if (data.enabled !== undefined) {
this.enabled = data.enabled;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
if (data.factor !== undefined) {
this.factor = data.factor;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
}
}
class Roll_Roll {
constructor() {
this.darken = new RollLight;
this.enable = false;
this.enlighten = new RollLight;
this.mode = "vertical";
this.speed = 25;
}
load(data) {
if (!data) {
return;
}
if (data.backColor !== undefined) {
this.backColor = OptionsColor.create(this.backColor, data.backColor);
}
this.darken.load(data.darken);
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.enlighten.load(data.enlighten);
if (data.mode !== undefined) {
this.mode = data.mode;
}
if (data.speed !== undefined) {
this.speed = setRangeValue(data.speed);
}
}
}
class Rotate_Rotate extends(null && ValueWithRandom){
constructor() {
super();
this.animation = new RotateAnimation;
this.direction = "clockwise";
this.path = false;
this.value = 0;
}
load(data) {
if (!data) {
return;
}
super.load(data);
if (data.direction !== undefined) {
this.direction = data.direction;
}
this.animation.load(data.animation);
if (data.path !== undefined) {
this.path = data.path;
}
}
}
class Shape_Shape {
constructor() {
this.options = {};
this.type = "circle";
}
get image() {
var _a;
return (_a = this.options["image"]) !== null && _a !== void 0 ? _a : this.options["images"];
}
set image(value) {
this.options["image"] = value;
this.options["images"] = value;
}
get custom() {
return this.options;
}
set custom(value) {
this.options = value;
}
get images() {
return this.image;
}
set images(value) {
this.image = value;
}
get stroke() {
return [];
}
set stroke(_value) {}
get character() {
var _a;
return (_a = this.options["character"]) !== null && _a !== void 0 ? _a : this.options["char"];
}
set character(value) {
this.options["character"] = value;
this.options["char"] = value;
}
get polygon() {
var _a;
return (_a = this.options["polygon"]) !== null && _a !== void 0 ? _a : this.options["star"];
}
set polygon(value) {
this.options["polygon"] = value;
this.options["star"] = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
const options = (_a = data.options) !== null && _a !== void 0 ? _a : data.custom;
if (options !== undefined) {
for (const shape in options) {
const item = options[shape];
if (item !== undefined) {
this.options[shape] = deepExtend((_b = this.options[shape]) !== null && _b !== void 0 ? _b : {}, item);
}
}
}
this.loadShape(data.character, "character", "char", true);
this.loadShape(data.polygon, "polygon", "star", false);
this.loadShape((_c = data.image) !== null && _c !== void 0 ? _c : data.images, "image", "images", true);
if (data.type !== undefined) {
this.type = data.type;
}
}
loadShape(item, mainKey, altKey, altOverride) {
var _a, _b, _c, _d;
if (item === undefined) {
return;
}
if (item instanceof Array) {
if (!(this.options[mainKey] instanceof Array)) {
this.options[mainKey] = [];
if (!this.options[altKey] || altOverride) {
this.options[altKey] = [];
}
}
this.options[mainKey] = deepExtend((_a = this.options[mainKey]) !== null && _a !== void 0 ? _a : [], item);
if (!this.options[altKey] || altOverride) {
this.options[altKey] = deepExtend((_b = this.options[altKey]) !== null && _b !== void 0 ? _b : [], item);
}
} else {
if (this.options[mainKey] instanceof Array) {
this.options[mainKey] = {};
if (!this.options[altKey] || altOverride) {
this.options[altKey] = {};
}
}
this.options[mainKey] = deepExtend((_c = this.options[mainKey]) !== null && _c !== void 0 ? _c : {}, item);
if (!this.options[altKey] || altOverride) {
this.options[altKey] = deepExtend((_d = this.options[altKey]) !== null && _d !== void 0 ? _d : {}, item);
}
}
}
}
class Size_Size extends(null && ValueWithRandom){
constructor() {
super();
this.animation = new SizeAnimation;
this.random.minimumValue = 1;
this.value = 3;
}
get anim() {
return this.animation;
}
set anim(value) {
this.animation = value;
}
load(data) {
var _a;
if (!data) {
return;
}
super.load(data);
const animation = (_a = data.animation) !== null && _a !== void 0 ? _a : data.anim;
if (animation !== undefined) {
this.animation.load(animation);
this.value = setRangeValue(this.value, this.animation.enable ? this.animation.minimumValue : undefined);
}
}
}
class Stroke_Stroke {
constructor() {
this.width = 0;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = AnimatableColor.create(this.color, data.color);
}
if (data.width !== undefined) {
this.width = data.width;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
class Tilt_Tilt extends(null && ValueWithRandom){
constructor() {
super();
this.animation = new TiltAnimation;
this.direction = "clockwise";
this.enable = false;
this.value = 0;
}
load(data) {
if (!data) {
return;
}
super.load(data);
this.animation.load(data.animation);
if (data.direction !== undefined) {
this.direction = data.direction;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
}
}
class Wobble_Wobble {
constructor() {
this.distance = 5;
this.enable = false;
this.speed = 50;
}
load(data) {
if (!data) {
return;
}
if (data.distance !== undefined) {
this.distance = setRangeValue(data.distance);
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.speed !== undefined) {
this.speed = setRangeValue(data.speed);
}
}
}
class ZIndex_ZIndex extends(null && ValueWithRandom){
constructor() {
super();
this.opacityRate = 1;
this.sizeRate = 1;
this.velocityRate = 1;
}
load(data) {
super.load(data);
if (!data) {
return;
}
if (data.opacityRate !== undefined) {
this.opacityRate = data.opacityRate;
}
if (data.sizeRate !== undefined) {
this.sizeRate = data.sizeRate;
}
if (data.velocityRate !== undefined) {
this.velocityRate = data.velocityRate;
}
}
}
class ParticlesOptions_ParticlesOptions {
constructor() {
this.bounce = new Bounce;
this.collisions = new Collisions;
this.color = new AnimatableColor;
this.destroy = new Destroy;
this.gradient = [];
this.groups = {};
this.life = new Life;
this.links = new Links;
this.move = new Move;
this.number = new ParticlesNumber;
this.opacity = new Opacity;
this.orbit = new Orbit;
this.reduceDuplicates = false;
this.repulse = new Repulse;
this.roll = new Roll;
this.rotate = new Rotate;
this.shadow = new Shadow;
this.shape = new Shape;
this.size = new Size;
this.stroke = new Stroke;
this.tilt = new Tilt;
this.twinkle = new Twinkle;
this.wobble = new Wobble;
this.zIndex = new ZIndex;
}
get line_linked() {
return this.links;
}
set line_linked(value) {
this.links = value;
}
get lineLinked() {
return this.links;
}
set lineLinked(value) {
this.links = value;
}
load(data) {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (data === undefined) {
return;
}
this.bounce.load(data.bounce);
this.color.load(AnimatableColor.create(this.color, data.color));
this.destroy.load(data.destroy);
this.life.load(data.life);
const links = (_b = (_a = data.links) !== null && _a !== void 0 ? _a : data.lineLinked) !== null && _b !== void 0 ? _b : data.line_linked;
if (links !== undefined) {
this.links.load(links);
}
if (data.groups !== undefined) {
for (const group in data.groups) {
const item = data.groups[group];
if (item !== undefined) {
this.groups[group] = deepExtend((_c = this.groups[group]) !== null && _c !== void 0 ? _c : {}, item);
}
}
}
this.move.load(data.move);
this.number.load(data.number);
this.opacity.load(data.opacity);
this.orbit.load(data.orbit);
if (data.reduceDuplicates !== undefined) {
this.reduceDuplicates = data.reduceDuplicates;
}
this.repulse.load(data.repulse);
this.roll.load(data.roll);
this.rotate.load(data.rotate);
this.shape.load(data.shape);
this.size.load(data.size);
this.shadow.load(data.shadow);
this.tilt.load(data.tilt);
this.twinkle.load(data.twinkle);
this.wobble.load(data.wobble);
this.zIndex.load(data.zIndex);
const collisions = (_e = (_d = data.move) === null || _d === void 0 ? void 0 : _d.collisions) !== null && _e !== void 0 ? _e : (_f = data.move) === null || _f === void 0 ? void 0 : _f.bounce;
if (collisions !== undefined) {
this.collisions.enable = collisions;
}
this.collisions.load(data.collisions);
const strokeToLoad = (_g = data.stroke) !== null && _g !== void 0 ? _g : (_h = data.shape) === null || _h === void 0 ? void 0 : _h.stroke;
if (strokeToLoad) {
if (strokeToLoad instanceof Array) {
this.stroke = strokeToLoad.map((s => {
const tmp = new Stroke;
tmp.load(s);
return tmp;
}));
} else {
if (this.stroke instanceof Array) {
this.stroke = new Stroke;
}
this.stroke.load(strokeToLoad);
}
}
const gradientToLoad = data.gradient;
if (gradientToLoad) {
if (gradientToLoad instanceof Array) {
this.gradient = gradientToLoad.map((s => {
const tmp = new AnimatableGradient;
tmp.load(s);
return tmp;
}));
} else {
if (this.gradient instanceof Array) {
this.gradient = new AnimatableGradient;
}
this.gradient.load(gradientToLoad);
}
}
}
}
class Responsive_Responsive {
constructor() {
this.maxWidth = Infinity;
this.options = {};
this.mode = "canvas";
}
load(data) {
if (!data) {
return;
}
if (data.maxWidth !== undefined) {
this.maxWidth = data.maxWidth;
}
if (data.mode !== undefined) {
if (data.mode === "screen") {
this.mode = "screen";
} else {
this.mode = "canvas";
}
}
if (data.options !== undefined) {
this.options = deepExtend({}, data.options);
}
}
}
class Theme_Theme {
constructor() {
this.name = "";
this.default = new ThemeDefault;
}
load(data) {
if (data === undefined) {
return;
}
if (data.name !== undefined) {
this.name = data.name;
}
this.default.load(data.default);
if (data.options !== undefined) {
this.options = deepExtend({}, data.options);
}
}
}
var __classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Options_instances, _Options_findDefaultTheme;
class Options_Options {
constructor() {
_Options_instances.add(this);
this.autoPlay = true;
this.background = new Background;
this.backgroundMask = new BackgroundMask;
this.fullScreen = new FullScreen;
this.detectRetina = true;
this.duration = 0;
this.fpsLimit = 60;
this.interactivity = new Interactivity;
this.manualParticles = [];
this.motion = new Motion;
this.particles = new ParticlesOptions;
this.pauseOnBlur = true;
this.pauseOnOutsideViewport = true;
this.responsive = [];
this.style = {};
this.themes = [];
this.zLayers = 100;
}
get fps_limit() {
return this.fpsLimit;
}
set fps_limit(value) {
this.fpsLimit = value;
}
get retina_detect() {
return this.detectRetina;
}
set retina_detect(value) {
this.detectRetina = value;
}
get backgroundMode() {
return this.fullScreen;
}
set backgroundMode(value) {
this.fullScreen.load(value);
}
load(data) {
var _a, _b, _c, _d, _e;
if (data === undefined) {
return;
}
if (data.preset !== undefined) {
if (data.preset instanceof Array) {
for (const preset of data.preset) {
this.importPreset(preset);
}
} else {
this.importPreset(data.preset);
}
}
if (data.autoPlay !== undefined) {
this.autoPlay = data.autoPlay;
}
const detectRetina = (_a = data.detectRetina) !== null && _a !== void 0 ? _a : data.retina_detect;
if (detectRetina !== undefined) {
this.detectRetina = detectRetina;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
const fpsLimit = (_b = data.fpsLimit) !== null && _b !== void 0 ? _b : data.fps_limit;
if (fpsLimit !== undefined) {
this.fpsLimit = fpsLimit;
}
if (data.pauseOnBlur !== undefined) {
this.pauseOnBlur = data.pauseOnBlur;
}
if (data.pauseOnOutsideViewport !== undefined) {
this.pauseOnOutsideViewport = data.pauseOnOutsideViewport;
}
if (data.zLayers !== undefined) {
this.zLayers = data.zLayers;
}
this.background.load(data.background);
const fullScreen = (_c = data.fullScreen) !== null && _c !== void 0 ? _c : data.backgroundMode;
if (typeof fullScreen === "boolean") {
this.fullScreen.enable = fullScreen;
} else {
this.fullScreen.load(fullScreen);
}
this.backgroundMask.load(data.backgroundMask);
this.interactivity.load(data.interactivity);
if (data.manualParticles !== undefined) {
this.manualParticles = data.manualParticles.map((t => {
const tmp = new ManualParticle;
tmp.load(t);
return tmp;
}));
}
this.motion.load(data.motion);
this.particles.load(data.particles);
this.style = deepExtend(this.style, data.style);
Plugins.loadOptions(this, data);
if (data.responsive !== undefined) {
for (const responsive of data.responsive) {
const optResponsive = new Responsive;
optResponsive.load(responsive);
this.responsive.push(optResponsive);
}
}
this.responsive.sort(((a, b) => a.maxWidth - b.maxWidth));
if (data.themes !== undefined) {
for (const theme of data.themes) {
const optTheme = new Theme;
optTheme.load(theme);
this.themes.push(optTheme);
}
}
this.defaultDarkTheme = (_d = __classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, "dark")) === null || _d === void 0 ? void 0 : _d.name;
this.defaultLightTheme = (_e = __classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, "light")) === null || _e === void 0 ? void 0 : _e.name;
}
setTheme(name) {
if (name) {
const chosenTheme = this.themes.find((theme => theme.name === name));
if (chosenTheme) {
this.load(chosenTheme.options);
}
} else {
const mediaMatch = typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)"), clientDarkMode = mediaMatch && mediaMatch.matches, defaultTheme = __classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, clientDarkMode ? "dark" : "light");
if (defaultTheme) {
this.load(defaultTheme.options);
}
}
}
setResponsive(width, pxRatio, defaultOptions) {
this.load(defaultOptions);
const responsiveOptions = this.responsive.find((t => t.mode === "screen" && screen ? t.maxWidth * pxRatio > screen.availWidth : t.maxWidth * pxRatio > width));
this.load(responsiveOptions === null || responsiveOptions === void 0 ? void 0 : responsiveOptions.options);
return responsiveOptions === null || responsiveOptions === void 0 ? void 0 : responsiveOptions.maxWidth;
}
importPreset(preset) {
this.load(Plugins.getPreset(preset));
}
}
_Options_instances = new WeakSet, _Options_findDefaultTheme = function _Options_findDefaultTheme(mode) {
var _a;
return (_a = this.themes.find((theme => theme.default.value && theme.default.mode === mode))) !== null && _a !== void 0 ? _a : this.themes.find((theme => theme.default.value && theme.default.mode === "any"));
};
const fixOutMode = data => {
if (isInArray(data.outMode, data.checkModes) || isInArray(data.outMode, data.checkModes)) {
if (data.coord > data.maxCoord - data.radius * 2) {
data.setCb(-data.radius);
} else if (data.coord < data.radius * 2) {
data.setCb(data.radius);
}
}
};
class Particle_Particle {
constructor(id, container, position, overrideOptions, group) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
this.id = id;
this.container = container;
this.group = group;
this.fill = true;
this.close = true;
this.lastPathTime = 0;
this.destroyed = false;
this.unbreakable = false;
this.splitCount = 0;
this.misplaced = false;
this.retina = {
maxDistance: {}
};
const pxRatio = container.retina.pixelRatio;
const mainOptions = container.actualOptions;
const particlesOptions = new ParticlesOptions;
particlesOptions.load(mainOptions.particles);
const shapeType = particlesOptions.shape.type;
const reduceDuplicates = particlesOptions.reduceDuplicates;
this.shape = shapeType instanceof Array ? itemFromArray(shapeType, this.id, reduceDuplicates) : shapeType;
if (overrideOptions === null || overrideOptions === void 0 ? void 0 : overrideOptions.shape) {
if (overrideOptions.shape.type) {
const overrideShapeType = overrideOptions.shape.type;
this.shape = overrideShapeType instanceof Array ? itemFromArray(overrideShapeType, this.id, reduceDuplicates) : overrideShapeType;
}
const shapeOptions = new Shape;
shapeOptions.load(overrideOptions.shape);
if (this.shape) {
this.shapeData = this.loadShapeData(shapeOptions, reduceDuplicates);
}
} else {
this.shapeData = this.loadShapeData(particlesOptions.shape, reduceDuplicates);
}
if (overrideOptions !== undefined) {
particlesOptions.load(overrideOptions);
}
if (((_a = this.shapeData) === null || _a === void 0 ? void 0 : _a.particles) !== undefined) {
particlesOptions.load((_b = this.shapeData) === null || _b === void 0 ? void 0 : _b.particles);
}
this.fill = (_d = (_c = this.shapeData) === null || _c === void 0 ? void 0 : _c.fill) !== null && _d !== void 0 ? _d : this.fill;
this.close = (_f = (_e = this.shapeData) === null || _e === void 0 ? void 0 : _e.close) !== null && _f !== void 0 ? _f : this.close;
this.options = particlesOptions;
this.pathDelay = getValue(this.options.move.path.delay) * 1e3;
const zIndexValue = getRangeValue(this.options.zIndex.value);
container.retina.initParticle(this);
const sizeOptions = this.options.size, sizeRange = sizeOptions.value;
this.size = {
enable: sizeOptions.animation.enable,
value: getValue(sizeOptions) * container.retina.pixelRatio,
max: getRangeMax(sizeRange) * pxRatio,
min: getRangeMin(sizeRange) * pxRatio,
loops: 0,
maxLoops: sizeOptions.animation.count
};
const sizeAnimation = sizeOptions.animation;
if (sizeAnimation.enable) {
this.size.status = 0;
switch (sizeAnimation.startValue) {
case "min":
this.size.value = this.size.min;
this.size.status = 0;
break;
case "random":
this.size.value = randomInRange(this.size) * pxRatio;
this.size.status = Math.random() >= .5 ? 0 : 1;
break;
case "max":
default:
this.size.value = this.size.max;
this.size.status = 1;
break;
}
this.size.velocity = ((_g = this.retina.sizeAnimationSpeed) !== null && _g !== void 0 ? _g : container.retina.sizeAnimationSpeed) / 100 * container.retina.reduceFactor;
if (!sizeAnimation.sync) {
this.size.velocity *= Math.random();
}
}
this.direction = getParticleDirectionAngle(this.options.move.direction);
this.bubble = {
inRange: false
};
this.initialVelocity = this.calculateVelocity();
this.velocity = this.initialVelocity.copy();
this.moveDecay = 1 - getRangeValue(this.options.move.decay);
this.position = this.calcPosition(container, position, clamp(zIndexValue, 0, container.zLayers));
this.initialPosition = this.position.copy();
this.offset = Vector.origin;
const particles = container.particles;
particles.needsSort = particles.needsSort || particles.lastZIndex < this.position.z;
particles.lastZIndex = this.position.z;
this.zIndexFactor = this.position.z / container.zLayers;
this.sides = 24;
let drawer = container.drawers.get(this.shape);
if (!drawer) {
drawer = Plugins.getShapeDrawer(this.shape);
if (drawer) {
container.drawers.set(this.shape, drawer);
}
}
if (drawer === null || drawer === void 0 ? void 0 : drawer.loadShape) {
drawer === null || drawer === void 0 ? void 0 : drawer.loadShape(this);
}
const sideCountFunc = drawer === null || drawer === void 0 ? void 0 : drawer.getSidesCount;
if (sideCountFunc) {
this.sides = sideCountFunc(this);
}
this.life = this.loadLife();
this.spawning = this.life.delay > 0;
if (this.options.move.spin.enable) {
const spinPos = (_h = this.options.move.spin.position) !== null && _h !== void 0 ? _h : {
x: 50,
y: 50
};
const spinCenter = {
x: spinPos.x / 100 * container.canvas.size.width,
y: spinPos.y / 100 * container.canvas.size.height
};
const pos = this.getPosition();
const distance = getDistance(pos, spinCenter);
this.spin = {
center: spinCenter,
direction: this.velocity.x >= 0 ? "clockwise" : "counter-clockwise",
angle: this.velocity.angle,
radius: distance,
acceleration: (_j = this.retina.spinAcceleration) !== null && _j !== void 0 ? _j : getRangeValue(this.options.move.spin.acceleration)
};
}
this.shadowColor = colorToRgb(this.options.shadow.color);
for (const updater of container.particles.updaters) {
if (updater.init) {
updater.init(this);
}
}
if (drawer && drawer.particleInit) {
drawer.particleInit(container, this);
}
for (const [, plugin] of container.plugins) {
if (plugin.particleCreated) {
plugin.particleCreated(this);
}
}
}
isVisible() {
return !this.destroyed && !this.spawning && this.isInsideCanvas();
}
isInsideCanvas() {
const radius = this.getRadius();
const canvasSize = this.container.canvas.size;
return this.position.x >= -radius && this.position.y >= -radius && this.position.y <= canvasSize.height + radius && this.position.x <= canvasSize.width + radius;
}
draw(delta) {
const container = this.container;
for (const [, plugin] of container.plugins) {
container.canvas.drawParticlePlugin(plugin, this, delta);
}
container.canvas.drawParticle(this, delta);
}
getPosition() {
return {
x: this.position.x + this.offset.x,
y: this.position.y + this.offset.y,
z: this.position.z
};
}
getRadius() {
var _a;
return (_a = this.bubble.radius) !== null && _a !== void 0 ? _a : this.size.value;
}
getMass() {
return this.getRadius() ** 2 * Math.PI / 2;
}
getFillColor() {
var _a, _b, _c;
const color = (_a = this.bubble.color) !== null && _a !== void 0 ? _a : getHslFromAnimation(this.color);
if (color && this.roll && (this.backColor || this.roll.alter)) {
const rolled = Math.floor(((_c = (_b = this.roll) === null || _b === void 0 ? void 0 : _b.angle) !== null && _c !== void 0 ? _c : 0) / (Math.PI / 2)) % 2;
if (rolled) {
if (this.backColor) {
return this.backColor;
}
if (this.roll.alter) {
return alterHsl(color, this.roll.alter.type, this.roll.alter.value);
}
}
}
return color;
}
getStrokeColor() {
var _a, _b;
return (_b = (_a = this.bubble.color) !== null && _a !== void 0 ? _a : getHslFromAnimation(this.strokeColor)) !== null && _b !== void 0 ? _b : this.getFillColor();
}
destroy(override) {
this.destroyed = true;
this.bubble.inRange = false;
if (this.unbreakable) {
return;
}
this.destroyed = true;
this.bubble.inRange = false;
for (const [, plugin] of this.container.plugins) {
if (plugin.particleDestroyed) {
plugin.particleDestroyed(this, override);
}
}
if (override) {
return;
}
const destroyOptions = this.options.destroy;
if (destroyOptions.mode === "split") {
this.split();
}
}
reset() {
if (this.opacity) {
this.opacity.loops = 0;
}
this.size.loops = 0;
}
split() {
const splitOptions = this.options.destroy.split;
if (splitOptions.count >= 0 && this.splitCount++ > splitOptions.count) {
return;
}
const rate = getRangeValue(splitOptions.rate.value);
for (let i = 0; i < rate; i++) {
this.container.particles.addSplitParticle(this);
}
}
calcPosition(container, position, zIndex, tryCount = 0) {
var _a, _b, _c, _d, _e, _f;
for (const [, plugin] of container.plugins) {
const pluginPos = plugin.particlePosition !== undefined ? plugin.particlePosition(position, this) : undefined;
if (pluginPos !== undefined) {
return Vector3d.create(pluginPos.x, pluginPos.y, zIndex);
}
}
const canvasSize = container.canvas.size;
const pos = Vector3d.create((_a = position === null || position === void 0 ? void 0 : position.x) !== null && _a !== void 0 ? _a : Math.random() * canvasSize.width, (_b = position === null || position === void 0 ? void 0 : position.y) !== null && _b !== void 0 ? _b : Math.random() * canvasSize.height, zIndex);
const radius = this.getRadius();
const outModes = this.options.move.outModes, fixHorizontal = outMode => {
fixOutMode({
outMode: outMode,
checkModes: [ "bounce", "bounce-horizontal" ],
coord: pos.x,
maxCoord: container.canvas.size.width,
setCb: value => pos.x += value,
radius: radius
});
}, fixVertical = outMode => {
fixOutMode({
outMode: outMode,
checkModes: [ "bounce", "bounce-vertical" ],
coord: pos.y,
maxCoord: container.canvas.size.height,
setCb: value => pos.y += value,
radius: radius
});
};
fixHorizontal((_c = outModes.left) !== null && _c !== void 0 ? _c : outModes.default);
fixHorizontal((_d = outModes.right) !== null && _d !== void 0 ? _d : outModes.default);
fixVertical((_e = outModes.top) !== null && _e !== void 0 ? _e : outModes.default);
fixVertical((_f = outModes.bottom) !== null && _f !== void 0 ? _f : outModes.default);
if (this.checkOverlap(pos, tryCount)) {
return this.calcPosition(container, undefined, zIndex, tryCount + 1);
}
return pos;
}
checkOverlap(pos, tryCount = 0) {
const collisionsOptions = this.options.collisions;
const radius = this.getRadius();
if (!collisionsOptions.enable) {
return false;
}
const overlapOptions = collisionsOptions.overlap;
if (overlapOptions.enable) {
return false;
}
const retries = overlapOptions.retries;
if (retries >= 0 && tryCount > retries) {
throw new Error("Particle is overlapping and can't be placed");
}
let overlaps = false;
for (const particle of this.container.particles.array) {
if (getDistance(pos, particle.position) < radius + particle.getRadius()) {
overlaps = true;
break;
}
}
return overlaps;
}
calculateVelocity() {
const baseVelocity = getParticleBaseVelocity(this.direction);
const res = baseVelocity.copy();
const moveOptions = this.options.move;
const rad = Math.PI / 180 * moveOptions.angle.value;
const radOffset = Math.PI / 180 * moveOptions.angle.offset;
const range = {
left: radOffset - rad / 2,
right: radOffset + rad / 2
};
if (!moveOptions.straight) {
res.angle += randomInRange(setRangeValue(range.left, range.right));
}
if (moveOptions.random && typeof moveOptions.speed === "number") {
res.length *= Math.random();
}
return res;
}
loadShapeData(shapeOptions, reduceDuplicates) {
const shapeData = shapeOptions.options[this.shape];
if (shapeData) {
return deepExtend({}, shapeData instanceof Array ? itemFromArray(shapeData, this.id, reduceDuplicates) : shapeData);
}
}
loadLife() {
const container = this.container;
const particlesOptions = this.options;
const lifeOptions = particlesOptions.life;
const life = {
delay: container.retina.reduceFactor ? getRangeValue(lifeOptions.delay.value) * (lifeOptions.delay.sync ? 1 : Math.random()) / container.retina.reduceFactor * 1e3 : 0,
delayTime: 0,
duration: container.retina.reduceFactor ? getRangeValue(lifeOptions.duration.value) * (lifeOptions.duration.sync ? 1 : Math.random()) / container.retina.reduceFactor * 1e3 : 0,
time: 0,
count: particlesOptions.life.count
};
if (life.duration <= 0) {
life.duration = -1;
}
if (life.count <= 0) {
life.count = -1;
}
return life;
}
}
class Particles_Particles {
constructor(container) {
this.container = container;
this.nextId = 0;
this.array = [];
this.zArray = [];
this.mover = new ParticlesMover(container);
this.limit = 0;
this.needsSort = false;
this.lastZIndex = 0;
this.freqs = {
links: new Map,
triangles: new Map
};
this.interactionManager = new InteractionManager(container);
const canvasSize = this.container.canvas.size;
this.linksColors = new Map;
this.quadTree = new QuadTree(new Rectangle(-canvasSize.width / 4, -canvasSize.height / 4, canvasSize.width * 3 / 2, canvasSize.height * 3 / 2), 4);
this.updaters = Plugins.getUpdaters(container, true);
}
get count() {
return this.array.length;
}
init() {
var _a;
const container = this.container;
const options = container.actualOptions;
this.lastZIndex = 0;
this.needsSort = false;
this.freqs.links = new Map;
this.freqs.triangles = new Map;
let handled = false;
this.updaters = Plugins.getUpdaters(container, true);
this.interactionManager.init();
for (const [, plugin] of container.plugins) {
if (plugin.particlesInitialization !== undefined) {
handled = plugin.particlesInitialization();
}
if (handled) {
break;
}
}
this.addManualParticles();
if (!handled) {
for (const group in options.particles.groups) {
const groupOptions = options.particles.groups[group];
for (let i = this.count, j = 0; j < ((_a = groupOptions.number) === null || _a === void 0 ? void 0 : _a.value) && i < options.particles.number.value; i++,
j++) {
this.addParticle(undefined, groupOptions, group);
}
}
for (let i = this.count; i < options.particles.number.value; i++) {
this.addParticle();
}
}
container.pathGenerator.init(container);
}
redraw() {
this.clear();
this.init();
this.draw({
value: 0,
factor: 0
});
}
removeAt(index, quantity = 1, group, override) {
if (!(index >= 0 && index <= this.count)) {
return;
}
let deleted = 0;
for (let i = index; deleted < quantity && i < this.count; i++) {
const particle = this.array[i];
if (!particle || particle.group !== group) {
continue;
}
particle.destroy(override);
this.array.splice(i--, 1);
const zIdx = this.zArray.indexOf(particle);
this.zArray.splice(zIdx, 1);
deleted++;
}
}
remove(particle, group, override) {
this.removeAt(this.array.indexOf(particle), undefined, group, override);
}
update(delta) {
const container = this.container;
const particlesToDelete = [];
container.pathGenerator.update();
for (const [, plugin] of container.plugins) {
if (plugin.update !== undefined) {
plugin.update(delta);
}
}
for (const particle of this.array) {
const resizeFactor = container.canvas.resizeFactor;
if (resizeFactor) {
particle.position.x *= resizeFactor.width;
particle.position.y *= resizeFactor.height;
}
particle.bubble.inRange = false;
for (const [, plugin] of this.container.plugins) {
if (particle.destroyed) {
break;
}
if (plugin.particleUpdate) {
plugin.particleUpdate(particle, delta);
}
}
this.mover.move(particle, delta);
if (particle.destroyed) {
particlesToDelete.push(particle);
continue;
}
this.quadTree.insert(new Point(particle.getPosition(), particle));
}
for (const particle of particlesToDelete) {
this.remove(particle);
}
this.interactionManager.externalInteract(delta);
for (const particle of container.particles.array) {
for (const updater of this.updaters) {
updater.update(particle, delta);
}
if (!particle.destroyed && !particle.spawning) {
this.interactionManager.particlesInteract(particle, delta);
}
}
delete container.canvas.resizeFactor;
}
draw(delta) {
const container = this.container;
container.canvas.clear();
const canvasSize = this.container.canvas.size;
this.quadTree = new QuadTree(new Rectangle(-canvasSize.width / 4, -canvasSize.height / 4, canvasSize.width * 3 / 2, canvasSize.height * 3 / 2), 4);
this.update(delta);
if (this.needsSort) {
this.zArray.sort(((a, b) => b.position.z - a.position.z || a.id - b.id));
this.lastZIndex = this.zArray[this.zArray.length - 1].position.z;
this.needsSort = false;
}
for (const [, plugin] of container.plugins) {
container.canvas.drawPlugin(plugin, delta);
}
for (const p of this.zArray) {
p.draw(delta);
}
}
clear() {
this.array = [];
this.zArray = [];
}
push(nb, mouse, overrideOptions, group) {
this.pushing = true;
for (let i = 0; i < nb; i++) {
this.addParticle(mouse === null || mouse === void 0 ? void 0 : mouse.position, overrideOptions, group);
}
this.pushing = false;
}
addParticle(position, overrideOptions, group) {
const container = this.container, options = container.actualOptions, limit = options.particles.number.limit * container.density;
if (limit > 0) {
const countToRemove = this.count + 1 - limit;
if (countToRemove > 0) {
this.removeQuantity(countToRemove);
}
}
return this.pushParticle(position, overrideOptions, group);
}
addSplitParticle(parent) {
const splitOptions = parent.options.destroy.split, options = new ParticlesOptions;
options.load(parent.options);
const factor = getRangeValue(splitOptions.factor.value);
options.color.load({
value: {
hsl: parent.getFillColor()
}
});
if (typeof options.size.value === "number") {
options.size.value /= factor;
} else {
options.size.value.min /= factor;
options.size.value.max /= factor;
}
options.load(splitOptions.particles);
const offset = splitOptions.sizeOffset ? setRangeValue(-parent.size.value, parent.size.value) : 0;
const position = {
x: parent.position.x + randomInRange(offset),
y: parent.position.y + randomInRange(offset)
};
return this.pushParticle(position, options, parent.group, (particle => {
if (particle.size.value < .5) {
return false;
}
particle.velocity.length = randomInRange(setRangeValue(parent.velocity.length, particle.velocity.length));
particle.splitCount = parent.splitCount + 1;
particle.unbreakable = true;
setTimeout((() => {
particle.unbreakable = false;
}), 500);
return true;
}));
}
removeQuantity(quantity, group) {
this.removeAt(0, quantity, group);
}
getLinkFrequency(p1, p2) {
const range = setRangeValue(p1.id, p2.id), key = `${getRangeMin(range)}_${getRangeMax(range)}`;
let res = this.freqs.links.get(key);
if (res === undefined) {
res = Math.random();
this.freqs.links.set(key, res);
}
return res;
}
getTriangleFrequency(p1, p2, p3) {
let [id1, id2, id3] = [ p1.id, p2.id, p3.id ];
if (id1 > id2) {
[id2, id1] = [ id1, id2 ];
}
if (id2 > id3) {
[id3, id2] = [ id2, id3 ];
}
if (id1 > id3) {
[id3, id1] = [ id1, id3 ];
}
const key = `${id1}_${id2}_${id3}`;
let res = this.freqs.triangles.get(key);
if (res === undefined) {
res = Math.random();
this.freqs.triangles.set(key, res);
}
return res;
}
addManualParticles() {
const container = this.container, options = container.actualOptions;
for (const particle of options.manualParticles) {
const pos = particle.position ? {
x: particle.position.x * container.canvas.size.width / 100,
y: particle.position.y * container.canvas.size.height / 100
} : undefined;
this.addParticle(pos, particle.options);
}
}
setDensity() {
const options = this.container.actualOptions;
for (const group in options.particles.groups) {
this.applyDensity(options.particles.groups[group], 0, group);
}
this.applyDensity(options.particles, options.manualParticles.length);
}
applyDensity(options, manualCount, group) {
var _a;
if (!((_a = options.number.density) === null || _a === void 0 ? void 0 : _a.enable)) {
return;
}
const numberOptions = options.number;
const densityFactor = this.initDensityFactor(numberOptions.density);
const optParticlesNumber = numberOptions.value;
const optParticlesLimit = numberOptions.limit > 0 ? numberOptions.limit : optParticlesNumber;
const particlesNumber = Math.min(optParticlesNumber, optParticlesLimit) * densityFactor + manualCount;
const particlesCount = Math.min(this.count, this.array.filter((t => t.group === group)).length);
this.limit = numberOptions.limit * densityFactor;
if (particlesCount < particlesNumber) {
this.push(Math.abs(particlesNumber - particlesCount), undefined, options, group);
} else if (particlesCount > particlesNumber) {
this.removeQuantity(particlesCount - particlesNumber, group);
}
}
initDensityFactor(densityOptions) {
const container = this.container;
if (!container.canvas.element || !densityOptions.enable) {
return 1;
}
const canvas = container.canvas.element, pxRatio = container.retina.pixelRatio;
return canvas.width * canvas.height / (densityOptions.factor * pxRatio ** 2 * densityOptions.area);
}
pushParticle(position, overrideOptions, group, initializer) {
try {
const particle = new Particle(this.nextId, this.container, position, overrideOptions, group);
let canAdd = true;
if (initializer) {
canAdd = initializer(particle);
}
if (!canAdd) {
return;
}
this.array.push(particle);
this.zArray.push(particle);
this.nextId++;
return particle;
} catch (e) {
console.warn(`error adding particle: ${e}`);
return;
}
}
}
class Retina_Retina {
constructor(container) {
this.container = container;
}
init() {
const container = this.container;
const options = container.actualOptions;
this.pixelRatio = !options.detectRetina || isSsr() ? 1 : window.devicePixelRatio;
const motionOptions = this.container.actualOptions.motion;
if (motionOptions && (motionOptions.disable || motionOptions.reduce.value)) {
if (isSsr() || typeof matchMedia === "undefined" || !matchMedia) {
this.reduceFactor = 1;
} else {
const mediaQuery = matchMedia("(prefers-reduced-motion: reduce)");
if (mediaQuery) {
this.handleMotionChange(mediaQuery);
const handleChange = () => {
this.handleMotionChange(mediaQuery);
container.refresh().catch((() => {}));
};
if (mediaQuery.addEventListener !== undefined) {
mediaQuery.addEventListener("change", handleChange);
} else if (mediaQuery.addListener !== undefined) {
mediaQuery.addListener(handleChange);
}
}
}
} else {
this.reduceFactor = 1;
}
const ratio = this.pixelRatio;
if (container.canvas.element) {
const element = container.canvas.element;
container.canvas.size.width = element.offsetWidth * ratio;
container.canvas.size.height = element.offsetHeight * ratio;
}
const particles = options.particles;
this.attractDistance = particles.move.attract.distance * ratio;
this.linksDistance = particles.links.distance * ratio;
this.linksWidth = particles.links.width * ratio;
this.sizeAnimationSpeed = particles.size.animation.speed * ratio;
this.maxSpeed = particles.move.gravity.maxSpeed * ratio;
if (particles.orbit.radius !== undefined) {
this.orbitRadius = particles.orbit.radius * this.container.retina.pixelRatio;
}
const modes = options.interactivity.modes;
this.connectModeDistance = modes.connect.distance * ratio;
this.connectModeRadius = modes.connect.radius * ratio;
this.grabModeDistance = modes.grab.distance * ratio;
this.repulseModeDistance = modes.repulse.distance * ratio;
this.bounceModeDistance = modes.bounce.distance * ratio;
this.attractModeDistance = modes.attract.distance * ratio;
this.slowModeRadius = modes.slow.radius * ratio;
this.bubbleModeDistance = modes.bubble.distance * ratio;
if (modes.bubble.size) {
this.bubbleModeSize = modes.bubble.size * ratio;
}
}
initParticle(particle) {
const options = particle.options;
const ratio = this.pixelRatio;
const moveDistance = options.move.distance;
const props = particle.retina;
props.attractDistance = options.move.attract.distance * ratio;
props.linksDistance = options.links.distance * ratio;
props.linksWidth = options.links.width * ratio;
props.moveDrift = getRangeValue(options.move.drift) * ratio;
props.moveSpeed = getRangeValue(options.move.speed) * ratio;
props.sizeAnimationSpeed = options.size.animation.speed * ratio;
if (particle.spin) {
props.spinAcceleration = getRangeValue(options.move.spin.acceleration) * ratio;
}
const maxDistance = props.maxDistance;
maxDistance.horizontal = moveDistance.horizontal !== undefined ? moveDistance.horizontal * ratio : undefined;
maxDistance.vertical = moveDistance.vertical !== undefined ? moveDistance.vertical * ratio : undefined;
props.maxSpeed = options.move.gravity.maxSpeed * ratio;
}
handleMotionChange(mediaQuery) {
const options = this.container.actualOptions;
if (mediaQuery.matches) {
const motion = options.motion;
this.reduceFactor = motion.disable ? 0 : motion.reduce.value ? 1 / motion.reduce.factor : 1;
} else {
this.reduceFactor = 1;
}
}
}
class Container_Container {
constructor(id, sourceOptions, ...presets) {
this.id = id;
this.fpsLimit = 60;
this.duration = 0;
this.lifeTime = 0;
this.firstStart = true;
this.started = false;
this.destroyed = false;
this.paused = true;
this.lastFrameTime = 0;
this.zLayers = 100;
this.pageHidden = false;
this._sourceOptions = sourceOptions;
this._initialSourceOptions = sourceOptions;
this.retina = new Retina(this);
this.canvas = new Canvas(this);
this.particles = new Particles(this);
this.drawer = new FrameManager(this);
this.presets = presets;
this.pathGenerator = {
generate: () => {
const v = Vector.create(0, 0);
v.length = Math.random();
v.angle = Math.random() * Math.PI * 2;
return v;
},
init: () => {},
update: () => {}
};
this.interactivity = {
mouse: {
clicking: false,
inside: false
}
};
this.bubble = {};
this.repulse = {
particles: []
};
this.attract = {
particles: []
};
this.plugins = new Map;
this.drawers = new Map;
this.density = 1;
this._options = new Options;
this.actualOptions = new Options;
this.eventListeners = new EventListeners(this);
if (typeof IntersectionObserver !== "undefined" && IntersectionObserver) {
this.intersectionObserver = new IntersectionObserver((entries => this.intersectionManager(entries)));
}
}
get options() {
return this._options;
}
get sourceOptions() {
return this._sourceOptions;
}
play(force) {
const needsUpdate = this.paused || force;
if (this.firstStart && !this.actualOptions.autoPlay) {
this.firstStart = false;
return;
}
if (this.paused) {
this.paused = false;
}
if (needsUpdate) {
for (const [, plugin] of this.plugins) {
if (plugin.play) {
plugin.play();
}
}
}
this.draw(needsUpdate || false);
}
pause() {
if (this.drawAnimationFrame !== undefined) {
cancelAnimation()(this.drawAnimationFrame);
delete this.drawAnimationFrame;
}
if (this.paused) {
return;
}
for (const [, plugin] of this.plugins) {
if (plugin.pause) {
plugin.pause();
}
}
if (!this.pageHidden) {
this.paused = true;
}
}
draw(force) {
let refreshTime = force;
this.drawAnimationFrame = animate()((timestamp => {
if (refreshTime) {
this.lastFrameTime = undefined;
refreshTime = false;
}
this.drawer.nextFrame(timestamp);
}));
}
getAnimationStatus() {
return !this.paused && !this.pageHidden;
}
setNoise(noiseOrGenerator, init, update) {
this.setPath(noiseOrGenerator, init, update);
}
setPath(pathOrGenerator, init, update) {
if (!pathOrGenerator) {
return;
}
if (typeof pathOrGenerator === "function") {
this.pathGenerator.generate = pathOrGenerator;
if (init) {
this.pathGenerator.init = init;
}
if (update) {
this.pathGenerator.update = update;
}
} else {
if (pathOrGenerator.generate) {
this.pathGenerator.generate = pathOrGenerator.generate;
}
if (pathOrGenerator.init) {
this.pathGenerator.init = pathOrGenerator.init;
}
if (pathOrGenerator.update) {
this.pathGenerator.update = pathOrGenerator.update;
}
}
}
destroy() {
this.stop();
this.canvas.destroy();
for (const [, drawer] of this.drawers) {
if (drawer.destroy) {
drawer.destroy(this);
}
}
for (const key of this.drawers.keys()) {
this.drawers.delete(key);
}
this.destroyed = true;
}
exportImg(callback) {
this.exportImage(callback);
}
exportImage(callback, type, quality) {
var _a;
return (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.toBlob(callback, type !== null && type !== void 0 ? type : "image/png", quality);
}
exportConfiguration() {
return JSON.stringify(this.actualOptions, undefined, 2);
}
refresh() {
this.stop();
return this.start();
}
reset() {
this._options = new Options;
return this.refresh();
}
stop() {
if (!this.started) {
return;
}
this.firstStart = true;
this.started = false;
this.eventListeners.removeListeners();
this.pause();
this.particles.clear();
this.canvas.clear();
if (this.interactivity.element instanceof HTMLElement && this.intersectionObserver) {
this.intersectionObserver.observe(this.interactivity.element);
}
for (const [, plugin] of this.plugins) {
if (plugin.stop) {
plugin.stop();
}
}
for (const key of this.plugins.keys()) {
this.plugins.delete(key);
}
this.particles.linksColors = new Map;
delete this.particles.grabLineColor;
delete this.particles.linksColor;
this._sourceOptions = this._options;
}
async loadTheme(name) {
this.currentTheme = name;
await this.refresh();
}
async start() {
if (this.started) {
return;
}
await this.init();
this.started = true;
this.eventListeners.addListeners();
if (this.interactivity.element instanceof HTMLElement && this.intersectionObserver) {
this.intersectionObserver.observe(this.interactivity.element);
}
for (const [, plugin] of this.plugins) {
if (plugin.startAsync !== undefined) {
await plugin.startAsync();
} else if (plugin.start !== undefined) {
plugin.start();
}
}
this.play();
}
addClickHandler(callback) {
const el = this.interactivity.element;
if (!el) {
return;
}
const clickOrTouchHandler = (e, pos, radius) => {
if (this.destroyed) {
return;
}
const pxRatio = this.retina.pixelRatio, posRetina = {
x: pos.x * pxRatio,
y: pos.y * pxRatio
}, particles = this.particles.quadTree.queryCircle(posRetina, radius * pxRatio);
callback(e, particles);
};
const clickHandler = e => {
if (this.destroyed) {
return;
}
const mouseEvent = e;
const pos = {
x: mouseEvent.offsetX || mouseEvent.clientX,
y: mouseEvent.offsetY || mouseEvent.clientY
};
clickOrTouchHandler(e, pos, 1);
};
const touchStartHandler = () => {
if (this.destroyed) {
return;
}
touched = true;
touchMoved = false;
};
const touchMoveHandler = () => {
if (this.destroyed) {
return;
}
touchMoved = true;
};
const touchEndHandler = e => {
var _a, _b, _c;
if (this.destroyed) {
return;
}
if (touched && !touchMoved) {
const touchEvent = e;
let lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
if (!lastTouch) {
lastTouch = touchEvent.changedTouches[touchEvent.changedTouches.length - 1];
if (!lastTouch) {
return;
}
}
const canvasRect = (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
const pos = {
x: lastTouch.clientX - ((_b = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _b !== void 0 ? _b : 0),
y: lastTouch.clientY - ((_c = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _c !== void 0 ? _c : 0)
};
clickOrTouchHandler(e, pos, Math.max(lastTouch.radiusX, lastTouch.radiusY));
}
touched = false;
touchMoved = false;
};
const touchCancelHandler = () => {
if (this.destroyed) {
return;
}
touched = false;
touchMoved = false;
};
let touched = false;
let touchMoved = false;
el.addEventListener("click", clickHandler);
el.addEventListener("touchstart", touchStartHandler);
el.addEventListener("touchmove", touchMoveHandler);
el.addEventListener("touchend", touchEndHandler);
el.addEventListener("touchcancel", touchCancelHandler);
}
updateActualOptions() {
this.actualOptions.responsive = [];
const newMaxWidth = this.actualOptions.setResponsive(this.canvas.size.width, this.retina.pixelRatio, this._options);
this.actualOptions.setTheme(this.currentTheme);
if (this.responsiveMaxWidth != newMaxWidth) {
this.responsiveMaxWidth = newMaxWidth;
return true;
}
return false;
}
async init() {
this._options = new Options;
for (const preset of this.presets) {
this._options.load(Plugins.getPreset(preset));
}
const shapes = Plugins.getSupportedShapes();
for (const type of shapes) {
const drawer = Plugins.getShapeDrawer(type);
if (drawer) {
this.drawers.set(type, drawer);
}
}
this._options.load(this._initialSourceOptions);
this._options.load(this._sourceOptions);
this.actualOptions = new Options;
this.actualOptions.load(this._options);
this.retina.init();
this.canvas.init();
this.updateActualOptions();
this.canvas.initBackground();
this.canvas.resize();
this.zLayers = this.actualOptions.zLayers;
this.duration = getRangeValue(this.actualOptions.duration);
this.lifeTime = 0;
this.fpsLimit = this.actualOptions.fpsLimit > 0 ? this.actualOptions.fpsLimit : 60;
const availablePlugins = Plugins.getAvailablePlugins(this);
for (const [id, plugin] of availablePlugins) {
this.plugins.set(id, plugin);
}
for (const [, drawer] of this.drawers) {
if (drawer.init) {
await drawer.init(this);
}
}
for (const [, plugin] of this.plugins) {
if (plugin.init) {
plugin.init(this.actualOptions);
} else if (plugin.initAsync !== undefined) {
await plugin.initAsync(this.actualOptions);
}
}
const pathOptions = this.actualOptions.particles.move.path;
if (pathOptions.generator) {
const customGenerator = Plugins.getPathGenerator(pathOptions.generator);
if (customGenerator) {
if (customGenerator.init) {
this.pathGenerator.init = customGenerator.init;
}
if (customGenerator.generate) {
this.pathGenerator.generate = customGenerator.generate;
}
if (customGenerator.update) {
this.pathGenerator.update = customGenerator.update;
}
}
}
this.particles.init();
this.particles.setDensity();
for (const [, plugin] of this.plugins) {
if (plugin.particlesSetup !== undefined) {
plugin.particlesSetup();
}
}
}
intersectionManager(entries) {
if (!this.actualOptions.pauseOnOutsideViewport) {
return;
}
for (const entry of entries) {
if (entry.target !== this.interactivity.element) {
continue;
}
if (entry.isIntersecting) {
this.play();
} else {
this.pause();
}
}
}
}
const tsParticlesDom = null && [];
function fetchError(statusCode) {
console.error(`Error tsParticles - fetch status: ${statusCode}`);
console.error("Error tsParticles - File config not found");
}
class Loader {
static dom() {
return tsParticlesDom;
}
static domItem(index) {
const dom = Loader.dom();
const item = dom[index];
if (item && !item.destroyed) {
return item;
}
dom.splice(index, 1);
}
static async loadOptions(params) {
var _a, _b, _c;
const tagId = (_a = params.tagId) !== null && _a !== void 0 ? _a : `tsparticles${Math.floor(Math.random() * 1e4)}`;
const {options: options, index: index} = params;
let domContainer = (_b = params.element) !== null && _b !== void 0 ? _b : document.getElementById(tagId);
if (!domContainer) {
domContainer = document.createElement("div");
domContainer.id = tagId;
(_c = document.querySelector("body")) === null || _c === void 0 ? void 0 : _c.append(domContainer);
}
const currentOptions = options instanceof Array ? itemFromArray(options, index) : options;
const dom = Loader.dom();
const oldIndex = dom.findIndex((v => v.id === tagId));
if (oldIndex >= 0) {
const old = Loader.domItem(oldIndex);
if (old && !old.destroyed) {
old.destroy();
dom.splice(oldIndex, 1);
}
}
let canvasEl;
if (domContainer.tagName.toLowerCase() === "canvas") {
canvasEl = domContainer;
canvasEl.dataset[Constants.generatedAttribute] = "false";
} else {
const existingCanvases = domContainer.getElementsByTagName("canvas");
if (existingCanvases.length) {
canvasEl = existingCanvases[0];
canvasEl.dataset[Constants.generatedAttribute] = "false";
} else {
canvasEl = document.createElement("canvas");
canvasEl.dataset[Constants.generatedAttribute] = "true";
canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
domContainer.appendChild(canvasEl);
}
}
const newItem = new Container(tagId, currentOptions);
if (oldIndex >= 0) {
dom.splice(oldIndex, 0, newItem);
} else {
dom.push(newItem);
}
newItem.canvas.loadCanvas(canvasEl);
await newItem.start();
return newItem;
}
static async loadRemoteOptions(params) {
const {url: jsonUrl, index: index} = params;
const url = jsonUrl instanceof Array ? itemFromArray(jsonUrl, index) : jsonUrl;
if (!url) {
return;
}
const response = await fetch(url);
if (!response.ok) {
fetchError(response.status);
return;
}
const data = await response.json();
return await Loader.loadOptions({
tagId: params.tagId,
element: params.element,
index: index,
options: data
});
}
static load(tagId, options, index) {
const params = {
index: index
};
if (typeof tagId === "string") {
params.tagId = tagId;
} else {
params.options = tagId;
}
if (typeof options === "number") {
params.index = options !== null && options !== void 0 ? options : params.index;
} else {
params.options = options !== null && options !== void 0 ? options : params.options;
}
return this.loadOptions(params);
}
static async set(id, domContainer, options, index) {
const params = {
index: index
};
if (typeof id === "string") {
params.tagId = id;
} else {
params.element = id;
}
if (domContainer instanceof HTMLElement) {
params.element = domContainer;
} else {
params.options = domContainer;
}
if (typeof options === "number") {
params.index = options;
} else {
params.options = options !== null && options !== void 0 ? options : params.options;
}
return this.loadOptions(params);
}
static async loadJSON(tagId, jsonUrl, index) {
let url, id;
if (typeof jsonUrl === "number" || jsonUrl === undefined) {
url = tagId;
} else {
id = tagId;
url = jsonUrl;
}
return await Loader.loadRemoteOptions({
tagId: id,
url: url,
index: index
});
}
static async setJSON(id, domContainer, jsonUrl, index) {
let url, newId, newIndex, element;
if (id instanceof HTMLElement) {
element = id;
url = domContainer;
newIndex = jsonUrl;
} else {
newId = id;
element = domContainer;
url = jsonUrl;
newIndex = index;
}
return await Loader.loadRemoteOptions({
tagId: newId,
url: url,
index: newIndex,
element: element
});
}
static setOnClickHandler(callback) {
const dom = Loader.dom();
if (dom.length === 0) {
throw new Error("Can only set click handlers after calling tsParticles.load() or tsParticles.loadJSON()");
}
for (const domItem of dom) {
domItem.addClickHandler(callback);
}
}
}
function NumberUtils_clamp(num, min, max) {
return Math.min(Math.max(num, min), max);
}
function NumberUtils_mix(comp1, comp2, weight1, weight2) {
return Math.floor((comp1 * weight1 + comp2 * weight2) / (weight1 + weight2));
}
function NumberUtils_randomInRange(r) {
const max = NumberUtils_getRangeMax(r);
let min = NumberUtils_getRangeMin(r);
if (max === min) {
min = 0;
}
return Math.random() * (max - min) + min;
}
function NumberUtils_getRangeValue(value) {
return typeof value === "number" ? value : NumberUtils_randomInRange(value);
}
function NumberUtils_getRangeMin(value) {
return typeof value === "number" ? value : value.min;
}
function NumberUtils_getRangeMax(value) {
return typeof value === "number" ? value : value.max;
}
function NumberUtils_setRangeValue(source, value) {
if (source === value || value === undefined && typeof source === "number") {
return source;
}
const min = NumberUtils_getRangeMin(source), max = NumberUtils_getRangeMax(source);
return value !== undefined ? {
min: Math.min(min, value),
max: Math.max(max, value)
} : NumberUtils_setRangeValue(min, max);
}
function NumberUtils_getValue(options) {
const random = options.random;
const {enable: enable, minimumValue: minimumValue} = typeof random === "boolean" ? {
enable: random,
minimumValue: 0
} : random;
return enable ? NumberUtils_getRangeValue(NumberUtils_setRangeValue(options.value, minimumValue)) : NumberUtils_getRangeValue(options.value);
}
function NumberUtils_getDistances(pointA, pointB) {
const dx = pointA.x - pointB.x;
const dy = pointA.y - pointB.y;
return {
dx: dx,
dy: dy,
distance: Math.sqrt(dx * dx + dy * dy)
};
}
function NumberUtils_getDistance(pointA, pointB) {
return NumberUtils_getDistances(pointA, pointB).distance;
}
function NumberUtils_getParticleDirectionAngle(direction) {
if (typeof direction === "number") {
return direction * Math.PI / 180;
} else {
switch (direction) {
case "top":
return -Math.PI / 2;
case "top-right":
return -Math.PI / 4;
case "right":
return 0;
case "bottom-right":
return Math.PI / 4;
case "bottom":
return Math.PI / 2;
case "bottom-left":
return 3 * Math.PI / 4;
case "left":
return Math.PI;
case "top-left":
return -3 * Math.PI / 4;
case "none":
default:
return Math.random() * Math.PI * 2;
}
}
}
function NumberUtils_getParticleBaseVelocity(direction) {
const baseVelocity = Vector.origin;
baseVelocity.length = 1;
baseVelocity.angle = direction;
return baseVelocity;
}
function NumberUtils_collisionVelocity(v1, v2, m1, m2) {
return Vector.create(v1.x * (m1 - m2) / (m1 + m2) + v2.x * 2 * m2 / (m1 + m2), v1.y);
}
function calcEasing(value, type) {
switch (type) {
case "ease-out-quad":
return 1 - (1 - value) ** 2;
case "ease-out-cubic":
return 1 - (1 - value) ** 3;
case "ease-out-quart":
return 1 - (1 - value) ** 4;
case "ease-out-quint":
return 1 - (1 - value) ** 5;
case "ease-out-expo":
return value === 1 ? 1 : 1 - Math.pow(2, -10 * value);
case "ease-out-sine":
return Math.sin(value * Math.PI / 2);
case "ease-out-back":
{
const c1 = 1.70158;
const c3 = c1 + 1;
return 1 + c3 * Math.pow(value - 1, 3) + c1 * Math.pow(value - 1, 2);
}
case "ease-out-circ":
return Math.sqrt(1 - Math.pow(value - 1, 2));
default:
return value;
}
}
function rectSideBounce(pSide, pOtherSide, rectSide, rectOtherSide, velocity, factor) {
const res = {
bounced: false
};
if (pOtherSide.min >= rectOtherSide.min && pOtherSide.min <= rectOtherSide.max && pOtherSide.max >= rectOtherSide.min && pOtherSide.max <= rectOtherSide.max) {
if (pSide.max >= rectSide.min && pSide.max <= (rectSide.max + rectSide.min) / 2 && velocity > 0 || pSide.min <= rectSide.max && pSide.min > (rectSide.max + rectSide.min) / 2 && velocity < 0) {
res.velocity = velocity * -factor;
res.bounced = true;
}
}
return res;
}
function checkSelector(element, selectors) {
if (selectors instanceof Array) {
for (const selector of selectors) {
if (element.matches(selector)) {
return true;
}
}
return false;
} else {
return element.matches(selectors);
}
}
function Utils_isSsr() {
return typeof window === "undefined" || !window || typeof window.document === "undefined" || !window.document;
}
function Utils_animate() {
return Utils_isSsr() ? callback => setTimeout(callback) : callback => (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || window.setTimeout)(callback);
}
function Utils_cancelAnimation() {
return Utils_isSsr() ? handle => clearTimeout(handle) : handle => (window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.clearTimeout)(handle);
}
function Utils_isInArray(value, array) {
return value === array || array instanceof Array && array.indexOf(value) > -1;
}
async function loadFont(character) {
var _a, _b;
try {
await document.fonts.load(`${(_a = character.weight) !== null && _a !== void 0 ? _a : "400"} 36px '${(_b = character.font) !== null && _b !== void 0 ? _b : "Verdana"}'`);
} catch (_c) {}
}
function arrayRandomIndex(array) {
return Math.floor(Math.random() * array.length);
}
function Utils_itemFromArray(array, index, useIndex = true) {
const fixedIndex = index !== undefined && useIndex ? index % array.length : arrayRandomIndex(array);
return array[fixedIndex];
}
function isPointInside(point, size, radius, direction) {
return areBoundsInside(calculateBounds(point, radius !== null && radius !== void 0 ? radius : 0), size, direction);
}
function areBoundsInside(bounds, size, direction) {
let inside = true;
if (!direction || direction === "bottom") {
inside = bounds.top < size.height;
}
if (inside && (!direction || direction === "left")) {
inside = bounds.right > 0;
}
if (inside && (!direction || direction === "right")) {
inside = bounds.left < size.width;
}
if (inside && (!direction || direction === "top")) {
inside = bounds.bottom > 0;
}
return inside;
}
function calculateBounds(point, radius) {
return {
bottom: point.y + radius,
left: point.x - radius,
right: point.x + radius,
top: point.y - radius
};
}
function Utils_deepExtend(destination, ...sources) {
for (const source of sources) {
if (source === undefined || source === null) {
continue;
}
if (typeof source !== "object") {
destination = source;
continue;
}
const sourceIsArray = Array.isArray(source);
if (sourceIsArray && (typeof destination !== "object" || !destination || !Array.isArray(destination))) {
destination = [];
} else if (!sourceIsArray && (typeof destination !== "object" || !destination || Array.isArray(destination))) {
destination = {};
}
for (const key in source) {
if (key === "__proto__") {
continue;
}
const sourceDict = source;
const value = sourceDict[key];
const isObject = typeof value === "object";
const destDict = destination;
destDict[key] = isObject && Array.isArray(value) ? value.map((v => Utils_deepExtend(destDict[key], v))) : Utils_deepExtend(destDict[key], value);
}
}
return destination;
}
function isDivModeEnabled(mode, divs) {
return divs instanceof Array ? !!divs.find((t => t.enable && Utils_isInArray(mode, t.mode))) : Utils_isInArray(mode, divs.mode);
}
function divModeExecute(mode, divs, callback) {
if (divs instanceof Array) {
for (const div of divs) {
const divMode = div.mode;
const divEnabled = div.enable;
if (divEnabled && Utils_isInArray(mode, divMode)) {
singleDivModeExecute(div, callback);
}
}
} else {
const divMode = divs.mode;
const divEnabled = divs.enable;
if (divEnabled && Utils_isInArray(mode, divMode)) {
singleDivModeExecute(divs, callback);
}
}
}
function singleDivModeExecute(div, callback) {
const selectors = div.selectors;
if (selectors instanceof Array) {
for (const selector of selectors) {
callback(selector, div);
}
} else {
callback(selectors, div);
}
}
function divMode(divs, element) {
if (!element || !divs) {
return;
}
if (divs instanceof Array) {
return divs.find((d => checkSelector(element, d.selectors)));
} else if (checkSelector(element, divs.selectors)) {
return divs;
}
}
function circleBounceDataFromParticle(p) {
return {
position: p.getPosition(),
radius: p.getRadius(),
mass: p.getMass(),
velocity: p.velocity,
factor: Vector.create(getValue(p.options.bounce.horizontal), getValue(p.options.bounce.vertical))
};
}
function circleBounce(p1, p2) {
const {x: xVelocityDiff, y: yVelocityDiff} = p1.velocity.sub(p2.velocity);
const [pos1, pos2] = [ p1.position, p2.position ];
const {dx: xDist, dy: yDist} = getDistances(pos2, pos1);
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
const angle = -Math.atan2(yDist, xDist);
const m1 = p1.mass;
const m2 = p2.mass;
const u1 = p1.velocity.rotate(angle);
const u2 = p2.velocity.rotate(angle);
const v1 = collisionVelocity(u1, u2, m1, m2);
const v2 = collisionVelocity(u2, u1, m1, m2);
const vFinal1 = v1.rotate(-angle);
const vFinal2 = v2.rotate(-angle);
p1.velocity.x = vFinal1.x * p1.factor.x;
p1.velocity.y = vFinal1.y * p1.factor.y;
p2.velocity.x = vFinal2.x * p2.factor.x;
p2.velocity.y = vFinal2.y * p2.factor.y;
}
}
function rectBounce(particle, divBounds) {
const pPos = particle.getPosition();
const size = particle.getRadius();
const bounds = calculateBounds(pPos, size);
const resH = rectSideBounce({
min: bounds.left,
max: bounds.right
}, {
min: bounds.top,
max: bounds.bottom
}, {
min: divBounds.left,
max: divBounds.right
}, {
min: divBounds.top,
max: divBounds.bottom
}, particle.velocity.x, getValue(particle.options.bounce.horizontal));
if (resH.bounced) {
if (resH.velocity !== undefined) {
particle.velocity.x = resH.velocity;
}
if (resH.position !== undefined) {
particle.position.x = resH.position;
}
}
const resV = rectSideBounce({
min: bounds.top,
max: bounds.bottom
}, {
min: bounds.left,
max: bounds.right
}, {
min: divBounds.top,
max: divBounds.bottom
}, {
min: divBounds.left,
max: divBounds.right
}, particle.velocity.y, getValue(particle.options.bounce.vertical));
if (resV.bounced) {
if (resV.velocity !== undefined) {
particle.velocity.y = resV.velocity;
}
if (resV.position !== undefined) {
particle.position.y = resV.position;
}
}
}
function hue2rgb(p, q, t) {
let tCalc = t;
if (tCalc < 0) {
tCalc += 1;
}
if (tCalc > 1) {
tCalc -= 1;
}
if (tCalc < 1 / 6) {
return p + (q - p) * 6 * tCalc;
}
if (tCalc < 1 / 2) {
return q;
}
if (tCalc < 2 / 3) {
return p + (q - p) * (2 / 3 - tCalc) * 6;
}
return p;
}
function stringToRgba(input) {
if (input.startsWith("rgb")) {
const regex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([\d.]+)\s*)?\)/i;
const result = regex.exec(input);
return result ? {
a: result.length > 4 ? parseFloat(result[5]) : 1,
b: parseInt(result[3], 10),
g: parseInt(result[2], 10),
r: parseInt(result[1], 10)
} : undefined;
} else if (input.startsWith("hsl")) {
const regex = /hsla?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([\d.]+)\s*)?\)/i;
const result = regex.exec(input);
return result ? hslaToRgba({
a: result.length > 4 ? parseFloat(result[5]) : 1,
h: parseInt(result[1], 10),
l: parseInt(result[3], 10),
s: parseInt(result[2], 10)
}) : undefined;
} else if (input.startsWith("hsv")) {
const regex = /hsva?\(\s*(\d+)°\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([\d.]+)\s*)?\)/i;
const result = regex.exec(input);
return result ? hsvaToRgba({
a: result.length > 4 ? parseFloat(result[5]) : 1,
h: parseInt(result[1], 10),
s: parseInt(result[2], 10),
v: parseInt(result[3], 10)
}) : undefined;
} else {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i;
const hexFixed = input.replace(shorthandRegex, ((_m, r, g, b, a) => r + r + g + g + b + b + (a !== undefined ? a + a : "")));
const regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i;
const result = regex.exec(hexFixed);
return result ? {
a: result[4] !== undefined ? parseInt(result[4], 16) / 255 : 1,
b: parseInt(result[3], 16),
g: parseInt(result[2], 16),
r: parseInt(result[1], 16)
} : undefined;
}
}
function ColorUtils_colorToRgb(input, index, useIndex = true) {
var _a, _b, _c;
if (input === undefined) {
return;
}
const color = typeof input === "string" ? {
value: input
} : input;
let res;
if (typeof color.value === "string") {
if (color.value === Constants.randomColorValue) {
res = getRandomRgbColor();
} else {
res = stringToRgb(color.value);
}
} else {
if (color.value instanceof Array) {
const colorSelected = itemFromArray(color.value, index, useIndex);
res = ColorUtils_colorToRgb({
value: colorSelected
});
} else {
const colorValue = color.value;
const rgbColor = (_a = colorValue.rgb) !== null && _a !== void 0 ? _a : color.value;
if (rgbColor.r !== undefined) {
res = rgbColor;
} else {
const hslColor = (_b = colorValue.hsl) !== null && _b !== void 0 ? _b : color.value;
if (hslColor.h !== undefined && hslColor.l !== undefined) {
res = hslToRgb(hslColor);
} else {
const hsvColor = (_c = colorValue.hsv) !== null && _c !== void 0 ? _c : color.value;
if (hsvColor.h !== undefined && hsvColor.v !== undefined) {
res = hsvToRgb(hsvColor);
}
}
}
}
}
return res;
}
function ColorUtils_colorToHsl(color, index, useIndex = true) {
const rgb = ColorUtils_colorToRgb(color, index, useIndex);
return rgb !== undefined ? rgbToHsl(rgb) : undefined;
}
function rgbToHsl(color) {
const r1 = color.r / 255;
const g1 = color.g / 255;
const b1 = color.b / 255;
const max = Math.max(r1, g1, b1);
const min = Math.min(r1, g1, b1);
const res = {
h: 0,
l: (max + min) / 2,
s: 0
};
if (max != min) {
res.s = res.l < .5 ? (max - min) / (max + min) : (max - min) / (2 - max - min);
res.h = r1 === max ? (g1 - b1) / (max - min) : res.h = g1 === max ? 2 + (b1 - r1) / (max - min) : 4 + (r1 - g1) / (max - min);
}
res.l *= 100;
res.s *= 100;
res.h *= 60;
if (res.h < 0) {
res.h += 360;
}
return res;
}
function stringToAlpha(input) {
var _a;
return (_a = stringToRgba(input)) === null || _a === void 0 ? void 0 : _a.a;
}
function stringToRgb(input) {
return stringToRgba(input);
}
function hslToRgb(hsl) {
const result = {
b: 0,
g: 0,
r: 0
};
const hslPercent = {
h: hsl.h / 360,
l: hsl.l / 100,
s: hsl.s / 100
};
if (hslPercent.s === 0) {
result.b = hslPercent.l;
result.g = hslPercent.l;
result.r = hslPercent.l;
} else {
const q = hslPercent.l < .5 ? hslPercent.l * (1 + hslPercent.s) : hslPercent.l + hslPercent.s - hslPercent.l * hslPercent.s;
const p = 2 * hslPercent.l - q;
result.r = hue2rgb(p, q, hslPercent.h + 1 / 3);
result.g = hue2rgb(p, q, hslPercent.h);
result.b = hue2rgb(p, q, hslPercent.h - 1 / 3);
}
result.r = Math.floor(result.r * 255);
result.g = Math.floor(result.g * 255);
result.b = Math.floor(result.b * 255);
return result;
}
function hslaToRgba(hsla) {
const rgbResult = hslToRgb(hsla);
return {
a: hsla.a,
b: rgbResult.b,
g: rgbResult.g,
r: rgbResult.r
};
}
function hslToHsv(hsl) {
const l = hsl.l / 100, sl = hsl.s / 100;
const v = l + sl * Math.min(l, 1 - l), sv = !v ? 0 : 2 * (1 - l / v);
return {
h: hsl.h,
s: sv * 100,
v: v * 100
};
}
function hslaToHsva(hsla) {
const hsvResult = hslToHsv(hsla);
return {
a: hsla.a,
h: hsvResult.h,
s: hsvResult.s,
v: hsvResult.v
};
}
function hsvToHsl(hsv) {
const v = hsv.v / 100, sv = hsv.s / 100;
const l = v * (1 - sv / 2), sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l);
return {
h: hsv.h,
l: l * 100,
s: sl * 100
};
}
function hsvaToHsla(hsva) {
const hslResult = hsvToHsl(hsva);
return {
a: hsva.a,
h: hslResult.h,
l: hslResult.l,
s: hslResult.s
};
}
function hsvToRgb(hsv) {
const result = {
b: 0,
g: 0,
r: 0
};
const hsvPercent = {
h: hsv.h / 60,
s: hsv.s / 100,
v: hsv.v / 100
};
const c = hsvPercent.v * hsvPercent.s, x = c * (1 - Math.abs(hsvPercent.h % 2 - 1));
let tempRgb;
if (hsvPercent.h >= 0 && hsvPercent.h <= 1) {
tempRgb = {
r: c,
g: x,
b: 0
};
} else if (hsvPercent.h > 1 && hsvPercent.h <= 2) {
tempRgb = {
r: x,
g: c,
b: 0
};
} else if (hsvPercent.h > 2 && hsvPercent.h <= 3) {
tempRgb = {
r: 0,
g: c,
b: x
};
} else if (hsvPercent.h > 3 && hsvPercent.h <= 4) {
tempRgb = {
r: 0,
g: x,
b: c
};
} else if (hsvPercent.h > 4 && hsvPercent.h <= 5) {
tempRgb = {
r: x,
g: 0,
b: c
};
} else if (hsvPercent.h > 5 && hsvPercent.h <= 6) {
tempRgb = {
r: c,
g: 0,
b: x
};
}
if (tempRgb) {
const m = hsvPercent.v - c;
result.r = Math.floor((tempRgb.r + m) * 255);
result.g = Math.floor((tempRgb.g + m) * 255);
result.b = Math.floor((tempRgb.b + m) * 255);
}
return result;
}
function hsvaToRgba(hsva) {
const rgbResult = hsvToRgb(hsva);
return {
a: hsva.a,
b: rgbResult.b,
g: rgbResult.g,
r: rgbResult.r
};
}
function rgbToHsv(rgb) {
const rgbPercent = {
r: rgb.r / 255,
g: rgb.g / 255,
b: rgb.b / 255
}, xMax = Math.max(rgbPercent.r, rgbPercent.g, rgbPercent.b), xMin = Math.min(rgbPercent.r, rgbPercent.g, rgbPercent.b), v = xMax, c = xMax - xMin;
let h = 0;
if (v === rgbPercent.r) {
h = 60 * ((rgbPercent.g - rgbPercent.b) / c);
} else if (v === rgbPercent.g) {
h = 60 * (2 + (rgbPercent.b - rgbPercent.r) / c);
} else if (v === rgbPercent.b) {
h = 60 * (4 + (rgbPercent.r - rgbPercent.g) / c);
}
const s = !v ? 0 : c / v;
return {
h: h,
s: s * 100,
v: v * 100
};
}
function rgbaToHsva(rgba) {
const hsvResult = rgbToHsv(rgba);
return {
a: rgba.a,
h: hsvResult.h,
s: hsvResult.s,
v: hsvResult.v
};
}
function getRandomRgbColor(min) {
const fixedMin = min !== null && min !== void 0 ? min : 0;
return {
b: Math.floor(randomInRange(setRangeValue(fixedMin, 256))),
g: Math.floor(randomInRange(setRangeValue(fixedMin, 256))),
r: Math.floor(randomInRange(setRangeValue(fixedMin, 256)))
};
}
function ColorUtils_getStyleFromRgb(color, opacity) {
return `rgba(${color.r}, ${color.g}, ${color.b}, ${opacity !== null && opacity !== void 0 ? opacity : 1})`;
}
function ColorUtils_getStyleFromHsl(color, opacity) {
return `hsla(${color.h}, ${color.s}%, ${color.l}%, ${opacity !== null && opacity !== void 0 ? opacity : 1})`;
}
function getStyleFromHsv(color, opacity) {
return ColorUtils_getStyleFromHsl(hsvToHsl(color), opacity);
}
function ColorUtils_colorMix(color1, color2, size1, size2) {
let rgb1 = color1;
let rgb2 = color2;
if (rgb1.r === undefined) {
rgb1 = hslToRgb(color1);
}
if (rgb2.r === undefined) {
rgb2 = hslToRgb(color2);
}
return {
b: mix(rgb1.b, rgb2.b, size1, size2),
g: mix(rgb1.g, rgb2.g, size1, size2),
r: mix(rgb1.r, rgb2.r, size1, size2)
};
}
function getLinkColor(p1, p2, linkColor) {
var _a, _b;
if (linkColor === Constants.randomColorValue) {
return getRandomRgbColor();
} else if (linkColor === "mid") {
const sourceColor = (_a = p1.getFillColor()) !== null && _a !== void 0 ? _a : p1.getStrokeColor();
const destColor = (_b = p2 === null || p2 === void 0 ? void 0 : p2.getFillColor()) !== null && _b !== void 0 ? _b : p2 === null || p2 === void 0 ? void 0 : p2.getStrokeColor();
if (sourceColor && destColor && p2) {
return ColorUtils_colorMix(sourceColor, destColor, p1.getRadius(), p2.getRadius());
} else {
const hslColor = sourceColor !== null && sourceColor !== void 0 ? sourceColor : destColor;
if (hslColor) {
return hslToRgb(hslColor);
}
}
} else {
return linkColor;
}
}
function getLinkRandomColor(optColor, blink, consent) {
const color = typeof optColor === "string" ? optColor : optColor.value;
if (color === Constants.randomColorValue) {
if (consent) {
return ColorUtils_colorToRgb({
value: color
});
} else if (blink) {
return Constants.randomColorValue;
} else {
return Constants.midColorValue;
}
} else {
return ColorUtils_colorToRgb({
value: color
});
}
}
function ColorUtils_getHslFromAnimation(animation) {
return animation !== undefined ? {
h: animation.h.value,
s: animation.s.value,
l: animation.l.value
} : undefined;
}
function getHslAnimationFromHsl(hsl, animationOptions, reduceFactor) {
const resColor = {
h: {
enable: false,
value: hsl.h
},
s: {
enable: false,
value: hsl.s
},
l: {
enable: false,
value: hsl.l
}
};
if (animationOptions) {
setColorAnimation(resColor.h, animationOptions.h, reduceFactor);
setColorAnimation(resColor.s, animationOptions.s, reduceFactor);
setColorAnimation(resColor.l, animationOptions.l, reduceFactor);
}
return resColor;
}
function setColorAnimation(colorValue, colorAnimation, reduceFactor) {
colorValue.enable = colorAnimation.enable;
if (colorValue.enable) {
colorValue.velocity = colorAnimation.speed / 100 * reduceFactor;
if (colorAnimation.sync) {
return;
}
colorValue.status = 0;
colorValue.velocity *= Math.random();
if (colorValue.value) {
colorValue.value *= Math.random();
}
} else {
colorValue.velocity = 0;
}
}
function drawLine(context, begin, end) {
context.beginPath();
context.moveTo(begin.x, begin.y);
context.lineTo(end.x, end.y);
context.closePath();
}
function drawTriangle(context, p1, p2, p3) {
context.beginPath();
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.lineTo(p3.x, p3.y);
context.closePath();
}
function CanvasUtils_paintBase(context, dimension, baseColor) {
context.save();
context.fillStyle = baseColor !== null && baseColor !== void 0 ? baseColor : "rgba(0,0,0,0)";
context.fillRect(0, 0, dimension.width, dimension.height);
context.restore();
}
function CanvasUtils_clear(context, dimension) {
context.clearRect(0, 0, dimension.width, dimension.height);
}
function drawLinkLine(context, width, begin, end, maxDistance, canvasSize, warp, backgroundMask, composite, colorLine, opacity, shadow) {
let drawn = false;
if (getDistance(begin, end) <= maxDistance) {
drawLine(context, begin, end);
drawn = true;
} else if (warp) {
let pi1;
let pi2;
const endNE = {
x: end.x - canvasSize.width,
y: end.y
};
const d1 = getDistances(begin, endNE);
if (d1.distance <= maxDistance) {
const yi = begin.y - d1.dy / d1.dx * begin.x;
pi1 = {
x: 0,
y: yi
};
pi2 = {
x: canvasSize.width,
y: yi
};
} else {
const endSW = {
x: end.x,
y: end.y - canvasSize.height
};
const d2 = getDistances(begin, endSW);
if (d2.distance <= maxDistance) {
const yi = begin.y - d2.dy / d2.dx * begin.x;
const xi = -yi / (d2.dy / d2.dx);
pi1 = {
x: xi,
y: 0
};
pi2 = {
x: xi,
y: canvasSize.height
};
} else {
const endSE = {
x: end.x - canvasSize.width,
y: end.y - canvasSize.height
};
const d3 = getDistances(begin, endSE);
if (d3.distance <= maxDistance) {
const yi = begin.y - d3.dy / d3.dx * begin.x;
const xi = -yi / (d3.dy / d3.dx);
pi1 = {
x: xi,
y: yi
};
pi2 = {
x: pi1.x + canvasSize.width,
y: pi1.y + canvasSize.height
};
}
}
}
if (pi1 && pi2) {
drawLine(context, begin, pi1);
drawLine(context, end, pi2);
drawn = true;
}
}
if (!drawn) {
return;
}
context.lineWidth = width;
if (backgroundMask) {
context.globalCompositeOperation = composite;
}
context.strokeStyle = getStyleFromRgb(colorLine, opacity);
if (shadow.enable) {
const shadowColor = colorToRgb(shadow.color);
if (shadowColor) {
context.shadowBlur = shadow.blur;
context.shadowColor = getStyleFromRgb(shadowColor);
}
}
context.stroke();
}
function drawLinkTriangle(context, pos1, pos2, pos3, backgroundMask, composite, colorTriangle, opacityTriangle) {
drawTriangle(context, pos1, pos2, pos3);
if (backgroundMask) {
context.globalCompositeOperation = composite;
}
context.fillStyle = getStyleFromRgb(colorTriangle, opacityTriangle);
context.fill();
}
function CanvasUtils_drawConnectLine(context, width, lineStyle, begin, end) {
context.save();
drawLine(context, begin, end);
context.lineWidth = width;
context.strokeStyle = lineStyle;
context.stroke();
context.restore();
}
function CanvasUtils_gradient(context, p1, p2, opacity) {
const gradStop = Math.floor(p2.getRadius() / p1.getRadius());
const color1 = p1.getFillColor();
const color2 = p2.getFillColor();
if (!color1 || !color2) {
return;
}
const sourcePos = p1.getPosition();
const destPos = p2.getPosition();
const midRgb = colorMix(color1, color2, p1.getRadius(), p2.getRadius());
const grad = context.createLinearGradient(sourcePos.x, sourcePos.y, destPos.x, destPos.y);
grad.addColorStop(0, getStyleFromHsl(color1, opacity));
grad.addColorStop(gradStop > 1 ? 1 : gradStop, getStyleFromRgb(midRgb, opacity));
grad.addColorStop(1, getStyleFromHsl(color2, opacity));
return grad;
}
function CanvasUtils_drawGrabLine(context, width, begin, end, colorLine, opacity) {
context.save();
drawLine(context, begin, end);
context.strokeStyle = getStyleFromRgb(colorLine, opacity);
context.lineWidth = width;
context.stroke();
context.restore();
}
function CanvasUtils_drawParticle(container, context, particle, delta, fillColorValue, strokeColorValue, backgroundMask, composite, radius, opacity, shadow, gradient) {
var _a, _b, _c, _d, _e, _f;
const pos = particle.getPosition();
const tiltOptions = particle.options.tilt;
const rollOptions = particle.options.roll;
context.save();
if (tiltOptions.enable || rollOptions.enable) {
const roll = rollOptions.enable && particle.roll;
const tilt = tiltOptions.enable && particle.tilt;
const rollHorizontal = roll && (rollOptions.mode === "horizontal" || rollOptions.mode === "both");
const rollVertical = roll && (rollOptions.mode === "vertical" || rollOptions.mode === "both");
context.setTransform(rollHorizontal ? Math.cos(particle.roll.angle) : 1, tilt ? Math.cos(particle.tilt.value) * particle.tilt.cosDirection : 0, tilt ? Math.sin(particle.tilt.value) * particle.tilt.sinDirection : 0, rollVertical ? Math.sin(particle.roll.angle) : 1, pos.x, pos.y);
} else {
context.translate(pos.x, pos.y);
}
context.beginPath();
const angle = ((_b = (_a = particle.rotate) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 0) + (particle.options.rotate.path ? particle.velocity.angle : 0);
if (angle !== 0) {
context.rotate(angle);
}
if (backgroundMask) {
context.globalCompositeOperation = composite;
}
const shadowColor = particle.shadowColor;
if (shadow.enable && shadowColor) {
context.shadowBlur = shadow.blur;
context.shadowColor = getStyleFromRgb(shadowColor);
context.shadowOffsetX = shadow.offset.x;
context.shadowOffsetY = shadow.offset.y;
}
if (gradient) {
const gradientAngle = gradient.angle.value;
const fillGradient = gradient.type === "radial" ? context.createRadialGradient(0, 0, 0, 0, 0, radius) : context.createLinearGradient(Math.cos(gradientAngle) * -radius, Math.sin(gradientAngle) * -radius, Math.cos(gradientAngle) * radius, Math.sin(gradientAngle) * radius);
for (const color of gradient.colors) {
fillGradient.addColorStop(color.stop, getStyleFromHsl({
h: color.value.h.value,
s: color.value.s.value,
l: color.value.l.value
}, (_d = (_c = color.opacity) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : opacity));
}
context.fillStyle = fillGradient;
} else {
if (fillColorValue) {
context.fillStyle = fillColorValue;
}
}
const stroke = particle.stroke;
context.lineWidth = (_e = particle.strokeWidth) !== null && _e !== void 0 ? _e : 0;
if (strokeColorValue) {
context.strokeStyle = strokeColorValue;
}
drawShape(container, context, particle, radius, opacity, delta);
if (((_f = stroke === null || stroke === void 0 ? void 0 : stroke.width) !== null && _f !== void 0 ? _f : 0) > 0) {
context.stroke();
}
if (particle.close) {
context.closePath();
}
if (particle.fill) {
context.fill();
}
context.restore();
context.save();
if (tiltOptions.enable && particle.tilt) {
context.setTransform(1, Math.cos(particle.tilt.value) * particle.tilt.cosDirection, Math.sin(particle.tilt.value) * particle.tilt.sinDirection, 1, pos.x, pos.y);
} else {
context.translate(pos.x, pos.y);
}
if (angle !== 0) {
context.rotate(angle);
}
if (backgroundMask) {
context.globalCompositeOperation = composite;
}
drawShapeAfterEffect(container, context, particle, radius, opacity, delta);
context.restore();
}
function drawShape(container, context, particle, radius, opacity, delta) {
if (!particle.shape) {
return;
}
const drawer = container.drawers.get(particle.shape);
if (!drawer) {
return;
}
drawer.draw(context, particle, radius, opacity, delta, container.retina.pixelRatio);
}
function drawShapeAfterEffect(container, context, particle, radius, opacity, delta) {
if (!particle.shape) {
return;
}
const drawer = container.drawers.get(particle.shape);
if (!(drawer === null || drawer === void 0 ? void 0 : drawer.afterEffect)) {
return;
}
drawer.afterEffect(context, particle, radius, opacity, delta, container.retina.pixelRatio);
}
function CanvasUtils_drawPlugin(context, plugin, delta) {
if (!plugin.draw) {
return;
}
context.save();
plugin.draw(context, delta);
context.restore();
}
function CanvasUtils_drawParticlePlugin(context, plugin, particle, delta) {
if (plugin.drawParticle !== undefined) {
context.save();
plugin.drawParticle(context, particle, delta);
context.restore();
}
}
function drawEllipse(context, particle, fillColorValue, radius, opacity, width, rotation, start, end) {
const pos = particle.getPosition();
if (fillColorValue) {
context.strokeStyle = getStyleFromHsl(fillColorValue, opacity);
}
if (width === 0) {
return;
}
context.lineWidth = width;
const rotationRadian = rotation * Math.PI / 180;
context.beginPath();
context.ellipse(pos.x, pos.y, radius / 2, radius * 2, rotationRadian, start, end);
context.stroke();
}
function CanvasUtils_alterHsl(color, type, value) {
return {
h: color.h,
s: color.s,
l: color.l + (type === "darken" ? -1 : 1) * value
};
}
class LifeUpdater {
constructor(container) {
this.container = container;
}
init() {}
isEnabled(particle) {
return !particle.destroyed;
}
update(particle, delta) {
if (!this.isEnabled(particle)) {
return;
}
const life = particle.life;
let justSpawned = false;
if (particle.spawning) {
life.delayTime += delta.value;
if (life.delayTime >= particle.life.delay) {
justSpawned = true;
particle.spawning = false;
life.delayTime = 0;
life.time = 0;
} else {
return;
}
}
if (life.duration === -1) {
return;
}
if (particle.spawning) {
return;
}
if (justSpawned) {
life.time = 0;
} else {
life.time += delta.value;
}
if (life.time < life.duration) {
return;
}
life.time = 0;
if (particle.life.count > 0) {
particle.life.count--;
}
if (particle.life.count === 0) {
particle.destroy();
return;
}
const canvasSize = this.container.canvas.size, widthRange = NumberUtils_setRangeValue(0, canvasSize.width), heightRange = NumberUtils_setRangeValue(0, canvasSize.width);
particle.position.x = NumberUtils_randomInRange(widthRange);
particle.position.y = NumberUtils_randomInRange(heightRange);
particle.spawning = true;
life.delayTime = 0;
life.time = 0;
particle.reset();
const lifeOptions = particle.options.life;
life.delay = NumberUtils_getRangeValue(lifeOptions.delay.value) * 1e3;
life.duration = NumberUtils_getRangeValue(lifeOptions.duration.value) * 1e3;
}
}
async function loadLifeUpdater(engine) {
await engine.addParticleUpdater("life", (container => new LifeUpdater(container)));
}
return __webpack_exports__;
}();
})); | mit |
dts-ait/sproute-json-route-format | src/main/java/at/ac/ait/ariadne/routeformat/location/Address.java | 4923 | package at.ac.ait.ariadne.routeformat.location;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.base.Joiner;
import at.ac.ait.ariadne.routeformat.Validatable;
/**
*
* @author AIT Austrian Institute of Technology GmbH
*/
@JsonInclude(Include.NON_ABSENT)
public class Address implements Validatable {
private Optional<String> country = Optional.empty();
private Optional<String> city = Optional.empty();
private Optional<String> postCode = Optional.empty();
private Optional<String> streetName = Optional.empty();
private Optional<String> houseNumber = Optional.empty();
private Map<String, Object> additionalInfo = new TreeMap<>();
// -- getters
public Optional<String> getCountry() {
return country;
}
public Optional<String> getCity() {
return city;
}
public Optional<String> getPostCode() {
return postCode;
}
public Optional<String> getStreetName() {
return streetName;
}
public Optional<String> getHouseNumber() {
return houseNumber;
}
public Map<String, Object> getAdditionalInfo() {
return additionalInfo;
}
// -- setters
public Address setCountry(String country) {
this.country = Optional.ofNullable(country);
return this;
}
public Address setCity(String city) {
this.city = Optional.ofNullable(city);
return this;
}
public Address setPostCode(String postCode) {
this.postCode = Optional.ofNullable(postCode);
return this;
}
public Address setStreetName(String streetName) {
this.streetName = Optional.ofNullable(streetName);
return this;
}
public Address setHouseNumber(String houseNumber) {
this.houseNumber = Optional.ofNullable(houseNumber);
return this;
}
public Address setAdditionalInfo(Map<String, Object> additionalInfo) {
this.additionalInfo = new TreeMap<>(additionalInfo);
return this;
}
// --
public static Address create(String streetName, String houseNumber) {
return new Address().setStreetName(streetName).setHouseNumber(houseNumber);
}
@Override
public void validate() {
// no minimum requirements, all fields can be empty
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((houseNumber == null) ? 0 : houseNumber.hashCode());
result = prime * result + ((postCode == null) ? 0 : postCode.hashCode());
result = prime * result + ((streetName == null) ? 0 : streetName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (additionalInfo == null) {
if (other.additionalInfo != null)
return false;
} else if (!additionalInfo.equals(other.additionalInfo))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (houseNumber == null) {
if (other.houseNumber != null)
return false;
} else if (!houseNumber.equals(other.houseNumber))
return false;
if (postCode == null) {
if (other.postCode != null)
return false;
} else if (!postCode.equals(other.postCode))
return false;
if (streetName == null) {
if (other.streetName != null)
return false;
} else if (!streetName.equals(other.streetName))
return false;
return true;
}
@Override
public String toString() {
List<String> fields = new ArrayList<>();
country.ifPresent(f -> fields.add(f));
city.ifPresent(f -> fields.add(f));
postCode.ifPresent(f -> fields.add(f));
streetName.ifPresent(f -> fields.add(f));
houseNumber.ifPresent(f -> fields.add(f));
return Joiner.on("|").join(fields);
}
}
| cc0-1.0 |
marcmo/nonius | test/manual_clock.h++ | 1290 | // Nonius - C++ benchmarking tool
//
// Written in 2014 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
// Clock that advances manually
#ifndef NONIUS_TEST_MANUAL_CLOCK_HPP
#define NONIUS_TEST_MANUAL_CLOCK_HPP
#include <nonius/clock.h++>
namespace nonius {
struct manual_clock {
public:
using duration = chrono::nanoseconds;
using time_point = chrono::time_point<manual_clock, duration>;
using rep = duration::rep;
using period = duration::period;
enum { is_steady = true };
static time_point now() {
return time_point(duration(tick()));
}
static void advance(int ticks = 1) {
tick() += ticks;
}
private:
static rep& tick() {
static rep the_tick = 0;
return the_tick;
}
};
} // namespace nonius
#endif // NONIUS_TEST_MANUAL_CLOCK_HPP
| cc0-1.0 |
usedgov/usedgov.github.io | assets/js/jquery.cbpQTRotator.js | 3935 | /**
* jquery.cbpQTRotator.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
'use strict';
// global
var Modernizr = window.Modernizr;
$.CBPQTRotator = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.CBPQTRotator.defaults = {
// default transition speed (ms)
speed : 700,
// default transition easing
easing : 'ease',
// rotator interval (ms)
interval : 8000
};
$.CBPQTRotator.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.CBPQTRotator.defaults, options );
// cache some elements and initialize some variables
this._config();
// show current item
this.$items.eq( this.current ).addClass( 'cbp-qtcurrent' );
// set the transition to the items
if( this.support ) {
this._setTransition();
}
// start rotating the items
this._startRotator();
},
_config : function() {
// the content items
this.$items = this.$el.children( 'div.cbp-qtcontent' );
// total items
this.itemsCount = this.$items.length;
// current item's index
this.current = 0;
// support for CSS Transitions
this.support = Modernizr.csstransitions;
// add the progress bar
if( this.support ) {
this.$progress = $( '<span class="cbp-qtprogress"></span>' ).appendTo( this.$el );
}
},
_setTransition : function() {
setTimeout( $.proxy( function() {
this.$items.css( 'transition', 'opacity ' + this.options.speed + 'ms ' + this.options.easing );
}, this ), 25 );
},
_startRotator: function() {
if( this.support ) {
this._startProgress();
}
setTimeout( $.proxy( function() {
if( this.support ) {
this._resetProgress();
}
this._next();
this._startRotator();
}, this ), this.options.interval );
},
_next : function() {
// hide previous item
this.$items.eq( this.current ).removeClass( 'cbp-qtcurrent' );
// update current value
this.current = this.current < this.itemsCount - 1 ? this.current + 1 : 0;
// show next item
this.$items.eq( this.current ).addClass('cbp-qtcurrent');
},
_startProgress : function() {
setTimeout( $.proxy( function() {
this.$progress.css( { transition : 'width ' + this.options.interval + 'ms linear', width : '100%' } );
}, this ), 25 );
},
_resetProgress : function() {
this.$progress.css( { transition : 'none', width : '0%' } );
},
destroy : function() {
if( this.support ) {
this.$items.css( 'transition', 'none' );
this.$progress.remove();
}
this.$items.removeClass( 'cbp-qtcurrent' ).css( {
'position' : 'relative',
'z-index' : 100,
'pointer-events' : 'auto',
'opacity' : 1
} );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.cbpQTRotator = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'cbpQTRotator' );
if ( !instance ) {
logError( "cannot call methods on cbpQTRotator prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for cbpQTRotator instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'cbpQTRotator' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'cbpQTRotator', new $.CBPQTRotator( options, this ) );
}
});
}
return this;
};
} )( jQuery, window );
| cc0-1.0 |
evan617/Cpp-Primer | ch14/ex14.6.7/Sales_data.cc | 2745 | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#include <iostream>
using std::istream; using std::ostream;
#include "Sales_data.h"
Sales_data::Sales_data(std::istream &is)
{
// read will read a transaction from is into this object
read(is, *this);
}
double
Sales_data::avg_price() const {
if (units_sold)
return revenue/units_sold;
else
return 0;
}
// add the value of the given Sales_data into this object
Sales_data&
Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold; // add the members of rhs into
revenue += rhs.revenue; // the members of ``this'' object
return *this; // return the object on which the function was called
}
Sales_data
add(const Sales_data &lhs, const Sales_data &rhs)
{
Sales_data sum = lhs; // copy data members from lhs into sum
sum.combine(rhs); // add data members from rhs into sum
return sum;
}
// transactions contain ISBN, number of copies sold, and sales price
istream&
read(istream &is, Sales_data &item)
{
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
ostream&
print(ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price();
return os;
}
//! added 10.Jan 2014
std::ostream &
operator <<(std::ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price();
return os;
}
| cc0-1.0 |
DanielParra159/EngineAndGame | Engine/extern/BOOST/include/boost/iostreams/detail/streambuf/direct_streambuf.hpp | 10544 | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_DETAIL_DIRECT_STREAMBUF_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_DIRECT_STREAMBUF_HPP_INCLUDED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <cassert>
#include <cstddef>
#include <typeinfo>
#include <utility> // pair.
#include <boost/config.hpp> // BOOST_DEDUCED_TYPENAME,
#include <boost/iostreams/detail/char_traits.hpp> // member template friends.
#include <boost/iostreams/detail/config/wide_streams.hpp>
#include <boost/iostreams/detail/error.hpp>
#include <boost/iostreams/detail/execute.hpp>
#include <boost/iostreams/detail/functional.hpp>
#include <boost/iostreams/detail/ios.hpp>
#include <boost/iostreams/detail/optional.hpp>
#include <boost/iostreams/detail/streambuf.hpp>
#include <boost/iostreams/detail/streambuf/linked_streambuf.hpp>
#include <boost/iostreams/operations.hpp>
#include <boost/iostreams/positioning.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/throw_exception.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC.
namespace boost { namespace iostreams {
namespace detail {
template< typename T,
typename Tr =
BOOST_IOSTREAMS_CHAR_TRAITS(
BOOST_DEDUCED_TYPENAME char_type_of<T>::type
) >
class direct_streambuf
: public linked_streambuf<BOOST_DEDUCED_TYPENAME char_type_of<T>::type, Tr>
{
public:
typedef typename char_type_of<T>::type char_type;
BOOST_IOSTREAMS_STREAMBUF_TYPEDEFS(Tr)
private:
typedef linked_streambuf<char_type, traits_type> base_type;
typedef typename category_of<T>::type category;
typedef BOOST_IOSTREAMS_BASIC_STREAMBUF(
char_type, traits_type
) streambuf_type;
public: // stream needs access.
void open(const T& t, std::streamsize buffer_size,
std::streamsize pback_size);
bool is_open() const;
void close();
bool auto_close() const { return auto_close_; }
void set_auto_close(bool close) { auto_close_ = close; }
bool strict_sync() { return true; }
// Declared in linked_streambuf.
T* component() { return storage_.get(); }
protected:
#if !BOOST_WORKAROUND(__GNUC__, == 2)
BOOST_IOSTREAMS_USING_PROTECTED_STREAMBUF_MEMBERS(base_type)
#endif
direct_streambuf();
//--------------Virtual functions-----------------------------------------//
// Declared in linked_streambuf.
void close_impl(BOOST_IOS::openmode m);
const std::type_info& component_type() const { return typeid(T); }
void* component_impl() { return component(); }
#ifdef BOOST_IOSTREAMS_NO_STREAM_TEMPLATES
public:
#endif
// Declared in basic_streambuf.
int_type underflow();
int_type pbackfail(int_type c);
int_type overflow(int_type c);
pos_type seekoff( off_type off, BOOST_IOS::seekdir way,
BOOST_IOS::openmode which );
pos_type seekpos(pos_type sp, BOOST_IOS::openmode which);
private:
pos_type seek_impl( stream_offset off, BOOST_IOS::seekdir way,
BOOST_IOS::openmode which );
void init_input(any_tag) { }
void init_input(input);
void init_output(any_tag) { }
void init_output(output);
void init_get_area();
void init_put_area();
bool one_head() const;
bool two_head() const;
optional<T> storage_;
char_type *ibeg_, *iend_, *obeg_, *oend_;
bool auto_close_;
};
//------------------Implementation of direct_streambuf------------------------//
template<typename T, typename Tr>
direct_streambuf<T, Tr>::direct_streambuf()
: ibeg_(0), iend_(0), obeg_(0), oend_(0), auto_close_(true)
{ this->set_true_eof(true); }
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::open
(const T& t, std::streamsize, std::streamsize)
{
storage_.reset(t);
init_input(category());
init_output(category());
setg(0, 0, 0);
setp(0, 0);
this->set_needs_close();
}
template<typename T, typename Tr>
bool direct_streambuf<T, Tr>::is_open() const
{ return ibeg_ != 0 || obeg_ != 0; }
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::close()
{
base_type* self = this;
detail::execute_all( detail::call_member_close(*self, BOOST_IOS::in),
detail::call_member_close(*self, BOOST_IOS::out),
detail::call_reset(storage_) );
}
template<typename T, typename Tr>
typename direct_streambuf<T, Tr>::int_type
direct_streambuf<T, Tr>::underflow()
{
if (!ibeg_)
boost::throw_exception(cant_read());
if (!gptr())
init_get_area();
return gptr() != iend_ ?
traits_type::to_int_type(*gptr()) :
traits_type::eof();
}
template<typename T, typename Tr>
typename direct_streambuf<T, Tr>::int_type
direct_streambuf<T, Tr>::pbackfail(int_type c)
{
using namespace std;
if (!ibeg_)
boost::throw_exception(cant_read());
if (gptr() != 0 && gptr() != ibeg_) {
gbump(-1);
if (!traits_type::eq_int_type(c, traits_type::eof()))
*gptr() = traits_type::to_char_type(c);
return traits_type::not_eof(c);
}
boost::throw_exception(bad_putback());
}
template<typename T, typename Tr>
typename direct_streambuf<T, Tr>::int_type
direct_streambuf<T, Tr>::overflow(int_type c)
{
using namespace std;
if (!obeg_)
boost::throw_exception(BOOST_IOSTREAMS_FAILURE("no write access"));
if (!pptr()) init_put_area();
if (!traits_type::eq_int_type(c, traits_type::eof())) {
if (pptr() == oend_)
boost::throw_exception(
BOOST_IOSTREAMS_FAILURE("write area exhausted")
);
*pptr() = traits_type::to_char_type(c);
pbump(1);
return c;
}
return traits_type::not_eof(c);
}
template<typename T, typename Tr>
inline typename direct_streambuf<T, Tr>::pos_type
direct_streambuf<T, Tr>::seekoff
(off_type off, BOOST_IOS::seekdir way, BOOST_IOS::openmode which)
{ return seek_impl(off, way, which); }
template<typename T, typename Tr>
inline typename direct_streambuf<T, Tr>::pos_type
direct_streambuf<T, Tr>::seekpos
(pos_type sp, BOOST_IOS::openmode which)
{
return seek_impl(position_to_offset(sp), BOOST_IOS::beg, which);
}
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::close_impl(BOOST_IOS::openmode which)
{
if (which == BOOST_IOS::in && ibeg_ != 0) {
setg(0, 0, 0);
ibeg_ = iend_ = 0;
}
if (which == BOOST_IOS::out && obeg_ != 0) {
sync();
setp(0, 0);
obeg_ = oend_ = 0;
}
boost::iostreams::close(*storage_, which);
}
template<typename T, typename Tr>
typename direct_streambuf<T, Tr>::pos_type direct_streambuf<T, Tr>::seek_impl
(stream_offset off, BOOST_IOS::seekdir way, BOOST_IOS::openmode which)
{
using namespace std;
BOOST_IOS::openmode both = BOOST_IOS::in | BOOST_IOS::out;
if (two_head() && (which & both) == both)
boost::throw_exception(bad_seek());
stream_offset result = -1;
bool one = one_head();
if (one && (pptr() != 0 || gptr()== 0))
init_get_area(); // Switch to input mode, for code reuse.
if (one || ((which & BOOST_IOS::in) != 0 && ibeg_ != 0)) {
if (!gptr()) setg(ibeg_, ibeg_, iend_);
ptrdiff_t next = 0;
switch (way) {
case BOOST_IOS::beg: next = off; break;
case BOOST_IOS::cur: next = (gptr() - ibeg_) + off; break;
case BOOST_IOS::end: next = (iend_ - ibeg_) + off; break;
default: assert(0);
}
if (next < 0 || next > (iend_ - ibeg_))
boost::throw_exception(bad_seek());
setg(ibeg_, ibeg_ + next, iend_);
result = next;
}
if (!one && (which & BOOST_IOS::out) != 0 && obeg_ != 0) {
if (!pptr()) setp(obeg_, oend_);
ptrdiff_t next = 0;
switch (way) {
case BOOST_IOS::beg: next = off; break;
case BOOST_IOS::cur: next = (pptr() - obeg_) + off; break;
case BOOST_IOS::end: next = (oend_ - obeg_) + off; break;
default: assert(0);
}
if (next < 0 || next > (oend_ - obeg_))
boost::throw_exception(bad_seek());
pbump(static_cast<int>(next - (pptr() - obeg_)));
result = next;
}
return offset_to_position(result);
}
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::init_input(input)
{
std::pair<char_type*, char_type*> p = input_sequence(*storage_);
ibeg_ = p.first;
iend_ = p.second;
}
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::init_output(output)
{
std::pair<char_type*, char_type*> p = output_sequence(*storage_);
obeg_ = p.first;
oend_ = p.second;
}
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::init_get_area()
{
setg(ibeg_, ibeg_, iend_);
if (one_head() && pptr()) {
gbump(static_cast<int>(pptr() - obeg_));
setp(0, 0);
}
}
template<typename T, typename Tr>
void direct_streambuf<T, Tr>::init_put_area()
{
setp(obeg_, oend_);
if (one_head() && gptr()) {
pbump(static_cast<int>(gptr() - ibeg_));
setg(0, 0, 0);
}
}
template<typename T, typename Tr>
inline bool direct_streambuf<T, Tr>::one_head() const
{ return ibeg_ && obeg_ && ibeg_ == obeg_; }
template<typename T, typename Tr>
inline bool direct_streambuf<T, Tr>::two_head() const
{ return ibeg_ && obeg_ && ibeg_ != obeg_; }
//----------------------------------------------------------------------------//
} // End namespace detail.
} } // End namespaces iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC
#endif // #ifndef BOOST_IOSTREAMS_DETAIL_DIRECT_STREAMBUF_HPP_INCLUDED
| cc0-1.0 |
yariplus/minecraft-nodebb-integration | bukkit-legacy/src/main/java/com/radiofreederp/nodebbintegration/bukkit/listeners/ListenerPlayerJoin.java | 1451 | package com.radiofreederp.nodebbintegration.bukkit.listeners;
import com.radiofreederp.nodebbintegration.MinecraftServerEvents;
import com.radiofreederp.nodebbintegration.NodeBBIntegrationBukkit;
import com.radiofreederp.nodebbintegration.NodeBBIntegrationPlugin;
import com.radiofreederp.nodebbintegration.bukkit.hooks.OnTimeHook;
import com.radiofreederp.nodebbintegration.bukkit.hooks.VanishNoPacketHook;
import com.radiofreederp.nodebbintegration.bukkit.hooks.VaultHook;
import com.radiofreederp.nodebbintegration.socketio.SocketIOClient;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Yari on 5/18/2016.
*/
public class ListenerPlayerJoin implements Listener {
private NodeBBIntegrationBukkit plugin;
public ListenerPlayerJoin(NodeBBIntegrationPlugin plugin) {
this.plugin = (NodeBBIntegrationBukkit)plugin;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
// Ignore vanished players.
if (VanishNoPacketHook.isEnabled()) {
if (VanishNoPacketHook.isVanished(event.getPlayer().getName())) return;
}
MinecraftServerEvents.onPlayerJoin(plugin, event.getPlayer(), plugin.getMinecraftServer().getPlayerJSON(event.getPlayer()));
}
}
| cc0-1.0 |
ibm-messaging/mq-mqsc-editor-plugin | com.ibm.mq.explorer.ms0s.mqsceditor/src/com/ibm/mq/explorer/ms0s/mqsceditor/gui/MQSCDamagerRepairer.java | 1297 | /*******************************************************************************
* Copyright (c) 2007,2014 IBM Corporation and other Contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Jeff Lowrey - Initial Contribution
*******************************************************************************/
package com.ibm.mq.explorer.ms0s.mqsceditor.gui;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.ITokenScanner;
/**
* @author Jeff Lowrey
*/
/**
* <p>
* This extends the DefaultDamagerRepairer to register a scanner and return the correct partition.
* This repairer does nothing unique.
**/
public class MQSCDamagerRepairer extends DefaultDamagerRepairer {
public MQSCDamagerRepairer(ITokenScanner scanner) {
super(scanner);
}
public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e,
boolean documentPartitioningChanged) {
return partition;
}
}
| epl-1.0 |
SINTEF-9012/SPLCATool | org.sat4j.core/src/test/java/org/sat4j/minisat/VarOrderTest.java | 3036 | /*******************************************************************************
* SAT4J: a SATisfiability library for Java Copyright (C) 2004-2008 Daniel Le Berre
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU Lesser General Public License Version 2.1 or later (the
* "LGPL"), in which case the provisions of the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of the LGPL, and not to allow others to use your version of
* this file under the terms of the EPL, indicate your decision by deleting
* the provisions above and replace them with the notice and other provisions
* required by the LGPL. If you do not delete the provisions above, a recipient
* may use your version of this file under the terms of the EPL or the LGPL.
*
* Based on the original MiniSat specification from:
*
* An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the
* Sixth International Conference on Theory and Applications of Satisfiability
* Testing, LNCS 2919, pp 502-518, 2003.
*
* See www.minisat.se for the original solver in C++.
*
*******************************************************************************/
package org.sat4j.minisat;
import junit.framework.TestCase;
import org.sat4j.minisat.constraints.ClausalDataStructureWL;
import org.sat4j.minisat.core.ILits;
import org.sat4j.minisat.core.IOrder;
import org.sat4j.minisat.orders.VarOrderHeap;
/**
* @author leberre
*
* To change the template for this generated type comment go to Window -
* Preferences - Java - Code Generation - Code and Comments
*/
public class VarOrderTest extends TestCase {
/*
* Class to test for void newVar()
*/
public void testNewVar() {
int p = voc.getFromPool(-1);
order.init();
assertEquals(p, order.select());
voc.satisfies(2); // satisfying literal 1
assertEquals(ILits.UNDEFINED, order.select());
}
/*
* Class to test for void newVar(int)
*/
public void testNewVarint() {
}
public void testSelect() {
}
public void testSetVarDecay() {
}
public void testUndo() {
}
public void testUpdateVar() {
}
public void testVarDecayActivity() {
}
public void testNumberOfInterestingVariables() {
}
public void testGetVocabulary() {
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
voc = new ClausalDataStructureWL().getVocabulary();
voc.ensurePool(5);
order = new VarOrderHeap();
order.setLits(voc);
}
private ILits voc;
private IOrder order;
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.jaxrs.2.0.client_fat/test-applications/thirdpartyjerseyclient/src/com/ibm/ws/jaxrs20/client/ThirdpartyJerseyClient/service/ServiceServlet.java | 1645 | /*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jaxrs20.client.ThirdpartyJerseyClient.service;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Test/*")
public class ServiceServlet extends HttpServlet {
private static final long serialVersionUID = 8688034399080432350L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getPathInfo();
PrintWriter pw = resp.getWriter();
if (null != path && path.equals("/BasicResource/echo/alex")) {
pw.write("[Basic Resource]:alex");
}
else {
pw.write("You should not see me");
}
pw.flush();
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
| epl-1.0 |
pchel-/pty4j | src/com/pty4j/windows/WinPtyProcess.java | 2754 | package com.pty4j.windows;
import com.google.common.base.Joiner;
import com.pty4j.PtyException;
import com.pty4j.PtyProcess;
import com.pty4j.WinSize;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author traff
*/
public class WinPtyProcess extends PtyProcess {
private final WinPty myWinPty;
private final WinPTYInputStream myInputStream;
private final InputStream myErrorStream;
private final WinPTYOutputStream myOutputStream;
@Deprecated
public WinPtyProcess(String[] command, String[] environment, String workingDirectory, boolean consoleMode) throws IOException {
this(command, convertEnvironment(environment), workingDirectory, consoleMode);
}
private static String convertEnvironment(String[] environment) {
StringBuilder envString = new StringBuilder();
for (String s : environment) {
envString.append(s).append('\0');
}
envString.append('\0');
return envString.toString();
}
public WinPtyProcess(String[] command, String environment, String workingDirectory, boolean consoleMode) throws IOException {
try {
myWinPty = new WinPty(Joiner.on(" ").join(command), workingDirectory, environment, consoleMode);
}
catch (PtyException e) {
throw new IOException("Couldn't create PTY", e);
}
myInputStream = new WinPTYInputStream(myWinPty.getInputPipe());
myOutputStream = new WinPTYOutputStream(myWinPty.getOutputPipe(), consoleMode, true);
if (!consoleMode) {
myErrorStream = new InputStream() {
@Override
public int read() {
return -1;
}
};
}
else {
myErrorStream = new WinPTYInputStream(myWinPty.getErrorPipe());
}
}
@Override
public boolean isRunning() {
return myWinPty.exitValue() == -1;
}
@Override
public void setWinSize(WinSize winSize) {
myWinPty.setWinSize(winSize);
}
@Override
public WinSize getWinSize() throws IOException {
return null; //TODO
}
@Override
public OutputStream getOutputStream() {
return myOutputStream;
}
@Override
public InputStream getInputStream() {
return myInputStream;
}
@Override
public InputStream getErrorStream() {
return myErrorStream;
}
@Override
public int waitFor() throws InterruptedException {
for (; ; ) {
int exitCode = myWinPty.exitValue();
if (exitCode != -1) {
return exitCode;
}
Thread.sleep(1000);
}
}
@Override
public int exitValue() {
int exitValue = myWinPty.exitValue();
if (exitValue == -1) {
throw new IllegalThreadStateException("Not terminated yet");
}
return exitValue;
}
@Override
public void destroy() {
myWinPty.close();
}
}
| epl-1.0 |
jacobfilik/scanning | org.eclipse.scanning.event.ui/src/org/eclipse/scanning/event/ui/view/StatusQueueView.java | 40645 | /*
* Copyright (c) 2012 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.scanning.event.ui.view;
import java.io.File;
import java.math.RoundingMode;
import java.net.URI;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EventListener;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.scanning.api.event.EventConstants;
import org.eclipse.scanning.api.event.EventException;
import org.eclipse.scanning.api.event.IEventService;
import org.eclipse.scanning.api.event.alive.PauseBean;
import org.eclipse.scanning.api.event.bean.BeanEvent;
import org.eclipse.scanning.api.event.bean.IBeanListener;
import org.eclipse.scanning.api.event.core.ConsumerConfiguration;
import org.eclipse.scanning.api.event.core.IPublisher;
import org.eclipse.scanning.api.event.core.ISubmitter;
import org.eclipse.scanning.api.event.core.ISubscriber;
import org.eclipse.scanning.api.event.queues.QueueViews;
import org.eclipse.scanning.api.event.scan.ScanBean;
import org.eclipse.scanning.api.event.status.AdministratorMessage;
import org.eclipse.scanning.api.event.status.OpenRequest;
import org.eclipse.scanning.api.event.status.StatusBean;
import org.eclipse.scanning.api.ui.IModifyHandler;
import org.eclipse.scanning.api.ui.IRerunHandler;
import org.eclipse.scanning.api.ui.IResultHandler;
import org.eclipse.scanning.event.ui.Activator;
import org.eclipse.scanning.event.ui.ServiceHolder;
import org.eclipse.scanning.event.ui.dialog.PropertiesDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A view for which the secondary id MUST be set and provides the queueName
* and optionally the queue view name if a custom one is required. Syntax of
* these parameters in the secondary id are key1=value1;key2=value2...
*
* The essential keys are: beanBundleName, beanClassName, queueName, topicName, submissionQueueName
* You can use createId(...) to generate a legal id from them.
*
* The optional keys are: partName,
* uri (default CommandConstants.JMS_URI),
* userName (default is user.name system property)
*
* Example id for this view would be:
* org.eclipse.scanning.event.ui.queueView:beanClassName=org.dawnsci.commandserver.mx.beans.ProjectBean;beanBundleName=org.dawnsci.commandserver.mx
*
* You can optionally extend this class to provide a table which is displayed for your
* queue of custom objects. For instance for a queue showing xia2 reruns, the
* extra columns for this could be defined. However by default the
*
* @author Matthew Gerring
*
*/
public class StatusQueueView extends EventConnectionView {
private static final String RERUN_HANDLER_EXTENSION_POINT_ID = "org.eclipse.scanning.api.rerunHandler";
private static final String MODIFY_HANDLER_EXTENSION_POINT_ID = "org.eclipse.scanning.api.modifyHandler";
private static final String RESULTS_HANDLER_EXTENSION_POINT_ID = "org.eclipse.scanning.api.resultsHandler";
public static final String ID = "org.eclipse.scanning.event.ui.queueView";
private static final Logger logger = LoggerFactory.getLogger(StatusQueueView.class);
// UI
private TableViewer viewer;
private DelegatingSelectionProvider selectionProvider;
// Data
private Map<String, StatusBean> queue;
private boolean showEntireQueue = false;
private ISubscriber<IBeanListener<StatusBean>> topicMonitor;
private ISubscriber<IBeanListener<PauseBean>> pauseMonitor;
private ISubscriber<IBeanListener<AdministratorMessage>> adminMonitor;
private ISubmitter<StatusBean> queueConnection;
private Action rerun, edit, remove, up, down, pause, pauseConsumer;
private IEventService service;
private ISubscriber<EventListener> pauseSubscriber;
private List<IResultHandler> resultsHandlers = null;
public StatusQueueView() {
this.service = ServiceHolder.getEventService();
}
@Override
public void createPartControl(Composite content) {
content.setLayout(new GridLayout(1, false));
Util.removeMargins(content);
this.viewer = new TableViewer(content, SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
viewer.setUseHashlookup(true);
viewer.getTable().setHeaderVisible(true);
viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
createColumns();
viewer.setContentProvider(createContentProvider());
try {
queueConnection = service.createSubmitter(getUri(), getSubmissionQueueName());
queueConnection.setStatusTopicName(getTopicName());
updateQueue(getUri());
String name = getSecondaryIdAttribute("partName");
if (name!=null) setPartName(name);
createActions();
// We just use this submitter to read the queue
createTopicListener(getUri());
} catch (Exception e) {
logger.error("Cannot listen to topic of command server!", e);
}
selectionProvider = new DelegatingSelectionProvider(viewer);
getViewSite().setSelectionProvider(selectionProvider);
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
updateSelected();
}
});
}
protected void updateSelected() {
for(StatusBean bean : getSelection()) {
remove.setEnabled(bean.getStatus()!=null);
rerun.setEnabled(true);
boolean isSubmitted = bean.getStatus()==org.eclipse.scanning.api.event.status.Status.SUBMITTED;
up.setEnabled(isSubmitted);
edit.setEnabled(isSubmitted);
down.setEnabled(isSubmitted);
pause.setEnabled(bean.getStatus().isRunning()||bean.getStatus().isPaused());
pause.setChecked(bean.getStatus().isPaused());
pause.setText(bean.getStatus().isPaused()?"Resume job":"Pause job");
}
}
/**
* Listens to a topic
*/
private void createTopicListener(final URI uri) throws Exception {
// Use job because connection might timeout.
final Job topicJob = new Job("Create topic listener") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
topicMonitor = service.createSubscriber(uri, getTopicName());
topicMonitor.addListener(new IBeanListener<StatusBean>() {
@Override
public void beanChangePerformed(BeanEvent<StatusBean> evt) {
final StatusBean bean = evt.getBean();
try {
mergeBean(bean);
} catch (Exception e) {
logger.error("Cannot merge changed bean!");
}
}
});
adminMonitor = service.createSubscriber(uri, IEventService.ADMIN_MESSAGE_TOPIC);
adminMonitor.addListener(new IBeanListener<AdministratorMessage>() {
@Override
public void beanChangePerformed(BeanEvent<AdministratorMessage> evt) {
final AdministratorMessage bean = evt.getBean();
getSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(getViewSite().getShell(),
bean.getTitle(),
bean.getMessage());
viewer.refresh();
}
});
}
});
return Status.OK_STATUS;
} catch (Exception ne) {
logger.error("Cannot listen to topic changes because command server is not there", ne);
return Status.CANCEL_STATUS;
}
}
};
topicJob.setPriority(Job.INTERACTIVE);
topicJob.setSystem(true);
topicJob.setUser(false);
topicJob.schedule();
}
@Override
public void dispose() {
super.dispose();
try {
if (topicMonitor!=null) topicMonitor.disconnect();
if (adminMonitor!=null) adminMonitor.disconnect();
if (pauseSubscriber!=null) pauseSubscriber.disconnect();
} catch (Exception ne) {
logger.warn("Problem stopping topic listening for "+getTopicName(), ne);
}
}
/**
* Updates the bean if it is found in the list, otherwise
* refreshes the whole list because a bean we are not reporting
* has been(bean?) encountered.
*
* @param bean
*/
protected void mergeBean(final StatusBean bean) throws Exception {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run(){
if (queue.containsKey(bean.getUniqueId())) {
queue.get(bean.getUniqueId()).merge(bean);
viewer.refresh();
updateSelected();
} else {
reconnect();
}
}
});
}
private void createActions() throws Exception {
final IContributionManager toolMan = getViewSite().getActionBars().getToolBarManager();
final IContributionManager dropDown = getViewSite().getActionBars().getMenuManager();
final MenuManager menuMan = new MenuManager();
final Action openResults = new Action("Open results for selected run", Activator.getImageDescriptor("icons/results.png")) {
@Override
public void run() {
for (StatusBean bean : getSelection()) {
openResults(bean);
}
}
};
toolMan.add(openResults);
toolMan.add(new Separator());
menuMan.add(openResults);
menuMan.add(new Separator());
dropDown.add(openResults);
dropDown.add(new Separator());
this.up = new Action("Less urgent (-1)", Activator.getImageDescriptor("icons/arrow-090.png")) {
@Override
public void run() {
for(StatusBean bean : getSelection()) {
try {
queueConnection.reorder(bean, -1);
} catch (EventException e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot move "+bean.getName(), "'"+bean.getName()+"' cannot be moved in the submission queue.",
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
}
refresh();
}
};
up.setEnabled(false);
toolMan.add(up);
menuMan.add(up);
dropDown.add(up);
this.down = new Action("More urgent (+1)", Activator.getImageDescriptor("icons/arrow-270.png")) {
@Override
public void run() {
for (StatusBean bean : getSelection()) {
try {
queueConnection.reorder(bean, +1);
} catch (EventException e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot move "+bean.getName(), e.getMessage(),
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
}
refresh();
}
};
down.setEnabled(false);
toolMan.add(down);
menuMan.add(down);
dropDown.add(down);
this.pause = new Action("Pause job.\nPauses a running job.", IAction.AS_CHECK_BOX) {
@Override
public void run() {
pauseJob();
}
};
pause.setImageDescriptor(Activator.getImageDescriptor("icons/control-pause.png"));
pause.setEnabled(false);
pause.setChecked(false);
toolMan.add(pause);
menuMan.add(pause);
dropDown.add(pause);
this.pauseConsumer = new Action("Pause "+getPartName()+" Queue. Does not pause running job.", IAction.AS_CHECK_BOX) {
@Override
public void run() {
togglePausedConsumer(this);
}
};
pauseConsumer.setImageDescriptor(Activator.getImageDescriptor("icons/control-pause-red.png"));
pauseConsumer.setChecked(queueConnection.isQueuePaused(getSubmissionQueueName()));
toolMan.add(pauseConsumer);
menuMan.add(pauseConsumer);
dropDown.add(pauseConsumer);
this.pauseMonitor = service.createSubscriber(getUri(), EventConstants.CMD_TOPIC);
pauseMonitor.addListener(new IBeanListener<PauseBean>() {
@Override
public void beanChangePerformed(BeanEvent<PauseBean> evt) {
pauseConsumer.setChecked(queueConnection.isQueuePaused(getSubmissionQueueName()));
}
});
this.remove = new Action("Stop job or remove if finished", Activator.getImageDescriptor("icons/control-stop-square.png")) {
@Override
public void run() {
stopJob();
}
};
remove.setEnabled(false);
toolMan.add(remove);
menuMan.add(remove);
dropDown.add(remove);
this.rerun = new Action("Rerun...", Activator.getImageDescriptor("icons/rerun.png")) {
@Override
public void run() {
rerunSelection();
}
};
rerun.setEnabled(false);
toolMan.add(rerun);
menuMan.add(rerun);
dropDown.add(rerun);
IAction open = new Action("Open...", Activator.getImageDescriptor("icons/application-dock-090.png")) {
@Override
public void run() {
openSelection();
}
};
toolMan.add(open);
menuMan.add(open);
dropDown.add(open);
this.edit = new Action("Edit...", Activator.getImageDescriptor("icons/modify.png")) {
@Override
public void run() {
editSelection();
}
};
edit.setEnabled(false);
toolMan.add(edit);
menuMan.add(edit);
dropDown.add(edit);
toolMan.add(new Separator());
menuMan.add(new Separator());
final Action showAll = new Action("Show other users results", IAction.AS_CHECK_BOX) {
@Override
public void run() {
showEntireQueue = isChecked();
viewer.refresh();
}
};
showAll.setImageDescriptor(Activator.getImageDescriptor("icons/spectacle-lorgnette.png"));
toolMan.add(showAll);
menuMan.add(showAll);
dropDown.add(showAll);
toolMan.add(new Separator());
menuMan.add(new Separator());
dropDown.add(new Separator());
final Action refresh = new Action("Refresh", Activator.getImageDescriptor("icons/arrow-circle-double-135.png")) {
@Override
public void run() {
reconnect();
}
};
toolMan.add(refresh);
menuMan.add(refresh);
dropDown.add(refresh);
final Action configure = new Action("Configure...", Activator.getImageDescriptor("icons/document--pencil.png")) {
@Override
public void run() {
PropertiesDialog dialog = new PropertiesDialog(getSite().getShell(), idProperties);
int ok = dialog.open();
if (ok == PropertiesDialog.OK) {
idProperties.clear();
idProperties.putAll(dialog.getProps());
reconnect();
}
}
};
toolMan.add(configure);
menuMan.add(configure);
dropDown.add(configure);
final Action clearQueue = new Action("Clear Queue") {
@Override
public void run() {
try {
purgeQueues();
} catch (EventException e) {
e.printStackTrace();
logger.error("Canot purge queues", e);
}
}
};
menuMan.add(new Separator());
dropDown.add(new Separator());
menuMan.add(clearQueue);
dropDown.add(clearQueue);
viewer.getControl().setMenu(menuMan.createContextMenu(viewer.getControl()));
}
protected void togglePausedConsumer(IAction pauseConsumer) {
// The button can get out of sync if two clients are used.
final boolean currentState = queueConnection.isQueuePaused(getSubmissionQueueName());
try {
pauseConsumer.setChecked(!currentState); // We are toggling it.
IPublisher<PauseBean> pauser = service.createPublisher(getUri(), IEventService.CMD_TOPIC);
pauser.setStatusSetName(IEventService.CMD_SET); // The set that other clients may check
pauser.setStatusSetAddRequired(true);
PauseBean pbean = new PauseBean();
pbean.setQueueName(getSubmissionQueueName()); // The queue we are pausing
pbean.setPause(pauseConsumer.isChecked());
pauser.broadcast(pbean);
} catch (Exception e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot pause queue "+getSubmissionQueueName(), "Cannot pause queue "+getSubmissionQueueName()+"\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
pauseConsumer.setChecked(queueConnection.isQueuePaused(getSubmissionQueueName()));
}
protected void pauseJob() {
for(StatusBean bean : getSelection()) {
if (bean.getStatus().isFinal()) {
MessageDialog.openInformation(getViewSite().getShell(), "Run '"+bean.getName()+"' inactive", "Run '"+bean.getName()+"' is inactive and cannot be paused.");
continue;
}
try {
if (bean.getStatus().isPaused()) {
bean.setStatus(org.eclipse.scanning.api.event.status.Status.REQUEST_RESUME);
bean.setMessage("Resume of "+bean.getName());
} else {
bean.setStatus(org.eclipse.scanning.api.event.status.Status.REQUEST_PAUSE);
bean.setMessage("Pause of "+bean.getName());
}
IPublisher<StatusBean> terminate = service.createPublisher(getUri(), getTopicName());
terminate.broadcast(bean);
} catch (Exception e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot pause "+bean.getName(), "Cannot pause "+bean.getName()+"\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
}
}
protected void stopJob() {
for(StatusBean bean : getSelection()) {
if (!bean.getStatus().isActive()) {
String queueName = null;
if (bean.getStatus()!=org.eclipse.scanning.api.event.status.Status.SUBMITTED) {
queueName = getQueueName();
boolean ok = MessageDialog.openQuestion(getSite().getShell(), "Confirm Remove '"+bean.getName()+"'", "Are you sure you would like to remove '"+bean.getName()+"'?");
if (!ok) continue;
} else {
// Submitted delete it right away without asking or the consumer will run it!
queueName = getSubmissionQueueName();
}
// It is submitted and not running. We can probably delete it.
try {
queueConnection.remove(bean, queueName);
refresh();
} catch (EventException e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot delete "+bean.getName(), "Cannot delete "+bean.getName()+"\n\nIt might have changed state at the same time and being remoted.",
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
continue;
}
try {
final DateFormat format = DateFormat.getDateTimeInstance();
boolean ok = MessageDialog.openQuestion(getViewSite().getShell(), "Confirm terminate "+bean.getName(),
"Are you sure you want to terminate "+bean.getName()+" submitted on "+format.format(new Date(bean.getSubmissionTime()))+"?");
if (!ok) continue;
bean.setStatus(org.eclipse.scanning.api.event.status.Status.REQUEST_TERMINATE);
bean.setMessage("Termination of "+bean.getName());
IPublisher<StatusBean> terminate = service.createPublisher(getUri(), getTopicName());
terminate.broadcast(bean);
} catch (Exception e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot terminate "+bean.getName(), "Cannot terminate "+bean.getName()+"\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, "org.eclipse.scanning.event.ui", e.getMessage()));
}
}
}
protected void purgeQueues() throws EventException {
boolean ok = MessageDialog.openQuestion(getSite().getShell(), "Confirm Clear Queues", "Are you sure you would like to remove all items from the queue "+getQueueName()+" and "+getSubmissionQueueName()+"?\n\nThis could abort or disconnect runs of other users.");
if (!ok) return;
queueConnection.clearQueue(getQueueName());
queueConnection.clearQueue(getSubmissionQueueName());
reconnect();
}
private List<IResultHandler> getResultsHandlers() {
if (resultsHandlers == null) {
final IConfigurationElement[] configElements = Platform.getExtensionRegistry()
.getConfigurationElementsFor(RESULTS_HANDLER_EXTENSION_POINT_ID);
final List<IResultHandler> handlers = new ArrayList<>(configElements.length + 1);
for (IConfigurationElement configElement : configElements) {
try {
final IResultHandler handler = (IResultHandler) configElement.createExecutableExtension("class");
handler.init(service, createConsumerConfiguration());
handlers.add(handler);
} catch (Exception e) {
ErrorDialog.openError(getSite().getShell(), "Internal Error",
"Could not create results handler for class " + configElement.getAttribute("class") +
".\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
}
}
handlers.add(new DefaultResultsHandler());
resultsHandlers = handlers;
}
return resultsHandlers;
}
/**
* You can override this method to provide custom opening of
* results if required.
*
* @param bean
*/
protected void openResults(StatusBean bean) {
if (bean == null) return;
for (IResultHandler handler : getResultsHandlers()) {
if (handler.isHandled(bean)) {
try {
boolean ok = handler.open(bean);
if (ok) return;
} catch (Exception e) {
ErrorDialog.openError(getSite().getShell(), "Internal Error", handler.getErrorMessage(null),
new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
}
}
}
}
/**
* Pushes any previous run back into the UI
*/
protected void openSelection() {
final StatusBean [] beans = getSelection();
if (beans.length == 0) {
MessageDialog.openInformation(getViewSite().getShell(), "Please select a run", "Please select a run to open.");
return;
}
// TODO FIXME Change to IScanBuilderService not selections so that it works with e4.
// We fire a special object into the selection mechanism with the data for this run.
// It is then up to parts to respond to this selection and update their contents.
// We call fireSelection as the openRequest isn't in the table. This sets the workb
for (StatusBean bean : beans) {
selectionProvider.fireSelection(new StructuredSelection(new OpenRequest(bean)));
}
}
/**
* Edits a not run yet selection
*/
protected void editSelection() {
for (StatusBean bean : getSelection()) {
if (bean.getStatus()!=org.eclipse.scanning.api.event.status.Status.SUBMITTED) {
MessageDialog.openConfirm(getSite().getShell(), "Cannot Edit '"+bean.getName()+"'", "The run '"+bean.getName()+"' cannot be edited because it is not waiting to run.");
continue;
}
try {
final IConfigurationElement[] c = Platform.getExtensionRegistry().getConfigurationElementsFor(MODIFY_HANDLER_EXTENSION_POINT_ID);
if (c!=null) {
for (IConfigurationElement i : c) {
final IModifyHandler handler = (IModifyHandler)i.createExecutableExtension("class");
handler.init(service, createConsumerConfiguration());
if (handler.isHandled(bean)) {
boolean ok = handler.modify(bean);
if (ok) continue;
}
}
}
} catch (Exception ne) {
ne.printStackTrace();
ErrorDialog.openError(getSite().getShell(), "Internal Error", "Cannot modify "+bean.getRunDirectory()+" normally.\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, Activator.PLUGIN_ID, ne.getMessage()));
continue;
}
MessageDialog.openConfirm(getSite().getShell(), "Cannot Edit '"+bean.getName()+"'", "There are no editers registered for '"+bean.getName()+"'\n\nPlease contact your support representative.");
}
}
protected void rerunSelection() {
for (StatusBean bean : getSelection()) {
try {
final IConfigurationElement[] c = Platform.getExtensionRegistry().getConfigurationElementsFor(RERUN_HANDLER_EXTENSION_POINT_ID);
if (c!=null) {
for (IConfigurationElement i : c) {
final IRerunHandler handler = (IRerunHandler)i.createExecutableExtension("class");
handler.init(service, createConsumerConfiguration());
if (handler.isHandled(bean)) {
final StatusBean copy = bean.getClass().newInstance();
copy.merge(bean);
copy.setUniqueId(UUID.randomUUID().toString());
copy.setStatus(org.eclipse.scanning.api.event.status.Status.SUBMITTED);
copy.setSubmissionTime(System.currentTimeMillis());
boolean ok = handler.run(copy);
if (ok) continue;
}
}
}
} catch (Exception ne) {
ne.printStackTrace();
ErrorDialog.openError(getSite().getShell(), "Internal Error", "Cannot rerun "+bean.getRunDirectory()+" normally.\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, Activator.PLUGIN_ID, ne.getMessage()));
continue;
}
// If we have not already handled this rerun, it is possible to call a generic one.
rerun(bean);
}
}
private ConsumerConfiguration createConsumerConfiguration() throws Exception {
return new ConsumerConfiguration(getUri(), getSubmissionQueueName(), getTopicName(), getQueueName());
}
private void rerun(StatusBean bean) {
try {
final DateFormat format = DateFormat.getDateTimeInstance();
boolean ok = MessageDialog.openQuestion(getViewSite().getShell(), "Confirm resubmission "+bean.getName(),
"Are you sure you want to rerun "+bean.getName()+" submitted on "+format.format(new Date(bean.getSubmissionTime()))+"?");
if (!ok) return;
final StatusBean copy = bean.getClass().newInstance();
copy.merge(bean);
copy.setUniqueId(UUID.randomUUID().toString());
copy.setMessage("Rerun of "+bean.getName());
copy.setStatus(org.eclipse.scanning.api.event.status.Status.SUBMITTED);
copy.setPercentComplete(0.0);
copy.setSubmissionTime(System.currentTimeMillis());
queueConnection.submit(copy, true);
reconnect();
} catch (Exception e) {
ErrorDialog.openError(getViewSite().getShell(), "Cannot rerun "+bean.getName(), "Cannot rerun "+bean.getName()+"\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
}
}
public void refresh() {
reconnect();
updateSelected();
}
protected void reconnect() {
try {
updateQueue(getUri());
} catch (Exception e) {
logger.error("Cannot resolve uri for activemq server of "+getSecondaryIdAttribute("uri"));
}
}
private IContentProvider createContentProvider() {
return new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
queue = (Map<String, StatusBean>)newInput;
}
@Override
public void dispose() {
if (queue!=null) queue.clear();
}
@Override
public Object[] getElements(Object inputElement) {
if (queue==null) return new StatusBean[]{StatusBean.EMPTY};
final List<StatusBean> retained = new ArrayList<StatusBean>(queue.values());
// This preference is not secure people could hack DAWN to do this.
if (!Boolean.getBoolean("org.dawnsci.commandserver.ui.view.showWholeQueue")) {
// Old fashioned loop. In Java8 we will use a predicate...
final String userName = getUserName();
for (Iterator it = retained.iterator(); it.hasNext();) {
StatusBean statusBean = (StatusBean) it.next();
if (statusBean.getUserName()==null) continue;
if (!showEntireQueue) {
if (!userName.equals(statusBean.getUserName())) it.remove();
}
}
// This form of filtering is not at all secure because we
// give the full list of the queue to the clients.
}
return retained.toArray(new StatusBean[retained.size()]);
}
};
}
protected StatusBean [] getSelection() {
final ISelection sel = viewer.getSelection();
IStructuredSelection ss = (IStructuredSelection)sel;
return Arrays.stream(ss.toArray()).toArray(StatusBean[]::new);
}
/**
* Read Queue and return in submission order.
* @param uri
* @return
* @throws Exception
*/
protected synchronized void updateQueue(final URI uri) {
final Job queueJob = new Job("Connect and read queue") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Connect to command server", 10);
monitor.worked(1);
queueConnection.setBeanClass(getBeanClass());
List<StatusBean> runningList = queueConnection.getQueue(getQueueName(), null);
Collections.reverse(runningList); // The list comes out with the head @ 0 but we have the last submitted at 0 in our table.
monitor.worked(1);
List<StatusBean> submittedList = queueConnection.getQueue(getSubmissionQueueName(), null);
Collections.reverse(submittedList); // The list comes out with the head @ 0 but we have the last submitted at 0 in our table.
monitor.worked(1);
// We reverse the queue because it comes out date ascending and we
// want newest submissions first.
final Map<String,StatusBean> ret = new LinkedHashMap<String,StatusBean>();
for (StatusBean bean : submittedList) {
ret.put(bean.getUniqueId(), bean);
}
monitor.worked(1);
for (StatusBean bean : runningList) {
ret.put(bean.getUniqueId(), bean);
}
monitor.worked(1);
getSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(ret);
viewer.refresh();
}
});
monitor.done();
return Status.OK_STATUS;
} catch (final Exception e) {
e.printStackTrace();
monitor.done();
logger.error("Updating changed bean from topic", e);
getSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
ErrorDialog.openError(getViewSite().getShell(), "Cannot connect to queue", "The server is unavailable at "+getUriString()+".\n\nPlease contact your support representative.",
new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
}
});
return Status.CANCEL_STATUS;
}
}
};
queueJob.setPriority(Job.INTERACTIVE);
queueJob.setUser(true);
queueJob.schedule();
}
private Class<StatusBean> getBeanClass() {
String beanBundleName = getSecondaryIdAttribute("beanBundleName");
String beanClassName = getSecondaryIdAttribute("beanClassName");
try {
Bundle bundle = Platform.getBundle(beanBundleName);
return (Class<StatusBean>)bundle.loadClass(beanClassName);
} catch (Exception ne) {
logger.error("Cannot get class "+beanClassName+". Defaulting to StatusBean. This will probably not work though.", ne);
return StatusBean.class;
}
}
protected void createColumns() {
final TableViewerColumn name = new TableViewerColumn(viewer, SWT.LEFT);
name.getColumn().setText("Name");
name.getColumn().setWidth(260);
name.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return ((StatusBean)element).getName();
}
});
final TableViewerColumn status = new TableViewerColumn(viewer, SWT.LEFT);
status.getColumn().setText("Status");
status.getColumn().setWidth(80);
status.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return ((StatusBean)element).getStatus().toString();
}
});
final TableViewerColumn pc = new TableViewerColumn(viewer, SWT.CENTER);
pc.getColumn().setText("Complete");
pc.getColumn().setWidth(70);
final NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setRoundingMode(RoundingMode.DOWN);
pc.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
String text = percentFormat.format(((StatusBean)element).getPercentComplete()/100d);
return text;
} catch (Exception ne) {
return "-";
}
}
});
final TableViewerColumn submittedDate = new TableViewerColumn(viewer, SWT.CENTER);
submittedDate.getColumn().setText("Date Submitted");
submittedDate.getColumn().setWidth(120);
submittedDate.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
return DateFormat.getDateTimeInstance().format(new Date(((StatusBean)element).getSubmissionTime()));
} catch (Exception e) {
return e.getMessage();
}
}
});
final TableViewerColumn message = new TableViewerColumn(viewer, SWT.LEFT);
message.getColumn().setText("Message");
message.getColumn().setWidth(150);
message.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
return ((StatusBean)element).getMessage();
} catch (Exception e) {
return e.getMessage();
}
}
});
final TableViewerColumn location = new TableViewerColumn(viewer, SWT.LEFT);
location.getColumn().setText("Location");
location.getColumn().setWidth(300);
location.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
final StatusBean bean = (StatusBean)element;
return getLocation(bean);
} catch (Exception e) {
return e.getMessage();
}
}
@Override
public Color getForeground(Object element) {
boolean isFinal = ((StatusBean) element).getStatus().isFinal();
return getSite().getShell().getDisplay().getSystemColor(isFinal ? SWT.COLOR_BLUE : SWT.COLOR_BLACK);
}
});
final TableViewerColumn host = new TableViewerColumn(viewer, SWT.CENTER);
host.getColumn().setText("Host");
host.getColumn().setWidth(90);
host.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
return ((StatusBean)element).getHostName();
} catch (Exception e) {
return e.getMessage();
}
}
});
final TableViewerColumn user = new TableViewerColumn(viewer, SWT.CENTER);
user.getColumn().setText("User Name");
user.getColumn().setWidth(80);
user.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
return ((StatusBean)element).getUserName();
} catch (Exception e) {
return e.getMessage();
}
}
});
final TableViewerColumn startTime = new TableViewerColumn(viewer, SWT.CENTER);
startTime.getColumn().setText("Start Time");
startTime.getColumn().setWidth(120);
startTime.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
long statusStartTime = ((StatusBean)element).getStartTime();
if (statusStartTime == 0) return "";
return DateFormat.getTimeInstance().format(new Date(statusStartTime));
} catch (Exception e) {
return e.getMessage();
}
}
});
final TableViewerColumn estimatedEndTime = new TableViewerColumn(viewer, SWT.CENTER);
estimatedEndTime.getColumn().setText("E. End Time");
estimatedEndTime.getColumn().setWidth(120);
estimatedEndTime.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
try {
long statusEstimatedEndTime = ((StatusBean)element).getStartTime() + ((StatusBean)element).getEstimatedTime();
if (statusEstimatedEndTime == 0) return "";
return DateFormat.getTimeInstance().format(new Date(statusEstimatedEndTime));
} catch (Exception e) {
return e.getMessage();
}
}
});
MouseMoveListener cursorListener = new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent e) {
Point pt = new Point(e.x, e.y);
TableItem item = viewer.getTable().getItem(pt);
Cursor cursor = null;
if (item != null && item.getBounds(5).contains(pt)) {
StatusBean statusBean = (StatusBean) item.getData();
if (statusBean != null && getLocation(statusBean) != null && statusBean.getStatus().isFinal()) {
cursor = Display.getDefault().getSystemCursor(SWT.CURSOR_HAND);
}
}
viewer.getTable().setCursor(cursor);
}
};
viewer.getTable().addMouseMoveListener(cursorListener);
MouseAdapter mouseClick = new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
Point pt = new Point(e.x, e.y);
TableItem item = viewer.getTable().getItem(pt);
if (item == null) return;
Rectangle rect = item.getBounds(5);
if (rect.contains(pt)) {
final StatusBean bean = (StatusBean)item.getData();
if (bean.getStatus().isFinal())
openResults(bean);
}
}
};
viewer.getTable().addMouseListener(mouseClick);
}
@Override
public void setFocus() {
if (!viewer.getTable().isDisposed()) {
viewer.getTable().setFocus();
}
}
public static String createId(final String beanBundleName, final String beanClassName, final String queueName, final String topicName, final String submissionQueueName) {
final StringBuilder buf = new StringBuilder();
buf.append(ID);
buf.append(":");
buf.append(QueueViews.createSecondaryId(beanBundleName, beanClassName, queueName, topicName, submissionQueueName));
return buf.toString();
}
public static String createId(final String uri, final String beanBundleName, final String beanClassName, final String queueName, final String topicName, final String submissionQueueName) {
final StringBuilder buf = new StringBuilder();
buf.append(ID);
buf.append(":");
buf.append(QueueViews.createSecondaryId(uri, beanBundleName, beanClassName, queueName, topicName, submissionQueueName));
return buf.toString();
}
/**
* Opens an external editor on an IEditorInput containing the file having filePath
* @param editorInput
* @param filePath
* @throws PartInitException
*/
private IEditorPart openExternalEditor(String filename) throws PartInitException {
return openExternalEditor(getExternalFileStoreEditorInput(filename), filename);
}
/**
* Opens an external editor on an IEditorInput containing the file having filePath
* @param editorInput
* @param filePath
* @throws PartInitException
*/
private IEditorPart openExternalEditor(IEditorInput editorInput, String filePath) throws PartInitException {
//TODO Maybe this method could be improved by omitting filepath which comes from editorInput, but "how?" should be defined here
final IWorkbenchPage page = getViewSite().getPage();
IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(filePath);
if (desc == null) desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(filePath+".txt");
return page.openEditor(editorInput, desc.getId());
}
private String getLocation(final StatusBean statusBean) {
if (statusBean instanceof ScanBean) return ((ScanBean)statusBean).getFilePath();
return statusBean.getRunDirectory();
}
private static IEditorInput getExternalFileStoreEditorInput(String filename) {
final IFileStore externalFile = EFS.getLocalFileSystem().fromLocalFile(new File(filename));
return new FileStoreEditorInput(externalFile);
}
}
| epl-1.0 |
ModelWriter/WP3 | Source/eu.modelwriter.model/src/eu/modelwriter/model/ModelManager.java | 8944 | package eu.modelwriter.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import eu.modelwriter.model.ModelElement.BOUND;
import eu.modelwriter.model.exception.InvalidArityException;
import eu.modelwriter.model.exception.NoSuchModelElementException;
import eu.modelwriter.model.observer.Subject;
import eu.modelwriter.model.observer.UpdateType;
public class ModelManager extends Subject {
private static ModelManager manager;
private static final Universe universe = new Universe();
public static ModelManager getInstance() {
if (ModelManager.manager == null) {
ModelManager.manager = new ModelManager();
}
return ModelManager.manager;
}
public Atom addAtom(List<RelationSet> relationSets, final Serializable data, final BOUND bound)
throws InvalidArityException {
if (relationSets == null) {
relationSets = Arrays.asList(new RelationSet[] {});
}
final Atom atom;
final String id = UUID.randomUUID().toString();
atom = new Atom(relationSets, id, data, bound);
if (relationSets.size() == 0) {
ModelManager.universe.addStrayedAtom(atom);
} else {
ModelManager.universe.addAtom(atom);
for (int i = 0; i < relationSets.size(); i++) {
final Tuple unaryTuple = this.addTuple(relationSets.get(i), data, bound, 1, atom);
atom.addTuplesIn(unaryTuple);
relationSets.get(i).addTuple(unaryTuple);
}
}
this.notifyAllObservers(atom, UpdateType.ADD_ATOM);
return atom;
}
public RelationSet addRelationSet(final String name, final int arity) {
final RelationSet relationSet = new RelationSet(name, arity);
ModelManager.universe.addRelationSet(relationSet);
return relationSet;
}
public Tuple addTuple(final RelationSet relationSet, final Serializable data, final BOUND bound,
final int arity, final Atom... atoms) throws InvalidArityException {
if (arity != atoms.length) {
throw new InvalidArityException();
}
final List<RelationSet> relationSets;
if (relationSet == null) {
relationSets = Arrays.asList(new RelationSet[] {});
} else {
relationSets = Arrays.asList(new RelationSet[] {relationSet});
}
final Tuple tuple;
final String id = UUID.randomUUID().toString();
tuple = new Tuple(relationSet, id, data, bound, arity, atoms);
if (relationSets.size() == 0) {
ModelManager.universe.addStrayedTuple(tuple);
} else {
ModelManager.universe.addTuple(tuple);
try {
relationSet.addTuple(tuple);
} catch (final InvalidArityException e) {
e.printStackTrace();
}
}
this.notifyAllObservers(tuple, UpdateType.ADD_TUPLE);
return tuple;
}
public void boundAboutToChange(final ModelElement modelElement, final String string)
throws NoSuchModelElementException {
if (modelElement instanceof Atom) {
final Atom atom = this.getAtom(modelElement.getID());
for (final Tuple tuple : atom.getTuplesIn()) {
if (tuple.getArity() == 1) {
tuple.setBound(BOUND.valueOf(string));
this.notifyAllObservers(tuple, UpdateType.valueOf(string));
}
}
} else if (modelElement instanceof Tuple) {
final Tuple tuple = this.getTuple(modelElement.getID());
tuple.setBound(BOUND.valueOf(string));
this.notifyAllObservers(tuple, UpdateType.valueOf(string));
}
}
public void changeRelationSetsOfAtom(final String id, final List<String> newRelationSetsNames)
throws InvalidArityException, NoSuchModelElementException {
final Atom atom = this.getAtom(id);
final Iterator<Tuple> tuplesInIter = atom.getTuplesIn().iterator();
while (tuplesInIter.hasNext()) {
final Tuple tuple = tuplesInIter.next();
if (tuple.getArity() == 1) {
this.removeTuple(tuple.getID());
tuplesInIter.remove();
}
}
final List<RelationSet> newRelationSets = this.getRelationSets(newRelationSetsNames);
for (final RelationSet relationSet : newRelationSets) {
final Tuple tuple = this.addTuple(relationSet, atom.getData(), atom.getBound(), 1, atom);
atom.addTuplesIn(tuple);
relationSet.addTuple(tuple);
}
atom.setRelationSets(newRelationSets);
this.notifyAllObservers(atom, UpdateType.CHANGE_RELATION_SETS);
}
public List<Atom> getAllAtoms() {
return Stream.concat(ModelManager.universe.getStrayedAtoms().stream(),
ModelManager.universe.getAtoms().stream()).collect(Collectors.toList());
}
public List<String> getAllRelationSetsNames() {
final List<String> relationSetsNames = new ArrayList<String>();
for (final RelationSet relationSet : ModelManager.universe.getRelationSets()) {
relationSetsNames.add(relationSet.getName());
}
return relationSetsNames;
}
public List<Tuple> getAllTuples() {
return Stream.concat(ModelManager.universe.getStrayedTuples().stream(),
ModelManager.universe.getTuples().stream()).collect(Collectors.toList());
}
public Atom getAtom(final String id) throws NoSuchModelElementException {
if (ModelManager.universe.containsStrayedAtom(id)) {
return ModelManager.universe.getStrayedAtom(id);
} else if (ModelManager.universe.containsAtom(id)) {
return ModelManager.universe.getAtom(id);
}
throw new NoSuchModelElementException();
}
public List<String> getNaryRelationSetNames() {
final List<String> naryRelationNames = new ArrayList<String>();
for (final RelationSet relationSet : ModelManager.universe.getRelationSets()) {
if (relationSet.getArity() > 1) {
naryRelationNames.add(relationSet.getName());
}
}
return naryRelationNames;
}
public RelationSet getRelationSet(final String relationSetName) {
return ModelManager.universe.getRelationSet(relationSetName);
}
public List<RelationSet> getRelationSets() {
return ModelManager.universe.getRelationSets();
}
public List<RelationSet> getRelationSets(final List<String> relationSetNames) {
final List<RelationSet> relationSets = new ArrayList<RelationSet>();
for (final String relationSetName : relationSetNames) {
final RelationSet relationSet = this.getRelationSet(relationSetName);
if (relationSet != null) {
relationSets.add(relationSet);
}
}
return relationSets;
}
public Tuple getTuple(final String id) throws NoSuchModelElementException {
if (ModelManager.universe.containsStrayedTuple(id)) {
return ModelManager.universe.getStrayedTuple(id);
} else if (ModelManager.universe.containsTuple(id)) {
return ModelManager.universe.getTuple(id);
}
throw new NoSuchModelElementException();
}
public List<String> getUnaryRelationSetNames() {
final List<String> unaryRelationSetNames = new ArrayList<String>();
unaryRelationSetNames.add("Univ");
for (final RelationSet relationSet : ModelManager.universe.getRelationSets()) {
if (relationSet.getArity() == 1) {
unaryRelationSetNames.add(relationSet.getName());
}
}
return unaryRelationSetNames;
}
public boolean removeAtom(final String id) throws NoSuchModelElementException {
boolean removed = false;
final Atom atom = this.getAtom(id);
if (atom.getRelationSets().size() == 0) {
removed = ModelManager.universe.removeStrayedAtom(id);
} else {
removed = ModelManager.universe.removeAtom(id);
for (final Tuple tupleIn : atom.getTuplesIn()) {
this.removeTuple(tupleIn.getID());
}
}
if (removed) {
this.notifyAllObservers(atom, UpdateType.REMOVE_ATOM);
return true;
}
throw new NoSuchModelElementException();
}
public boolean removeModelElement(final ModelElement element) throws NoSuchModelElementException {
if (element instanceof Atom) {
return this.removeAtom(element.getID());
} else if (element instanceof Tuple) {
return this.removeTuple(element.getID());
}
throw new NoSuchModelElementException();
}
public boolean removeTuple(final String id) throws NoSuchModelElementException {
boolean removed = false;
final Tuple tuple = this.getTuple(id);
if (tuple.getRelationSets().size() == 0) {
removed = ModelManager.universe.removeStrayedTuple(id);
} else {
removed = ModelManager.universe.removeTuple(id);
final Iterator<RelationSet> relationSetIter = tuple.getRelationSets().iterator();
while (relationSetIter.hasNext()) {
final RelationSet relationSet = relationSetIter.next();
relationSet.removeTuple(tuple.getID());
}
}
if (removed) {
this.notifyAllObservers(tuple, UpdateType.REMOVE_TUPLE);
return true;
}
throw new NoSuchModelElementException();
}
}
| epl-1.0 |
gomezabajo/Wodel | anatlyzer.atl.typing/src/anatlyzer/atl/analyser/namespaces/AbstractTypeNamespace.java | 5834 | package anatlyzer.atl.analyser.namespaces;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EStructuralFeature;
import anatlyzer.atl.analyser.AnalyserContext;
import anatlyzer.atl.analyser.libtypes.AtlTypeDef;
import anatlyzer.atl.analyser.typeconstraints.ITypeConstraint;
import anatlyzer.atl.types.Metaclass;
import anatlyzer.atl.types.Type;
import anatlyzer.atlext.ATL.LocatedElement;
import anatlyzer.atlext.OCL.Operation;
import anatlyzer.atlext.OCL.OperationCallExp;
import anatlyzer.atlext.OCL.Parameter;
import anatlyzer.atlext.OCL.VariableExp;
public abstract class AbstractTypeNamespace implements ITypeNamespace {
protected HashMap<String, FeatureInfo> featureInfos = new HashMap<String, FeatureInfo>();
protected FeatureInfo addFeatureInfo(String featureName, Type t) {
FeatureInfo info = new FeatureInfo(featureName, t);
featureInfos.put(featureName, info);
return info;
}
protected FeatureInfo addFeatureInfo(String featureName, Type t, EStructuralFeature f) {
FeatureInfo info = new FeatureInfo(featureName, t, f);
featureInfos.put(featureName, info);
return info;
}
@Override
public boolean hasFeature(String featureName) {
return AnalyserContext.getOclAnyInheritedNamespace().hasFeature(featureName);
}
/**
* Checks for common inherited operations.
* Does not have any side effect.
* @param featureName
* @param node Can be null.
*/
@Override
public Type getFeatureType(String featureName, LocatedElement node) {
return AnalyserContext.getOclAnyInheritedNamespace().getFeatureType(featureName, node);
}
@Override
public Type getFeatureType(String featureName, LocatedElement node, Consumer<Type> onImplicitCasting) {
return getFeatureType(featureName, node);
}
@Override
public boolean hasOperation(String operationName, Type[] arguments) {
if ( AnalyserContext.getOclAnyInheritedNamespace().hasOperation(operationName, arguments) )
return true;
return operationName.equals("oclIsUndefined") || operationName.equals("toString") ||
operationName.equals("oclIsKindOf") || operationName.equals("oclIsTypeOf");
}
@Override
public Type getOperationType(String operationName, Type[] arguments, LocatedElement node) {
Type t = AnalyserContext.getOclAnyInheritedNamespace().getOperationType(operationName, arguments, node);
if ( t != null )
return t;
// TODO: Replace this for libtypes
if ( operationName.equals("oclIsUndefined") ) {
checkArguments("oclIsUndefined", new Type[] {}, new String[] { }, arguments, node);
return AnalyserContext.getTypingModel().newBooleanType();
} else if ( operationName.equals("toString") ) {
checkArguments("toString", new Type[] {}, new String[] { }, arguments, node);
return AnalyserContext.getTypingModel().newStringType();
} else if ( operationName.equals("oclIsKindOf") || operationName.equals("oclIsTypeOf")) {
if ( arguments.length != 1 ) {
Type formalArgs[] = new Type[] { AnalyserContext.getTypingModel().newOclType() };
AnalyserContext.getErrorModel().signalOperationCallInvalidNumberOfParameters("oclIsKindOf", formalArgs , arguments, node);
return AnalyserContext.getTypingModel().newBooleanType();
}
if ( ! (arguments[0] instanceof Metaclass) ) {
AnalyserContext.getErrorModel().signalInvalidArgument(operationName, "Expected class", node);
return AnalyserContext.getTypingModel().newBooleanType();
}
OperationCallExp op = (OperationCallExp) node;
if ( op.getSource() instanceof VariableExp ) {
return AnalyserContext.getTypingModel().newBooleanType((Metaclass) arguments[0]);
} else {
return AnalyserContext.getTypingModel().newBooleanType();
}
} else if ( operationName.equals("debug") ) {
return this.getType();
}
AtlTypeDef typeDef = AnalyserContext.getStdLib().getTypeDefOf(this);
if ( typeDef != null ) {
return typeDef.getOperationReturnType(operationName);
}
return null;
}
protected static void checkArguments(String operationName, Type[] formalArguments, String[] formalArgumentsNames, Type[] arguments, LocatedElement node) {
if ( formalArguments.length != arguments.length ) {
AnalyserContext.getErrorModel().signalOperationCallInvalidNumberOfParameters(operationName, formalArguments, arguments, node);
return;
}
List<String> blamedParameters = new ArrayList<String>();
for(int i = 0; i < formalArguments.length; i++) {
if ( ! AnalyserContext.getTypingModel().assignableTypes(formalArguments[i], arguments[i]) ) {
blamedParameters.add(formalArgumentsNames[i]);
}
}
if ( blamedParameters.size() > 0 ) {
AnalyserContext.getErrorModel().signalOperationCallInvalidParameter(operationName, formalArguments, arguments, blamedParameters, node);
}
}
public static final Set<String> logicalOperators = new HashSet<String>();
static {
logicalOperators.add("=");
logicalOperators.add("<>");
logicalOperators.add(">");
logicalOperators.add(">=");
logicalOperators.add("<");
logicalOperators.add("<=");
}
@Override
public Type getOperatorType(String operatorSymbol, Type optionalArgument, LocatedElement node) {
if ( logicalOperators.contains(operatorSymbol) ) {
return AnalyserContext.getTypingModel().newBooleanType();
}
return null;
}
private Type getType() {
// This should be change for a "type" reference in the hierarchy, instead of
// creating a type each time, then createType() replace for cloneType in case this is actually needed
return createType(false);
}
@Override
public ITypeConstraint newTypeConstraint() {
throw new UnsupportedOperationException(this.getClass().getName());
}
}
| epl-1.0 |
rkadle/Tank | api/src/test/java/com/intuit/tank/script/RequestDataPhaseCpTest.java | 1081 | package com.intuit.tank.script;
/*
* #%L
* Intuit Tank Api
* %%
* Copyright (C) 2011 - 2015 Intuit Inc.
* %%
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* #L%
*/
import org.junit.*;
import com.intuit.tank.script.RequestDataPhase;
import static org.junit.Assert.*;
/**
* The class <code>RequestDataPhaseCpTest</code> contains tests for the class <code>{@link RequestDataPhase}</code>.
*
* @generatedBy CodePro at 9/3/14 3:44 PM
*/
public class RequestDataPhaseCpTest {
/**
* Run the String getDisplay() method test.
*
* @throws Exception
*
* @generatedBy CodePro at 9/3/14 3:44 PM
*/
@Test
public void testGetDisplay_1()
throws Exception {
RequestDataPhase fixture = RequestDataPhase.POST_REQUEST;
String result = fixture.getDisplay();
assertEquals("Post Request", result);
}
} | epl-1.0 |
codenvy/plugin-datasource | codenvy-ext-datasource-shared/src/main/java/org/eclipse/che/ide/ext/datasource/shared/exception/BadSQLRequestParameterException.java | 1206 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.datasource.shared.exception;
/**
* Exception for invalid SQL request parameters.
*
* @author "Mickaël Leduque"
*/
public class BadSQLRequestParameterException extends Exception {
/** UID for serialization */
private static final long serialVersionUID = 1L;
public BadSQLRequestParameterException() {
}
public BadSQLRequestParameterException(final String message) {
super(message);
}
public BadSQLRequestParameterException(final Throwable cause) {
super(cause);
}
public BadSQLRequestParameterException(final String message, final Throwable cause) {
super(message, cause);
}
}
| epl-1.0 |
bobwalker99/Pydev | plugins/org.python.pydev/pysrc/_pydev_runfiles/pydev_runfiles_pytest2.py | 9352 | import pickle, zlib, base64, os
import py
from _pydev_runfiles import pydev_runfiles_xml_rpc
from pydevd_file_utils import _NormFile
import pytest
import sys
import time
#===================================================================================================
# Load filters with tests we should skip
#===================================================================================================
py_test_accept_filter = None
def _load_filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(zlib.decompress(base64.b64decode(py_test_accept_filter)))
else:
py_test_accept_filter = {}
def connect_to_server_for_communication_to_xml_rpc_on_xdist():
main_pid = os.environ.get('PYDEV_MAIN_PID')
if main_pid and main_pid != str(os.getpid()):
port = os.environ.get('PYDEV_PYTEST_SERVER')
if not port:
sys.stderr.write('Error: no PYDEV_PYTEST_SERVER environment variable defined.\n')
else:
pydev_runfiles_xml_rpc.initialize_server(int(port), daemon=True)
PY2 = sys.version_info[0] <= 2
PY3 = not PY2
_mock_code = []
try:
from py._code import code # @UnresolvedImport
_mock_code.append(code)
except ImportError:
pass
try:
from _pytest._code import code # @UnresolvedImport
_mock_code.append(code)
except ImportError:
pass
#===================================================================================================
# Mocking to get clickable file representations
#===================================================================================================
def _MockFileRepresentation():
for code in _mock_code:
code.ReprFileLocation._original_toterminal = code.ReprFileLocation.toterminal
def toterminal(self, tw):
# filename and lineno output for each entry,
# using an output format that most editors understand
msg = self.message
i = msg.find("\n")
if i != -1:
msg = msg[:i]
path = os.path.abspath(self.path)
if PY2:
if not isinstance(path, unicode): # Note: it usually is NOT unicode...
path = path.decode(sys.getfilesystemencoding(), 'replace')
if not isinstance(msg, unicode): # Note: it usually is unicode...
msg = msg.decode('utf-8', 'replace')
unicode_line = unicode('File "%s", line %s\n%s') % (path, self.lineno, msg)
tw.line(unicode_line)
else:
tw.line('File "%s", line %s\n%s' % (path, self.lineno, msg))
code.ReprFileLocation.toterminal = toterminal
def _UninstallMockFileRepresentation():
for code in _mock_code:
code.ReprFileLocation.toterminal = code.ReprFileLocation._original_toterminal #@UndefinedVariable
class State:
numcollected = 0
start_time = time.time()
def pytest_configure(*args, **kwargs):
_MockFileRepresentation()
def pytest_collectreport(report):
i = 0
for x in report.result:
if isinstance(x, pytest.Item):
try:
# Call our setup (which may do a skip, in which
# case we won't count it).
pytest_runtest_setup(x)
i += 1
except:
continue
State.numcollected += i
def pytest_collection_modifyitems():
connect_to_server_for_communication_to_xml_rpc_on_xdist()
pydev_runfiles_xml_rpc.notifyTestsCollected(State.numcollected)
State.numcollected = 0
def pytest_unconfigure(*args, **kwargs):
_UninstallMockFileRepresentation()
pydev_runfiles_xml_rpc.notifyTestRunFinished('Finished in: %.2f secs.' % (time.time() - State.start_time,))
def pytest_runtest_setup(item):
filename = item.fspath.strpath
test = item.location[2]
State.start_test_time = time.time()
pydev_runfiles_xml_rpc.notifyStartTest(filename, test)
def report_test(cond, filename, test, captured_output, error_contents, delta):
'''
@param filename: 'D:\\src\\mod1\\hello.py'
@param test: 'TestCase.testMet1'
@param cond: fail, error, ok
'''
time_str = '%.2f' % (delta,)
pydev_runfiles_xml_rpc.notifyTest(cond, captured_output, error_contents, filename, test, time_str)
def pytest_runtest_makereport(item, call):
report_when = call.when
report_duration = call.stop-call.start
excinfo = call.excinfo
if not call.excinfo:
evalxfail = getattr(item, '_evalxfail', None)
if evalxfail and report_when == 'call' and (not hasattr(evalxfail, 'expr') or evalxfail.expr):
# I.e.: a method marked with xfail passed... let the user know.
report_outcome = "failed"
report_longrepr = "XFAIL: Unexpected pass"
else:
report_outcome = "passed"
report_longrepr = None
else:
excinfo = call.excinfo
handled = False
if not (call.excinfo and
call.excinfo.errisinstance(pytest.xfail.Exception)):
evalxfail = getattr(item, '_evalxfail', None)
# Something which had an xfail failed: this is expected.
if evalxfail and (not hasattr(evalxfail, 'expr') or evalxfail.expr):
report_outcome = "passed"
report_longrepr = None
handled = True
if handled:
pass
if excinfo.errisinstance(pytest.xfail.Exception):
# Case where an explicit xfail is raised (i.e.: pytest.xfail("reason") is called
# programatically).
report_outcome = "passed"
report_longrepr = None
elif excinfo.errisinstance(py.test.skip.Exception): # @UndefinedVariable
report_outcome = "skipped"
r = excinfo._getreprcrash()
report_longrepr = None #(str(r.path), r.lineno, r.message)
elif not isinstance(excinfo, py.code.ExceptionInfo): # @UndefinedVariable
report_outcome = "failed"
report_longrepr = excinfo
else:
report_outcome = "failed"
if call.when == "call":
report_longrepr = item.repr_failure(excinfo)
else: # exception in setup or teardown
report_longrepr = item._repr_failure_py(excinfo, style=item.config.option.tbstyle)
filename = item.fspath.strpath
test = item.location[2]
status = 'ok'
captured_output = ''
error_contents = ''
if report_outcome in ('passed', 'skipped'):
#passed or skipped: no need to report if in setup or teardown (only on the actual test if it passed).
if report_when in ('setup', 'teardown'):
return
else:
#It has only passed, skipped and failed (no error), so, let's consider error if not on call.
if report_when == 'setup':
if status == 'ok':
status = 'error'
elif report_when == 'teardown':
if status == 'ok':
status = 'error'
else:
#any error in the call (not in setup or teardown) is considered a regular failure.
status = 'fail'
if call.excinfo:
rep = report_longrepr
if hasattr(rep, 'reprcrash'):
reprcrash = rep.reprcrash
error_contents += str(reprcrash)
error_contents += '\n'
if hasattr(rep, 'reprtraceback'):
error_contents += str(rep.reprtraceback)
if hasattr(rep, 'sections'):
for name, content, sep in rep.sections:
error_contents += sep * 40
error_contents += name
error_contents += sep * 40
error_contents += '\n'
error_contents += content
error_contents += '\n'
else:
if report_longrepr:
error_contents += str(report_longrepr)
if status != 'skip': #I.e.: don't event report skips...
report_test(status, filename, test, captured_output, error_contents, report_duration)
@pytest.mark.tryfirst
def pytest_runtest_setup(item): # @DuplicatedSignature
'''
Skips tests. With xdist will be on a secondary process.
'''
_load_filters()
if not py_test_accept_filter:
return #Keep on going (nothing to filter)
f = _NormFile(str(item.parent.fspath))
name = item.name
if f not in py_test_accept_filter:
pytest.skip() # Skip the file
accept_tests = py_test_accept_filter[f]
if item.cls is not None:
class_name = item.cls.__name__
else:
class_name = None
for test in accept_tests:
# This happens when parameterizing pytest tests.
i = name.find('[')
if i > 0:
name = name[:i]
if test == name:
#Direct match of the test (just go on with the default loading)
return
if class_name is not None:
if test == class_name + '.' + name:
return
if class_name == test:
return
# If we had a match it'd have returned already.
pytest.skip() # Skip the test
| epl-1.0 |
optsicom-urjc/optsicom-framework | es.optsicom.lib.analysis/src/main/java/es/optsicom/lib/expresults/manager/MultipleExperimentManager.java | 6274 | package es.optsicom.lib.expresults.manager;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import es.optsicom.lib.analyzer.tablecreator.filter.ElementFilter;
import es.optsicom.lib.expresults.model.Execution;
import es.optsicom.lib.expresults.model.Experiment;
import es.optsicom.lib.expresults.model.InstanceDescription;
import es.optsicom.lib.expresults.model.MethodDescription;
import es.optsicom.lib.util.BestMode;
/**
* Creates a new ExperimentManager as fusion of several ExperimentManagers. This
* class is useful when an experiment is run in different machines and ends up
* stored as multiple entries in the experiment table. This class considers all
* the experiments specified as if it was a single experiment. In this sense, it
* is considered that different experiments can contain the same method and
* instances are sum up.
*
* @author Patxi Gortázar
*
*/
public class MultipleExperimentManager implements ExperimentManager {
private ExperimentRepositoryManager manager;
private List<ExperimentManager> expManagers;
private List<MethodDescription> mergedMethods;
private List<InstanceDescription> mergedInstances;
private Map<InstanceDescription, ExperimentManager> instancesMap = new HashMap<InstanceDescription, ExperimentManager>();
private long timeLimit = -1;
private long maxTimeLimit = -1;
public MultipleExperimentManager(ExperimentRepositoryManager manager, List<ExperimentManager> expManagers) {
this.manager = manager;
this.expManagers = expManagers;
mergeMethods();
mergeInstances();
calculateTimeLimits();
}
private void calculateTimeLimits() {
this.timeLimit = getTimeLimit(mergedMethods, mergedInstances);
this.maxTimeLimit = getMaxTimeLimit(mergedMethods, mergedInstances);
}
@Override
public List<MethodDescription> getMethods() {
return mergedMethods;
}
private void mergeMethods() {
this.mergedMethods = new ArrayList<MethodDescription>(expManagers.get(0).getMethods());
for (int i = 1; i < expManagers.size(); i++) {
List<MethodDescription> methods = new ArrayList<MethodDescription>(this.mergedMethods);
methods.addAll(expManagers.get(i).getMethods());
this.mergedMethods.retainAll(expManagers.get(i).getMethods());
methods.removeAll(mergedMethods);
methods.removeAll(expManagers.get(i).getMethods());
System.out.println("The following methods were not included: " + methods);
}
}
@Override
public List<InstanceDescription> getInstances() {
return mergedInstances;
}
private void mergeInstances() {
this.mergedInstances = new ArrayList<InstanceDescription>();
for (ExperimentManager em : expManagers) {
for (InstanceDescription instance : em.getInstances()) {
if (!instancesMap.containsKey(instance)) {
instancesMap.put(instance, em);
this.mergedInstances.add(instance);
}
}
}
}
@Override
public String getExperimentMethodName(MethodDescription method) {
return instancesMap.values().iterator().next().getExperimentMethodName(method);
}
@Override
public List<ExecutionManager> getExecutionManagers(InstanceDescription instance, MethodDescription method) {
if (mergedInstances.contains(instance) && mergedMethods.contains(method)) {
return instancesMap.get(instance).getExecutionManagers(instance, method);
} else {
return null;
}
}
@Override
public BestMode getProblemBestMode() {
return expManagers.get(0).getProblemBestMode();
}
@Override
public long getTimeLimit() {
return timeLimit;
}
@Override
public long getMaxTimeLimit() {
return maxTimeLimit;
}
@Override
public ExperimentManager createFilteredExperimentManager(ElementFilter instanceFilter, ElementFilter methodFilter) {
return new FilteredExperimentManager(manager, this, instanceFilter, methodFilter);
}
@Override
public ExperimentManager createFilteredExperimentManager(ElementFilter instanceFilter, String... methodsByExpName) {
return new FilteredExperimentManager(null, this, instanceFilter, methodsByExpName);
}
@Override
public long getTimeLimit(List<MethodDescription> subsetMethods, List<InstanceDescription> subsetInstances) {
// TODO The timelimit calculation is broken
return 1000;
}
@Override
public long getMaxTimeLimit(List<MethodDescription> subsetMethods, List<InstanceDescription> subsetInstances) {
// TODO The timelimit calculation is broken
return 1000;
}
@Override
public List<Execution> getExecutions(InstanceDescription instance, MethodDescription method) {
return instancesMap.get(instance).getExecutions(instance, method);
}
@Override
public String getName() {
StringBuilder sb = new StringBuilder("MergedExperiment from [");
for (ExperimentManager exp : this.expManagers) {
sb.append(exp.getName()).append(" ");
}
sb.append("]");
return sb.toString();
}
@Override
public Experiment getExperiment() {
Experiment firstExperiment = expManagers.get(0).getExperiment();
Experiment experiment = new Experiment(this.getName(), firstExperiment.getResearcher(), new Date(0),
firstExperiment.getComputer());
experiment.setProblemName(firstExperiment.getProblemName());
experiment.setProblemBestMode(firstExperiment.getProblemBestMode());
experiment.setMethods(getMethods());
experiment.setInstances(getInstances());
experiment.setDescription("Multiple experiments...");
experiment.setMaxTimeLimit(-1);
experiment.setTimeLimit(firstExperiment.getTimeLimit());
experiment.setNumExecs(firstExperiment.getNumExecs());
experiment.setRecordEvolution(firstExperiment.isRecordEvolution());
return experiment;
}
@Override
public List<Execution> createExecutions() {
List<Execution> execs = new ArrayList<Execution>();
for (MethodDescription method : mergedMethods) {
for (InstanceDescription instance : mergedInstances) {
execs.addAll(getExecutions(instance, method));
}
}
return execs;
}
@Override
public Map<MethodDescription, String> createExperimentMethodNames() {
Map<MethodDescription, String> expMethodNames = new HashMap<MethodDescription, String>();
for (MethodDescription method : getMethods()) {
expMethodNames.put(method, getExperimentMethodName(method));
}
return expMethodNames;
}
}
| epl-1.0 |
codeaudit/rlpark | rlpark.plugin.rltoys/jvsrc/rlpark/plugin/rltoys/envio/rl/RLAgent.java | 202 | package rlpark.plugin.rltoys.envio.rl;
import java.io.Serializable;
import rlpark.plugin.rltoys.envio.actions.Action;
public interface RLAgent extends Serializable {
Action getAtp1(TRStep step);
}
| epl-1.0 |
marwensaid/SimpleFunctionalTest | sft-core/src/main/java/sft/result/ScenarioResult.java | 4525 | /*******************************************************************************
* Copyright (c) 2013, 2014 Sylvain Lézier.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sylvain Lézier - initial implementation
*******************************************************************************/
package sft.result;
import sft.FixtureCall;
import sft.Scenario;
import java.util.ArrayList;
import java.util.List;
public class ScenarioResult {
public final Scenario scenario;
public final Throwable failure;
public final Issue issue;
public final ArrayList<FixtureCallResult> fixtureCallResults;
public final List<String> contextToDisplay;
private final ErrorLocation errorLocation;
private ScenarioResult(Scenario scenarioByMethodName, Issue issue, Throwable failure, ErrorLocation errorLocation) {
this.scenario = scenarioByMethodName;
this.contextToDisplay = scenario.useCase.getDisplayedContext();
this.issue = issue;
this.failure = failure;
this.errorLocation = errorLocation;
this.fixtureCallResults = generateFixtureResults();
}
private ScenarioResult(Scenario scenario, Issue issue) {
this(scenario, issue, null, null);
}
public static ScenarioResult failed(Scenario scenario, Throwable throwable) {
return new ScenarioResult(scenario, Issue.FAILED, throwable, ErrorLocation.during);
}
public static ScenarioResult ignored(Scenario scenario) {
return new ScenarioResult(scenario, Issue.IGNORED, null, null);
}
public static ScenarioResult success(Scenario scenario) {
return new ScenarioResult(scenario, Issue.SUCCEEDED);
}
public static ScenarioResult failedBeforeTest(Scenario scenario, Throwable throwable) {
return new ScenarioResult(scenario, Issue.FAILED, throwable, ErrorLocation.before);
}
public static ScenarioResult failedAfterTest(Scenario scenario, Throwable throwable) {
return new ScenarioResult(scenario, Issue.FAILED, throwable, ErrorLocation.after);
}
private ArrayList<FixtureCallResult> generateFixtureResults() {
final ArrayList<FixtureCallResult> fixtureCallResults = new ArrayList<FixtureCallResult>();
for (FixtureCall fixtureCall : scenario.fixtureCalls) {
Issue methodCallIssue = getIssueOf(fixtureCall);
fixtureCallResults.add(new FixtureCallResult(fixtureCall, methodCallIssue));
}
return fixtureCallResults;
}
private Issue getIssueOf(FixtureCall fixtureCall) {
Issue methodIssue = resolveIssueWithUseCaseIssue();
if (methodIssue != null) {
return methodIssue;
}
methodIssue = resolveIssueWithErrorLocation();
if (methodIssue != null) {
return methodIssue;
}
return resolveIssueWithLineError(fixtureCall);
}
private Issue resolveIssueWithErrorLocation() {
switch (errorLocation) {
case before:
return Issue.IGNORED;
case after:
return Issue.SUCCEEDED;
default:
case during:
return null;
}
}
private Issue resolveIssueWithUseCaseIssue() {
switch (issue) {
case SUCCEEDED:
return Issue.SUCCEEDED;
case IGNORED:
return Issue.IGNORED;
default:
case FAILED:
return null;
}
}
private Issue resolveIssueWithLineError(FixtureCall fixtureCall) {
if (getFailedLine() > fixtureCall.line) {
return Issue.SUCCEEDED;
} else if (getFailedLine() == fixtureCall.line) {
return Issue.FAILED;
} else {
return Issue.IGNORED;
}
}
public int getFailedLine() {
for (StackTraceElement stackTraceElement : failure.getStackTrace()) {
if (stackTraceElement.getClassName().equals(scenario.useCase.classUnderTest.getName())) {
if (stackTraceElement.getMethodName().equals(scenario.method.getName())) {
return stackTraceElement.getLineNumber();
}
}
}
return -1;
}
private enum ErrorLocation {before, during, after}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.security.social/test/com/ibm/ws/security/social/tai/TAISubjectUtilsTest.java | 109614 | /*******************************************************************************
* Copyright (c) 2016, 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.social.tai;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletResponse;
import org.jmock.Expectations;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.ibm.websphere.security.WebTrustAssociationFailedException;
import com.ibm.websphere.security.jwt.Claims;
import com.ibm.websphere.security.jwt.JwtToken;
import com.ibm.websphere.security.social.UserProfile;
import com.ibm.ws.security.common.jwk.subject.mapping.AttributeToSubject;
import com.ibm.ws.security.social.SocialLoginConfig;
import com.ibm.ws.security.social.error.SocialLoginException;
import com.ibm.ws.security.social.internal.utils.CacheToken;
import com.ibm.ws.security.social.internal.utils.ClientConstants;
import com.ibm.ws.security.social.internal.utils.SocialHashUtils;
import com.ibm.ws.security.social.tai.TAISubjectUtils.SettingCustomPropertiesException;
import com.ibm.ws.security.social.test.CommonTestClass;
import com.ibm.wsspi.security.tai.TAIResult;
import com.ibm.wsspi.security.token.AttributeNameConstants;
import test.common.SharedOutputManager;
public class TAISubjectUtilsTest extends CommonTestClass {
private static SharedOutputManager outputMgr = SharedOutputManager.getInstance().trace("com.ibm.ws.security.social.*=all");
private static final String USERNAME = "John Q. Doe";
private static String ACCESS_TOKEN = "EAANQIE2J5nMBAErWBIFfkmu9r6yQeGoIMg39mHRJrZA7L0jbiD7GEpLSZBm96tgqvvlbQI3UIgQXSJaO6sRJGaFEZCwn5kolWgSjs5q71rrNg0GdbHk5yxrtsZAWsZBv3XV1xFmJ4reZBKA6sx5PqQJejg5RtTWKPg4jJoP0zk1AZDZD";
private static String REFRESH_TOKEN = "67890";
private static long EXPIRES_IN = 5177064;
// IdToken with claims {"at_hash":"0HbzhW49bhEP2b3SVHfeGg","sub":"user1","realmName":"OpBasicRealm","uniqueSecurityName":"user1","iss":"https://localhost:8020/oidc/endpoint/OP","nonce":"v1zg5OZ9vXP5h0lEiYs1","aud":"rp","exp":1455909058,"iat":1455901858}
private static final String ID_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo4MDIwL29pZGMvZW5kcG9pbnQvT1AiLCJub25jZSI6InYxemc1T1o5dlhQNWgwbEVpWXMxIiwiaWF0IjoxNDU1OTAxODU4LCJzdWIiOiJ1c2VyMSIsImV4cCI6MTQ1NTkwOTA1OCwiYXVkIjoicnAiLCJyZWFsbU5hbWUiOiJPcEJhc2ljUmVhbG0iLCJ1bmlxdWVTZWN1cml0eU5hbWUiOiJ1c2VyMSIsImF0X2hhc2giOiIwSGJ6aFc0OWJoRVAyYjNTVkhmZUdnIn0.VJNknPRe0BhzfMA4MpQIEeVczaHYiMzPiBYejp72zIs";
private final String uniqueId = "facebookLogin";
private final String userApiResponseString = "{\"id\":\"104747623349374\",\"name\":\"Teddy Torres\",\"email\":\"teddyjtorres\\u0040hotmail.com\",\"gender\":\"male\"}";
private final String socialMediaName = "facebookLogin";
private final String userNameAttribute = "sub";
private final String realmName = "facebook";
private final String clientConfigScope = "email user_friends public_profile user_about_me";
public interface MockInterface {
public Hashtable<String, Object> setAllCustomProperties() throws SettingCustomPropertiesException;
public Hashtable<String, Object> setUsernameAndCustomProperties() throws SettingCustomPropertiesException;
Hashtable<String, Object> setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping() throws SettingCustomPropertiesException;
Hashtable<String, Object> setUsernameAndCustomPropertiesUsingJwt() throws SettingCustomPropertiesException;
public Hashtable<String, Object> createCustomPropertiesFromSubjectMapping() throws SettingCustomPropertiesException;
public Hashtable<String, Object> createCustomPropertiesFromConfig() throws SettingCustomPropertiesException;
Subject buildSubject() throws SocialLoginException;
UserProfile createUserProfile() throws SocialLoginException;
Hashtable<String, Object> createCustomProperties() throws SocialLoginException;
CacheToken createCacheToken();
}
final MockInterface mockInterface = mockery.mock(MockInterface.class);
private final JwtToken jwt = mockery.mock(JwtToken.class);
private final JwtToken issuedJwt = mockery.mock(JwtToken.class, "issuedJwt");
private final Claims claims = mockery.mock(Claims.class);
private final AttributeToSubject attributeToSubject = mockery.mock(AttributeToSubject.class);
private final SocialLoginConfig config = mockery.mock(SocialLoginConfig.class, "mockSocialLoginConfig");
private final TAIEncryptionUtils taiEncryptionUtils = mockery.mock(TAIEncryptionUtils.class);
private final TAIWebUtils taiWebUtils = mockery.mock(TAIWebUtils.class);
private final UserProfile userProfile = mockery.mock(UserProfile.class);
@SuppressWarnings("unchecked")
private final Map<String, Object> userApiTokens = mockery.mock(Map.class);
TAISubjectUtils subjectUtils = null;
class MockTAISubjectUtils extends TAISubjectUtils {
public MockTAISubjectUtils(String accessToken, JwtToken jwt, JwtToken issuedJwt, Map<String, Object> userApiResponseTokens, String userApiResponse) {
super(accessToken, jwt, issuedJwt, userApiResponseTokens, userApiResponse);
}
AttributeToSubject createAttributeToSubject(SocialLoginConfig config) {
return attributeToSubject;
}
}
@Rule
public final TestName testName = new TestName();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
outputMgr.captureStreams();
}
@Before
public void setUp() throws Exception {
System.out.println("Entering test: " + testName.getMethodName());
subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
}
@After
public void tearDown() throws Exception {
System.out.println("Exiting test: " + testName.getMethodName());
outputMgr.resetStreams();
mockery.assertIsSatisfied();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
outputMgr.dumpStreams();
outputMgr.restoreStreams();
}
private void mockProtectedClassMembers(TAISubjectUtils subjectUtils) {
subjectUtils.taiWebUtils = taiWebUtils;
subjectUtils.taiEncryptionUtils = taiEncryptionUtils;
}
/****************************************** createResult ******************************************/
@Test
public void createResult_errorSettingCustomProperties() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> setAllCustomProperties(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.setAllCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
int errorCode = HttpServletResponse.SC_UNAUTHORIZED;
final TAIResult unsuccessfulResult = TAIResult.create(errorCode);
mockery.checking(new Expectations() {
{
one(mockInterface).setAllCustomProperties();
will(throwException(new TAISubjectUtils.SettingCustomPropertiesException()));
one(taiWebUtils).sendToErrorPage(with(any(HttpServletResponse.class)), with(any(TAIResult.class)));
will(returnValue(unsuccessfulResult));
}
});
TAIResult result = subjectUtils.createResult(response, config);
assertResultStatus(errorCode, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createResult_buildingSubjectThrowsException() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> setAllCustomProperties(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.setAllCustomProperties();
}
Subject buildSubject(SocialLoginConfig config, Hashtable<String, Object> customProperties) throws SocialLoginException {
return mockInterface.buildSubject();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(mockInterface).setAllCustomProperties();
one(mockInterface).buildSubject();
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
}
});
try {
TAIResult result = subjectUtils.createResult(response, config);
fail("Should have thrown an exception but got result: " + result);
} catch (SocialLoginException e) {
verifyException(e, Pattern.quote(defaultExceptionMsg));
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createResult_success() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> setAllCustomProperties(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.setAllCustomProperties();
}
Subject buildSubject(SocialLoginConfig config, Hashtable<String, Object> customProperties) throws SocialLoginException {
return mockInterface.buildSubject();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(mockInterface).setAllCustomProperties();
one(mockInterface).buildSubject();
}
});
try {
TAIResult result = subjectUtils.createResult(response, config);
fail("Should have thrown an exception because of a missing user principal, but got result: " + result);
} catch (WebTrustAssociationFailedException e) {
// Expected because we've mocked out the calls that would have set the principal name string, so a null principal value is being used
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** setAllCustomProperties ******************************************/
@Test
public void setAllCustomProperties_errorSettingUsernameOrProperties() throws Exception {
final TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> setUsernameAndCustomProperties(SocialLoginConfig clientConfig) throws SettingCustomPropertiesException {
return mockInterface.setUsernameAndCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(mockInterface).setUsernameAndCustomProperties();
will(throwException(new TAISubjectUtils.SettingCustomPropertiesException()));
}
});
try {
Hashtable<String, Object> result = subjectUtils.setAllCustomProperties(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setAllCustomProperties_missingUsername() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> setUsernameAndCustomProperties(SocialLoginConfig clientConfig) throws SettingCustomPropertiesException {
return mockInterface.setUsernameAndCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
// Mock the method to return normally, but also to ensure the username variable isn't set
one(mockInterface).setUsernameAndCustomProperties();
will(returnValue(new Hashtable<String, Object>()));
}
});
try {
Hashtable<String, Object> result = subjectUtils.setAllCustomProperties(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyLogMessage(outputMgr, CWWKS5435E_USERNAME_NOT_FOUND);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setAllCustomProperties_missingAccessToken() throws Exception {
String userApiResponse = "{\"" + userNameAttribute + "\":\"" + USERNAME + "\"}";
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(null, null, null, null, userApiResponse);
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedUser();
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(true));
}
});
try {
Hashtable<String, Object> result = subjectUtils.setAllCustomProperties(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyLogMessageWithInserts(outputMgr, CWWKS5455E_ACCESS_TOKEN_MISSING, USERNAME);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setAllCustomProperties_success() throws Exception {
String userApiResponse = "{\"" + userNameAttribute + "\":\"" + USERNAME + "\"}";
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponse) {
@Override
Hashtable<String, Object> createCustomPropertiesFromSubjectMapping(SocialLoginConfig clientConfig, AttributeToSubject attributeToSubject) throws SettingCustomPropertiesException {
return mockInterface.createCustomPropertiesFromSubjectMapping();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedUser();
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(false));
one(mockInterface).createCustomPropertiesFromSubjectMapping();
will(returnValue(new Hashtable<String, Object>()));
}
});
Hashtable<String, Object> result = subjectUtils.setAllCustomProperties(config);
assertEquals("Result did not contain the expected number of custom properties. Props were: " + result, 2, result.size());
assertEquals("Security name custom property did not match expected value.", USERNAME, result.get(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME));
assertEquals("Access token custom property did not match expected value.", ACCESS_TOKEN, result.get(ClientConstants.ACCESS_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** setUsernameAndCustomProperties ******************************************/
@Test
public void setUsernameAndCustomProperties_nonNullUserApiResponse() throws Exception {
String userApiResponse = "";
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponse) {
Hashtable<String, Object> setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping();
}
};
try {
mockery.checking(new Expectations() {
{
one(mockInterface).setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping();
will(returnValue(new Hashtable<String, Object>()));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomProperties(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomProperties_nullUserApiResponse() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, null, null, null, null) {
Hashtable<String, Object> setUsernameAndCustomPropertiesUsingJwt(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.setUsernameAndCustomPropertiesUsingJwt();
}
};
try {
mockery.checking(new Expectations() {
{
one(mockInterface).setUsernameAndCustomPropertiesUsingJwt();
will(returnValue(new Hashtable<String, Object>()));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomProperties(config);
assertTrue("Properties result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping ******************************************/
@Test
public void setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping_mapToUserRegistry() throws Exception {
String userApiResponse = "";
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponse);
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedUser();
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(true));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping_doNotMapToUserRegistry() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
@Override
Hashtable<String, Object> createCustomPropertiesFromSubjectMapping(SocialLoginConfig clientConfig, AttributeToSubject attributeToSubject) throws SettingCustomPropertiesException {
return mockInterface.createCustomPropertiesFromSubjectMapping();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedUser();
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(false));
one(mockInterface).createCustomPropertiesFromSubjectMapping();
will(returnValue(new Hashtable<String, Object>()));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping_doNotMapToUserRegistry_errorResult() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, null, null, null, userApiResponseString) {
@Override
Hashtable<String, Object> createCustomPropertiesFromSubjectMapping(SocialLoginConfig clientConfig, AttributeToSubject attributeToSubject) throws SettingCustomPropertiesException {
return mockInterface.createCustomPropertiesFromSubjectMapping();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedUser();
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(false));
one(mockInterface).createCustomPropertiesFromSubjectMapping();
will(throwException(new TAISubjectUtils.SettingCustomPropertiesException()));
}
});
try {
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingAttributeToSubjectMapping(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** setUsernameAndCustomPropertiesUsingJwt ******************************************/
@Test
public void setUsernameAndCustomPropertiesUsingJwt_nullJwt() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, null, null, null, null);
try {
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
assertTrue("Properties result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingJwt_validJwt_nullClaims() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(jwt).getClaims();
will(returnValue(null));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingJwt_validJwt_missingUsernameAttributeClaim() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(jwt).getClaims();
will(returnValue(claims));
one(config).getUserNameAttribute();
will(returnValue(userNameAttribute));
one(claims).get(userNameAttribute);
will(returnValue(null));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingJwt_validJwt_mapToUserRegsitry() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(jwt).getClaims();
will(returnValue(claims));
one(config).getUserNameAttribute();
will(returnValue(userNameAttribute));
one(claims).get(userNameAttribute);
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(true));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingJwt_validJwt_doNotMapToUserRegsitry_errorResult() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null) {
@Override
Hashtable<String, Object> createCustomPropertiesFromConfig(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.createCustomPropertiesFromConfig();
}
};
try {
mockery.checking(new Expectations() {
{
one(jwt).getClaims();
will(returnValue(claims));
one(config).getUserNameAttribute();
will(returnValue(userNameAttribute));
one(claims).get(userNameAttribute);
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(false));
one(mockInterface).createCustomPropertiesFromConfig();
will(throwException(new TAISubjectUtils.SettingCustomPropertiesException()));
}
});
try {
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void setUsernameAndCustomPropertiesUsingJwt_validJwt_doNotMapToUserRegsitry_nullResult() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, null, null, null) {
@Override
Hashtable<String, Object> createCustomPropertiesFromConfig(SocialLoginConfig config) throws SettingCustomPropertiesException {
return mockInterface.createCustomPropertiesFromConfig();
}
};
try {
mockery.checking(new Expectations() {
{
one(jwt).getClaims();
will(returnValue(claims));
one(config).getUserNameAttribute();
will(returnValue(userNameAttribute));
one(claims).get(userNameAttribute);
will(returnValue(USERNAME));
one(config).getMapToUserRegistry();
will(returnValue(false));
one(mockInterface).createCustomPropertiesFromConfig();
will(returnValue(new Hashtable<String, Object>()));
}
});
Hashtable<String, Object> result = subjectUtils.setUsernameAndCustomPropertiesUsingJwt(config);
assertTrue("Result should have been empty but was: " + result, result.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** buildSubject ******************************************/
@Test
public void buildSubject_nullJwt_nullIssuedJwt_nullUserProfile() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, null, null, userApiTokens, null) {
@Override
UserProfile createUserProfile(SocialLoginConfig config) throws SocialLoginException {
return mockInterface.createUserProfile();
}
@Override
CacheToken createCacheToken(SocialLoginConfig clientConfig) {
return mockInterface.createCacheToken();
}
};
try {
mockery.checking(new Expectations() {
{
one(mockInterface).createUserProfile();
will(returnValue(null));
one(mockInterface).createCacheToken();
}
});
Subject subject = subjectUtils.buildSubject(config, new Hashtable<String, Object>());
// Subject should have one private cred: An empty Hashtable
Set<Object> privateCreds = subject.getPrivateCredentials();
assertEquals("Did not find the expected number of private credentials: " + privateCreds, 1, privateCreds.size());
Hashtable<String, Object> hashtableCreds = assertHashtablePrivateCredentialExists(subject);
assertTrue("Hashtable credentials should have been empty but were : " + hashtableCreds, hashtableCreds.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void buildSubject_nullUserProfile() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null) {
@Override
UserProfile createUserProfile(SocialLoginConfig config) throws SocialLoginException {
return mockInterface.createUserProfile();
}
@Override
CacheToken createCacheToken(SocialLoginConfig clientConfig) {
return mockInterface.createCacheToken();
}
};
try {
final String compactedIssuedJwt = "compactedIssuedJwt";
mockery.checking(new Expectations() {
{
one(issuedJwt).compact();
will(returnValue(compactedIssuedJwt));
one(mockInterface).createUserProfile();
will(returnValue(null));
one(mockInterface).createCacheToken();
}
});
Hashtable<String, Object> inputProps = new Hashtable<String, Object>();
inputProps.put("prop1", "value1");
inputProps.put("prop2", "value2");
Subject subject = subjectUtils.buildSubject(config, inputProps);
// Subject should have two private creds: A JwtToken, and a Hashtable with an issued JWT entry
Set<Object> privateCreds = subject.getPrivateCredentials();
assertEquals("Did not find the expected number of private credentials: " + privateCreds, 2, privateCreds.size());
assertJwtTokenPrivateCredentialExists(subject, jwt);
Hashtable<String, Object> hashtableCreds = assertHashtablePrivateCredentialExists(subject);
// Hashtable creds should include the issued JWT entry AND the original props that were passed into the method
assertEquals("Did not find the expected number of hashtable credentials: " + hashtableCreds, 3, hashtableCreds.size());
assertIssuedJwtPrivateCredentialExists(hashtableCreds, compactedIssuedJwt);
// Ensure original properties are still in the Hashtable
for (Entry<String, Object> entry : inputProps.entrySet()) {
assertEquals("Hashtable credential for original prop [" + entry.getKey() + "] did not match expected value.", entry.getValue(), hashtableCreds.get(entry.getKey()));
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void buildSubject_exceptionThrownCreatingUserProfile() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null) {
@Override
UserProfile createUserProfile(SocialLoginConfig config) throws SocialLoginException {
return mockInterface.createUserProfile();
}
@Override
CacheToken createCacheToken(SocialLoginConfig clientConfig) {
return mockInterface.createCacheToken();
}
};
try {
mockery.checking(new Expectations() {
{
one(issuedJwt).compact();
one(mockInterface).createUserProfile();
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
}
});
try {
Subject subject = subjectUtils.buildSubject(config, new Hashtable<String, Object>());
fail("Should have thrown an exception but got subject: " + subject);
} catch (SocialLoginException e) {
verifyException(e, Pattern.quote(defaultExceptionMsg));
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void buildSubject_nullJwts() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, null, null, null, null) {
@Override
UserProfile createUserProfile(SocialLoginConfig config) throws SocialLoginException {
return mockInterface.createUserProfile();
}
@Override
CacheToken createCacheToken(SocialLoginConfig clientConfig) {
return mockInterface.createCacheToken();
}
};
try {
mockery.checking(new Expectations() {
{
one(mockInterface).createUserProfile();
will(returnValue(userProfile));
one(userProfile).getEncryptedAccessToken();
one(userProfile).getAccessTokenAlias();
one(mockInterface).createCacheToken();
}
});
Subject subject = subjectUtils.buildSubject(config, new Hashtable<String, Object>());
// Subject should have two private creds: An empty Hashtable, and a UserProfile
Set<Object> privateCreds = subject.getPrivateCredentials();
assertEquals("Did not find the expected number of private credentials: " + privateCreds, 2, privateCreds.size());
Hashtable<String, Object> hashtableCreds = assertHashtablePrivateCredentialExists(subject);
assertTrue("Hashtable credentials should have been empty but were : " + hashtableCreds, hashtableCreds.isEmpty());
assertUserProfilePrivateCredentialExists(subject, userProfile);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void buildSubject_nonNullEncryptedAccessToken_nonNullAccessTokenAlias() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, null, null) {
@Override
UserProfile createUserProfile(SocialLoginConfig config) throws SocialLoginException {
return mockInterface.createUserProfile();
}
@Override
CacheToken createCacheToken(SocialLoginConfig clientConfig) {
return mockInterface.createCacheToken();
}
};
try {
final String compactedIssuedJwt = "compactedIssuedJwt";
mockery.checking(new Expectations() {
{
one(issuedJwt).compact();
will(returnValue(compactedIssuedJwt));
one(mockInterface).createUserProfile();
will(returnValue(userProfile));
one(userProfile).getEncryptedAccessToken();
will(returnValue("encryptedAccessToken"));
one(userProfile).getAccessTokenAlias();
will(returnValue("accessTokenAlias"));
one(mockInterface).createCacheToken();
}
});
Subject subject = subjectUtils.buildSubject(config, new Hashtable<String, Object>());
// Subject should have three private creds: A JwtToken, A Hashtable with an issued JWT entry, and a UserProfile
Set<Object> privateCreds = subject.getPrivateCredentials();
assertEquals("Did not find the expected number of private credentials: " + privateCreds, 3, privateCreds.size());
assertJwtTokenPrivateCredentialExists(subject, jwt);
Hashtable<String, Object> hashtableCreds = assertHashtablePrivateCredentialExists(subject);
assertEquals("Did not find the expected number of hashtable credentials: " + hashtableCreds, 1, hashtableCreds.size());
assertIssuedJwtPrivateCredentialExists(hashtableCreds, compactedIssuedJwt);
assertUserProfilePrivateCredentialExists(subject, userProfile);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** createCustomPropertiesFromSubjectMapping ******************************************/
@Test
public void createCustomPropertiesFromSubjectMapping_nullRealm() throws Exception {
try {
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedRealm();
will(returnValue(null));
one(config).getUserApiType();
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(null));
one(config).getUserApi();
will(returnValue(null));
}
});
try {
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromSubjectMapping(config, attributeToSubject);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyLogMessage(outputMgr, CWWKS5436E_REALM_NOT_FOUND);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomPropertiesFromSubjectMapping_nullUniqueUser_noGroups() throws Exception {
try {
final String uniqueUser = null;
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedRealm();
will(returnValue(realmName));
one(attributeToSubject).getMappedUniqueUser();
will(returnValue(uniqueUser));
one(attributeToSubject).getMappedGroups();
}
});
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromSubjectMapping(null, attributeToSubject);
assertEquals("Did not find the expected number of custom properties. Props were: " + result, 2, result.size());
String expectedUniqueId = "user:" + realmName + "/" + uniqueUser;
assertEquals("Unique ID custom property did not match expected value.", expectedUniqueId, result.get(AttributeNameConstants.WSCREDENTIAL_UNIQUEID));
assertEquals("Realm custom property did not match expected value.", realmName, result.get(AttributeNameConstants.WSCREDENTIAL_REALM));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@SuppressWarnings("unchecked")
@Test
public void createCustomPropertiesFromSubjectMapping_withGroups() throws Exception {
try {
final String uniqueUser = " a / user ";
final List<String> groups = new ArrayList<String>();
groups.add("group1");
groups.add("my 2nd \n\t group");
mockery.checking(new Expectations() {
{
one(attributeToSubject).getMappedRealm();
will(returnValue(realmName));
one(attributeToSubject).getMappedUniqueUser();
will(returnValue(uniqueUser));
one(attributeToSubject).getMappedGroups();
will(returnValue(groups));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromSubjectMapping(config, attributeToSubject);
assertEquals("Did not find the expected number of custom properties. Props were: " + result, 3, result.size());
String expectedUniqueId = "user:" + realmName + "/" + uniqueUser;
assertEquals("Unique ID custom property did not match expected value.", expectedUniqueId, result.get(AttributeNameConstants.WSCREDENTIAL_UNIQUEID));
assertEquals("Realm custom property did not match expected value.", realmName, result.get(AttributeNameConstants.WSCREDENTIAL_REALM));
List<String> groupsProp = (List<String>) result.get(AttributeNameConstants.WSCREDENTIAL_GROUPS);
assertNotNull("Groups entry should not have been null but was. Props were: " + result, groupsProp);
for (String groupName : groups) {
String expectedGroupId = "group:" + realmName + "/" + groupName;
assertTrue("Groups property did not contain expected entry for [" + expectedGroupId + "]. Groups were: " + groupsProp, groupsProp.contains(expectedGroupId));
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** createCustomPropertiesFromConfig ******************************************/
@Test
public void createCustomPropertiesFromConfig_nullRealm() throws Exception {
try {
mockery.checking(new Expectations() {
{
one(config).getRealmName();
will(returnValue(null));
one(config).getUserApiType();
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(null));
one(config).getUserApi();
will(returnValue(null));
}
});
try {
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromConfig(config);
fail("Should have thrown an exception but got custom properties: " + result);
} catch (SettingCustomPropertiesException e) {
// No need to check anything
}
verifyLogMessage(outputMgr, CWWKS5436E_REALM_NOT_FOUND);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomPropertiesFromConfig_emptyRealmNullUsername() throws Exception {
try {
// Username member variable is set by another method so will only be null here
final String username = null;
final String realm = "";
mockery.checking(new Expectations() {
{
one(config).getRealmName();
will(returnValue(realm));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromConfig(config);
assertEquals("Did not find the expected number of custom properties. Props were: " + result, 2, result.size());
String expectedUniqueId = "user:" + realm + "/" + username;
assertEquals("Unique ID custom property did not match expected value.", expectedUniqueId, result.get(AttributeNameConstants.WSCREDENTIAL_UNIQUEID));
assertEquals("Realm custom property did not match expected value.", realm, result.get(AttributeNameConstants.WSCREDENTIAL_REALM));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomPropertiesFromConfig() throws Exception {
try {
// Username member variable is set by another method so will only be null here
final String username = null;
final String realm = "http://my unique realm| name. value";
mockery.checking(new Expectations() {
{
one(config).getRealmName();
will(returnValue(realm));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomPropertiesFromConfig(config);
assertEquals("Did not find the expected number of custom properties. Props were: " + result, 2, result.size());
String expectedUniqueId = "user:" + realm + "/" + username;
assertEquals("Unique ID custom property did not match expected value.", expectedUniqueId, result.get(AttributeNameConstants.WSCREDENTIAL_UNIQUEID));
assertEquals("Realm custom property did not match expected value.", realm, result.get(AttributeNameConstants.WSCREDENTIAL_REALM));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** constructDefaultRealmFromConfig ******************************************/
@Test
public void constructDefaultRealmFromConfig_errorGettingAuthorizationEndpoint() throws Exception {
try {
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
one(config).getUserApi();
will(returnValue(null));
}
});
try {
String result = subjectUtils.constructDefaultRealmFromConfig(config);
fail("Should have thrown an exception but got: [" + result + "].");
} catch (SettingCustomPropertiesException e) {
// Do nothing - this is expected
}
verifyLogMessage(outputMgr, Pattern.quote(defaultExceptionMsg));
verifyLogMessage(outputMgr, CWWKS5436E_REALM_NOT_FOUND);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_errorGettingAuthorizationEndpoint_useUserapi() throws Exception {
try {
final String userApi = "http://myuser-domain.com:80";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
one(config).getUserApi();
will(returnValue(userApi));
}
});
try {
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("Non-HTTPS, authorization endpoint is not valid, get realm from user api endpoint.", userApi, result);
} catch (SettingCustomPropertiesException e) {
// Do nothing - this is expected
}
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_authzEndpointNotHttps_noPath() throws Exception {
try {
final String authzEndpoint = "http://my-domain.com:80";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(authzEndpoint));
}
});
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("Non-HTTPS authorization endpoint should still have returned host and port as the realm.", authzEndpoint, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_authzEndpointNotHttps_withPath() throws Exception {
try {
final String host = "http://my-domain.com:80";
final String authzEndpoint = host + "/some/path";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(authzEndpoint));
}
});
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("Non-HTTPS authorization endpoint should still have returned host and port as the realm.", host, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_authzEndpointHttps_noPath() throws Exception {
try {
final String authzEndpoint = "https://my-domain.com:80";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(authzEndpoint));
}
});
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("HTTPS authorization endpoint without path component should have returned host and port as the realm.", authzEndpoint, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_authzEndpointHttps_withPath() throws Exception {
try {
final String host = "https://my-domain.com:80";
final String authzEndpoint = host + "/some/path";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(authzEndpoint));
}
});
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("HTTPS authorization endpoint with path component should have returned host and port as the realm.", host, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void constructDefaultRealmFromConfig_authzEndpointHttps_withPathAndQuery() throws Exception {
try {
final String host = "https://my-domain.com:80";
final String authzEndpoint = host + "/some/path?and=stuff";
mockery.checking(new Expectations() {
{
one(taiWebUtils).getAuthorizationEndpoint(config);
will(returnValue(authzEndpoint));
}
});
String result = subjectUtils.constructDefaultRealmFromConfig(config);
assertEquals("HTTPS authorization endpoint with query string should have returned host and port as the realm.", host, result);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** createUserProfile ******************************************/
@Test
public void createUserProfile_exceptionThrownCreatingProperties() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
Hashtable<String, Object> createCustomProperties(SocialLoginConfig config, boolean getRefreshAndIdTokens) throws SocialLoginException {
return mockInterface.createCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(mockInterface).createCustomProperties();
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
}
});
try {
UserProfile result = subjectUtils.createUserProfile(config);
fail("Should have thrown SocialLoginException for missing access token. Result was: " + result);
} catch (SocialLoginException e) {
verifyException(e, Pattern.quote(defaultExceptionMsg));
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createUserProfile_nullUserApiResponse() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null) {
Hashtable<String, Object> createCustomProperties(SocialLoginConfig config, boolean getRefreshAndIdTokens) throws SocialLoginException {
return mockInterface.createCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
String accessTokenAlias = "accessTokenAlias";
final Hashtable<String, Object> customProperties = new Hashtable<String, Object>();
customProperties.put("access_token", ACCESS_TOKEN);
customProperties.put("refresh_token", REFRESH_TOKEN);
customProperties.put("expires_in", 1234L);
customProperties.put("social_media", socialMediaName);
customProperties.put("scope", clientConfigScope);
customProperties.put("id_token", ID_TOKEN);
customProperties.put("accessTokenAlias", accessTokenAlias);
mockery.checking(new Expectations() {
{
one(mockInterface).createCustomProperties();
will(returnValue(customProperties));
}
});
UserProfile result = subjectUtils.createUserProfile(config);
assertUserProfile(result, ACCESS_TOKEN, REFRESH_TOKEN, jwt, 1234L, socialMediaName, clientConfigScope, accessTokenAlias);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createUserProfile_emptyCustomProperties() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, userApiResponseString) {
Hashtable<String, Object> createCustomProperties(SocialLoginConfig config, boolean getRefreshAndIdTokens) throws SocialLoginException {
return mockInterface.createCustomProperties();
}
};
mockProtectedClassMembers(subjectUtils);
try {
mockery.checking(new Expectations() {
{
one(mockInterface).createCustomProperties();
will(returnValue(new Hashtable<String, Object>()));
}
});
UserProfile result = subjectUtils.createUserProfile(config);
assertUserProfile(result, null, null, null, 0, null, null, null);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** createCustomProperties ******************************************/
@Test
public void createCustomProperties_nullUserApiTokens() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, null, userApiResponseString);
try {
try {
Hashtable<String, Object> result = subjectUtils.createCustomProperties(config, false);
fail("Should have thrown SocialLoginException for missing access token but did not. Result: " + result);
} catch (SocialLoginException e) {
verifyException(e, CWWKS5459E_SOCIAL_LOGIN_RESULT_MISSING_ACCESS_TOKEN);
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomProperties_emptyUserApiTokens() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, new HashMap<String, Object>(), userApiResponseString);
mockProtectedClassMembers(subjectUtils);
try {
try {
Hashtable<String, Object> result = subjectUtils.createCustomProperties(config, false);
fail("Should have thrown SocialLoginException for missing access token but did not. Result: " + result);
} catch (SocialLoginException e) {
verifyException(e, CWWKS5459E_SOCIAL_LOGIN_RESULT_MISSING_ACCESS_TOKEN);
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomProperties_accessTokenOnlyInUserApiTokens_getRefreshAndIdTokens() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(ACCESS_TOKEN, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(config).getScope();
will(returnValue(clientConfigScope));
one(taiEncryptionUtils).getEncryptedAccessToken(with(any(SocialLoginConfig.class)), with(any(String.class)));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomProperties(config, true);
// Expect entries for: access token, config ID, scope, access token alias
assertEquals("Unexpected number of entries in the properties table. Properties were: " + result, 4, result.size());
assertEquals("Access token did not match expected value. Properties were: " + result, ACCESS_TOKEN, result.get(ClientConstants.ACCESS_TOKEN));
assertEquals("Config ID did not match expected value. Properties were: " + result, uniqueId, result.get(ClientConstants.SOCIAL_MEDIA));
assertEquals("Scope did not match expected value. Properties were: " + result, clientConfigScope, result.get(ClientConstants.SCOPE));
String expectedAccessTokenAlias = SocialHashUtils.digest(ACCESS_TOKEN);
assertEquals("Access token alias value did not match expected value. Properties were: " + result, expectedAccessTokenAlias, result.get(ClientConstants.ACCESS_TOKEN_ALIAS));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomProperties_allTokensInUserApiTokens_doNotGetRefreshOrIdToken() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(ACCESS_TOKEN, REFRESH_TOKEN, ID_TOKEN, EXPIRES_IN);
userApiResponseTokens.put(ClientConstants.SCOPE, clientConfigScope);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(taiEncryptionUtils).getEncryptedAccessToken(with(any(SocialLoginConfig.class)), with(any(String.class)));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomProperties(config, false);
// Expect entries for: access token, expires_in, config ID, scope, access token alias
assertEquals("Unexpected number of entries in the properties table. Properties were: " + result, 5, result.size());
assertEquals("Access token did not match expected value. Properties were: " + result, ACCESS_TOKEN, result.get(ClientConstants.ACCESS_TOKEN));
assertEquals("Lifetime value did not match expected value. Properties were: " + result, EXPIRES_IN, result.get(ClientConstants.EXPIRES_IN));
assertEquals("Config ID did not match expected value. Properties were: " + result, uniqueId, result.get(ClientConstants.SOCIAL_MEDIA));
assertEquals("Scope did not match expected value. Properties were: " + result, clientConfigScope, result.get(ClientConstants.SCOPE));
String expectedAccessTokenAlias = SocialHashUtils.digest(ACCESS_TOKEN);
assertEquals("Access token alias value did not match expected value. Properties were: " + result, expectedAccessTokenAlias, result.get(ClientConstants.ACCESS_TOKEN_ALIAS));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCustomProperties_allTokens() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(ACCESS_TOKEN, REFRESH_TOKEN, ID_TOKEN, EXPIRES_IN);
userApiResponseTokens.put(ClientConstants.SCOPE, clientConfigScope);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(taiEncryptionUtils).getEncryptedAccessToken(with(any(SocialLoginConfig.class)), with(any(String.class)));
}
});
Hashtable<String, Object> result = subjectUtils.createCustomProperties(config, true);
// Expect entries for: access token, refresh token, ID token, expires_in, config ID, scope, access token alias
assertEquals("Unexpected number of entries in the properties table. Properties were: " + result, 7, result.size());
assertEquals("Access token did not match expected value. Properties were: " + result, ACCESS_TOKEN, result.get(ClientConstants.ACCESS_TOKEN));
assertEquals("Refresh token did not match expected value. Properties were: " + result, REFRESH_TOKEN, result.get(ClientConstants.REFRESH_TOKEN));
assertEquals("ID token did not match expected value. Properties were: " + result, ID_TOKEN, result.get(ClientConstants.ID_TOKEN));
assertEquals("Lifetime value did not match expected value. Properties were: " + result, EXPIRES_IN, result.get(ClientConstants.EXPIRES_IN));
assertEquals("Config ID did not match expected value. Properties were: " + result, uniqueId, result.get(ClientConstants.SOCIAL_MEDIA));
assertEquals("Scope did not match expected value. Properties were: " + result, clientConfigScope, result.get(ClientConstants.SCOPE));
String expectedAccessTokenAlias = SocialHashUtils.digest(ACCESS_TOKEN);
assertEquals("Access token alias value did not match expected value. Properties were: " + result, expectedAccessTokenAlias, result.get(ClientConstants.ACCESS_TOKEN_ALIAS));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** getAccessTokenAndAddCustomProp ******************************************/
@Test
public void getAccessTokenAndAddCustomProp_missingAccessToken() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
try {
String accessToken = subjectUtils.getAccessTokenAndAddCustomProp(props);
fail("Should have thrown SocialLoginException, but got access token: [" + accessToken + "].");
} catch (SocialLoginException e) {
verifyException(e, CWWKS5459E_SOCIAL_LOGIN_RESULT_MISSING_ACCESS_TOKEN);
}
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void getAccessTokenAndAddCustomProp_emptyAccessToken() throws Exception {
try {
String inputAccessToken = "";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(inputAccessToken, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
String accessToken = subjectUtils.getAccessTokenAndAddCustomProp(props);
assertEquals("Returned access token should match the original (empty) token.", inputAccessToken, accessToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void getAccessTokenAndAddCustomProp_nonEmptyAccessToken() throws Exception {
try {
String inputAccessToken = " \t" + ACCESS_TOKEN + " \t";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(inputAccessToken, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
String accessToken = subjectUtils.getAccessTokenAndAddCustomProp(props);
assertEquals("Returned access token should match the original token.", inputAccessToken, accessToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addRefreshTokenCustomProp ******************************************/
@Test
public void addRefreshTokenCustomProp_missingRefreshToken() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addRefreshTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addRefreshTokenCustomProp_emptyRefreshToken() throws Exception {
try {
String inputRefreshToken = "";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, inputRefreshToken, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addRefreshTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addRefreshTokenCustomProp_whitespaceRefreshToken() throws Exception {
try {
String inputRefreshToken = " \n\r \t ";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, inputRefreshToken, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addRefreshTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addRefreshTokenCustomProp_nonEmptyRefreshToken() throws Exception {
try {
String inputRefreshToken = "myRefreshToken";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, inputRefreshToken, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addRefreshTokenCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Refresh token entry did not match original value.", inputRefreshToken, props.get(ClientConstants.REFRESH_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addRefreshTokenCustomProp_nonEmptyRefreshTokenWithWhitespace() throws Exception {
try {
String inputRefreshToken = "\t my Refresh\n\rToken ";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, inputRefreshToken, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addRefreshTokenCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Refresh token entry did not match original value.", inputRefreshToken, props.get(ClientConstants.REFRESH_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addIdTokenCustomProp ******************************************/
@Test
public void addIdTokenCustomProp_missingIdToken() throws Exception {
try {
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, null, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addIdTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addIdTokenCustomProp_emptyIdToken() throws Exception {
try {
String inputIdToken = "";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, inputIdToken, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addIdTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addIdTokenCustomProp_whitespaceIdToken() throws Exception {
try {
String inputIdToken = " \n\r \t ";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, inputIdToken, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addIdTokenCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addIdTokenCustomProp_nonEmptyIdToken() throws Exception {
try {
String inputIdToken = "myIdToken";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, inputIdToken, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addIdTokenCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("ID token entry did not match original value.", inputIdToken, props.get(ClientConstants.ID_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addIdTokenCustomProp_nonEmptyIdTokenWithWhitespace() throws Exception {
try {
String inputIdToken = "\t my Id\n\rToken ";
Map<String, Object> userApiResponseTokens = createUserApiTokenMap(null, null, inputIdToken, null);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addIdTokenCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("ID token entry did not match original value.", inputIdToken, props.get(ClientConstants.ID_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addAccessTokenLifetimeCustomProp ******************************************/
@Test
public void addAccessTokenLifetimeCustomProp_missingLifetime() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addAccessTokenLifetimeCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
// TODO - Is this a valid test?
//@Test
public void addAccessTokenLifetimeCustomProp_lifetimeEntryIsString() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.EXPIRES_IN, "123");
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addAccessTokenLifetimeCustomProp(props);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addAccessTokenLifetimeCustomProp_negativeLifetime() throws Exception {
try {
long inputExpiresIn = -123L;
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.EXPIRES_IN, inputExpiresIn);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addAccessTokenLifetimeCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Expires in entry did not match original value.", inputExpiresIn, props.get(ClientConstants.EXPIRES_IN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addAccessTokenLifetimeCustomProp_largeLifetime() throws Exception {
try {
long inputExpiresIn = 1234567890123456789L;
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.EXPIRES_IN, inputExpiresIn);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addAccessTokenLifetimeCustomProp(props);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Expires in entry did not match original value.", inputExpiresIn, props.get(ClientConstants.EXPIRES_IN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addSocialMediaNameCustomProp ******************************************/
@Test
public void addSocialMediaNameCustomProp_emptyName() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String configId = "";
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(configId));
}
});
subjectUtils.addSocialMediaNameCustomProp(props, config);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addSocialMediaNameCustomProp_whitespaceName() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String configId = "\n \r\t ";
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(configId));
}
});
subjectUtils.addSocialMediaNameCustomProp(props, config);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addSocialMediaNameCustomProp_nonEmptyName() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String configId = " my\t config ID\r\t ";
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(configId));
}
});
subjectUtils.addSocialMediaNameCustomProp(props, config);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Social media name entry did not match original value.", configId, props.get(ClientConstants.SOCIAL_MEDIA));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addScopeCustomProp ******************************************/
@Test
public void addScopeCustomProp_tokensIncludeScope_empty() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.SCOPE, "");
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
final String configScope = clientConfigScope;
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(configScope));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Scope entry did not match original value.", configScope, props.get(ClientConstants.SCOPE));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensIncludeScope_whitespace() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.SCOPE, "\n \r \t");
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
final String configScope = clientConfigScope;
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(configScope));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Scope entry did not match original value.", configScope, props.get(ClientConstants.SCOPE));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensIncludeScope_nonEmpty() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
userApiResponseTokens.put(ClientConstants.SCOPE, clientConfigScope);
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Scope entry did not match original value.", clientConfigScope, props.get(ClientConstants.SCOPE));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensMissingScope_configMissingScope() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(null));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensMissingScope_configEmptyScope() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
final String configScope = "";
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(configScope));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensMissingScope_configWhitespaceScope() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
final String configScope = " \n\r";
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(configScope));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addScopeCustomProp_tokensMissingScope_configNonEmptyScope() throws Exception {
try {
Map<String, Object> userApiResponseTokens = new HashMap<String, Object>();
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiResponseTokens, userApiResponseString);
mockProtectedClassMembers(subjectUtils);
final String configScope = "My config\t scope ";
mockery.checking(new Expectations() {
{
one(config).getScope();
will(returnValue(configScope));
}
});
Hashtable<String, Object> props = new Hashtable<String, Object>();
subjectUtils.addScopeCustomProp(props, config);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Scope entry did not match original value.", configScope, props.get(ClientConstants.SCOPE));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addEncryptedAccessTokenCustomProp ******************************************/
@Test
public void addEncryptedAccessTokenCustomProp_errorGettingToken() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
mockery.checking(new Expectations() {
{
one(taiEncryptionUtils).getEncryptedAccessToken(config, ACCESS_TOKEN);
will(throwException(new SocialLoginException(defaultExceptionMsg, null, null)));
one(config).getUniqueId();
will(returnValue(uniqueId));
}
});
try {
subjectUtils.addEncryptedAccessTokenCustomProp(props, config, ACCESS_TOKEN);
fail("Should have thrown a SocialLoginException but did not. Properties were set to: " + props);
} catch (SocialLoginException e) {
verifyException(e, CWWKS5438E_ERROR_GETTING_ENCRYPTED_ACCESS_TOKEN);
}
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addEncryptedAccessTokenCustomProp_emptyEncryptedToken() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String encryptedToken = "";
mockery.checking(new Expectations() {
{
one(taiEncryptionUtils).getEncryptedAccessToken(config, ACCESS_TOKEN);
will(returnValue(encryptedToken));
}
});
subjectUtils.addEncryptedAccessTokenCustomProp(props, config, ACCESS_TOKEN);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addEncryptedAccessTokenCustomProp_nonEmptyEncryptedToken() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String encryptedToken = "\nnon-empty \t token";
mockery.checking(new Expectations() {
{
one(taiEncryptionUtils).getEncryptedAccessToken(config, ACCESS_TOKEN);
will(returnValue(encryptedToken));
}
});
subjectUtils.addEncryptedAccessTokenCustomProp(props, config, ACCESS_TOKEN);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertEquals("Encrypted access token entry did not match original value.", encryptedToken, props.get(ClientConstants.ENCRYPTED_TOKEN));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** addAccessTokenAliasCustomProp ******************************************/
@Test
public void addAccessTokenAliasCustomProp_emptyAccessToken() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String accessToken = "";
subjectUtils.addAccessTokenAliasCustomProp(props, accessToken);
assertTrue("Property map should have remained empty but is now: " + props, props.isEmpty());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void addAccessTokenAliasCustomProp_nonEmptyAccessToken() throws Exception {
try {
Hashtable<String, Object> props = new Hashtable<String, Object>();
final String accessToken = "my token";
subjectUtils.addAccessTokenAliasCustomProp(props, accessToken);
assertFalse("Property map should not have remained empty but did.", props.isEmpty());
assertNotNull("Access token alias entry should not have been null but was. Props were: " + props, props.get(ClientConstants.ACCESS_TOKEN_ALIAS));
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** createCacheToken ******************************************/
@Test
public void createCacheToken_missingAccessToken_nullTokensMap() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(null, jwt, issuedJwt, null, null);
try {
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
}
});
CacheToken token = subjectUtils.createCacheToken(config);
String idToken = token.getIdToken();
assertNull("ID token should not have been set but was [" + idToken + "].", idToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCacheToken_nullTokensMap() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, null, null);
try {
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
}
});
CacheToken token = subjectUtils.createCacheToken(config);
String idToken = token.getIdToken();
assertNull("ID token should not have been set but was [" + idToken + "].", idToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCacheToken_missingIdToken() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(userApiTokens).get(ClientConstants.ID_TOKEN);
will(returnValue(null));
}
});
CacheToken token = subjectUtils.createCacheToken(config);
String idToken = token.getIdToken();
assertNull("ID token should not have been set but was [" + idToken + "].", idToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCacheToken_tokensIncludeEmptyIdToken() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(userApiTokens).get(ClientConstants.ID_TOKEN);
will(returnValue(""));
}
});
CacheToken token = subjectUtils.createCacheToken(config);
String idToken = token.getIdToken();
assertNull("ID token should not have been set but was [" + idToken + "].", idToken);
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
@Test
public void createCacheToken_tokensIncludeIdToken() throws Exception {
TAISubjectUtils subjectUtils = new MockTAISubjectUtils(ACCESS_TOKEN, jwt, issuedJwt, userApiTokens, null);
try {
mockery.checking(new Expectations() {
{
one(config).getUniqueId();
will(returnValue(uniqueId));
one(userApiTokens).get(ClientConstants.ID_TOKEN);
will(returnValue(ID_TOKEN));
}
});
CacheToken token = subjectUtils.createCacheToken(config);
assertEquals("ID token did not match expected value.", ID_TOKEN, token.getIdToken());
verifyNoLogMessage(outputMgr, MSG_BASE);
} catch (Throwable t) {
outputMgr.failWithThrowable(testName.getMethodName(), t);
}
}
/****************************************** Helper methods ******************************************/
private Map<String, Object> createUserApiTokenMap(String accessToken, String refreshToken, String idToken, Long expiresIn) {
Map<String, Object> tokens = new HashMap<String, Object>();
if (accessToken != null) {
tokens.put(ClientConstants.ACCESS_TOKEN, accessToken);
}
if (refreshToken != null) {
tokens.put(ClientConstants.REFRESH_TOKEN, refreshToken);
}
if (idToken != null) {
tokens.put(ClientConstants.ID_TOKEN, idToken);
}
if (expiresIn != null) {
tokens.put(ClientConstants.EXPIRES_IN, expiresIn);
}
return tokens;
}
private void assertResultStatus(int expected, TAIResult result) {
assertEquals("Result code did not match expected result.", expected, result.getStatus());
}
private void assertJwtTokenPrivateCredentialExists(Subject subject, JwtToken jwt) {
Set<JwtToken> jwtPrivateCreds = subject.getPrivateCredentials(JwtToken.class);
assertEquals("JWT private credential did not match the expected object.", jwt, jwtPrivateCreds.iterator().next());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Hashtable<String, Object> assertHashtablePrivateCredentialExists(Subject subject) {
Set<Hashtable> hashtablePrivateCreds = subject.getPrivateCredentials(Hashtable.class);
assertEquals("Did not find the expected number of hashtable private credentials: " + hashtablePrivateCreds, 1, hashtablePrivateCreds.size());
return (Hashtable<String, Object>) (hashtablePrivateCreds.iterator().next());
}
private void assertIssuedJwtPrivateCredentialExists(Hashtable<String, Object> hashtableCreds, String expectedIssuedJwt) {
Object issuedJwtCred = hashtableCreds.get(ClientConstants.ISSUED_JWT_TOKEN);
assertEquals("Issued JWT credential did not match expected value.", expectedIssuedJwt, issuedJwtCred);
}
private void assertUserProfilePrivateCredentialExists(Subject subject, UserProfile userProfile) {
Set<UserProfile> userProfilePrivateCreds = subject.getPrivateCredentials(UserProfile.class);
assertEquals("Did not find the expected number of UserProfile private credentials: " + userProfilePrivateCreds, 1, userProfilePrivateCreds.size());
assertEquals("UserProfile private credential did not match expected object.", userProfile, userProfilePrivateCreds.iterator().next());
}
private void assertUserProfile(UserProfile userProfile, String accessToken, String refreshToken, JwtToken idToken, long tokenLifetime, String socialMediaName, String scopes, String accessTokenAlias) {
assertNotNull("A non-null user profile is expected to be created.", userProfile);
assertEquals("The access token in the user profile did not match expected value.", accessToken, userProfile.getAccessToken());
assertEquals("The refresh token in the user profile did not match expected value.", refreshToken, userProfile.getRefreshToken());
assertEquals("The ID token in the user profile did not match expected value.", idToken, userProfile.getIdToken());
assertEquals("The token lifetime in the user profile did not match expected value.", tokenLifetime, userProfile.getAccessTokenLifeTime());
assertEquals("The social media name in the user profile did not match expected value.", socialMediaName, userProfile.getSocialMediaName());
assertEquals("The scopes in the user profile did not match expected value.", scopes, userProfile.getScopes());
assertEquals("The access token alias in the user profile did not match expected value.", accessTokenAlias, userProfile.getAccessTokenAlias());
}
}
| epl-1.0 |
jcryptool/crypto | org.jcryptool.visual.aup/src/org/jcryptool/visual/aup/AndroidUnlockPatternPlugin.java | 859 | // -----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2013, 2021 JCrypTool Team and Contributors
*
* All rights reserved. This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
// -----END DISCLAIMER-----
package org.jcryptool.visual.aup;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The activator class controls the plug-in life cycle
*/
public class AndroidUnlockPatternPlugin extends AbstractUIPlugin {
/** The plug-in ID. */
public static final String PLUGIN_ID = "org.jcryptool.visual.aup"; //$NON-NLS-1$
} | epl-1.0 |