repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
IngbertPalm/project.dike | src/Dike.Core/UI/Inputs/LocalizableComboboxItem.cs | 1523 | namespace Dike.Core.UI.Inputs
{
using System;
/// <summary>
/// Represents a localizable ComboBox item.
/// </summary>
/// <seealso cref="Dike.Core.UI.Inputs.ILocalizableComboboxItem" />
[Serializable]
public class LocalizableComboboxItem
: ILocalizableComboboxItem
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocalizableComboboxItem"/> class.
/// </summary>
public LocalizableComboboxItem()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalizableComboboxItem"/> class.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="displayText">The display text.</param>
public LocalizableComboboxItem(string value, Localization.ILocalizableString displayText)
{
Value = value;
DisplayText = displayText;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the display text.
/// </summary>
/// <value>The display text.</value>
public Localization.ILocalizableString DisplayText
{
get;
set;
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public string Value
{
get;
set;
}
#endregion Properties
}
} | mit |
roganmelo/slush-feathers | templates/base/connection/sequelize.js | 743 | import Sequelize from 'sequelize';
export default function() {
const app = this;
const connectionString = app.get('<%= database %>');
const sequelize = new Sequelize(connectionString, {
dialect: '<%= database %>',
logging: false,
define: {
freezeTableName: true
}
});
const oldSetup = app.setup;
app.set('sequelizeClient', sequelize);
app.setup = function (...args) {
const result = oldSetup.apply(this, args);
// Set up data relationships
const models = sequelize.models;
Object.keys(models).forEach(name => {
if ('associate' in models[name]) {
models[name].associate(models);
}
});
// Sync to the database
sequelize.sync();
return result;
};
};
| mit |
HackPack/HackUnit | src/Assertion/KeyedContainerAssertion.php | 6159 | <?hh // strict
namespace HackPack\HackUnit\Assertion;
use HackPack\HackUnit\Event\Failure;
use HackPack\HackUnit\Event\FailureEmitter;
use HackPack\HackUnit\Event\FailureListener;
use HackPack\HackUnit\Event\SuccessEmitter;
use HackPack\HackUnit\Event\SuccessListener;
use HackPack\HackUnit\Util\Trace;
use
HackPack\HackUnit\Contract\Assertion\KeyedContainerAssertion as IAssertion
;
class KeyedContainerAssertion<Tkey, Tval> implements IAssertion<Tkey, Tval> {
use FailureEmitter;
use SuccessEmitter;
private bool $negate = false;
private \ConstMap<Tkey, Tval> $context;
public function __construct(
KeyedContainer<Tkey, Tval> $context,
Vector<FailureListener> $failureListeners,
Vector<SuccessListener> $successListeners,
) {
$this->context = new Map($context);
$this->setFailureListeners($failureListeners);
$this->setSuccessListeners($successListeners);
}
public function not(): this {
$this->negate = true;
return $this;
}
public function containsKey(Tkey $expected): void {
if ($this->context->containsKey($expected)) {
if ($this->negate) {
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to not have key '.
var_export($expected, true),
),
);
return;
}
$this->emitSuccess();
return;
}
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to have key '.var_export($expected, true),
),
);
return;
}
public function contains(
Tkey $key,
Tval $val,
?(function(Tkey, Tval, Tval): bool) $comparitor = null,
): void {
if ($comparitor === null) {
$comparitor = self::identityComparitor();
}
if (!$this->context->containsKey($key)) {
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to have key '.var_export($key, true),
),
);
return;
}
if ($comparitor($key, $this->context->at($key), $val)) {
if ($this->negate) {
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to not contain a matching value at key '.
var_export($key, true),
),
);
return;
}
$this->emitSuccess();
return;
}
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to contain a matching value at key '.
var_export($key, true),
),
);
}
public function containsAll(
KeyedContainer<Tkey, Tval> $expected,
?(function(Tkey, Tval, Tval): bool) $comparitor = null,
): void {
if ($comparitor === null) {
$comparitor = self::identityComparitor();
}
$filtered =
(new Map($expected))->filterWithKey(
($k, $v) ==> {
if ($this->context->containsKey($k)) {
return !$comparitor($k, $this->context->at($k), $v);
}
return true;
},
);
if ($filtered->count() === 0) {
if ($this->negate) {
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to not contain all elements of given list.',
),
);
return;
}
$this->emitSuccess();
return;
}
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to contain all elements of given list.',
),
);
}
public function containsOnly(
KeyedContainer<Tkey, Tval> $expected,
?(function(Tkey, Tval, Tval): bool) $comparitor = null,
): void {
$comparitor =
$comparitor === null ? self::identityComparitor() : $comparitor;
$filter = ($a, $b) ==> {
return $a->filterWithKey(
($k, $v) ==> {
if ($b->containsKey($k)) {
return !$comparitor($k, $b->at($k), $v);
}
return true;
},
);
};
$expected = new Map($expected);
$filteredContext = $filter($this->context, $expected);
$filteredExpected = $filter($expected, $this->context);
if ($filteredContext->isEmpty() && $filteredExpected->isEmpty()) {
if ($this->negate) {
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to not contain only the elements of the given list',
),
);
return;
}
$this->emitSuccess();
return;
}
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to contain only the elements of the given list',
),
);
}
public function containsAny(
KeyedContainer<Tkey, Tval> $expected,
?(function(Tkey, Tval, Tval): bool) $comparitor = null,
): void {
if ($comparitor === null) {
$comparitor = self::identityComparitor();
}
foreach ($expected as $expectedKey => $expectedValue) {
if (!$this->context->containsKey($expectedKey)) {
continue;
}
if ($comparitor(
$expectedKey,
$this->context->at($expectedKey),
$expectedValue,
)) {
if ($this->negate) {
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to not contain any elements of the given list.',
),
);
return;
}
$this->emitSuccess();
return;
}
}
if ($this->negate) {
$this->emitSuccess();
return;
}
$this->emitFailure(
Failure::fromCallStack(
'Expected Keyed Container to contain any elements of the given list.',
),
);
}
<<__Memoize>>
private static function identityComparitor(
): (function(Tkey, Tval, Tval): bool) {
return ($key, $a, $b) ==> $a === $b;
}
}
| mit |
cuckata23/wurfl-data | data/mot_mb525_ver1_sub_funnyua.php | 149 | <?php
return array (
'id' => 'mot_mb525_ver1_sub_funnyua',
'fallback' => 'mot_mb525_ver1_sub_android221',
'capabilities' =>
array (
),
);
| mit |
DailyActie/Surrogate-Model | 01-codes/numpy-master/numpy/matrixlib/tests/test_numeric.py | 603 | from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import assert_equal, TestCase, run_module_suite
class TestDot(TestCase):
def test_matscalar(self):
b1 = np.matrix(np.ones((3, 3), dtype=complex))
assert_equal(b1 * 1.0, b1)
def test_diagonal():
b1 = np.matrix([[1, 2], [3, 4]])
diag_b1 = np.matrix([[1, 4]])
array_b1 = np.array([1, 4])
assert_equal(b1.diagonal(), diag_b1)
assert_equal(np.diagonal(b1), array_b1)
assert_equal(np.diag(b1), array_b1)
if __name__ == "__main__":
run_module_suite()
| mit |
smoogipooo/osu | osu.Game/Graphics/UserInterface/ScreenBreadcrumbControl.cs | 1547 | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Screens;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A <see cref="BreadcrumbControl"/> which follows the active screen (and allows navigation) in a <see cref="Screen"/> stack.
/// </summary>
public class ScreenBreadcrumbControl : BreadcrumbControl<Screen>
{
private Screen last;
public ScreenBreadcrumbControl(Screen initialScreen)
{
Current.ValueChanged += newScreen =>
{
if (last != newScreen && !newScreen.IsCurrentScreen)
newScreen.MakeCurrent();
};
onPushed(initialScreen);
}
private void screenChanged(Screen newScreen)
{
if (newScreen == null) return;
if (last != null)
{
last.Exited -= screenChanged;
last.ModePushed -= onPushed;
}
last = newScreen;
newScreen.Exited += screenChanged;
newScreen.ModePushed += onPushed;
Current.Value = newScreen;
}
private void onPushed(Screen screen)
{
Items.ToList().SkipWhile(i => i != Current.Value).Skip(1).ForEach(RemoveItem);
AddItem(screen);
screenChanged(screen);
}
}
}
| mit |
omise/omise-dotnet | Omise/Resources/CustomerSpecificCardResource.cs | 441 | using Omise.Models;
namespace Omise.Resources
{
public class CustomerSpecificCardResource : BaseResource<Card>,
IListable<Card>,
IListRetrievable<Card>,
IUpdatable<Card, UpdateCardRequest>,
IDestroyable<Card>
{
public CustomerSpecificCardResource(IRequester requester, string customerId)
: base(requester, Endpoint.Api, $"/customers/{customerId}/cards")
{
}
}
} | mit |
LuchunPen/FastHashCollection | FastCollection/FastDictionaryM2.cs | 13680 | /*
Copyright (c) Luchunpen (bwolf88). All rights reserved.
Date: 04.03.2016 6:42:37
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Nano3.Collection
{
public class FastDictionaryM2<TKey, TValue> : IDictionary<TKey, TValue>
where TKey : struct, IEquatable<TKey>
{
//private static readonly string stringUID = "CC78FEF1FDAD4302";
protected static readonly int[] primesM2 =
{
4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,
8192, 16384, 32768, 65536, 131072, 262144, 524288,
1048576, 2097152, 4194304, 8388608
};
protected static int GetPrimeM2(int capacity)
{
if (capacity < primesM2[0]) { return primesM2[0]; }
for (int i = 0; i < primesM2.Length; i++) {
if (primesM2[i] >= capacity) { return primesM2[i]; }
}
return primesM2[primesM2.Length - 1];
}
protected int[] _bucket;
protected TKey[] _keys;
protected TValue[] _values;
protected int[] _next;
protected bool[] _fillmarker;
protected int _count;
protected int _freeCount;
protected int _nextFree;
protected int _size;
protected int _mask;
protected DoubleKeyMode _dkMode;
public DoubleKeyMode DKMode { get { return _dkMode; } }
public FastDictionaryM2() : this (4, DoubleKeyMode.KeepExist) { }
public FastDictionaryM2(DoubleKeyMode dkmode) : this(4, dkmode){ }
public FastDictionaryM2(int capacity, DoubleKeyMode dkmode)
{
int cap = GetPrimeM2(capacity);
_size = cap;
_bucket = new int[_size];
_keys = new TKey[_size];
_next = new int[_size];
_values = new TValue[_size];
_fillmarker = new bool[_size];
_count = 1;
_nextFree = 0;
_mask = _size - 1;
_dkMode = dkmode;
}
public virtual TValue this[TKey key]
{
get
{
int itempos = _bucket[(key.GetHashCode() & _mask)];
FINDMATCH:
if (itempos == 0) { throw new ArgumentNullException(); }
if (_keys[itempos].Equals(key)) { return _values[itempos]; }
else
{
itempos = _next[itempos];
goto FINDMATCH;
}
}
set
{
int hash = key.GetHashCode() & _mask;
int itempos = _bucket[hash];
int next = 0;
if (itempos > 0)
{
next = itempos;
for (int i = itempos; i > 0; i = _next[i])
{
if (_keys[i].Equals(key))
{
_values[i] = value;
return;
}
}
}
if (_freeCount > 0)
{
int pos = _bucket[hash] = _nextFree;
_nextFree = _next[_nextFree];
_next[pos] = next; _values[pos] = value; _keys[pos] = key; _fillmarker[pos] = true;
_freeCount--;
}
else
{
_next[_count] = next; _values[_count] = value; _keys[_count] = key; _fillmarker[_count] = true;
_bucket[hash] = _count;
_count = _count + 1;
if (_count >= _size * 0.75f) { Resize(_size * 2); }
}
}
}
public int Count
{
get { return _count - _freeCount - 1; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool ContainsKey(TKey key)
{
int itempos = _bucket[(key.GetHashCode() & _mask)];
FINDMATCH:
if (itempos == 0) { return false; }
if (_keys[itempos].Equals(key)) { return true; }
else
{
itempos = _next[itempos];
goto FINDMATCH;
}
}
public virtual void Add(TKey key, TValue value)
{
int hash = key.GetHashCode() & _mask;
int itempos = _bucket[hash];
int next = 0;
if (itempos > 0)
{
next = itempos;
//check to match ===================
for (int i = itempos; i > 0; i = _next[i])
{
if (_keys[i].Equals(key))
{
if (_dkMode == DoubleKeyMode.Repcale){
_values[i] = value;
}
else if (_dkMode == DoubleKeyMode.ThrowException){
throw new ArgumentException("this key is already exist");
}
return;
}
}
//=========================================
}
if (_freeCount > 0)
{
int pos = _bucket[hash] = _nextFree;
_nextFree = _next[_nextFree];
_next[pos] = next; _values[pos] = value; _keys[pos] = key; _fillmarker[pos] = true;
_freeCount--;
}
else
{
_next[_count] = next; _values[_count] = value; _keys[_count] = key; _fillmarker[_count] = true;
_bucket[hash] = _count;
_count = _count + 1;
if (_count >= _size * 0.75f) { Resize(_size * 2); }
}
}
public void Add(KeyValuePair<TKey, TValue>[] kvs)
{
if (kvs == null || kvs.Length == 0) return;
for (int i = 0; i < kvs.Length; i++)
{
Add(kvs[i].Key, kvs[i].Value);
}
}
public void Add(List<KeyValuePair<TKey, TValue>> kvs)
{
if (kvs == null || kvs.Count == 0) return;
int count = kvs.Count;
for (int i = 0; i < count; i++)
{
Add(kvs[i].Key, kvs[i].Value);
}
}
public bool Remove(TKey key)
{
int hash = key.GetHashCode() & _mask;
int itempos = _bucket[hash];
int prev = 0;
FINDMATCH:
if (itempos == 0) { return false; }
if (_keys[itempos].Equals(key))
{
if (prev == 0) { _bucket[hash] = _next[itempos]; }
else { _next[prev] = _next[itempos]; }
_values[itempos] = default(TValue);
_keys[itempos] = default(TKey);
_next[itempos] = _nextFree;
_fillmarker[itempos] = false;
_nextFree = itempos;
_freeCount++;
return true;
}
else
{
prev = itempos;
itempos = _next[itempos];
goto FINDMATCH;
}
}
public bool TryGetValue(TKey key, out TValue value)
{
int itempos = _bucket[(key.GetHashCode() & _mask)];
FINDMATCH:
if (itempos == 0) { value = default(TValue); return false; }
if (_keys[itempos].Equals(key)) { value = _values[itempos]; return true; }
else
{
itempos = _next[itempos];
goto FINDMATCH;
}
}
public bool TryGetAndRemove(TKey key, out TValue value)
{
int hash = key.GetHashCode() & _mask;
int itempos = _bucket[hash];
int prev = 0;
FINDMATCH:
if (itempos == 0) { value = default(TValue); return false; }
if (_keys[itempos].Equals(key))
{
if (prev == 0) { _bucket[hash] = _next[itempos]; }
else { _next[prev] = _next[itempos]; }
value = _values[itempos];
_values[itempos] = default(TValue);
_keys[itempos] = default(TKey);
_next[itempos] = _nextFree;
_fillmarker[itempos] = false;
_nextFree = itempos;
_freeCount++;
return true;
}
else
{
prev = itempos;
itempos = _next[itempos];
goto FINDMATCH;
}
}
public TValue GetValueOrDefault(TKey key)
{
int itempos = _bucket[(key.GetHashCode() & _mask)];
FINDMATCH:
if (itempos == 0) { return default(TValue); }
if (_keys[itempos].Equals(key)) { return _values[itempos]; }
else
{
itempos = _next[itempos];
goto FINDMATCH;
}
}
public virtual void Clear()
{
if (Count > 0)
{
Array.Clear(_bucket, 0, _bucket.Length);
Array.Clear(_next, 0, _next.Length);
Array.Clear(_keys, 0, _keys.Length);
Array.Clear(_values, 0, _values.Length);
Array.Clear(_fillmarker, 0, _fillmarker.Length);
_count = 1;
_freeCount = 0;
_nextFree = 0;
_mask = _size - 1;
}
}
public TKey[] GetKeys()
{
TKey[] k = new TKey[Count];
int id = 0;
for (int i = 0; i < _count; i++)
{
if (!_fillmarker[i]) continue;
k[id++] = _keys[i];
}
return k;
}
public TValue[] GetValues()
{
TValue[] v = new TValue[Count];
int id = 0;
for (int i = 0; i < _count; i++)
{
if (!_fillmarker[i]) continue;
v[id++] = _values[i];
}
return v;
}
public KeyValuePair<TKey, TValue>[] GetKeyValues()
{
KeyValuePair<TKey, TValue>[] kv = new KeyValuePair<TKey, TValue>[Count];
int id = 0;
for (int i = 0; i < _count; i++)
{
if (!_fillmarker[i]) continue;
kv[id++] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
return kv;
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
int itempos = _bucket[(item.Key.GetHashCode() & _mask)];
FINDMATCH:
if (itempos == 0) { return false; }
if (_keys[itempos].Equals(item.Key))
{
if (_values[itempos].Equals(item)) return true;
return false;
}
else
{
itempos = _next[itempos];
goto FINDMATCH;
}
}
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (Contains(item)) { return Remove(item.Key); }
return false;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if (array == null) { throw new ArgumentNullException("Array is null"); }
if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(); }
if (array.Length - arrayIndex < Count) { throw new ArgumentOutOfRangeException("Destination array is to small"); }
int id = 0;
for (int i = 0; i < _count; i++)
{
if (!_fillmarker[i]) continue;
array[id++] = new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
}
protected void Resize(int nsize)
{
int newSize = nsize;
int newMask = newSize - 1;
int[] newBucket = new int[newSize];
int[] newnext = new int[newSize];
bool[] newfillmarker = new bool[newSize];
Array.Copy(_fillmarker, newfillmarker, _count);
TKey[] newkeys = new TKey[newSize];
Array.Copy(_keys, newkeys, _count);
TValue[] newvalues = new TValue[newSize];
Array.Copy(_values, newvalues, _count);
for (int i = 1; i < _count; i++)
{
int bucket = newkeys[i].GetHashCode() & newMask;
newnext[i] = newBucket[bucket];
newBucket[bucket] = i;
}
_bucket = newBucket;
_next = newnext;
_keys = newkeys;
_values = newvalues;
_fillmarker = newfillmarker;
_size = newSize;
_mask = newMask;
}
public ICollection<TKey> Keys
{
get { return GetKeys(); }
}
public ICollection<TValue> Values
{
get { return GetValues(); }
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
for (int i = 0; i < _count; i++)
{
if (!_fillmarker[i]) continue;
yield return new KeyValuePair<TKey, TValue>(_keys[i], _values[i]);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| mit |
ishisaka/nodeintellisense | nodelib/buffer.js | 24573 | var Buffer = function (args) {
/// <summary>
/// Allocates a new buffer, using subject as a size of octets or using it as an array of octets.
/// </summary>
/// <param name="subject">Number, array, or string.</param>
/// <param name="encoding" optional="true" default="'utf-8'"></param>
/// <param name="offset" optional="true" default="0"></param>
/// <field name="length">
/// The size of the buffer in bytes.
/// Note that this is not necessarily the size of the contents.
/// length refers to the amount of memory allocated for the buffer object.
/// It does not change when the contents of the buffer are changed.
/// </field>
/// <field name="INSPECT_MAX_BYTES">
/// How many bytes will be returned when buffer.inspect() is called. This can be overriden by user modules.
/// </field>
var buf = new Array();
buf.write = function (string, offset, length, encoding) {
/// <summary>
/// Writes string to the buffer at offset using the given encoding.
/// length is the number of bytes to write. Returns number of octets written.
/// If buffer did not contain enough space to fit the entire string, it will write a partial amount of the string.
/// The method will not write partial characters.
/// </summary>
/// <param name="string" type="String">String data.</param>
/// <param name="offset" type="Integer" optional="true" default="0">Offset number.</param>
/// <param name="length" type="Integer" optional="true" default="buffer.length-offset">Length of data to writing buffers.</param>
/// <param name="encoding" type="String" optional="true" default="'utf8'">Encoding option</param>
};
buf.copy = function (targetBuffer, targetStart, sourceStart, sourceEnd) {
/// <summary>
/// Does copy between buffers. The source and target regions can be overlapped.
/// </summary>
/// <param name="targetBuffer"></param>
/// <param name="targetStart" type="Integer" optional="true" default="0"></param>
/// <param name="sourceStart" type="Integer" optional="true" default="0"></param>
/// <param name="sourceEnd" type="Integer" optional="true" default="buffer.length"></param>
};
buf.toString = function(encoding, start, end) {
/// <summary>
/// Decodes and returns a string from buffer data encoded with encoding beginning at start and ending at end.
/// </summary>
/// <param name="encoding" type="String"></param>
/// <param name="start" type="Integer" optional="true" default="0"></param>
/// <param name="end" type="Integer" optional="true" default="buffer.length"></param>
};
buf.slice = function(start, end) {
/// <summary>
/// Returns a new buffer which references the same memory as the old, but offset and cropped by the start and end indexes.
/// Modifying the new buffer slice will modify memory in the original buffer!
/// </summary>
/// <param name="start" type="Integer"></param>
/// <param name="end" type="Integer" optional="true" default="buffer.length"></param>
};
buf.readUInt8 = function (offset, noAssert) {
/// <summary>
/// Reads an unsigned 8 bit integer from the buffer at the specified offset.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readUInt16LE = function (offset, noAssert) {
/// <summary>
/// Reads an unsigned 16 bit integer from the buffer at the specified offset with little endian format.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readUInt16BE = function (offset, noAssert) {
///<summary>
/// Reads an unsigned 16 bit integer from the buffer at the specified offset with big endian format.
/// </summary>
///<param name="offset" type="Integer"></param>
///<param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readUInt32LE = function (offset, noAssert) {
/// <summary>
/// Reads an unsigned 32 bit integer from the buffer at the specified offset with little endian format.
/// </summary>
/// <param name='offset' type='Number' />
/// <param name='noAssert' type='Boolean' optional='true'/>
/// <returns type='Number' />
return new Number();
};
buf.readUInt32BE = function (offset, noAssert) {
/// <summary>
/// Reads an unsigned 32 bit integer from the buffer at the specified offset with big endian format.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">Set `noAssert` to true to skip validation of `offset`. This means that `offset` may be beyond the end of the buffer.</param>
return new Number();
};
buf.readInt8 = function (offset, noAssert) {
/// <summary>
/// Reads a signed 8 bit integer from the buffer at the specified offset.
/// Works as buffer.readUInt8, except buffer contents are treated as two's complement signed values.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readInt16LE = function (offset, noAssert) {
/// <summary>
/// Reads a signed 16 bit integer from the buffer at the specified offset with little endian format.
/// Works as buffer.readUInt16*, except buffer contents are treated as two's complement signed values.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readInt16BE = function (offset, noAssert) {
/// <summary>
/// Reads a signed 16 bit integer from the buffer at the specified offset with big endian format.
/// Works as `buffer.readUInt16*`, except buffer contents are treated as two's complement signed values.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readInt32LE = function (offset, noAssert) {
/// <summary>
/// Reads a signed 32 bit integer from the buffer at the specified offset with little endian format.
/// Works as buffer.readUInt32*, except buffer contents are treated as two's complement signed values.
/// </summary>
/// <param name="offset"></param>
/// <param name="noAssert" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readInt32BE = function (offset, noAssert) {
/// <summary>
/// Reads a signed 32 bit integer from the buffer at the specified offset with big endian format.
/// Works as buffer.readUInt32*, except buffer contents are treated as two's complement signed values.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that offset may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readFloatLE = function (offset, noAssert) {
///<summary>
/// Reads a 32 bit float from the buffer at the specified offset with little endian format.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readFloatBE = function (offset, noAssert) {
/// <summary>
/// Reads a 64 bit double from the buffer at the specified offset with little endian format.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readDoubleLE = function (offset, noAssert) {
/// <summary>
/// Reads a 64 bit double from the buffer at the specified offset with little endian format.
/// </summary>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.readDoubleBE = function (offset, noAssert) {
/// <summary>
/// Reads a 64 bit double from the buffer at the specified offset with big endian format.
/// </summary>
/// <param name="offset" type="Double"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of offset.
/// This means that `offset` may be beyond the end of the buffer.
/// </param>
return new Number();
};
buf.writeUInt8 = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset.
/// Note, value must be a valid unsigned 8 bit integer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeUInt16LE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid unsigned 16 bit integer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeUInt16BE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid unsigned 16 bit integer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function and offset may be beyond
/// the end of the buffer leading to the values being silently dropped. This should not be used
/// unless you are certain of correctness.
/// </param>
};
buf.writeUInt32LE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid unsigned 32 bit integer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that `value` may be too large for the specific function and offset
/// may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeUInt32BE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid unsigned 32 bit integer.
/// </summary>
/// <param name="value"></param>
/// <param name="offset"></param>
/// <param name="noAssert" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function and offset
/// may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeInt8 = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset.
/// Note, value must be a valid signed 8 bit integer.
/// Works as buffer.writeUInt8, except value is written out as a two's complement signed integer into buffer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that `value` may be too large for the specific function and offset
/// may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeInt16LE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid signed 16 bit integer.
/// Works as buffer.writeUInt16*, except value is written out as a two's complement signed integer into buffer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeInt16BE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid signed 16 bit integer.
/// Works as buffer.writeUInt16*, except value is written out as a two's complement signed integer into buffe.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function and offset
/// may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeInt32LE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid signed 32 bit integer. Works as buffer.writeUInt32*,
/// except value is written out as a two's complement signed integer into buffer.
/// </summary>
/// <param name="value" type="Integer32"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function and offset
/// may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeInt32BE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid signed 32 bit integer.
/// Works as buffer.writeUInt32*, except value is written out as a two's complement signed integer into buffer.
/// </summary>
/// <param name="value" type="Integer"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeFloatLE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid 32 bit float.
/// </summary>
/// <param name="value" type="Float"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeFloatBE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid 32 bit float.
/// </summary>
/// <param name="value" type="Float"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function and offset may be beyond
/// the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeDoubleLE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with little endian format.
/// Note, value must be a valid 64 bit double.
/// </summary>
/// <param name="value" type="Double"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.writeDoubleBE = function (value, offset, noAssert) {
/// <summary>
/// Writes value to the buffer at the specified offset with big endian format.
/// Note, value must be a valid 64 bit double.
/// </summary>
/// <param name="value" type="Double"></param>
/// <param name="offset" type="Integer"></param>
/// <param name="noAssert" type="Boolean" optional="true" default="false">
/// Set noAssert to true to skip validation of value and offset.
/// This means that value may be too large for the specific function
/// and offset may be beyond the end of the buffer leading to the values being silently dropped.
/// This should not be used unless you are certain of correctness.
/// </param>
};
buf.fill = function (value, offset, end) {
/// <summary>
/// Fills the buffer with the specified value.
/// If the offset and length are not given it will fill the entire buffer.
/// </summary>
/// <param name="value" type="Object"></param>
/// <param name="offset" type="Integer" optional="true" default="0"></param>
/// <param name="length" type="Integer" optional="true" default="-1"></param>
};
return buf;
};
Buffer.isBuffer = function (obj) {
/// <summary>Tests if `obj` is a `Buffer`.</summary>
/// <param name="obj" type="Object"></param>
/// <returns type="Boolean"></returns>
return new Boolean();
};
Buffer.byteLength = function (string, encoding) {
/// <summary>
/// Gives the actual byte length of a string.
/// This is not the same as String.prototype.length since that returns the number of *characters* in a string.
/// </summary>
/// <param name="string" type="String"></param>
/// <param name="encoding" type="String" optional="true" default="'utf8'"></param>
/// <returns type="Integer"></returns>
return new Number();
};
var INSPECT_MAX_BYTES = new Number(50);
| mit |
igrigorik/vimgolf | spec/models/challenge_spec.rb | 3480 | require 'spec_helper'
describe Challenge do
describe 'Validations' do
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to validate_presence_of(:description) }
it { is_expected.to validate_length_of(:input) }
it { is_expected.to validate_length_of(:output) }
it { is_expected.to validate_length_of(:diff) }
end
describe '#participator?' do
let(:owner) { create(:user) }
let(:challenge) { create(:challenge, user: owner) }
context 'user is the challenge owner' do
it 'return true' do
expect(challenge.participator?(owner)).to be true
end
end
context 'when user has an entry in challenge' do
let(:participant) { create(:user) }
before do
challenge.entries << build(:entry, user: participant)
end
it 'return true' do
expect(challenge.participator?(participant)).to be true
end
end
context 'when user is admin' do
let(:admin) { create(:user, nickname: 'igrigorik') }
it 'return true' do
expect(challenge.participator?(admin)).to be true
end
end
end
describe '#top_entries' do
context 'when user has more than one entry' do
let(:user) { create(:user) }
let(:challenge) { create(:challenge, user: user) }
let(:participant) { create(:user) }
let(:best_entry) { build(:entry, user: participant, score: 1) }
let(:another_entry) { build(:entry, user: user, score: 1) }
before do
challenge.entries << build(:entry, user: participant, score: 10)
challenge.entries << best_entry
challenge.entries << another_entry
end
it 'return most recent entry with best score per user' do
expect(challenge.top_entries).to match_array [another_entry, best_entry]
end
end
end
describe '#allowed_entries' do
let(:user) { create(:user) }
let(:challenge) { create(:challenge, user: user) }
let(:participant) { create(:user) }
let(:another_participant) { create(:user) }
let(:non_competitor) { create(:user) }
let(:best_entry) { build(:entry, user: participant, score: 1) }
let(:another_entry) { build(:entry, user: user, score: 1) }
let(:almost_good_entry) { build(:entry, user: participant, score: 10) }
let(:not_so_good_entry) { build(:entry, user: another_participant, score: 20) }
before do
challenge.entries << almost_good_entry
challenge.entries << best_entry
challenge.entries << another_entry
challenge.entries << not_so_good_entry
end
context 'when user is admin' do
it 'can see all top entries' do
allowed_entries = challenge.allowed_entries(user)
expect(allowed_entries[0]).to match_array [another_entry, best_entry, not_so_good_entry]
expect(allowed_entries[1]).to eq 0
end
end
context 'when user is a competitor' do
it 'can see all entries below her' do
allowed_entries = challenge.allowed_entries(another_participant)
expect(allowed_entries[0]).to match_array [another_entry, best_entry, not_so_good_entry]
expect(allowed_entries[1]).to eq 0
end
end
context 'when user is not a competitor' do
it 'can see all entries bottom 20%' do
allowed_entries = challenge.allowed_entries(non_competitor)
expect(allowed_entries[0]).to match_array [not_so_good_entry]
expect(allowed_entries[1]).to eq 2
end
end
end
end
| mit |
SourceHollandaise/TriggerSol | TriggerSol.JStore/StoreHandlers/Contracts/IDataStoreLoadAllHandler.cs | 1444 | //
// IDataStoreLoadAllHandler.cs
//
// Author:
// Jörg Egger <[email protected]>
//
// Copyright (c) 2015 Jörg Egger
//
// 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.
using System;
using System.Collections.Generic;
namespace TriggerSol.JStore
{
public interface IDataStoreLoadAllHandler : IDataStoreExecutionHandlerBase
{
IEnumerable<IPersistentBase> LoadAllInternal(Type type);
}
}
| mit |
Moumou57/DMC | src/DMC/CrudBundle/Form/LignesDevisType.php | 2198 | <?php
namespace DMC\CrudBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class LignesDevisType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type','choice', array(
'choices' => array(
'Description' => 'Description',
'Article' => 'Article',
),
'choices_as_values' => true,
))
->add('positionmaitre','number')
->add('position','number')
->add('article','text')
->add('libelle','text')
->add('unite','choice', array(
'choices' => array(
'' => '', // <null>
'm' => 'm',
'm²' => 'm2',
'm3' => 'm3',
'to' => 'to', // Tonne(s)
'u' => 'u', // Unité(s)
'h' => 'h', // Heure(s)
),
'choices_as_values' => true,
))
->add('quantite','number')
->add('puHt','number')
->add('totalHt','number')
->add('souligne','checkbox', array('required' => false))
->add('gras','checkbox', array('required' => false))
->add('italique','checkbox', array('required' => false))
->add('affprix','checkbox', array('required' => false))
->add('affqte','checkbox', array('required' => false))
->add('idEntete','number')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DMC\CrudBundle\Entity\LignesDevis'
));
}
/**
* @return string
*/
public function getName()
{
return 'dmc_crudbundle_lignesdevis';
}
}
| mit |
Apprenda/Log4Net-Onboarder | src/Tests/CustomAttributeTestTarget/CustomModuleTarget.cs | 1759 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CustomModuleTarget.cs" company="Apprenda, Inc.">
// The MIT License (MIT)
//
// Copyright (c) 2015 Apprenda Inc.
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CustomAttributeTestTarget
{
using System;
/// <summary>
/// The custom module target.
/// </summary>
[AttributeUsage(AttributeTargets.Module)]
public class CustomModuleTarget : CustomTestAttribute
{
}
} | mit |
MRH4287/HpClass | include/template.php | 2051 | <?php
$right = $hp->getright();
$config = $hp->getconfig();
if ($config['titel'] != "")
{
$titel = $config['titel'];
}
if ($config['design'] != "")
{
$design = $config['design'];
}
// Template
$template['titel']=$titel;
if (isset($_SESSION['username']))
{
$template['username']=$_SESSION['username'];
} else
{
$template['username'] = "NONE";
}
// JS
$template['head']='
<script src="js/jQuery.js"></script>
<script src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.tipTip.js"></script>
<script type="text/javascript" src="js/jquery.filedrop.js"></script>
<script type="text/javascript" src="js/lightboxX2.js"></script>
<script type="text/javascript" src="js/jquery.lightbox-0.5.js"></script>
<script src="js/functions.js"></script>
<script src="js/communicator.js"></script>
<script src="js/drag&drop.js"></script>
<script src="js/widgetconfig.js"></script>
<script type="text/javascript" src="js/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="js/tiny_mce/jquery.tinymce.js"></script>
<script type="text/javascript" src="js/votes.js"></script>
<script src="js/l10n.js"></script>
<script src="js/templateSystem.js"></script>
<script src="js/autorun.js"></script>
<link rel="stylesheet" href="css/lightboxX2.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/tipTip.css" type="text/css"/>
<link rel="stylesheet" href="css/forum.css" type="text/css"/>
<link rel="stylesheet" href="css/widget.css" type="text/css"/>
<link rel="stylesheet" href="include/usedpics/css/usedpics.css" type="text/css" />
<link rel="stylesheet" href="css/news.css" type="text/css"/>
<link rel="stylesheet" href="css/plugins.css" type="text/css"/>
<link rel="stylesheet" href="css/popup_tagestermine.css" type="text/css"/>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css" />
<link rel="stylesheet" href="css/jquery.lightbox-0.5.css" type="text/css" media="screen" />
';
?>
| mit |
GeoNode/geonode-announcements | announcements/admin.py | 1398 | from django.contrib import admin
from announcements.models import Announcement, Dismissal
# import our user model and determine the field we will use to search by user
# support custom user models & username fields in django 1.5+
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
username_search = "user__username"
else:
if hasattr(User, "USERNAME_FIELD"):
username_search = "user__%s" % User.USERNAME_FIELD
else:
username_search = "user__username"
class AnnouncementAdmin(admin.ModelAdmin):
list_display = ("title", "level", "creator", "creation_date", "members_only")
list_filter = ("members_only",)
fieldsets = [
(None, {
"fields": ["title", "level", "content", "site_wide", "members_only", "publish_start", "publish_end", "dismissal_type"],
}),
]
def save_model(self, request, obj, form, change):
if not change:
# When creating a new announcement, set the creator field.
obj.creator = request.user
obj.save()
class DismissalAdmin(admin.ModelAdmin):
list_display = ("user", "announcement", "dismissed_at")
search_fields = (username_search, "announcement__title")
admin.site.register(Announcement, AnnouncementAdmin)
admin.site.register(Dismissal, DismissalAdmin)
| mit |
warpdesign/brackets-regex-diagram | main.js | 8380 | /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */
define(function (require, exports, module) {
"use strict";
// get access to needed singletons
var CommandManager = brackets.getModule("command/CommandManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
Menus = brackets.getModule("command/Menus"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
AppInit = brackets.getModule("utils/AppInit"),
WorkspaceManager = brackets.getModule("view/WorkspaceManager"),
MainViewManager = brackets.getModule("view/MainViewManager");
// files needed by regex-diagram
var railRoad = require('thirdparty/regex-to-railroad'),
panelHtml = require("text!html/panel.html");
// some constants
var SHOW_REGEX_DIAGRAM = "regexdiagram.show", // package-style naming to avoid collisions
EXTENSION_NAME = "regex-diagram";
// the extension
var myExtension = {
init: function() {
console.log('[regex-diagram] init');
var that = this;
this.panel = null;
this.panelElement = null;
this.state = null;
// keep track of each editor we're listening too so that we do not listen twice for the same editor
this.editors = [];
this.active = false;
this.word = '';
AppInit.htmlReady(function () {
ExtensionUtils.loadStyleSheet(module, "stylesheets/regex-railroad-diagram.css");
});
AppInit.appReady(function() {
that.registerCommand();
that.createDomElements();
that.bindEvents();
// get saved prefs
that.getViewState();
that.onStateChange();
if (that.active) {
CommandManager.get(SHOW_REGEX_DIAGRAM).setChecked(true);
} else {
CommandManager.get(SHOW_REGEX_DIAGRAM).setChecked(false);
}
that.onCurrentDocumentChange(null, EditorManager.getFocusedEditor());
});
},
registerCommand: function() {
console.log('[regex-diagram] registerCommand');
// TODO: check preferences, if not there, activate it, and add preference
// if it's here, get pref
CommandManager.register("Show RegExp Diagram", SHOW_REGEX_DIAGRAM, this.onToggleView.bind(this));
},
getViewState: function() {
var stateManager = PreferencesManager.stateManager.getPrefixedSystem(EXTENSION_NAME),
that = this;
stateManager.definePreference('showDiagram', 'boolean', 'true').on('change', this.onStateChange.bind(this));
},
onStateChange: function() {
var stateManager = PreferencesManager.stateManager.getPrefixedSystem(EXTENSION_NAME);
this.active = stateManager.get('showDiagram');
},
createDomElements: function() {
var $panel;
console.log('[regex-diagram] createDomElements');
// Then create a menu item bound to the command
// The label of the menu item is the name we gave the command (see above)
var menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
menu.addMenuDivider();
// We could also add a key binding at the same time:
menu.addMenuItem(SHOW_REGEX_DIAGRAM, "Ctrl-Alt-D");
this.panel = WorkspaceManager.createBottomPanel(SHOW_REGEX_DIAGRAM, $(panelHtml), 200);
$panel = this.panel.$panel;
this.$titleSpan = $panel.find('span.regexp');
this.$titleDiv = $panel.find('.toolbar');
this.$diagramDiv = $panel.find('.regex-diagram');
},
bindEvents: function() {
console.log('[regex-diagram] bindEvents');
MainViewManager.on("currentFileChange", this.onCurrentDocumentChange.bind(this));
},
onToggleView: function() {
console.log('[regex-diagram] onToggleView');
var stateManager = PreferencesManager.stateManager.getPrefixedSystem(EXTENSION_NAME);
this.active = !this.active;
console.log('[regex-diagram] setting showDiagram to', this.active);
stateManager.set('showDiagram', this.active);
stateManager.save();
if (this.active) {
CommandManager.get(SHOW_REGEX_DIAGRAM).setChecked(true);
} else {
CommandManager.get(SHOW_REGEX_DIAGRAM).setChecked(false);
}
console.log('[regex-diagram] showDiagram set to', stateManager.get('showDiagram'));
// call onCursorActivity() to enable & display panel with current regexp if one is found
this.onCursorActivity();
},
onCurrentDocumentChange: function() {
var activeEditor = EditorManager.getActiveEditor();
this.panel.hide();
if (activeEditor && this.editors.indexOf(activeEditor) === -1) {
this.editors.push(activeEditor);
activeEditor.on('cursorActivity', this.onCursorActivity.bind(this));
}
this.onCursorActivity();
},
onCursorActivity: function() {
var editor = EditorManager.getFocusedEditor(),
previousWord = this.word,
titleHeight = 0,
svgHeight = null;
if (!editor || !this.active) {
this.panel.hide();
} else {
// get word under cursor
this.word = this.getCurrentWord(editor);
// do not re-render the same diagram
if (this.word && previousWord !== this.word) {
previousWord = this.word;
this.$diagramDiv.empty();
// generate diagram onto panel
railRoad.Regex2RailRoadDiagram(this.word, this.$diagramDiv[0]);
// change title
this.$titleSpan.html(this.word);
// resize panel: since it's resizable, it shouldn't be automatically resized
// svgHeight = this.$diagramDiv.find('svg').attr('height');
// titleHeight = this.$titleDiv.height();
// this.panel.$panel.height(svgHeight + titleHeight);
this.panel.show();
} else if (!this.word) {
this.panel.hide();
} else {
this.panel.show();
}
}
},
getCurrentWord: function(editor) {
var regex = '';
if (editor) {
if (!editor.hasSelection()) {
// get token under cursor
regex = editor._codeMirror.getTokenAt(editor.getCursorPos());
// regular expressions will be a type 2 string, and always start
// with a forward slash
if (regex && regex.type === "string-2" && /^\//.test(regex.string)) {
regex = regex.string;
} else {
regex = '';
}
}
}
return this.clean(regex);
},
clean: function(text) {
var m;
text = text.replace(/^\s+/, "").replace(/\s+$/, "");
if (text.length === 1 && text === "/") {
return '';
}
m = /^r('''|"""|"|')(.*)\1$/.exec(text);
if (m !== null) {
text = m[2];
}
m = /^\/\/\/(.*)\/\/\/\w*$/.exec(text);
if (m !== null) {
text = m[1].replace(/\s+/, "");
} else {
m = /^\/(.*)\/\w*$/.exec(text);
if (m !== null) {
text = m[1];
}
}
return text;
}
};
myExtension.init();
});
| mit |
kpboyle1/devtreks | src/DevTreks.Models/Properties/AssemblyInfo.cs | 827 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DevTreks.Models")]
[assembly: AssemblyTrademark("")]
// 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("a74b3028-922f-48c6-a54a-07bccd9db165")]
| mit |
anithri/game_master | spec/game_master/config_loader/stages/game_file_loader_spec.rb | 1036 | require 'spec_helper'
describe GameMaster::ConfigLoader::Stages::GameFileLoader do
subject{GameMaster::ConfigLoader::Stages::GameFileLoader}
let(:files){loader.find_game_files(TEST_GAME_DIR)}
let(:game_opts){{}}
let(:loader_opts){{game_dir: TEST_GAME_DIR}}
let(:runtime_opts){{boot:{all_stages: [subject]},stages: []}}
let(:config){GameMaster::Config.new(game_opts,loader_opts,runtime_opts)}
let(:loader){subject.new(config)}
let(:do_load){loader.load}
describe "#find_game_files(parent_dir" do
it{files.map{|f| f.basename.to_s}.should eq ["game_config.yml", "b.yaml", "c.yaml", "d.yml"]}
end
describe "#scan_dirs" do
it{loader.scan_dirs.should eq [TEST_GAME_DIR]}
end
describe "#parent_keys(parent_dir,game_file)" do
it{loader.parent_keys(TEST_GAME_DIR, files[0]).should eq []}
it{loader.parent_keys(TEST_GAME_DIR, files[1]).should eq []}
it{loader.parent_keys(TEST_GAME_DIR, files[2]).should eq [:a]}
it{loader.parent_keys(TEST_GAME_DIR, files[3]).should eq [:a,:foo]}
end
end | mit |
happner/happner-2 | test/integration/component/component-init-start-secure.js | 3788 | module.exports = Explicit;
var expect = require('expect.js');
function Explicit() {}
Explicit.prototype.asyncStart = function($happn, opts, optionalOpts, callback) {
if (typeof callback === 'undefined') callback = optionalOpts;
setTimeout(function() {
callback(null);
}, 200);
};
Explicit.prototype.asyncInit = function($happn, opts, optionalOpts, callback) {
if (typeof callback === 'undefined') callback = optionalOpts;
expect(opts.op).to.be('tions');
var testUser = {
username: 'TEST [email protected]',
password: 'TEST PWD',
custom_data: {
something: 'useful'
}
};
$happn.exchange.security.addUser(testUser).then(function() {
callback(null);
});
};
Explicit.prototype.asyncStartFails = function(callback) {
callback(new Error('erm'));
};
Explicit.prototype.asyncInitFails = function(callback) {
callback(new Error('erm'));
};
Explicit.prototype.methodName1 = function($happn, callback) {
$happn.exchange.security.getUser('TEST [email protected]').then(function(user) {
callback(null, user);
});
};
if (global.TESTING_INIT_START) return; // When 'requiring' the module above,
var mesh;
var Mesh = require('../../..');
describe(
require('../../__fixtures/utils/test_helper')
.create()
.testName(__filename, 3),
function() {
this.timeout(120000);
before(function(done) {
global.TESTING_INIT_START = true; //.............
mesh = this.mesh = new Mesh();
mesh.initialize(
{
happn: {
port: 8001,
secure: true
},
modules: {
expliCit: {
path: __filename
}
},
components: {
explicit: {
accessLevel: 'mesh',
moduleName: 'expliCit',
startMethod: 'asyncStart',
initMethod: 'asyncInit',
schema: {
exclusive: true,
methods: {
asyncInit: {
type: 'async',
parameters: [
{ name: 'opts', required: true, value: { op: 'tions' } },
{ name: 'optionalOpts', required: false },
{ type: 'callback', required: true }
],
callback: {
parameters: [{ type: 'error' }]
}
},
asyncStart: {
type: 'async',
parameters: [
{ name: 'opts', required: true, value: { op: 'tions' } },
{ name: 'optionalOpts', required: false },
{ type: 'callback', required: true }
],
callback: {
parameters: [{ type: 'error' }]
}
},
methodName1: {
// alias: 'm1',
parameters: [{ type: 'callback', required: true }]
}
}
}
}
}
},
function(err) {
if (err) return done(err);
mesh.start(function(err) {
if (err) {
//eslint-disable-next-line
console.log(err.stack);
return done(err);
}
return done();
});
}
);
});
after(function(done) {
delete global.TESTING_INIT_START; //.............
mesh.stop({ reconnect: false }, done);
});
it('validates init method created a user', function(done) {
this.mesh.api.exchange.explicit.methodName1(function(err, user) {
expect(user.username).to.be('TEST [email protected]');
done();
});
});
}
);
| mit |
javierjulio/activeadmin | spec/unit/csv_builder_spec.rb | 8583 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe ActiveAdmin::CSVBuilder do
describe ".default_for_resource using Post" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new(application, :admin) }
let(:resource) { ActiveAdmin::Resource.new(namespace, Post, {}) }
let(:csv_builder) { ActiveAdmin::CSVBuilder.default_for_resource(resource).tap(&:exec_columns) }
it "returns a default csv_builder for Post" do
expect(csv_builder).to be_a(ActiveAdmin::CSVBuilder)
end
it "defines Id as the first column" do
expect(csv_builder.columns.first.name).to eq "Id"
expect(csv_builder.columns.first.data).to eq :id
end
it "has Post's content_columns" do
csv_builder.columns[1..-1].each_with_index do |column, index|
expect(column.name).to eq resource.content_columns[index].to_s.humanize
expect(column.data).to eq resource.content_columns[index]
end
end
context "when column has a localized name" do
let(:localized_name) { "Titulo" }
before do
allow(Post).to receive(:human_attribute_name).and_call_original
allow(Post).to receive(:human_attribute_name).with(:title) { localized_name }
end
it "gets name from I18n" do
title_index = resource.content_columns.index(:title) + 1 # First col is always id
expect(csv_builder.columns[title_index].name).to eq localized_name
end
end
context "for models having sensitive attributes" do
let(:resource) { ActiveAdmin::Resource.new(namespace, User, {}) }
it "omits sensitive fields" do
expect(csv_builder.columns.map(&:data)).to_not include :encrypted_password
end
end
end
context "when empty" do
let(:builder) { ActiveAdmin::CSVBuilder.new.tap(&:exec_columns) }
it "should have no columns" do
expect(builder.columns).to eq []
end
end
context "with a symbol column (:title)" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column :title
end.tap(&:exec_columns)
end
it "should have one column" do
expect(builder.columns.size).to eq 1
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'Title'" do
expect(column.name).to eq "Title"
end
it "should have the data :title" do
expect(column.data).to eq :title
end
end
end
context "with a block and title" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "My title" do
# nothing
end
end.tap(&:exec_columns)
end
it "should have one column" do
expect(builder.columns.size).to eq 1
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'My title'" do
expect(column.name).to eq "My title"
end
it "should have the data :title" do
expect(column.data).to be_an_instance_of(Proc)
end
end
end
context "with a humanize_name column option" do
context "with symbol column name" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column :my_title, humanize_name: false
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
context "with string column name" do
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "my_title", humanize_name: false
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
end
context "with a separator" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(col_sep: ";").tap(&:exec_columns)
end
it "should have proper separator" do
expect(builder.options).to include(col_sep: ";")
end
end
context "with humanize_name option" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(humanize_name: false) do
column :my_title
end.tap(&:exec_columns)
end
describe "the column" do
let(:column) { builder.columns.first }
it "should have humanize_name option set" do
expect(column.options).to eq humanize_name: false
end
it "should have a name of 'my_title'" do
expect(column.name).to eq "my_title"
end
end
end
context "with csv_options" do
let(:builder) do
ActiveAdmin::CSVBuilder.new(force_quotes: true).tap(&:exec_columns)
end
it "should have proper separator" do
expect(builder.options).to include(force_quotes: true)
end
end
context "with access to the controller" do
let(:dummy_view_context) { double(controller: dummy_controller) }
let(:dummy_controller) { double(names: %w(title summary updated_at created_at)) }
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "id"
controller.names.each do |name|
column(name)
end
end.tap { |b| b.exec_columns(dummy_view_context) }
end
it "should build columns provided by the controller" do
expect(builder.columns.map(&:data)).to match_array([:id, :title, :summary, :updated_at, :created_at])
end
end
context "build csv using the supplied order" do
before do
@post1 = Post.create!(title: "Hello1", published_date: Date.today - 2.day)
@post2 = Post.create!(title: "Hello2", published_date: Date.today - 1.day)
end
let(:dummy_controller) do
class DummyController
def find_collection(*)
collection
end
def collection
Post.order("published_date DESC")
end
def apply_decorator(resource)
resource
end
def view_context
end
end
DummyController.new
end
let(:builder) do
ActiveAdmin::CSVBuilder.new do
column "id"
column "title"
column "published_date"
end
end
it "should generate data with the supplied order" do
expect(builder).to receive(:build_row).and_return([]).once.ordered { |post| expect(post.id).to eq @post2.id }
expect(builder).to receive(:build_row).and_return([]).once.ordered { |post| expect(post.id).to eq @post1.id }
builder.build dummy_controller, []
end
it "should generate data ignoring pagination" do
expect(dummy_controller).to receive(:find_collection).
with(except: :pagination).once.
and_call_original
expect(builder).to receive(:build_row).and_return([]).twice
builder.build dummy_controller, []
end
it "should disable the ActiveRecord query cache" do
expect(builder).to receive(:build_row).twice do
expect(ActiveRecord::Base.connection.query_cache_enabled).to be_falsy
[]
end
ActiveRecord::Base.cache do
builder.build dummy_controller, []
end
end
end
context "build csv using specified encoding and encoding_options" do
let(:dummy_controller) do
class DummyController
def find_collection(*)
collection
end
def collection
Post
end
def view_context
end
end
DummyController.new
end
let(:encoding) { Encoding::ASCII }
let(:opts) { {} }
let(:builder) do
ActiveAdmin::CSVBuilder.new(encoding: encoding, encoding_options: opts) do
column "おはようございます"
column "title"
end
end
context "Shift-JIS with options" do
let(:encoding) { Encoding::Shift_JIS }
let(:opts) { { invalid: :replace, undef: :replace, replace: "?" } }
it "encodes the CSV" do
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line.encoding).to eq(encoding)
end
end
context "ASCII with options" do
let(:encoding) { Encoding::ASCII }
let(:opts) do
{ invalid: :replace, undef: :replace, replace: "__REPLACED__" }
end
it "encodes the CSV without errors" do
receiver = []
builder.build dummy_controller, receiver
line = receiver.last
expect(line.encoding).to eq(encoding)
expect(line).to include("__REPLACED__")
end
end
end
end
| mit |
fuyuno/Norma | Source/Norma.Gamma/Models/Profile.cs | 358 | using Newtonsoft.Json;
namespace Norma.Gamma.Models
{
[AppVersion("1.0.46")]
public class Profile
{
[JsonProperty("userId")]
public string UserId { get; set; }
[JsonProperty("createdAt")]
// [JsonConverter(typeof(Newtonsoft.Json.Converters.))]
public /* DateTime */ int CreatedAt { get; set; }
}
} | mit |
Chris911/OpenWeather | lib/OpenWeather/version.rb | 43 | module OpenWeather
VERSION = "0.0.4"
end
| mit |
jcwoltz/mrrapi | examples/list_myrigs.py | 4622 | import json
import urllib2
import mrrapi
mkey = 'YourKey'
msecret = 'YourSecret'
mapi = mrrapi.api(mkey,msecret)
debug = False
#helper function to format floats
def ff(f):
return format(f, '.8f')
#helper function to format floats
def ff12(f):
return format(f, '.12f')
def getBTCValue():
# https://www.bitstamp.net/api/ BTC -> USD
bitstampurl = "https://www.bitstamp.net/api/ticker/"
try:
bsjson = urllib2.urlopen(bitstampurl).read()
dbstamp_params = json.loads(bsjson)
btc_usd = float(dbstamp_params['last'])
except:
print "Unable to retrieve BTC Value"
btc_usd = float(1.1)
return btc_usd
def parsemyrigs(rigs,list_disabled=False):
"""
:param rigs: pass the raw api return from mrrapi.myrigs()
:param list_disabled: Boolean to list the disabled rigs
:return: returns dict by algorithm
"""
global mrrrigs
mrrrigs = {}
# I am not a python programmer, do you know a better way to do this?
# first loop to create algo keys
# second loop populates rigs in algo
for x in myrigs['data']['records']:
mrrrigs.update({str(x['type']): {}})
for x in myrigs['data']['records']:
if debug:
print x
if (list_disabled or str(x['status']) != 'disabled') and not (str(x['name']).__contains__('retired') or str(x['name']).__contains__('test')):
mrrrigs[str(x['type'])][int(x['id'])] = str(x['name'])
if debug:
print mrrrigs
return mrrrigs
def calculateMaxIncomeAlgo(parsedrigs):
global mhash
rentalfee = float(0.03)
outcome = float(0)
mhash = float(0)
namelen = 0
# Pre-process loop to find longest name
for algo in parsedrigs:
algorigs = parsedrigs[algo]
for x in algorigs:
nametmp = len(parsedrigs[algo][x])
if nametmp > namelen:
namelen = nametmp
#print x, algo, namelen
layout = "{0:>" + str(namelen) + "}{1:>10}{2:>10}{3:>17}{4:>15}{5:>14}{6:>14}{7:>14}"
print(layout.format(" Device Name ", " Type ", " Speed ","Cur hash 30m","Price ", "Daily income", "Rented? ","RentID"))
for algo in parsedrigs:
algorigs = parsedrigs[algo]
for x in algorigs:
rig = mapi.rig_detail(x)
t = rig['data']
if debug:
print t
rigstat = "available"
curhash = float(0.0)
rentid = ''
mhashrate = float(t['hashrate']['advertised'])/(1000000.0)
mhash += mhashrate
admhashrate = nicehash(float(t['hashrate']['advertised'])/(1000000.0))
dailyprice = mhashrate * float(t['price']) * (1.0 - rentalfee)
curhash = nicehash(round(float(t['hashrate']['30min'])/10**6,3))
if (str(t['status']) == 'rented'):
aih = float(t['available_in_hours'])
rigstat = "R "
if 0.1 < aih < 10.0:
rigstat += " "
rigstat += str(aih) + " hrs"
rentid = str(t['rentalid'])
elif (str(t['status']) == 'unavailable'):
rigstat = "disabled"
outcome -= dailyprice
print(layout.format(str(t['name']),str(t['type']),str(admhashrate),str(curhash),ff12(float(t['price'])) ,ff(dailyprice), rigstat,rentid))
outcome += dailyprice
return outcome
def nicehash(mhashrate):
mhunit = "MH"
if 1000 <= mhashrate < 1000000:
mhunit = "GH"
mhashrate = round(float(mhashrate/1000),3)
elif mhashrate >= 1000000:
mhunit = "TH"
mhashrate = round(float(mhashrate/1000000),3)
return (str(mhashrate) + " " + mhunit)
if __name__ == '__main__':
myrigs = mapi.myrigs()
if myrigs['success'] is not True:
print "Error getting my rig listings"
if str(myrigs['message']) == 'not authenticated':
print 'Make sure you fill in your key and secret that you get from https://www.miningrigrentals.com/account/apikey'
else:
prigs = parsemyrigs(myrigs,True)
#print prigs
maxi = calculateMaxIncomeAlgo(prigs)
bal = mapi.getbalance()
btcv = getBTCValue()
print
print "Max income/day : %s BTC. USD: %s" % (str(round(maxi,8) - 0.002),str(round(btcv*(maxi -0.002),2)))
print "Current Balance: %s BTC. USD: %s" % (str(bal['data']['confirmed']),str(round(btcv*float(bal['data']['confirmed']),2)))
print "Pending Balance: %s BTC. USD: %s" % (str(bal['data']['unconfirmed']),str(round(btcv*float(bal['data']['unconfirmed']),2)))
| mit |
sturoscy/canvas-app | app/controllers/synced_groups_controller.rb | 1655 | class SyncedGroupsController < ApplicationController
before_filter :get_context, :only => [:index]
def index
if @context
@synced_groups = @context.synced_groups.by_group_id
else
@synced_groups = SyncedGroup.by_group_id
end
respond_to do |format|
format.json { render :json => @synced_groups }
end
end
def show
synced_group = SyncedGroup.find(params[:id])
respond_to do |format|
format.json { render :json => synced_group }
end
end
def new
end
def create
synced_group = SyncedGroup.new(
:group_id => params[:group_id],
:group_name => params[:group_name],
:section_id => params[:section_id],
:section_name => params[:section_name],
:course_id => params[:course_id],
:course_code => params[:course_code],
:skip_sync => false,
:synced_group_category_id => params[:synced_group_category_id]
)
synced_group.save
respond_to do |format|
format.json { render :json => synced_group }
end
end
def update
synced_group = SyncedGroup.find(params[:id])
synced_group.group_id = params[:group_id]
synced_group.group_name = params[:group_name]
synced_group.section_id = params[:section_id]
synced_group.section_name = params[:section_name]
synced_group.touch
synced_group.save
respond_to do |format|
format.json { render :json => synced_group }
end
end
def destroy
synced_group = SyncedGroup.find(params[:id])
synced_group.delete
respond_to do |format|
format.json { render :json => synced_group }
end
end
end
| mit |
JonnyOrman/EzApp | Src/EzApp.Data.Sql.Core/EzSqlOperators.cs | 211 | namespace EzApp.Data.Sql.Core
{
public enum EzSqlOperators
{
SELECT,
INSERT,
UPDATE,
DELETE,
SET,
WHERE,
FROM,
AND,
TOP
}
}
| mit |
Opiumtm/DvachBrowser3 | DvachBrowser3.Core/Serialization/ISerializerCacheService.cs | 505 | using System;
using System.Runtime.Serialization;
namespace DvachBrowser3
{
/// <summary>
/// Сервис кэша сериализаторов.
/// </summary>
public interface ISerializerCacheService
{
/// <summary>
/// Получить сериализатор.
/// </summary>
/// <typeparam name="T">Тип объекта.</typeparam>
/// <returns>Сериализатор.</returns>
IObjectSerializer GetSerializer<T>();
}
} | mit |
DogusTeknoloji/BatMap | BatMap.Tests/Model/ForTest.cs | 1095 | using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace BatMap.Tests.Model {
public class ForTest1 {
[ExcludeFromCodeCoverage]
public Address Address { get; set; }
}
public class ForTest2 {
public string Number { get; set; }
public int Number2 { get; set; }
}
public class ForTest3 {
public City[] Cities { get; set; }
}
public class ForTest4 {
public Dictionary<int, Order> Orders { get; set; }
}
public class ForTest5 {
public Collection<City> Cities { get; set; }
}
public class ForTest6 {
public HashSet<City> Cities { get; set; }
}
public class ForTest7 {
public byte[] Image1 { get; set; }
public List<int> Image2 { get; set; }
public ICollection<byte> Image3 { get; set; }
}
public class ForTest8 {
public ForTest8(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; }
public string Name { get; }
}
}
| mit |
svalyn/svalyn | backend/svalyn-application/src/main/java/com/svalyn/application/dto/input/DeleteProjectsInput.java | 537 | /**************************************************************
* Copyright (c) Stéphane Bégaudeau
*
* This source code is licensed under the MIT license found in
* the LICENSE file in the root directory of this source tree.
**************************************************************/
package com.svalyn.application.dto.input;
import java.util.List;
import java.util.UUID;
public class DeleteProjectsInput {
private List<UUID> projectIds;
public List<UUID> getProjectIds() {
return this.projectIds;
}
}
| mit |
nofdev/fastforward | Godeps/_workspace/src/golang.org/x/crypto/ssh/kex.go | 13864 | // Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/subtle"
"errors"
"io"
"math/big"
"github.com/nofdev/fastforward/Godeps/_workspace/src/golang.org/x/crypto/curve25519"
)
const (
kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
kexAlgoECDH256 = "ecdh-sha2-nistp256"
kexAlgoECDH384 = "ecdh-sha2-nistp384"
kexAlgoECDH521 = "ecdh-sha2-nistp521"
kexAlgoCurve25519SHA256 = "[email protected]"
)
// kexResult captures the outcome of a key exchange.
type kexResult struct {
// Session hash. See also RFC 4253, section 8.
H []byte
// Shared secret. See also RFC 4253, section 8.
K []byte
// Host key as hashed into H.
HostKey []byte
// Signature of H.
Signature []byte
// A cryptographic hash function that matches the security
// level of the key exchange algorithm. It is used for
// calculating H, and for deriving keys from H and K.
Hash crypto.Hash
// The session ID, which is the first H computed. This is used
// to signal data inside transport.
SessionID []byte
}
// handshakeMagics contains data that is always included in the
// session hash.
type handshakeMagics struct {
clientVersion, serverVersion []byte
clientKexInit, serverKexInit []byte
}
func (m *handshakeMagics) write(w io.Writer) {
writeString(w, m.clientVersion)
writeString(w, m.serverVersion)
writeString(w, m.clientKexInit)
writeString(w, m.serverKexInit)
}
// kexAlgorithm abstracts different key exchange algorithms.
type kexAlgorithm interface {
// Server runs server-side key agreement, signing the result
// with a hostkey.
Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error)
// Client runs the client-side key agreement. Caller is
// responsible for verifying the host key signature.
Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
}
// dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
type dhGroup struct {
g, p *big.Int
}
func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
if theirPublic.Sign() <= 0 || theirPublic.Cmp(group.p) >= 0 {
return nil, errors.New("ssh: DH parameter out of bounds")
}
return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
}
func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
hashFunc := crypto.SHA1
x, err := rand.Int(randSource, group.p)
if err != nil {
return nil, err
}
X := new(big.Int).Exp(group.g, x, group.p)
kexDHInit := kexDHInitMsg{
X: X,
}
if err := c.writePacket(Marshal(&kexDHInit)); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var kexDHReply kexDHReplyMsg
if err = Unmarshal(packet, &kexDHReply); err != nil {
return nil, err
}
kInt, err := group.diffieHellman(kexDHReply.Y, x)
if err != nil {
return nil, err
}
h := hashFunc.New()
magics.write(h)
writeString(h, kexDHReply.HostKey)
writeInt(h, X)
writeInt(h, kexDHReply.Y)
K := make([]byte, intLength(kInt))
marshalInt(K, kInt)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: kexDHReply.HostKey,
Signature: kexDHReply.Signature,
Hash: crypto.SHA1,
}, nil
}
func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
hashFunc := crypto.SHA1
packet, err := c.readPacket()
if err != nil {
return
}
var kexDHInit kexDHInitMsg
if err = Unmarshal(packet, &kexDHInit); err != nil {
return
}
y, err := rand.Int(randSource, group.p)
if err != nil {
return
}
Y := new(big.Int).Exp(group.g, y, group.p)
kInt, err := group.diffieHellman(kexDHInit.X, y)
if err != nil {
return nil, err
}
hostKeyBytes := priv.PublicKey().Marshal()
h := hashFunc.New()
magics.write(h)
writeString(h, hostKeyBytes)
writeInt(h, kexDHInit.X)
writeInt(h, Y)
K := make([]byte, intLength(kInt))
marshalInt(K, kInt)
h.Write(K)
H := h.Sum(nil)
// H is already a hash, but the hostkey signing will apply its
// own key-specific hash algorithm.
sig, err := signAndMarshal(priv, randSource, H)
if err != nil {
return nil, err
}
kexDHReply := kexDHReplyMsg{
HostKey: hostKeyBytes,
Y: Y,
Signature: sig,
}
packet = Marshal(&kexDHReply)
err = c.writePacket(packet)
return &kexResult{
H: H,
K: K,
HostKey: hostKeyBytes,
Signature: sig,
Hash: crypto.SHA1,
}, nil
}
// ecdh performs Elliptic Curve Diffie-Hellman key exchange as
// described in RFC 5656, section 4.
type ecdh struct {
curve elliptic.Curve
}
func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
if err != nil {
return nil, err
}
kexInit := kexECDHInitMsg{
ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
}
serialized := Marshal(&kexInit)
if err := c.writePacket(serialized); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var reply kexECDHReplyMsg
if err = Unmarshal(packet, &reply); err != nil {
return nil, err
}
x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
if err != nil {
return nil, err
}
// generate shared secret
secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
h := ecHash(kex.curve).New()
magics.write(h)
writeString(h, reply.HostKey)
writeString(h, kexInit.ClientPubKey)
writeString(h, reply.EphemeralPubKey)
K := make([]byte, intLength(secret))
marshalInt(K, secret)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: reply.HostKey,
Signature: reply.Signature,
Hash: ecHash(kex.curve),
}, nil
}
// unmarshalECKey parses and checks an EC key.
func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
x, y = elliptic.Unmarshal(curve, pubkey)
if x == nil {
return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
}
if !validateECPublicKey(curve, x, y) {
return nil, nil, errors.New("ssh: public key not on curve")
}
return x, y, nil
}
// validateECPublicKey checks that the point is a valid public key for
// the given curve. See [SEC1], 3.2.2
func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
if x.Sign() == 0 && y.Sign() == 0 {
return false
}
if x.Cmp(curve.Params().P) >= 0 {
return false
}
if y.Cmp(curve.Params().P) >= 0 {
return false
}
if !curve.IsOnCurve(x, y) {
return false
}
// We don't check if N * PubKey == 0, since
//
// - the NIST curves have cofactor = 1, so this is implicit.
// (We don't foresee an implementation that supports non NIST
// curves)
//
// - for ephemeral keys, we don't need to worry about small
// subgroup attacks.
return true
}
func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var kexECDHInit kexECDHInitMsg
if err = Unmarshal(packet, &kexECDHInit); err != nil {
return nil, err
}
clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
if err != nil {
return nil, err
}
// We could cache this key across multiple users/multiple
// connection attempts, but the benefit is small. OpenSSH
// generates a new key for each incoming connection.
ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
if err != nil {
return nil, err
}
hostKeyBytes := priv.PublicKey().Marshal()
serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
// generate shared secret
secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
h := ecHash(kex.curve).New()
magics.write(h)
writeString(h, hostKeyBytes)
writeString(h, kexECDHInit.ClientPubKey)
writeString(h, serializedEphKey)
K := make([]byte, intLength(secret))
marshalInt(K, secret)
h.Write(K)
H := h.Sum(nil)
// H is already a hash, but the hostkey signing will apply its
// own key-specific hash algorithm.
sig, err := signAndMarshal(priv, rand, H)
if err != nil {
return nil, err
}
reply := kexECDHReplyMsg{
EphemeralPubKey: serializedEphKey,
HostKey: hostKeyBytes,
Signature: sig,
}
serialized := Marshal(&reply)
if err := c.writePacket(serialized); err != nil {
return nil, err
}
return &kexResult{
H: H,
K: K,
HostKey: reply.HostKey,
Signature: sig,
Hash: ecHash(kex.curve),
}, nil
}
var kexAlgoMap = map[string]kexAlgorithm{}
func init() {
// This is the group called diffie-hellman-group1-sha1 in RFC
// 4253 and Oakley Group 2 in RFC 2409.
p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{
g: new(big.Int).SetInt64(2),
p: p,
}
// This is the group called diffie-hellman-group14-sha1 in RFC
// 4253 and Oakley Group 14 in RFC 3526.
p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{
g: new(big.Int).SetInt64(2),
p: p,
}
kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()}
kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()}
kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()}
kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{}
}
// curve25519sha256 implements the [email protected] key
// agreement protocol, as described in
// https://git.libssh.org/projects/libssh.git/tree/doc/[email protected]
type curve25519sha256 struct{}
type curve25519KeyPair struct {
priv [32]byte
pub [32]byte
}
func (kp *curve25519KeyPair) generate(rand io.Reader) error {
if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
return err
}
curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
return nil
}
// curve25519Zeros is just an array of 32 zero bytes so that we have something
// convenient to compare against in order to reject curve25519 points with the
// wrong order.
var curve25519Zeros [32]byte
func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
var kp curve25519KeyPair
if err := kp.generate(rand); err != nil {
return nil, err
}
if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var reply kexECDHReplyMsg
if err = Unmarshal(packet, &reply); err != nil {
return nil, err
}
if len(reply.EphemeralPubKey) != 32 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
}
var servPub, secret [32]byte
copy(servPub[:], reply.EphemeralPubKey)
curve25519.ScalarMult(&secret, &kp.priv, &servPub)
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
}
h := crypto.SHA256.New()
magics.write(h)
writeString(h, reply.HostKey)
writeString(h, kp.pub[:])
writeString(h, reply.EphemeralPubKey)
kInt := new(big.Int).SetBytes(secret[:])
K := make([]byte, intLength(kInt))
marshalInt(K, kInt)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: reply.HostKey,
Signature: reply.Signature,
Hash: crypto.SHA256,
}, nil
}
func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
packet, err := c.readPacket()
if err != nil {
return
}
var kexInit kexECDHInitMsg
if err = Unmarshal(packet, &kexInit); err != nil {
return
}
if len(kexInit.ClientPubKey) != 32 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
}
var kp curve25519KeyPair
if err := kp.generate(rand); err != nil {
return nil, err
}
var clientPub, secret [32]byte
copy(clientPub[:], kexInit.ClientPubKey)
curve25519.ScalarMult(&secret, &kp.priv, &clientPub)
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
}
hostKeyBytes := priv.PublicKey().Marshal()
h := crypto.SHA256.New()
magics.write(h)
writeString(h, hostKeyBytes)
writeString(h, kexInit.ClientPubKey)
writeString(h, kp.pub[:])
kInt := new(big.Int).SetBytes(secret[:])
K := make([]byte, intLength(kInt))
marshalInt(K, kInt)
h.Write(K)
H := h.Sum(nil)
sig, err := signAndMarshal(priv, rand, H)
if err != nil {
return nil, err
}
reply := kexECDHReplyMsg{
EphemeralPubKey: kp.pub[:],
HostKey: hostKeyBytes,
Signature: sig,
}
if err := c.writePacket(Marshal(&reply)); err != nil {
return nil, err
}
return &kexResult{
H: H,
K: K,
HostKey: hostKeyBytes,
Signature: sig,
Hash: crypto.SHA256,
}, nil
}
| mit |
funkatron/CBTTool | app/config/production.php | 338 | <?php
return array(
"mode" => "production",
"debug" => false,
"log.enabled" => false,
"cookies.encrypt" => true,
"cookies.secure" => true,
"cookies.httponly" => true,
"twig.debug" => false,
"db.type" => "sqlite",
"db.pdo.connect" => "sqlite:{$_ENV['CONFIG_APP_BASE_PATH']}/data/cbttool.sqlite3",
);
| mit |
gersese/inv | application/models/module/Product/Product_model.php | 285 | <?php
class Product_model extends GCA_Model
{
const PRODUCTS_TABLE = 'products';
public function __construct()
{
$this->load->database();
}
public function addProduct($newProduct)
{
$this->db->insert(self::PRODUCTS_TABLE, $newProduct);
}
}
?> | mit |
VadimRomansky/PICpp | RoeOsherSpherical/GridUpdating.cpp | 5485 | #include <time.h>
#include "math.h"
#include "stdio.h"
#include <stdlib.h>
#include "simulation.h"
#include "util.h"
#include "constants.h"
#include "output.h"
//èçìåíåíèå ñåòêè
void Simulation::updateGrid(){
if ((shockWavePoint < 1) || (shockWavePoint > rgridNumber - 1)) return;
if( !shockWaveMoved) {
return;
}
printf("updating grid\n");
double shockWaveR = grid[shockWavePoint];
double rightR = grid[rgridNumber] - shockWaveR;
int indent = 3;
int leftPoints = shockWavePoint - indent - 2;
int rightPonts = rgridNumber - indent - shockWavePoint + 1;
double R1 = grid[shockWavePoint - indent - 1];
double R2 = grid[rgridNumber] - grid[shockWavePoint+3];
double a = 100;
double b = 1000;
double h1 = leftPoints/log(1.0+a);
double h2 = rightPonts/log(1.0+b);
tempGrid[0] = 0;
for(int i = 1; i < shockWavePoint - indent - 1; ++i){
tempGrid[i] = (R1/a)*(1 - exp(-(i-leftPoints)/h1)) + R1;
}
for(int i = shockWavePoint - indent-1; i < shockWavePoint + indent-1; ++i){
tempGrid[i] = grid[i+1];
}
for(int i = shockWavePoint + indent-1; i < rgridNumber; ++i){
tempGrid[i] = (R2/b)*(exp((i+1-shockWavePoint-indent)/h2)-1.0) + grid[shockWavePoint+3];
}
tempGrid[rgridNumber] = grid[rgridNumber];
shockWavePoint -= 1;
for(int i = 1; i <= rgridNumber; ++i){
if(tempGrid[i] < tempGrid[i-1]){
printf("grid[i] < grid[i-1]\n");
}
}
redistributeValues();
}
//ïåðåðàñïðåäåëåíèå âåëè÷èí ìåæäó ÿ÷åéêàìè íîâîé ñåòêè
void Simulation::redistributeValues(){
int oldCount = 1;
double tDensity = 0;
double tMomentum = 0;
double tEnergy = 0;
double** newDistributionFunction = new double*[rgridNumber];
double* tempFunction = new double[pgridNumber];
for(int i = 0; i < rgridNumber; ++i){
newDistributionFunction[i] = new double[pgridNumber];
double newVolume = cube(tempGrid[i+1]) - cube(tempGrid[i]);
bool oldChanged = false;
if(tempGrid[i+1] > grid[oldCount]){
tDensity = middleDensity[oldCount - 1]*(cube(grid[oldCount]) - cube(tempGrid[i]))/(newVolume);
tMomentum = momentum(oldCount - 1)*(cube(grid[oldCount]) - cube(tempGrid[i]))/(newVolume);
tEnergy = energy(oldCount - 1)*(cube(grid[oldCount]) - cube(tempGrid[i]))/(newVolume);
for(int j = 0; j < pgridNumber; j++){
tempFunction[j] = distributionFunction[oldCount-1][j]*(cube(grid[oldCount]) - cube(tempGrid[i]))/(newVolume);
}
++oldCount;
oldChanged = true;
} else {
tDensity = middleDensity[oldCount - 1];
tMomentum = momentum(oldCount - 1);
tEnergy = energy(oldCount - 1);
for(int j = 0; j < pgridNumber; j++){
tempFunction[j] = distributionFunction[oldCount-1][j];
}
}
while(grid[oldCount] < tempGrid[i+1]){
tDensity += middleDensity[oldCount - 1]*volume(oldCount - 1)/(4*pi*newVolume/3);
tMomentum += momentum(oldCount - 1)*volume(oldCount - 1)/(4*pi*newVolume/3);
tEnergy += energy(oldCount - 1)*volume(oldCount - 1)/(4*pi*newVolume/3);
for(int j = 0; j < pgridNumber; j++){
tempFunction[j] = distributionFunction[oldCount-1][j]*volume(oldCount - 1)/(4*pi*newVolume/3);
}
++oldCount;
oldChanged = true;
if(oldCount > rgridNumber + 1){
printf("oldCount > rgridNUmber + 1\n");
}
}
if(oldChanged){
tDensity += middleDensity[oldCount - 1]*(cube(tempGrid[i+1]) - cube(grid[oldCount - 1]))/(newVolume);
tMomentum += momentum(oldCount - 1)*(cube(tempGrid[i+1]) - cube(grid[oldCount - 1]))/(newVolume);
tEnergy += energy(oldCount - 1)*(cube(tempGrid[i+1]) - cube(grid[oldCount - 1]))/(newVolume);
for(int j = 0; j < pgridNumber; j++){
tempFunction[j] = distributionFunction[oldCount-1][j]*(cube(tempGrid[i+1]) - cube(grid[oldCount - 1]))/(newVolume);
}
}
tempDensity[i] = tDensity;
alertNaNOrInfinity(tempDensity[i], "newDensity = NaN");
alertNegative(tempDensity[i], "newDensity < 0");
tempMomentum[i] = tMomentum;
alertNaNOrInfinity(tempMomentum[i], "newMomentum = NaN");
tempEnergy[i] = tEnergy;
alertNaNOrInfinity(tempEnergy[i], "newEnergy = NaN");
alertNegative(tempEnergy[i], "newEnergy < 0");
for(int j = 0; j < pgridNumber; ++j){
newDistributionFunction[i][j] = tempFunction[j];
alertNaNOrInfinity(newDistributionFunction[i][j], "newDistribution = NaN");
alertNegative(newDistributionFunction[i][j], "newDistribution < 0");
}
}
for(int i = 0; i < rgridNumber; ++i){
grid[i + 1] = tempGrid[i + 1];
middleGrid[i] = (grid[i] + grid[i+1])/2;
deltaR[i] = grid[i+1] - grid[i];
if(i == 0){
middleDeltaR[i] = middleGrid[i];
} else {
middleDeltaR[i] = middleGrid[i] - middleGrid[i-1];
}
middleDensity[i] = tempDensity[i];
if(tempDensity[i] <= epsilon*density0){
middleVelocity[i] = 0;
} else {
middleVelocity[i] = tempMomentum[i]/tempDensity[i];
}
double tempPressure = (tempEnergy[i] - middleDensity[i]*middleVelocity[i]*middleVelocity[i]/2)*(_gamma - 1);
if(tempPressure < 0){
middlePressure[i] = 0.01*min2(middlePressure[i+1],middlePressure[i]);
printf("pressure < 0\n");
} else {
middlePressure[i] = tempPressure;
}
alertNegative(middlePressure[i], "middlePressure < 0");
alertNaNOrInfinity(middlePressure[i], "middlePressure = NaN");
for(int j = 0; j < pgridNumber; ++j){
distributionFunction[i][j] = newDistributionFunction[i][j];
}
}
if(tempDensity[rgridNumber - 1] < middleDensity[rgridNumber - 1]){
printf("aaa\n");
}
for(int i = 0; i < rgridNumber; ++i){
delete[] newDistributionFunction[i];
}
delete[] newDistributionFunction;
delete[] tempFunction;
} | mit |
baoxuan/wxlbb | static/webroot-dev/js/address.js | 2529 | /*懒加载效果*/
var Lazy = {
"Img": null,
"getY": function(b) {
var a = 0;
if (b && b.offsetParent) while (b.offsetParent) a += b.offsetTop, b = b.offsetParent; else b && b.y && (a += b.y);
return a;
},
"getX": function(b) {
var a = 0;
if (b && b.offsetParent) while (b.offsetParent) a += b.offsetLeft, b = b.offsetParent; else b && b.x && (a += b.X);
return a;
},
"scrollY": function() {
var a = document.documentElement;
return self.pageYOffset || a && a.scrollTop || document.body.scrollTop || 0;
},
"scrollX": function() {
var a = document.documentElement;
return self.pageXOffset || a && a.scrollLeft || document.body.scrollLeft || 0;
},
"windowWidth": function() {
var a = document.documentElement;
return self.innerWidth || a && a.clientWidth || document.body.clientWidth;
},
"windowHeight": function() {
var a = document.documentElement;
return self.innerHeight || a && a.clientHeight || document.body.clientHeight;
},
"CurrentHeight": function() {
return Lazy.scrollY() + Lazy.windowHeight();
},
"CurrentWidth": function() {
return Lazy.scrollX() + Lazy.windowWidth();
},
"Load": function(d) {
Lazy.Init();
var f = Lazy.CurrentHeight(), b = Lazy.CurrentWidth();
for (_index = 0; _index < Lazy.Img.length; _index++) {
var a = Lazy.Img[_index];
$(a).attr("lazy") == undefined && $(a).attr("lazy", "n");
if($(a).attr("lazy") == "y") continue;
/*$(a).bind("error", function() {
this.id == "subject" ? $(this).attr("src", "") : $(this).attr("src", "http://wap.cmread.com/rbc/p/content/repository/ues/image/s109/nopic.png");
});*/
if (d == undefined || d == "" || d == null) {
var c = Lazy.getY(a), e = Lazy.getX(a);
//e < b && c < f && (a.src = a.getAttribute("data-src"), $(a).attr("lazy", "y"), a.removeAttribute("data-src"));
c < f && (a.src = a.getAttribute("data-src"), $(a).attr("lazy", "y"), a.removeAttribute("data-src"));
$(a).attr("data-rel",e);
} else if (d == "x") {
var c = Lazy.getX(a);
c < b && (a.src = a.getAttribute("data-src"), $(a).attr("lazy", "y"));
}
}
},
"Init": function() {
var a = document.querySelectorAll("img[data-src]");
Lazy.Img = a;
}
};
document.onscroll = function(){Lazy.Load();};
setTimeout(function(){Lazy.Load();},100);
| mit |
khandy21yo/aplus | CMC040/smg/smg_create_virtual_keyboard.cc | 198 | //
// Create virtual keyboard
//
#include "smg/smg.h"
//
// Create virtual keyboard
//
// NOTE: Currently does nothing.
//
long smg$create_virtual_keyboard(
smg_keyboard_id &kbid)
{
return 1;
}
| mit |
ronaldosvieira/javaframes | src/model/constraint/RangeConstraint.java | 2143 | package model.constraint;
import com.sun.istack.internal.NotNull;
import org.jetbrains.annotations.Contract;
import java.util.HashMap;
import java.util.function.BiPredicate;
public class RangeConstraint implements Constraint {
private final String constraint = "range";
private Comparable lo, hi;
private char[] bounds = {'[', ')'};
private static final HashMap<Character, BiPredicate<Comparable, Comparable>> operators = new HashMap<>();
static {
operators.put(')', (c1, c2) -> c1.compareTo(c2) < 0);
operators.put(']', (c1, c2) -> c1.compareTo(c2) <= 0);
operators.put('(', (c1, c2) -> c1.compareTo(c2) > 0);
operators.put('[', (c1, c2) -> c1.compareTo(c2) >= 0);
}
public RangeConstraint(Comparable lo, Comparable hi) {
this(lo, hi, "[]");
}
@Contract("_, _, null -> fail")
public RangeConstraint(Comparable lo, Comparable hi, @NotNull String inclusivity) {
if (lo == null && hi == null)
throw new IllegalArgumentException("Lo and hi can't both be null");
this.lo = lo;
this.hi = hi;
if (inclusivity == null || inclusivity.length() != 2)
throw new IllegalArgumentException("Invalid inclusivity string");
char incl = inclusivity.charAt(0);
if (incl == '[') bounds[0] = '[';
else if (incl == '(' || incl == ']') bounds[0] = '(';
else throw new IllegalArgumentException("Invalid inclusivity string");
incl = inclusivity.charAt(1);
if (incl == ']') bounds[1] = ']';
else if (incl == ')' || incl == '[') bounds[1] = ')';
else throw new IllegalArgumentException("Invalid inclusivity string");
}
@Override
public boolean check(Object value) {
if (!(value instanceof Comparable)) return false;
try {
lo.getClass().cast(value);
hi.getClass().cast(value);
} catch (ClassCastException e) {
return false;
}
return operators.get(bounds[0]).test((Comparable) value, lo)
&& operators.get(bounds[1]).test((Comparable)value, hi);
}
}
| mit |
kleberandrade/dream-net | DreamNet.TCPServer/Program.cs | 12878 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DreamNet.TCPServer
{
class Program
{
public static void Main()
{
TCPServer server = new TCPServer("127.0.0.1", 13000);
server.Open();
server.ListenForClients();
server.HandleClientComm();
}
#region STATIC METHODS
static int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex)
{
return (data[startIndex] << 24)
| (data[startIndex + 1] << 16)
| (data[startIndex + 2] << 8)
| data[startIndex + 3];
}
static int GetLittleEndianIntegerFromByteArray(byte[] data, int startIndex)
{
return (data[startIndex + 3] << 24)
| (data[startIndex + 2] << 16)
| (data[startIndex + 1] << 8)
| data[startIndex];
}
#endregion
#region TCPServer 01
static void TestTCPServer1()
{
while (true)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Server: Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
int i = 0;
using (NetworkStream stream = client.GetStream())
{
while (client.Connected && (i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
}
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
}
}
#endregion
#region TCPServer 02
static void TestTCPServer2()
{
while (true)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Server: Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
int i = 0;
using (NetworkStream stream = client.GetStream())
{
while (client.Connected)
{
i = stream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.ASCII.GetString(bytes, 0, bytes.Length);
int iValor = BitConverter.ToInt32(bytes, 0); // OK
double dValor = BitConverter.ToDouble(bytes, 4); // OK
Console.WriteLine("Received: {0} | {1} | {2}", i, iValor, dValor);
for (int j = 0; j < 10; j++)
{
Console.WriteLine("Received: {0} | {1}", j, BitConverter.ToDouble(bytes, j));
}
stream.Write(bytes, 0, 256);
Console.WriteLine("Sent: {0}", data);
// Translate data bytes to a ASCII string.
//data = System.Text.Encoding.ASCII.GetString(bytes, 0, sizeof(int));
//data = System.Text.Encoding.UTF32.GetBytes(bytes, 0, sizeof(int));
//Console.WriteLine("Received ({0}): {1} | {2}", i, data, BitConverter.ToInt32(bytes, 0));
/*
int number = bReader.ReadInt32();
Console.WriteLine("Received: {0} | {1}", number);
*/
/*
Encoding.UTF32.get
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
*/
}
}
//client.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
}
}
#endregion
#region TCPServer 03
static void TestTCPServer3()
{
const int BUFFER_SIZE = 64;
while (true)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytesRead = new Byte[BUFFER_SIZE];
Byte[] bytesWrite = new Byte[BUFFER_SIZE];
// Enter the listening loop.
while (true)
{
Console.Write("Server: Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
int i = 0;
int cont = 1;
using (NetworkStream stream = client.GetStream())
{
while (client.Connected)
{
// Leitura dos dados na rede
i = stream.Read(bytesRead, 0, BUFFER_SIZE);
// Pega os dados do robo
int robotStatus = BitConverter.ToInt32(bytesRead, 0);
double robotPosition = BitConverter.ToDouble(bytesRead, 4);
Console.Clear();
Console.WriteLine("ROBOT #######################\n");
Console.WriteLine("Status: {0}", robotStatus);
Console.WriteLine("Position: {0}\n", robotPosition);
// Dados do robo
double gamePosition = cont * 1.5;
double gameStiffness = cont * 2.0;
double gameVelocity = cont * 3.0;
double gameAcceleration = cont * 5.0;
int gameControl = cont;
// Escrevendo os dados na rede
Array.Copy(BitConverter.GetBytes(gameControl), 0, bytesWrite, 0, sizeof(int));
Array.Copy(BitConverter.GetBytes(gamePosition), 0, bytesWrite, 4, sizeof(double));
Array.Copy(BitConverter.GetBytes(gameStiffness), 0, bytesWrite, 12, sizeof(double));
Array.Copy(BitConverter.GetBytes(gameVelocity), 0, bytesWrite, 20, sizeof(double));
Array.Copy(BitConverter.GetBytes(gameAcceleration), 0, bytesWrite, 28, sizeof(double));
stream.Write(bytesWrite, 0, BUFFER_SIZE);
Console.WriteLine("\nGAME ########################\n");
Console.WriteLine("Position: {0}", gamePosition);
Console.WriteLine("Stiffness: {0}", gameStiffness);
Console.WriteLine("Velocity: {0}", gameVelocity);
Console.WriteLine("Acceleration: {0}", gameAcceleration);
Console.WriteLine("Control: {0}", gameControl);
//printf("Tempo %.3f (ms)\n", ((double)(stop - start) / CLOCKS_PER_SEC));
Console.WriteLine("Bytes (Receive): " + BitConverter.ToString( bytesRead ) + "\n");
Console.WriteLine("Bytes (Send): " + BitConverter.ToString( bytesWrite ) + "\n");
cont++;
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
}
}
#endregion
}
}
| mit |
saysa/vyperS | src/Vyper/SiteBundle/Controller/ArtistController.php | 5034 | <?php
namespace Vyper\SiteBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Vyper\SiteBundle\Entity\Artist;
class ArtistController extends Controller
{
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param Artist $artist
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showArtistAction(Request $request, Artist $artist)
{
$em = $this->getDoctrine()->getManager();
$increment = $this->container->get('vpr_visit_increment');
$increment->increment($artist, $em);
$view = $this->container->get('saysa_view');
$artist = $em->getRepository('VyperSiteBundle:Artist')->find($artist->getId());
$articles = $em->getRepository('VyperSiteBundle:Article')->getByArtist($artist);
$events = $em->getRepository('VyperSiteBundle:Event')->getByArtist($artist);
$discos = $em->getRepository('VyperSiteBundle:Disco')->getByArtist($artist, 4);
$albums = $em->getRepository('VyperSiteBundle:Album')->getByArtist($artist);
foreach ($albums as $album)
{
$album->cover = $em->getRepository('VyperSiteBundle:Picture')->getByAlbum($album);
}
if (sizeof($articles)>0) $view->set('articles', $articles);
if (sizeof($events)>0) $view->set('events', $events);
if (sizeof($discos)>0) $view->set('discos', $discos);
if (sizeof($albums)>0) $view->set('albums', $albums);
$view
->set('artist', $artist)
;
return $this->render('VyperSiteBundle:Artist:showArtist.html.twig', $view->getView());
}
public function showAllAction(Request $request, $page)
{
$em = $this->getDoctrine()->getManager();
$view = $this->container->get('saysa_view');
$articles_per_page = $this->container->getParameter('artists_per_page');
$type = $em->getRepository('VyperSiteBundle:ArtistType')->findByName("Musique");
# var_dump($type); // array 0 => objet ArtistType
$artists = $em->getRepository('VyperSiteBundle:Artist')->myFindAll($type);
#$artistTypes = $em->getRepository('VyperSiteBundle:ArtistType')->findAll();
$view
#->set('artistTypes', $artistTypes)
->set('current_artists', true)
->set('artists', $artists)
->set('page', $page)
->set('total_artists', ceil(count($artists)/$articles_per_page))
;
if ($request->isXmlHttpRequest()) {
$template = $this->renderView('VyperSiteBundle:Artist:ajaxShowAll.html.twig', $view->getView());
return new Response($template);
} else {
return $this->render('VyperSiteBundle:Artist:showAll.html.twig', $view->getView());
}
}
public function showDiscoAction(Artist $artist, $page)
{
#var_dump($page);
#die();
$em = $this->getDoctrine()->getManager();
$view = $this->container->get('saysa_view');
$discos = $em->getRepository('VyperSiteBundle:Disco')->getByArtist($artist, $page);
$view
->set('artist', $artist)
->set('discos', $discos)
->set('page', $page)
;
return $this->render('VyperSiteBundle:Artist:showDisco.html.twig', $view->getView());
}
public function infinteScrollShowDiscoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$artist = $em->getRepository('VyperSiteBundle:Artist')->find($request->request->get('artist'));
$view = $this->container->get('saysa_view');
$discos = $em->getRepository('VyperSiteBundle:Disco')->getByArtist($artist, $request->request->get('page'), 12);
$view
->set('discos', $discos)
;
$template = $this->renderView('VyperSiteBundle:Artist:isShowDisco.html.twig', $view->getView());
return new Response($template);
}
public function recentArticlesAction()
{
$view = $this->container->get('saysa_view');
$articles = $this->getDoctrine()->getManager()->getRepository('VyperSiteBundle:Article')->showRecentArticles();
$view->set('recent_articles', $articles);
return $this->render('VyperSiteBundle:Article:recentArticles.html.twig', $view->getView());
}
public function popularArtistsAction()
{
$em = $this->getDoctrine()->getManager();
$view = $this->container->get('saysa_view');
$results = $em->getRepository('VyperSiteBundle:Visit')->showPopularArtist();
$popular_artists = array();
foreach($results as $result) {
$popular_artists[] = $result['item']->getArtist();
}
$view->set('popular_artists', $popular_artists);
return $this->render('VyperSiteBundle:Artist:popularArtists.html.twig', $view->getView());
}
}
| mit |
martindevans/Myre | Myre/Myre.Graphics/Geometry/IGeometryProvider.cs | 2647 | using System;
using Myre.Collections;
using System.Collections.Generic;
namespace Myre.Graphics.Geometry
{
public interface IGeometryProvider
{
void Query(string phase, NamedBoxCollection metadata, ICollection<IGeometry> result);
}
public class GeometryRenderer
{
private readonly IReadOnlyList<IGeometryProvider> _geometryProviders;
private readonly List<IGeometry> _geometry = new List<IGeometry>();
public bool BackToFront { get; set; }
public GeometryRenderer(IReadOnlyList<IGeometryProvider> geometryProviders)
{
_geometryProviders = geometryProviders;
}
public List<IGeometry> Query(string phase, Renderer renderer)
{
//Find geometry to draw in this phase
_geometry.Clear();
foreach (var geometryProvider in _geometryProviders)
geometryProvider.Query(phase, renderer.Data, _geometry);
//Return the raw list. Risky, as it could be externally mutated, but we don't want to incur a copy
return _geometry;
}
public void Draw(string phase, Renderer renderer)
{
//Draw the geometry
Draw(Query(phase, renderer), DepthSort.FrontToBack, phase, renderer);
}
public static void Draw(List<IGeometry> geometry, DepthSort sort, string phase, Renderer renderer)
{
//Depth sort geometry (always sort front-to-back, we'll render in reverse order for back-to-front)
if (sort != DepthSort.None)
DepthSortGeometryFrontToBack(geometry);
//Draw geometry
switch (sort)
{
case DepthSort.BackToFront: {
for (int i = geometry.Count - 1; i >= 0; i--)
geometry[i].Draw(phase, renderer);
break;
}
case DepthSort.None:
case DepthSort.FrontToBack: {
foreach (var g in geometry)
g.Draw(phase, renderer);
break;
}
default:
throw new ArgumentOutOfRangeException("sort");
}
}
public static void DepthSortGeometryFrontToBack(List<IGeometry> meshes)
{
meshes.Sort(RenderDataComparator);
}
private static int RenderDataComparator(IGeometry a, IGeometry b)
{
//Negated, because XNA uses a negative Z space
return -a.WorldView.Translation.Z.CompareTo(b.WorldView.Translation.Z);
}
}
}
| mit |
mhamrah/gql | ast_test.go | 742 | package gql
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTypeName(t *testing.T) {
name := "InputTypeName"
tests := []struct {
input TypeDefinition
expected TypeKind
}{
{ObjectDefinition{Name: name}, TypeKind_OBJECT},
{ScalarDefinition{Name: name}, TypeKind_SCALAR},
{UnionDefinition{Name: name}, TypeKind_UNION},
{InterfaceDefinition{Name: name}, TypeKind_INTERFACE},
{InputObjectDefinition{Name: name}, TypeKind_INPUT_OBJECT},
{EnumDefinition{Name: name}, TypeKind_ENUM},
}
for _, test := range tests {
t.Run(reflect.TypeOf(test).Name(), func(t *testing.T) {
assert.Equal(t, name, test.input.TypeName())
assert.Equal(t, test.expected, test.input.TypeKind())
})
}
}
| mit |
Hunv/beRemote | Core/Common/beRemote.Core.Common.LogSystem/Properties/AssemblyInfo.cs | 1564 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("beRemote.Core.Common.LogSystem")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("beRemote Team")]
[assembly: AssemblyProduct("beRemote.Core.Common.LogSystem")]
[assembly: AssemblyCopyright("Copyright © beRemote 2012-2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("696453c3-bc45-469b-b6b1-aa26a2cb910f")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.3.0")]
[assembly: AssemblyFileVersion("0.0.3.0")]
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/wish/job/BatchOrderDownloadTask.java | 669 | package com.swfarm.biz.wish.job;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import com.swfarm.biz.wish.srv.WishService;
public class BatchOrderDownloadTask extends QuartzJobBean{
Logger logger = Logger.getLogger(BatchOrderDownloadTask.class);
private WishService wishService;
public void setWishService(WishService wishService) {
this.wishService = wishService;
}
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
// TODO
}
}
| mit |
fengalin/media-toc | ui/src/main/mod.rs | 1532 | mod controller;
pub use self::controller::{Controller, State};
mod dispatcher;
pub use self::dispatcher::Dispatcher;
use std::path::PathBuf;
use crate::{UIEventChannel, UIFocusContext};
#[derive(Debug)]
pub enum Event {
About,
CancelSelectMedia,
OpenMedia(PathBuf),
Quit,
ResetCursor,
RestoreContext,
SelectMedia,
SetCursorDoubleArrow,
SetCursorWaiting,
ShowAll,
SwitchTo(UIFocusContext),
TemporarilySwitchTo(UIFocusContext),
UpdateFocus,
}
fn about() {
UIEventChannel::send(Event::About);
}
fn cancel_select_media() {
UIEventChannel::send(Event::CancelSelectMedia);
}
fn open_media(path: impl Into<PathBuf>) {
UIEventChannel::send(Event::OpenMedia(path.into()));
}
pub fn quit() {
UIEventChannel::send(Event::Quit);
}
pub fn reset_cursor() {
UIEventChannel::send(Event::ResetCursor);
}
pub fn restore_context() {
UIEventChannel::send(Event::RestoreContext);
}
fn select_media() {
UIEventChannel::send(Event::SelectMedia);
}
pub fn set_cursor_double_arrow() {
UIEventChannel::send(Event::SetCursorDoubleArrow);
}
pub fn set_cursor_waiting() {
UIEventChannel::send(Event::SetCursorWaiting);
}
fn show_all() {
UIEventChannel::send(Event::ShowAll);
}
pub fn switch_to(ctx: UIFocusContext) {
UIEventChannel::send(Event::SwitchTo(ctx));
}
pub fn temporarily_switch_to(ctx: UIFocusContext) {
UIEventChannel::send(Event::TemporarilySwitchTo(ctx));
}
pub fn update_focus() {
UIEventChannel::send(Event::UpdateFocus);
}
| mit |
shokai/sinatra-rocketio-linda | lib/js/linda.js | 2327 | var Linda = function(io, opts){
var self = this;
this.io = null;
if(io === null || typeof io === "undefined"){
this.io = new RocketIO().connect();
}
else{
this.io = io;
}
this.opts = opts || {};
this.TupleSpace = function(name){
if(name === null || typeof name !== "string") name = "__default__";
this.name = name;
this.linda = self;
var space = this;
var make_callback_id = function(){
return new Date()-0+"_"+Math.floor(Math.random()*1000000);
};
this.write = function(tuple, opts){
if(tuple === null || typeof tuple !== "object") return;
if(opts === null || typeof opts === "undefined") opts = {};
self.io.push("__linda_write", [space.name, tuple, opts]);
};
this.read = function(tuple, callback){
if(tuple === null || typeof tuple !== "object") return;
if(typeof callback !== "function") return;
var callback_id = make_callback_id();
self.io.once("__linda_read_callback_"+callback_id, function(data){
callback(data.tuple, data.info);
});
self.io.push("__linda_read", [space.name, tuple, callback_id]);
};
this.take = function(tuple, callback){
if(tuple === null || typeof tuple !== "object") return;
if(typeof callback !== "function") return;
var callback_id = make_callback_id();
self.io.once("__linda_take_callback_"+callback_id, function(data){
callback(data.tuple, data.info);
});
self.io.push("__linda_take", [space.name, tuple, callback_id]);
};
this.watch = function(tuple, callback){
if(tuple === null || typeof tuple !== "object") return;
if(typeof callback !== "function") return;
var callback_id = make_callback_id();
self.io.on("__linda_watch_callback_"+callback_id, function(data){
callback(data.tuple, data.info);
});
self.io.push("__linda_watch", [space.name, tuple, callback_id]);
};
this.list = function(tuple, callback){
if(tuple === null || typeof tuple !== "object") return;
if(typeof callback !== "function") return;
var callback_id = make_callback_id();
self.io.on("__linda_list_callback_"+callback_id, function(list){
callback(list);
});
self.io.push("__linda_list", [space.name, tuple, callback_id]);
}
};
};
| mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_recovery_services_site_recovery/lib/2018-01-10/generated/azure_mgmt_recovery_services_site_recovery/models/hyper_vreplica_base_replication_details.rb | 4631 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::RecoveryServicesSiteRecovery::Mgmt::V2018_01_10
module Models
#
# Hyper V replica provider specific settings base class.
#
class HyperVReplicaBaseReplicationDetails < ReplicationProviderSpecificSettings
include MsRestAzure
def initialize
@instanceType = "HyperVReplicaBaseReplicationDetails"
end
attr_accessor :instanceType
# @return [DateTime] The Last replication time.
attr_accessor :last_replicated_time
# @return [Array<VMNicDetails>] The PE Network details.
attr_accessor :vm_nics
# @return [String] The virtual machine Id.
attr_accessor :vm_id
# @return [String] The protection state for the vm.
attr_accessor :vm_protection_state
# @return [String] The protection state description for the vm.
attr_accessor :vm_protection_state_description
# @return [InitialReplicationDetails] Initial replication details.
attr_accessor :initial_replication_details
# @return [Array<DiskDetails>] VM disk details.
attr_accessor :v_mdisk_details
#
# Mapper for HyperVReplicaBaseReplicationDetails class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'HyperVReplicaBaseReplicationDetails',
type: {
name: 'Composite',
class_name: 'HyperVReplicaBaseReplicationDetails',
model_properties: {
instanceType: {
client_side_validation: true,
required: true,
serialized_name: 'instanceType',
type: {
name: 'String'
}
},
last_replicated_time: {
client_side_validation: true,
required: false,
serialized_name: 'lastReplicatedTime',
type: {
name: 'DateTime'
}
},
vm_nics: {
client_side_validation: true,
required: false,
serialized_name: 'vmNics',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VMNicDetailsElementType',
type: {
name: 'Composite',
class_name: 'VMNicDetails'
}
}
}
},
vm_id: {
client_side_validation: true,
required: false,
serialized_name: 'vmId',
type: {
name: 'String'
}
},
vm_protection_state: {
client_side_validation: true,
required: false,
serialized_name: 'vmProtectionState',
type: {
name: 'String'
}
},
vm_protection_state_description: {
client_side_validation: true,
required: false,
serialized_name: 'vmProtectionStateDescription',
type: {
name: 'String'
}
},
initial_replication_details: {
client_side_validation: true,
required: false,
serialized_name: 'initialReplicationDetails',
type: {
name: 'Composite',
class_name: 'InitialReplicationDetails'
}
},
v_mdisk_details: {
client_side_validation: true,
required: false,
serialized_name: 'vMDiskDetails',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'DiskDetailsElementType',
type: {
name: 'Composite',
class_name: 'DiskDetails'
}
}
}
}
}
}
}
end
end
end
end
| mit |
djfroofy/beatlounge | bl/ugen.py | 2186 | import random
from itertools import cycle
__all__ = ['N', 'Cycle', 'C', 'Random', 'R', 'RandomPhrase', 'RP',
'RandomWalk', 'RW', 'W', 'Weight', 'Oscillate', 'O']
class _Nothing(object):
def __str__(self):
return 'N'
def __repr__(self):
return 'N'
def __call__(self):
return None
def __nonzero__(self):
return False
N = _Nothing()
class _CyclicSampler(object):
_cycle = None
def __call__(self, c):
if self._cycle is None:
self._cycle = cycle(c)
return self._cycle.next()
def _sample(sample=None, c=()):
if sample is None:
sample = _CyclicSampler()
return lambda: sample(c)
def Cycle(*c):
return _sample(c=c)
C = Cycle
def Oscillate(*c):
c = list(c) + list(reversed(c[1:-1]))
return _sample(c=c)
O = Oscillate
def Random(*c):
return _sample(random.choice, c)
R = Random
def _randomPhraseGen(phrases):
while 1:
phrase = random.choice(phrases)
for next in phrase:
yield next
def RandomPhrase(phrases=(), length=None):
if length is not None:
for phrase in phrases:
if len(phrase) != length:
raise ValueError('Phrase %s is not of specified length: %s' %
(phrase, length))
return _randomPhraseGen(phrases).next
RP = RandomPhrase
def _randomWalk(sounds, startIndex=None):
ct = len(sounds)
if startIndex is None:
index = random.randint(0, ct - 1)
else:
index = startIndex
direction = 1
while 1:
yield sounds[index]
if index == 0:
direction = 1
elif index == ct - 1:
direction = -1
else:
if random.randint(0, 1):
direction *= -1
index += direction
def RandomWalk(sounds, startIndex=None):
return _randomWalk(sounds, startIndex).next
RW = RandomWalk
def _weighted(*notes):
ws = []
for (note, weight) in notes:
ws.extend([note for w in range(weight)])
random.shuffle(ws)
return ws
def Weight(*weights):
ws = _weighted(*weights)
return R(*ws)
W = Weight
| mit |
talis/aspire-blackboard-learn-integration | src/org/oscelot/talis/Utils.java | 8645 | package org.oscelot.talis;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import org.apache.commons.codec.binary.Base64;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import com.spvsoftwareproducts.blackboard.utils.B2Context;
import com.talisaspire.BbCategoryEmail;
import com.talisaspire.Section;
import com.talisaspire.TAResourceList;
import blackboard.data.course.Course;
import blackboard.persist.KeyNotFoundException;
import blackboard.persist.PersistenceException;
import blackboard.platform.BbServiceException;
import blackboard.platform.session.BbSession;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import blackboard.platform.log.Log;
import blackboard.platform.log.LogService;
import blackboard.platform.log.LogServiceFactory;
public class Utils {
public static int code;
public final static int SOCKETTIMEOUT = -1;
public static String sectionHTML (List<Section> sections) {
String sectionHTML = "";
if (sections.size() == 0) return sectionHTML;
for (int i = 0; i < sections.size(); i++) {
sectionHTML += "<a href='" + sections.get(i).URI + "' target = '_blank'>" + sections.get(i).name + "</a><br />";
}
sectionHTML = sectionHTML.substring(0, sectionHTML.length() - 6);
return sectionHTML;
}
public static JSONObject getJSON (String URI) {
Log log = Utils.getLogger("talis");
String baseLogMessage = "Utils.getJson: ";
try {
JSONObject jsonRoot = null;
URL u = new URL(URI + ".json");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod ("GET");
huc.setConnectTimeout(10000); //set timeout to 10 seconds
huc.connect();
Utils.code = huc.getResponseCode();
log.logDebug(baseLogMessage + "Response Code: " + Utils.code);
if(Utils.code == HttpURLConnection.HTTP_MOVED_PERM
|| Utils.code == HttpURLConnection.HTTP_MOVED_TEMP
|| Utils.code == HttpURLConnection.HTTP_SEE_OTHER){
// get redirect url from "location" header field
String newUrl = huc.getHeaderField("Location");
log.logDebug(baseLogMessage + "Redirecting to: " + newUrl.toString());
// get the cookie if need, for login
String cookies = huc.getHeaderField("Set-Cookie");
// close the first connection
huc.disconnect();
// open the new connection
huc = (HttpURLConnection) new URL(newUrl).openConnection();
huc.setConnectTimeout(10000); //set timeout to 10 seconds
huc.setRequestProperty("Cookie", cookies);
huc.connect();
Utils.code = huc.getResponseCode();
log.logDebug(baseLogMessage + "Response Code: " + Utils.code);
}
if (Utils.code == HttpURLConnection.HTTP_OK) {
InputStreamReader in = new InputStreamReader((InputStream) huc.getContent());
jsonRoot = (JSONObject)new JSONParser().parse(in);
log.logDebug(baseLogMessage + "Response json: " + jsonRoot.toJSONString());
}
huc.disconnect();
return jsonRoot;
}
catch (SocketTimeoutException ste) {
Utils.code = Utils.SOCKETTIMEOUT;
log.logError(baseLogMessage + "Got a timeout", ste);
}
catch (MalformedURLException mu) {
log.logError(baseLogMessage + "malformed Url", mu);
}
catch (IOException ioe) {
log.logError(baseLogMessage + "IO Exception", ioe);
}
catch (ParseException pe) {
log.logError(baseLogMessage + "ParseException", pe);
}
finally () {
if (huc != null) {
try {
huc.disconnect();
}
catch (Exception e) {
log.logError(baseLogMessage + "Tried to tidy up the http connection", e);
}
}
}
return null;
}
public static String textForStaff (Course c, B2Context b2Context) {
String staffMessage = b2Context.getSetting("staffMessage");
String message = "<div class='noItems divider'>" + String.format(staffMessage, c.getTitle(), c.getCourseId()) + "</div>";
// Check if email link(s) are wanted
if (b2Context.getSetting("emailMode").equals("true")) {
// Check if we some email addresses to use
BbCategoryEmail bbcg;
try {
bbcg = new BbCategoryEmail(c, b2Context);
String email = bbcg.getEmails(b2Context.getSetting("separator"));
if (!email.equals("")) {
String rawEmailMessage = b2Context.getSetting("emailMsg");
if (!rawEmailMessage.equals("")) {
String[] emailText = rawEmailMessage.split("_");
message += "<div class='noItems divider'>" + emailText[0] + "<a href='mailto:" + email + "'>" + emailText[1] + "</a>" + emailText[2] + "</div>";
}
}
}
catch (KeyNotFoundException e) {}
catch (PersistenceException e) {}
}
return message;
}
public static boolean maintenancePeriodNow (String startTime, String endTime) {
boolean maintenance = false;
Calendar start = blackboard.servlet.util.DatePickerUtil.pickerDatetimeStrToCal(startTime);
Calendar end = blackboard.servlet.util.DatePickerUtil.pickerDatetimeStrToCal(endTime);
Calendar now = Calendar.getInstance();
try {
if (now.after(start) && now.before(end)) maintenance = true;
} catch (NullPointerException npe) {};
return maintenance;
}
public static boolean maintenancePeriodFuture(String startTime) {
boolean inFuture = false;
Calendar start = blackboard.servlet.util.DatePickerUtil.pickerDatetimeStrToCal(startTime);
Calendar now = Calendar.getInstance();
try {
if (start.after(now)) inFuture = true;
} catch (NullPointerException npe) {};
return inFuture;
}
public static String endTimeHHMM (String endTime) {
String endTimeFormatted = "";
Calendar end = blackboard.servlet.util.DatePickerUtil.pickerDatetimeStrToCal(endTime);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
endTimeFormatted = formatter.format(end.getTime());
return endTimeFormatted;
}
public static String endTimeDMYHHMM (String endTime) {
String endTimeFormatted = "";
Calendar end = blackboard.servlet.util.DatePickerUtil.pickerDatetimeStrToCal(endTime);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy:HH:mm");
endTimeFormatted = formatter.format(end.getTime());
return endTimeFormatted;
}
public static void setSessionKey(TAResourceList rl, String name, BbSession bbSession) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos;
oos = new ObjectOutputStream(baos);
oos.writeObject(rl);
oos.close();
String resourceList = Base64.encodeBase64String(baos.toByteArray());
bbSession.setGlobalKey(name, resourceList);
} catch (IOException e) {}
catch (PersistenceException pe) {}
}
public static TAResourceList getObjectFromString (String resourceList) {
try {
byte [] data = Base64.decodeBase64(resourceList);
ObjectInputStream ois = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
TAResourceList rl = (TAResourceList) o;
return rl;
} catch (IOException e) {}
catch (ClassNotFoundException cnf) {}
return null;
}
public static Log getLogger(String name) {
// Set up log
LogService logService = LogServiceFactory.getInstance();
Log log = logService.getConfiguredLog(name);
if (log == null) {
try {
logService = LogServiceFactory.getInstance();
logService.defineNewFileLog(name, "logs" + java.io.File.separator + name + ".log", LogService.Verbosity.DEBUG, false);
log = logService.getConfiguredLog(name);
log.logInfo("Talis ASPIRE Logging");
} catch (BbServiceException e) {
log = null;
}
} else {
log.setVerbosityLevel(LogService.Verbosity.DEBUG);
}
return log;
}
}
| mit |
getsenic/senic-hub | senic_hub/backend/tests/test_nuimo_components.py | 11019 | from os import remove
from pytest import fixture, yield_fixture
from tempfile import NamedTemporaryFile
import yaml
import responses
from senic_hub.backend.views.nuimo_components import create_component
@fixture
def url(route_url):
return route_url('nuimo_components', mac_address='00:00:00:00:00:00'.replace(':', '-'))
@fixture
def no_such_nuimo_url(route_url):
return route_url('nuimo_components', mac_address='de:ad:be:ef:00:00'.replace(':', '-'))
@fixture
def no_nuimo_app_config_file(settings):
settings['nuimo_app_config_path'] = '/no/such/file'
return settings
def test_nuimo_components_returns_404_if_config_file_doesnt_exist(
no_nuimo_app_config_file, url, browser):
assert browser.get_json(url, status=404)
def test_nuimo_components_returns_components(url, browser):
assert browser.get_json(url).json == {'components': [
{
'id': 'ph2',
'type': 'philips_hue',
'device_ids': ['ph2-light-4', 'ph2-light-5', 'ph2-light-6', 'ph2-light-7', 'ph2-light-8'],
'name': "Philips Hue Bridge 2"
},
{
'id': 's1',
'type': 'sonos',
'device_ids': ['s1'],
'name': "Sonos Player S1"
}
]}
def test_nuimo_components_returns_404_if_nuimo_doesnt_exist(no_such_nuimo_url, browser):
assert browser.get_json(no_such_nuimo_url, status=404)
@yield_fixture(autouse=True)
def temporary_nuimo_app_config_file(settings):
"""don't run actual external commands during these tests
"""
with NamedTemporaryFile('w+', delete=False) as f:
temp_file_name = f.name
with open(settings['nuimo_app_config_path']) as config_file:
f.write(config_file.read())
settings['nuimo_app_config_path'] = f.name
yield temporary_nuimo_app_config_file
remove(temp_file_name)
def test_add_component_adds_to_app_config(url, browser, temporary_nuimo_app_config_file, settings):
browser.post_json(url, {
'device_ids': ['s1'],
'type': 'sonos'},
status=200
)
with open(settings['nuimo_app_config_path'], 'r') as f:
config = yaml.load(f)
components = config['nuimos']['00:00:00:00:00:00']['components']
assert len(components) == 3
added_component = components[len(components) - 1]
assert 'id' in added_component
assert added_component['device_ids'] == ['s1']
assert added_component['ip_address'] == '127.0.0.1'
assert added_component['type'] == 'sonos'
def test_add_component_returns_new_component(url, browser, temporary_nuimo_app_config_file):
response = browser.post_json(url, {'device_ids': ['ph2-light-4']}).json
assert 'id' in response
assert response['device_ids'] == ['ph2-light-4']
assert response['type'] == 'philips_hue'
assert response['ip_address'] == '127.0.0.2'
def test_adding_component_with_unknown_device_id_returns_400(url, browser, temporary_nuimo_app_config_file):
browser.post_json(url, {'device_ids': ['invalid-device-id']}, status=400)
def test_adding_component_with_unknown_nuimo_returns_404(
no_such_nuimo_url, browser):
assert browser.post_json(no_such_nuimo_url, {
'device_ids': ['s1'],
'type': 'sonos'},
status=404)
def test_create_philips_hue_component():
device = {
'id': 'ph1',
'type': 'philips_hue',
'name': 'Philips Hue Bridge 1',
'ip': '127.0.0.1',
'extra': {
'username': 'light_bringer',
'lights': {
'4': {},
'5': {},
'6': {},
'7': {},
'8': {},
}
}
}
component = create_component(device)
assert component == {
'id': component['id'],
'device_ids': ['ph1-light-4', 'ph1-light-5', 'ph1-light-6', 'ph1-light-7', 'ph1-light-8'],
'type': 'philips_hue',
'name': 'Philips Hue Bridge 1',
'ip_address': '127.0.0.1',
'username': 'light_bringer',
}
def test_create_sonos_component():
device = {
'id': 'sonos1',
'type': 'sonos',
'name': 'test sonos',
'ip': '127.0.0.1',
'extra': {}
}
component = create_component(device)
assert component == {
'id': component['id'],
'device_ids': ['sonos1'],
'type': 'sonos',
'name': 'test sonos',
'ip_address': '127.0.0.1',
}
@fixture
def component_url(route_url):
return route_url('nuimo_component', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='ph2')
def test_get_component_returns_component(component_url, browser, temporary_nuimo_app_config_file, settings):
component = browser.get(component_url, status=200).json
component_id = component_url.rsplit('/', 1)[-1]
assert component == {
'id': component_id,
'device_ids': ['ph2-light-4', 'ph2-light-5', 'ph2-light-6', 'ph2-light-7', 'ph2-light-8'],
'type': 'philips_hue',
'name': 'Philips Hue Bridge 2',
'ip_address': '127.0.0.2',
'username': 'light_bringer',
'station1': {
"name": "station1 name"
},
'station2': {
"name": "station2 name"
},
'station3': {
"name": "station3 name"
}
}
def test_get_invalid_component_returns_404(route_url, browser, temporary_nuimo_app_config_file, settings):
browser.get(route_url('nuimo_component', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='invalid-id'), status=404)
def test_get_component_of_unknown_nuimo_returns_404(route_url, browser, temporary_nuimo_app_config_file, settings):
browser.get(route_url('nuimo_component', mac_address='de:ad:be:ef:00:00'.replace(':', '-'), component_id='ph2'), status=404)
def test_delete_component_returns_200(component_url, browser, temporary_nuimo_app_config_file, settings):
browser.delete(component_url, status=200)
component_id = component_url.rsplit('/', 1)[-1]
with open(settings['nuimo_app_config_path'], 'r') as f:
config = yaml.load(f)
components = config['nuimos']['00:00:00:00:00:00']['components']
assert len(components) == 1
for component in config['nuimos']['00:00:00:00:00:00']['components']:
assert component_id is not component['id']
def test_delete_invalid_component_returns_404(route_url, browser, temporary_nuimo_app_config_file):
browser.delete(route_url('nuimo_component', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='invalid-id'), status=404)
def test_delete_component_of_unknown_nuimo_returns_404(route_url, browser, temporary_nuimo_app_config_file):
browser.delete(route_url('nuimo_component', mac_address='de:ad:be:ef:00:00'.replace(':', '-'), component_id='ph2'), status=404)
def test_put_invalid_component_returns_404(route_url, browser, temporary_nuimo_app_config_file):
browser.put_json(
route_url('nuimo_component', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='invalid-id'),
{'device_ids': ['device-id']},
status=404)
def test_put_component_devices_modifies_app_config(component_url, browser, temporary_nuimo_app_config_file, settings):
browser.put_json(component_url, {'device_ids': ['ph2-light-5', 'ph2-light-6']}, status=200)
with open(settings['nuimo_app_config_path'], 'r') as f:
config = yaml.load(f)
component = next(c for c in config['nuimos']['00:00:00:00:00:00']['components'] if c['id'] == 'ph2')
assert set(component['device_ids']) == set(['ph2-light-5', 'ph2-light-6'])
def test_put_component_devices_returns_modified_component(component_url, browser):
response = browser.put_json(component_url, {'device_ids': ['ph2-light-5', 'ph2-light-6']}).json
component_id = component_url.rsplit('/', 1)[-1]
assert response['id'] == component_id
assert set(response['device_ids']) == set(['ph2-light-5', 'ph2-light-6'])
def test_put_component_devices_of_unknown_nuimo_returns_404(route_url, browser):
browser.put_json(
route_url('nuimo_component', mac_address='de:ad:be:ef:00:00'.replace(':', '-'), component_id='ph2'),
{'device_ids': ['ph2-light-5']},
status=404)
@fixture
def device_test_url(route_url):
return route_url('nuimo_device_test', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='ph2', device_id='ph2-light-5')
def test_get_invalid_device_returns_404(route_url, browser, temporary_nuimo_app_config_file, settings):
browser.get(route_url('nuimo_device_test', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='ph2', device_id='invalid_device-id'), status=404)
def test_get_device_test_fail_message(device_test_url, browser, temporary_nuimo_app_config_file):
device = browser.get(device_test_url, status=200).json
device_id = device_test_url.rsplit('/')[-1]
assert device == {
'test_component': 'philips_hue',
'test_component_id': 'ph2',
'test_device_id': str(device_id),
'test_result': 'FAIL',
'message': 'ERROR_PHUE_PUT_REQUEST_FAIL'
}
@responses.activate
def test_get_device_test_pass_message(device_test_url, browser, temporary_nuimo_app_config_file):
state = {'state': {'on': True, 'bri': 30}}
responses.add(responses.GET, 'http://127.0.0.2/api/light_bringer/lights/5', json=state, status=200)
responses.add(responses.PUT, 'http://127.0.0.2/api/light_bringer/lights/5/state', json={}, status=200)
device = browser.get(device_test_url, status=200).json
device_id = device_test_url.rsplit('/')[-1]
assert device == {
'test_component': 'philips_hue',
'test_component_id': 'ph2',
'test_device_id': str(device_id),
'test_result': 'PASS',
'message': 'BLINK_SUCCESSFUL'
}
@responses.activate
def test_get_device_test_fail_message_due_to_put_exception(device_test_url, browser, temporary_nuimo_app_config_file):
state = {'state': {'on': True, 'bri': 30}}
responses.add(responses.GET, 'http://127.0.0.2/api/light_bringer/lights/5', json=state, status=200)
device = browser.get(device_test_url, status=200).json
device_id = device_test_url.rsplit('/')[-1]
assert device == {
'test_component': 'philips_hue',
'test_component_id': 'ph2',
'test_device_id': str(device_id),
'test_result': 'FAIL',
'message': 'ERROR_PHUE_PUT_REQUEST_FAIL'
}
def test_get_component_of_unknown_nuimo_test_returns_404(route_url, browser, temporary_nuimo_app_config_file, settings):
browser.get(route_url('nuimo_device_test', mac_address='de:ad:be:ef:00:00'.replace(':', '-'), component_id='ph2', device_id='ph2-light-5'), status=404)
def test_get_invalid_component_test_returns_404(route_url, browser, temporary_nuimo_app_config_file, settings):
browser.get(route_url('nuimo_device_test', mac_address='00:00:00:00:00:00'.replace(':', '-'), component_id='invalid-id-1', device_id='ph2-light-5'), status=404)
| mit |
maldrasen/archive | jadefire-0.1/engine/models/character.js | 6197 | "use strict";
global.Character = class Character extends Model {
constructor(data) {
super()
if (data.history == null) { data.history = []; }
if (data.player) { this._role = 'player' }
this.build(data);
}
static evictTemp() {
Character.deleteWhere({ role:'temp' });
}
get isPlayer() { return this._role == 'player'; }
get firstName() { return this._firstName; }
get lastName() { return this._lastName; }
get name() { return `${this._firstName} ${this._lastName}`; }
get gender() { return Gender[this._gender]; }
get stamina() { return this._stamina }
get role() { return this._role; }
get race() { return Race.lookup(this._race); }
get physical() { return this._physical; }
get mental() { return this._mental; }
get personal() { return this._personal; }
get magical() { return this._magical; }
setFirstName(name) { this._firstName = name; }
setLastName(name) { this._lastName = name; }
setPhysical(value) { this._physical = value; }
setMental(value) { this._mental = value; }
setPersonal(value) { this._personal = value; }
setMagical(value) { this._magical = value; }
setStamina(value) { this._stamina = value; }
// Possible possessive form of first name.
getFirstName(possessive) { return (possessive) ? English.possessive(this._firstName) : this._firstName; }
getLoadout() { return Loadout.find(this._loadout_id); }
getAnus() { return (this._anus_id == null) ? null : Anus.find(this._anus_id); }
getBalls() { return (this._balls_id == null) ? null : Balls.find(this._balls_id); }
getBody() { return (this._body_id == null) ? null : Body.find(this._body_id); }
getCock() { return (this._cock_id == null) ? null : Cock.find(this._cock_id); }
getMouth() { return (this._mouth_id == null) ? null : Mouth.find(this._mouth_id); }
getNippleCock() { return (this._nipple_cock_id == null) ? null : Cock.find(this._nipple_cock_id); }
getNipplePussy() { return (this._nipple_pussy_id == null) ? null : Pussy.find(this._nipple_pussy_id); }
getNipples() { return (this._nipples_id == null) ? null : Nipples.find(this._nipples_id); }
getPussy() { return (this._pussy_id == null) ? null : Pussy.find(this._pussy_id); }
getTits() { return (this._tits_id == null) ? null : Tits.find(this._tits_id); }
getTongueCock() { return (this._tongue_cock_id == null) ? null : Cock.find(this._tongue_cock_id); }
hasCock() { return this._cock_id != null; }
hasPussy() { return this._pussy_id != null; }
addNames(options) { NameFactory.build(this,options); }
addLoadout() {
let loadout = new Loadout({ character_id:this.id });
this.hasOne('_loadout_id', loadout);
}
addAnus(options) {
let anus = new Anus({ character_id:this.id });
AnusFactory.build(anus, options);
this.hasOne('_anus_id', anus);
}
addBalls(options) {
let balls = new Balls({ character_id:this.id });
BallsFactory.build(balls, options);
this.hasOne('_balls_id', balls);
}
addBody(options) {
let body = new Body({ character_id:this.id });
BodyFactory.build(body, options);
this.hasOne('_body_id', body);
}
addMouth(options) {
let mouth = new Mouth({ character_id:this.id });
MouthFactory.build(mouth, options);
this.hasOne('_mouth_id', mouth);
}
addCock(options) {
let cock = new Cock({ character_id:this.id, type:'crotch' });
CockFactory.build(cock, options);
this.hasOne('_cock_id', cock);
}
addNippleCock(options) {
let cock = new Cock({ character_id:this.id, type:'nipple' });
CockFactory.build(cock, options);
this.hasOne('_nipple_cock_id', cock);
}
addNipplePussy(options) {
let pussy = new Pussy({ character_id:this.id, type:'nipple' });
PussyFactory.build(pussy, options);
this.hasOne('_nipple_pussy_id', pussy);
}
addNipples(options) {
let nipples = new Nipples({ character_id:this.id });
NippleFactory.build(nipples, options);
this.hasOne('_nipples_id', nipples);
}
addPussy(options) {
let pussy = new Pussy({ character_id:this.id, type:'crotch' });
PussyFactory.build(pussy, options);
this.hasOne('_pussy_id', pussy);
}
addTits(options) {
let tits = new Tits({ character_id:this.id });
TitsFactory.build(tits, options);
this.hasOne('_tits_id', tits);
}
addTongueCock(options) {
let cock = new Cock({ character_id:this.id, type:'tongue' });
CockFactory.build(cock, options);
this.hasOne('_tongue_cock_id', cock);
}
removeNippleCock() {
Cock.deleteWhere({ id:this._nipple_cock_id });
this._nipple_cock_id = null;
this.save();
}
removeNipplePussy() {
Pussy.deleteWhere({ id:this._nipple_pussy_id });
this._nipple_pussy_id = null;
this.save();
}
removeTongueCock() {
Cock.deleteWhere({ id:this._tongue_cock_id });
this._tongue_cock_id = null;
this.save();
}
setGender(gender) {
if (gender instanceof Gender) { return this._gender = gender.code; }
this.validateValueIn('gender', gender, ['male','female','futa','custom']);
this._gender = gender;
}
// Role will be used to determine what kind of character this is.
// player - The player character object.
// temp - This character exists for a single event, and is deleted afterwards.
// plot - This character is part of the game's plot.
// random - This character was randomly generated during world generation.
setRole(role) {
this.validateValueIn('role', role, ['player','plot','temp','random']);
this._role = role;
}
// === Orgasms ===
getOrgasmThreshold() { return 1000; }
getOrgasmMultiplier() { return 100; }
getOrgasmState() { return 'normal'; }
getOrgasmCount() { return 0; }
// === History ===
get history() { return this._history; }
addHistory(key) {
this._history.push(key);
}
hasHistory(key) {
return this.history.indexOf(key) >= 0
}
}
DataObject.isAppliedTo(Character);
MutableDataObject.isAppliedTo(Character);
HasAspects.isAppliedTo(Character);
HasSkills.isAppliedTo(Character);
HasPersonality.isAppliedTo(Character);
| mit |
Kiandr/CrackingCodingInterview | php/test/chapter07/question7.10/PointTest.php | 267 | <?php
require_once __DIR__ . '/../../../src/chapter07/question7.10/Point.php';
class PointTest extends \PHPUnit\Framework\TestCase {
public function testToString() {
$point = new Point(3, 5);
$this->assertEquals('3,5', (string) $point);
}
}
| mit |
ECOcoin-src/ECO-source | src/init.cpp | 36095 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include "zerocoin/ZeroTest.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
bool fConfChange;
bool fEnforceCanonical;
unsigned int nNodeLifespan;
unsigned int nDerivationMethodIndex;
unsigned int nMinerSleep;
bool fUseFastIndex;
enum Checkpoints::CPMode CheckpointsMode;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
void ExitTimeout(void* parg)
{
#ifdef WIN32
MilliSleep(5000);
ExitProcess(0);
#endif
}
void StartShutdown()
{
#ifdef QT_GUI
// ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
uiInterface.QueueShutdown();
#else
// Without UI, Shutdown() can simply be started in a new thread
NewThread(Shutdown, NULL);
#endif
}
void Shutdown(void* parg)
{
static CCriticalSection cs_Shutdown;
static bool fTaken;
// Make this thread recognisable as the shutdown thread
RenameThread("ecocoin-shutoff");
bool fFirstThread = false;
{
TRY_LOCK(cs_Shutdown, lockShutdown);
if (lockShutdown)
{
fFirstThread = !fTaken;
fTaken = true;
}
}
static bool fExit;
if (fFirstThread)
{
fShutdown = true;
nTransactionsUpdated++;
// CTxDB().Close();
bitdb.Flush(false);
StopNode();
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
NewThread(ExitTimeout, NULL);
MilliSleep(50);
printf("ecocoin exited\n\n");
fExit = true;
#ifndef QT_GUI
// ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp
exit(0);
#endif
}
else
{
while (!fExit)
MilliSleep(500);
MilliSleep(100);
ExitThread(0);
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown(NULL);
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("ecocoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" ecocoind [options] " + "\n" +
" ecocoind [options] <command> [params] " + _("Send command to -server or ecocoind") + "\n" +
" ecocoind [options] help " + _("List commands") + "\n" +
" ecocoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "ecocoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
fRet = AppInit2();
}
catch (std::exception& e) {
PrintException(&e, "AppInit()");
} catch (...) {
PrintException(NULL, "AppInit()");
}
if (!fRet)
Shutdown(NULL);
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return 1;
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("ecocoin"), CClientUIInterface::OK | CClientUIInterface::MODAL);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, _("ecocoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
return true;
}
bool static Bind(const CService &addr, bool fError = true) {
if (IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (fError)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: ecocoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: ecocoind.pid)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 11047 or testnet: 11047)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" +
" -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" +
" -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" +
" -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 11048 or testnet: 11048)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -confchange " + _("Require a confirmations for change (default: 0)") + "\n" +
" -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
/** Sanity checks
* Ensure that Bitcoin is running in a usable environment with all
* necessary library support.
*/
bool InitSanityCheck(void)
{
if(!ECC_InitSanityCheck()) {
InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
"information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
return false;
}
// TODO: remaining sanity checks, see #4081
return true;
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
nNodeLifespan = GetArg("-addrlifespan", 7);
fUseFastIndex = GetBoolArg("-fastindex", true);
nMinerSleep = GetArg("-minersleep", 500);
CheckpointsMode = Checkpoints::STRICT;
std::string strCpMode = GetArg("-cppolicy", "strict");
if(strCpMode == "strict")
CheckpointsMode = Checkpoints::STRICT;
if(strCpMode == "advisory")
CheckpointsMode = Checkpoints::ADVISORY;
if(strCpMode == "permissive")
CheckpointsMode = Checkpoints::PERMISSIVE;
nDerivationMethodIndex = 0;
fTestNet = GetBoolArg("-testnet");
if (fTestNet) {
SoftSetBoolArg("-irc", true);
}
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
#if !defined(WIN32) && !defined(QT_GUI)
fDaemon = GetBoolArg("-daemon");
#else
fDaemon = false;
#endif
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps");
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
fConfChange = GetBoolArg("-confchange", false);
fEnforceCanonical = GetBoolArg("-enforcecanonical", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Sanity check
if (!InitSanityCheck())
return InitError(_("Initialization sanity check failed. ecocoin is shutting down."));
std::string strDataDir = GetDataDir().string();
std::string strWalletFileName = GetArg("-wallet", "wallet.dat");
// strWalletFileName must be a plain filename without a directory
if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName))
return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. ecocoin is probably already running."), strDataDir.c_str()));
#if !defined(WIN32) && !defined(QT_GUI)
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0)
{
CreatePidFile(GetPidFile(), pid);
return true;
}
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("ecocoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Used data directory %s\n", strDataDir.c_str());
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "ecocoin server starting\n");
int64_t nStart;
// ********************************************************* Step 5: verify database integrity
uiInterface.InitMessage(_("Verifying database integrity..."));
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
return false;
}
if (filesystem::exists(GetDataDir() / strWalletFileName))
{
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
uiInterface.ThreadSafeMessageBox(msg, _("ecocoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
#ifdef USE_UPNP
fUseUPnP = GetBoolArg("-upnp", USE_UPNP);
#endif
bool fBound = false;
if (!fNoListen)
{
std::string strError;
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind);
}
} else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
if (!IsLimited(NET_IPV6))
fBound |= Bind(CService(in6addr_any, GetListenPort()), false);
if (!IsLimited(NET_IPV4))
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip"))
{
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount
{
if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
{
InitError(_("Invalid amount for -reservebalance=<amount>"));
return false;
}
}
if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key
{
if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load blockchain
if (!bitdb.Open(GetDataDir()))
{
string msg = strprintf(_("Error initializing database environment %s!"
" To recover, BACKUP THAT DIRECTORY, then remove"
" everything from it except for wallet.dat."), strDataDir.c_str());
return InitError(msg);
}
if (GetBoolArg("-loadblockindextest"))
{
CTxDB txdb("r");
txdb.LoadBlockIndex();
PrintBlockTree();
return false;
}
uiInterface.InitMessage(_("Loading block index..."));
printf("Loading block index...\n");
nStart = GetTimeMillis();
if (!LoadBlockIndex())
return InitError(_("Error loading blkindex.dat"));
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Testing Zerocoin
if (GetBoolArg("-zerotest", false))
{
printf("\n=== ZeroCoin tests start ===\n");
Test_RunAllTests();
printf("=== ZeroCoin tests end ===\n\n");
}
// ********************************************************* Step 8: load wallet
uiInterface.InitMessage(_("Loading wallet..."));
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFileName);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
uiInterface.ThreadSafeMessageBox(msg, _("ecocoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of ecocoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart ecocoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb(strWalletFileName);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
}
if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart);
}
// ********************************************************* Step 9: import blocks
if (mapArgs.count("-loadblock"))
{
uiInterface.InitMessage(_("Importing blockchain data file."));
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
{
FILE *file = fopen(strFile.c_str(), "rb");
if (file)
LoadExternalBlockFile(file);
}
exit(0);
}
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
uiInterface.InitMessage(_("Importing bootstrap blockchain data file."));
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
printf("Loading addresses...\n");
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
if (!NewThread(StartNode, NULL))
InitError(_("Error: could not start node"));
if (fServer)
NewThread(ThreadRPCServer, NULL);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
printf("Done loading\n");
if (!strErrors.str().empty())
return InitError(strErrors.str());
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
#if !defined(QT_GUI)
// Loop until process is exit()ed from shutdown() function,
// called from ThreadRPCServer thread when a "stop" command is received.
while (1)
MilliSleep(5000);
#endif
return true;
}
| mit |
starkland/veggiemap | src/assets/js/Firebase.js | 1314 | import Events from '../../events/all';
class Firebase {
constructor() {
this.config = {
apiKey: "AIzaSyCewtn3iS76Cw8N3JAlY-_I9Do92cdtxRw",
authDomain: "form-location-jsday-recife.firebaseapp.com",
databaseURL: "https://form-location-jsday-recife.firebaseio.com",
storageBucket: "form-location---jsday-recife.appspot.com",
messagingSenderId: "43232483561"
}
firebase.initializeApp(this.config);
this.db = firebase.database();
this.veggies = [];
}
addVeggie(obj) {
obj.form.created_at = new Date().getTime();
obj.user.created_at = obj.form.created_at;
this.db.ref(`veggies/${obj.form.id}`).set(obj.form);
this.db.ref(`users/${obj.user.id}`).set(obj.user);
}
update() {
this.db.ref('veggies').on('value', (snapshot) => this.snapshot(snapshot));
}
snapshot(data) {
if (data.val()) {
if (Object.keys(data.val()).length > 0 && Object.keys(data.val())[0] !== 'created_at') {
let obj = data.val();
this.veggies = [];
for (let item in obj) {
this.veggies.push(obj[item]);
}
}
}
this.dispatchEvent(this.veggies);
}
dispatchEvent(data) {
if (data.length > 0) {
Events.$emit('update_veggies', { veggies: data });
}
}
}
export default Firebase; | mit |
rjgreaves/finances | app/components/Login/index.js | 2306 | /**
*
* Login
*
*/
import React from 'react';
import styles from './styles.css';
import validator from 'email-validator';
import TextInput from '../TextInput';
class Login extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
login: React.PropTypes.func.isRequired,
cancelLogin: React.PropTypes.func.isRequired,
loginError: React.PropTypes.string,
}
state = {};
login = () => {
let validationFailed = false;
const email = this.emailField.value();
const password = this.passwordField.value();
if (!validator.validate(email)) {
this.setState({
errorText: 'Please provide a valid email',
});
validationFailed = true;
} else {
this.setState({
errorText: null,
});
}
if (!password) {
this.setState({
passwordErrorText: 'Please provide a password',
});
validationFailed = true;
} else {
this.setState({
passwordErrorText: null,
});
}
if (!validationFailed) {
this.props.login(email, password);
}
}
render() {
let serverError = null;
if (this.props.loginError) {
serverError = <div className={styles.errorMessage}>{this.props.loginError}</div>;
}
return (
<div className={styles.login}>
<div
className={styles.heading}
>
Login with your email
</div>
<TextInput
placeholder="Your email"
ref={(f) => { this.emailField = f; }}
errorText={this.state.errorText}
type="text"
/>
<TextInput
placeholder="Password"
ref={(f) => { this.passwordField = f; }}
errorText={this.state.passwordErrorText}
type="password"
/>
{serverError}
<div
className={styles.actionContainer}
>
<div
className={styles.button}
onClick={this.props.cancelLogin}
>
cancel
</div>
<div
className={styles.button}
onClick={this.login}
>
login
</div>
</div>
</div>
);
}
}
Login.propTypes = {
loginError: React.PropTypes.string,
};
export default Login;
| mit |
cbrghostrider/Hacking | leetcode/020_validParentheses.cpp | 938 | // -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
class Solution {
unordered_map<char, char> complement = {{')', '('}, {']', '['}, {'}', '{'}};
public:
bool isValid(string s) {
vector<char> stack;
for (const char& ch : s) {
if (ch == ')' || ch == ']' || ch == '}') {
if (stack.empty()) return false;
if (stack.back() != complement[ch]) return false;
stack.pop_back();
} else {
stack.push_back(ch);
}
}
return (stack.empty());
}
};
| mit |
ianwcarlson/hatTeamSelector | outputToGDoc.js | 4998 | /**
* @module outputToGDoc
*/
/**
* @typedef {Object} SpreadsheetAuthInfoType
* @property {String} spreadsheetID - Spreadsheet identification encoded in
* url: https://docs.google.com/spreadsheet/ccc?key=<spreadsheetID>&usp=sharing
* @property {String} worksheetID - Worksheet identification
* @property {String} emailID - Developer account generated account identification
* @property {String} keyFile - PEM file contained generated authorization key
* @memberOf Typedefs
*/
/**
* @typedef {PlayerProfileType[]} TeamProfileArrayType
* @memberOf Typedefs
*/
/**
* @typedef {Array} GDocFormattedArrayType
* @property {String} firstName
* @property {String} lastName
* @property {Number} skillLevel
* @memberOf Typedefs
*/
// go to http://www.nczonline.net/blog/2014/03/04/accessing-google-spreadsheets-from-node-js/
// for more details on opening Google developer account and oauth tokens
/**
* Interfaces with Google Spreadsheet API and populates it with
* player/team information. Will format the document into four columns
* @param {TeamProfileArrayType[]} teams2DArray - Two-dimensional array
* containing all the teams and players
* @param {SpreadsheetAuthInfoType} spreadsheetAuthInfo - object containing
* all the document and oauth information
*/
module.exports = function(teams2DArray, spreadsheetAuthInfo, callback){
var fs = require('fs');
var underscore = require('underscore');
var totalCsv = '';
var json2csv = require('json2csv');
var maxRowsPerTeam = findMaxNumPlayers(teams2DArray)+2;
var numCols = 4;
var Spreadsheet = require('edit-google-spreadsheet');
Spreadsheet.load({
debug: true,
spreadsheetId: spreadsheetAuthInfo.spreadsheetID,
worksheetId: spreadsheetAuthInfo.worksheetID,
oauth : {
email: spreadsheetAuthInfo.emailID,
keyFile: spreadsheetAuthInfo.keyFile
}
}, function sheetReady(err, spreadsheet) {
//if(err) throw err;
//
//spreadsheet.add({ 3: { 5: "hello!" } });
//
//spreadsheet.send(function(err) {
// if(err) throw err;
// console.log("Updated Cell at row 3, column 5 to 'hello!'");
//});
if (err) {
callback(err);
return;
}
var rowIdx = 3;
var colIdx = 1;
teams2DArray.forEach(function(element, index){
rowIdx = calcNewRowIdx(rowIdx, index, maxRowsPerTeam);
colIdx = calcNewColIdx(colIdx, index, numCols);
var teamArray = removeObjectKeys(element);
var rowString = rowIdx.toString();
var colString = colIdx.toString();
console.log('row: ', rowString);
console.log('column: ', colString);
var newSheetObject = {};
var newColObj = {};
newColObj[colString] = teamArray;
newSheetObject[rowString] = newColObj;
spreadsheet.add(newSheetObject);
});
spreadsheet.send(function(err) {
if(err){
callback(err);
return;
}
});
callback(null);
});
/**
* Returns the maximum number of players on any one team. This is
* used to format the spreadsheet so the teams don't overlap each
* other
* @param {TeamProfileArrayType} teamsArray - Array containing the
* player profiles
* @returns {Number} maxPlayers
* @private
*/
function findMaxNumPlayers(teamsArray){
var maxPlayers = 0;
teamsArray.forEach(function(element){
var numPlayers = element.length;
if (numPlayers > maxPlayers){
maxPlayers = numPlayers;
}
});
console.log('max players: ', maxPlayers);
return maxPlayers;
}
/**
* Returns a new data structure that doesn't contain any of the
* object keys. This is formatting to the spreadsheet format since
* cells are indexed like arrays
* @param {TeamProfileArrayType} teamsArray - Array containing the
* player profiles
* @returns {GDocFormattedArrayType}
* @private
*/
function removeObjectKeys(teamArray){
var outputArray = [];
teamArray.forEach(function(element){
var innerArray = [];
innerArray.push(element.firstName);
innerArray.push(element.lastName);
innerArray.push(element.skill);
outputArray.push(innerArray);
});
return outputArray;
}
/**
* Calculates new row index. Will auto-wrap.
* @param {Number} oldRowIdx - Old row index
* @param {Number} index - Index of team
* @param {Number} maxRowsPerTeam - Maximum Rows Per Team
* @returns {Number}
* @private
*/
function calcNewRowIdx(oldRowIdx, index, maxRowsPerTeam){
if (index === 0){
oldRowIdx = 1;
} else if (index % 4 === 0){
oldRowIdx += maxRowsPerTeam;
}
return oldRowIdx;
}
/**
* Calculates new column index. Will auto-wrap.
* @param {Number} oldRowIdx - Old row index
* @param {Number} index - Index of Team
* @param {Number} maxRowsPerTeam - Maximum Rows Per Team
* @returns {Number}
* @private
*/
function calcNewColIdx(oldColIdx, index, numCols){
if (index % 4 === 0 || index === 0){
oldColIdx = 1;
} else {
oldColIdx += numCols;
}
return oldColIdx;
}
}; | mit |
StevenOosterbeek/oauth2-setup | client-server/server.js | 5015 | process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
// Necessary for this setup, because we don't have a CA signed certificate
var https = require('https'),
colors = require('colors'),
q = require('q'),
settings = require('../settings').clientServer,
errorCodes = require('../shared/error-codes'),
operations = require('./operations'),
app = require('../shared/app')(__dirname),
mongoose = require('mongoose'),
db = mongoose.connection,
Authserver = require('./models/authserver');
// Open a connection with the client Mongo database
mongoose.connect(settings.database);
db.on('error', console.error.bind(console, '\' Something went wrong during connecting to the client database! \''.red));
db.once('open', function () {
console.log('\n---------------------------------'.grey);
console.log('Client server and database online'.yellow);
console.log('---------------------------------\n'.grey);
});
// Create and start the https server using the Express app
https.createServer(settings.options, app).listen(settings.port);
//
// Global functionality for this server
app.set('findAuthserver', function (options) {
return q.promise(function (resolve) {
Authserver.find(options, function (err, authServers) {
if (err) { console.log('An error occured during getting an authorization server out of the database:'.red, err.red); resolve({ err: err, authServers: false }); }
if (authServers.length > 0) resolve({ err: false, authServers: authServers });
else {
console.log('Authorization server not found in database (based on provided options), stopping the process'.red);
resolve({ err: false, authServers: false });
}
});
});
});
/*
Routes
*/
// Default
app.get('/', function (req, res) {
res.send(errorCodes.respondWith('invalidRequest', 'This route is a dead end..'));
});
// Registration response of the authorization server
app.post(settings.routes.registration_response, function (req, res) {
app.get('validateResponse')('authorization server', req.body, res).then(function (response) {
operations.saveRegistration(response);
});
});
//
// Authorization
app.get(settings.routes.authorization_start, function (req, res) {
// Just for this setup, to make it more dynamically
Authserver.findOne({}, function (err, authServer) {
// A browser interface for this setup, so the client can start the authorization process
res.render('start-authorization', { authServerName: authServer.name, thisClientName: settings.name });
});
});
app.post(settings.routes.authorization_start, function (req, res) {
// Redirect the end-user to the authorization end-point of the authorization server
operations.startAuthorization(req.body, res, app);
});
app.post(settings.routes.authorization_response, function (req, res) {
// Recieving the grant code, if the end-user granted access
app.get('validateResponse')('authorization server', req.body, res).then(function (response) {
operations.requestAccessToken(req.query, res, app);
});
});
//
// Tokens
app.post(settings.routes.token_response, function (req, res) {
// Recieving the tokens
app.get('validateResponse')('authorization server', req.body, res).then(function (response) {
operations.saveTokens(response, res, app);
});
});
app.post(settings.routes.refresh_response, function (req, res) {
// Recieving and saving the refreshed tokens
var response = app.get('urlencodedParser')(req.body);
app.get('validateResponse')('authorization server', response, res).then(function (response) {
operations.updateTokens(response, res, app);
});
});
//
// Get protected data
app.get(settings.routes.get_protected_data, function (req, res) {
// Start the request to the resource server
if (!req.query.resource || !req.query.file) res.send(errorCodes.respondWith('invalidRequest', 'You need to specify the protected file and the file\'s resource server: \'?file= ... &resource= ...\' ')); // For this setup only
else operations.getProtectedData(req.query, res, app);
});
app.post(settings.routes.recieve_protected_data, function (req, res) {
// Recieving the resource server response
app.get('validateResponse')('resource server', app.get('urlencodedParser')(req.body), res, true).then(function (response) {
app.get('requestOutOfBuffer')(req.params.requestToken).then(function (request) {
if (response.error) {
// Try to refesh the tokens once after a denial of access
if (response.error === 'access_denied') operations.refreshTokens(request, res, app);
else return;
} else {
console.log(response.fileUri);
res.redirect('https://' + response.fileUri);
}
app.get('removeRequestFromBuffer')(request.index);
});
});
}); | mit |
habibmasuro/XChange | xchange-btce/src/main/java/com/xeiam/xchange/btce/v3/dto/trade/BTCEOrder.java | 2797 | /**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
*
* 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 com.xeiam.xchange.btce.v3.dto.trade;
import java.math.BigDecimal;
import java.text.MessageFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Matija Mazi
*/
public class BTCEOrder {
private final String pair;
private final Type type;
private final BigDecimal amount;
private final BigDecimal rate;
private final Long timestampCreated;
/** 0: active; 1: ??; 2: cancelled */
private final int status;
/**
* Constructor
*
* @param status
* @param timestampCreated
* @param rate
* @param amount
* @param type
* @param pair
*/
public BTCEOrder(@JsonProperty("status") int status, @JsonProperty("timestamp_created") Long timestampCreated, @JsonProperty("rate") BigDecimal rate, @JsonProperty("amount") BigDecimal amount,
@JsonProperty("type") Type type, @JsonProperty("pair") String pair) {
this.status = status;
this.timestampCreated = timestampCreated;
this.rate = rate;
this.amount = amount;
this.type = type;
this.pair = pair;
}
public String getPair() {
return pair;
}
public Type getType() {
return type;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getRate() {
return rate;
}
public Long getTimestampCreated() {
return timestampCreated;
}
public int getStatus() {
return status;
}
@Override
public String toString() {
return MessageFormat.format("BTCEOrder[pair=''{0}'', type={1}, amount={2}, rate={3}, timestampCreated={4}, status={5}]", pair, type, amount, rate, timestampCreated, status);
}
public static enum Type {
buy, sell
}
}
| mit |
postcss/postcss | test/node.test.ts | 12305 | import { resolve } from 'path'
import { test } from 'uvu'
import { is, equal, type, not } from 'uvu/assert'
import postcss, {
AnyNode,
AtRule,
Root,
Rule,
CssSyntaxError,
Declaration,
parse,
Result,
Plugin,
Document
} from '../lib/postcss.js'
function stringify(node: AnyNode, builder: (str: string) => void): void {
if (node.type === 'rule') {
builder(node.selector)
}
}
test('error() generates custom error', () => {
let file = resolve('a.css')
let css = parse('a{}', { from: file })
let a = css.first as Rule
let error = a.error('Test')
is(error instanceof CssSyntaxError, true)
is(error.message, file + ':1:1: Test')
})
test('error() generates custom error for nodes without source', () => {
let rule = new Rule({ selector: 'a' })
let error = rule.error('Test')
is(error.message, '<css input>: Test')
})
test('error() highlights index', () => {
let root = parse('a { b: c }')
let a = root.first as Rule
let b = a.first as Declaration
let error = b.error('Bad semicolon', { index: 1 })
is(error.showSourceCode(false), '> 1 | a { b: c }\n' + ' | ^')
})
test('error() highlights word', () => {
let root = parse('a { color: x red }')
let a = root.first as Rule
let color = a.first as Declaration
let error = color.error('Wrong color', { word: 'x' })
is(
error.showSourceCode(false),
'> 1 | a { color: x red }\n' + ' | ^'
)
})
test('error() highlights word in multiline string', () => {
let root = parse('a { color: red\n x }')
let a = root.first as Rule
let color = a.first as Declaration
let error = color.error('Wrong color', { word: 'x' })
is(
error.showSourceCode(false),
' 1 | a { color: red\n' + '> 2 | x }\n' + ' | ^'
)
})
test('warn() attaches a warning to the result object', async () => {
let warning: any
let warner: Plugin = {
postcssPlugin: 'warner',
Once(css, { result }) {
warning = css.first?.warn(result, 'FIRST!')
}
}
let result = await postcss([warner]).process('a{}', { from: undefined })
is(warning.type, 'warning')
is(warning.text, 'FIRST!')
is(warning.plugin, 'warner')
equal(result.warnings(), [warning])
})
test('warn() accepts options', () => {
let warner = (css: Root, result: Result): void => {
css.first?.warn(result, 'FIRST!', { index: 1 })
}
let result = postcss([warner]).process('a{}')
is(result.warnings().length, 1)
let warning = result.warnings()[0] as any
is(warning.index, 1)
})
test('remove() removes node from parent', () => {
let rule = new Rule({ selector: 'a' })
let decl = new Declaration({ prop: 'color', value: 'black' })
rule.append(decl)
decl.remove()
is(rule.nodes.length, 0)
type(decl.parent, 'undefined')
})
test('replaceWith() inserts new node', () => {
let rule = new Rule({ selector: 'a' })
rule.append({ prop: 'color', value: 'black' })
rule.append({ prop: 'width', value: '1px' })
rule.append({ prop: 'height', value: '1px' })
let node = new Declaration({ prop: 'min-width', value: '1px' })
let width = rule.nodes[1]
let result = width.replaceWith(node)
equal(result, width)
is(
rule.toString(),
'a {\n' +
' color: black;\n' +
' min-width: 1px;\n' +
' height: 1px\n' +
'}'
)
})
test('replaceWith() inserts new root', () => {
let root = new Root()
root.append(new AtRule({ name: 'import', params: '"a.css"' }))
let a = new Root()
a.append(new Rule({ selector: 'a' }))
a.append(new Rule({ selector: 'b' }))
root.first?.replaceWith(a)
is(root.toString(), 'a {}\nb {}')
})
test('replaceWith() replaces node', () => {
let css = parse('a{one:1;two:2}')
let a = css.first as Rule
let one = a.first as Declaration
let result = one.replaceWith({ prop: 'fix', value: 'fixed' })
is(result.prop, 'one')
type(result.parent, 'undefined')
is(css.toString(), 'a{fix:fixed;two:2}')
})
test('replaceWith() can include itself', () => {
let css = parse('a{one:1;two:2}')
let a = css.first as Rule
let one = a.first as Declaration
let beforeDecl = { prop: 'fix1', value: 'fixedOne' }
let afterDecl = { prop: 'fix2', value: 'fixedTwo' }
one.replaceWith(beforeDecl, one, afterDecl)
is(css.toString(), 'a{fix1:fixedOne;one:1;fix2:fixedTwo;two:2}')
})
test('toString() accepts custom stringifier', () => {
is(new Rule({ selector: 'a' }).toString(stringify), 'a')
})
test('toString() accepts custom syntax', () => {
is(new Rule({ selector: 'a' }).toString({ stringify }), 'a')
})
test('assign() assigns to node', () => {
let decl = new Declaration({ prop: 'white-space', value: 'overflow-wrap' })
is(decl.prop, 'white-space')
is(decl.value, 'overflow-wrap')
decl.assign({ prop: 'word-wrap', value: 'break-word' })
is(decl.prop, 'word-wrap')
is(decl.value, 'break-word')
})
test('clone() clones nodes', () => {
let rule = new Rule({ selector: 'a' })
rule.append({ prop: 'color', value: '/**/black' })
let clone = rule.clone()
type(clone.parent, 'undefined')
equal(rule.first?.parent, rule)
equal(clone.first?.parent, clone)
clone.append({ prop: 'z-index', value: '1' })
is(rule.nodes.length, 1)
})
test('clone() overrides properties', () => {
let rule = new Rule({ selector: 'a' })
let clone = rule.clone({ selector: 'b' })
is(clone.selector, 'b')
})
test('clone() keeps code style', () => {
let css = parse('@page 1{a{color:black;}}')
is(css.clone().toString(), '@page 1{a{color:black;}}')
})
test('clone() works with null in raws', () => {
let decl = new Declaration({
prop: 'color',
value: 'black',
// @ts-expect-error
raws: { value: null }
})
let clone = decl.clone()
equal(Object.keys(clone.raws), ['value'])
})
test('cloneBefore() clones and insert before current node', () => {
let rule = new Rule({ selector: 'a', raws: { after: '' } })
rule.append({ prop: 'z-index', value: '1', raws: { before: '' } })
let result = rule.first?.cloneBefore({ value: '2' })
equal(result, rule.first)
is(rule.toString(), 'a {z-index: 2;z-index: 1}')
})
test('cloneAfter() clones and insert after current node', () => {
let rule = new Rule({ selector: 'a', raws: { after: '' } })
rule.append({ prop: 'z-index', value: '1', raws: { before: '' } })
let result = rule.first?.cloneAfter({ value: '2' })
equal(result, rule.last)
is(rule.toString(), 'a {z-index: 1;z-index: 2}')
})
test('before() insert before current node', () => {
let rule = new Rule({ selector: 'a', raws: { after: '' } })
rule.append({ prop: 'z-index', value: '1', raws: { before: '' } })
let result = rule.first?.before('color: black')
equal(result, rule.last)
is(rule.toString(), 'a {color: black;z-index: 1}')
})
test('after() insert after current node', () => {
let rule = new Rule({ selector: 'a', raws: { after: '' } })
rule.append({ prop: 'z-index', value: '1', raws: { before: '' } })
let result = rule.first?.after('color: black')
equal(result, rule.first)
is(rule.toString(), 'a {z-index: 1;color: black}')
})
test('next() returns next node', () => {
let css = parse('a{one:1;two:2}')
let a = css.first as Rule
equal(a.first?.next(), a.last)
type(a.last?.next(), 'undefined')
})
test('next() returns undefined on no parent', () => {
let css = parse('')
type(css.next(), 'undefined')
})
test('prev() returns previous node', () => {
let css = parse('a{one:1;two:2}')
let a = css.first as Rule
equal(a.last?.prev(), a.first)
type(a.first?.prev(), 'undefined')
})
test('prev() returns undefined on no parent', () => {
let css = parse('')
type(css.prev(), 'undefined')
})
test('toJSON() cleans parents inside', () => {
let rule = new Rule({ selector: 'a' })
rule.append({ prop: 'color', value: 'b' })
let json = rule.toJSON() as any
type(json.parent, 'undefined')
type(json.nodes[0].parent, 'undefined')
is(
JSON.stringify(rule),
'{"raws":{},"selector":"a","type":"rule","nodes":[' +
'{"raws":{},"prop":"color","value":"b","type":"decl"}' +
'],"inputs":[]}'
)
})
test('toJSON() converts custom properties', () => {
let root = new Root() as any
root._cache = [1]
root._hack = {
toJSON() {
return 'hack'
}
}
equal(root.toJSON(), {
type: 'root',
nodes: [],
raws: {},
_hack: 'hack',
inputs: [],
_cache: [1]
})
})
test('raw() has shortcut to stringifier', () => {
let rule = new Rule({ selector: 'a' })
is(rule.raw('before'), '')
})
test('root() returns root', () => {
let css = parse('@page{a{color:black}}')
let page = css.first as AtRule
let a = page.first as Rule
let color = a.first as Declaration
equal(color.root(), css)
})
test('root() returns parent of parents', () => {
let rule = new Rule({ selector: 'a' })
rule.append({ prop: 'color', value: 'black' })
equal(rule.first?.root(), rule)
})
test('root() returns self on root', () => {
let rule = new Rule({ selector: 'a' })
equal(rule.root(), rule)
})
test('root() returns root in document', () => {
let css = new Document({ nodes: [parse('@page{a{color:black}}')] })
let root = css.first as Root
let page = root.first as AtRule
let a = page.first as Rule
let color = a.first as Declaration
equal(color.root(), root)
})
test('root() on root in document returns same root', () => {
let document = new Document()
let root = new Root()
document.append(root)
equal(document.first?.root(), root)
})
test('root() returns self on document', () => {
let document = new Document()
equal(document.root(), document)
})
test('cleanRaws() cleans style recursivelly', () => {
let css = parse('@page{a{color:black}}')
css.cleanRaws()
is(css.toString(), '@page {\n a {\n color: black\n }\n}')
let page = css.first as AtRule
let a = page.first as Rule
let color = a.first as Declaration
type(page.raws.before, 'undefined')
type(color.raws.before, 'undefined')
type(page.raws.between, 'undefined')
type(color.raws.between, 'undefined')
type(page.raws.after, 'undefined')
})
test('cleanRaws() keeps between on request', () => {
let css = parse('@page{a{color:black}}')
css.cleanRaws(true)
is(css.toString(), '@page{\n a{\n color:black\n }\n}')
let page = css.first as AtRule
let a = page.first as Rule
let color = a.first as Declaration
not.type(page.raws.between, 'undefined')
not.type(color.raws.between, 'undefined')
type(page.raws.before, 'undefined')
type(color.raws.before, 'undefined')
type(page.raws.after, 'undefined')
})
test('positionInside() returns position when node starts mid-line', () => {
let css = parse('a { one: X }')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.positionInside(6), { line: 1, column: 12 })
})
test('positionInside() returns position when before contains newline', () => {
let css = parse('a {\n one: X}')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.positionInside(6), { line: 2, column: 9 })
})
test('positionInside() returns position when node contains newlines', () => {
let css = parse('a {\n\tone: 1\n\t\tX\n3}')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.positionInside(10), { line: 3, column: 4 })
})
test('positionBy() returns position for word', () => {
let css = parse('a { one: X }')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.positionBy({ word: 'one' }), { line: 1, column: 6 })
})
test('positionBy() returns position for index', () => {
let css = parse('a { one: X }')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.positionBy({ index: 1 }), { line: 1, column: 7 })
})
test('rangeBy() returns range for word', () => {
let css = parse('a { one: X }')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.rangeBy({ word: 'one' }), {
start: { line: 1, column: 6 },
end: { line: 1, column: 9 }
})
})
test('rangeBy() returns range for index and endIndex', () => {
let css = parse('a { one: X }')
let a = css.first as Rule
let one = a.first as Declaration
equal(one.rangeBy({ index: 1, endIndex: 3 }), {
start: { line: 1, column: 7 },
end: { line: 1, column: 9 }
})
})
test.run()
| mit |
tosyx/fuby | test/fuby/suffixes.rb | 239 | require 'fuby/suffixes'
using Fuby
describe Array do
describe "suffixes" do
it "returns an Enumerable of the suffixes of self, longest first" do
[1, 2, 3].suffixes.to_a.must_equal [[1, 2, 3], [2, 3], [3]]
end
end
end
| mit |
AbenezerMamo/crypto-signal | app/conf.py | 1980 | """Load configuration from environment
"""
import os
import ccxt
import yaml
class Configuration():
"""Parses the environment configuration to create the config objects.
"""
def __init__(self):
"""Initializes the Configuration class
"""
with open('defaults.yml', 'r') as config_file:
default_config = yaml.load(config_file)
if os.path.isfile('config.yml'):
with open('config.yml', 'r') as config_file:
user_config = yaml.load(config_file)
else:
user_config = dict()
if 'settings' in user_config:
self.settings = {**default_config['settings'], **user_config['settings']}
else:
self.settings = default_config['settings']
if 'notifiers' in user_config:
self.notifiers = {**default_config['notifiers'], **user_config['notifiers']}
else:
self.notifiers = default_config['notifiers']
if 'indicators' in user_config:
self.indicators = {**default_config['indicators'], **user_config['indicators']}
else:
self.indicators = default_config['indicators']
if 'informants' in user_config:
self.informants = {**default_config['informants'], **user_config['informants']}
else:
self.informants = default_config['informants']
if 'crossovers' in user_config:
self.crossovers = {**default_config['crossovers'], **user_config['crossovers']}
else:
self.crossovers = default_config['crossovers']
if 'exchanges' in user_config:
self.exchanges = user_config['exchanges']
else:
self.exchanges = dict()
for exchange in ccxt.exchanges:
if exchange not in self.exchanges:
self.exchanges[exchange] = {
'required': {
'enabled': False
}
}
| mit |
bebopjmm/woin-rpg-services | woin-entityReferenceData-service/src/main/java/com/rpgcampaigner/woin/entityReference/dal/ReferenceDynamoRepository.java | 3495 | package com.rpgcampaigner.woin.entityReference.dal;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Expected;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.rpgcampaigner.woin.core.entity.Skill;
import com.rpgcampaigner.woin.core.entity.SkillGroup;
/**
* @author jmccormick
* @since 6/14/17
*/
public class ReferenceDynamoRepository implements ReferenceRepository {
private final AmazonDynamoDB client;
private final DynamoDB dynamoDB;
private final DynamoConfiguration configuration;
public ReferenceDynamoRepository(DynamoConfiguration configuration) {
this.configuration = configuration;
this.client = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.valueOf(configuration.getRegion()))
.build();
this.dynamoDB = new DynamoDB(client);
}
@Override
public Set<SkillGroup> getAllSkillGroups() {
ScanRequest scanRequest = new ScanRequest().withTableName(configuration.getSkillGroupTableName());
ScanResult scanResult = client.scan(scanRequest);
return scanResult.getItems().stream()
.map(mapToSkillGroup)
.collect(Collectors.toSet());
}
@Override
public Optional<SkillGroup> getSkillGroup(String name) {
Objects.requireNonNull(name);
Table table = dynamoDB.getTable(configuration.getSkillGroupTableName());
Optional<Item> item = Optional.ofNullable(table.getItem("Name", name));
return item.isPresent() ?
Optional.of(convertToSkillGroup.apply(item.get())) :
Optional.empty();
}
@Override
public void createSkillGroup(SkillGroup skillGroup) {
PutItemOutcome outcome = dynamoDB.getTable(configuration.getSkillGroupTableName())
.putItem(itemFromSkillGroup.apply(skillGroup), new Expected("Name").notExist());
}
@Override
public void updateSkillGroup(SkillGroup skillGroup) {
PutItemOutcome outcome = dynamoDB.getTable(configuration.getSkillGroupTableName())
.putItem(itemFromSkillGroup.apply(skillGroup));
}
private final Function<Item, SkillGroup> convertToSkillGroup = item -> {
SkillGroup skillGroup = new SkillGroup(item.getString("Name"));
item.getStringSet("skills").stream()
.forEach(skillName -> skillGroup.getSkillSet().add(new Skill(skillName)));
return skillGroup;
};
private final Function<Map<String, AttributeValue>, SkillGroup> mapToSkillGroup = map -> {
SkillGroup skillGroup = new SkillGroup(map.get("Name").getS());
map.get("skills").getSS().stream()
.forEach(skillName -> skillGroup.getSkillSet().add(new Skill(skillName)));
return skillGroup;
};
private final Function<SkillGroup, Item> itemFromSkillGroup = skillGroup ->
new Item()
.withPrimaryKey("Name", skillGroup.getName())
.withStringSet("skills",
skillGroup.getSkillSet().stream()
.map(skill -> skill.getName())
.collect(Collectors.toSet()));
}
| mit |
seanpar203/validator | validator/fields.py | 3114 | from typing import Any
from collections import OrderedDict
FORMATTED_TYPE_NAMES = {
'str': 'String',
'int': 'Integer',
'list': 'List',
'float': 'Float',
'dict': 'Dictionary'
}
class DeclarativeFieldsMetaclass(type):
"""
Metaclass for removing declared Fields from Validator instances.
"""
def __new__(mcs, name, bases, attrs):
"""
Remove declared Fields as object attributes
Notes:
This is necessary to allow a declarative interface for inherited
Validation objects. We then reset the attrs to be the value from
the incoming dictionary in the BaseValidator class, similar to how
it's done in Django with Models.
"""
declared_fields = []
required_fields = []
for key, val in list(attrs.items()):
if isinstance(val, Field):
if val.required:
required_fields.append((key, val))
declared_fields.append((key, val))
attrs.pop(key)
# Attach collected lists to attrs before object creation.
attrs['fields'] = OrderedDict(declared_fields)
attrs['required_fields'] = OrderedDict(required_fields)
new_class = super().__new__(mcs, name, bases, attrs)
return new_class
class Field:
""" Validation Field. """
def __init__(self, data_type: type = None,
validators: list = [],
required: bool = False) -> None:
self.data_type = data_type
self.validators = validators
self.required = required
def validate_type(self, val: Any):
""" Validates field data type
:param val: Value passed for checking
:type val: Any
:return: error message if any
"""
err = None
# A single valid data type
if (type(self.data_type) != list) and (type(val) != self.data_type):
formatted = FORMATTED_TYPE_NAMES[self.data_type.__name__]
err = "'{}' is expected to be a '{}'".format(val,
formatted)
# Multiple valid types are passed as a list
elif (type(self.data_type) == list) and (type(val) not in self.data_type):
error_msg = " or ".join([FORMATTED_TYPE_NAMES[t.__name__] for t in self.data_type])
err = "'{}' is expected to be a '{}'".format(val, error_msg)
return err
def validate(self, val: Any) -> list:
""" Validates value by passing into all validators
:param val: Value to pass into validators
:type val: Any
:return: Errors or empty list.
:rtype: list
"""
errors: list = []
if self.data_type:
err_msg = self.validate_type(val)
if err_msg: # There was an error
errors.append(err_msg)
return errors
for validator in self.validators:
passed, err = validator(val)
if not passed:
errors.append(err)
return errors
| mit |
testdouble/testdouble.js | test/unit/imitate/index.test.js | 1859 | let initializeNames, createImitation, overwriteChildren, subject
module.exports = {
beforeEach: () => {
initializeNames = td.replace('../../../src/imitate/initialize-names').default
createImitation = td.replace('../../../src/imitate/create-imitation').default
overwriteChildren = td.replace('../../../src/imitate/overwrite-children').default
subject = require('../../../src/imitate').default
},
'golden path': () => {
td.when(initializeNames('something', undefined)).thenReturn(['a name'])
td.when(createImitation('something', ['a name'])).thenReturn('a fake')
const childCallbackCaptor = td.matchers.captor()
const result = subject('something')
assert.equal(result, 'a fake')
td.verify(overwriteChildren('something', 'a fake', childCallbackCaptor.capture()))
// Now make sure the child callback is handled correctly:
td.when(initializeNames('another thing', ['a name', 'another name'])).thenReturn(['new names'])
td.when(createImitation('another thing', ['new names'])).thenReturn('fake2')
const result2 = childCallbackCaptor.value('another thing', 'another name')
assert.equal(result2, 'fake2')
td.verify(overwriteChildren('another thing', 'fake2', td.matchers.isA(Function)))
},
'breaks cycles by tracking encounteredObjects': () => {
const top = { type: 'top' }
const childCallbackCaptor = td.matchers.captor()
td.when(initializeNames(top, undefined)).thenReturn(['lol'])
td.when(createImitation(top, ['lol']), { times: 1 }).thenReturn('fake-top')
const result = subject(top)
assert.equal(result, 'fake-top')
td.verify(overwriteChildren(top, 'fake-top', childCallbackCaptor.capture()))
// Make sure it short-circuits the known thing
const result2 = childCallbackCaptor.value(top, 'whatever')
assert.equal(result2, 'fake-top')
}
}
| mit |
mrjanczak/OPPEN2 | src/AppBundle/Model/map/FileCatTableMap.php | 3772 | <?php
namespace AppBundle\Model\map;
use \RelationMap;
use \TableMap;
/**
* This class defines the structure of the 'file_cat' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package propel.generator.src.AppBundle.Model.map
*/
class FileCatTableMap extends TableMap
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'src.AppBundle.Model.map.FileCatTableMap';
/**
* Initialize the table attributes, columns and validators
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('file_cat');
$this->setPhpName('FileCat');
$this->setClassname('AppBundle\\Model\\FileCat');
$this->setPackage('src.AppBundle.Model');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('id', 'Id', 'INTEGER', true, null, null);
$this->addColumn('name', 'Name', 'VARCHAR', false, 100, null);
$this->getColumn('name', false)->setPrimaryString(true);
$this->addColumn('symbol', 'Symbol', 'VARCHAR', false, 10, null);
$this->addColumn('as_project', 'AsProject', 'BOOLEAN', false, 1, false);
$this->addColumn('as_income', 'AsIncome', 'BOOLEAN', false, 1, false);
$this->addColumn('as_cost', 'AsCost', 'BOOLEAN', false, 1, false);
$this->addColumn('as_contractor', 'AsContractor', 'BOOLEAN', false, 1, false);
$this->addColumn('is_locked', 'IsLocked', 'BOOLEAN', false, 1, false);
$this->addForeignKey('year_id', 'YearId', 'INTEGER', 'year', 'id', false, null, null);
$this->addForeignKey('sub_file_cat_id', 'SubFileCatId', 'INTEGER', 'file_cat', 'id', false, null, null);
// validators
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
$this->addRelation('Year', 'AppBundle\\Model\\Year', RelationMap::MANY_TO_ONE, array('year_id' => 'id', ), 'CASCADE', null);
$this->addRelation('SubFileCat', 'AppBundle\\Model\\FileCat', RelationMap::MANY_TO_ONE, array('sub_file_cat_id' => 'id', ), null, null);
$this->addRelation('FileCat', 'AppBundle\\Model\\FileCat', RelationMap::ONE_TO_MANY, array('id' => 'sub_file_cat_id', ), null, null, 'FileCats');
$this->addRelation('File', 'AppBundle\\Model\\File', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_id', ), 'CASCADE', null, 'Files');
$this->addRelation('DocCat', 'AppBundle\\Model\\DocCat', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_id', ), null, null, 'DocCats');
$this->addRelation('AccountRelatedByFileCatLev1Id', 'AppBundle\\Model\\Account', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_lev1_id', ), null, null, 'AccountsRelatedByFileCatLev1Id');
$this->addRelation('AccountRelatedByFileCatLev2Id', 'AppBundle\\Model\\Account', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_lev2_id', ), null, null, 'AccountsRelatedByFileCatLev2Id');
$this->addRelation('AccountRelatedByFileCatLev3Id', 'AppBundle\\Model\\Account', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_lev3_id', ), null, null, 'AccountsRelatedByFileCatLev3Id');
$this->addRelation('Project', 'AppBundle\\Model\\Project', RelationMap::ONE_TO_MANY, array('id' => 'file_cat_id', ), null, null, 'Projects');
} // buildRelations()
} // FileCatTableMap
| mit |
SmartGeoTools/SmartGeoToolsJava | SmartGeoToolsJava/src/cd/syna/geotools/ihms/MainForm.java | 11946 | /*
* 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 cd.syna.geotools.ihms;
import cd.syna.geotools.main.SplashScreen;
import cd.syna.geotools.utils.MySwingUtilities;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.JXHyperlink;
/**
*
* @author Mishka
*/
public class MainForm extends javax.swing.JFrame {
private JXHyperlink hynewcity, hynewrestaurant, hylogout,
hymapcontrol;
private MySwingUtilities mUtils=new MySwingUtilities();
private SplashScreen welcomepanel;
private MapControlPanel mappanel;
/** Creates new form MainForm */
public MainForm() {
initComponents();
/** Initialisation de la frame */
setTitle("SmartGeoTools 1.0");
/** call the method for creating task pane */
createGeoToolsTaskPane();
MapPrevisualization();
}
void createGeoToolsTaskPane(){
/** HyperLink for cities */
hynewcity=new JXHyperlink(new_city_action);
hynewcity.setText("Visualiser les cités");
hynewcity.setIcon(new ImageIcon(getClass().getResource("/cd/syna/geotools/res/ecole.png")));
jXt_navigation.add(hynewcity);
/** HyperLink Logout */
hymapcontrol=new JXHyperlink();
hymapcontrol.setText("Afficher la Map");
hymapcontrol.setIcon(new ImageIcon(getClass().getResource("/cd/syna/geotools/res/search.png")));
jXtmapcontrol.add(hymapcontrol);
// ------------------------------------------------------------------------------------------------------------------
/** Permet de rendre les taskpane collapsable (si cela se dit en anglais... lol !!!) */
jXt_navigation.setCollapsed(true);
jXtmapcontrol.setCollapsed(true);
}
/** Define all actions for our hyper link */
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Action new_city_action=new AbstractAction(){
public void actionPerformed(ActionEvent e){
addCityMode();
System.out.println("Nouvelle cité a été créée !"); // pas obligatoire d'ajouter cette ligne de code
}
};
/** Action for MapControl */
Action mapcontrol_action=new AbstractAction(){
public void actionPerformed(ActionEvent e){
addMapcontrolMode();
}
};
/** Action to allow user to logout */
Action logout_action=new AbstractAction(){
public void actionPerformed(ActionEvent e){
if(hymapcontrol.isEnabled()){
//Put one method here in case the hymapcontrol is active
}else{
if(JOptionPane.showConfirmDialog(null, "Voulez-vous vraiment quitter ?")==JOptionPane.YES_NO_OPTION){
System.exit(0);
}else{
return;
}
}
}
};
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------------------------------------------------------
void addCityMode(){
MySwingUtilities.setContentPane(ParentContent_panel, new CityPanel());
}
void addMapcontrolMode(){
MySwingUtilities.setContentPane(main_panel, new MapControlPanel());
}
// ------------------------------------------------------------------------------------------------------------------
void enableDisableHyperlinks(boolean enableOrDisable){
Component[] c=this.getComponents();
for(int i=0;i<c.length;i++){
if(c[i].getClass().equals(JXHyperlink.class)){
c[i].setEnabled(enableOrDisable);
}
}
}
void MapPrevisualization(){
MySwingUtilities.setContentPane(main_panel, new UsersConnectPanel());
// hynewcity.setEnabled(false);
hynewcity.setEnabled(true);
}
public void connectToMode(){
//this will enable all HyperLinks
hynewcity.setEnabled(true); // to do the same with others hyper links
hymapcontrol.setEnabled(true);
addCityMode(); //this will be replace by the default map mode
jXTaskPaneContainer1.setVisible(true);
ParentContent_panel.repaint();
ParentContent_panel.revalidate();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jXHeader1 = new org.jdesktop.swingx.JXHeader();
ParentContent_panel = new javax.swing.JPanel();
jXTaskPaneContainer1 = new org.jdesktop.swingx.JXTaskPaneContainer();
jXtmapcontrol = new org.jdesktop.swingx.JXTaskPane();
jXt_navigation = new org.jdesktop.swingx.JXTaskPane();
jXtAdmin = new org.jdesktop.swingx.JXTaskPane();
main_panel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
org.jdesktop.swingx.VerticalLayout verticalLayout1 = new org.jdesktop.swingx.VerticalLayout();
verticalLayout1.setGap(14);
jXTaskPaneContainer1.setLayout(verticalLayout1);
jXtmapcontrol.setName("jxtaskpMapControl"); // NOI18N
jXtmapcontrol.setTitle("Map Control & Navigation");
jXTaskPaneContainer1.add(jXtmapcontrol);
jXt_navigation.setName("jxtaskpNavigation"); // NOI18N
jXt_navigation.setTitle("Current Navigation");
jXTaskPaneContainer1.add(jXt_navigation);
jXtAdmin.setName("jxtaskpAdmin"); // NOI18N
jXtAdmin.setTitle("Administration");
jXTaskPaneContainer1.add(jXtAdmin);
javax.swing.GroupLayout main_panelLayout = new javax.swing.GroupLayout(main_panel);
main_panel.setLayout(main_panelLayout);
main_panelLayout.setHorizontalGroup(
main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
main_panelLayout.setVerticalGroup(
main_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout ParentContent_panelLayout = new javax.swing.GroupLayout(ParentContent_panel);
ParentContent_panel.setLayout(ParentContent_panelLayout);
ParentContent_panelLayout.setHorizontalGroup(
ParentContent_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ParentContent_panelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jXTaskPaneContainer1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(main_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
ParentContent_panelLayout.setVerticalGroup(
ParentContent_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ParentContent_panelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(ParentContent_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(main_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jXTaskPaneContainer1, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jXHeader1, javax.swing.GroupLayout.DEFAULT_SIZE, 966, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ParentContent_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jXHeader1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ParentContent_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel ParentContent_panel;
private org.jdesktop.swingx.JXHeader jXHeader1;
private org.jdesktop.swingx.JXTaskPaneContainer jXTaskPaneContainer1;
private org.jdesktop.swingx.JXTaskPane jXtAdmin;
private org.jdesktop.swingx.JXTaskPane jXt_navigation;
private org.jdesktop.swingx.JXTaskPane jXtmapcontrol;
private javax.swing.JPanel main_panel;
// End of variables declaration//GEN-END:variables
}
| mit |
yanhongwang/Codility | MaxProductOfThree.py | 1442 | """
A non-empty zero-indexed array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).
For example, array A such that:
A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6
contains the following example triplets:
(0, 1, 2), product is −3 * 1 * 2 = −6
(1, 2, 4), product is 1 * 2 * 5 = 10
(2, 4, 5), product is 2 * 5 * 6 = 60
Your goal is to find the maximal product of any triplet.
Write a function:
def solution(A)
that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.
For example, given array A such that:
A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6
the function should return 60, as the product of triplet (2, 4, 5) is maximal.
Assume that:
N is an integer within the range [3..100,000];
each element of array A is an integer within the range [−1,000..1,000].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Copyright 2009–2016 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
"""
def solution(A):
A.sort()
return max(A[0]*A[1]*A[-1], A[-1]*A[-2]*A[-3])
| mit |
kartenmacherei/rest-framework | src/Response/HttpHeader.php | 541 | <?php
namespace Kartenmacherei\RestFramework\Response;
class HttpHeader
{
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $value = '';
/**
* @param string $name
* @param string $value
*/
public function __construct($name, $value)
{
$this->name = $name;
$this->value = $value;
}
/**
* @return string
*/
public function asString(): string
{
return sprintf('%s: %s', $this->name, $this->value);
}
}
| mit |
slinderman/theano_pyglm | pyglm/models/model_factory.py | 15855 | """
Make models from a template
"""
import numpy as np
from scipy.optimize import nnls
from standard_glm import StandardGlm
from spatiotemporal_glm import SpatiotemporalGlm
from shared_tuningcurve_glm import SharedTuningCurveGlm
from simple_weighted_model import SimpleWeightedModel
from simple_sparse_model import SimpleSparseModel
from sparse_weighted_model import SparseWeightedModel
from sbm_weighted_model import SbmWeightedModel
from distance_weighted_model import DistanceWeightedModel
import copy
def make_model(template, N=None, dt=None):
""" Construct a model from a template and update the specified parameters
"""
if isinstance(template, str):
# Create the specified model
if template.lower() == 'standard_glm' or \
template.lower() == 'standardglm':
model = copy.deepcopy(StandardGlm)
elif template.lower() == 'spatiotemporal_glm':
model = copy.deepcopy(SpatiotemporalGlm)
elif template.lower() == 'shared_tuning_curve':
model = copy.deepcopy(SharedTuningCurveGlm)
elif template.lower() == 'simple_weighted_model' or \
template.lower() == 'simpleweightedmodel':
model = copy.deepcopy(SimpleWeightedModel)
elif template.lower() == 'simple_sparse_model' or \
template.lower() == 'simplesparsemodel':
model = copy.deepcopy(SimpleSparseModel)
elif template.lower() == 'sparse_weighted_model' or \
template.lower() == 'sparseweightedmodel':
model = copy.deepcopy(SparseWeightedModel)
elif template.lower() == 'sbm_weighted_model' or \
template.lower() == 'sbmweightedmodel':
model = copy.deepcopy(SbmWeightedModel)
elif template.lower() == 'distance_weighted_model' or \
template.lower() == 'distanceweightedmodel':
model = copy.deepcopy(DistanceWeightedModel)
else:
raise Exception("Unrecognized template model: %s!" % template)
elif isinstance(template, dict):
model = copy.deepcopy(template)
else:
raise Exception("Unrecognized template model!")
# Override template model parameters
if N is not None:
model['N'] = N
if dt is not None:
model['dt'] = dt
# # Update other parameters as necessary
# if template.lower() == 'distance_weighted_model' or \
# template.lower() == 'distanceweightedmodel':
# #model['network']['graph']['location_prior']['sigma'] = N/2.0/3.0
# model['network']['graph']['location_prior']['mu'] = \
# np.tile(np.arange(N).reshape((N,1)),
# [1,model['network']['graph']['N_dims']]).ravel()
return model
def stabilize_sparsity(model):
""" Adjust the sparsity level for simple weighted models
with Gaussian weight models and Bernoulli adjacency matrices.
The variance of a Gaussian N(0,sigma) times a Bernoulli(rho) is
E[B*N] = 0
Var[B*N] = E[(B*N)**2] = rho*sigma^2 + (1-rho)*0 = rho*sigma^2
Hence the eigenvalues will be distributed in a complex disk of radius
\sqrt(N) * \sqrt(rho) * sigma
For this to be less than (1-delta), we have
\sqrt(rho) < (1-delta)/sqrt(N)/sigma
rho < (1-delta)**2 / N / sigma**2
"""
N = model['N']
imp_model = model['impulse']
weight_model = model['network']['weight']
graph_model = model['network']['graph']
delta = 0.3
maxeig = 1.0-delta
if graph_model['type'].lower() == 'erdos_renyi':
if weight_model['prior']['type'].lower() == 'gaussian':
# If we have a refractory bias on the diagonal weights then
# we can afford slightly stronger weights
if 'refractory_prior' in weight_model:
maxeig -= weight_model['refractory_prior']['mu']
sigma = weight_model['prior']['sigma']
stable_rho = maxeig**2/N/sigma**2
stable_rho = np.minimum(stable_rho, 1.0)
print "Setting sparsity to %.2f for stability." % stable_rho
graph_model['rho'] = stable_rho
elif graph_model['type'].lower() == 'sbm':
# Things are trickier in the SBM case because the entries in A
# are not iid. But, we can still make some approximations by
# thinking about the mean and variance within a single block, wherein
# the entries really are i.i.d. Then we scale the eigs of
# each block by N/R, as if the blocks were equal size and the
# interdependencies between blocks did not matter. Obviously,
# this is a hack.
R = graph_model['R']
if weight_model['type'].lower() == 'sbm':
sig_mu = weight_model['sigma_mu']
sig_w = weight_model['sigma_w']
elif weight_model['type'].lower() == 'gaussian':
sig_mu = 0.0
sig_w = weight_model['sigma']
else:
raise Exception("Unrecognized weight model for SBM graph: %s" % weight_model['type'])
# var_AW = 1./4. * (3.*sig_mu)**2 + sig_w**2
# mean_lam_max = sig_mu * np.sqrt(R) * N/float(R) + 3*sig_w
# sig_lam_max = np.sqrt(var_AW)
# ub_lam_max = mean_lam_max + 3*sig_lam_max
#
# var_B = (((1.0-mean_lam_max)/3.0)**2 - sig_w**2) / (3*sig_mu)**2
#
# print "Setting b0 to %.2f to achive sparsity of %.2f." % (graph_model['b0'],stable_rho)
#elif weight_model['type'].lower() == 'constant' and \
# imp_model['type'].lower() == 'basis':
# sigma = imp_model['sigma']
# maxeig = 0.7
#
# # TODO Figure out how sigma actually relates to the eigenvalues
# stable_rho = maxeig/N/sigma**2
# stable_rho = np.minimum(stable_rho, 1.0)
# print "Setting sparsity to %.2f for stability." % stable_rho
# graph_model['rho'] = stable_rho\
elif graph_model['type'].lower() == 'distance':
# It's hard to characterize this exactly, but suppose that we had an exact
# banded adjacency matrix where the -b-th lower diagonal to the +b-th upper diagonal
# are normally distributed, and the rest of the matrix is zero.
#
# The max eigenvalue of this matrix tends to grow proportionally to log N
# and b, and is scaled by the standard deviation of the weights, sigma.
# The mean refractory weight adds a bias to the max eigenvalue.
#
# To estimate the bandwidth (i.e. 2b in this example), suppose that the
# probability of connection p(A_n,n') decays exponentially with |n-n'| at
# length scale d. That is, when |n-n'| > d, the probability has decreased to
# about 1/3. Hence, at distance 2d, the probability of interaction is about 10%.
# Thus, let's say the bandwidth of this matrix is roughly 2*(2d) = 4d,
#
# So, given the bandwidth of 4d and the matrix size N, we will scale the weight
# distribution to hopefully achieve stability
b = 8.0 * graph_model['delta']
# Constant scaling factors
# max eig ~= mu_ref + .25*sigma_W * (b+2*log(N))
# So set sigma_W ~= 4*(1-mu_ref)/(b+2*log N)
if weight_model['type'].lower() == 'gaussian':
mu_ref = weight_model['refractory_prior']['mu']
sig_w = 4.0*(1.0-mu_ref)/(b+2.0*np.log(model['N']))
print "Setting sig_w to %.3f to ensure stability" % sig_w
weight_model['prior']['sigma'] = sig_w
else:
raise Exception("Unrecognized weight model for distance graph: %s" % weight_model['type'])
def check_stability(model, x, N):
"""
Check the stability of model parameters
"""
if model['network']['weight']['type'].lower() == 'gaussian':
Weff = x['net']['graph']['A'] * np.reshape(x['net']['weights']['W'], (N,N))
maxeig = np.amax(np.real(np.linalg.eig(Weff)[0]))
print "Max eigenvalue of Weff: %.2f" % maxeig
return maxeig < 1
else:
print "Check stability: unrecognized model type. Defaulting to true."
return True
def convert_model(from_popn, from_model, from_vars, to_popn, to_model, to_vars):
""" Convert from one model to another model of a different type
Generally this will involve projecting impulse responses, etc.
It's hairy business.
"""
# Idea: Get the state of the GLMs, e.g. the impulse responses, etc.
# Project those states onto the parameters of the to-model
N = from_popn.N
from_state = from_popn.eval_state(from_vars)
to_state = to_popn.eval_state(to_vars)
conv_vars = None
if from_model['impulse']['type'].lower() == 'basis':
if to_model['impulse']['type'].lower() == 'normalized' or \
to_model['impulse']['type'].lower() == 'dirichlet':
import copy
conv_vars = copy.deepcopy(to_vars)
# To convert from basis -> normalized, project the impulse
# responses onto the normalized basis, divide by the area
# under the curve to get the weight.
W = np.zeros((N,N))
for n2 in np.arange(N):
B = to_state['glms'][n2]['imp']['basis'].shape[1]
w_ir_n2 = np.zeros((N,B))
for n1 in np.arange(N):
# Solve a nonnegative least squares problem
(w_ir_n1n2p, residp) = nnls(to_state['glms'][n2]['imp']['basis'],
from_state['glms'][n2]['imp']['impulse'][n1,:])
(w_ir_n1n2n, residn) = nnls(to_state['glms'][n2]['imp']['basis'],
-1.0*from_state['glms'][n2]['imp']['impulse'][n1,:])
# Take the better of the two solutions
if residp < residn:
Wsgn = 1.0
w_ir_n1n2 = w_ir_n1n2p
else:
Wsgn = -1.0
w_ir_n1n2 = w_ir_n1n2n
# Normalized weights must be > 0, sum to 1
w_ir_n1n2 = w_ir_n1n2
w_ir_n1n2 = np.clip(w_ir_n1n2,0.001,np.Inf)
# Normalize the impulse response to get a weight
W[n1,n2] = Wsgn*np.sum(w_ir_n1n2)
# Set impulse response to normalized impulse response
w_ir_n2[n1,:] = w_ir_n1n2 / np.sum(w_ir_n1n2)
# Update to_vars
if to_model['impulse']['type'].lower() == 'normalized':
conv_vars['glms'][n2]['imp']['w_lng'] = np.log(w_ir_n2.flatten())
if to_model['impulse']['type'].lower() == 'dirichlet':
for n1 in range(N):
# Scale up the weights such that the average is preserved
alpha = to_popn.glm.imp_model.alpha
B = to_popn.glm.imp_model.B
conv_vars['glms'][n2]['imp']['g_%d' % n1] = alpha * B * w_ir_n2[n1,:]
# Update to_vars
conv_vars['net']['weights']['W'] = W.flatten()
# Threshold the adjacency matrix to start with the right level of sparsity
if 'rho' in to_model['network']['graph'].keys():
W_sorted = np.sort(np.abs(W.ravel()))
thresh = W_sorted[np.floor((1.0-2.0*to_model['network']['graph']['rho'])*(N**2-N)-N)]
conv_vars['net']['graph']['A'] = (np.abs(W) >= thresh).astype(np.int8)
else:
conv_vars['net']['graph']['A'] = np.ones((N,N), dtype=np.int8)
# Copy over the bias
for n in np.arange(N):
conv_vars['glms'][n]['bias']['bias'] = from_vars['glms'][n]['bias']['bias']
# Copy over the background params
if 'sharedtuningcurves' in to_model['latent'] and \
from_model['bkgd']['type'] == 'spatiotemporal':
convert_stimulus_filters_to_sharedtc(from_popn, from_model, from_vars,
to_popn, to_model, conv_vars)
return conv_vars
def convert_stimulus_filters_to_sharedtc(from_popn, from_model, from_vars, to_popn, to_model, to_vars):
"""
Convert a set of stimulus filters to a shared set of tuning curves
"""
# Get the spatial component of the stimulus filter for each neuron
N = from_popn.N
R = to_model['latent']['sharedtuningcurves']['R']
from_state = from_popn.eval_state(from_vars)
locs = np.zeros((N,2))
local_stim_xs = []
local_stim_ts = []
for n in range(N):
s_glm = from_state['glms'][n]
# to_state = to_popn.eval_state(to_vars)
assert 'stim_response_x' in s_glm['bkgd']
# Get the stimulus responses
stim_x = s_glm['bkgd']['stim_response_x']
stim_t = s_glm['bkgd']['stim_response_t']
loc_max = np.argmax(np.abs(stim_x))
if stim_x.ndim == 2:
locsi, locsj = np.unravel_index(loc_max, stim_x.shape)
locs[n,0], locs[n,1] = locsi.ravel(), locsj.ravel()
# # TODO: Test whether we have an issue with unraveling the data.
# locs[n,0], locs[n,1] = locsj.ravel(), locsi.ravel()
# Get the stimulus response in the vicinity of the mode
# Create a meshgrid of the correct shape, centered around the max
max_rb = to_model['latent']['latent_location']['location_prior']['max0']
max_ub = to_model['latent']['latent_location']['location_prior']['max1']
gsz = to_model['latent']['sharedtuningcurves']['spatial_shape']
gwidth = (np.array(gsz) - 1)//2
lb = max(0, locs[n,0]-gwidth[0])
rb = min(locs[n,0]-gwidth[0]+gsz[0], max_rb)
db = max(0, locs[n,1]-gwidth[1])
ub = min(locs[n,1]-gwidth[1]+gsz[1], max_ub)
grid = np.ix_(np.arange(lb, rb).astype(np.int),
np.arange(db, ub).astype(np.int))
# grid = grid.astype(np.int)
# Add this local filter to the list
local_stim_xs.append(stim_x[grid])
local_stim_ts.append(stim_t)
# Cluster the local stimulus filters
from sklearn.cluster import KMeans
flattened_filters_x = np.array(map(lambda f: f.ravel(), local_stim_xs))
flattened_filters_t = np.array(map(lambda f: f.ravel(), local_stim_ts))
km = KMeans(n_clusters=R)
km.fit(flattened_filters_x)
Y = km.labels_
print 'Filter cluster labels from kmeans: ', Y
# Initialize type based on stimulus filter
to_vars['latent']['sharedtuningcurve_provider']['Y'] = Y
# Initialize shared tuning curves (project onto the bases)
from pyglm.utils.basis import project_onto_basis
for r in range(R):
mean_filter_xr = flattened_filters_x[Y==r].mean(axis=0)
mean_filter_tr = flattened_filters_t[Y==r].mean(axis=0)
# TODO: Make sure the filters are being normalized properly!
# Project the mean filters onto the basis
to_vars['latent']['sharedtuningcurve_provider']['w_x'][:,r] = \
project_onto_basis(mean_filter_xr,
to_popn.glm.bkgd_model.spatial_basis).ravel()
# Temporal part of the filter
temporal_basis = to_popn.glm.bkgd_model.temporal_basis
t_temporal_basis = np.arange(temporal_basis.shape[0])
t_mean_filter_tr = np.linspace(0, temporal_basis.shape[0]-1, mean_filter_tr.shape[0])
interp_mean_filter_tr = np.interp(t_temporal_basis, t_mean_filter_tr, mean_filter_tr)
to_vars['latent']['sharedtuningcurve_provider']['w_t'][:,r] = \
project_onto_basis(interp_mean_filter_tr, temporal_basis).ravel()
# Initialize locations based on stimuls filters
to_vars['latent']['location_provider']['L'] = locs.ravel().astype(np.int)
| mit |
nvanheuverzwijn/naughty-chat | parsers.py | 2756 | def get_parser(parser_name):
"""
Try to instantiate a parser from the parser_name
parser_name: The name of the parser to instantiate.
throws: NameError, if the parser is not found
returns: A Parser object.
"""
try:
return globals()[parser_name]()
except KeyError as e:
raise NameError("The parser '"+parser_name+"' was not found. Is it properly defined in parsers.py? Is it correctly spelled?")
class Result(object):
"""
This object is the result of a parse operation
"""
_command_name = ""
_command_arguments = []
@property
def command_name(self):
return self._command_name
@command_name.setter
def command_name(self, value):
self._command_name = value
@property
def command_arguments(self):
return self._command_arguments
@command_arguments.setter
def command_arguments(self, value):
self._command_arguments = value
def __init__(self, command_name="", command_arguments=[]):
self.command_name = command_name
self.command_arguments = command_arguments
class Parser(object):
_trigger_parse_character = '/'
@property
def trigger_parse_character(self):
return self._trigger_parse_character
@trigger_parse_character.setter
def trigger_parse_character(self, value):
self._trigger_parse_character = value
def __init__(self, trigger_parse_character = "/"):
self.trigger_parse_character = trigger_parse_character
def parse(self, message):
"""
Parse a message and return a tuple of the command that should be executed in the module commands and it's arguments.
message: the message to parse
returns: (string to pass to commands.get_command; array of arguments)
"""
if len(message) == 0 or message[0] != self.trigger_parse_character:
return Result("Broadcast", [message])
else:
parts = message.split(' ')
for i, part in enumerate(parts[:]):
if(self._is_part_array(part)):
parts[i] = part.split(",")
return Result(parts[0][1:].title(), parts[1:])
def _is_part_array(self, part):
"""
Determine if part is should be treated as an array or not.
An array have the form of "first,second,last"
"""
if len(part) == 0 or part[0] == "," or part[-1] == "," or "," not in part:
return False
for i in range(1, len(part)-1):
if part[i] == "," and (part[i-1] == ' ' or part[i+1] == ' '):
return False
return True
#
# Example of parser.
#
class Standard(Parser):
def parse(self, message):
if cmd == "leave":
return Result("Exit")
return Result("Broadcast", message)
class Kronos(Parser):
def parse(self, message):
parts = message.split(' ')
if len(parts) != 0:
if parts[0] == "exit":
return Result("Exit")
if parts[0] == "rename" and len(parts) >= 2:
return Result("Rename", [parts[1]])
return Result("Broadcast", message)
| mit |
Seally/hamster-project | src/hamster-project-app/src/main/java/hamster/app/gui/ICommPortButton.java | 177 | package hamster.app.gui;
import gnu.io.CommPortIdentifier;
/**
* Created by sealc on 11/24/2015.
*/
public interface ICommPortButton {
CommPortIdentifier getPortID();
}
| mit |
hoangmle/crave-bundle-2015-07-22 | crave/src/lib/ConstraintPartition.cpp | 1584 | #include "../crave/ir/ConstraintPartition.hpp"
#include <ostream>
namespace crave {
template <typename ostream>
ostream& operator<<(ostream& os, const ConstraintPartition& cp) {
os << "[ ";
BOOST_FOREACH(ConstraintPtr c, cp) { os << c->name() << " "; }
os << "]";
os << std::flush;
return os;
}
template std::ostream& operator<<<std::ostream>(std::ostream& os, const ConstraintPartition& cp);
typedef ConstraintList::iterator iterator;
typedef ConstraintList::const_iterator const_iterator;
iterator ConstraintPartition::begin() { return constraints_.begin(); }
const_iterator ConstraintPartition::begin() const { return constraints_.begin(); }
iterator ConstraintPartition::end() { return constraints_.end(); }
const_iterator ConstraintPartition::end() const { return constraints_.end(); }
void ConstraintPartition::add(ConstraintPtr c) {
iterator ite = constraints_.begin();
while (ite != constraints_.end() && ((*ite)->id() > c->id())) ite++;
constraints_.insert(ite, c);
// only add hard constraints to singleVariableConstraintMap
if (!c->isSoft() && !c->isCover() && c->support_vars_.size() == 1) {
unsigned varID = (*(c->support_vars_.begin()));
singleVariableConstraintMap_[varID].push_back(c);
}
}
bool ConstraintPartition::containsVar(int id) const { return support_vars_.find(id) != support_vars_.end(); }
std::set<int> const& ConstraintPartition::supportSet() const { return support_vars_; }
std::map<int, ConstraintList> const& ConstraintPartition::singleVariableConstraintMap() const {
return singleVariableConstraintMap_;
}
}
| mit |
johnnygreen/laravel-api | src/migrations/2013_09_09_023108_create_permissions_table.php | 564 | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePermissionsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('permissions', function(Blueprint $table) {
$table->engine = 'MyISAM';
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('permissions');
}
} | mit |
vchelaru/FlatRedBall | FRBDK/Glue/Glue/Elements/VariableDefinition.cs | 5024 | using FlatRedBall.Glue.CodeGeneration.CodeBuilder;
using FlatRedBall.Glue.SaveClasses;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace FlatRedBall.Glue.Elements
{
#region Enums
public enum CsvInclusion
{
None = 0,
InThisElement = 1,
InBaseElements = 2,
InDerivedElements = 4,
InUnrelatedElements = 8,
InGlobalContent = 16,
AllInProject = InThisElement | InBaseElements | InDerivedElements | InUnrelatedElements | InGlobalContent,
}
#endregion
/// <summary>
/// Defines characteristics of a variable on an object for use by Glue when displaying the
/// variable.
/// </summary>
/// <remarks>
/// VariableDefinitions are used in the AssetTypeInfo class to either define new variables or
/// provide information about existing variables. This information can be used to improve how variables
/// are to be displayed by Glue. VariableDefinitions are a more-informative replacement of AssetTypeInfo's
/// ExtraVariablesPattern
/// </remarks>.
public class VariableDefinition
{
public string Name { get; set; }
public string Type { get; set; }
/// <summary>
/// The value of this variable on the backing class implementation.
/// This is not a forced default value. The default value will not be code-generated.
/// </summary>
public string DefaultValue { get; set; }
public string Category { get; set; }
/// <summary>
/// If true, Glue will not do the standard variable assignment. This should be true
/// for plugins that want to fully handle their own code generation for certain variables
/// </summary>
public bool UsesCustomCodeGeneration { get; set; }
/// <summary>
/// Func returning the assignment for a variable.
/// </summary>
[XmlIgnore]
[JsonIgnore]
// The second to last string is the name of the variable, which may be a tunneled variable
public Func<IElement, NamedObjectSave, ReferencedFileSave, string, string> CustomGenerationFunc;
/// <summary>
/// Action for filling the code block with the custom definition for a property.
/// </summary>
[XmlIgnore]
[JsonIgnore]
public Func<IElement, CustomVariable, string> CustomPropertySetFunc;
/// <summary>
/// A list of options which the user must pick from. Filling this list with
/// options prevents the user form freely entering values. This can be used for
/// functionality similar to enums.
/// </summary>
public List<string> ForcedOptions { get; set; } = new List<string>();
public double? MinValue { get; set; }
public double? MaxValue { get; set; }
// Vic says - maybe we'll need this? Not sure...
//public CsvInclusion PrimaryCsvInclusion { get; set; } = CsvInclusion.InThisElement;
//public CsvInclusion FallbackCsvInclusion { get; set; } = CsvInclusion.AllInProject;
[XmlIgnore]
[JsonIgnore]
public Func<IElement, NamedObjectSave, ReferencedFileSave, List<string>> CustomGetForcedOptionFunc;
public bool HasGetter { get; set; } = true;
[XmlIgnore]
[JsonIgnore]
public Type PreferredDisplayer { get; set; }
public override string ToString()
{
return Name + " (" + Type + ")";
}
public object GetCastedDefaultValue()
{
var toReturn = this.DefaultValue;
return GetCastedValueForType(this.Type, this.DefaultValue);
}
public static object GetCastedValueForType(string typeName, string value)
{
var toReturn = value;
if (typeName == "bool")
{
bool boolToReturn = false;
bool.TryParse(value, out boolToReturn);
return boolToReturn;
}
else if (typeName == "float")
{
float floatToReturn = 0.0f;
float.TryParse(value, out floatToReturn);
return floatToReturn;
}
else if (typeName == "int")
{
int intToReturn = 0;
int.TryParse(value, out intToReturn);
return intToReturn;
}
else if (typeName == "long")
{
long longToReturn = 0;
long.TryParse(value, out longToReturn);
return longToReturn;
}
else if (typeName == "double")
{
double doubleToReturn = 0.0;
double.TryParse(value, out doubleToReturn);
return doubleToReturn;
}
else
{
return toReturn;
}
}
}
}
| mit |
dlcs/elucidate-server | elucidate-server/src/main/java/com/digirati/elucidate/service/statistics/W3CAnnotationStatisticsPageService.java | 243 | package com.digirati.elucidate.service.statistics;
import com.digirati.elucidate.model.statistics.W3CStatisticsPage;
public interface W3CAnnotationStatisticsPageService extends AbstractAnnotationStatisticsPageService<W3CStatisticsPage> {
}
| mit |
will-gilbert/OSWf-OSWorkflow-fork | oswf/simulator/src/main/java/org/informagen/oswf/simulator/server/GraphvizServiceImpl.java | 7638 | package org.informagen.oswf.simulator.server;
/**
* From: http://stackoverflow.com/questions/4553316/gwt-image-from-database
*
* Here is the solution. First you should encode the byte array by using
*
* com.google.gwt.user.server.Base64Utils.toBase64(byte[]).
*
* But this method does not work for IE 7 and IE8 has 32kb limit. IE9 does
* not have this limit.
*
* Here is the client method ;
*
* public void onSuccess(String imageData) {
* Image image = new Image(imageData);
* RootPanel.get("image").add(image);
* }
*
*/
// Application - RPC
import org.informagen.oswf.simulator.rpc.GraphvizService;
import org.informagen.oswf.simulator.rpc.ServiceException;
// OSWf Core
import org.informagen.oswf.OSWfEngine;
import org.informagen.oswf.OSWfConfiguration;
import org.informagen.oswf.util.Graphviz;
import org.informagen.oswf.descriptors.WorkflowDescriptor;
// OSWf Default Implementations & Service Providers
import org.informagen.oswf.impl.DefaultOSWfEngine;
import org.informagen.oswf.impl.DefaultOSWfConfiguration;
import org.informagen.oswf.exceptions.WorkflowLoaderException;
import org.informagen.oswf.util.Base64;
// Nidi Graphviz For Java
import guru.nidi.graphviz.model.MutableGraph;
import guru.nidi.graphviz.parse.Parser;
import guru.nidi.graphviz.engine.Format;
// Java
import java.lang.StringBuffer;
import java.lang.Process;
import java.lang.Runtime;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
// Java IO
import java.io.File;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.FileWriter;
// Simple Logging Facade
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Google DI Annotation
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class GraphvizServiceImpl implements GraphvizService {
private static Logger logger = LoggerFactory.getLogger(GraphvizService.class);
private static Logger startupLogger = LoggerFactory.getLogger("StartupLogger");
private final String dotExecutable;
private OSWfConfiguration configuration;
@Inject
public GraphvizServiceImpl(@Named("executable.graphviz")String dotExecutable, OSWfConfiguration configuration) {
startupLogger.info("Configuring GraphvizService");
this.dotExecutable = dotExecutable;
this.configuration = configuration;
}
public String renderAsGraphviz(String workflowName) throws ServiceException {
return renderAsPNG(workflowName);
}
public String renderAsPNG(String workflowName) throws ServiceException {
String base64Image = null;
try {
String dot = createDotNotation(workflowName);
MutableGraph g = Parser.read(dot);
BufferedImage bi = guru.nidi.graphviz.engine.Graphviz.fromGraph(g).render(Format.PNG).toImage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", outputStream);
byte[] imageByteArray = outputStream.toByteArray();
base64Image = Base64.getInstance().encodeAsString(imageByteArray);
} catch (Exception exception) {
logger.error(exception.getMessage());
}
return base64Image;
}
public String renderAsSVG(String workflowName) throws ServiceException {
String base64Image = null;
try {
String dot = createDotNotation(workflowName);
MutableGraph g = Parser.read(dot);
String svg = guru.nidi.graphviz.engine.Graphviz.fromGraph(g).render(Format.SVG).toString();
byte[] imageByteArray = svg.getBytes();
base64Image = Base64.getInstance().encodeAsString(imageByteArray);
} catch (Exception exception) {
logger.error(exception.getMessage());
}
return base64Image;
}
public String createDotNotation(String workflowName) throws ServiceException {
String dot = null;
try {
WorkflowDescriptor wfd = configuration.getWorkflow(workflowName);
dot = new Graphviz(wfd).create();
} catch (Exception exception) {
logger.error(exception.getMessage());
}
return dot;
}
/*
public String renderAsGraphviz(String workflowName) throws ServiceException {
String base64Image = null;
File dotFile = null;
try {
String dot = createDotNotation(workflowName);
dotFile = writeDotToFile(dot);
// Render the DOT file as a PNG image; returned as a byte array
// Sadly there is no Java 'dot' implementation so we will
// have to rely on it being installed.
byte[] imageByteArray = createImageAsByteArray(dotFile, "png");
return Base64.getInstance().encodeAsString(imageByteArray);
} catch (Exception exception) {
logger.error(exception.getMessage());
} finally {
if(dotFile != null)
dotFile.delete();
}
return base64Image;
}
private File writeDotToFile(String dot) throws Exception {
// Use a system temporary file; Set it to autodelete when
// the JVM exists in case it doesn't get deleted here.
File file = File.createTempFile("tmp-", ".dot");
file.deleteOnExit();
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(dot);
} finally {
writer.close();
}
return file;
}
private byte[] createImageAsByteArray(File dotFile, String imageType) throws Exception {
// Build the 'dot' command line; 'dot -Tformat /path/to/file'
String command = new StringBuffer()
.append(dotExecutable)
.append(" ").append("-T").append(imageType)
.append(" ").append(dotFile.getAbsolutePath())
.toString()
;
// Execute the command, route stdout as an inputstream directly into a byte array
Process process = Runtime.getRuntime().exec(command);
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
BufferedInputStream inputStream = new BufferedInputStream(process.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int c;
while((c = inputStream.read()) != -1)
outputStream.write(c);
// Log any errors from the external process
String line = null;
while( (line = errReader.readLine()) != null)
logger.error(line);
int result = process.waitFor();
// We should end up with a normal termination and a non-zero length output stream
if(result != 0 || outputStream.size() == 0)
logger.error("There was an error running Graphviz using " + dotFile.toString());
// Garbage Collection hint
process = null;
// Return the image as a byte array
return outputStream.toByteArray();
}
*/
}
| mit |
etraiger/PCWG | pcwg_tool.py | 171416 | from Tkinter import *
from tkFileDialog import *
import tkSimpleDialog
import tkMessageBox
from dataset import getSeparatorValue
from dataset import getDecimalValue
import Analysis
import configuration
import datetime
import os
import os.path
import pandas as pd
import dateutil
columnSeparator = "|"
filterSeparator = "#"
datePickerFormat = "%Y-%m-%d %H:%M"# "%d-%m-%Y %H:%M"
datePickerFormatDisplay = "[dd-mm-yyyy hh:mm]"
version = "0.5.9 (Beta)"
ExceptionType = Exception
#ExceptionType = None #comment this line before release
pcwg_inner_ranges = {'A': {'LTI': 0.08, 'UTI': 0.12, 'LSh': 0.05, 'USh': 0.25},
'B': {'LTI': 0.05, 'UTI': 0.09, 'LSh': 0.05, 'USh': 0.25},
'C': {'LTI': 0.1, 'UTI': 0.14, 'LSh': 0.1, 'USh': 0.3}}
def getDateFromEntry(entry):
if len(entry.get()) > 0:
return datetime.datetime.strptime(entry.get(), datePickerFormat)
else:
return None
def getBoolFromText(text):
if text == "True":
return True
elif text == "False":
return False
else:
raise Exception("Cannot convert Text to Boolean: %s" % text)
def SelectFile(parent, defaultextension=None):
if len(preferences.workSpaceFolder) > 0:
return askopenfilename(parent=parent, initialdir=preferences.workSpaceFolder, defaultextension=defaultextension)
else:
return askopenfilename(parent=parent, defaultextension=defaultextension)
def encodePowerLevelValueAsText(windSpeed, power):
return "%f%s%f" % (windSpeed, columnSeparator, power)
def extractPowerLevelValuesFromText(text):
items = text.split(columnSeparator)
windSpeed = float(items[0])
power = float(items[1])
return (windSpeed, power)
def extractREWSLevelValuesFromText(text):
items = text.split(columnSeparator)
height = float(items[0])
windSpeed = items[1].strip()
windDirection = items[2].strip()
return (height, windSpeed, windDirection)
def encodeREWSLevelValuesAsText(height, windSpeed, windDirection):
return "{hight:.04}{sep}{windspeed}{sep}{windDir}".format(hight = height, sep = columnSeparator, windspeed = windSpeed, windDir = windDirection)
def extractShearMeasurementValuesFromText(text):
items = text.split(columnSeparator)
height = float(items[0])
windSpeed = items[1].strip()
return (height, windSpeed)
def encodeShearMeasurementValuesAsText(height, windSpeed):
return "{height:.04}{sep}{windspeed}{sep}".format(height = height, sep = columnSeparator, windspeed = windSpeed)
def extractCalibrationDirectionValuesFromText(text):
items = text.split(columnSeparator)
direction = float(items[0])
slope = float(items[1].strip())
offset = float(items[2].strip())
active = getBoolFromText(items[3].strip())
return (direction, slope, offset, active)
def encodeCalibrationDirectionValuesAsText(direction, slope, offset, active):
return "%0.4f%s%0.4f%s%0.4f%s%s" % (direction, columnSeparator, slope, columnSeparator, offset, columnSeparator, active)
def extractExclusionValuesFromText(text):
items = text.split(columnSeparator)
startDate = pd.to_datetime(items[0].strip(), dayfirst =True)
endDate = pd.to_datetime(items[1].strip(), dayfirst =True)
active = getBoolFromText(items[2].strip())
return (startDate, endDate, active)
def encodeFilterValuesAsText(column, value, filterType, inclusive, active):
return "{column}{sep}{value}{sep}{FilterType}{sep}{inclusive}{sep}{active}".format(column = column, sep = columnSeparator,value = value, FilterType = filterType, inclusive =inclusive, active = active)
def encodeRelationshipFilterValuesAsText(relationshipFilter):
text = ""
for clause in relationshipFilter.clauses:
text += encodeFilterValuesAsText(clause.column,clause.value, clause.filterType, clause.inclusive, "" )
text += " #" + relationshipFilter.conjunction + "# "
return text[:-5]
def extractRelationshipFilterFromText(text):
try:
clauses = []
for i, subFilt in enumerate(text.split(filterSeparator)):
if i%2 == 0:
items = subFilt.split(columnSeparator)
column = items[0].strip()
value = float(items[1].strip())
filterType = items[2].strip()
inclusive = getBoolFromText(items[3].strip())
clauses.append(configuration.Filter(True,column,filterType,inclusive,value))
else:
if len(subFilt.strip()) > 1:
conjunction = subFilt.strip()
return configuration.RelationshipFilter(True,conjunction,clauses)
except Exception as ex:
raise Exception("Cannot parse values from filter text: %s (%s)" % (text, ex.message))
def extractFilterValuesFromText(text):
try:
items = text.split(columnSeparator)
column = items[0].strip()
value = float(items[1].strip())
filterType = items[2].strip()
inclusive = getBoolFromText(items[3].strip())
active = getBoolFromText(items[4].strip())
return (column, value, filterType, inclusive, active)
except Exception as ex:
raise Exception("Cannot parse values from filter text: %s (%s)" % (text, ex.message))
def encodeExclusionValuesAsText(startDate, endDate, active):
return "%s%s%s%s%s" % (startDate, columnSeparator, endDate, columnSeparator, active)
def intSafe(text, valueIfBlank = 0):
try:
return int(text)
except:
return valueIfBlank
def floatSafe(text, valueIfBlank = 0.):
try:
return float(text)
except:
return valueIfBlank
class WindowStatus:
def __nonzero__(self):
return True
def __init__(self, gui):
self.gui = gui
def addMessage(self, message):
self.gui.addMessage(message)
class ValidationResult:
def __init__(self, valid, message = "", permitInput = True):
self.valid = valid
self.message = message
self.permitInput = permitInput
class ValidateBase:
def __init__(self, master, createMessageLabel = True):
self.title = ''
self.CMD = (master.register(self.validationHandler),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
if createMessageLabel:
self.messageLabel = Label(master, text="", fg="red")
else:
self.messageLabel = None
self.executeValidation("", "", "")
def link(self, control):
self.control = control
def setMessage(self, message):
if self.messageLabel != None:
self.messageLabel['text'] = message
def validationHandler(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name):
return self.executeValidation(text, value_if_allowed, prior_value)
def executeValidation(self, text, value_if_allowed, prior_value):
if len(value_if_allowed) > 0:
permitInput = self.mask(text, value_if_allowed)
else:
permitInput = True
if permitInput:
result = self.validate(value_if_allowed)
else:
result = self.validate(prior_value)
self.valid = result.valid
try:
if self.valid:
self.setMessage("")
else:
self.setMessage(result.message)
except Exception as ex:
print "Error reporting validation message: %s" % ex.message
return permitInput
def mask(self, text, value):
return True
class ValidateNonNegativeInteger(ValidateBase):
def validate(self, value):
message = "Value must be a positive integer"
try:
val = int(value)
return ValidationResult(int(value) >= 0, message)
except ValueError:
return ValidationResult(False, message)
def mask(self, text, value):
return (text in '0123456789')
class ValidatePositiveInteger(ValidateBase):
def validate(self, value):
message = "Value must be a positive integer"
try:
val = int(value)
return ValidationResult(int(value) > 0, message)
except ValueError:
return ValidationResult(False, message)
def mask(self, text, value):
return (text in '0123456789')
class ValidateFloat(ValidateBase):
def validate(self, value):
message = "Value must be a float"
try:
val = float(value)
return ValidationResult(True, message)
except ValueError:
return ValidationResult(False, message)
def mask(self, text, value):
return (text in '0123456789.-')
class ValidateNonNegativeFloat(ValidateBase):
def validate(self, value):
message = "Value must be a non-negative float"
try:
val = float(value)
return ValidationResult(val >= 0, message)
except ValueError:
return ValidationResult(False, message)
def mask(self, text, value):
return (text in '0123456789.')
class ValidatePositiveFloat(ValidateBase):
def validate(self, value):
message = "Value must be a positive float"
try:
val = float(value)
return ValidationResult(val > 0, message)
except ValueError:
return ValidationResult(False, message)
def mask(self, text, value):
return (text in '0123456789.-')
class ValidateSpecifiedPowerDeviationMatrix(ValidateBase):
def __init__(self, master, activeVariable):
self.activeVariable = activeVariable
self.activeVariable.trace("w", self.refreshValidation)
ValidateBase.__init__(self, master)
def refreshValidation(self, *args):
self.control.tk.call(self.control._w, 'validate')
def validate(self, value):
active = bool(self.activeVariable.get())
message = "Value not specified"
if active:
return ValidationResult(len(value) > 0, message)
else:
return ValidationResult(True, "")
class ValidateSpecifiedPowerCurve(ValidateBase):
def __init__(self, master, powerCurveModeVariable):
self.powerCurveModeVariable = powerCurveModeVariable
self.powerCurveModeVariable.trace("w", self.refreshValidation)
ValidateBase.__init__(self, master)
def refreshValidation(self, *args):
self.control.tk.call(self.control._w, 'validate')
def validate(self, value):
powerCurveMode = self.powerCurveModeVariable.get().lower()
message = "Value not specified"
if powerCurveMode == "specified":
return ValidationResult(len(value) > 0, message)
else:
return ValidationResult(True, message)
class ValidateAnalysisFilePath(ValidateBase):
def validate(self, value):
message = "Value not specified"
return ValidationResult(len(value) > 0, message)
class ValidateNominalWindSpeedDistribution(ValidateBase):
def validate(self, value):
message = "Value not specified"
return ValidationResult(len(value) >= 0, message)
class ValidateDatasetFilePath(ValidateBase):
def validate(self, value):
message = "Value not specified"
return ValidationResult(len(value) > 0, message)
class ValidateTimeSeriesFilePath(ValidateBase):
def validate(self, value):
message = "Value not specified"
return ValidationResult(len(value) > 0, message)
class ValidateNotBlank(ValidateBase):
def validate(self, value):
message = "Value not specified"
return ValidationResult(len(value) > 0, message)
class ValidatePowerCurveLevels:
def __init__(self, master, listbox):
self.listbox = listbox
self.messageLabel = Label(master, text="", fg="red")
self.validate()
def validate(self):
self.valid = True
message = ""
if self.listbox.size() < 3:
self.valid = self.valid and False
message = "At least three levels must be specified"
dictionary = {}
duplicateCount = 0
for i in range(self.listbox.size()):
item = self.listbox.get(i)
if item in dictionary:
duplicateCount += 1
else:
dictionary[item] = item
if duplicateCount> 0:
self.valid = self.valid and False
message = "Duplicate level specified"
self.messageLabel['text'] = message
class ValidateREWSProfileLevels:
def __init__(self, master, listbox):
self.listbox = listbox
self.messageLabel = Label(master, text="", fg="red")
self.validate()
def validate(self):
self.valid = True
message = ""
if self.listbox.size() < 3:
self.valid = self.valid and False
message = "At least three levels must be specified"
dictionary = {}
duplicateCount = 0
for i in range(self.listbox.size()):
item = self.listbox.get(i)
if item in dictionary:
duplicateCount += 1
else:
dictionary[item] = item
if duplicateCount> 0:
self.valid = self.valid and False
message = "Duplicate level specified"
self.messageLabel['text'] = message
class ValidateDatasets:
def __init__(self, master, listbox):
self.listbox = listbox
self.messageLabel = Label(master, text="", fg="red")
self.validate()
self.title = "Datasets Validation"
def validate(self):
self.valid = True
message = ""
if self.listbox.size() < 1:
self.valid = self.valid and False
message = "At least one dataset must be specified"
dictionary = {}
duplicateCount = 0
for i in range(self.listbox.size()):
item = self.listbox.get(i)
if item in dictionary:
duplicateCount += 1
else:
dictionary[item] = item
if duplicateCount> 0:
self.valid = self.valid and False
message = "Duplicate dataset specified"
self.messageLabel['text'] = message
class VariableEntry:
def __init__(self, variable, entry, tip):
self.variable = variable
self.entry = entry
self.pickButton = None
self.tip = tip
def clearTip(self):
self.setTip("")
def setTipNotRequired(self):
self.setTip("Not Required")
def setTip(self, text):
if self.tip != None:
self.tip['text'] = text
def get(self):
return self.variable.get()
def set(self, value):
return self.variable.set(value)
def configure(self, state):
self.entry.configure(state = state)
if self.pickButton != None:
self.pickButton.configure(state = state)
def bindPickButton(self, pickButton):
self.pickButton = pickButton
class ListBoxEntry(VariableEntry):
def __init__(self, listbox, scrollbar, tip):
self.scrollbar = scrollbar
self.listbox = listbox
self.tip = tip
def addToShowHide(self,showHide):
if showHide != None:
showHide.addControl(self.listbox )
showHide.addControl(self.tip)
showHide.addControl(self.scrollbar )
def error(self):
raise Exception("Not possible with listbox object")
def get(self):
self.error()
def set(self, value):
self.error()
def configure(self, state):
self.error()
def bindPickButton(self, pickButton):
self.error()
class ShowHideCommand:
def __init__(self, master):
self.controls = []
self.visible = True
self.button = Button(master, command = self.showHide, height=1)
self.setButtonText()
def addControl(self, control):
if control != None:
self.controls.append(control)
def setButtonText(self):
if self.visible:
self.button['text'] = "Hide"
else:
self.button['text'] = "Show"
def showHide(self):
self.visible = not self.visible
self.setButtonText()
for control in self.controls:
if self.visible:
control.grid()
else:
control.grid_remove()
def hide(self):
if self.visible:
self.showHide()
def show(self):
if not self.visible:
self.showHide()
class SetFileSaveAsCommand:
def __init__(self, master, variable):
self.master = master
self.variable = variable
def __call__(self):
fileName = asksaveasfilename(parent=self.master,defaultextension=".xml", initialdir=preferences.workSpaceFolder)
if len(fileName) > 0: self.variable.set(fileName)
class SetFileOpenCommand:
def __init__(self, master, variable, basePathVariable = None):
self.master = master
self.variable = variable
self.basePathVariable = basePathVariable
def __call__(self):
fileName = SelectFile(parent=self.master,defaultextension=".xml")
if len(fileName) > 0:
if self.basePathVariable != None:
relativePath = configuration.RelativePath(self.basePathVariable.get())
self.variable.set(relativePath.convertToRelativePath(fileName))
else:
self.variable.set(fileName)
class BaseDialog(tkSimpleDialog.Dialog):
def __init__(self, master, status):
self.status = status
self.titleColumn = 0
self.labelColumn = 1
self.inputColumn = 2
self.buttonColumn = 3
self.secondButtonColumn = 4
self.tipColumn = 5
self.messageColumn = 6
self.showHideColumn = 7
self.validations = []
self.row = 0
self.listboxEntries = {}
tkSimpleDialog.Dialog.__init__(self, master)
def prepareColumns(self, master):
master.columnconfigure(self.titleColumn, pad=10, weight = 0)
master.columnconfigure(self.labelColumn, pad=10, weight = 0)
master.columnconfigure(self.inputColumn, pad=10, weight = 1)
master.columnconfigure(self.buttonColumn, pad=10, weight = 0)
master.columnconfigure(self.secondButtonColumn, pad=10, weight = 0)
master.columnconfigure(self.tipColumn, pad=10, weight = 0)
master.columnconfigure(self.messageColumn, pad=10, weight = 0)
def addDatePickerEntry(self, master, title, validation, value, width = None, showHideCommand = None):
if value != None:
if type(value) == str:
textValue = value
else:
textValue = value.strftime(datePickerFormat)
else:
textValue = None
entry = self.addEntry(master, title + " " + datePickerFormatDisplay, validation, textValue, width = width, showHideCommand = showHideCommand)
entry.entry.config(state=DISABLED)
pickButton = Button(master, text=".", command = DatePicker(self, entry, datePickerFormat), width=3, height=1)
pickButton.grid(row=(self.row-1), sticky=N, column=self.inputColumn, padx = 160)
clearButton = Button(master, text="x", command = ClearEntry(entry), width=3, height=1)
clearButton.grid(row=(self.row-1), sticky=W, column=self.inputColumn, padx = 133)
if showHideCommand != None:
showHideCommand.addControl(pickButton)
showHideCommand.addControl(clearButton)
entry.bindPickButton(pickButton)
return entry
def addPickerEntry(self, master, title, validation, value, width = None, showHideCommand = None):
entry = self.addEntry(master, title, validation, value, width = width, showHideCommand = showHideCommand)
pickButton = Button(master, text=".", command = ColumnPicker(self, entry), width=5, height=1)
pickButton.grid(row=(self.row-1), sticky=E+N, column=self.buttonColumn)
if showHideCommand != None:
showHideCommand.addControl(pickButton)
entry.bindPickButton(pickButton)
return entry
def addOption(self, master, title, options, value, showHideCommand = None):
label = Label(master, text=title)
label.grid(row=self.row, sticky=W, column=self.labelColumn)
variable = StringVar(master, value)
option = apply(OptionMenu, (master, variable) + tuple(options))
option.grid(row=self.row, column=self.inputColumn, sticky=W)
if showHideCommand != None:
showHideCommand.addControl(label)
showHideCommand.addControl(option)
self.row += 1
return variable
def addListBox(self, master, title, showHideCommand = None):
scrollbar = Scrollbar(master, orient=VERTICAL)
tipLabel = Label(master, text="")
tipLabel.grid(row = self.row, sticky=W, column=self.tipColumn)
lb = Listbox(master, yscrollcommand=scrollbar, selectmode=EXTENDED, height=3)
self.listboxEntries[title] = ListBoxEntry(lb,scrollbar,tipLabel)
self.listboxEntries[title].addToShowHide(showHideCommand)
self.row += 1
self.listboxEntries[title].scrollbar.configure(command=self.listboxEntries[title].listbox.yview)
self.listboxEntries[title].scrollbar.grid(row=self.row, sticky=W+N+S, column=self.titleColumn)
return self.listboxEntries[title]
def addCheckBox(self, master, title, value, showHideCommand = None):
label = Label(master, text=title)
label.grid(row=self.row, sticky=W, column=self.labelColumn)
variable = IntVar(master, value)
checkButton = Checkbutton(master, variable=variable)
checkButton.grid(row=self.row, column=self.inputColumn, sticky=W)
if showHideCommand != None:
showHideCommand.addControl(label)
showHideCommand.addControl(checkButton)
self.row += 1
return variable
def addTitleRow(self, master, title, showHideCommand = None):
Label(master, text=title).grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
#add dummy label to stop form shrinking when validation messages hidden
Label(master, text = " " * 70).grid(row=self.row, sticky=W, column=self.messageColumn)
if showHideCommand != None:
showHideCommand.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
def addEntry(self, master, title, validation, value, width = None, showHideCommand = None):
variable = StringVar(master, value)
label = Label(master, text=title)
label.grid(row = self.row, sticky=W, column=self.labelColumn)
tipLabel = Label(master, text="")
tipLabel.grid(row = self.row, sticky=W, column=self.tipColumn)
if validation != None:
validation.messageLabel.grid(row = self.row, sticky=W, column=self.messageColumn)
validation.title = title
self.validations.append(validation)
validationCommand = validation.CMD
else:
validationCommand = None
entry = Entry(master, textvariable=variable, validate = 'key', validatecommand = validationCommand, width = width)
entry.grid(row=self.row, column=self.inputColumn, sticky=W)
if showHideCommand != None:
showHideCommand.addControl(label)
showHideCommand.addControl(entry)
showHideCommand.addControl(tipLabel)
if validation != None:
showHideCommand.addControl(validation.messageLabel)
if validation != None:
validation.link(entry)
self.row += 1
return VariableEntry(variable, entry, tipLabel)
def addFileSaveAsEntry(self, master, title, validation, value, width = 60, showHideCommand = None):
variable = self.addEntry(master, title, validation, value, width, showHideCommand)
button = Button(master, text="...", command = SetFileSaveAsCommand(master, variable), height=1)
button.grid(row=(self.row - 1), sticky=E+W, column=self.buttonColumn)
if showHideCommand != None:
showHideCommand.addControl(button)
return variable
def addFileOpenEntry(self, master, title, validation, value, basePathVariable = None, width = 60, showHideCommand = None):
variable = self.addEntry(master, title, validation, value, width, showHideCommand)
button = Button(master, text="...", command = SetFileOpenCommand(master, variable, basePathVariable), height=1)
button.grid(row=(self.row - 1), sticky=E+W, column=self.buttonColumn)
if showHideCommand != None:
showHideCommand.addControl(button)
return variable
def validate(self):
valid = True
message = ""
for validation in self.validations:
if not validation.valid:
if not isinstance(validation,ValidateDatasets):
message += "%s (%s)\r" % (validation.title, validation.messageLabel['text'])
else:
message += "Datasets error. \r"
valid = False
if not valid:
tkMessageBox.showwarning(
"Validation errors",
"Illegal values, please review error messages and try again:\r %s" % message
)
return 0
else:
return 1
class ClearEntry:
def __init__(self, entry):
self.entry = entry
def __call__(self):
self.entry.set("")
class PowerCurveLevelDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = self.text.split("|")
windSpeed = float(items[0])
power = float(items[1].strip())
else:
windSpeed = 0.0
power = 0.0
self.addTitleRow(master, "Power Curve Level Settings:")
self.windSpeed = self.addEntry(master, "Wind Speed:", ValidatePositiveFloat(master), windSpeed)
self.power = self.addEntry(master, "Power:", ValidateFloat(master), power)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
self.text = "%f|%f" % (float(self.windSpeed.get()), float(self.power.get()))
if self.isNew:
self.status.addMessage("Power curve level created")
else:
self.status.addMessage("Power curve level updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class FilterDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def ShowColumnPicker(self, parentDialog, pick, selectedColumn):
return self.parent.ShowColumnPicker(parentDialog, pick, selectedColumn)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = extractFilterValuesFromText(self.text)
column = items[0]
value = items[1]
filterType = items[2]
inclusive = items[3]
active = items[4]
else:
column = ''
value = 0.0
filterType = 'Below'
inclusive = False
active = False
self.addTitleRow(master, "Filter Settings:")
self.column = self.addPickerEntry(master, "Column:", ValidateNotBlank(master), column)
self.value = self.addEntry(master, "Value:", ValidateFloat(master), value)
self.filterType = self.addOption(master, "Filter Type:", ["Below", "Above", "AboveOrBelow"], filterType)
if inclusive:
self.inclusive = self.addCheckBox(master, "Inclusive:", 1)
else:
self.inclusive = self.addCheckBox(master, "Inclusive:", 0)
if active:
self.active = self.addCheckBox(master, "Active:", 1)
else:
self.active = self.addCheckBox(master, "Active:", 0)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
if int(self.active.get()) == 1:
active = True
else:
active = False
if int(self.inclusive.get()) == 1:
inclusive = True
else:
inclusive = False
self.text = encodeFilterValuesAsText(self.column.get(), float(self.value.get()), self.filterType.get(), inclusive, active)
if self.isNew:
self.status.addMessage("Filter created")
else:
self.status.addMessage("Filter updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class CalibrationFilterDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def ShowColumnPicker(self, parentDialog, pick, selectedColumn):
return self.parent.ShowColumnPicker(parentDialog, pick, selectedColumn)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = extractFilterValuesFromText(self.text)
column = items[0]
value = items[1]
calibrationFilterType = items[2]
inclusive = items[3]
active = items[4]
else:
column = ''
value = 0.0
calibrationFilterType = 'Below'
inclusive = False
active = False
self.addTitleRow(master, "Calibration Filter Settings:")
self.column = self.addPickerEntry(master, "Column:", ValidateNotBlank(master), column)
self.value = self.addEntry(master, "Value:", ValidateFloat(master), value)
self.calibrationFilterType = self.addOption(master, "Calibration Filter Type:", ["Below", "Above", "AboveOrBelow"], calibrationFilterType)
if inclusive:
self.inclusive = self.addCheckBox(master, "Inclusive:", 1)
else:
self.inclusive = self.addCheckBox(master, "Inclusive:", 0)
if active:
self.active = self.addCheckBox(master, "Active:", 1)
else:
self.active = self.addCheckBox(master, "Active:", 0)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
if int(self.active.get()) == 1:
active = True
else:
active = False
if int(self.inclusive.get()) == 1:
inclusive = True
else:
inclusive = False
self.text = encodeFilterValuesAsText(self.column.get(), float(self.value.get()), self.calibrationFilterType.get(), inclusive, active)
if self.isNew:
self.status.addMessage("Calibration Filter created")
else:
self.status.addMessage("Calibration Filter updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class ExclusionDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
#dummy label to force width
Label(master, text=" " * 275).grid(row = self.row, sticky=W, column=self.titleColumn, columnspan = 8)
self.row += 1
if not self.isNew:
items = extractExclusionValuesFromText(self.text)
startDate = items[0]
endDate = items[1]
active = items[2]
else:
startDate = None
endDate = None
active = False
self.addTitleRow(master, "Exclusion Settings:")
self.startDate = self.addDatePickerEntry(master, "Start Date:", ValidateNotBlank(master), startDate)
self.endDate = self.addDatePickerEntry(master, "End Date:", ValidateNotBlank(master), endDate)
if active:
self.active = self.addCheckBox(master, "Active:", 1)
else:
self.active = self.addCheckBox(master, "Active:", 0)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
if int(self.active.get()) == 1:
active = True
else:
active = False
self.text = encodeExclusionValuesAsText(self.startDate.get(), self.endDate.get().strip(), active)
if self.isNew:
self.status.addMessage("Exclusion created")
else:
self.status.addMessage("Exclusion updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class CalibrationDirectionDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = extractCalibrationDirectionValuesFromText(self.text)
direction = items[0]
slope = items[1]
offset = items[2]
active = items[3]
else:
direction = 0.0
slope = 0.0
offset = 0.0
active = False
self.addTitleRow(master, "Calibration Direction Settings:")
self.direction = self.addEntry(master, "Direction:", ValidateFloat(master), direction)
self.slope = self.addEntry(master, "Slope:", ValidateFloat(master), slope)
self.offset = self.addEntry(master, "Offset:", ValidateFloat(master), offset)
if active:
self.active = self.addCheckBox(master, "Active:", 1)
else:
self.active = self.addCheckBox(master, "Active:", 0)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
if int(self.active.get()) == 1:
active = True
else:
active = False
self.text = encodeCalibrationDirectionValuesAsText(float(self.direction.get()), float(self.slope.get().strip()), float(self.offset.get().strip()), active)
if self.isNew:
self.status.addMessage("Calibration direction created")
else:
self.status.addMessage("Calibration direction updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class ShearMeasurementDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def ShowColumnPicker(self, parentDialog, pick, selectedColumn):
return self.parent.ShowColumnPicker(parentDialog, pick, selectedColumn)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = extractShearMeasurementValuesFromText(self.text)
height = items[0]
windSpeed = items[1]
else:
height = 0.0
windSpeed = ""
self.addTitleRow(master, "Shear measurement:")
self.height = self.addEntry(master, "Height:", ValidatePositiveFloat(master), height)
self.windSpeed = self.addPickerEntry(master, "Wind Speed:", ValidateNotBlank(master), windSpeed, width = 60)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
self.text = encodeShearMeasurementValuesAsText(float(self.height.get()), self.windSpeed.get().strip())
if self.isNew:
self.status.addMessage("Shear measurement created")
else:
self.status.addMessage("Shear measurement updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class REWSProfileLevelDialog(BaseDialog):
def __init__(self, master, status, callback, text = None, index = None):
self.callback = callback
self.text = text
self.index = index
self.callback = callback
self.isNew = (text == None)
BaseDialog.__init__(self, master, status)
def ShowColumnPicker(self, parentDialog, pick, selectedColumn):
return self.parent.ShowColumnPicker(parentDialog, pick, selectedColumn)
def body(self, master):
self.prepareColumns(master)
if not self.isNew:
items = extractREWSLevelValuesFromText(self.text)
height = items[0]
windSpeed = items[1]
windDirection = items[2]
else:
height = 0.0
windSpeed = ""
windDirection = ""
self.addTitleRow(master, "REWS Level Settings:")
self.height = self.addEntry(master, "Height:", ValidatePositiveFloat(master), height)
self.windSpeed = self.addPickerEntry(master, "Wind Speed:", ValidateNotBlank(master), windSpeed, width = 60)
self.windDirection = self.addPickerEntry(master, "Wind Direction:", None, windDirection, width = 60)
#dummy label to indent controls
Label(master, text=" " * 5).grid(row = (self.row-1), sticky=W, column=self.titleColumn)
def apply(self):
self.text = encodeREWSLevelValuesAsText(float(self.height.get()), self.windSpeed.get().strip(), self.windDirection.get().strip())
if self.isNew:
self.status.addMessage("Rotor level created")
else:
self.status.addMessage("Rotor level updated")
if self.index== None:
self.callback(self.text)
else:
self.callback(self.text, self.index)
class BaseConfigurationDialog(BaseDialog):
def __init__(self, master, status, callback, config, index = None):
self.index = index
self.callback = callback
self.isSaved = False
self.isNew = config.isNew
self.config = config
if not self.isNew:
self.originalPath = config.path
else:
self.originalPath = None
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
self.generalShowHide = ShowHideCommand(master)
#add spacer labels
spacer = " "
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.titleColumn)
Label(master, text=spacer * 40).grid(row = self.row, sticky=W, column=self.labelColumn)
Label(master, text=spacer * 80).grid(row = self.row, sticky=W, column=self.inputColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.buttonColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.secondButtonColumn)
Label(master, text=spacer * 40).grid(row = self.row, sticky=W, column=self.messageColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.showHideColumn)
self.row += 1
self.addTitleRow(master, "General Settings:", self.generalShowHide)
if self.config.isNew:
path = asksaveasfilename(parent=self.master,defaultextension=".xml", initialfile="%s.xml" % self.getInitialFileName(), title="Save New Config", initialdir=preferences.workSpaceFolder)
else:
path = self.config.path
self.filePath = self.addFileSaveAsEntry(master, "Configuration XML File Path:", ValidateDatasetFilePath(master), path, showHideCommand = self.generalShowHide)
self.addFormElements(master)
def getInitialFileName(self):
return "Config"
def validate(self):
if BaseDialog.validate(self) == 0: return
if self.originalPath != None and self.filePath.get() != self.originalPath and os.path.isfile(self.filePath.get()):
result = tkMessageBox.askokcancel(
"File Overwrite Confirmation",
"Specified file path already exists, do you wish to overwrite?")
if not result: return 0
return 1
def apply(self):
self.config.path = self.filePath.get()
self.setConfigValues()
self.config.save()
self.isSaved = True
if self.isNew:
self.status.addMessage("Config created")
else:
self.status.addMessage("Config updated")
if self.index == None:
self.callback(self.config.path)
else:
self.callback(self.config.path, self.index)
class ColumnPickerDialog(BaseDialog):
def __init__(self, master, status, callback, availableColumns, column):
self.callback = callback
self.availableColumns = availableColumns
self.column = column
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
if len(self.availableColumns) > 0:
self.column = self.addOption(master, "Select Column:", self.availableColumns, self.column)
def apply(self):
self.callback(self.column.get())
class DatePickerDialog(BaseDialog):
def __init__(self, master, status, callback, date, dateFormat):
self.callback = callback
self.date = date
self.dateFormat = dateFormat
BaseDialog.__init__(self, master, status)
def validate(self):
valid = False
if type(self.getDate()) == datetime.datetime:
valid = True
if valid:
return 1
else:
return 0
def body(self, master):
thisYear = datetime.datetime.today().year
if self.date != None:
selectedDay = self.date.day
selectedMonth = self.date.month
selectedYear = self.date.year
selectedHour = self.date.hour
selectedMinute = self.date.minute
else:
selectedDay = None
selectedMonth = None
selectedYear = None
selectedHour = None
selectedMinute = None
self.parseButton = Button(master, text="Parse Clipboard", command = ParseClipBoard(master, self.dateFormat, self.parseClipBoard), width=30, height=1)
self.parseButton.grid(row=self.row, column=self.titleColumn, columnspan = 8)
self.row += 1
spacer = Label(master, text=" " * 60)
spacer.grid(row=self.row, column=self.titleColumn, columnspan = 4)
spacer = Label(master, text=" " * 60)
spacer.grid(row=self.row, column=self.secondButtonColumn, columnspan = 4)
self.row += 1
self.day = self.addEntry(master, "Day:", ValidateNonNegativeInteger(master), selectedDay, showHideCommand = None)
self.month = self.addEntry(master, "Month:", ValidateNonNegativeInteger(master), selectedMonth, showHideCommand = None)
self.year = self.addEntry(master, "Year:", ValidateNonNegativeInteger(master), selectedYear, showHideCommand = None)
self.hour = self.addEntry(master, "Hour:", ValidateNonNegativeInteger(master), selectedHour, showHideCommand = None)
self.minute = self.addEntry(master, "Minute:", ValidateNonNegativeInteger(master), selectedMinute, showHideCommand = None)
self.validations.append(self.validateDate)
def validateDate(self):
try:
self.getDate()
except Exception as e:
pass
def parseClipBoard(self, date):
self.day.set(date.day)
self.month.set(date.month)
self.year.set(date.year)
self.hour.set(date.hour)
self.minute.set(date.minute)
def getDate(self):
return datetime.datetime(int(self.year.get()), int(self.month.get()), int(self.day.get()), int(self.hour.get()), int(self.minute.get()))
def apply(self):
self.callback(self.getDate())
class ParseClipBoard:
def __init__(self, master, dateFormat, callback):
self.master = master
self.dateFormat = dateFormat
self.callback = callback
def __call__(self):
try:
clipboard = self.master.selection_get(selection = "CLIPBOARD")
if len(clipboard) > 0:
try:
date = datetime.datetime.strptime(clipboard, self.dateFormat)
except Exception as e:
try:
date = dateutil.parser.parse(clipboard)
except Exception as e:
date = None
print "Can't parse clipboard (%s)" % e.message
if date != None:
self.callback(date)
except Exception as e:
print "Can't parse clipboard (%s)" % e.message
class ExportDataSetDialog(BaseDialog):
def __init__(self, master, status):
#self.callback = callback
self.cleanDataset = True
self.allDatasets = False
self.calibrationDatasets = False
BaseDialog.__init__(self, master, status)
def validate(self):
valid = any(self.getSelections())
if valid:
return 1
else:
return 0
def body(self, master):
spacer = Label(master, text=" " * 30)
spacer.grid(row=self.row, column=self.titleColumn, columnspan = 2)
spacer = Label(master, text=" " * 30)
spacer.grid(row=self.row, column=self.secondButtonColumn, columnspan = 2)
self.row += 1
cleanDataset = self.cleanDataset
allDatasets = self.allDatasets
calibrationDatasets = self.calibrationDatasets
self.cleanDataset = self.addCheckBox (master, "Clean Combined Dataset:", cleanDataset, showHideCommand = None)
spacer = Label(master, text="Extra Time Series:")
spacer.grid(row=self.row, column=self.titleColumn, columnspan = 2)
self.row += 1
self.allDatasets = self.addCheckBox(master, " Filtered Individual Datasets:", allDatasets, showHideCommand = None)
self.calibrationDatasets = self.addCheckBox(master, " Calibration Datasets:", calibrationDatasets, showHideCommand = None)
def getSelections(self):
return (bool(self.cleanDataset.get()), bool(self.allDatasets.get()), bool(self.calibrationDatasets.get()))
def apply(self):
return self.getSelections()
class ExportAnonReportPickerDialog(BaseDialog):
def __init__(self, master, status):
#self.callback = callback
self.scatter = True
self.deviationMatrix = True
BaseDialog.__init__(self, master, status)
def validate(self):
valid = any(self.getSelections())
if valid:
return 1
else:
return 0
def body(self, master):
spacer = Label(master, text=" " * 30)
spacer.grid(row=self.row, column=self.titleColumn, columnspan = 2)
spacer = Label(master, text=" " * 30)
spacer.grid(row=self.row, column=self.secondButtonColumn, columnspan = 2)
self.row += 1
scatter = self.scatter
deviationMatrix = self.deviationMatrix
self.deviationMatrix = self.addCheckBox (master, "Power Deviation Matrix:", deviationMatrix, showHideCommand = None)
self.scatter = self.addCheckBox(master, "Scatter metric:", scatter, showHideCommand = None)
def getSelections(self):
return (bool(self.scatter.get()), bool(self.deviationMatrix.get()))
def apply(self):
return self.getSelections()
class DatePicker:
def __init__(self, parentDialog, entry, dateFormat):
self.parentDialog = parentDialog
self.entry = entry
self.dateFormat = dateFormat
def __call__(self):
if len(self.entry.get()) > 0:
date = datetime.datetime.strptime(self.entry.get(), self.dateFormat)
else:
date = None
DatePickerDialog(self.parentDialog, self.parentDialog.status, self.pick, date, self.dateFormat)
def pick(self, date):
self.entry.set(date.strftime(datePickerFormat))
class ColumnPicker:
def __init__(self, parentDialog, entry):
self.parentDialog = parentDialog
self.entry = entry
def __call__(self):
self.parentDialog.ShowColumnPicker(self.parentDialog, self.pick, self.entry.get())
def pick(self, column):
if len(column) > 0:
self.entry.set(column)
class DateFormatPickerDialog(BaseDialog):
def __init__(self, master, status, callback, availableFormats, selectedFormat):
self.callback = callback
self.availableFormats = availableFormats
self.selectedFormat = selectedFormat
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
self.dateFormat = self.addOption(master, "Select Date Format:", self.availableFormats, self.selectedFormat)
def apply(self):
self.callback(self.dateFormat.get())
class DateFormatPicker:
def __init__(self, parentDialog, entry, availableFormats):
self.parentDialog = parentDialog
self.entry = entry
self.availableFormats = availableFormats
def __call__(self):
try:
dialog = DateFormatPickerDialog(self.parentDialog, self.parentDialog.status, self.pick, self.availableFormats, self.entry.get())
except ExceptionType as e:
self.status.addMessage("ERROR picking dateFormat: %s" % e)
def pick(self, column):
if len(column) > 0:
self.entry.set(column)
class ColumnSeparatorDialog(BaseDialog):
def __init__(self, master, status, callback, availableSeparators, selectedSeparator):
self.callback = callback
self.availableSeparators = availableSeparators
self.selectedSeparator = selectedSeparator
BaseDialog.__init__(self, master, status)
def body(self, master):
self.prepareColumns(master)
self.separator = self.addOption(master, "Select Column Separator:", self.availableSeparators, self.selectedSeparator)
def apply(self):
self.callback(self.separator.get())
class ColumnSeparatorPicker:
def __init__(self, parentDialog, entry, availableSeparators):
self.parentDialog = parentDialog
self.entry = entry
self.availableSeparators = availableSeparators
def __call__(self):
try:
dialog = ColumnSeparatorDialog(self.parentDialog, self.parentDialog.status, self.pick, self.availableSeparators, self.entry.get())
except ExceptionType as e:
self.status.addMessage("ERROR picking separator: %s" % e)
def pick(self, column):
if len(column) > 0:
self.entry.set(column)
class DatasetConfigurationDialog(BaseConfigurationDialog):
def getInitialFileName(self):
return "Dataset"
def addFormElements(self, master):
self.availableColumnsFile = None
self.columnsFileHeaderRows = None
self.availableColumns = []
self.shearWindSpeedHeights = []
self.shearWindSpeeds = []
self.name = self.addEntry(master, "Dataset Name:", ValidateNotBlank(master), self.config.name, showHideCommand = self.generalShowHide)
self.inputTimeSeriesPath = self.addFileOpenEntry(master, "Input Time Series Path:", ValidateTimeSeriesFilePath(master), self.config.inputTimeSeriesPath, self.filePath, showHideCommand = self.generalShowHide)
self.separator = self.addOption(master, "Separator:", ["TAB", "COMMA", "SPACE", "SEMI-COLON"], self.config.separator, showHideCommand = self.generalShowHide)
self.separator.trace("w", self.columnSeparatorChange)
self.decimal = self.addOption(master, "Decimal Mark:", ["FULL STOP", "COMMA"], self.config.decimal, showHideCommand = self.generalShowHide)
self.decimal.trace("w", self.decimalChange)
self.headerRows = self.addEntry(master, "Header Rows:", ValidateNonNegativeInteger(master), self.config.headerRows, showHideCommand = self.generalShowHide)
self.startDate = self.addDatePickerEntry(master, "Start Date:", None, self.config.startDate, showHideCommand = self.generalShowHide)
self.endDate = self.addDatePickerEntry(master, "End Date:", None, self.config.endDate, showHideCommand = self.generalShowHide)
self.hubWindSpeedMode = self.addOption(master, "Hub Wind Speed Mode:", ["None", "Calculated", "Specified"], self.config.hubWindSpeedMode, showHideCommand = self.generalShowHide)
self.hubWindSpeedMode.trace("w", self.hubWindSpeedModeChange)
self.calibrationMethod = self.addOption(master, "Calibration Method:", ["Specified", "LeastSquares"], self.config.calibrationMethod, showHideCommand = self.generalShowHide)
self.calibrationMethod.trace("w", self.calibrationMethodChange)
self.densityMode = self.addOption(master, "Density Mode:", ["Calculated", "Specified"], self.config.densityMode, showHideCommand = self.generalShowHide)
self.densityMode.trace("w", self.densityMethodChange)
measurementShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Measurement Settings:", showHideCommand = measurementShowHide)
self.timeStepInSeconds = self.addEntry(master, "Time Step In Seconds:", ValidatePositiveInteger(master), self.config.timeStepInSeconds, showHideCommand = measurementShowHide)
self.badData = self.addEntry(master, "Bad Data Value:", ValidateFloat(master), self.config.badData, showHideCommand = measurementShowHide)
self.dateFormat = self.addEntry(master, "Date Format:", ValidateNotBlank(master), self.config.dateFormat, width = 60, showHideCommand = measurementShowHide)
pickDateFormatButton = Button(master, text=".", command = DateFormatPicker(self, self.dateFormat, ['%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%d-%m-%y %H:%M', '%y-%m-%d %H:%M', '%d/%m/%Y %H:%M', '%d/%m/%Y %H:%M:%S', '%d/%m/%y %H:%M', '%y/%m/%d %H:%M']), width=5, height=1)
pickDateFormatButton.grid(row=(self.row-1), sticky=E+N, column=self.buttonColumn)
measurementShowHide.addControl(pickDateFormatButton)
self.timeStamp = self.addPickerEntry(master, "Time Stamp:", ValidateNotBlank(master), self.config.timeStamp, width = 60, showHideCommand = measurementShowHide)
#self.turbineAvailabilityCount = self.addPickerEntry(master, "Turbine Availability Count:", None, self.config.turbineAvailabilityCount, width = 60, showHideCommand = measurementShowHide) #Could be taken out? Doesn't have to be used.
self.turbineLocationWindSpeed = self.addPickerEntry(master, "Turbine Location Wind Speed:", None, self.config.turbineLocationWindSpeed, width = 60, showHideCommand = measurementShowHide) #Should this be with reference wind speed?
self.hubWindSpeed = self.addPickerEntry(master, "Hub Wind Speed:", None, self.config.hubWindSpeed, width = 60, showHideCommand = measurementShowHide)
self.hubTurbulence = self.addPickerEntry(master, "Hub Turbulence:", None, self.config.hubTurbulence, width = 60, showHideCommand = measurementShowHide)
self.temperature = self.addPickerEntry(master, "Temperature:", None, self.config.temperature, width = 60, showHideCommand = measurementShowHide)
self.pressure = self.addPickerEntry(master, "Pressure:", None, self.config.pressure, width = 60, showHideCommand = measurementShowHide)
self.density = self.addPickerEntry(master, "Density:", None, self.config.density, width = 60, showHideCommand = measurementShowHide)
powerShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Power Settings:", showHideCommand = powerShowHide)
self.power = self.addPickerEntry(master, "Power:", None, self.config.power, width = 60, showHideCommand = powerShowHide)
self.powerMin = self.addPickerEntry(master, "Power Min:", None, self.config.powerMin, width = 60, showHideCommand = powerShowHide)
self.powerMax = self.addPickerEntry(master, "Power Max:", None, self.config.powerMax, width = 60, showHideCommand = powerShowHide)
self.powerSD = self.addPickerEntry(master, "Power Std Dev:", None, self.config.powerSD, width = 60, showHideCommand = powerShowHide)
referenceWindSpeedShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Reference Wind Speed Settings:", showHideCommand = referenceWindSpeedShowHide)
self.referenceWindSpeed = self.addPickerEntry(master, "Reference Wind Speed:", None, self.config.referenceWindSpeed, width = 60, showHideCommand = referenceWindSpeedShowHide)
self.referenceWindSpeedStdDev = self.addPickerEntry(master, "Reference Wind Speed Std Dev:", None, self.config.referenceWindSpeedStdDev, width = 60, showHideCommand = referenceWindSpeedShowHide)
self.referenceWindDirection = self.addPickerEntry(master, "Reference Wind Direction:", None, self.config.referenceWindDirection, width = 60, showHideCommand = referenceWindSpeedShowHide)
self.referenceWindDirectionOffset = self.addEntry(master, "Reference Wind Direction Offset:", ValidateFloat(master), self.config.referenceWindDirectionOffset, showHideCommand = referenceWindSpeedShowHide)
shearShowHide = ShowHideCommand(master)
label = Label(master, text="Shear Measurements:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
shearShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.shearProfileLevelsListBoxEntry = self.addListBox(master, "Shear Listbox", showHideCommand = shearShowHide)
self.shearProfileLevelsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.shearProfileLevelsListBoxEntry.listbox.insert(END, "Height,Wind Speed")
self.newShearProfileLevelButton = Button(master, text="New", command = self.NewShearProfileLevel, width=12, height=1)
self.newShearProfileLevelButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
shearShowHide.addControl(self.newShearProfileLevelButton)
self.copyToREWSShearProileLevelButton = Button(master, text="Copy To REWS", command = self.copyToREWSShearProileLevels, width=12, height=1)
self.copyToREWSShearProileLevelButton.grid(row=self.row, sticky=E+N, column=self.buttonColumn)
shearShowHide.addControl(self.copyToREWSShearProileLevelButton)
self.editShearProfileLevelButton = Button(master, text="Edit", command = self.EditShearProfileLevel, width=12, height=1)
self.editShearProfileLevelButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
shearShowHide.addControl(self.editShearProfileLevelButton)
self.deleteShearProfileLevelButton = Button(master, text="Delete", command = self.removeShearProfileLevels, width=12, height=1)
self.deleteShearProfileLevelButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
shearShowHide.addControl(self.deleteShearProfileLevelButton)
self.row +=1
rewsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "REWS Settings:", showHideCommand = rewsShowHide)
self.rewsDefined = self.addCheckBox(master, "REWS Active", self.config.rewsDefined, showHideCommand = rewsShowHide)
self.numberOfRotorLevels = self.addEntry(master, "REWS Number of Rotor Levels:", ValidateNonNegativeInteger(master), self.config.numberOfRotorLevels, showHideCommand = rewsShowHide)
self.rotorMode = self.addOption(master, "REWS Rotor Mode:", ["EvenlySpacedLevels", "ProfileLevels"], self.config.rotorMode, showHideCommand = rewsShowHide)
self.hubMode = self.addOption(master, "Hub Mode:", ["Interpolated", "PiecewiseExponent"], self.config.hubMode, showHideCommand = rewsShowHide)
rewsProfileShowHide = ShowHideCommand(master)
label = Label(master, text="REWS Profile Levels:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
rewsProfileShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.rewsProfileLevelsListBoxEntry = self.addListBox(master, "REWS Listbox", showHideCommand = rewsProfileShowHide)
self.rewsProfileLevelsListBoxEntry.listbox.insert(END, "Height,WindSpeed,WindDirection")
if not self.isNew:
for height in sorted(self.config.windSpeedLevels):
windSpeed = self.config.windSpeedLevels[height]
direction = self.config.windDirectionLevels[height]
self.rewsProfileLevelsListBoxEntry.listbox.insert(END, encodeREWSLevelValuesAsText(height, windSpeed, direction))
for height in sorted(self.config.shearMeasurements):
windSpeed = self.config.shearMeasurements[height]
self.shearProfileLevelsListBoxEntry.listbox.insert(END, encodeShearMeasurementValuesAsText(height, windSpeed))
self.rewsProfileLevelsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
#self.rewsProfileLevelsScrollBar.configure(command=self.rewsProfileLevelsListBox.yview)
#self.rewsProfileLevelsScrollBar.grid(row=self.row, sticky=W+N+S, column=self.titleColumn)
#self.validatedREWSProfileLevels = ValidateREWSProfileLevels(master, self.rewsProfileLevelsListBox) #Should we add this back in?
#self.validations.append(self.validatedREWSProfileLevels)
#self.validatedREWSProfileLevels.messageLabel.grid(row=self.row, sticky=W, column=self.messageColumn)
self.newREWSProfileLevelButton = Button(master, text="New", command = self.NewREWSProfileLevel, width=12, height=1)
self.newREWSProfileLevelButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
rewsProfileShowHide.addControl(self.newREWSProfileLevelButton)
self.copyToShearREWSProileLevelButton = Button(master, text="Copy To Shear", command = self.copyToShearREWSProileLevels, width=12, height=1)
self.copyToShearREWSProileLevelButton.grid(row=self.row, sticky=E+N, column=self.buttonColumn)
rewsProfileShowHide.addControl(self.copyToShearREWSProileLevelButton)
self.editREWSProfileLevelButton = Button(master, text="Edit", command = self.EditREWSProfileLevel, width=12, height=1)
self.editREWSProfileLevelButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
rewsProfileShowHide.addControl(self.editREWSProfileLevelButton)
self.deleteREWSProfileLevelButton = Button(master, text="Delete", command = self.removeREWSProfileLevels, width=12, height=1)
self.deleteREWSProfileLevelButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
rewsProfileShowHide.addControl(self.deleteREWSProfileLevelButton)
self.row +=1
calibrationSettingsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Calibration Settings:", showHideCommand = calibrationSettingsShowHide)
calibrationSettingsShowHide.button.grid(row=self.row, sticky=N+E+W, column=self.showHideColumn)
self.calibrationStartDate = self.addDatePickerEntry(master, "Calibration Start Date:", None, self.config.calibrationStartDate, showHideCommand = calibrationSettingsShowHide)
self.calibrationEndDate = self.addDatePickerEntry(master, "Calibration End Date:", None, self.config.calibrationEndDate, showHideCommand = calibrationSettingsShowHide)
self.siteCalibrationNumberOfSectors = self.addEntry(master, "Number of Sectors:", None, self.config.siteCalibrationNumberOfSectors, showHideCommand = calibrationSettingsShowHide)
self.siteCalibrationCenterOfFirstSector = self.addEntry(master, "Center of First Sector:", None, self.config.siteCalibrationCenterOfFirstSector, showHideCommand = calibrationSettingsShowHide)
calibrationSectorsShowHide = ShowHideCommand(master)
label = Label(master, text="Calibration Sectors:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
calibrationSectorsShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.calibrationDirectionsListBoxEntry = self.addListBox(master, "Calibration Sectors ListBox", showHideCommand = calibrationSectorsShowHide)
self.calibrationDirectionsListBoxEntry.listbox.insert(END, "Direction,Slope,Offset,Active")
self.calibrationDirectionsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.newCalibrationDirectionButton = Button(master, text="New", command = self.NewCalibrationDirection, width=5, height=1)
self.newCalibrationDirectionButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
calibrationSectorsShowHide.addControl(self.newCalibrationDirectionButton)
self.editCalibrationDirectionButton = Button(master, text="Edit", command = self.EditCalibrationDirection, width=5, height=1)
self.editCalibrationDirectionButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
calibrationSectorsShowHide.addControl(self.editCalibrationDirectionButton)
self.calibrationDirectionsListBoxEntry.listbox.bind("<Double-Button-1>", self.EditCalibrationDirection)
self.deleteCalibrationDirectionButton = Button(master, text="Delete", command = self.RemoveCalibrationDirection, width=5, height=1)
self.deleteCalibrationDirectionButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
calibrationSectorsShowHide.addControl(self.deleteCalibrationDirectionButton)
self.row +=1
if not self.isNew:
for direction in sorted(self.config.calibrationSlopes):
slope = self.config.calibrationSlopes[direction]
offset = self.config.calibrationOffsets[direction]
active = self.config.calibrationActives[direction]
text = encodeCalibrationDirectionValuesAsText(direction, slope, offset, active)
self.calibrationDirectionsListBoxEntry.listbox.insert(END, text)
calibrationFiltersShowHide = ShowHideCommand(master)
label = Label(master, text="Calibration Filters:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
calibrationFiltersShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.calibrationFiltersListBoxEntry = self.addListBox(master, "Calibration Filters ListBox", showHideCommand = calibrationFiltersShowHide)
self.calibrationFiltersListBoxEntry.listbox.insert(END, "Column,Value,FilterType,Inclusive,Active")
self.calibrationFiltersListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.newCalibrationFilterButton = Button(master, text="New", command = self.NewCalibrationFilter, width=5, height=1)
self.newCalibrationFilterButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
calibrationFiltersShowHide.addControl(self.newCalibrationFilterButton)
self.editCalibrationFilterButton = Button(master, text="Edit", command = self.EditCalibrationFilter, width=5, height=1)
self.editCalibrationFilterButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
calibrationFiltersShowHide.addControl(self.editCalibrationFilterButton)
self.calibrationFiltersListBoxEntry.listbox.bind("<Double-Button-1>", self.EditCalibrationFilter)
self.deleteCalibrationFilterButton = Button(master, text="Delete", command = self.RemoveCalibrationFilter, width=5, height=1)
self.deleteCalibrationFilterButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
calibrationFiltersShowHide.addControl(self.deleteCalibrationFilterButton)
self.row +=1
if not self.isNew:
for calibrationFilterItem in sorted(self.config.calibrationFilters):
if isinstance(calibrationFilterItem, configuration.RelationshipFilter):
text = encodeRelationshipFilterValuesAsText(calibrationFilterItem)
else:
text = encodeFilterValuesAsText(calibrationFilterItem.column, calibrationFilterItem.value, calibrationFilterItem.filterType, calibrationFilterItem.inclusive, calibrationFilterItem.active)
self.calibrationFiltersListBoxEntry.listbox.insert(END, text)
#Exclusions
exclusionsShowHide = ShowHideCommand(master)
label = Label(master, text="Exclusions:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
exclusionsShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.exclusionsListBoxEntry = self.addListBox(master, "Exclusions ListBox", showHideCommand = exclusionsShowHide)
self.exclusionsListBoxEntry.listbox.insert(END, "StartDate,EndDate,Active")
self.exclusionsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.newExclusionButton = Button(master, text="New", command = self.NewExclusion, width=5, height=1)
self.newExclusionButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
exclusionsShowHide.addControl(self.newExclusionButton)
self.editExclusionButton = Button(master, text="Edit", command = self.EditExclusion, width=5, height=1)
self.editExclusionButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
exclusionsShowHide.addControl(self.editExclusionButton)
self.exclusionsListBoxEntry.listbox.bind("<Double-Button-1>", self.EditExclusion)
self.deleteExclusionButton = Button(master, text="Delete", command = self.RemoveExclusion, width=5, height=1)
self.deleteExclusionButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
exclusionsShowHide.addControl(self.deleteExclusionButton)
self.row +=1
if not self.isNew:
for exclusion in sorted(self.config.exclusions):
startDate = exclusion[0]
endDate = exclusion[1]
active = exclusion[2]
text = encodeExclusionValuesAsText(startDate, endDate, active)
self.exclusionsListBoxEntry.listbox.insert(END, text)
#Filters
filtersShowHide = ShowHideCommand(master)
label = Label(master, text="Filters:")
label.grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
filtersShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.filtersListBoxEntry = self.addListBox(master, "Filters ListBox", showHideCommand = filtersShowHide)
self.filtersListBoxEntry.listbox.insert(END, "Column,Value,FilterType,Inclusive,Active")
self.filtersListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.newFilterButton = Button(master, text="New", command = self.NewFilter, width=5, height=1)
self.newFilterButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
filtersShowHide.addControl(self.newFilterButton)
self.editFilterButton = Button(master, text="Edit", command = self.EditFilter, width=5, height=1)
self.editFilterButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
filtersShowHide.addControl(self.editFilterButton)
self.filtersListBoxEntry.listbox.bind("<Double-Button-1>", self.EditFilter)
self.deleteFilterButton = Button(master, text="Delete", command = self.RemoveFilter, width=5, height=1)
self.deleteFilterButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
filtersShowHide.addControl(self.deleteFilterButton)
self.row +=1
if not self.isNew:
for filterItem in sorted(self.config.filters):
if isinstance(filterItem, configuration.RelationshipFilter):
text = encodeRelationshipFilterValuesAsText(filterItem)
else:
text = encodeFilterValuesAsText(filterItem.column, filterItem.value, filterItem.filterType, filterItem.inclusive, filterItem.active)
self.filtersListBoxEntry.listbox.insert(END, text)
#set initial visibility
self.generalShowHide.show()
rewsShowHide.hide()
measurementShowHide.hide()
shearShowHide.hide()
rewsProfileShowHide.hide()
calibrationSettingsShowHide.hide()
calibrationSectorsShowHide.hide()
calibrationFiltersShowHide.hide()
exclusionsShowHide.hide()
filtersShowHide.hide()
powerShowHide.hide()
referenceWindSpeedShowHide.hide()
self.calibrationMethodChange()
self.densityMethodChange()
def densityMethodChange(self, *args):
if self.densityMode.get() == "Specified":
densityModeSpecifiedComment = "Not required when density mode is set to specified"
self.temperature.setTip(densityModeSpecifiedComment)
self.pressure.setTip(densityModeSpecifiedComment)
self.density.clearTip()
elif self.densityMode.get() == "Calculated":
densityModeCalculatedComment = "Not required when density mode is set to calculate"
self.temperature.clearTip()
self.pressure.clearTip()
self.density.setTip(densityModeCalculatedComment)
elif self.densityMode.get() == "None":
densityModeNoneComment = "Not required when density mode is set to none"
self.temperature.setTip(densityModeNoneComment)
self.pressure.setTip(densityModeNoneComment)
self.density.setTip(densityModeNoneComment)
else:
raise Exception("Unknown density methods: %s" % self.densityMode.get())
def columnSeparatorChange(self, *args):
print 'reading separator'
sep = getSeparatorValue(self.separator.get())
self.read_dataset()
return sep
def decimalChange(self, *args):
print 'reading decimal'
decimal = getDecimalValue(self.decimal.get())
self.read_dataset()
return decimal
def hubWindSpeedModeChange(self, *args):
self.calibrationMethodChange()
def calibrationMethodChange(self, *args):
if self.hubWindSpeedMode.get() == "Calculated":
hubWindSpeedModeCalculatedComment = "Not required for calculated hub wind speed mode"
specifiedCalibrationMethodComment = "Not required for Specified Calibration Method"
leastSquaresCalibrationMethodComment = "Not required for Least Squares Calibration Method"
self.hubWindSpeed.setTip(hubWindSpeedModeCalculatedComment)
self.hubTurbulence.setTip(hubWindSpeedModeCalculatedComment)
self.siteCalibrationNumberOfSectors.clearTip()
self.siteCalibrationCenterOfFirstSector.clearTip()
self.referenceWindSpeed.clearTip()
self.referenceWindSpeedStdDev.clearTip()
self.referenceWindDirection.clearTip()
self.referenceWindDirectionOffset.clearTip()
if self.calibrationMethod.get() in ("LeastSquares", "York"):
self.turbineLocationWindSpeed.clearTip()
self.calibrationStartDate.clearTip()
self.calibrationEndDate.clearTip()
self.calibrationDirectionsListBoxEntry.setTip(leastSquaresCalibrationMethodComment)
self.calibrationFiltersListBoxEntry.clearTip()
elif self.calibrationMethod.get() == "Specified":
self.turbineLocationWindSpeed.setTipNotRequired()
self.calibrationStartDate.setTipNotRequired()
self.calibrationEndDate.setTipNotRequired()
self.calibrationDirectionsListBoxEntry.clearTip()
self.calibrationFiltersListBoxEntry.setTip(specifiedCalibrationMethodComment)
else:
raise Exception("Unknown calibration methods: %s" % self.calibrationMethod.get())
elif self.hubWindSpeedMode.get() == "Specified":
hubWindSpeedModeSpecifiedComment = "Not required for specified hub wind speed mode"
self.hubWindSpeed.clearTip()
self.hubTurbulence.clearTip()
self.turbineLocationWindSpeed.setTip(hubWindSpeedModeSpecifiedComment)
self.calibrationStartDate.setTip(hubWindSpeedModeSpecifiedComment)
self.calibrationEndDate.setTip(hubWindSpeedModeSpecifiedComment)
self.siteCalibrationNumberOfSectors.setTip(hubWindSpeedModeSpecifiedComment)
self.siteCalibrationCenterOfFirstSector.setTip(hubWindSpeedModeSpecifiedComment)
self.referenceWindSpeed.setTip(hubWindSpeedModeSpecifiedComment)
self.referenceWindSpeedStdDev.setTip(hubWindSpeedModeSpecifiedComment)
self.referenceWindDirection.setTip(hubWindSpeedModeSpecifiedComment)
self.referenceWindDirectionOffset.setTip(hubWindSpeedModeSpecifiedComment)
elif self.hubWindSpeedMode.get() == "None":
hubWindSpeedModeNoneComment = "Not required when hub wind speed mode is set to none"
self.hubWindSpeed.setTip(hubWindSpeedModeNoneComment)
self.hubTurbulence.setTip(hubWindSpeedModeNoneComment)
self.turbineLocationWindSpeed.setTip(hubWindSpeedModeNoneComment)
self.calibrationStartDate.setTip(hubWindSpeedModeNoneComment)
self.calibrationEndDate.setTip(hubWindSpeedModeNoneComment)
self.siteCalibrationNumberOfSectors.setTip(hubWindSpeedModeNoneComment)
self.siteCalibrationCenterOfFirstSector.setTip(hubWindSpeedModeNoneComment)
self.referenceWindSpeed.setTip(hubWindSpeedModeNoneComment)
self.referenceWindSpeedStdDev.setTip(hubWindSpeedModeNoneComment)
self.referenceWindDirection.setTip(hubWindSpeedModeNoneComment)
self.referenceWindDirectionOffset.setTip(hubWindSpeedModeNoneComment)
else:
raise Exception("Unknown hub wind speed mode: %s" % self.hubWindSpeedMode.get())
def NewFilter(self):
configDialog = FilterDialog(self, self.status, self.addFilterFromText)
def EditFilter(self, event = None):
items = self.filtersListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = int(items[0])
if idx > 0:
text = self.filtersListBoxEntry.listbox.get(items[0])
try:
dialog = FilterDialog(self, self.status, self.addFilterFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def RemoveFilter(self):
items = self.filtersListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.filtersListBoxEntry.listbox.delete(idx, idx)
pos += 1
def addFilterFromText(self, text, index = None):
if index != None:
self.filtersListBoxEntry.listbox.delete(index, index)
self.filtersListBoxEntry.listbox.insert(index, text)
else:
self.filtersListBoxEntry.listbox.insert(END, text)
def NewCalibrationFilter(self):
configDialog = CalibrationFilterDialog(self, self.status, self.addCalibrationFilterFromText)
def EditCalibrationFilter(self, event = None):
items = self.calibrationFiltersListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = int(items[0])
if idx > 0:
text = self.calibrationFiltersListBoxEntry.listbox.get(items[0])
try:
dialog = CalibrationFilterDialog(self, self.status, self.addCalibrationFilterFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def RemoveCalibrationFilter(self):
items = self.calibrationFiltersListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.calibrationFiltersListBoxEntry.listbox.delete(idx, idx)
pos += 1
def addCalibrationFilterFromText(self, text, index = None):
if index != None:
self.calibrationFiltersListBoxEntry.listbox.delete(index, index)
self.calibrationFiltersListBoxEntry.listbox.insert(index, text)
else:
self.calibrationFiltersListBoxEntry.listbox.insert(END, text)
def NewExclusion(self):
configDialog = ExclusionDialog(self, self.status, self.addExclusionFromText)
def EditExclusion(self, event = None):
items = self.exclusionsListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = int(items[0])
if idx > 0:
text = self.exclusionsListBoxEntry.listbox.get(items[0])
try:
dialog = ExclusionDialog(self, self.status, self.addExclusionFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def RemoveExclusion(self):
items = self.exclusionsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.exclusionsListBoxEntry.listbox.delete(idx, idx)
pos += 1
def addExclusionFromText(self, text, index = None):
if index != None:
self.exclusionsListBoxEntry.listbox.delete(index, index)
self.exclusionsListBoxEntry.listbox.insert(index, text)
else:
self.exclusionsListBoxEntry.listbox.insert(END, text)
def NewCalibrationDirection(self):
configDialog = CalibrationDirectionDialog(self, self.status, self.addCalbirationDirectionFromText)
def EditCalibrationDirection(self, event = None):
items = self.calibrationDirectionsListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = int(items[0])
if idx > 0:
text = self.calibrationDirectionsListBoxEntry.listbox.get(items[0])
try:
dialog = CalibrationDirectionDialog(self, self.status, self.addCalbirationDirectionFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def RemoveCalibrationDirection(self):
items = self.calibrationDirectionsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.calibrationDirectionsListBoxEntry.listbox.delete(idx, idx)
pos += 1
def addCalbirationDirectionFromText(self, text, index = None):
if index != None:
self.calibrationDirectionsListBoxEntry.listbox.delete(index, index)
self.calibrationDirectionsListBoxEntry.listbox.insert(index, text)
else:
self.calibrationDirectionsListBoxEntry.listbox.insert(END, text)
def EditShearProfileLevel(self):
items = self.shearProfileLevelsListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = items[0]
if idx > 0:
text = self.shearProfileLevelsListBoxEntry.listbox.get(items[0])
try:
dialog = ShearMeasurementDialog(self, self.status, self.addShearProfileLevelFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def NewShearProfileLevel(self):
configDialog = ShearMeasurementDialog(self, self.status, self.addShearProfileLevelFromText)
def addShearProfileLevelFromText(self, text, index = None):
if index != None:
self.shearProfileLevelsListBoxEntry.listbox.delete(index, index)
self.shearProfileLevelsListBoxEntry.listbox.insert(index, text)
else:
self.shearProfileLevelsListBoxEntry.listbox.insert(END, text)
self.sortLevelsShear()
#self.validatedShearProfileLevels.validate()
def removeShearProfileLevels(self):
items = self.shearProfileLevelsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.shearProfileLevelsListBoxEntry.listbox.delete(idx, idx)
pos += 1
def copyToREWSShearProileLevels(self):
shears = {}
for i in range(self.shearProfileLevelsListBoxEntry.listbox.size()):
if i > 0:
text = self.shearProfileLevelsListBoxEntry.listbox.get(i)
referenceWindDirection = self.config.referenceWindDirection
shears[extractShearMeasurementValuesFromText(text)[0]] = text + columnSeparator + str(referenceWindDirection)
for height in sorted(shears):
self.rewsProfileLevelsListBoxEntry.listbox.insert(END, shears[height])
self.sortLevels()
def sortLevelsShear(self):
levels = {}
startText = self.shearProfileLevelsListBoxEntry.listbox.get(0)
for i in range(1, self.shearProfileLevelsListBoxEntry.listbox.size()):
text = self.shearProfileLevelsListBoxEntry.listbox.get(i)
levels[extractShearMeasurementValuesFromText(text)[0]] = text
self.shearProfileLevelsListBoxEntry.listbox.delete(0, END)
self.shearProfileLevelsListBoxEntry.listbox.insert(END, startText)
for height in sorted(levels):
self.shearProfileLevelsListBoxEntry.listbox.insert(END, levels[height])
def EditREWSProfileLevel(self):
items = self.rewsProfileLevelsListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = items[0]
if idx > 0:
text = self.rewsProfileLevelsListBoxEntry.listbox.get(items[0])
try:
dialog = REWSProfileLevelDialog(self, self.status, self.addREWSProfileLevelFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def NewREWSProfileLevel(self):
configDialog = REWSProfileLevelDialog(self, self.status, self.addREWSProfileLevelFromText)
def addREWSProfileLevelFromText(self, text, index = None):
if index != None:
self.rewsProfileLevelsListBoxEntry.listbox.delete(index, index)
self.rewsProfileLevelsListBoxEntry.listbox.insert(index, text)
else:
self.rewsProfileLevelsListBoxEntry.listbox.insert(END, text)
self.sortLevels()
#self.validatedREWSProfileLevels.validate()
def removeREWSProfileLevels(self):
items = self.rewsProfileLevelsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
if idx > 0:
self.rewsProfileLevelsListBoxEntry.listbox.delete(idx, idx)
pos += 1
#self.validatedREWSProfileLevels.validate()
def copyToShearREWSProileLevels(self):
profiles = {}
for i in range(self.rewsProfileLevelsListBoxEntry.listbox.size()):
if i > 0:
text = self.rewsProfileLevelsListBoxEntry.listbox.get(i)
height, ws , wd = extractREWSLevelValuesFromText(text)
profiles[height] = encodeShearMeasurementValuesAsText(height, ws )
for height in sorted(profiles):
self.shearProfileLevelsListBoxEntry.listbox.insert(END, profiles[height])
self.sortLevelsShear()
def sortLevels(self):
levels = {}
startText = self.rewsProfileLevelsListBoxEntry.listbox.get(0)
for i in range(1,self.rewsProfileLevelsListBoxEntry.listbox.size()):
text = self.rewsProfileLevelsListBoxEntry.listbox.get(i)
levels[extractREWSLevelValuesFromText(text)[0]] = text
self.rewsProfileLevelsListBoxEntry.listbox.delete(0, END)
self.rewsProfileLevelsListBoxEntry.listbox.insert(END,startText)
for height in sorted(levels):
self.rewsProfileLevelsListBoxEntry.listbox.insert(END, levels[height])
def getInputTimeSeriesRelativePath(self):
relativePath = configuration.RelativePath(self.filePath.get())
return relativePath.convertToRelativePath(self.inputTimeSeriesPath.get())
def getInputTimeSeriesAbsolutePath(self):
if len(self.inputTimeSeriesPath.get()) > 0:
relativePath = configuration.RelativePath(self.filePath.get())
return relativePath.convertToAbsolutePath(self.inputTimeSeriesPath.get())
else:
return ""
def getHeaderRows(self):
headerRowsText = self.headerRows.get()
if len(headerRowsText) > 0:
return int(headerRowsText)
else:
return 0
def ShowColumnPicker(self, parentDialog, pick, selectedColumn):
if len(self.getInputTimeSeriesAbsolutePath()) < 1:
tkMessageBox.showwarning(
"InputTimeSeriesPath Not Set",
"You must set the InputTimeSeriesPath before using the ColumnPicker"
)
return
inputTimeSeriesPath = self.getInputTimeSeriesAbsolutePath()
headerRows = self.getHeaderRows()
if self.columnsFileHeaderRows != headerRows or self.availableColumnsFile != inputTimeSeriesPath:
try:
dataFrame = self.read_dataset()
except ExceptionType as e:
tkMessageBox.showwarning(
"Column header error",
"It was not possible to read column headers using the provided inputs.\rPlease check and amend 'Input Time Series Path' and/or 'Header Rows'.\r"
)
self.status.addMessage("ERROR reading columns from %s: %s" % (inputTimeSeriesPath, e))
self.columnsFileHeaderRows = headerRows
self.availableColumnsFile = inputTimeSeriesPath
try:
dialog = ColumnPickerDialog(parentDialog, self.status, pick, self.availableColumns, selectedColumn)
except ExceptionType as e:
self.status.addMessage("ERROR picking column: %s" % e)
def read_dataset(self):
print 'reading dataSet'
inputTimeSeriesPath = self.getInputTimeSeriesAbsolutePath()
headerRows = self.getHeaderRows()
dataFrame = pd.read_csv(inputTimeSeriesPath, sep = getSeparatorValue(self.separator.get()), skiprows = headerRows, decimal = getDecimalValue(self.decimal.get()))
self.availableColumns = []
for col in dataFrame:
self.availableColumns.append(col)
def setConfigValues(self):
self.config.name = self.name.get()
self.config.startDate = getDateFromEntry(self.startDate)
self.config.endDate = getDateFromEntry(self.endDate)
self.config.hubWindSpeedMode = self.hubWindSpeedMode.get()
self.config.calibrationMethod = self.calibrationMethod.get()
self.config.densityMode = self.densityMode.get()
self.config.rewsDefined = bool(self.rewsDefined.get())
self.config.numberOfRotorLevels = intSafe(self.numberOfRotorLevels.get())
self.config.rotorMode = self.rotorMode.get()
self.config.hubMode = self.hubMode.get()
self.config.inputTimeSeriesPath = self.getInputTimeSeriesRelativePath()
self.config.timeStepInSeconds = int(self.timeStepInSeconds.get())
self.config.badData = float(self.badData.get())
self.config.dateFormat = self.dateFormat.get()
self.config.separator = self.separator.get()
self.config.decimal = self.decimal.get()
self.config.headerRows = self.getHeaderRows()
self.config.timeStamp = self.timeStamp.get()
self.config.power = self.power.get()
self.config.powerMin = self.powerMin.get()
self.config.powerMax = self.powerMax.get()
self.config.powerSD = self.powerSD.get()
self.config.referenceWindSpeed = self.referenceWindSpeed.get()
self.config.referenceWindSpeedStdDev = self.referenceWindSpeedStdDev.get()
self.config.referenceWindDirection = self.referenceWindDirection.get()
self.config.referenceWindDirectionOffset = floatSafe(self.referenceWindDirectionOffset.get())
self.config.turbineLocationWindSpeed = self.turbineLocationWindSpeed.get()
#self.config.turbineAvailabilityCount = self.turbineAvailabilityCount.get()
self.config.temperature = self.temperature.get()
self.config.pressure = self.pressure.get()
self.config.density = self.density.get()
self.config.hubWindSpeed = self.hubWindSpeed.get()
self.config.hubTurbulence = self.hubTurbulence.get()
self.config.windDirectionLevels = {}
self.config.windSpeedLevels = {}
for i in range(self.rewsProfileLevelsListBoxEntry.listbox.size()):
if i > 0:
items = extractREWSLevelValuesFromText(self.rewsProfileLevelsListBoxEntry.listbox.get(i))
self.config.windSpeedLevels[items[0]] = items[1]
self.config.windDirectionLevels[items[0]] = items[2]
self.config.shearMeasurements = {}
for i in range(self.shearProfileLevelsListBoxEntry.listbox.size()):
if i > 0:
items = extractShearMeasurementValuesFromText(self.shearProfileLevelsListBoxEntry.listbox.get(i))
self.config.shearMeasurements[items[0]] = items[1]
#for i in range(len(self.shearWindSpeedHeights)):
# shearHeight = self.shearWindSpeedHeights[i].get()
# shearColumn = self.shearWindSpeeds[i].get()
# self.config.shearMeasurements[shearHeight] = shearColumn
self.config.calibrationDirections = {}
self.config.calibrationSlopes = {}
self.config.calibrationOffsets = {}
self.config.calibrationActives = {}
self.config.calibrationStartDate = getDateFromEntry(self.calibrationStartDate)
self.config.calibrationEndDate = getDateFromEntry(self.calibrationEndDate)
self.config.siteCalibrationNumberOfSectors = intSafe(self.siteCalibrationNumberOfSectors.get())
self.config.siteCalibrationCenterOfFirstSector = intSafe(self.siteCalibrationCenterOfFirstSector.get())
#calbirations
for i in range(self.calibrationDirectionsListBoxEntry.listbox.size()):
if i > 0:
direction, slope, offset, active = extractCalibrationDirectionValuesFromText(self.calibrationDirectionsListBoxEntry.listbox.get(i))
if not direction in self.config.calibrationDirections:
self.config.calibrationDirections[direction] = direction
self.config.calibrationSlopes[direction] = slope
self.config.calibrationOffsets[direction] = offset
self.config.calibrationActives[direction] = active
else:
raise Exception("Duplicate calibration direction: %f" % direction)
self.config.calibrationFilters = []
for i in range(self.calibrationFiltersListBoxEntry.listbox.size()):
if i > 0:
try: # try simple Filter, if fails assume realtionship filter
calibrationFilterColumn, calibrationFilterValue, calibrationFilterType, calibrationFilterInclusive, calibrationFilterActive = extractFilterValuesFromText(self.calibrationFiltersListBoxEntry.listbox.get(i))
self.config.calibrationFilters.append(configuration.Filter(calibrationFilterActive, calibrationFilterColumn, calibrationFilterType, calibrationFilterInclusive, calibrationFilterValue))
except:
filter = extractRelationshipFilterFromText(self.calibrationFiltersListBoxEntry.listbox.get(i))
self.config.calibrationFilters.append(filter)
#exclusions
self.config.exclusions = []
for i in range(self.exclusionsListBoxEntry.listbox.size()):
if i > 0:
self.config.exclusions.append(extractExclusionValuesFromText(self.exclusionsListBoxEntry.listbox.get(i)))
#filters
self.config.filters = []
for i in range(self.filtersListBoxEntry.listbox.size()):
if i > 0:
try:
filterColumn, filterValue, filterType, filterInclusive, filterActive = extractFilterValuesFromText(self.filtersListBoxEntry.listbox.get(i))
self.config.filters.append(configuration.Filter(filterActive, filterColumn, filterType, filterInclusive, filterValue))
except:
filter = extractRelationshipFilterFromText(self.filtersListBoxEntry.listbox.get(i))
self.config.filters.append(filter)
class PowerCurveConfigurationDialog(BaseConfigurationDialog):
def getInitialFileName(self):
return "PowerCurve"
def addFormElements(self, master):
self.name = self.addEntry(master, "Name:", None, self.config.name, width = 60)
self.referenceDensity = self.addEntry(master, "Reference Density:", ValidateNonNegativeFloat(master), self.config.powerCurveDensity)
self.referenceTurbulence = self.addEntry(master, "Reference Turbulence:", ValidateNonNegativeFloat(master), self.config.powerCurveTurbulence)
Label(master, text="Power Curve Levels:").grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
self.row += 1
self.powerCurveLevelsListBoxEntry = self.addListBox(master, "Power Curve Levels ListBox")
for windSpeed in self.config.powerCurveDictionary:
power = self.config.powerCurveDictionary[windSpeed]
self.powerCurveLevelsListBoxEntry.listbox.insert(END, encodePowerLevelValueAsText(windSpeed, power))
self.powerCurveLevelsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.validatedPowerCurveLevels = ValidatePowerCurveLevels(master, self.powerCurveLevelsListBoxEntry.listbox)
self.validations.append(self.validatedPowerCurveLevels)
self.validatedPowerCurveLevels.messageLabel.grid(row=self.row, sticky=W, column=self.messageColumn)
self.addPowerCurveLevelButton = Button(master, text="New", command = self.NewPowerCurveLevel, width=5, height=1)
self.addPowerCurveLevelButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn, pady=30)
self.addPowerCurveLevelButton = Button(master, text="Edit", command = self.EditPowerCurveLevel, width=5, height=1)
self.addPowerCurveLevelButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
self.addPowerCurveLevelButton = Button(master, text="Delete", command = self.removePowerCurveLevels, width=5, height=1)
self.addPowerCurveLevelButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
def EditPowerCurveLevel(self):
items = self.powerCurveLevelsListBoxEntry.listbox.curselection()
if len(items) == 1:
idx = items[0]
text = self.powerCurveLevelsListBoxEntry.listbox.get(items[0])
try:
dialog = PowerCurveLevelDialog(self, self.status, self.addPowerCurveLevelFromText, text, idx)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (text, e))
def NewPowerCurveLevel(self):
configDialog = PowerCurveLevelDialog(self, self.status, self.addPowerCurveLevelFromText)
def addPowerCurveLevelFromText(self, text, index = None):
if index != None:
self.powerCurveLevelsListBoxEntry.listbox.delete(index, index)
self.powerCurveLevelsListBoxEntry.listbox.insert(index, text)
else:
self.powerCurveLevelsListBoxEntry.listbox.insert(END, text)
self.sortLevels()
self.validatedPowerCurveLevels.validate()
def removePowerCurveLevels(self):
items = self.powerCurveLevelsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
self.powerCurveLevelsListBoxEntry.listbox.delete(idx, idx)
pos += 1
self.powerCurveLevelsListBoxEntry.listbox.validate()
def sortLevels(self):
levels = {}
for i in range(self.powerCurveLevelsListBoxEntry.listbox.size()):
text = self.powerCurveLevelsListBoxEntry.listbox.get(i)
windSpeed, power = extractPowerLevelValuesFromText(text)
levels[windSpeed] = power
self.powerCurveLevelsListBoxEntry.listbox.delete(0, END)
for windSpeed in sorted(levels):
self.powerCurveLevelsListBoxEntry.listbox.insert(END, encodePowerLevelValueAsText(windSpeed, levels[windSpeed]))
def setConfigValues(self):
self.config.name = self.name.get()
self.config.powerCurveDensity = float(self.referenceDensity.get())
self.config.powerCurveTurbulence = float(self.referenceTurbulence.get())
powerCurveDictionary = {}
for i in range(self.powerCurveLevelsListBoxEntry.listbox.size()):
windSpeed, power = extractPowerLevelValuesFromText(self.powerCurveLevelsListBoxEntry.listbox.get(i))
powerCurveDictionary[windSpeed] = power
self.config.setPowerCurve(powerCurveDictionary)
class AnalysisConfigurationDialog(BaseConfigurationDialog):
def getInitialFileName(self):
return "Analysis"
def addFormElements(self, master):
self.powerCurveMinimumCount = self.addEntry(master, "Power Curve Minimum Count:", ValidatePositiveInteger(master), self.config.powerCurveMinimumCount, showHideCommand = self.generalShowHide)
filterModeOptions = ["All", "Inner", "Outer"]
self.filterMode = self.addOption(master, "Filter Mode:", filterModeOptions, self.config.filterMode, showHideCommand = self.generalShowHide)
powerCurveModes = ["Specified", "AllMeasured", "InnerMeasured", "OuterMeasured"]
self.powerCurveMode = self.addOption(master, "Reference Power Curve Mode:", powerCurveModes, self.config.powerCurveMode, showHideCommand = self.generalShowHide)
self.powerCurvePaddingMode = self.addOption(master, "Power Curve Padding Mode:", ["None", "Linear", "Observed", "Specified", "Max"], self.config.powerCurvePaddingMode, showHideCommand = self.generalShowHide)
powerCurveShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Power Curve Bins:", powerCurveShowHide)
self.powerCurveFirstBin = self.addEntry(master, "First Bin Centre:", ValidateNonNegativeFloat(master), self.config.powerCurveFirstBin, showHideCommand = powerCurveShowHide)
self.powerCurveLastBin = self.addEntry(master, "Last Bin Centre:", ValidateNonNegativeFloat(master), self.config.powerCurveLastBin, showHideCommand = powerCurveShowHide)
self.powerCurveBinSize = self.addEntry(master, "Bin Size:", ValidatePositiveFloat(master), self.config.powerCurveBinSize, showHideCommand = powerCurveShowHide)
datasetsShowHide = ShowHideCommand(master)
Label(master, text="Dataset Configuration XMLs:").grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
datasetsShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.datasetsListBoxEntry = self.addListBox(master, "DataSets ListBox", showHideCommand = datasetsShowHide )
if not self.isNew:
for dataset in self.config.datasets:
self.datasetsListBoxEntry.listbox.insert(END, dataset)
self.datasetsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.validateDatasets = ValidateDatasets(master, self.datasetsListBoxEntry.listbox)
self.validations.append(self.validateDatasets)
self.validateDatasets.messageLabel.grid(row=self.row, sticky=W, column=self.messageColumn)
datasetsShowHide.addControl(self.validateDatasets.messageLabel)
self.newDatasetButton = Button(master, text="New", command = self.NewDataset, width=5, height=1)
self.newDatasetButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
datasetsShowHide.addControl(self.newDatasetButton)
self.editDatasetButton = Button(master, text="Edit", command = self.EditDataset, width=5, height=1)
self.datasetsListBoxEntry.listbox.bind("<Double-Button-1>", self.EditDataset)
self.editDatasetButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
datasetsShowHide.addControl(self.editDatasetButton)
self.addDatasetButton = Button(master, text="+", command = self.addDataset, width=2, height=1)
self.addDatasetButton.grid(row=self.row, sticky=E+N, column=self.buttonColumn)
datasetsShowHide.addControl(self.addDatasetButton)
self.removeDatasetButton = Button(master, text="-", command = self.removeDatasets, width=2, height=1)
self.removeDatasetButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
datasetsShowHide.addControl(self.removeDatasetButton)
self.row += 1
innerRangeShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Inner Range Settings:", innerRangeShowHide)
self.innerRangeLowerTurbulence = self.addEntry(master, "Inner Range Lower Turbulence:", ValidateNonNegativeFloat(master), self.config.innerRangeLowerTurbulence, showHideCommand = innerRangeShowHide)
self.innerRangeUpperTurbulence = self.addEntry(master, "Inner Range Upper Turbulence:", ValidateNonNegativeFloat(master), self.config.innerRangeUpperTurbulence, showHideCommand = innerRangeShowHide)
self.innerRangeLowerShear = self.addEntry(master, "Inner Range Lower Shear:", ValidatePositiveFloat(master), self.config.innerRangeLowerShear, showHideCommand = innerRangeShowHide)
self.innerRangeUpperShear = self.addEntry(master, "Inner Range Upper Shear:", ValidatePositiveFloat(master), self.config.innerRangeUpperShear, showHideCommand = innerRangeShowHide)
turbineSettingsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Turbine Settings:", turbineSettingsShowHide)
self.cutInWindSpeed = self.addEntry(master, "Cut In Wind Speed:", ValidatePositiveFloat(master), self.config.cutInWindSpeed, showHideCommand = turbineSettingsShowHide)
self.cutOutWindSpeed = self.addEntry(master, "Cut Out Wind Speed:", ValidatePositiveFloat(master), self.config.cutOutWindSpeed, showHideCommand = turbineSettingsShowHide)
self.ratedPower = self.addEntry(master, "Rated Power:", ValidatePositiveFloat(master), self.config.ratedPower, showHideCommand = turbineSettingsShowHide)
self.hubHeight = self.addEntry(master, "Hub Height:", ValidatePositiveFloat(master), self.config.hubHeight, showHideCommand = turbineSettingsShowHide)
self.diameter = self.addEntry(master, "Diameter:", ValidatePositiveFloat(master), self.config.diameter, showHideCommand = turbineSettingsShowHide)
self.specifiedPowerCurve = self.addFileOpenEntry(master, "Specified Power Curve:", ValidateSpecifiedPowerCurve(master, self.powerCurveMode), self.config.specifiedPowerCurve, self.filePath, showHideCommand = turbineSettingsShowHide)
self.addPowerCurveButton = Button(master, text="New", command = self.NewPowerCurve, width=5, height=1)
self.addPowerCurveButton.grid(row=(self.row-2), sticky=E+N, column=self.secondButtonColumn)
turbineSettingsShowHide.addControl(self.addPowerCurveButton)
self.editPowerCurveButton = Button(master, text="Edit", command = self.EditPowerCurve, width=5, height=1)
self.editPowerCurveButton.grid(row=(self.row-1), sticky=E+S, column=self.secondButtonColumn)
turbineSettingsShowHide.addControl(self.editPowerCurveButton)
correctionSettingsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Correction Settings:", correctionSettingsShowHide)
self.densityCorrectionActive = self.addCheckBox(master, "Density Correction Active", self.config.densityCorrectionActive, showHideCommand = correctionSettingsShowHide)
self.turbulenceCorrectionActive = self.addCheckBox(master, "Turbulence Correction Active", self.config.turbRenormActive, showHideCommand = correctionSettingsShowHide)
self.rewsCorrectionActive = self.addCheckBox(master, "REWS Correction Active", self.config.rewsActive, showHideCommand = correctionSettingsShowHide)
self.powerDeviationMatrixActive = self.addCheckBox(master, "PDM Correction Active", self.config.powerDeviationMatrixActive, showHideCommand = correctionSettingsShowHide)
self.specifiedPowerDeviationMatrix = self.addFileOpenEntry(master, "Specified PDM:", ValidateSpecifiedPowerDeviationMatrix(master, self.powerDeviationMatrixActive), self.config.specifiedPowerDeviationMatrix, self.filePath, showHideCommand = correctionSettingsShowHide)
advancedSettingsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Advanced Settings:", advancedSettingsShowHide)
self.baseLineMode = self.addOption(master, "Base Line Mode:", ["Hub", "Measured"], self.config.baseLineMode, showHideCommand = advancedSettingsShowHide)
self.interpolationMode = self.addOption(master, "Interpolation Mode:", ["Linear", "Cubic"], self.config.interpolationMode, showHideCommand = advancedSettingsShowHide)
self.nominalWindSpeedDistribution = self.addFileOpenEntry(master, "Nominal Wind Speed Distribution:", ValidateNominalWindSpeedDistribution(master, self.powerCurveMode), self.config.nominalWindSpeedDistribution, self.filePath, showHideCommand = advancedSettingsShowHide)
#hide all initially
self.generalShowHide.show()
powerCurveShowHide.hide()
datasetsShowHide.show()
innerRangeShowHide.hide()
turbineSettingsShowHide.hide()
correctionSettingsShowHide.hide()
advancedSettingsShowHide.hide()
def EditPowerCurve(self):
specifiedPowerCurve = self.specifiedPowerCurve.get()
analysisPath = self.filePath.get()
folder = os.path.dirname(os.path.abspath(analysisPath))
path = os.path.join(folder, specifiedPowerCurve)
if len(specifiedPowerCurve) > 0:
try:
config = configuration.PowerCurveConfiguration(path)
configDialog = PowerCurveConfigurationDialog(self, self.status, self.setSpecifiedPowerCurveFromPath, config)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (specifiedPowerCurve, e))
def NewPowerCurve(self):
config = configuration.PowerCurveConfiguration()
configDialog = PowerCurveConfigurationDialog(self, self.status, self.setSpecifiedPowerCurveFromPath, config)
def EditDataset(self, event = None):
items = self.datasetsListBoxEntry.listbox.curselection()
if len(items) == 1:
index = items[0]
path = self.datasetsListBoxEntry.listbox.get(index)
try:
relativePath = configuration.RelativePath(self.filePath.get())
datasetConfig = configuration.DatasetConfiguration(relativePath.convertToAbsolutePath(path))
configDialog = DatasetConfigurationDialog(self, self.status, self.addDatasetFromPath, datasetConfig, index)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (path, e))
def NewDataset(self):
try:
config = configuration.DatasetConfiguration()
configDialog = DatasetConfigurationDialog(self, self.status, self.addDatasetFromPath, config)
except ExceptionType as e:
self.status.addMessage("ERROR creating dataset config: %s" % e)
def setAnalysisFilePath(self):
fileName = asksaveasfilename(parent=self.master,defaultextension=".xml", initialdir=preferences.workSpaceFolder)
if len(fileName) > 0: self.analysisFilePath.set(fileName)
def setSpecifiedPowerCurve(self):
fileName = SelectFile(parent=self.master,defaultextension=".xml")
self.setSpecifiedPowerCurveFromPath(fileName)
def setSpecifiedPowerCurveFromPath(self, fileName):
if len(fileName) > 0: self.specifiedPowerCurve.set(fileName)
def addDataset(self):
fileName = SelectFile(parent=self.master,defaultextension=".xml")
if len(fileName) > 0: self.addDatasetFromPath(fileName)
def addDatasetFromPath(self, path, index = None):
relativePath = configuration.RelativePath(self.filePath.get())
path = relativePath.convertToRelativePath(path)
if index != None:
self.datasetsListBoxEntry.listbox.delete(index, index)
self.datasetsListBoxEntry.listbox.insert(index, path)
else:
self.datasetsListBoxEntry.listbox.insert(END, path)
self.validateDatasets.validate()
def removeDatasets(self):
items = self.datasetsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
self.datasetsListBoxEntry.listbox.delete(idx, idx)
pos += 1
self.validateDatasets.validate()
def setConfigValues(self):
relativePath = configuration.RelativePath(self.config.path)
self.config.powerCurveMinimumCount = int(self.powerCurveMinimumCount.get())
self.config.filterMode = self.filterMode.get()
self.config.baseLineMode = self.baseLineMode.get()
self.config.interpolationMode = self.interpolationMode.get()
self.config.powerCurveMode = self.powerCurveMode.get()
self.config.powerCurvePaddingMode = self.powerCurvePaddingMode.get()
self.config.nominalWindSpeedDistribution = self.nominalWindSpeedDistribution.get()
self.config.powerCurveFirstBin = self.powerCurveFirstBin.get()
self.config.powerCurveLastBin = self.powerCurveLastBin.get()
self.config.powerCurveBinSize = self.powerCurveBinSize.get()
self.config.innerRangeLowerTurbulence = float(self.innerRangeLowerTurbulence.get())
self.config.innerRangeUpperTurbulence = float(self.innerRangeUpperTurbulence.get())
self.config.innerRangeLowerShear = float(self.innerRangeLowerShear.get())
self.config.innerRangeUpperShear = float(self.innerRangeUpperShear.get())
self.config.cutInWindSpeed = float(self.cutInWindSpeed.get())
self.config.cutOutWindSpeed = float(self.cutOutWindSpeed.get())
self.config.ratedPower = float(self.ratedPower.get())
self.config.hubHeight = float(self.hubHeight.get())
self.config.diameter = float(self.diameter.get())
self.config.specifiedPowerCurve = relativePath.convertToRelativePath(self.specifiedPowerCurve.get())
self.config.densityCorrectionActive = bool(self.densityCorrectionActive.get())
self.config.turbRenormActive = bool(self.turbulenceCorrectionActive.get())
self.config.rewsActive = bool(self.rewsCorrectionActive.get())
self.config.specifiedPowerDeviationMatrix = relativePath.convertToRelativePath(self.specifiedPowerDeviationMatrix.get())
self.config.powerDeviationMatrixActive = bool(self.powerDeviationMatrixActive.get())
self.config.datasets = []
for i in range(self.datasetsListBoxEntry.listbox.size()):
dataset = relativePath.convertToRelativePath(self.datasetsListBoxEntry.listbox.get(i))
self.config.datasets.append(dataset)
class PcwgShare1Dialog(BaseConfigurationDialog):
def _pcwg_defaults(self):
self.powerCurveMinimumCount = 10
self.filterMode = "All"
self.powerCurveMode = "InnerMeasured"
self.powerCurvePaddingMode = "Max"
self.powerCurveFirstBin = 1.
self.powerCurveLastBin = 30.
self.powerCurveBinSize = 1.
self.set_inner_range_values()
self.specifiedPowerCurve = None
self.baseLineMode = "Hub"
self.interpolationMode = "Cubic"
self.nominalWindSpeedDistribution = None
self.specifiedPowerDeviationMatrix = os.getcwd() + os.sep + 'Data' + os.sep + 'HypothesisMatrix.xml'
self.densityCorrectionActive = False
self.turbulenceCorrectionActive = False
self.rewsCorrectionActive = False
self.powerDeviationMatrixActive = False
def set_inner_range_values(self):
self.innerRangeLowerTurbulence = pcwg_inner_ranges[self.inner_range_id]['LTI']
self.innerRangeUpperTurbulence = pcwg_inner_ranges[self.inner_range_id]['UTI']
self.innerRangeLowerShear = pcwg_inner_ranges[self.inner_range_id]['LSh']
self.innerRangeUpperShear = pcwg_inner_ranges[self.inner_range_id]['USh']
def getInitialFileName(self):
return "PCWG Share 1 Analysis Configuration"
def body(self, master):
self.prepareColumns(master)
self.generalShowHide = ShowHideCommand(master)
#add spacer labels
spacer = " "
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.titleColumn)
Label(master, text=spacer * 40).grid(row = self.row, sticky=W, column=self.labelColumn)
Label(master, text=spacer * 80).grid(row = self.row, sticky=W, column=self.inputColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.buttonColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.secondButtonColumn)
Label(master, text=spacer * 40).grid(row = self.row, sticky=W, column=self.messageColumn)
Label(master, text=spacer * 10).grid(row = self.row, sticky=W, column=self.showHideColumn)
self.row += 1
#self.addTitleRow(master, "PCWG Share 1 Analysis Configuration")
self.row += 2
if self.config.isNew:
path = asksaveasfilename(parent=self.master,defaultextension=".xml", initialfile="%s.xml" % self.getInitialFileName(), title="Save PCWG 1 Analysis Configuration", initialdir=preferences.workSpaceFolder)
else:
path = self.config.path
#self.filePath = path#
self.filePath = self.addFileSaveAsEntry(master, "Configuration XML File Path:", ValidateDatasetFilePath(master), path, showHideCommand = self.generalShowHide)
self.addFormElements(master)
def addFormElements(self, master):
datasetsShowHide = ShowHideCommand(master)
Label(master, text="Dataset Configuration XMLs:").grid(row=self.row, sticky=W, column=self.titleColumn, columnspan = 2)
datasetsShowHide.button.grid(row=self.row, sticky=E+W, column=self.showHideColumn)
self.row += 1
self.datasetsListBoxEntry = self.addListBox(master, "DataSets ListBox", showHideCommand = datasetsShowHide )
if not self.isNew:
for dataset in self.config.datasets:
self.datasetsListBoxEntry.listbox.insert(END, dataset)
self.datasetsListBoxEntry.listbox.grid(row=self.row, sticky=W+E+N+S, column=self.labelColumn, columnspan=2)
self.validateDatasets = ValidateDatasets(master, self.datasetsListBoxEntry.listbox)
self.validations.append(self.validateDatasets)
self.validateDatasets.messageLabel.grid(row=self.row, sticky=W, column=self.messageColumn)
datasetsShowHide.addControl(self.validateDatasets.messageLabel)
self.newDatasetButton = Button(master, text="New", command = self.NewDataset, width=5, height=1)
self.newDatasetButton.grid(row=self.row, sticky=E+N, column=self.secondButtonColumn)
datasetsShowHide.addControl(self.newDatasetButton)
self.editDatasetButton = Button(master, text="Edit", command = self.EditDataset, width=5, height=1)
self.datasetsListBoxEntry.listbox.bind("<Double-Button-1>", self.EditDataset)
self.editDatasetButton.grid(row=self.row, sticky=E+S, column=self.secondButtonColumn)
datasetsShowHide.addControl(self.editDatasetButton)
self.addDatasetButton = Button(master, text="+", command = self.addDataset, width=2, height=1)
self.addDatasetButton.grid(row=self.row, sticky=E+N, column=self.buttonColumn)
datasetsShowHide.addControl(self.addDatasetButton)
self.removeDatasetButton = Button(master, text="-", command = self.removeDatasets, width=2, height=1)
self.removeDatasetButton.grid(row=self.row, sticky=E+S, column=self.buttonColumn)
datasetsShowHide.addControl(self.removeDatasetButton)
self.row += 2
turbineSettingsShowHide = ShowHideCommand(master)
self.addTitleRow(master, "Turbine Settings:", turbineSettingsShowHide)
self.cutInWindSpeed = self.addEntry(master, "Cut In Wind Speed:", ValidatePositiveFloat(master), '', showHideCommand = turbineSettingsShowHide)#self.config.cutInWindSpeed
self.cutOutWindSpeed = self.addEntry(master, "Cut Out Wind Speed:", ValidatePositiveFloat(master), '', showHideCommand = turbineSettingsShowHide)#self.config.cutOutWindSpeed
self.ratedPower = self.addEntry(master, "Rated Power:", ValidatePositiveFloat(master), '', showHideCommand = turbineSettingsShowHide)#self.config.ratedPower
self.hubHeight = self.addEntry(master, "Hub Height:", ValidatePositiveFloat(master), '', showHideCommand = turbineSettingsShowHide)#self.config.hubHeight
self.diameter = self.addEntry(master, "Diameter:", ValidatePositiveFloat(master), '', showHideCommand = turbineSettingsShowHide)#self.config.diameter
self.generalShowHide.hide()
datasetsShowHide.show()
turbineSettingsShowHide.show()
def EditDataset(self, event = None):
items = self.datasetsListBoxEntry.listbox.curselection()
if len(items) == 1:
index = items[0]
path = self.datasetsListBoxEntry.listbox.get(index)
try:
relativePath = configuration.RelativePath(self.filePath.get())
datasetConfig = configuration.DatasetConfiguration(relativePath.convertToAbsolutePath(path))
configDialog = DatasetConfigurationDialog(self, self.status, self.addDatasetFromPath, datasetConfig, index)
except ExceptionType as e:
self.status.addMessage("ERROR loading config (%s): %s" % (path, e))
def NewDataset(self):
try:
config = configuration.DatasetConfiguration()
configDialog = DatasetConfigurationDialog(self, self.status, self.addDatasetFromPath, config)
except ExceptionType as e:
self.status.addMessage("ERROR creating dataset config: %s" % e)
def setAnalysisFilePath(self):
fileName = asksaveasfilename(parent=self.master,defaultextension=".xml", initialdir=preferences.workSpaceFolder)
if len(fileName) > 0: self.analysisFilePath.set(fileName)
def addDataset(self):
fileName = SelectFile(parent=self.master,defaultextension=".xml")
if len(fileName) > 0: self.addDatasetFromPath(fileName)
def addDatasetFromPath(self, path, index = None):
relativePath = configuration.RelativePath(self.filePath.get())
path = relativePath.convertToRelativePath(path)
if index != None:
self.datasetsListBoxEntry.listbox.delete(index, index)
self.datasetsListBoxEntry.listbox.insert(index, path)
else:
self.datasetsListBoxEntry.listbox.insert(END, path)
self.validateDatasets.validate()
def removeDatasets(self):
items = self.datasetsListBoxEntry.listbox.curselection()
pos = 0
for i in items:
idx = int(i) - pos
self.datasetsListBoxEntry.listbox.delete(idx, idx)
pos += 1
self.validateDatasets.validate()
def setConfigValues(self, inner_range_id = 'A'):
self.config.path = self.filePath.get()
relativePath = configuration.RelativePath(self.config.path)
self.inner_range_id = inner_range_id
self._pcwg_defaults()
self.config.powerCurveMinimumCount = self.powerCurveMinimumCount
self.config.filterMode = self.filterMode
self.config.baseLineMode = self.baseLineMode
self.config.interpolationMode = self.interpolationMode
self.config.powerCurveMode = self.powerCurveMode
self.config.powerCurvePaddingMode = self.powerCurvePaddingMode
self.config.nominalWindSpeedDistribution = self.nominalWindSpeedDistribution
self.config.powerCurveFirstBin = self.powerCurveFirstBin
self.config.powerCurveLastBin = self.powerCurveLastBin
self.config.powerCurveBinSize = self.powerCurveBinSize
self.config.innerRangeLowerTurbulence = self.innerRangeLowerTurbulence
self.config.innerRangeUpperTurbulence = self.innerRangeUpperTurbulence
self.config.innerRangeLowerShear = self.innerRangeLowerShear
self.config.innerRangeUpperShear = self.innerRangeUpperShear
self.config.cutInWindSpeed = float(self.cutInWindSpeed.get())
self.config.cutOutWindSpeed = float(self.cutOutWindSpeed.get())
self.config.ratedPower = float(self.ratedPower.get())
self.config.hubHeight = float(self.hubHeight.get())
self.config.diameter = float(self.diameter.get())
self.config.specifiedPowerCurve = self.specifiedPowerCurve
self.config.densityCorrectionActive = self.config.densityCorrectionActive
self.config.turbRenormActive = self.turbulenceCorrectionActive
self.config.rewsActive = self.rewsCorrectionActive
self.config.powerDeviationMatrixActive = self.powerDeviationMatrixActive
if self.specifiedPowerDeviationMatrix is not None:
self.config.specifiedPowerDeviationMatrix = relativePath.convertToRelativePath(self.specifiedPowerDeviationMatrix)
self.config.datasets = []
for i in range(self.datasetsListBoxEntry.listbox.size()):
dataset = relativePath.convertToRelativePath(self.datasetsListBoxEntry.listbox.get(i))
self.config.datasets.append(dataset)
class UserInterface:
def __init__(self):
self.analysis = None
self.analysisConfiguration = None
self.root = Tk()
self.root.geometry("800x400")
self.root.title("PCWG")
labelsFrame = Frame(self.root)
settingsFrame = Frame(self.root)
consoleframe = Frame(self.root)
commandframe = Frame(self.root)
load_button = Button(settingsFrame, text="Load", command = self.LoadAnalysis)
edit_button = Button(settingsFrame, text="Edit", command = self.EditAnalysis)
new_button = Button(settingsFrame, text="New", command = self.NewAnalysis)
calculate_button = Button(commandframe, text="Calculate", command = self.Calculate)
export_report_button = Button(commandframe, text="Export Report", command = self.ExportReport)
anonym_report_button = Button(commandframe, text="Export Anonymous Report", command = self.ExportAnonymousReport)
pcwg_share1_report_button = Button(commandframe, text="PCWG Share 1 Report", command = self.export_pcwg_share1_report)
export_time_series_button = Button(commandframe, text="Export Time Series", command = self.ExportTimeSeries)
benchmark_button = Button(commandframe, text="Benchmark", command = self.RunBenchmark)
clear_console_button = Button(commandframe, text="Clear Console", command = self.ClearConsole)
about_button = Button(commandframe, text="About", command = self.About)
set_work_space_button = Button(commandframe, text="Set Work Space", command = self.SetWorkSpace)
self.analysisFilePathLabel = Label(labelsFrame, text="Analysis File")
self.analysisFilePathTextBox = Entry(settingsFrame)
self.analysisFilePathTextBox.config(state=DISABLED)
scrollbar = Scrollbar(consoleframe, orient=VERTICAL)
self.listbox = Listbox(consoleframe, yscrollcommand=scrollbar.set, selectmode=EXTENDED)
scrollbar.configure(command=self.listbox.yview)
new_button.pack(side=RIGHT, padx=5, pady=5)
edit_button.pack(side=RIGHT, padx=5, pady=5)
load_button.pack(side=RIGHT, padx=5, pady=5)
calculate_button.pack(side=LEFT, padx=5, pady=5)
export_report_button.pack(side=LEFT, padx=5, pady=5)
#anonym_report_button.pack(side=LEFT, padx=5, pady=5)
pcwg_share1_report_button.pack(side=LEFT, padx=5, pady=5)
export_time_series_button.pack(side=LEFT, padx=5, pady=5)
benchmark_button.pack(side=LEFT, padx=5, pady=5)
clear_console_button.pack(side=LEFT, padx=5, pady=5)
about_button.pack(side=LEFT, padx=5, pady=5)
set_work_space_button.pack(side=LEFT, padx=5, pady=5)
self.analysisFilePathLabel.pack(anchor=NW, padx=5, pady=5)
self.analysisFilePathTextBox.pack(anchor=NW,fill=X, expand=1, padx=5, pady=5)
self.listbox.pack(side=LEFT,fill=BOTH, expand=1)
scrollbar.pack(side=RIGHT, fill=Y)
commandframe.pack(side=TOP)
consoleframe.pack(side=BOTTOM,fill=BOTH, expand=1)
labelsFrame.pack(side=LEFT)
settingsFrame.pack(side=RIGHT,fill=BOTH, expand=1)
if len(preferences.analysisLastOpened) > 0:
try:
self.addMessage("Loading last analysis opened")
self.LoadAnalysisFromPath(preferences.analysisLastOpened)
except IOError:
self.addMessage("Couldn't load last analysis. File could not be found.")
self.root.mainloop()
def RunBenchmark(self):
self.LoadAnalysisFromPath("")
self.ClearConsole()
#read the benchmark config xml
path = askopenfilename(parent = self.root, title="Select Benchmark Configuration", initialfile = "Data\\Benchmark.xml")
if len(path) > 0:
self.addMessage("Loading benchmark configuration file: %s" % path)
benchmarkConfig = configuration.BenchmarkConfiguration(path)
self.addMessage("Loaded benchmark configuration: %s" % benchmarkConfig.name)
self.addMessage("")
benchmarkPassed = True
totalTime = 0.0
for i in range(len(benchmarkConfig.benchmarks)):
benchmark = benchmarkConfig.benchmarks[i]
self.addMessage("Executing Benchmark %d of %d" % (i + 1, len(benchmarkConfig.benchmarks)))
benchmarkResults = self.BenchmarkAnalysis(benchmark.analysisPath, benchmarkConfig.tolerance, benchmark.expectedResults)
benchmarkPassed = benchmarkPassed & benchmarkResults[0]
totalTime += benchmarkResults[1]
if benchmarkPassed:
self.addMessage("All benchmarks passed")
else:
self.addMessage("There are failing benchmarks", red = True)
self.addMessage("Total Time Taken: %fs" % totalTime)
else:
self.addMessage("No benchmark loaded", red = True)
def BenchmarkAnalysis(self, path, tolerance, dictExpectedResults):
self.addMessage("Calculating %s (please wait)..." % path)
self.addMessage("Benchmark Tolerance: %s" % self.formatPercentTwoDP(tolerance))
benchmarkPassed = True
start = datetime.datetime.now()
try:
analysis = Analysis.Analysis(configuration.AnalysisConfiguration(path))
except ExceptionType as e:
analysis = None
self.addMessage(str(e))
benchmarkPassed = False
if analysis != None:
for (field, value) in dictExpectedResults.iteritems():
try:
benchmarkPassed = benchmarkPassed & self.compareBenchmark(field, value, eval("analysis.%s" % field), tolerance)
except:
raise Exception("Evaluation of analysis.{f} has failed, does this property exist?".format(f=field))
# benchmarkPassed = benchmarkPassed & self.compareBenchmark(field, value, exec("analysis.%s" % field), tolerance)
# benchmarkPassed = benchmarkPassed & self.compareBenchmark("REWS Delta", rewsDelta, analysis.rewsDelta, tolerance)
# benchmarkPassed = benchmarkPassed & self.compareBenchmark("Turbulence Delta", turbulenceDelta, analysis.turbulenceDelta, tolerance)
# benchmarkPassed = benchmarkPassed & self.compareBenchmark("Combined Delta", combinedDelta, analysis.combinedDelta, tolerance)
if benchmarkPassed:
self.addMessage("Benchmark Passed")
else:
self.addMessage("Benchmark Failed", red = True)
end = datetime.datetime.now()
timeTaken = (end - start).total_seconds()
self.addMessage("Time Taken: %fs" % timeTaken)
self.addMessage("")
return (benchmarkPassed, timeTaken)
def formatPercentTwoDP(self, value):
return "%0.2f%%" % (value * 100.0)
def compareBenchmark(self, title, expected, actual, tolerance):
diff = abs(expected - actual)
passed = (diff <= tolerance)
text = "{title}: {expec:0.10} (expected) vs {act:0.10} (actual) =>".format(title = title, expec=expected, act= actual)
if passed:
self.addMessage("%s passed" % text)
else:
self.addMessage("%s failed" % text, red = True)
return passed
def EditAnalysis(self):
if self.analysisConfiguration == None:
self.addMessage("ERROR: Analysis not loaded", red = True)
return
configDialog = AnalysisConfigurationDialog(self.root, WindowStatus(self), self.LoadAnalysisFromPath, self.analysisConfiguration)
def NewAnalysis(self):
conf = configuration.AnalysisConfiguration()
configDialog = AnalysisConfigurationDialog(self.root, WindowStatus(self), self.LoadAnalysisFromPath, conf)
def LoadAnalysis(self):
fileName = SelectFile(self.root)
if len(fileName) < 1: return
self.LoadAnalysisFromPath(fileName)
def SetWorkSpace(self):
folder = askdirectory(parent=self.root, initialdir=preferences.workSpaceFolder)
if len(folder) < 1: return
preferences.workSpaceFolder = folder
preferences.save()
self.addMessage("Workspace set to: %s" % folder)
def LoadAnalysisFromPath(self, fileName):
try:
preferences.analysisLastOpened = fileName
preferences.save()
except ExceptionType as e:
self.addMessage("Cannot save preferences: %s" % e)
self.analysisFilePathTextBox.config(state=NORMAL)
self.analysisFilePathTextBox.delete(0, END)
self.analysisFilePathTextBox.insert(0, fileName)
self.analysisFilePathTextBox.config(state=DISABLED)
self.analysis = None
self.analysisConfiguration = None
if len(fileName) > 0:
try:
self.analysisConfiguration = configuration.AnalysisConfiguration(fileName)
self.addMessage("Analysis config loaded: %s" % fileName)
except ExceptionType as e:
self.addMessage("ERROR loading config: %s" % e, red = True)
def ExportReport(self):
if self.analysis == None:
self.addMessage("ERROR: Analysis not yet calculated", red = True)
return
if not self.analysis.hasActualPower:
self.addMessage("ERROR: No Power Signal in Dataset", red = True)
return
try:
fileName = asksaveasfilename(parent=self.root,defaultextension=".xls", initialfile="report.xls", title="Save Report", initialdir=preferences.workSpaceFolder)
self.analysis.report(fileName, version)
self.addMessage("Report written to %s" % fileName)
except ExceptionType as e:
self.addMessage("ERROR Exporting Report: %s" % e, red = True)
def export_pcwg_share1_report(self):
self.analysisConfiguration = configuration.AnalysisConfiguration()
configDialog = PcwgShare1Dialog(self.root, WindowStatus(self), self.LoadAnalysisFromPath, self.analysisConfiguration)
inner_range_id = 'A'
self.addMessage("Attempting PCWG analysis using Inner Range definition %s." % inner_range_id)
success = False
try:
self.analysis = Analysis.Analysis(self.analysisConfiguration, WindowStatus(self), auto_activate_corrections = True)
self.analysis.pcwg_share_metrics_calc()
if not self._is_sufficient_complete_bins(self.analysis):
raise Exception('Insufficient complete power curve bins')
success = True
except Exception as e:
self.addMessage(str(e), red = True)
self.addMessage("Analysis failed using Inner Range definition %s." % inner_range_id, red = True)
path = self.analysisConfiguration.path
for inner_range_id in ['B','C']:
self.analysisConfiguration = configuration.AnalysisConfiguration(path)
self.addMessage("Attempting PCWG analysis using Inner Range definition %s." % inner_range_id)
configDialog.inner_range_id = inner_range_id
configDialog.set_inner_range_values()
self.analysisConfiguration.innerRangeLowerTurbulence = configDialog.innerRangeLowerTurbulence
self.analysisConfiguration.innerRangeUpperTurbulence = configDialog.innerRangeUpperTurbulence
self.analysisConfiguration.innerRangeLowerShear = configDialog.innerRangeLowerShear
self.analysisConfiguration.innerRangeUpperShear = configDialog.innerRangeUpperShear
self.analysisConfiguration.save()
try:
self.analysis = Analysis.Analysis(self.analysisConfiguration, WindowStatus(self), auto_activate_corrections = True)
self.analysis.pcwg_share_metrics_calc()
if not self._is_sufficient_complete_bins(self.analysis):
raise Exception('Insufficient complete power curve bins')
success = True
break
except Exception as e:
self.addMessage(str(e), red = True)
self.addMessage("Analysis failed using Inner Range definition %s." % inner_range_id, red = True)
if success:
if self.analysis == None:
self.addMessage("ERROR: Analysis not yet calculated", red = True)
return
if not self.analysis.hasActualPower or not self.analysis.config.turbRenormActive:
self.addMessage("ERROR: Anonymous report can only be generated if analysis has actual power and turbulence renormalisation is active.", red = True)
return
try:
fileName = asksaveasfilename(parent=self.root,defaultextension=".xls", initialfile="PCWG Share 1 Report.xls", title="Save PCWG Share 1 Report", initialdir=preferences.workSpaceFolder)
self.analysis.pcwg_data_share_report(version = version, output_fname = fileName)
self.addMessage("Report written to %s" % fileName)
except ExceptionType as e:
self.addMessage("ERROR Exporting Report: %s" % e, red = True)
def _is_sufficient_complete_bins(self, analysis):
#Todo refine to be fully consistent with PCWG-Share-01 definition document
return (len(analysis.powerCurveCompleteBins) >= 12)
def ExportAnonymousReport(self):
scatter = True
deviationMatrix = True
selections = ExportAnonReportPickerDialog(self.root, None)
scatter, deviationMatrix = selections.getSelections()
if self.analysis == None:
self.addMessage("ERROR: Analysis not yet calculated", red = True)
return
if not self.analysis.hasActualPower or not self.analysis.config.turbRenormActive:
self.addMessage("ERROR: Anonymous report can only be generated if analysis has actual power and turbulence renormalisation is active.", red = True)
deviationMatrix = False
return
try:
fileName = asksaveasfilename(parent=self.root,defaultextension=".xls", initialfile="anonym_report.xls", title="Save Anonymous Report", initialdir=preferences.workSpaceFolder)
self.analysis.anonym_report(fileName, version, scatter = scatter, deviationMatrix = deviationMatrix)
self.addMessage("Anonymous report written to %s" % fileName)
if hasattr(self.analysis,"observedRatedWindSpeed") and hasattr(self.analysis,"observedRatedPower"):
self.addMessage("Wind speeds have been normalised to {ws}".format(ws=self.analysis.observedRatedWindSpeed))
self.addMessage("Powers have been normalised to {pow}".format(pow=self.analysis.observedRatedPower))
except ExceptionType as e:
self.addMessage("ERROR Exporting Anonymous Report: %s" % e, red = True)
def ExportTimeSeries(self):
if self.analysis == None:
self.addMessage("ERROR: Analysis not yet calculated", red = True)
return
try:
selections = ExportDataSetDialog(self.root, None)
clean, full, calibration = selections.getSelections()
fileName = asksaveasfilename(parent=self.root,defaultextension=".dat", initialfile="timeseries.dat", title="Save Time Series", initialdir=preferences.workSpaceFolder)
self.analysis.export(fileName, clean, full, calibration)
if clean:
self.addMessage("Time series written to %s" % fileName)
if any((full, calibration)):
self.addMessage("Extra time series have been written to %s" % self.analysis.config.path.split(".")[0] + "_TimeSeriesData")
except ExceptionType as e:
self.addMessage("ERROR Exporting Time Series: %s" % e, red = True)
def Calculate(self):
if self.analysisConfiguration == None:
self.addMessage("ERROR: Analysis Config file not specified", red = True)
return
try:
self.analysis = Analysis.Analysis(self.analysisConfiguration, WindowStatus(self))
except ExceptionType as e:
self.addMessage("ERROR Calculating Analysis: %s" % e, red = True)
def ClearConsole(self):
self.listbox.delete(0, END)
self.root.update()
def About(self):
tkMessageBox.showinfo("PCWG-Tool About", "Version: {vers} \nVisit http://www.pcwg.org for more info".format(vers=version))
def addMessage(self, message, red=False):
self.listbox.insert(END, message)
if red:
self.listbox.itemconfig(END, {'bg':'red','foreground':"white"})
self.listbox.see(END)
self.root.update()
if __name__ == "__main__":
preferences = configuration.Preferences()
gui = UserInterface()
preferences.save()
print "Done"
| mit |
ActiDoo/gamification-engine | gengine/app/alembic/versions/65c7a32b7322_achievement_date_unique.py | 2270 | """achievement_date_unique
Revision ID: 65c7a32b7322
Revises: d4a70083f72e
Create Date: 2017-01-31 23:01:11.744725
"""
# revision identifiers, used by Alembic.
revision = '65c7a32b7322'
down_revision = 'd4a70083f72e'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.execute("ALTER TABLE achievements_users DROP CONSTRAINT pk_achievements_users;")
op.execute("ALTER TABLE achievements_users ADD COLUMN id SERIAL;")
op.execute("ALTER TABLE achievements_users ADD CONSTRAINT pk_achievements_users PRIMARY KEY(id);")
op.execute("ALTER TABLE goal_evaluation_cache DROP CONSTRAINT pk_goal_evaluation_cache;")
op.execute("ALTER TABLE goal_evaluation_cache ADD COLUMN id SERIAL;")
op.execute("ALTER TABLE goal_evaluation_cache ADD CONSTRAINT pk_goal_evaluation_cache PRIMARY KEY(id);")
op.create_index('idx_achievements_users_date_not_null_unique', 'achievements_users', ['user_id', 'achievement_id', 'achievement_date', 'level'], unique=True, postgresql_where=sa.text('achievement_date IS NOT NULL'))
op.create_index('idx_achievements_users_date_null_unique', 'achievements_users', ['user_id', 'achievement_id', 'level'], unique=True, postgresql_where=sa.text('achievement_date IS NULL'))
op.create_index(op.f('ix_achievements_users_achievement_id'), 'achievements_users', ['achievement_id'], unique=False)
op.create_index(op.f('ix_achievements_users_level'), 'achievements_users', ['level'], unique=False)
op.create_index('idx_goal_evaluation_cache_date_not_null_unique', 'goal_evaluation_cache', ['user_id', 'goal_id', 'achievement_date'], unique=True, postgresql_where=sa.text('achievement_date IS NOT NULL'))
op.create_index('idx_goal_evaluation_cache_date_null_unique', 'goal_evaluation_cache', ['user_id', 'goal_id'], unique=True, postgresql_where=sa.text('achievement_date IS NULL'))
op.create_index(op.f('ix_goal_evaluation_cache_goal_id'), 'goal_evaluation_cache', ['goal_id'], unique=False)
op.create_index(op.f('ix_goal_evaluation_cache_user_id'), 'goal_evaluation_cache', ['user_id'], unique=False)
### end Alembic commands ###
def downgrade():
pass
# not possible !
| mit |
UTF2390/Racons | application/controllers/Alumno.php | 2993 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Alumno extends CI_Controller {
public $modelo_alumno;
public function __construct() {
parent::__construct();
If ($this->session->userdata['rol'] != 'alumno') {
session_destroy();
redirect('/home');
}
}
public function index() {
$this->load->model('Taller_model');
$this->load->model('Horario_model');
$taller = new Taller_model();
$horario = new Horario_model();
$id_alumno = $taller->session->userdata('id_alumno');
$id_curso = $taller->session->userdata('id_curso');
$data['horario'] = $taller->taller_alumno_horario($id_alumno, $id_curso);
$data['dias_semana'] = $horario->dias_semana();
$this->load->view('head');
$this->load->view('horario', $data);
}
public function lista_taller() {
$this->load->model('Taller_model');
$taller = new Taller_model();
$data['title'] = 'Paginacion_ci';
$config['base_url'] = base_url() . 'alumno/lista_taller'; // parametro base de la aplicación, si tenemos un .htaccess nos evitamos el index.php
// $config['total_rows'] = $taller->filas_taller_alumno();//calcula el número de filas
$config['total_rows'] = $taller->numero_filas_taller_alumno();;
$config['per_page'] = 7; //Número de registros mostrados por páginas
$config['num_links'] = 10; //Número de links mostrados en la paginación
$config['first_link'] = 'Primera'; //primer link
$config['last_link'] = 'Última'; //último link
$config['uri_segment'] = 3; //el segmento de la paginación
$config['next_link'] = 'Siguiente'; //siguiente link
$config['prev_link'] = 'Anterior'; //anterior link
$this->pagination->initialize($config); //inicializamos la paginación
$data["talleres"] = $taller->total_paginados_alumno($config['per_page'], $this->uri->segment(3));
$data['paginacion'] = $this->pagination->create_links();
$this->load->view('head');
$this->load->view('taller_alumno', $data);
}
public function apuntarse($id_taller) {
$this->load->model('Taller_model');
$taller = new Taller_model();
$id_alumno = $taller->session->userdata('id_alumno');
// var_dump($id_alumno);
$q = $taller->apuntar($id_taller, $id_alumno);
$data = $q[0]['respuesta'];
echo $data;
return $data;
// redirect('alumno/lista_taller');
}
public function desapuntarse($id_taller) {
$this->load->model('Taller_model');
$taller = new Taller_model();
$id_alumno = $taller->session->userdata('id_alumno');
$respuesta = $taller->desapuntar($id_taller, $id_alumno);
if($respuesta == true){
echo 'ok';
}else{
echo 'No estabas apuntado a esta asignatura (-.-) Hacker!!';
}
}
}
| mit |
previtus/MGR-Project-Code | Settings/independent_experiments/finetunning_tests/finetune_tests_varAdeep.py | 1783 | def Setup(Settings,DefaultModel):
# finetune_tests_varA.py
Settings["experiment_name"] = "Finetuning-tests_big_cca_10hrs_experiment_1k50_varAdeep-useFeat-152"
Settings["graph_histories"] = ['together'] #['all','together',[],[1,0],[0,0,0],[]]
n = 0
Settings["models"][n]["model_type"] = 'simple_cnn_with_top'
Settings["models"][n]["unique_id"] = '1k50_varAdeep-useFeat-152'
Settings["models"][n]["epochs"] = 1000
Settings["models"][n]["number_of_images"] = None
Settings["models"][n]["cooking_method"] = 'generators'
Settings["models"][n]["finetune"] = True
Settings["models"][n]["finetune_num_of_cnn_layers"] = 152
Settings["models"][n]["finetune_epochs"] = 50
Settings["models"][n]["finetune_DEBUG_METHOD_OF_MODEL_GEN"] = True
# 5 cca 1 hour
# 50 cca 10 hrs?
'''
16 <keras.layers.merge.Add object at 0x7f5517c4ed50>
26 <keras.layers.merge.Add object at 0x7f55179e3710>
36 <keras.layers.merge.Add object at 0x7f5514a647d0>
48 <keras.layers.merge.Add object at 0x7f5514867d50>
58 <keras.layers.merge.Add object at 0x7f5514746710>
68 <keras.layers.merge.Add object at 0x7f55145c97d0>
78 <keras.layers.merge.Add object at 0x7f5514449890>
90 <keras.layers.merge.Add object at 0x7f551424ce10>
100 <keras.layers.merge.Add object at 0x7f551404e7d0>
110 <keras.layers.merge.Add object at 0x7f5513ecf890>
120 <keras.layers.merge.Add object at 0x7f5513d53850>
130 <keras.layers.merge.Add object at 0x7f5513bd3910>
140 <keras.layers.merge.Add object at 0x7f5513a599d0>
152 <keras.layers.merge.Add object at 0x7f551385cfd0>
162 <keras.layers.merge.Add object at 0x7f55136e0910>
172 <keras.layers.merge.Add object at 0x7f55135639d0>
'''
return Settings
| mit |
jmagly/BlockScriptEditTools | BlockScriptItemTemplate/Properties/AssemblyInfo.cs | 1422 | 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("BlockScriptItemTemplate")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BlockScriptItemTemplate")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("38e535cd-23ee-4a4f-aad5-6ea912c9c539")]
// 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 |
zhangtdavid/SimCity | src/city/gui/interiors/RestaurantZhangPanel.java | 3427 | package city.gui.interiors;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import utilities.RestaurantZhangTable;
import city.bases.interfaces.AnimationInterface;
import city.gui.BuildingCard;
public class RestaurantZhangPanel extends BuildingCard implements ActionListener {
private static final long serialVersionUID = 1255285244678935863L;
private static BufferedImage restaurantZhangBackgroundImage = null;
private static BufferedImage restaurantZhangTableImage = null;
private static BufferedImage restaurantZhangGrillImage = null;
private static BufferedImage restaurantZhangPlatingImage = null;
private static BufferedImage restaurantZhangWaitingAreaImage = null;
private Collection<RestaurantZhangTable> tables = new ArrayList<RestaurantZhangTable>();
public RestaurantZhangPanel(Color color) {
super(color);
setVisible(true);
Timer timer = new Timer(delayMS, this);
timer.start();
try {
if(restaurantZhangBackgroundImage == null) {
restaurantZhangBackgroundImage = ImageIO.read(RestaurantZhangPanel.class.getResource("/icons/restaurantZhangPanel/RestaurantZhangBackgroundImage.png"));
restaurantZhangGrillImage = ImageIO.read(RestaurantZhangPanel.class.getResource("/icons/restaurantZhangPanel/RestaurantZhangGrillImage.png"));
restaurantZhangPlatingImage = ImageIO.read(RestaurantZhangPanel.class.getResource("/icons/restaurantZhangPanel/RestaurantZhangPlatingImage.png"));
restaurantZhangTableImage = ImageIO.read(RestaurantZhangPanel.class.getResource("/icons/restaurantZhangPanel/RestaurantZhangTableImage.png"));
restaurantZhangWaitingAreaImage = ImageIO.read(RestaurantZhangPanel.class.getResource("/icons/restaurantZhangPanel/RestaurantZhangWaitingAreaImage.png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
}
@Override
public void paint(Graphics graphics) {
Graphics2D graphics2D = (Graphics2D)graphics;
// Clear the screen by painting a rectangle the size of the frame
graphics2D.setColor(Color.yellow);
graphics2D.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
graphics2D.drawImage(restaurantZhangBackgroundImage, 0, 0, null);
graphics.setColor(Color.black);
graphics.drawImage(restaurantZhangWaitingAreaImage, 20, 15, null);
graphics.setColor(Color.GRAY);
for(int i = 0; i < 3; i++) {
graphics.drawImage(restaurantZhangGrillImage, 100 + 70 * i, 10, null);
graphics.drawString("Grill " + i, 100 + 70 * i, 10);
}
graphics.setColor(Color.LIGHT_GRAY);
graphics.drawImage(restaurantZhangPlatingImage, 100, 100, null);
graphics.drawString("Plating", 100, 100);
graphics.setColor(Color.ORANGE);
graphics.setColor(Color.ORANGE);
for(RestaurantZhangTable t : tables) {
graphics.drawImage(restaurantZhangTableImage, t.getX(), t.getY(), null);
}
animate();
// Draw each visible element after updating their positions
synchronized(animations) {
for(AnimationInterface animation : animations) {
if (animation.getVisible()) {
animation.draw(graphics2D);
}
}
}
}
public void setTables(Collection<RestaurantZhangTable> t) {
tables = t;
}
}
| mit |
wolli2710/SleepStagingVisualization | rawDataPreparation/create_pre_processed_rawdata_files.py | 6808 | #this file needs the filename format audio_26_mattrass instead of audio_1407157806
#this file needs the filename format acceleration_26_mattrass instead of acceleration_1407157806
import time
import json
import math
import numpy as np
import pandas as pd
import datetime
acceleration_filename = "acceleration_"
audio_filename = "audio_"
positions = [ "_mattrass","_right_arm"]
outputFormat = "csv"
separator = ","
hz = 500
interval = 1.0
def calculate_distance(vec1, vec2):
return math.sqrt( math.pow( (vec1[0]-vec2[0]), 2) + math.pow( (vec1[1]-vec2[1]), 2) + math.pow( (vec1[2]-vec2[2]), 2) )
def interpolateAcceleration(array):
n = [np.nan]*hz
l = float(len(n)) / len(array)
for i in range(0, len(array)):
j = int(math.floor(i*l))
n[j] = array[i] * 100
return n
def interpolate(n, lastValue=0):
if np.isnan(n[0]):
n[0] = lastValue
val1=np.nan
i1 = 0
for i in range(0,len(n)):
if not np.isnan(n[i]) and not np.isnan(val1):
interpolation = (n[i] - val1) / (i - i1)
step = 0
for j in range(i1, i+1):
n[j] = val1 + (interpolation * step)
step += 1
val1=n[i]
i1 = i
if not np.isnan(n[i]) and np.isnan(val1):
val1 = n[i]
i1 = i
if np.isnan(n[-1]):
for i in range(i1, len(n)):
n[i] = val1
return n
def interpolateSoundValues( currentValues ):
n = [np.nan]*hz
l = float(len(n)) / len(currentValues)
for i in range(0, len(currentValues)):
j = int( math.floor(i*l) )
n[j] = currentValues[i]
return n
for pos in positions:
for vp in range(26, 32):
markerFileLines = open("../marker_files/timestamp_and_marker_"+str(vp)+".txt", "r").readlines()
startTimestamp = int(markerFileLines[0])
start = int(markerFileLines[1])
current_folder = "../result_data_vp"+str(vp)+pos+"/"
outputFile = open(current_folder+"VP"+str(vp)+pos+"_output."+outputFormat, "w")
print("raw data started")
for line in open("../sleep_staging_files/VP"+str(vp)+"_NAP.txt", "r").readlines():
line = line.replace(",", ".")
values = line.split(" ")
values2 = []
for i in range(start, len(values)):
try:
y = float(values[i])
values2.append( y )
except ValueError:
y
outputFile.write(str(values[0])+separator)
for line in values2:
outputFile.write(str(line)+separator)
outputFile.write("\n")
lastVector = [0,0,0]
nextSecond = 0
currentDistances = []
allValues = []
accelerationLines = open(current_folder+acceleration_filename+str(vp)+pos, "r").readlines()
lastValue = 0
print("acceleration data started")
outputFile.write("acceleration"+separator)
cnt = 0
for line in accelerationLines:
line = line[0:-2]
j = json.loads(line)
array = j.values()
try:
distance = calculate_distance(lastVector, array[0])
lastVector = array[0]
except KeyError:
j
try:
timestamp = int(j.keys()[0])
if timestamp >= startTimestamp:
t = float(timestamp / 1000000000)
currentDistances.append(distance)
if( t >= nextSecond ):
cnt += 1
nextSecond = t+interval
n = interpolateAcceleration( currentDistances )
allValues = interpolate(n, lastValue)
lastValue = allValues[-1]
currentDistances = []
for line in allValues:
outputFile.write(str(line)+separator)
except ValueError:
print(timestamp)
print("cnt "+str(cnt))
outputFile.write("\n")
currentValues = []
soundLines = open(current_folder+audio_filename+str(vp)+pos, "r").readlines()
nextSecond = 0
print("sound data started")
outputFile.write("audio"+separator)
for line in soundLines:
line = line[0:-2]
j = json.loads(line)
array = j.values()
try:
timestamp = int(j.keys()[0])
value = int(array[0])
if value == 0:
value = np.nan
if timestamp >= startTimestamp:
t = timestamp / 1000
currentValues.append(value)
if( t >= nextSecond ):
nextSecond = t+interval
n = interpolateSoundValues( currentValues )
allValues = interpolate(n, lastValue)
lastValue = allValues[-1]
currentValues = []
for line in allValues:
outputFile.write(str(line)+separator)
except ValueError:
print(timestamp)
# outputFile.write("\n")
outputFile.close()
outputFormat = "csv"
positions = ["_right_arm", "_mattrass"]
for pos in positions:
for vp in range(26, 32):
filename = "VP"+str(vp)+pos+"_output."+outputFormat
f = open(filename, "r").readlines()
f2 = open("r_"+filename, "w")
lines = 25
length = len(f[0])
print(length)
n = [[0]*(length*10)]*(lines+1)
for i in range(0, lines+1):
n[i] = f[i].split(",")
if(len(n[i]) < length):
length = len(n[i])
print(length)
cnt = 0
for i in range(0, length):
for j in range(0, lines+1):
cnt += 1
f2.write( n[j][i])
if j==lines:
f2.write("\n")
else:
f2.write(",")
print(cnt)
f2.close()
######## interpolation test cases ##############
# n1 = [1, np.nan, np.nan, 100]
# n1 = [-10, np.nan, np.nan, 100, np.nan, -200]
# n1 = [-10, np.nan, np.nan, -200, np.nan, 200]
# n1 = [np.nan, -10, np.nan, np.nan, -200, np.nan, 200]
# n1 = [np.nan, -10, np.nan, np.nan, -200, np.nan, 200, np.nan, np.nan]
# n1 = [0, np.nan, np.nan, np.nan, 100]
# print(interpolate(n1, 200))
# print(interpolate(n1)) | mit |
PTS3-S34A/Soccar | Soccar [Client]/src/nl/soccar/ui/input/Keyboard.java | 4241 | package nl.soccar.ui.input;
import javafx.scene.input.KeyCode;
import nl.soccar.physics.enumeration.HandbrakeAction;
import nl.soccar.physics.enumeration.SteerAction;
import nl.soccar.physics.enumeration.ThrottleAction;
import java.util.ArrayList;
import java.util.List;
/**
* The Keyboard class keeps track of all pressed (and in turn released) keys.
*
* @author PTS34A
*/
public final class Keyboard {
// Stores the keys that are being pressed at any time.
private static final List<KeyCode> PRESSED_KEYS;
// Stores the key binds.
private static final List<KeyCode> ACCELERATE;
private static final List<KeyCode> REVERSE;
private static final List<KeyCode> STEER_LEFT;
private static final List<KeyCode> STEER_RIGHT;
private static final List<KeyCode> HANDBRAKE;
static {
PRESSED_KEYS = new ArrayList<>();
// Accelerate binds
ACCELERATE = new ArrayList<>();
ACCELERATE.add(KeyCode.W);
ACCELERATE.add(KeyCode.UP);
// Reverse binds
REVERSE = new ArrayList<>();
REVERSE.add(KeyCode.S);
REVERSE.add(KeyCode.DOWN);
// Steer left binds
STEER_LEFT = new ArrayList<>();
STEER_LEFT.add(KeyCode.A);
STEER_LEFT.add(KeyCode.LEFT);
// Steer right binds
STEER_RIGHT = new ArrayList<>();
STEER_RIGHT.add(KeyCode.D);
STEER_RIGHT.add(KeyCode.RIGHT);
// Handbrake binds
HANDBRAKE = new ArrayList<>();
HANDBRAKE.add(KeyCode.SPACE);
}
/**
* Constructor
*/
private Keyboard() {
}
/**
* Method that checks if the given key is already present in pressedKeys
* list.
*
* @param code The keycode that needs to be checked.
* @return boolean True if already pressed, false if not in pressedKeys
* list.
*/
public static boolean isPressed(KeyCode code) {
return PRESSED_KEYS.contains(code);
}
/**
* Method that adds the given KeyCode to the pressedKeys list.
*
* @param code The keycode that needs to be added to the pressedKeys list.
*/
public static void setKeyPressed(KeyCode code) {
if (!PRESSED_KEYS.contains(code)) {
PRESSED_KEYS.add(0, code); // Prepend to the list, so the last key pressed gets first priority
}
}
/**
* Method that removes the given KeyCode from the pressedKeys list.
*
* @param code The keycode that needs to be removed of the pressedKeys list.
*/
public static void setKeyReleased(KeyCode code) {
PRESSED_KEYS.remove(code);
}
/**
* Returns the correct ThrottleAction based on the current pressed keys
*
* @return ThrottleAction
*/
public static ThrottleAction getThrottleAction() {
// The last pressed key
for (KeyCode pressedKey : PRESSED_KEYS) {
if (ACCELERATE.contains(pressedKey)) {
return ThrottleAction.ACCELERATE;
}
if (REVERSE.contains(pressedKey)) {
return ThrottleAction.REVERSE;
}
}
return ThrottleAction.IDLE;
}
/**
* Returns the correct SteerAction based on the current pressed keys
*
* @return SteerAction
*/
public static SteerAction getSteerAction() {
for (KeyCode pressedKey : PRESSED_KEYS) {
if (STEER_LEFT.contains(pressedKey)) {
return SteerAction.STEER_LEFT;
}
if (STEER_RIGHT.contains(pressedKey)) {
return SteerAction.STEER_RIGHT;
}
}
return SteerAction.NONE;
}
/**
* Returns the correct HandbrakeAction based on the current pressed keys
*
* @return SteerAction
*/
public static HandbrakeAction getHandbrakeAction() {
for (KeyCode pressedKey : PRESSED_KEYS) {
if (HANDBRAKE.contains(pressedKey)) {
return HandbrakeAction.ACTIVE;
}
}
return HandbrakeAction.INACTIVE;
}
}
| mit |
hunterae/cancan | lib/cancan/inherited_resource.rb | 441 | module CanCan
# For use with Inherited Resources
class InheritedResource < ControllerResource # :nodoc:
def load_resource_instance
if parent?
@controller.send :parent
elsif new_actions.include? @params[:action].to_sym
@controller.send :build_resource
else
@controller.send :resource
end
end
def resource_base
@controller.send :end_of_association_chain
end
end
end
| mit |
Mart-Bogdan/IoC-manager-net | Innahema.Ioc.Manager/Windsor/Installers/Helper.cs | 532 | using System;
using Bender.Reflection;
using Castle.MicroKernel.Registration;
using Innahema.Ioc.Common.Attributes;
namespace Innahema.Ioc.Manager.Windsor.Installers
{
internal static class Helper
{
public static ComponentRegistration<T> ConfigIsDefaultImpl<T>(this ComponentRegistration<T> cr, Type type)
where T : class
{
if (type.HasAttribute<DefaultImplementation>())
{
return cr.IsDefault();
}
return cr;
}
}
} | mit |
holyman2k/commic | src/app/reducers/settingsReducer.js | 586 | import clone from "clone";
const initialState = {
expand: false,
};
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case "EXPAND": {
const newState = clone(state);
newState.settings = payload;
newState.expand = true;
return newState;
}
case "COLLAPSE": {
const newState = clone(state);
newState.settings = payload;
newState.expand = false;
return newState;
}
}
return state;
} | mit |
VelvetMirror/login | app/cache/dev/twig/96/e6/f79ee861b7e8f7d2e5ff4480d4ef.php | 8155 | <?php
/* WebProfilerBundle:Collector:events.html.twig */
class __TwigTemplate_96e6f79ee861b7e8f7d2e5ff4480d4ef extends Twig_Template
{
protected $parent;
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->blocks = array(
'menu' => array($this, 'block_menu'),
'panel' => array($this, 'block_panel'),
);
}
public function getParent(array $context)
{
if (null === $this->parent) {
$this->parent = $this->env->loadTemplate("WebProfilerBundle:Profiler:layout.html.twig");
}
return $this->parent;
}
protected function doDisplay(array $context, array $blocks = array())
{
$context = array_merge($this->env->getGlobals(), $context);
// line 3
$context['__internal_96e6f79ee861b7e8f7d2e5ff4480d4ef_1'] = $this;
$this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
}
// line 5
public function block_menu($context, array $blocks = array())
{
// line 6
echo "<span class=\"label\">
<span class=\"icon\"><img src=\"";
// line 7
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/webprofiler/images/profiler/events.png"), "html");
echo "\" alt=\"Events\" /></span>
<strong>Events</strong>
</span>
";
}
// line 12
public function block_panel($context, array $blocks = array())
{
// line 13
echo " <h2>Called Listeners</h2>
<table>
<tr>
<th>Event name</th>
<th>Listener</th>
</tr>
";
// line 20
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getContext($context, 'collector'), "calledlisteners", array(), "any", false));
foreach ($context['_seq'] as $context['_key'] => $context['listener']) {
// line 21
echo " <tr>
<td><code>";
// line 22
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'listener'), "event", array(), "any", false), "html");
echo "</code></td>
<td><code>";
// line 23
echo twig_escape_filter($this->env, $this->getAttribute($context['__internal_96e6f79ee861b7e8f7d2e5ff4480d4ef_1'], "display_listener", array($this->getContext($context, 'listener'), ), "method", false), "html");
echo "</code></td>
</tr>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['listener'], $context['_parent'], $context['loop']);
$context = array_merge($_parent, array_intersect_key($context, $_parent));
// line 26
echo " </table>
";
// line 28
if ($this->getAttribute($this->getContext($context, 'collector'), "notcalledlisteners", array(), "any", false)) {
// line 29
echo " <h2>Not Called Listeners</h2>
<table>
<tr>
<th>Event name</th>
<th>Listener</th>
</tr>
";
// line 36
$context['listeners'] = $this->getAttribute($this->getContext($context, 'collector'), "notcalledlisteners", array(), "any", false);
// line 37
echo " ";
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable(twig_sort_filter(twig_get_array_keys_filter($this->getContext($context, 'listeners'))));
foreach ($context['_seq'] as $context['_key'] => $context['listener']) {
// line 38
echo " <tr>
<td><code>";
// line 39
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getContext($context, 'listeners'), $this->getContext($context, 'listener'), array(), "array", false), "event", array(), "any", false), "html");
echo "</code></td>
<td><code>";
// line 40
echo twig_escape_filter($this->env, $this->getAttribute($context['__internal_96e6f79ee861b7e8f7d2e5ff4480d4ef_1'], "display_listener", array($this->getAttribute($this->getContext($context, 'listeners'), $this->getContext($context, 'listener'), array(), "array", false), ), "method", false), "html");
echo "</code></td>
</tr>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['listener'], $context['_parent'], $context['loop']);
$context = array_merge($_parent, array_intersect_key($context, $_parent));
// line 43
echo " </table>
";
}
}
// line 47
public function getdisplay_listener($listener = null)
{
$context = array_merge($this->env->getGlobals(), array(
"listener" => $listener,
));
ob_start();
// line 48
echo " ";
if (($this->getAttribute($this->getContext($context, 'listener'), "type", array(), "any", false) == "Closure")) {
// line 49
echo " Closure
";
} elseif (($this->getAttribute($this->getContext($context, 'listener'), "type", array(), "any", false) == "Function")) {
// line 51
echo " ";
$context['link'] = $this->env->getExtension('code')->getFileLink($this->getAttribute($this->getContext($context, 'listener'), "file", array(), "any", false), $this->getAttribute($this->getContext($context, 'listener'), "line", array(), "any", false));
// line 52
echo " ";
if ($this->getContext($context, 'link')) {
echo "<a href=\"";
echo twig_escape_filter($this->env, $this->getContext($context, 'link'), "html");
echo "\">";
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'listener'), "function", array(), "any", false), "html");
echo "</a>";
} else {
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'listener'), "function", array(), "any", false), "html");
}
// line 53
echo " ";
} elseif (($this->getAttribute($this->getContext($context, 'listener'), "type", array(), "any", false) == "Method")) {
// line 54
echo " ";
$context['link'] = $this->env->getExtension('code')->getFileLink($this->getAttribute($this->getContext($context, 'listener'), "file", array(), "any", false), $this->getAttribute($this->getContext($context, 'listener'), "line", array(), "any", false));
// line 55
echo " ";
echo $this->env->getExtension('code')->abbrClass($this->getAttribute($this->getContext($context, 'listener'), "class", array(), "any", false));
echo "::";
if ($this->getContext($context, 'link')) {
echo "<a href=\"";
echo twig_escape_filter($this->env, $this->getContext($context, 'link'), "html");
echo "\">";
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'listener'), "method", array(), "any", false), "html");
echo "</a>";
} else {
echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, 'listener'), "method", array(), "any", false), "html");
}
// line 56
echo " ";
}
return ob_get_clean();
}
public function getTemplateName()
{
return "WebProfilerBundle:Collector:events.html.twig";
}
public function isTraitable()
{
return false;
}
}
| mit |
ranian129/webworkbook | webworkbook/src/spms/dao/ProjectDao.java | 382 | package spms.dao;
import java.util.HashMap;
import java.util.List;
import spms.vo.Project;
public interface ProjectDao {
List<Project> selectList(HashMap<String, Object> paramMap) throws Exception;
int insert(Project project) throws Exception;
Project selectOne(int no) throws Exception;
int update(Project project) throws Exception;
int delete(int no) throws Exception;
}
| mit |
hedwig-project/dashboard | src/routes/AccessModulePage/components/LightConfiguration.js | 2990 | import React, {
Component,
PropTypes,
} from 'react'
import styled from 'styled-components'
import { Field } from 'redux-form'
import { TextField } from 'redux-form-material-ui'
import FontIcon from 'material-ui/FontIcon'
import RaisedButton from 'material-ui/RaisedButton'
const Form = styled.form`
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: #E0F7FA;
color: #006064;
padding: 40px 20px;
`
const Title = styled.div`
flex: 1 1 300px;
display: flex;
align-items: center;
font-family: 'Roboto', sans-serif;
font-size: 24px;
`
const LightConfigurationField = styled.div`
flex: 1 1 250px;
display: flex;
align-items: center;
font-family: 'Roboto', sans-serif;
`
const SubmitButton = styled.div`
flex: 1;
display: flex;
align-items: center;
justify-content: flex-end;
`
class LightConfiguration extends Component {
iconStyle = {
fontSize: '38px',
lineHeight: '24px',
marginRight: '10px',
verticalAlign: 'top',
}
render() {
const { lightConfigurationSubmit, handleSubmit } = this.props
return (
<Form onSubmit={handleSubmit(lightConfigurationSubmit)}>
<Title>
<FontIcon
className="fa fa-lightbulb-o"
color={'#006064'}
style={this.iconStyle}
/>
Configurar luzes
</Title>
<LightConfigurationField>
<Field
component={TextField}
name={'initialTime'}
floatingLabelFixed
floatingLabelText={'Hora de início de acendimento'}
floatingLabelFocusStyle={{ color: '#00838F' }}
underlineFocusStyle={{ borderColor: '#00838F' }}
style={{ width: '90%', marginTop: '-14px' }}
/>
</LightConfigurationField>
<LightConfigurationField>
<Field
component={TextField}
name={'finalTime'}
floatingLabelFixed
floatingLabelText={'Hora de fim de acendimento'}
floatingLabelFocusStyle={{ color: '#00838F' }}
underlineFocusStyle={{ borderColor: '#00838F' }}
style={{ width: '90%', marginTop: '-14px' }}
/>
</LightConfigurationField>
<LightConfigurationField>
<Field
component={TextField}
name={'keepOn'}
floatingLabelFixed
floatingLabelText={'Tempo de permanência acesas (minutos)'}
floatingLabelFocusStyle={{ color: '#00838F' }}
underlineFocusStyle={{ borderColor: '#00838F' }}
style={{ width: '90%', marginTop: '-14px' }}
/>
</LightConfigurationField>
<SubmitButton>
<RaisedButton label="Enviar" style={{ color: '#00838F' }} type="submit" />
</SubmitButton>
</Form>
)
}
}
LightConfiguration.propTypes = {
lightConfigurationSubmit: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
}
export default LightConfiguration
| mit |
terrydash/XgxFrameWork | Dos.Common/EmitMapper/MappingConfiguration/MappingOperations/Interfaces/IDestReadOperation.cs | 225 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmitMapper.MappingConfiguration.MappingOperations
{
public interface IDestReadOperation : IDestOperation
{
}
}
| mit |
south-coast-science/scs_core | src/scs_core/aws/client/api_auth.py | 2332 | """
Created on 2 Apr 2018
@author: Bruno Beloff ([email protected])
example document:
{"endpoint": "xy1eszuu23.execute-api.us-west-2.amazonaws.com", "api-key": "de92c5ff-b47a-4cc4-a04c-62d684d74a1f"}
"""
from collections import OrderedDict
from scs_core.data.json import PersistentJSONable
# --------------------------------------------------------------------------------------------------------------------
class APIAuth(PersistentJSONable):
"""
classdocs
"""
__FILENAME = "aws_api_auth.json"
@classmethod
def persistence_location(cls):
return cls.aws_dir(), cls.__FILENAME
# ----------------------------------------------------------------------------------------------------------------
@classmethod
def construct_from_jdict(cls, jdict, skeleton=False):
if not jdict:
return None
endpoint = jdict.get('endpoint')
api_key = jdict.get('api-key')
return cls(endpoint, api_key)
# ----------------------------------------------------------------------------------------------------------------
def __init__(self, endpoint, api_key):
"""
Constructor
"""
super().__init__()
self.__endpoint = endpoint # String
self.__api_key = api_key # String
def __eq__(self, other):
try:
return self.endpoint == other.endpoint and self.api_key == other.api_key
except (TypeError, AttributeError):
return False
# ----------------------------------------------------------------------------------------------------------------
def as_json(self):
jdict = OrderedDict()
jdict['endpoint'] = self.endpoint
jdict['api-key'] = self.api_key
return jdict
# ----------------------------------------------------------------------------------------------------------------
@property
def endpoint(self):
return self.__endpoint
@property
def api_key(self):
return self.__api_key
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
return "APIAuth:{endpoint:%s, api_key:%s}" % (self.endpoint, self.api_key)
| mit |
dinukadesilva/music-ctrls | lib/infusion/tests/component-tests/pager/js/PagedTableTests.js | 24375 | /*
Copyright 2008-2009 University of Cambridge
Copyright 2008-2009 University of Toronto
Copyright 2010-2014 OCAD University
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
/* global fluid, jqUnit */
(function ($, fluid) {
"use strict";
jqUnit.module("Paged Table Tests");
fluid.registerNamespace("fluid.tests.pager");
// NB: ensure to destroy each pager at the end of a test fixture in order to prevent leakage of tooltips
fluid.defaults("fluid.tests.renderedPager", {
gradeNames: ["fluid.pagedTable"],
mergePolicy: {
dataModel: "replace"
},
columnDefs: [
{
key: "animal",
valuebinding: "*.animal",
sortable: true
}
],
tooltip: {
type: "fluid.tooltip",
options: { // These options simplify the test structure by assuring that tooltip changes are synchronous
delay: 0,
duration: 0
}
},
annotateColumnRange: "animal",
dataOffset: "pets",
model: {
pageSize: 2
},
dataModel: {
pets: [
{
animal: "dog"
},
{
animal: "cat"
},
{
animal: "bird"
},
{
animal: "fish"
},
{
animal: "camel"
},
{
animal: "dragon"
},
{
animal: "ant"
}
]
},
components: {
bodyRenderer: {
options: {
selectors: {
category: ".tests-category",
breed: ".tests-breed",
origin: ".tests-origin",
animal: ".tests-animal"
}
}
}
}
});
fluid.tests.pager.animalDataModel = {
pets: [
{
category: "B",
breed: "Siberian Husky",
origin: "Russia"
},
{
category: "C",
breed: "Old German Shepherd Dog",
origin: "Germany"
},
{
category: "A",
breed: "Old England Old English Terrier",
origin: "Germany"
},
{
category: "D",
breed: "Kuvasz",
origin: "Hungary"
},
{
category: "D",
breed: "King Shepherd",
origin: "United States"
},
{
category: "B",
breed: "Kishu",
origin: "Japan"
}
]
};
fluid.tests.pager.animalColumnDefs = [
{
key: "category",
valuebinding: "*.category",
sortable: true
},
{
key: "breed",
valuebinding: "*.breed",
sortable: true
},
{
key: "origin",
valuebinding: "*.origin",
sortable: true
}
];
/** Convenience strategy pager creator **/
var strategyRenderer = function (n, pageSize, pageList) {
var dataModel = {};
dataModel.pets = [];
for (var i = 0; i < n; i++) {
dataModel.pets.push({animal: "cat_" + i});
}
var opt = {
dataModel: dataModel,
model: {
pageSize: pageSize
},
pageList: pageList
};
var pager = fluid.tests.renderedPager("#rendered", opt);
return pager;
};
fluid.defaults("fluid.tests.pagerTooltipEnv", {
gradeNames: ["fluid.test.testEnvironment"],
markupFixture: "#rendered-ioc",
components: {
pager: {
type: "fluid.tests.renderedPager",
container: "#rendered-ioc",
options: {
gradeNames: ["fluid.tests.tooltip.trackTooltips", "fluid.tests.focusNotifier"]
}
},
fixtures: {
type: "fluid.tests.pagerTooltipTests",
options: {
sequenceOfPageSizes: [2, 3, 4]
}
}
}
});
fluid.defaults("fluid.tests.pagerTooltipTests", {
gradeNames: ["fluid.test.testCaseHolder"],
sequenceOfPageSizes: [],
moduleSource: {
func: "fluid.tests.getTooltipModuleSource",
args: ["{pager}", "{that}.options.sequenceOfPageSizes"]
}
});
fluid.tests.getTooltipModuleSource = function (pager, sequencesOfPageSizes) {
var sequence = [];
var linksList = fluid.transform(pager.dataModel, function (data) {
return {text: data.animal};
});
/* Change the page size and verify whether the tooltips and links are synced accordingly */
fluid.each(sequencesOfPageSizes, function (pageSize) {
var expectedTooltips = fluid.tests.getTooltipContents(linksList, pageSize);
$.merge(sequence, [
{
func: "fluid.changeElementValue",
args: ["{pager}.dom.pageSize", pageSize]
},
{
func: "fluid.tests.verifyPagerBar",
args: ["{pager}", "top", pageSize]
},
{
func: "fluid.tests.verifyPagerBar",
args: ["{pager}", "bottom", pageSize]
},
{
func: "fluid.tests.verifyToolTipsOfPagerBar",
args: ["{pager}", "top", pageSize, expectedTooltips]
},
{
func: "fluid.tests.verifyToolTipsOfPagerBar",
args: ["{pager}", "bottom", pageSize, expectedTooltips]
}
]);
});
return {
name: "Pager tooltip tests",
tests: [
{
name: "Tooltip visibility and contents",
sequence: sequence
}
]
};
};
fluid.tests.getTooltipContents = function (listOfData, pageSize) {
var tooltipContents = [];
for (var i = 0; i < listOfData.length; i += pageSize) {
var tooltipContent = [];
var pageStartIndex = i;
var pageEndIndex = Math.min(pageStartIndex + pageSize - 1, listOfData.length - 1);
tooltipContent.push({nodeName: "b", nodeText: listOfData[pageStartIndex].text});
tooltipContent.push({nodeName: "b", nodeText: listOfData[pageEndIndex].text});
tooltipContents.push(tooltipContent);
}
return tooltipContents;
};
fluid.tests.getPagerBar = function (pager, location) {
return pager[location === "top" ? "pagerBar" : "pagerBar-1"];
};
fluid.tests.verifyPagerBar = function (pager, location, pageSize) {
var expectedNumberOfLinks = Math.ceil(pager.dataModel.length / pageSize);
//Verify the number of links in the pager bar
jqUnit.assertEquals("The number of links in the pager should be according to the page size",
expectedNumberOfLinks,
fluid.tests.getPagerBar(pager, location).locate("pageLinks").length);
};
fluid.tests.assertVisibleTips = function (pager, message, targetIds, expectedTooltip) {
fluid.tests.tooltip.assertVisible(message, pager, targetIds, null, function (tooltip) {
jqUnit.assertNode("The contents of the tooltip should be set", expectedTooltip, $("b", tooltip));
});
};
fluid.tests.verifyToolTipsOfPagerBar = function (pager, location, pageSize, expectedTooltips) {
var expectedNumberOfLinks = Math.ceil(pager.dataModel.length / pageSize);
for (var x = 0; x < expectedNumberOfLinks; x++) {
fluid.tests.verifyPagerToolTip(pager, location, x, expectedTooltips[x]);
}
};
fluid.tests.verifyPagerToolTip = function (pager, location, index, expectedTooltip) {
var link = fluid.tests.getPagerBar(pager, location).locate("pageLinks").find("a").eq(index);
var linkNumber = index + 1;
var linkId = "page-link:link" + linkNumber + (location === "bottom" ? "-1" : "");
link.trigger("focus");
fluid.tests.assertVisibleTips(pager,
"The tooltip of page link " + linkNumber + ", in " + location + " page bar is visible",
[linkId], expectedTooltip);
link.trigger("blur");
fluid.tests.assertVisibleTips(pager,
"There should not be any tooltips visible when no pageLinks are focused.",
[], expectedTooltip);
};
fluid.tests.runPagedTableTests = function () {
// This IoC-enabled test must come first, as a result of an undiagnosed Firefox issue which causes the running
// of the plain QUnit tests to somehow clobber the markup belonging to it
// QUnit's markup restoration cycle can't play nicely with ours. It grabs the document's markup at a slightly later point
// than our initialisation - during which time we have rendered already and clobbered it. It doesn't expose an event
// that lets us hook into this process, so we must make sure that plain tests and IoC tests always use different markup
// areas.
var rendered = $("#rendered").html();
var rendered_ioc = $("<div id=\"rendered-ioc\"></div>").html(rendered);
rendered_ioc.appendTo(document.body);
fluid.test.runTests(["fluid.tests.pagerTooltipEnv"]);
jqUnit.module("Paged Table Tests");
// Just tests that the pager will initialize with only a container, and dataModel passed in.
// The rest of the options are the defaults.
jqUnit.test("Default Pager: FLUID-4213", function () {
var pager = fluid.pagedTable("#rendered", {
dataModel: [{language: "javascript"}]
});
jqUnit.assertValue("The default pager initialized", pager);
pager.destroy();
});
jqUnit.test("Pager Current Page label", function () {
var pager = fluid.tests.renderedPager("#rendered");
var currentPages = $(".fl-pager-currentPage", pager.container);
currentPages.each(function (idx, currentPage) {
var descElmID = $(currentPage).attr("aria-label");
jqUnit.assertTrue("aria-label was added to the current page list element", descElmID);
jqUnit.assertEquals("The label is correct", pager.pagerBar.options.strings.currentPageIndexMsg, descElmID);
});
pager.destroy();
});
/**
* Test everyPageStrategy Strategy
*/
jqUnit.test("Pager everyPageStrategy", function () {
/*
* Create n pages, check if number of pages = n
*/
var pageSize = 3;
var pageList = 20;
var everyPageStrategyPageList = {
type: "fluid.pager.renderedPageList",
options: {
pageStrategy: fluid.pager.everyPageStrategy
}
};
var expectedPages = Math.ceil(pageList / pageSize);
var pager = strategyRenderer(pageList, pageSize, everyPageStrategyPageList);
var pagerTopPageLinks = $(".flc-pager-top .flc-pager-pageLink", pager.container).length;
var pagerBottomPageLinks = $(".flc-pager-bottom .flc-pager-pageLink", pager.container).length;
jqUnit.assertEquals("Top pageLinks", expectedPages, pagerTopPageLinks);
jqUnit.assertEquals("Bottom pageLinks", expectedPages, pagerBottomPageLinks);
pager.destroy();
});
/**
* Test gappedPageStrategy Strategy
*/
jqUnit.asyncTest("Pager gappedPageStrategy", function () {
var pageSize = 3;
var pageList = 100;
var expectedPages = Math.ceil(pageList / pageSize);
var j = 3;
var m = 1;
var gappedPageStrategyPageList = function (j, m) {
return {
type: "fluid.pager.renderedPageList",
options: {
dataModel: fluid.copy(fluid.tests.pager.animalDataModel),
columnDefs: fluid.copy(fluid.tests.pager.animalColumnDefs),
pageStrategy: fluid.pager.gappedPageStrategy(j, m)
}
};
};
var pager = strategyRenderer(pageList, pageSize, gappedPageStrategyPageList(j, m));
/*
* Check if element is in the list when we clicked on "i"
*/
var shouldExistInList = function (i, element) {
//manually retrieve ID
//todo: make this better?
var link = $(element).find("a");
var linkId = parseInt(link.attr("id").replace("page-link:link", ""), 10);
//if this link is within the leading linkCount
if (linkId <= j) {
return true;
}
//if this link is within the trailing linkCount
if (linkId > expectedPages - j && linkId <= expectedPages) {
return true;
}
//if this link is within the middle linkCount
if (i >= linkId - m && i <= linkId + m) {
return true;
}
//if all the above fails.
return false;
};
var i = 1;
var allPagesAfterClickedEachFn = function (index, element) {
if (!$(element).hasClass("flc-pager-pageLink-skip")) {
jqUnit.assertTrue("Clicked on [page " + i + "] and checking [" + $(element).find("a").attr("id") + "]", shouldExistInList(i, element));
}
};
function clickNext() {
var page = fluid.jById("page-link:link" + i);
page.click();
var allPagesAfterClicked = pager.pagerBar.pageList.locate("root").find("li");
allPagesAfterClicked.each(allPagesAfterClickedEachFn);
if (i === expectedPages - 1) {
pager.destroy();
jqUnit.start();
}
else { // Convert the test to async since on FF it is now expensive enough to generate painful "unresponsive script" warnings (mainly due to tooltip cost)
++i;
setTimeout(clickNext, 1);
}
}
clickNext();
});
jqUnit.test("Page Table Header aria-sort and title, and body rendering test", function () {
var strings = fluid.defaults("fluid.table").strings;
var opt = {
dataModel: fluid.copy(fluid.tests.pager.animalDataModel),
columnDefs: fluid.copy(fluid.tests.pager.animalColumnDefs),
annotateColumnRange: "category",
model: {
pageSize: 6
}
};
var pager = fluid.tests.renderedPager("#rendered", opt);
var currentHeaders = pager.locate("headerSortStylisticOffset");
// Check that the table data was actually rendered into the markup
var trs = $("tbody tr", pager.container);
jqUnit.assertEquals("Correct number of rows rendered", opt.model.pageSize, trs.length);
function spanToObject(accum, span) {
var id = span.prop("id");
var member = id.substring(id.lastIndexOf(":") + 1);
accum[member] = span.text();
}
var recovered = fluid.transform(trs, function (tr) {
var togo = {};
var spans = $("span", tr);
fluid.each(spans, function (span) {
spanToObject(togo, $(span));
});
return togo;
});
jqUnit.assertDeepEq("All table data rendered", fluid.tests.pager.animalDataModel, {pets: recovered});
/**
* Get a string representation of the parameter based on the strings we have in Pager.js
*/
var sortableColumnTextStr = function (dir_order) {
if (dir_order === "ascending") {
return strings.sortableColumnTextAsc;
} else if (dir_order === "descending") {
return strings.sortableColumnTextDesc;
} else {
return strings.sortableColumnText;
}
};
/**
* Upon a click on a single column, this function will check the aira-sort attribute, and the anchor titles on ALL columns,
* making sure they all have the correct values.
*
* @param int index of the header column on which aria-sort should display in
* @param string the n-th times this column is clicked, use strings like 1st, 2nd, 3rd, etc. Used for displaying report.
* @param string descending/ascending
*/
var testAriaOnAllHeaders = function (aria_index, times, dir_order) {
var currentHeadersMod = pager.locate("headerSortStylisticOffset");
var currentHeadersAnchor = $("a", currentHeadersMod);
for (var j = 0; j < currentHeadersMod.length; j++) {
var aria_sort_attr = $(currentHeadersMod[j]).attr("aria-sort");
var title_attr = $(currentHeadersAnchor[j]).attr("title");
var test_prefix = times + " clicked on Column [" + currentHeadersAnchor.eq(aria_index).text() +
"], checking column [" + currentHeadersAnchor.eq(j).text() + "] - ";
if (aria_index === j) {
jqUnit.assertTrue(test_prefix + "aria-sort was added to the sorted column", aria_sort_attr);
jqUnit.assertEquals(test_prefix + "The aria-sort value is set", dir_order, aria_sort_attr);
jqUnit.assertEquals(test_prefix + "The anchor of the header is set", sortableColumnTextStr(dir_order), title_attr);
} else {
jqUnit.assertFalse(test_prefix + "aria-sort was not added to the unsorted column", aria_sort_attr);
jqUnit.assertEquals(test_prefix + "The anchor of the header is set", sortableColumnTextStr(""), title_attr);
}
}
};
/**
* This function performs a mouse click on the column header
*
* @param int index of the header column on which aria-sort should display in
*/
var clickHeader = function (aria_index) {
currentHeaders = pager.locate("headerSortStylisticOffset");
var currentHeader = currentHeaders.eq(aria_index);
//first click is ascending order
$("a", currentHeader).click();
};
//sort each column individually, and check aria-sort on all columns after every sort.
for (var i = 0; i < currentHeaders.length; i++) {
//first click is ascending order
clickHeader(i);
testAriaOnAllHeaders(i, "1st", "ascending");
//second click is descending order
clickHeader(i);
testAriaOnAllHeaders(i, "2nd", "descending");
}
pager.destroy();
});
/**
* Test consistentGappedPageStrategy Strategy
*/
jqUnit.asyncTest("Pager consistentGappedPageStrategy", function () {
/*
* Create n pages, check if number of pages = n
* consistentGappedPageStrategy(j, m) should look like this:
* ---j--- -m-[x]-m- ---j---
*/
var pageSize = 3;
var pageList = 100;
var expectedPages = Math.ceil(pageList / pageSize);
var j = 3;
var m = 1;
var consistentGappedPageStrategyPageList = function (j, m) {
return {
type: "fluid.pager.renderedPageList",
options: {
pageStrategy: fluid.pager.consistentGappedPageStrategy(j, m)
}
};
};
/*
* Check if element is in the list when we clicked on "i"
*/
var shouldExistInList = function (i, element) {
//manually retrieve ID
//todo: make this better?
var link = $(element).find("a");
var linkId = parseInt(link.attr("id").replace("page-link:link", ""), 10);
//if this link is within the leading linkCount
if (linkId <= j) {
return true;
}
//if this link is within the trailing linkCount
if (linkId > expectedPages - j && linkId <= expectedPages) {
return true;
}
//if this link is within the middle linkCount
if (i >= linkId - m && i <= linkId + m) {
return true;
}
//if this element is outside of leading linkCount but index
//is within leading linkCount
//i-m-2 because 1 2 3 ... 5 6 is pointless. it should be 1 2 3 4 5 6.
if ((i - m - 2) <= j && linkId <= (expectedPages - j - 1)) {
return true;
}
//if this element is outside of trailing linkCount but index
//is within leading linkCount
if (i + m + 2 >= expectedPages - j && linkId > expectedPages - (expectedPages - j - 1)) {
return true;
}
//if all the above fails.
return false;
};
var pager = strategyRenderer(pageList, pageSize, consistentGappedPageStrategyPageList(j, m));
//total queue size allowed is current_page + 2 * (j + m) + self + 2 skipped_pages
var totalPages = 2 * (j + m) + 3;
var allPagesAfterClickedEachFn = function (index, element) {
if (!$(element).hasClass("flc-pager-pageLink-skip")) {
jqUnit.assertTrue("On [page " + i + "] and checking [" + $(element).find("a").attr("id") + "]", shouldExistInList(i, element));
}
};
var i = 1;
//Go through all pages 1 by 1 , and click all page dynamically each time
function clickNext() {
var page = fluid.jById("page-link:link" + i);
page.click();
jqUnit.assertEquals("Verify number of top page links", totalPages,
pager.pagerBar.locate("pageLinks").length + pager.pagerBar.locate("pageLinkSkip").length);
var allPagesAfterClicked = pager.pagerBar.pageList.locate("root").find("li");
allPagesAfterClicked.each(allPagesAfterClickedEachFn);
if (i === expectedPages - 1) {
pager.destroy();
jqUnit.start();
}
else {
++i;
setTimeout(clickNext, 1);
}
}
clickNext();
});
};
})(jQuery, fluid);
| mit |
adamahrens/RailsExploration | Scheduler/spec/features/audit_log_spec.rb | 774 | require 'rails_helper'
describe 'AuditLog feature' do
describe 'index' do
before do
@audit_log = FactoryGirl.create(:audit_log)
@admin_user = FactoryGirl.create(:admin_user)
login_as(@admin_user, scope: :user)
visit audit_logs_path
end
it 'has an index page that can be reached' do
expect(page.status_code).to eq(200)
end
it 'renders audit log contents that are available' do
full_name = @audit_log.user.full_name
expect(page).to have_content(/#{full_name}/)
end
it 'cant be accessed by a non-admin user' do
logout(@admin_user)
user = FactoryGirl.create(:user)
login_as(user, scope: :user)
visit audit_logs_path
expect(current_path).to eq(root_path)
end
end
end
| mit |
RemiFusade2/RubberTheGame | Rubber Game/Assets/Scripts/StopPlayerScript.cs | 375 | using UnityEngine;
using System.Collections;
public class StopPlayerScript : MonoBehaviour {
public PlayerBehaviour playerScript;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider col)
{
if (col.tag.Equals("Player"))
{
playerScript.StopPlayerSlowly ();
}
}
}
| mit |
digitalocean/droplet_kit | spec/lib/droplet_kit/client_spec.rb | 3356 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe DropletKit::Client do
subject(:client) { DropletKit::Client.new(access_token: 'bunk') }
describe '#initialize' do
it 'initializes with an access token' do
client = DropletKit::Client.new(access_token: 'my-token')
expect(client.access_token).to eq('my-token')
end
it 'allows string option keys for the client' do
client = DropletKit::Client.new('access_token' => 'my-token')
expect(client.access_token).to eq('my-token')
end
it 'allows string option for api url' do
_my_url = 'https://api.example.com'
client = DropletKit::Client.new('api_url' => _my_url)
expect(client.api_url).to eq(_my_url)
end
it 'has default open_timeout for faraday' do
client = DropletKit::Client.new('access_token' => 'my-token')
expect(client.open_timeout).to eq(DropletKit::Client::DEFAULT_OPEN_TIMEOUT)
end
it 'allows open_timeout to be set' do
open_timeout = 10
client = DropletKit::Client.new(
'access_token' => 'my-token',
'open_timeout' => open_timeout
)
expect(client.open_timeout).to eq(open_timeout)
end
it 'has default timeout' do
client = DropletKit::Client.new('access_token' => 'my-token')
expect(client.timeout).to eq(DropletKit::Client::DEFAULT_TIMEOUT)
end
it 'allows timeout to be set' do
timeout = 10
client = DropletKit::Client.new(
'access_token' => 'my-token',
'timeout' => timeout
)
expect(client.timeout).to eq(timeout)
end
end
describe "#method_missing" do
context "called with an existing method" do
it { expect{ client.actions}.to_not raise_error }
end
context "called with a missing method" do
it { expect{client.this_is_wrong}.to raise_error(NoMethodError) }
end
end
describe '#connection' do
module AcmeApp
class CustomLogger < Faraday::Middleware
end
end
it 'populates the authorization header correctly' do
expect(client.connection.headers['Authorization']).to eq("Bearer #{client.access_token}")
end
it 'sets the content type' do
expect(client.connection.headers['Content-Type']).to eq("application/json")
end
context 'with default user agent' do
it 'contains the version of DropletKit and Faraday' do
stub_const('DropletKit::VERSION', '1.2.3')
stub_const('Faraday::VERSION', '1.2.3')
expect(client.connection.headers['User-Agent']).to eq('DropletKit/1.2.3 Faraday/1.2.3')
end
end
context 'with user provided user agent' do
it 'includes their agent string as well' do
client = DropletKit::Client.new(access_token: 'bunk', user_agent: 'tugboat')
expect(client.connection.headers['User-Agent']).to include('tugboat')
end
end
it 'allows access to faraday instance' do
client.connection.use AcmeApp::CustomLogger
expect(client.connection.builder.handlers).to include(AcmeApp::CustomLogger)
end
it 'has open_timeout set' do
expect(client.connection.options.open_timeout).to eq(DropletKit::Client::DEFAULT_OPEN_TIMEOUT)
end
it 'has timeout set' do
expect(client.connection.options.timeout).to eq(DropletKit::Client::DEFAULT_TIMEOUT)
end
end
end
| mit |
neatphp/neat | src/Container/Exception/UnexpectedValueException.php | 172 | <?php
namespace Neat\Container\Exception;
/**
* Container exception.
*/
class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface {} | mit |
chunkiat82/rarebeauty-ui | src/routes/appointment/ListAppointments.js | 1639 | import React from 'react';
import Layout from '../../components/Layout';
import AppointmentList from './components/List';
import { getServices } from './common/functions';
function show(store) {
return () => {
store.dispatch({ type: 'SHOW_LOADER' });
};
}
function hide(store) {
return () => {
store.dispatch({ type: 'HIDE_LOADER' });
};
}
async function getEvents(fetch) {
const resp = await fetch('/graphql', {
body: JSON.stringify({
query: `{
events {
id,
status,
name
mobile,
start,
end,
apptId,
serviceIds,
confirmed,
shortURL,
created
}
}`,
}),
});
const { data } = await resp.json();
// console.log(`data=${JSON.stringify(data, null, 2)}`);
return data.events.reduce((array, item) => {
if (item) {
// eslint-disable-next-line no-param-reassign
array[array.length] = item;
}
return array;
}, []);
}
// eslint-disable-next-line no-unused-vars
async function action({ fetch, _, store }) {
show(store)();
const events = await getEvents(fetch);
const services = await getServices(fetch)();
hide(store)();
return {
chunks: ['appointment-list'],
title: 'Rare Beauty Professional',
component: (
<Layout>
<AppointmentList rows={events} services={services} />
</Layout>
),
};
}
export default action;
| mit |
rdkmaster/jigsaw | src/app/demo/mobile/graph/heat/demo.module.ts | 589 | import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {JigsawMobileGraphModule} from "jigsaw/mobile_public_api";
import {HeatGraphComponent} from "./demo.component";
import {JigsawDemoDescriptionModule} from "app/demo-description/demo-description";
import {JigsawMobileHeaderModule} from "jigsaw/mobile_public_api";
@NgModule({
declarations: [HeatGraphComponent],
exports: [HeatGraphComponent],
imports: [JigsawMobileGraphModule, JigsawDemoDescriptionModule, CommonModule, JigsawMobileHeaderModule]
})
export class HeatGraphModule {
}
| mit |
Totokaelo/stellae | lib/stellae/requests/get_catalog_information_request.rb | 248 | module Stellae
module Requests
class GetCatalogInformationRequest < Base
endpoint_name :get_catalog_information
root_name :cir
string :upc
string :style
string :season_code
string :flags
end
end
end
| mit |
mburgknap/Redmine-Time-Log-2 | RedmineLog/UI/frmSubIssue.Designer.cs | 7639 | namespace RedmineLog.UI
{
partial class frmSubIssue
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbSubject = new System.Windows.Forms.TextBox();
this.tbDescription = new System.Windows.Forms.TextBox();
this.btnAccept = new System.Windows.Forms.Button();
this.cbTracker = new System.Windows.Forms.ComboBox();
this.cbPriority = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.cbPerson = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// tbSubject
//
this.tbSubject.Location = new System.Drawing.Point(12, 22);
this.tbSubject.Multiline = true;
this.tbSubject.Name = "tbSubject";
this.tbSubject.Size = new System.Drawing.Size(308, 30);
this.tbSubject.TabIndex = 0;
//
// tbDescription
//
this.tbDescription.Location = new System.Drawing.Point(11, 74);
this.tbDescription.Multiline = true;
this.tbDescription.Name = "tbDescription";
this.tbDescription.Size = new System.Drawing.Size(309, 62);
this.tbDescription.TabIndex = 1;
//
// btnAccept
//
this.btnAccept.Location = new System.Drawing.Point(192, 197);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(128, 39);
this.btnAccept.TabIndex = 2;
this.btnAccept.Text = "Accept";
this.btnAccept.UseVisualStyleBackColor = true;
//
// cbTracker
//
this.cbTracker.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbTracker.FormattingEnabled = true;
this.cbTracker.Location = new System.Drawing.Point(12, 162);
this.cbTracker.Name = "cbTracker";
this.cbTracker.Size = new System.Drawing.Size(174, 21);
this.cbTracker.TabIndex = 3;
//
// cbPriority
//
this.cbPriority.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbPriority.FormattingEnabled = true;
this.cbPriority.Location = new System.Drawing.Point(192, 162);
this.cbPriority.Name = "cbPriority";
this.cbPriority.Size = new System.Drawing.Size(128, 21);
this.cbPriority.TabIndex = 5;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 3);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(43, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Subject";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 55);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(60, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Description";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 146);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(44, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Tracker";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(189, 146);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(38, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Priority";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(11, 197);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(62, 13);
this.label4.TabIndex = 12;
this.label4.Text = "Assigned to";
//
// cbPerson
//
this.cbPerson.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbPerson.FormattingEnabled = true;
this.cbPerson.Location = new System.Drawing.Point(11, 213);
this.cbPerson.Name = "cbPerson";
this.cbPerson.Size = new System.Drawing.Size(175, 21);
this.cbPerson.TabIndex = 11;
//
// frmSubIssue
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(332, 250);
this.Controls.Add(this.label4);
this.Controls.Add(this.cbPerson);
this.Controls.Add(this.label5);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.cbPriority);
this.Controls.Add(this.cbTracker);
this.Controls.Add(this.btnAccept);
this.Controls.Add(this.tbDescription);
this.Controls.Add(this.tbSubject);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmSubIssue";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Add sub issue";
this.TopMost = true;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
internal System.Windows.Forms.TextBox tbSubject;
internal System.Windows.Forms.TextBox tbDescription;
internal System.Windows.Forms.ComboBox cbTracker;
internal System.Windows.Forms.ComboBox cbPriority;
internal System.Windows.Forms.ComboBox cbPerson;
public System.Windows.Forms.Button btnAccept;
}
} | mit |
OpenSpace/OpenSpace | modules/kameleon/kameleonmodule.cpp | 2249 | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2022 *
* *
* 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 <modules/kameleon/kameleonmodule.h>
namespace openspace {
KameleonModule::KameleonModule() : OpenSpaceModule(Name) {}
} // namespace openspace
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.