repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
schupeter/LSRS | app/models/object_accessors/lsrs_organic_coeff_class.rb | 65 | class LsrsOrganicCoeffClass
attr_accessor :crop, :Za, :Zb
end
| mit |
WheretIB/nullc | NULLC/translation/runtime.cpp | 67236 | #include "runtime.h"
#include <memory>
#include <math.h>
#include <time.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef _MSC_VER
#include <stdint.h>
#endif
#undef assert
#define __assert(_Expression) if(!(_Expression)){ printf("assertion failed"); abort(); };
typedef uintptr_t markerType;
namespace NULLC
{
void* defaultAlloc(int size);
void defaultDealloc(void* ptr);
void* alignedAlloc(int size);
void* alignedAlloc(int size, int extraSize);
void alignedDealloc(void* ptr);
}
void* NULLC::defaultAlloc(int size)
{
return malloc(size);
}
void NULLC::defaultDealloc(void* ptr)
{
free(ptr);
}
void* NULLC::alignedAlloc(int size)
{
void *unaligned = defaultAlloc((size + 16 - 1) + sizeof(void*));
if(!unaligned)
return NULL;
void *ptr = (void*)(((intptr_t)unaligned + sizeof(void*) + 16 - 1) & ~(16 - 1));
*((void**)ptr - 1) = unaligned;
return ptr;
}
void* NULLC::alignedAlloc(int size, int extraSize)
{
void *unaligned = defaultAlloc((size + 16 - 1) + sizeof(void*) + extraSize);
if(!unaligned)
return NULL;
void *ptr = (void*)((((intptr_t)unaligned + sizeof(void*) + extraSize + 16 - 1) & ~(16 - 1)) - extraSize);
*((void**)ptr - 1) = unaligned;
return ptr;
}
void NULLC::alignedDealloc(void* ptr)
{
defaultDealloc(*((void **)ptr - 1));
}
int SafeSprintf(char* dst, size_t size, const char* src, ...)
{
va_list args;
va_start(args, src);
int result = vsnprintf(dst, size, src, args);
dst[size-1] = '\0';
va_end(args);
return (result == -1 || (size_t)result >= size) ? (int)size : result;
}
template<typename T>
class FastVector
{
public:
FastVector()
{
data = (T*)malloc(sizeof(T) * 128);
memset(data, 0, sizeof(T));
max = 128;
count = 0;
}
explicit FastVector(unsigned int reserved)
{
data = (T*)malloc(sizeof(T) * reserved);
memset(data, 0, reserved * sizeof(T));
max = reserved;
count = 0;
}
~FastVector()
{
free(data);
}
void reset()
{
free(data);
data = (T*)malloc(sizeof(T) * 128);
memset(data, 0, sizeof(T));
max = 128;
count = 0;
}
T* push_back()
{
count++;
if(count == max)
grow(count);
return &data[count - 1];
};
void push_back(const T& val)
{
data[count++] = val;
if(count == max)
grow(count);
};
void push_back(const T* valPtr, unsigned int elem)
{
if(count + elem >= max)
grow(count + elem);
for(unsigned int i = 0; i < elem; i++)
data[count++] = valPtr[i];
};
T& back()
{
return data[count-1];
}
unsigned int size()
{
return count;
}
void pop_back()
{
count--;
}
void clear()
{
count = 0;
}
T& operator[](unsigned int index)
{
return data[index];
}
void resize(unsigned int newSize)
{
if(newSize >= max)
grow(newSize);
count = newSize;
}
void shrink(unsigned int newSize)
{
count = newSize;
}
void reserve(unsigned int resSize)
{
if(resSize >= max)
grow(resSize);
}
void grow(unsigned int newSize)
{
if(max + (max >> 1) > newSize)
newSize = max + (max >> 1);
else
newSize += 32;
T* newData;
newData = (T*)malloc(sizeof(T) * newSize);
memset(newData, 0, newSize * sizeof(T));
memcpy(newData, data, max * sizeof(T));
free(data);
data = newData;
max = newSize;
}
T *data;
unsigned int max, count;
private:
// Disable assignment and copy constructor
void operator =(FastVector &r);
FastVector(FastVector &r);
};
namespace detail
{
template<typename T>
T max(T x, T y)
{
return x > y ? x : y;
}
template<typename T>
struct node
{
node(): left(NULL), right(NULL), height(1u)
{
}
node* min_tree()
{
node* x = this;
while(x->left)
x = x->left;
return x;
}
T key;
node *left;
node *right;
int height;
};
}
namespace detail
{
template<typename T>
union SmallBlock
{
char data[sizeof(T)];
SmallBlock *next;
};
template<typename T, int countInBlock>
struct LargeBlock
{
typedef SmallBlock<T> Block;
Block page[countInBlock];
LargeBlock *next;
};
}
template<typename T, int countInBlock>
class TypedObjectPool
{
typedef detail::SmallBlock<T> MySmallBlock;
typedef typename detail::LargeBlock<T, countInBlock> MyLargeBlock;
public:
TypedObjectPool()
{
freeBlocks = NULL;
activePages = NULL;
lastNum = countInBlock;
}
~TypedObjectPool()
{
Reset();
}
void Reset()
{
freeBlocks = NULL;
lastNum = countInBlock;
while(activePages)
{
MyLargeBlock *following = activePages->next;
NULLC::alignedDealloc(activePages);
activePages = following;
}
}
T* Allocate()
{
MySmallBlock *result;
if(freeBlocks)
{
result = freeBlocks;
freeBlocks = freeBlocks->next;
}else{
if(lastNum == countInBlock)
{
MyLargeBlock *newPage = new(NULLC::alignedAlloc(sizeof(MyLargeBlock))) MyLargeBlock;
newPage->next = activePages;
activePages = newPage;
lastNum = 0;
}
result = &activePages->page[lastNum++];
}
return new(result) T;
}
void Deallocate(T* ptr)
{
if(!ptr)
return;
MySmallBlock *freedBlock = (MySmallBlock*)(void*)ptr;
ptr->~T(); // Destroy object
freedBlock->next = freeBlocks;
freeBlocks = freedBlock;
}
public:
MySmallBlock *freeBlocks;
MyLargeBlock *activePages;
unsigned lastNum;
};
template<typename T>
class Tree
{
public:
typedef detail::node<T>* iterator;
typedef detail::node<T> node_type;
TypedObjectPool<node_type, 1024> pool;
Tree(): root(NULL)
{
}
void reset()
{
pool.Reset();
root = NULL;
}
void clear()
{
pool.Reset();
root = NULL;
}
iterator insert(const T& key)
{
return root = insert(root, key);
}
void erase(const T& key)
{
root = erase(root, key);
}
iterator find(const T& key)
{
node_type *curr = root;
while(curr)
{
if(curr->key == key)
return iterator(curr);
curr = key < curr->key ? curr->left : curr->right;
}
return iterator(NULL);
}
void for_each(void (*it)(T&))
{
if(root)
for_each(root, it);
}
private:
int get_height(node_type* n)
{
return n ? n->height : 0;
}
int get_balance(node_type* n)
{
return n ? get_height(n->left) - get_height(n->right) : 0;
}
node_type* left_rotate(node_type* x)
{
node_type *y = x->right;
node_type *T2 = y->left;
y->left = x;
x->right = T2;
x->height = detail::max(get_height(x->left), get_height(x->right)) + 1;
y->height = detail::max(get_height(y->left), get_height(y->right)) + 1;
return y;
}
node_type* right_rotate(node_type* y)
{
node_type *x = y->left;
node_type *T2 = x->right;
x->right = y;
y->left = T2;
y->height = detail::max(get_height(y->left), get_height(y->right)) + 1;
x->height = detail::max(get_height(x->left), get_height(x->right)) + 1;
return x;
}
node_type* insert(node_type* node, const T& key)
{
if(node == NULL)
{
node_type *t = pool.Allocate();
t->key = key;
return t;
}
if(key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
node->height = detail::max(get_height(node->left), get_height(node->right)) + 1;
int balance = get_balance(node);
if(balance > 1 && key < node->left->key)
return right_rotate(node);
if(balance < -1 && key > node->right->key)
return left_rotate(node);
if(balance > 1 && key > node->left->key)
{
node->left = left_rotate(node->left);
return right_rotate(node);
}
if(balance < -1 && key < node->right->key)
{
node->right = right_rotate(node->right);
return left_rotate(node);
}
return node;
}
node_type* erase(node_type* node, const T& key)
{
if(node == NULL)
return node;
if(key < node->key)
{
node->left = erase(node->left, key);
}else if(key > node->key){
node->right = erase(node->right, key);
}else{
if((node->left == NULL) || (node->right == NULL))
{
node_type *temp = node->left ? node->left : node->right;
if(temp == NULL)
{
temp = node;
node = NULL;
}else{
*node = *temp;
}
pool.Deallocate(temp);
if(temp == root)
root = node;
}else{
node_type* temp = node->right->min_tree();
node->key = temp->key;
node->right = erase(node->right, temp->key);
}
}
if(node == NULL)
return node;
node->height = detail::max(get_height(node->left), get_height(node->right)) + 1;
int balance = get_balance(node);
if(balance > 1 && get_balance(node->left) >= 0)
return right_rotate(node);
if(balance > 1 && get_balance(node->left) < 0)
{
node->left = left_rotate(node->left);
return right_rotate(node);
}
if(balance < -1 && get_balance(node->right) <= 0)
return left_rotate(node);
if(balance < -1 && get_balance(node->right) > 0)
{
node->right = right_rotate(node->right);
return left_rotate(node);
}
return node;
}
node_type* find(node_type* node, const T& key)
{
if(!node)
return NULL;
if(node->key == key)
return node;
if(key < node->key)
return find(node->left, key);
return find(node->right, key);
}
void for_each(node_type* node, void (*it)(T&))
{
if(node->left)
for_each(node->left, it);
it(node->key);
if(node->right)
for_each(node->right, it);
}
node_type *root;
};
namespace NULLC
{
FastVector<NULLCRef> finalizeList;
}
NULLCArray<__function> __vtbl3761170085finalize;
FastVector<NULLCTypeInfo> __nullcTypeList;
FastVector<NULLCMemberInfo> __nullcTypePart;
FastVector<__nullcFunction> funcTable;
FastVector<NULLCFuncInfo> funcTableExt;
unsigned __nullcRegisterType(unsigned hash, const char *name, unsigned size, unsigned subTypeID, int memberCount, unsigned category, unsigned alignment, unsigned flags)
{
for(unsigned int i = 0; i < __nullcTypeList.size(); i++)
{
NULLCTypeInfo &type = __nullcTypeList[i];
if(type.hash == hash)
{
if((type.flags & NULLC_TYPE_FLAG_FORWARD_DECLARATION) != 0)
{
type.hash = hash;
type.name = name;
type.size = size;
type.subTypeID = subTypeID;
type.memberCount = memberCount;
type.category = category;
type.alignment = alignment;
type.flags = flags;
}
return i;
}
}
__nullcTypeList.push_back(NULLCTypeInfo());
__nullcTypeList.back().hash = hash;
__nullcTypeList.back().name = name;
__nullcTypeList.back().size = size;
__nullcTypeList.back().subTypeID = subTypeID;
__nullcTypeList.back().memberCount = memberCount;
__nullcTypeList.back().category = category;
__nullcTypeList.back().alignment = alignment;
__nullcTypeList.back().flags = flags;
__nullcTypeList.back().members = 0;
return __nullcTypeList.size() - 1;
}
void __nullcRegisterMembers(unsigned id, unsigned count, ...)
{
if(__nullcTypeList[id].members || !count)
return;
va_list args;
va_start(args, count);
__nullcTypeList[id].members = __nullcTypePart.size();
for(unsigned i = 0; i < count; i++)
{
NULLCMemberInfo member;
member.typeID = va_arg(args, unsigned);
member.offset = va_arg(args, unsigned);
member.name = va_arg(args, const char*);
__nullcTypePart.push_back(member);
}
va_end(args);
}
unsigned __nullcGetTypeCount()
{
return __nullcTypeList.size();
}
NULLCTypeInfo* __nullcGetTypeInfo(unsigned id)
{
return &__nullcTypeList[id];
}
NULLCMemberInfo* __nullcGetTypeMembers(unsigned id)
{
return &__nullcTypePart[__nullcTypeList[id].members];
}
bool nullcIsArray(unsigned int typeID)
{
return __nullcGetTypeInfo(typeID)->category == NULLC_ARRAY;
}
const char* nullcGetTypeName(unsigned int typeID)
{
return __nullcGetTypeInfo(typeID)->name;
}
unsigned int nullcGetArraySize(unsigned int typeID)
{
return __nullcGetTypeInfo(typeID)->memberCount;
}
unsigned int nullcGetSubType(unsigned int typeID)
{
return __nullcGetTypeInfo(typeID)->subTypeID;
}
unsigned int nullcGetTypeSize(unsigned int typeID)
{
return __nullcGetTypeInfo(typeID)->size;
}
int __nullcPow(int number, int power)
{
if(power < 0)
return number == 1 ? 1 : (number == -1 ? (power & 1 ? -1 : 1) : 0);
int result = 1;
while(power)
{
if(power & 1)
{
result *= number;
power--;
}
number *= number;
power >>= 1;
}
return result;
}
double __nullcPow(double a, double b)
{
return pow(a, b);
}
long long __nullcPow(long long number, long long power)
{
if(power < 0)
return number == 1 ? 1 : (number == -1 ? (power & 1 ? -1 : 1) : 0);
long long result = 1;
while(power)
{
if(power & 1)
{
result *= number;
power--;
}
number *= number;
power >>= 1;
}
return result;
}
double __nullcMod(double a, double b)
{
return fmod(a, b);
}
int __nullcPowSet(char *a, int b)
{
return *a = (char)__nullcPow((int)*a, b);
}
int __nullcPowSet(short *a, int b)
{
return *a = (short)__nullcPow((int)*a, b);
}
int __nullcPowSet(int *a, int b)
{
return *a = __nullcPow(*a, b);
}
double __nullcPowSet(float *a, double b)
{
return *a = (float)__nullcPow((double)*a, b);
}
double __nullcPowSet(double *a, double b)
{
return *a = __nullcPow(*a, b);
}
long long __nullcPowSet(long long *a, long long b)
{
return *a = __nullcPow(*a, b);
}
void __nullcSetArray(short arr[], short val, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
arr[i] = val;
}
void __nullcSetArray(int arr[], int val, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
arr[i] = val;
}
void __nullcSetArray(float arr[], float val, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
arr[i] = val;
}
void __nullcSetArray(double arr[], double val, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
arr[i] = val;
}
void __nullcSetArray(long long arr[], long long val, unsigned int count)
{
for(unsigned int i = 0; i < count; i++)
arr[i] = val;
}
namespace GC
{
// Range of memory that is not checked. Used to exclude pointers to stack from marking and GC
char *unmanageableBase = NULL;
char *unmanageableTop = NULL;
}
void __nullcCloseUpvalue(__nullcUpvalue *&head, void *ptr)
{
__nullcUpvalue *curr = head;
GC::unmanageableBase = (char*)&curr;
// close upvalue if it's target is equal to local variable, or it's address is out of stack
while(curr && ((char*)curr->ptr == ptr || (char*)curr->ptr < GC::unmanageableBase || (char*)curr->ptr > GC::unmanageableTop))
{
__nullcUpvalue *next = curr->next;
unsigned int size = curr->size;
head = curr->next;
memcpy(&curr->next, curr->ptr, size);
curr->ptr = (unsigned int*)&curr->next;
curr = next;
}
}
NULLCFuncPtr<> __nullcMakeFunction(unsigned int id, void* context)
{
NULLCFuncPtr<> ret;
ret.id = id;
ret.context = context;
return ret;
}
NULLCRef __nullcMakeAutoRef(void* ptr, unsigned int typeID)
{
NULLCRef ret;
ret.ptr = (char*)ptr;
ret.typeID = typeID;
return ret;
}
NULLCRef __nullcMakeExtendableAutoRef(void* ptr)
{
NULLCRef ret;
ret.ptr = (char*)ptr;
ret.typeID = ptr ? *(unsigned*)ptr : 0; // Take type from first class typeid member
return ret;
}
void* __nullcGetAutoRef(const NULLCRef &ref, unsigned int typeID)
{
unsigned sourceTypeID = ref.typeID;
if(sourceTypeID == typeID)
return (void*)ref.ptr;
while(__nullcGetTypeInfo(sourceTypeID)->baseClassID)
{
sourceTypeID = __nullcGetTypeInfo(sourceTypeID)->baseClassID;
if(sourceTypeID == typeID)
return (void*)ref.ptr;
}
nullcThrowError("ERROR: cannot convert from %s ref to %s ref", __nullcGetTypeInfo(ref.typeID)->name, __nullcGetTypeInfo(typeID)->name);
return 0;
}
NULLCAutoArray __makeAutoArray(unsigned type, NULLCArray<void> arr)
{
NULLCAutoArray ret;
ret.size = arr.size;
ret.ptr = arr.ptr;
ret.typeID = type;
return ret;
}
bool operator ==(const NULLCRef& a, const NULLCRef& b)
{
return a.ptr == b.ptr && a.typeID == b.typeID;
}
bool operator !=(const NULLCRef& a, const NULLCRef& b)
{
return a.ptr != b.ptr || a.typeID != b.typeID;
}
bool operator !(const NULLCRef& a)
{
return !a.ptr;
}
void assert(int val, const char* message, void* unused)
{
if(!val)
printf("%s\n", message);
__assert(val);
}
void assert_void_ref_int_(int val, void* __context)
{
__assert(val);
}
void assert_void_ref_int_char___(int val, NULLCArray<char> message, void* __context)
{
if(!val)
printf("%s\n", message.ptr);
__assert(val);
}
int __operatorEqual_int_ref_char___char___(NULLCArray<char> a, NULLCArray<char> b, void* unused)
{
if(a.size != b.size)
return 0;
if(memcmp(a.ptr, b.ptr, a.size) == 0)
return 1;
return 0;
}
int __operatorNEqual_int_ref_char___char___(NULLCArray<char> a, NULLCArray<char> b, void* unused)
{
return !__operatorEqual_int_ref_char___char___(a, b, 0);
}
NULLCArray<char> __operatorAdd_char___ref_char___char___(NULLCArray<char> a, NULLCArray<char> b, void* unused)
{
NULLCArray<char> ret;
ret.size = a.size + b.size - 1;
ret.ptr = (char*)(intptr_t)__newS_void_ref_ref_int_int_(ret.size, NULLC_BASETYPE_CHAR, 0);
if(!ret.ptr)
return ret;
memcpy(ret.ptr, a.ptr, a.size);
memcpy(ret.ptr + a.size - 1, b.ptr, b.size);
return ret;
}
NULLCArray<char> __operatorAddSet_char___ref_char___ref_char___(NULLCArray<char> * a, NULLCArray<char> b, void* unused)
{
return *a = __operatorAdd_char___ref_char___char___(*a, b, 0);
}
bool bool_bool_ref_bool_(bool a, void* __context)
{
return a;
}
char char_char_ref_char_(char a, void* __context)
{
return a;
}
short short_short_ref_short_(short a, void* __context)
{
return a;
}
int int_int_ref_int_(int a, void* __context)
{
return a;
}
long long long_long_ref_long_(long long a, void* __context)
{
return a;
}
float float_float_ref_float_(float a, void* __context)
{
return a;
}
double double_double_ref_double_(double a, void* __context)
{
return a;
}
void bool__bool_void_ref_bool_(bool a, bool *target)
{
*target = a;
}
void char__char_void_ref_char_(char a, char *target)
{
*target = a;
}
void short__short_void_ref_short_(short a, short *target)
{
*target = a;
}
void int__int_void_ref_int_(int a, int *target)
{
*target = a;
}
void long__long_void_ref_long_(long long a, long long *target)
{
*target = a;
}
void float__float_void_ref_float_(float a, float *target)
{
*target = a;
}
void double__double_void_ref_double_(double a, double *target)
{
*target = a;
}
int as_unsigned_int_ref_char_(char a, void* __context)
{
return (int)a;
}
int as_unsigned_int_ref_short_(short a, void* __context)
{
return (int)a;
}
long long as_unsigned_long_ref_int_(int a, void* __context)
{
return (long long)a;
}
short short_short_ref_char___(NULLCArray<char> str, void* __context)
{
return short(atoi(str.ptr));
}
void short__short_void_ref_char___(NULLCArray<char> str, short *__context)
{
*__context = str.ptr ? short(atoi(str.ptr)) : 0;
}
NULLCArray<char> short__str_char___ref__(short* __context)
{
int number = *__context;
bool sign = 0;
char buf[16];
char *curr = buf;
if(number < 0)
sign = 1;
*curr++ = (char)(abs(number % 10) + '0');
while(number /= 10)
*curr++ = (char)(abs(number % 10) + '0');
if(sign)
*curr++ = '-';
NULLCArray<char> arr = __newA_int___ref_int_int_int_(1, (int)(curr - buf) + 1, 0, 0);
char *str = arr.ptr;
do
{
--curr;
*str++ = *curr;
}while(curr != buf);
return arr;
}
int int_int_ref_char___(NULLCArray<char> str, void* __context)
{
return atoi(str.ptr);
}
void int__int_void_ref_char___(NULLCArray<char> str, int* __context)
{
*__context = str.ptr ? atoi(str.ptr) : 0;
}
NULLCArray<char> int__str_char___ref__(int* __context)
{
int number = *__context;
bool sign = 0;
char buf[16];
char *curr = buf;
if(number < 0)
sign = 1;
*curr++ = (char)(abs(number % 10) + '0');
while(number /= 10)
*curr++ = (char)(abs(number % 10) + '0');
if(sign)
*curr++ = '-';
NULLCArray<char> arr = __newA_int___ref_int_int_int_(1, (int)(curr - buf) + 1, 0, 0);
char *str = arr.ptr;
do
{
--curr;
*str++ = *curr;
}while(curr != buf);
return arr;
}
long long long_long_ref_char___(NULLCArray<char> str, void* __context)
{
return strtoll(str.ptr, 0, 10);
}
void long__long_void_ref_char___(NULLCArray<char> str, long long* __context)
{
*__context = str.ptr ? strtoll(str.ptr, 0, 10) : 0;
}
NULLCArray<char> long__str_char___ref__(long long* __context)
{
long long number = *__context;
bool sign = 0;
char buf[32];
char *curr = buf;
if(number < 0)
sign = 1;
*curr++ = (char)(abs(number % 10) + '0');
while(number /= 10)
*curr++ = (char)(abs(number % 10) + '0');
if(sign)
*curr++ = '-';
NULLCArray<char> arr = __newA_int___ref_int_int_int_(1, (int)(curr - buf) + 1, 0, 0);
char *str = arr.ptr;
do
{
--curr;
*str++ = *curr;
}while(curr != buf);
return arr;
}
float float_float_ref_char___(NULLCArray<char> str, void* __context)
{
return (float)atof(str.ptr);
}
void float__float_void_ref_char___(NULLCArray<char> str, float* __context)
{
*__context = str.ptr ? (float)atof(str.ptr) : 0;
}
NULLCArray<char> float__str_char___ref_int_bool_(int precision, bool showExponent, float* __context)
{
char buf[256];
SafeSprintf(buf, 256, showExponent ? "%.*e" : "%.*f", precision, *__context);
NULLCArray<char> arr = __newA_int___ref_int_int_int_(1, (int)strlen(buf) + 1, 0, 0);
memcpy(arr.ptr, buf, arr.size);
return arr;
}
double double_double_ref_char___(NULLCArray<char> str, void* __context)
{
return atof(str.ptr);
}
void double__double_void_ref_char___(NULLCArray<char> str, double* __context)
{
*__context = str.ptr ? atof(str.ptr) : 0;
}
NULLCArray<char> double__str_char___ref_int_bool_(int precision, bool showExponent, double* r)
{
char buf[256];
SafeSprintf(buf, 256, showExponent ? "%.*e" : "%.*f", precision, *r);
NULLCArray<char> arr = __newA_int___ref_int_int_int_(1, (int)strlen(buf) + 1, 0, 0);
memcpy(arr.ptr, buf, arr.size);
return arr;
}
void* __newS_void_ref_ref_int_int_(int size, int type, void* __context)
{
return NULLC::AllocObject(size, type);
}
NULLCArray<int> __newA_int___ref_int_int_int_(int size, int count, int type, void* __context)
{
return NULLC::AllocArray(size, count, type);
}
NULLCRef duplicate_auto_ref_ref_auto_ref_(NULLCRef obj, void* unused)
{
NULLCRef ret;
ret.typeID = obj.typeID;
unsigned int objSize = nullcGetTypeSize(ret.typeID);
ret.ptr = (char*)__newS_void_ref_ref_int_int_(objSize, 0, 0);
memcpy(ret.ptr, obj.ptr, objSize);
return ret;
}
void __duplicate_array_void_ref_auto___ref_auto___(NULLCAutoArray* dst, NULLCAutoArray src, void* unused)
{
dst->typeID = src.typeID;
dst->len = src.len;
dst->ptr = (char*)NULLC::AllocArray(nullcGetTypeSize(src.typeID), src.len, src.typeID).ptr;
memcpy(dst->ptr, src.ptr, src.len * nullcGetTypeSize(src.typeID));
}
NULLCAutoArray duplicate_auto___ref_auto___(NULLCAutoArray arr, void* unused)
{
NULLCAutoArray ret;
__duplicate_array_void_ref_auto___ref_auto___(&ret, arr, NULL);
return ret;
}
NULLCRef replace_auto_ref_ref_auto_ref_auto_ref_(NULLCRef l, NULLCRef r, void* unused)
{
if(l.typeID != r.typeID)
{
nullcThrowError("ERROR: cannot convert from %s ref to %s ref", __nullcGetTypeInfo(r.typeID)->name, __nullcGetTypeInfo(l.typeID)->name);
return l;
}
memcpy(l.ptr, r.ptr, nullcGetTypeSize(r.typeID));
return l;
}
void swap_void_ref_auto_ref_auto_ref_(NULLCRef l, NULLCRef r, void* unused)
{
if(l.typeID != r.typeID)
{
nullcThrowError("ERROR: types don't match (%s ref, %s ref)", __nullcGetTypeInfo(r.typeID)->name, __nullcGetTypeInfo(l.typeID)->name);
return;
}
unsigned size = nullcGetTypeSize(l.typeID);
char tmpStack[512];
// $$ should use some extendable static storage for big objects
char *tmp = size < 512 ? tmpStack : (char*)NULLC::AllocObject(size, l.typeID);
memcpy(tmp, l.ptr, size);
memcpy(l.ptr, r.ptr, size);
memcpy(r.ptr, tmp, size);
}
int equal_int_ref_auto_ref_auto_ref_(NULLCRef l, NULLCRef r, void* unused)
{
if(l.typeID != r.typeID)
{
nullcThrowError("ERROR: types don't match (%s ref, %s ref)", __nullcGetTypeInfo(r.typeID)->name, __nullcGetTypeInfo(l.typeID)->name);
return 0;
}
return 0 == memcmp(l.ptr, r.ptr, nullcGetTypeSize(l.typeID));
}
void assign_void_ref_auto_ref_auto_ref_(NULLCRef l, NULLCRef r, void* unused)
{
if(nullcGetSubType(l.typeID) != r.typeID)
{
nullcThrowError("ERROR: can't assign value of type %s to a pointer of type %s", __nullcGetTypeInfo(r.typeID)->name, __nullcGetTypeInfo(l.typeID)->name);
return;
}
memcpy(l.ptr, &r.ptr, nullcGetTypeSize(l.typeID));
}
void array_copy_void_ref_auto___auto___(NULLCAutoArray l, NULLCAutoArray r, void* __context)
{
if(l.ptr == r.ptr)
return;
if(l.typeID != r.typeID)
{
nullcThrowError("ERROR: destination element type '%s' doesn't match source element type '%s'", nullcGetTypeName(l.typeID), nullcGetTypeName(r.typeID));
return;
}
if(l.len < r.len)
{
nullcThrowError("ERROR: destination array size '%d' is smaller than source array size '%s'", l.len, r.len);
return;
}
memcpy(l.ptr, r.ptr, nullcGetTypeSize(l.typeID) * r.len);
}
NULLCFuncPtr<__typeProxy_void_ref__> __redirect_void_ref___ref_auto_ref___function___ref_(NULLCRef r, NULLCArray<__function>* arr, void* __context)
{
unsigned int *funcs = (unsigned int*)arr->ptr;
NULLCFuncPtr<> ret;
if(r.typeID > arr->size)
{
nullcThrowError("ERROR: type index is out of bounds of redirection table");
return ret;
}
// If there is no implementation for a method
if(!funcs[r.typeID])
{
// Find implemented function ID as a type reference
unsigned int found = 0;
for(; found < arr->size; found++)
{
if(funcs[found])
break;
}
//if(found == arr->size)
nullcThrowError("ERROR: type '%s' doesn't implement method", nullcGetTypeName(r.typeID));
//else
// nullcThrowError("ERROR: type '%s' doesn't implement method '%s%s' of type '%s'", nullcGetTypeName(r.typeID), nullcGetTypeName(r.typeID), strchr(nullcGetFunctionName(funcs[found]), ':'), nullcGetTypeName(nullcGetFunctionType(funcs[found])));
return ret;
}
ret.context = r.ptr;
ret.id = funcs[r.typeID];
return ret;
}
NULLCFuncPtr<__typeProxy_void_ref__> __redirect_ptr_void_ref___ref_auto_ref___function___ref_(NULLCRef r, NULLCArray<__function>* arr, void* __context)
{
NULLCFuncPtr<> ret;
if(!arr)
{
nullcThrowError("ERROR: null pointer access");
return ret;
}
unsigned int *funcs = (unsigned int*)arr->ptr;
if(r.typeID >= arr->size)
{
nullcThrowError("ERROR: type index is out of bounds of redirection table");
return ret;
}
ret.context = funcs[r.typeID] ? r.ptr : 0;
ret.id = funcs[r.typeID];
return ret;
}
NULLCArray<char>* __aassign_itoc_char___ref_ref_char___ref_int___(NULLCArray<char>* dst, NULLCArray<int> src, void* __context)
{
if(dst->size < src.size)
*dst = __newA_int___ref_int_int_int_(1, src.size, 0, 0);
for(int i = 0; i < src.size; i++)
((char*)dst->ptr)[i] = ((int*)src.ptr)[i];
return dst;
}
NULLCArray<short>* __aassign_itos_short___ref_ref_short___ref_int___(NULLCArray<short>* dst, NULLCArray<int> src, void* __context)
{
if(dst->size < src.size)
*dst = __newA_int___ref_int_int_int_(2, src.size, 0, 0);
for(int i = 0; i < src.size; i++)
((short*)dst->ptr)[i] = ((int*)src.ptr)[i];
return dst;
}
NULLCArray<float>* __aassign_dtof_float___ref_ref_float___ref_double___(NULLCArray<float>* dst, NULLCArray<double> src, void* __context)
{
if(dst->size < src.size)
*dst = __newA_int___ref_int_int_int_(4, src.size, 0, 0);
for(int i = 0; i < src.size; i++)
((float*)dst->ptr)[i] = ((double*)src.ptr)[i];
return dst;
}
unsigned typeid_typeid_ref_auto_ref_(NULLCRef type, void* __context)
{
NULLCTypeInfo *info = __nullcGetTypeInfo(type.typeID);
// Read first member of an extendable class
if(info->category == NULLC_CLASS && (info->flags & NULLC_TYPE_FLAG_IS_EXTENDABLE) != 0)
return *(unsigned*)type.ptr;
return type.typeID;
}
int typeid__size__int_ref___(unsigned * __context)
{
return __nullcGetTypeInfo(*__context)->size;
}
int __operatorEqual_int_ref_typeid_typeid_(unsigned a, unsigned b, void* unused)
{
return a == b;
}
int __operatorNEqual_int_ref_typeid_typeid_(unsigned a, unsigned b, void* unused)
{
return a != b;
}
int __rcomp_int_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return a.ptr == b.ptr;
}
int __rncomp_int_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return a.ptr != b.ptr;
}
bool __operatorLess_bool_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return uintptr_t(a.ptr) < uintptr_t(b.ptr);
}
bool __operatorLEqual_bool_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return uintptr_t(a.ptr) <= uintptr_t(b.ptr);
}
bool __operatorGreater_bool_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return uintptr_t(a.ptr) > uintptr_t(b.ptr);
}
bool __operatorGEqual_bool_ref_auto_ref_auto_ref_(NULLCRef a, NULLCRef b, void* unused)
{
return uintptr_t(a.ptr) >= uintptr_t(b.ptr);
}
int hash_value_int_ref_auto_ref_(NULLCRef a, void* unused)
{
long long value = (long long)(intptr_t)(a.ptr);
return (int)((value >> 32) ^ value);
}
int __pcomp_int_ref_void_ref_int__void_ref_int__(NULLCFuncPtr<__typeProxy_void_ref_int_> a, NULLCFuncPtr<__typeProxy_void_ref_int_> b, void* __context)
{
return a.context == b.context && a.id == b.id;
}
int __pncomp_int_ref_void_ref_int__void_ref_int__(NULLCFuncPtr<__typeProxy_void_ref_int_> a, NULLCFuncPtr<__typeProxy_void_ref_int_> b, void* __context)
{
return a.context != b.context || a.id != b.id;
}
int __acomp_int_ref_auto___auto___(NULLCAutoArray a, NULLCAutoArray b, void* __context)
{
return a.size == b.size && a.ptr == b.ptr;
}
int __ancomp_int_ref_auto___auto___(NULLCAutoArray a, NULLCAutoArray b, void* __context)
{
return a.size != b.size || a.ptr != b.ptr;
}
int __typeCount_int_ref__(void* __context)
{
return __nullcTypeList.size() + 1024;
}
NULLCAutoArray* __operatorSet_auto___ref_ref_auto___ref_auto_ref_(NULLCAutoArray* left, NULLCRef right, void* unused)
{
if(!nullcIsArray(right.typeID))
{
nullcThrowError("ERROR: cannot convert from '%s' to 'auto[]'", nullcGetTypeName(right.typeID));
return NULL;
}
left->len = nullcGetArraySize(right.typeID);
if(left->len == ~0u)
{
NULLCArray<char> *arr = (NULLCArray<char>*)right.ptr;
left->len = arr->size;
left->ptr = arr->ptr;
}else{
left->ptr = right.ptr;
}
left->typeID = nullcGetSubType(right.typeID);
return left;
}
NULLCRef __aaassignrev_auto_ref_ref_auto_ref_auto___ref_(NULLCRef left, NULLCAutoArray *right, void* unused)
{
NULLCRef ret = { 0, 0 };
if(!nullcIsArray(left.typeID))
{
nullcThrowError("ERROR: cannot convert from 'auto[]' to '%s'", nullcGetTypeName(left.typeID));
return ret;
}
if(nullcGetSubType(left.typeID) != right->typeID)
{
nullcThrowError("ERROR: cannot convert from 'auto[]' (actual type '%s[%d]') to '%s'", nullcGetTypeName(right->typeID), right->len, nullcGetTypeName(left.typeID));
return ret;
}
unsigned int leftLength = nullcGetArraySize(left.typeID);
if(leftLength == ~0u)
{
NULLCArray<char> *arr = (NULLCArray<char>*)left.ptr;
arr->size = right->len;
arr->ptr = right->ptr;
}else{
if(leftLength != right->len)
{
nullcThrowError("ERROR: cannot convert from 'auto[]' (actual type '%s[%d]') to '%s'", nullcGetTypeName(right->typeID), right->len, nullcGetTypeName(left.typeID));
return ret;
}
memcpy(left.ptr, right->ptr, leftLength * nullcGetTypeSize(right->typeID));
}
return left;
}
NULLCRef __operatorIndex_auto_ref_ref_auto___ref_int_(NULLCAutoArray* left, int index, void* unused)
{
NULLCRef ret = { 0, 0 };
if(unsigned(index) >= unsigned(left->len))
{
nullcThrowError("ERROR: array index out of bounds");
return ret;
}
ret.typeID = left->typeID;
ret.ptr = (char*)left->ptr + index * nullcGetTypeSize(ret.typeID);
return ret;
}
int isStackPointer_int_ref_auto_ref_(NULLCRef ptr, void* unused)
{
GC::unmanageableBase = (char*)&ptr;
return ptr.ptr >= GC::unmanageableBase && ptr.ptr <= GC::unmanageableTop;
}
void auto_array_impl_void_ref_auto___ref_typeid_int_(NULLCAutoArray* arr, unsigned type, int count, void* unused)
{
arr->typeID = type;
arr->len = count;
arr->ptr = (char*)__newS_void_ref_ref_int_int_(typeid__size__int_ref___(&type) * (count), type, 0);
}
NULLCAutoArray auto_array_auto___ref_typeid_int_(unsigned type, int count, void* unused)
{
NULLCAutoArray res;
auto_array_impl_void_ref_auto___ref_typeid_int_(&res, type, count, NULL);
return res;
}
void auto____set_void_ref_auto_ref_int_(NULLCRef x, int pos, NULLCAutoArray* arr)
{
if(x.typeID != arr->typeID)
{
nullcThrowError("ERROR: cannot convert from '%s' to an 'auto[]' element type '%s'", nullcGetTypeName(x.typeID), nullcGetTypeName(arr->typeID));
return;
}
unsigned elemSize = __nullcGetTypeInfo(arr->typeID)->size;
if(unsigned(pos) >= unsigned(arr->len))
{
unsigned newSize = 1 + arr->len + (arr->len >> 1);
if(pos >= newSize)
newSize = pos;
NULLCAutoArray n;
auto_array_impl_void_ref_auto___ref_typeid_int_(&n, arr->typeID, newSize, NULL);
memcpy(n.ptr, arr->ptr, arr->len * elemSize);
*arr = n;
}
memcpy(arr->ptr + elemSize * pos, x.ptr, elemSize);
}
void __force_size_void_ref_auto___ref_int_(NULLCAutoArray* arr, int size, void* unused)
{
if(unsigned(size) > unsigned(arr->len))
{
nullcThrowError("ERROR: cannot extend array");
return;
}
arr->len = size;
}
int isCoroutineReset_int_ref_auto_ref_(NULLCRef f, void* unused)
{
if(__nullcGetTypeInfo(f.typeID)->category != NULLC_FUNCTION)
{
nullcThrowError("Argument is not a function");
return 0;
}
NULLCFuncPtr<> *fPtr = (NULLCFuncPtr<>*)f.ptr;
if(funcTableExt[fPtr->id].funcType != FunctionCategory::COROUTINE)
{
nullcThrowError("Function is not a coroutine");
return 0;
}
unsigned jmpOffset = *(unsigned*)fPtr->context;
return jmpOffset == 0;
}
void __assertCoroutine_void_ref_auto_ref_(NULLCRef f, void* unused)
{
if(__nullcGetTypeInfo(f.typeID)->category != NULLC_FUNCTION)
nullcThrowError("Argument is not a function");
NULLCFuncPtr<> *fPtr = (NULLCFuncPtr<>*)f.ptr;
if(funcTableExt[fPtr->id].funcType != FunctionCategory::COROUTINE)
nullcThrowError("ERROR: function is not a coroutine");
}
NULLCArray<NULLCRef> __getFinalizeList_auto_ref___ref__(void* __context)
{
NULLCArray<NULLCRef> arr;
arr.ptr = (char*)NULLC::finalizeList.data;
arr.size = NULLC::finalizeList.size();
return arr;
}
void __FinalizeProxy__finalize_void_ref__(__FinalizeProxy* __context)
{
}
void __finalizeObjects_void_ref__(void* __context)
{
NULLCArray<NULLCRef> l = __getFinalizeList_auto_ref___ref__(0);
for(int i = 0; i < l.size; i++)
{
NULLCRef *el = __nullcIndexUnsizedArray(l, i, sizeof(NULLCRef));
NULLCFuncPtr<__typeProxy_void_ref__> function = NULLCFuncPtr<__typeProxy_void_ref__>(__redirect_void_ref___ref_auto_ref___function___ref_(*el, &__vtbl3761170085finalize, 0));
((void(*)(void*))funcTable[function.id])(function.context);
}
}
void* assert_derived_from_base_void_ref_ref_void_ref_typeid_(void* derived, unsigned base, void* unused)
{
if(!derived)
return derived;
unsigned typeId = *(unsigned*)derived;
for(;;)
{
if(base == typeId)
return derived;
NULLCTypeInfo *info = __nullcGetTypeInfo(typeId);
if(info->category == NULLC_CLASS && info->baseClassID != 0)
{
typeId = info->baseClassID;
}
else
{
break;
}
}
nullcThrowError("ERROR: cannot convert from '%s' to '%s'", nullcGetTypeName(*(unsigned*)derived), nullcGetTypeName(base));
return derived;
}
void __closeUpvalue_void_ref_void_ref_ref_void_ref_int_int_(void **upvalueList, void *variable, int offset, int size, void* __context)
{
if (!upvalueList || !variable)
{
nullcThrowError("ERROR: null pointer access");
return;
}
struct Upvalue
{
void *target;
Upvalue *next;
};
Upvalue *upvalue = *(Upvalue**)upvalueList;
while (upvalue && upvalue->target == variable)
{
Upvalue *next = upvalue->next;
char *copy = (char*)upvalue + offset;
memcpy(copy, variable, unsigned(size));
upvalue->target = copy;
upvalue->next = NULL;
upvalue = next;
}
*(Upvalue**)upvalueList = upvalue;
}
int float__str_610894668_precision__int_ref___(void* __context)
{
return 6;
}
bool float__str_610894668_showExponent__bool_ref___(void* __context)
{
return false;
}
int double__str_610894668_precision__int_ref___(void* __context)
{
return 6;
}
bool double__str_610894668_showExponent__bool_ref___(void* __context)
{
return false;
}
void nullcThrowError(const char* error, ...)
{
va_list args;
va_start(args, error);
vprintf(error, args);
va_end(args);
}
__nullcFunctionArray* __nullcGetFunctionTable()
{
return &funcTable.data;
}
unsigned int __nullcGetStringHash(const char *str)
{
unsigned int hash = 5381;
int c;
while((c = *str++) != 0)
hash = ((hash << 5) + hash) + c;
return hash;
}
unsigned __nullcRegisterFunction(const char* name, void* fPtr, unsigned extraType, unsigned funcType, bool unique)
{
unsigned hash = __nullcGetStringHash(name);
if(!unique)
{
for(unsigned int i = 0; i < funcTable.size(); i++)
{
if(funcTableExt[i].hash == hash)
return i;
}
}
funcTable.push_back(fPtr);
NULLCFuncInfo info;
info.hash = hash;
info.name = name;
info.extraType = extraType;
info.funcType = funcType;
funcTableExt.push_back(info);
return funcTable.size() - 1;
}
NULLCFuncInfo* __nullcGetFunctionInfo(unsigned id)
{
return &funcTableExt[id];
}
// Memory allocation and GC
#define GC_DEBUG_PRINT(...)
//#define GC_DEBUG_PRINT printf
#define NULLC_PTR_SIZE sizeof(void*)
namespace
{
const uintptr_t OBJECT_VISIBLE = 1 << 0;
const uintptr_t OBJECT_FREED = 1 << 1;
const uintptr_t OBJECT_FINALIZABLE = 1 << 2;
const uintptr_t OBJECT_FINALIZED = 1 << 3;
const uintptr_t OBJECT_ARRAY = 1 << 4;
const uintptr_t OBJECT_MASK = OBJECT_VISIBLE | OBJECT_FREED;
}
namespace GC
{
unsigned int objectName = __nullcGetStringHash("auto ref");
unsigned int autoArrayName = __nullcGetStringHash("auto[]");
void PrintMarker(markerType marker)
{
GC_DEBUG_PRINT("\tMarker is 0x%2x [", marker);
if(marker & OBJECT_VISIBLE)
GC_DEBUG_PRINT("visible");
else
GC_DEBUG_PRINT("unmarked");
if(marker & OBJECT_FREED)
GC_DEBUG_PRINT(" freed");
if(marker & OBJECT_FINALIZABLE)
GC_DEBUG_PRINT(" finalizable");
if(marker & OBJECT_FINALIZED)
GC_DEBUG_PRINT(" finalized");
if(marker & OBJECT_ARRAY)
GC_DEBUG_PRINT(" array");
GC_DEBUG_PRINT("] type %d '%s'\r\n", marker >> 8, __nullcGetTypeInfo(marker >> 8)->name);
}
void CheckArray(char* ptr, const NULLCTypeInfo& type);
void CheckClass(char* ptr, const NULLCTypeInfo& type);
void CheckFunction(char* ptr);
void CheckVariable(char* ptr, const NULLCTypeInfo& type);
// Function that marks memory blocks belonging to GC
void MarkPointer(char* ptr, const NULLCTypeInfo& type, bool takeSubtype)
{
// We have pointer to stack that has a pointer inside, so 'ptr' is really a pointer to pointer
char **rPtr = (char**)ptr;
// Check for unmanageable ranges. Range of 0x00000000-0x00010000 is unmanageable by default due to upvalues with offsets inside closures.
if(*rPtr > (char*)0x00010000 && (*rPtr < unmanageableBase || *rPtr > unmanageableTop))
{
// Get type that pointer points to
GC_DEBUG_PRINT("\tGlobal pointer [ref] %s %p (at %p)\r\n", type.name, *rPtr, ptr);
// Get pointer to the start of memory block. Some pointers may point to the middle of memory blocks
unsigned int *basePtr = (unsigned int*)NULLC::GetBasePointer(*rPtr);
// If there is no base, this pointer points to memory that is not GCs memory
if(!basePtr)
return;
GC_DEBUG_PRINT("\tPointer base is %p\r\n", basePtr);
// Marker is 4 bytes before the block
markerType *marker = (markerType*)((char*)basePtr - sizeof(markerType));
PrintMarker(*marker);
// If block is unmarked
if(!(*marker & OBJECT_VISIBLE))
{
// Mark block as used
*marker |= OBJECT_VISIBLE;
GC_DEBUG_PRINT("Type near memory %d, type %d (%d)\n", *marker >> 8, type.subTypeID, takeSubtype);
unsigned targetSubType = type.subTypeID;
if(takeSubtype && targetSubType == 0)
targetSubType = unsigned(*marker >> 8);
// And if type is not simple, check memory to which pointer points to
if(type.category != NULLC_NONE)
CheckVariable(*rPtr, takeSubtype ? __nullcTypeList[targetSubType] : type);
}
else if(takeSubtype && __nullcTypeList[type.subTypeID].category == NULLC_POINTER)
{
MarkPointer(*rPtr, __nullcTypeList[type.subTypeID], true);
}
}
}
void CheckArrayElements(char* ptr, unsigned size, const NULLCTypeInfo& elementType)
{
// Check every array element
switch(elementType.category)
{
case NULLC_ARRAY:
for(unsigned int i = 0; i < size; i++, ptr += elementType.size)
CheckArray(ptr, elementType);
break;
case NULLC_POINTER:
for(unsigned int i = 0; i < size; i++, ptr += elementType.size)
MarkPointer(ptr, elementType, true);
break;
case NULLC_CLASS:
for(unsigned int i = 0; i < size; i++, ptr += elementType.size)
CheckClass(ptr, elementType);
break;
case NULLC_FUNCTION:
for(unsigned int i = 0; i < size; i++, ptr += elementType.size)
CheckFunction(ptr);
break;
}
}
// Function that checks arrays for pointers
void CheckArray(char* ptr, const NULLCTypeInfo& type)
{
// Get array element type
NULLCTypeInfo *subType = &__nullcTypeList[type.subTypeID];
// Real array size (changed for unsized arrays)
unsigned int size = type.memberCount;
// If array type is an unsized array, check pointer that points to actual array contents
if(size == -1)
{
// Get real array size
size = ((NULLCArray<void>*)ptr)->size;
// Switch pointer to array data
char **rPtr = (char**)ptr;
ptr = *rPtr;
// If uninitialized or points to stack memory, return
if(!ptr || ptr <= (char*)0x00010000 || (ptr >= unmanageableBase && ptr <= unmanageableTop))
return;
GC_DEBUG_PRINT("\tGlobal pointer [array] %p\r\n", ptr);
// Get base pointer
unsigned int *basePtr = (unsigned int*)NULLC::GetBasePointer(ptr);
// If there is no base, this pointer points to memory that is not GCs memory
if(!basePtr)
return;
GC_DEBUG_PRINT("\tPointer base is %p\r\n", basePtr);
markerType *marker = (markerType*)((char*)basePtr - sizeof(markerType));
PrintMarker(*marker);
// If there is no base pointer or memory already marked, exit
if((*marker & OBJECT_VISIBLE))
return;
// Mark memory as used
*marker |= OBJECT_VISIBLE;
}else if(type.hash == autoArrayName){
NULLCAutoArray *data = (NULLCAutoArray*)ptr;
// Get real variable type
subType = &__nullcTypeList[data->typeID];
// skip uninitialized array
if(!data->ptr)
return;
// Mark target data
MarkPointer((char*)&data->ptr, *subType, false);
// Switch pointer to target
ptr = data->ptr;
// Get array size
size = data->len;
}
CheckArrayElements(ptr, size, *subType);
}
// Function that checks classes for pointers
void CheckClass(char* ptr, const NULLCTypeInfo& type)
{
const NULLCTypeInfo *realType = &type;
if(type.hash == objectName)
{
// Get real variable type
realType = &__nullcTypeList[*(int*)ptr];
// Switch pointer to target
ptr = ((NULLCRef*)ptr)->ptr;
// If uninitialized or points to stack memory, return
if(!ptr || ptr <= (char*)0x00010000 || (ptr >= unmanageableBase && ptr <= unmanageableTop))
return;
GC_DEBUG_PRINT("\tGlobal pointer [class] %p\r\n", ptr);
// Get base pointer
unsigned int *basePtr = (unsigned int*)NULLC::GetBasePointer(ptr);
// If there is no base, this pointer points to memory that is not GCs memory
if(!basePtr)
return;
GC_DEBUG_PRINT("\tPointer base is %p\r\n", basePtr);
markerType *marker = (markerType*)((char*)basePtr - sizeof(markerType));
PrintMarker(*marker);
// If there is no base pointer or memory already marked, exit
if((*marker & OBJECT_VISIBLE))
return;
// Mark memory as used
*marker |= OBJECT_VISIBLE;
// Fixup target
CheckVariable(ptr, *realType);
// Exit
return;
}else if(type.hash == autoArrayName){
CheckArray(ptr, type);
// Exit
return;
}
// Get class member type list
NULLCMemberInfo *memberList = &__nullcTypePart[realType->members];
// Check pointer members
for(unsigned int n = 0; n < realType->memberCount; n++)
{
// Get member type
NULLCTypeInfo &subType = __nullcTypeList[memberList[n].typeID];
unsigned int pos = memberList[n].offset;
// Check member
CheckVariable(ptr + pos, subType);
}
}
// Function that checks function context for pointers
void CheckFunction(char* ptr)
{
NULLCFuncPtr<> *fPtr = (NULLCFuncPtr<>*)ptr;
// If there's no context, there's nothing to check
if(!fPtr->context)
return;
const NULLCFuncInfo &func = funcTableExt[fPtr->id];
// If context is "this" pointer
if(func.extraType != ~0u)
MarkPointer((char*)&fPtr->context, __nullcTypeList[func.extraType], true);
}
// Function that decides, how variable of type 'type' should be checked for pointers
void CheckVariable(char* ptr, const NULLCTypeInfo& type)
{
const NULLCTypeInfo *realType = &type;
if((type.flags & NULLC_TYPE_FLAG_IS_EXTENDABLE) != 0)
realType = __nullcGetTypeInfo(*(unsigned*)ptr);
switch(type.category)
{
case NULLC_ARRAY:
CheckArray(ptr, type);
break;
case NULLC_POINTER:
MarkPointer(ptr, type, true);
break;
case NULLC_CLASS:
CheckClass(ptr, *realType);
break;
case NULLC_FUNCTION:
CheckFunction(ptr);
break;
}
}
}
struct GlobalRoot
{
void *ptr;
unsigned typeID;
};
FastVector<GlobalRoot> rootSet;
// Main function for marking all pointers in a program
void MarkUsedBlocks()
{
GC_DEBUG_PRINT("Unmanageable range: %p-%p\r\n", GC::unmanageableBase, GC::unmanageableTop);
// Mark global variables
for(unsigned int i = 0; i < rootSet.size(); i++)
{
GC_DEBUG_PRINT("Global %s (at %p)\r\n", __nullcTypeList[rootSet[i].typeID].name, rootSet[i].ptr);
GC::CheckVariable((char*)rootSet[i].ptr, __nullcTypeList[rootSet[i].typeID]);
}
// Check that temporary stack range is correct
assert(GC::unmanageableTop >= GC::unmanageableBase, "ERROR: GC - incorrect stack range", 0);
char* tempStackBase = GC::unmanageableBase;
// Check temporary stack for pointers
while(tempStackBase < GC::unmanageableTop)
{
char *ptr = *(char**)(tempStackBase);
// Check for unmanageable ranges. Range of 0x00000000-0x00010000 is unmanageable by default due to upvalues with offsets inside closures.
if(ptr > (char*)0x00010000 && (ptr < GC::unmanageableBase || ptr > GC::unmanageableTop))
{
// Get pointer base
unsigned int *basePtr = (unsigned int*)NULLC::GetBasePointer(ptr);
// If there is no base, this pointer points to memory that is not GCs memory
if(basePtr)
{
markerType *marker = (markerType*)(basePtr) - 1;
// Might step on a left-over pointer in stale registers
if(*marker & OBJECT_FREED)
{
tempStackBase += 4;
continue;
}
// If block is unmarked, mark it as used
if(!(*marker & OBJECT_VISIBLE))
{
NULLCTypeInfo &type = __nullcTypeList[*marker >> 8];
*marker |= OBJECT_VISIBLE;
GC_DEBUG_PRINT("Found %s type %d on stack at %p\n", type.name, *marker >> 8, ptr);
if(*marker & OBJECT_ARRAY)
{
unsigned arrayPadding = type.alignment > 4 ? type.alignment : 4;
char *elements = (char*)basePtr + arrayPadding;
unsigned size;
memcpy(&size, elements - sizeof(unsigned), sizeof(unsigned));
GC::CheckArrayElements(elements, size, type);
}
else
{
// And if type is not simple, check memory to which pointer points to
if(type.category != NULLC_NONE)
GC::CheckVariable(ptr, type);
}
}
}
}
tempStackBase += 4;
}
}
void __nullcRegisterGlobal(void* ptr, unsigned typeID)
{
GlobalRoot entry;
entry.ptr = ptr;
entry.typeID = typeID;
rootSet.push_back(entry);
}
void __nullcRegisterBase(void* ptr)
{
if(GC::unmanageableTop)
GC::unmanageableTop = (uintptr_t)ptr > (uintptr_t)GC::unmanageableTop ? (char*)ptr : GC::unmanageableTop;
else
GC::unmanageableTop = (char*)ptr;
}
namespace NULLC
{
void FinalizeObject(markerType& marker, char* base)
{
if(marker & OBJECT_ARRAY)
{
NULLCTypeInfo *typeInfo = __nullcGetTypeInfo((unsigned)marker >> 8);
unsigned arrayPadding = typeInfo->alignment > 4 ? typeInfo->alignment : 4;
unsigned count = *(unsigned*)(base + sizeof(markerType) + arrayPadding - 4);
NULLCRef r = { (unsigned)marker >> 8, base + sizeof(markerType) + arrayPadding }; // skip over marker and array size
for(unsigned i = 0; i < count; i++)
{
NULLC::finalizeList.push_back(r);
r.ptr += typeInfo->size;
}
}
else
{
NULLCRef r = { (unsigned)marker >> 8, base + sizeof(markerType) }; // skip over marker
NULLC::finalizeList.push_back(r);
}
marker |= OBJECT_FINALIZED;
}
}
template<int elemSize>
union SmallBlock
{
char data[elemSize];
markerType marker;
SmallBlock *next;
};
template<int elemSize, int countInBlock>
struct LargeBlock
{
typedef SmallBlock<elemSize> Block;
// Padding is used to break the 16 byte alignment of pages in a way that after a marker offset is added to the block, the object pointer will be correctly aligned
char padding[16 - sizeof(markerType)];
Block page[countInBlock];
LargeBlock *next;
};
template<int elemSize, int countInBlock>
class ObjectBlockPool
{
typedef SmallBlock<elemSize> MySmallBlock;
typedef LargeBlock<elemSize, countInBlock> MyLargeBlock;
public:
ObjectBlockPool()
{
freeBlocks = &lastBlock;
activePages = NULL;
lastNum = countInBlock;
}
~ObjectBlockPool()
{
if(!activePages)
return;
do
{
MyLargeBlock* following = activePages->next;
NULLC::alignedDealloc(activePages);
activePages = following;
}while(activePages != NULL);
freeBlocks = &lastBlock;
activePages = NULL;
lastNum = countInBlock;
sortedPages.reset();
}
void* Alloc()
{
MySmallBlock* result;
if(freeBlocks && freeBlocks != &lastBlock)
{
result = freeBlocks;
freeBlocks = (MySmallBlock*)((intptr_t)freeBlocks->next & ~OBJECT_MASK);
}else{
if(lastNum == countInBlock)
{
MyLargeBlock* newPage = (MyLargeBlock*)NULLC::alignedAlloc(sizeof(MyLargeBlock));
memset(newPage, 0, sizeof(MyLargeBlock));
newPage->next = activePages;
activePages = newPage;
lastNum = 0;
sortedPages.push_back(newPage);
int index = sortedPages.size() - 1;
while(index > 0 && sortedPages[index] < sortedPages[index - 1])
{
MyLargeBlock *tmp = sortedPages[index];
sortedPages[index] = sortedPages[index - 1];
sortedPages[index - 1] = tmp;
index--;
}
}
result = &activePages->page[lastNum++];
}
return result;
}
void Free(void* ptr)
{
if(!ptr)
return;
MySmallBlock* freedBlock = static_cast<MySmallBlock*>(static_cast<void*>(ptr));
freedBlock->next = (MySmallBlock*)((intptr_t)freeBlocks | OBJECT_FREED);
freeBlocks = freedBlock;
}
bool IsBasePointer(void* ptr)
{
MyLargeBlock *curr = activePages;
while(curr)
{
if((char*)ptr >= (char*)curr->page && (char*)ptr <= (char*)curr->page + sizeof(MyLargeBlock))
{
if(((unsigned int)(intptr_t)((char*)ptr - (char*)curr->page) & (elemSize - 1)) == 4)
return true;
}
curr = curr->next;
}
return false;
}
void* GetBasePointer(void* ptr)
{
if(!sortedPages.size() || ptr < sortedPages[0] || ptr > (char*)sortedPages.back() + sizeof(MyLargeBlock))
return NULL;
// Binary search
unsigned int lowerBound = 0;
unsigned int upperBound = sortedPages.size() - 1;
unsigned int pointer = 0;
while(upperBound - lowerBound > 1)
{
pointer = (lowerBound + upperBound) >> 1;
if(ptr < sortedPages[pointer])
upperBound = pointer;
if(ptr > sortedPages[pointer])
lowerBound = pointer;
}
if(ptr < sortedPages[pointer])
pointer--;
if(ptr > (char*)sortedPages[pointer] + sizeof(MyLargeBlock))
pointer++;
MyLargeBlock *best = sortedPages[pointer];
if(ptr < best->page || ptr > (char*)best + sizeof(best->page))
return NULL;
unsigned int fromBase = (unsigned int)(intptr_t)((char*)ptr - (char*)best->page);
return (char*)best->page + (fromBase & ~(elemSize - 1)) + sizeof(markerType);
}
void Mark(unsigned int number)
{
__assert(number <= 1);
MyLargeBlock *curr = activePages;
while(curr)
{
for(unsigned int i = 0; i < (curr == activePages ? lastNum : countInBlock); i++)
{
curr->page[i].marker = (curr->page[i].marker & ~OBJECT_VISIBLE) | number;
}
curr = curr->next;
}
}
unsigned int FreeMarked()
{
unsigned int freed = 0;
MyLargeBlock *curr = activePages;
while(curr)
{
for(unsigned int i = 0; i < (curr == activePages ? lastNum : countInBlock); i++)
{
if(!(curr->page[i].marker & (OBJECT_VISIBLE | OBJECT_FREED)))
{
if((curr->page[i].marker & OBJECT_FINALIZABLE) && !(curr->page[i].marker & OBJECT_FINALIZED))
{
NULLC::FinalizeObject(curr->page[i].marker, curr->page[i].data);
}else{
Free(&curr->page[i]);
freed++;
}
}
}
curr = curr->next;
}
return freed;
}
MySmallBlock lastBlock;
MySmallBlock *freeBlocks;
MyLargeBlock *activePages;
unsigned int lastNum;
FastVector<MyLargeBlock*> sortedPages;
};
namespace NULLC
{
const unsigned int poolBlockSize = 64 * 1024;
unsigned int usedMemory = 0;
unsigned int collectableMinimum = 1024 * 1024;
unsigned int globalMemoryLimit = 1024 * 1024 * 1024;
ObjectBlockPool<8, poolBlockSize / 8> pool8;
ObjectBlockPool<16, poolBlockSize / 16> pool16;
ObjectBlockPool<32, poolBlockSize / 32> pool32;
ObjectBlockPool<64, poolBlockSize / 64> pool64;
ObjectBlockPool<128, poolBlockSize / 128> pool128;
ObjectBlockPool<256, poolBlockSize / 256> pool256;
ObjectBlockPool<512, poolBlockSize / 512> pool512;
struct Range
{
Range(): start(NULL), end(NULL)
{
}
Range(void* start, void* end): start(start), end(end)
{
}
// Ranges are equal if they intersect
bool operator==(const Range& rhs) const
{
return !(start > rhs.end || end < rhs.start);
}
bool operator<(const Range& rhs) const
{
return end < rhs.start;
}
bool operator>(const Range& rhs) const
{
return start > rhs.end;
}
void *start, *end;
};
typedef Tree<Range>::iterator BigBlockIterator;
Tree<Range> bigBlocks;
unsigned currentMark = 0;
unsigned unusedBlocks = 0;
FastVector<Range> toErase;
void MarkBlock(Range& curr);
void CollectBlock(Range& curr);
void FinalizeBlock(Range& curr);
double markTime = 0.0;
double collectTime = 0.0;
}
void* NULLC::AllocObject(int size, unsigned typeID)
{
if(size < 0)
{
nullcThrowError("Requested memory size is less than zero.");
return NULL;
}
void *data = NULL;
size += sizeof(markerType);
if((unsigned int)(usedMemory + size) > globalMemoryLimit)
{
CollectMemory();
if((unsigned int)(usedMemory + size) > globalMemoryLimit)
{
nullcThrowError("Reached global memory maximum");
return NULL;
}
}else if((unsigned int)(usedMemory + size) > collectableMinimum){
CollectMemory();
}
unsigned int realSize = size;
if(size <= 64)
{
if(size <= 16)
{
if(size <= 8)
{
data = pool8.Alloc();
realSize = 8;
}else{
data = pool16.Alloc();
realSize = 16;
}
}else{
if(size <= 32)
{
data = pool32.Alloc();
realSize = 32;
}else{
data = pool64.Alloc();
realSize = 64;
}
}
}else{
if(size <= 256)
{
if(size <= 128)
{
data = pool128.Alloc();
realSize = 128;
}else{
data = pool256.Alloc();
realSize = 256;
}
}else{
if(size <= 512)
{
data = pool512.Alloc();
realSize = 512;
}else{
void *ptr = NULLC::alignedAlloc(size - sizeof(markerType), 4 + sizeof(markerType));
if(ptr == NULL)
{
nullcThrowError("Allocation failed.");
return NULL;
}
Range range(ptr, (char*)ptr + size + 4);
bigBlocks.insert(range);
realSize = *(int*)ptr = size;
data = (char*)ptr + 4;
}
}
}
usedMemory += realSize;
if(data == NULL)
{
nullcThrowError("Allocation failed.");
return NULL;
}
int finalize = 0;
if(typeID && (__nullcGetTypeInfo(typeID)->flags & NULLC_TYPE_FLAG_HAS_FINALIZER) != 0)
finalize = (int)OBJECT_FINALIZABLE;
memset(data, 0, size);
*(markerType*)data = finalize | (typeID << 8);
return (char*)data + sizeof(markerType);
}
unsigned int NULLC::UsedMemory()
{
return usedMemory;
}
NULLCArray<int> NULLC::AllocArray(int size, int count, unsigned typeID)
{
NULLCArray<int> ret;
ret.size = 0;
ret.ptr = NULL;
if((unsigned long long)size * count > globalMemoryLimit)
{
nullcThrowError("ERROR: can't allocate array with %u elements of size %u", count, size);
return ret;
}
NULLCTypeInfo *type = __nullcGetTypeInfo(typeID);
unsigned arrayPadding = type->alignment > 4 ? type->alignment : 4;
unsigned bytes = count * size;
if(bytes == 0)
bytes += 4;
char *ptr = (char*)AllocObject(bytes + arrayPadding, typeID);
if(!ptr)
return ret;
ret.size = count;
ret.ptr = arrayPadding + ptr;
((unsigned*)ret.ptr)[-1] = count;
markerType *marker = (markerType*)(ptr - sizeof(markerType));
*marker |= OBJECT_ARRAY;
return ret;
}
void NULLC::MarkBlock(Range& curr)
{
markerType *marker = (markerType*)((char*)curr.start + 4);
*marker = (*marker & ~OBJECT_VISIBLE) | currentMark;
}
void NULLC::MarkMemory(unsigned int number)
{
__assert(number <= 1);
currentMark = number;
bigBlocks.for_each(MarkBlock);
pool8.Mark(number);
pool16.Mark(number);
pool32.Mark(number);
pool64.Mark(number);
pool128.Mark(number);
pool256.Mark(number);
pool512.Mark(number);
}
bool NULLC::IsBasePointer(void* ptr)
{
// Search in range of every pool
if(pool8.IsBasePointer(ptr))
return true;
if(pool16.IsBasePointer(ptr))
return true;
if(pool32.IsBasePointer(ptr))
return true;
if(pool64.IsBasePointer(ptr))
return true;
if(pool128.IsBasePointer(ptr))
return true;
if(pool256.IsBasePointer(ptr))
return true;
if(pool512.IsBasePointer(ptr))
return true;
// Search in global pool
if(BigBlockIterator it = bigBlocks.find(Range(ptr, ptr)))
{
void *block = it->key.start;
if((char*)ptr - 4 - sizeof(markerType) == block)
return true;
}
return false;
}
void* NULLC::GetBasePointer(void* ptr)
{
// Search in range of every pool
if(void *base = pool8.GetBasePointer(ptr))
return base;
if(void *base = pool16.GetBasePointer(ptr))
return base;
if(void *base = pool32.GetBasePointer(ptr))
return base;
if(void *base = pool64.GetBasePointer(ptr))
return base;
if(void *base = pool128.GetBasePointer(ptr))
return base;
if(void *base = pool256.GetBasePointer(ptr))
return base;
if(void *base = pool512.GetBasePointer(ptr))
return base;
// Search in global pool
if(BigBlockIterator it = bigBlocks.find(Range(ptr, ptr)))
{
void *block = it->key.start;
if(ptr >= block && ptr <= (char*)block + *(unsigned int*)block)
return (char*)block + 4 + sizeof(markerType);
}
return NULL;
}
void NULLC::CollectBlock(Range& curr)
{
void *block = curr.start;
markerType &marker = *(markerType*)((char*)block + 4);
if(!(marker & OBJECT_VISIBLE))
{
if((marker & OBJECT_FINALIZABLE) && !(marker & OBJECT_FINALIZED))
{
NULLC::FinalizeObject(marker, (char*)block + 4);
}else{
usedMemory -= *(unsigned int*)block;
NULLC::alignedDealloc(block);
toErase.push_back(curr);
unusedBlocks++;
}
}
}
void NULLC::CollectMemory()
{
GC_DEBUG_PRINT("%d used memory (%d collectable cap, %d max cap)\r\n", usedMemory, collectableMinimum, globalMemoryLimit);
double time = (double(clock()) / CLOCKS_PER_SEC);
GC::unmanageableBase = (char*)&time;
// All memory blocks are marked with 0
MarkMemory(0);
// Used memory blocks are marked with 1
MarkUsedBlocks();
markTime += (double(clock()) / CLOCKS_PER_SEC) - time;
time = (double(clock()) / CLOCKS_PER_SEC);
// Globally allocated objects marked with 0 are deleted
unusedBlocks = 0;
toErase.clear();
bigBlocks.for_each(CollectBlock);
for(unsigned i = 0; i < toErase.size(); i++)
bigBlocks.erase(toErase[i]);
toErase.clear();
// printf("%d unused globally allocated blocks destroyed\r\n", unusedBlocks);
// printf("%d used memory\r\n", usedMemory);
// Objects allocated from pools are freed
unusedBlocks = pool8.FreeMarked();
usedMemory -= unusedBlocks * 8;
// printf("%d unused pool blocks freed (8 bytes)\r\n", unusedBlocks);
unusedBlocks = pool16.FreeMarked();
usedMemory -= unusedBlocks * 16;
// printf("%d unused pool blocks freed (16 bytes)\r\n", unusedBlocks);
unusedBlocks = pool32.FreeMarked();
usedMemory -= unusedBlocks * 32;
// printf("%d unused pool blocks freed (32 bytes)\r\n", unusedBlocks);
unusedBlocks = pool64.FreeMarked();
usedMemory -= unusedBlocks * 64;
// printf("%d unused pool blocks freed (64 bytes)\r\n", unusedBlocks);
unusedBlocks = pool128.FreeMarked();
usedMemory -= unusedBlocks * 128;
// printf("%d unused pool blocks freed (128 bytes)\r\n", unusedBlocks);
unusedBlocks = pool256.FreeMarked();
usedMemory -= unusedBlocks * 256;
// printf("%d unused pool blocks freed (256 bytes)\r\n", unusedBlocks);
unusedBlocks = pool512.FreeMarked();
usedMemory -= unusedBlocks * 512;
// printf("%d unused pool blocks freed (512 bytes)\r\n", unusedBlocks);
GC_DEBUG_PRINT("%d used memory\r\n", usedMemory);
collectTime += (double(clock()) / CLOCKS_PER_SEC) - time;
if(usedMemory + (usedMemory >> 1) >= collectableMinimum)
collectableMinimum <<= 1;
__finalizeObjects_void_ref__(0);
finalizeList.clear();
}
double NULLC::MarkTime()
{
return markTime;
}
double NULLC::CollectTime()
{
return collectTime;
}
void NULLC::FinalizeBlock(Range& curr)
{
void *block = curr.start;
markerType &marker = *(markerType*)((char*)block + 4);
if(!(marker & OBJECT_VISIBLE) && (marker & OBJECT_FINALIZABLE) && !(marker & OBJECT_FINALIZED))
NULLC::FinalizeObject(marker, (char*)block + 4);
}
void NULLC::FinalizeMemory()
{
MarkMemory(0);
pool8.FreeMarked();
pool16.FreeMarked();
pool32.FreeMarked();
pool64.FreeMarked();
pool128.FreeMarked();
pool256.FreeMarked();
pool512.FreeMarked();
bigBlocks.for_each(FinalizeBlock);
__finalizeObjects_void_ref__(0);
finalizeList.clear();
}
int __nullcOutputResultInt(int x)
{
printf("%d", x);
return 0;
}
int __nullcOutputResultLong(long long x)
{
printf("%lld", x);
return 0;
}
int __nullcOutputResultDouble(double x)
{
printf("%f", x);
return 0;
}
// Typeid redirect table
static unsigned __nullcTR[17];
int __nullcInitBaseModule()
{
static int moduleInitialized = 0;
if(moduleInitialized++)
return 0;
int __local = 0;
__nullcRegisterBase(&__local);
// Register types
__nullcTR[0] = __nullcRegisterType(2090838615u, "void", 0, __nullcTR[0], 0, NULLC_NONE, 0, 0);
__nullcTR[1] = __nullcRegisterType(2090120081u, "bool", 1, __nullcTR[0], 0, NULLC_NONE, 0, 0);
__nullcTR[2] = __nullcRegisterType(2090147939u, "char", 1, __nullcTR[0], 0, NULLC_NONE, 0, 0);
__nullcTR[3] = __nullcRegisterType(274395349u, "short", 2, __nullcTR[0], 0, NULLC_NONE, 2, 0);
__nullcTR[4] = __nullcRegisterType(193495088u, "int", 4, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[5] = __nullcRegisterType(2090479413u, "long", 8, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[6] = __nullcRegisterType(259121563u, "float", 4, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[7] = __nullcRegisterType(4181547808u, "double", 8, __nullcTR[0], 0, NULLC_NONE, 8, 0);
__nullcTR[8] = __nullcRegisterType(524429492u, "typeid", 4, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[9] = __nullcRegisterType(1211668521u, "__function", 4, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[10] = __nullcRegisterType(84517172u, "__nullptr", 4, __nullcTR[0], 0, NULLC_NONE, 4, 0);
__nullcTR[11] = 0; // generic type 'generic'
__nullcTR[12] = __nullcRegisterType(2090090846u, "auto", 0, __nullcTR[0], 0, NULLC_NONE, 0, 0);
__nullcTR[13] = __nullcRegisterType(1166360283u, "auto ref", 8, __nullcTR[0], 2, NULLC_CLASS, 4, 0);
__nullcTR[14] = __nullcRegisterType(3198057556u, "void ref", 4, __nullcTR[0], 1, NULLC_POINTER, 4, 0);
__nullcTR[15] = __nullcRegisterType(4071234806u, "auto[]", 12, __nullcTR[0], 3, NULLC_CLASS, 4, 0);
__nullcTR[16] = __nullcRegisterType(952062593u, "__function[]", 8, __nullcTR[9], -1, NULLC_ARRAY, 4, 0);
// Register type members
__nullcRegisterMembers(__nullcTR[13], 2, __nullcTR[8], 0, "type", __nullcTR[14], 4, "ptr"); // type 'auto ref' members
__nullcRegisterMembers(__nullcTR[15], 3, __nullcTR[8], 0, "type", __nullcTR[14], 4, "ptr", __nullcTR[4], 8, "size"); // type 'auto[]' members
__nullcRegisterMembers(__nullcTR[16], 1, __nullcTR[4], 4, "size"); // type '__function[]' members
// Register globals
__nullcRegisterGlobal((void*)&__vtbl3761170085finalize, __nullcTR[16]);
// Expressions
__vtbl3761170085finalize = NULLC::AllocArray(4, 1024, __nullcTR[9]);
return 0;
}
| mit |
AntShares/AntShares | tests/neo.UnitTests/Network/P2P/Payloads/UT_AddrPayload.cs | 1489 | using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using System;
using System.Linq;
using System.Net;
namespace Neo.UnitTests.Network.P2P.Payloads
{
[TestClass]
public class UT_AddrPayload
{
[TestMethod]
public void Size_Get()
{
var test = new AddrPayload() { AddressList = new NetworkAddressWithTime[0] };
test.Size.Should().Be(1);
test = AddrPayload.Create(new NetworkAddressWithTime[] { new NetworkAddressWithTime() { Address = IPAddress.Any, Capabilities = new Neo.Network.P2P.Capabilities.NodeCapability[0], Timestamp = 1 } });
test.Size.Should().Be(22);
}
[TestMethod]
public void DeserializeAndSerialize()
{
var test = AddrPayload.Create(new NetworkAddressWithTime[] { new NetworkAddressWithTime()
{
Address = IPAddress.Any,
Capabilities = new Neo.Network.P2P.Capabilities.NodeCapability[0], Timestamp = 1
}
});
var clone = test.ToArray().AsSerializable<AddrPayload>();
CollectionAssert.AreEqual(test.AddressList.Select(u => u.EndPoint).ToArray(), clone.AddressList.Select(u => u.EndPoint).ToArray());
Assert.ThrowsException<FormatException>(() => new AddrPayload() { AddressList = new NetworkAddressWithTime[0] }.ToArray().AsSerializable<AddrPayload>());
}
}
}
| mit |
overtrue/wechat | tests/OpenPlatform/Authorizer/OfficialAccount/Account/ClientTest.php | 1461 | <?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Tests\OpenPlatform\Authorizer\OfficialAccount\Account;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Account\Client;
use EasyWeChat\Tests\TestCase;
class ClientTest extends TestCase
{
public function testGetPreAuthorizationUrl()
{
$app = new Application(['app_id' => 'component-app-id']);
$client = \Mockery::mock(Client::class.'[request]', [new Application(['app_id' => 'app-id']), $app]);
$this->assertSame(
'https://mp.weixin.qq.com/cgi-bin/fastregisterauth?copy_wx_verify=0&component_appid=component-app-id&appid=app-id&redirect_uri=https%3A%2F%2Feasywechat.com%2Fcallback',
$client->getFastRegistrationUrl('https://easywechat.com/callback', false)
);
}
public function testRegister()
{
$app = new Application(['app_id' => 'component-app-id']);
$client = \Mockery::mock(Client::class.'[httpPostJson]', [new Application(['app_id' => 'app-id']), $app]);
$client->expects()->httpPostJson('cgi-bin/account/fastregister', [
'ticket' => 'ticket',
])->andReturn('mock-result');
$this->assertSame('mock-result', $client->register('ticket'));
}
}
| mit |
pfrendo/ngx-playground | src/app/app.component.ts | 155 | import { Component } from "@angular/core";
@Component({
moduleId: module.id,
selector: "app",
templateUrl: "app.html"
})
export class AppComponent {
} | mit |
Kronuz/Xapiand | src/msgpack/preprocessor/seq/first_n.hpp | 1341 | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef MSGPACK_PREPROCESSOR_SEQ_FIRST_N_HPP
# define MSGPACK_PREPROCESSOR_SEQ_FIRST_N_HPP
#
# include "../config/config.hpp"
# include "../control/if.hpp"
# include "detail/split.hpp"
# include "../tuple/eat.hpp"
# include "../tuple/elem.hpp"
#
# /* MSGPACK_PP_SEQ_FIRST_N */
#
# if ~MSGPACK_PP_CONFIG_FLAGS() & MSGPACK_PP_CONFIG_EDG()
# define MSGPACK_PP_SEQ_FIRST_N(n, seq) MSGPACK_PP_IF(n, MSGPACK_PP_TUPLE_ELEM, MSGPACK_PP_TUPLE_EAT_3)(2, 0, MSGPACK_PP_SEQ_SPLIT(n, seq (nil)))
# else
# define MSGPACK_PP_SEQ_FIRST_N(n, seq) MSGPACK_PP_SEQ_FIRST_N_I(n, seq)
# define MSGPACK_PP_SEQ_FIRST_N_I(n, seq) MSGPACK_PP_IF(n, MSGPACK_PP_TUPLE_ELEM, MSGPACK_PP_TUPLE_EAT_3)(2, 0, MSGPACK_PP_SEQ_SPLIT(n, seq (nil)))
# endif
#
# endif
| mit |
Thorinair/Princess-Luna | luna.js | 282441 | // Modules
const util = require("util")
const fs = require("fs");
const readline = require("readline");
const http = require("http");
const url = require('url');
const exec = require('child_process').exec;
const WebSocket = require('ws');
const dgram = require('dgram');
// 3rd Party Modules
const Discord = require("discord.io");
const CronJob = require("cron").CronJob;
const moment = require("moment-timezone");
const request = require("request");
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const archiver = require("archiver");
const tradfrilib = require('node-tradfri');
const color = require('c0lor');
const jsmegahal = require("jsmegahal");
const tripwire = require("tripwire");
const blitzorapi = require("@simonschick/blitzortungapi");
const Fili = require('fili');
const package = require("./package.json");
// Load file data
var token = require("./config/token.json");
var config = require("./config/config.json");
var commands = require("./config/commands.json");
var custom = require("./config/custom.json");
var strings = require("./config/strings.json");
var gotn = require("./config/gotn.json");
var phases = require("./config/phases.json");
var mlp = require("./config/mlp.json");
var channels = require("./config/channels.json");
var varipass = require("./config/varipass.json");
var printer = require("./config/printer.json");
var dtls = require("./config/dtls.json");
var tradfri = require("./config/tradfri.json");
var schedule = require("./config/schedule.json");
var httpkey = require("./config/httpkey.json");
var mac = require("./config/mac.json");
var blitzor = require("./config/blitzor.json");
var thori = require("./config/thori.json");
var devices = require("./config/devices.json");
var reactrole = require("./config/reactrole.json");
var moon = require(config.moon.lunamoon.pathdata);
require("tls").DEFAULT_ECDH_CURVE = "auto"
/************************************
* Princess Luna's functions are divided in multiple categories
* based on various functionality. In order to jump to a
* certain category, please search for the terms below.
*
* Function index:
*
* STATUS VARIABLES
* COMMAND DEFINITIONS
* COMPONENT AND CONFIG LOADING
* REST API REQUESTS
* DISCORD FUNCTIONALITY
* VARIPASS FUNCTIONALITY
* BLITZORTUNG FUNCTIONALITY
* TRADFRI FUNCTIONALITY
* CHANNEL AND DATA TRANSLATION
* STRING MANIPULATION AND GENERATION
* GEOGRAPHIC DATA PROCESSING
* SEISMOGRAPH DATA PROCESSING
* STATUS MONITORING
* MISCELLANEOUS FUNCTIONS
*
************************************/
/*******************
* STATUS VARIABLES
*******************/
var started = false;
// Loaded
var jobsGOTN = [];
var lyrics;
var art;
var story;
var spool;
var nptoggles;
var annStatus;
var blacklist;
var ignore;
// Phase Data
var jobsPhases = [];
// Brain Data
var brains = {};
var brainProg = 0;
var messages = {};
// Now Playing Data
var np = {};
var npradio = {};
var npstarted = false;
var nppaused = false;
var npover = {};
// EEG Data
var eegValues;
var eegValuesEMA;
var eegValuesEMAPrev;
var eegTable;
var eegTableEMA;
var eegInitial = true;
var eegRecording = false;
var eegConfig;
// Tradfri
var hub;
var tBulbs;
var tDevices;
var hubRetry = 0;
var scheduleEntries = [];
var scheduleJobs = [];
// VariPass
var vpTimeDose;
var vpTimePressure;
var doseWasWarned = false;
var pm025WasWarned = false;
var nightLightCount = 0;
// Purging
var purgeReady = false;
var purgeBrain = "";
var purgeStart = "";
var purgeEnd = "";
// Power Monitoring
var powerStatus = null;
// Blitzortung
var blitzorws;
var lightningRange = blitzor.range;
var lightningNew = blitzor.range;
var lightningLat = 0;
var lightningLng = 0;
var lightningExpire;
var lightningSpread;
var lightningReconnect;
// Blitzortung Storm Chasing
var chasews;
var isChasing = false;
var chaseRange = blitzor.range;
var chaseNew = blitzor.range;
var chaseLat = 0;
var chaseLng = 0;
var chaseExpire;
var chaseSpread;
var chaseReconnect;
var chaseThoriLat = 0.0;
var chaseThoriLng = 0.0;
// RariTUSH Data
var tushStep = 0;
var tushEncL;
var tushEncR;
var tushWeight;
var tushRaw;
var tushPaused = false;
var tushStart;
// Status
var statusGlobal = {};
var statusTimeoutLunaLocal;
var statusTimeoutLunaPublic;
var statusTimeoutChrysalisFileLocal;
var statusTimeoutChrysalisFilePublic;
var statusTimeoutChrysalisIcecastLocal;
var statusTimeoutChrysalisIcecastPublic;
var statusTimeoutChrysalisAnn;
var statusTimeoutRarityLocal;
var statusTimeoutRarityPublic;
var statusTimeoutFluttershyLocal;
var statusTimeoutMoonLocal;
var statusTimeoutTantabusLocal;
var statusTimeoutTantabusPublic;
// Seismo
var seismoLatest = {};
var seismoSamplesBuf = [];
var seismoSamples = [];
var seismoFilter;
var seismoReadyFilter = false;
var seismoReadyEarthquake = false;
var seismoSampleCounter = 0;
var seismoQuakeStartTimeTemp;
var seismoQuakeStartTime;
var seismoQuakePrevTime;
var seismoIsShaking = false;
var seismoIsQuake = false;
var seismoLastMinute = -1;
var seismoAccu = [];
var sampleMedian = 0;
var lastQuake;
// Miscellaneous
var bot;
var server;
var startTime;
var waifuTimeout;
var cameraTimeout;
var reconnectTime = 0;
var rebooting = false;
var isLive = false;
var isplushie = false;
var isShowingLyrics = false;
var isShowingStory = false;
var isShowingArt = false;
var hTrack = {};
var corona;
var udpServer;
/**********************
* COMMAND DEFINITIONS
**********************/
// Object storing all the commands.
var comm = {};
// Command: !gotn
comm.gotn = function(data) {
var now = new Date();
var found = false;
var timezone = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (timezone == "" || timezone == config.options.commandsymbol + data.command)
timezone = "UTC";
if (moment.tz.zone(timezone)) {
gotn.dates.forEach(function(d) {
if (!found) {
var partsDate = d.split(config.separators.date);
var partsTime = gotn.time.split(config.separators.time);
var date = new Date(partsDate[0], parseInt(partsDate[1]) - 1, partsDate[2], partsTime[0], partsTime[1], 0, 0);
if (date > now) {
send(data.channelID, util.format(
strings.commands.gotn.message,
mention(data.userID),
getTimeLeft(now, date, timezone)
), true);
found = true;
}
}
});
}
else {
send(data.channelID, util.format(
strings.misc.timezone,
mention(data.userID)
), true);
}
};
// Command: !mlp
comm.mlp = function(data) {
var now = new Date();
var found = false;
var timezone = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (timezone == "" || timezone == config.options.commandsymbol + data.command)
timezone = "UTC";
if (moment.tz.zone(timezone)) {
mlp.episodes.forEach(function(e) {
if (!found) {
var partsDate = e.date.split(config.separators.date);
var partsTime = e.time.split(config.separators.time);
var date = new Date(partsDate[0], parseInt(partsDate[1]) - 1, partsDate[2], partsTime[0], partsTime[1], 0, 0);
if (date > now) {
send(data.channelID, util.format(
strings.commands.mlp.message,
mention(data.userID),
e.name,
getTimeLeft(now, date, timezone),
mlp.channel
), true);
found = true;
}
}
});
if (!found)
send(data.channelID, util.format(
strings.commands.mlp.error,
mention(data.userID)
), true);
}
else {
send(data.channelID, util.format(
strings.misc.timezone,
mention(data.userID)
), true);
}
};
// Command: !time
comm.time = function(data) {
var now = new Date();
var found = false;
var timezone = data.message.replace(config.options.commandsymbol + data.command + " ", "");
var useEq = (
timezone == "QST" ||
timezone == "Equestria" ||
timezone == "Equestria/Canterlot" ||
timezone == "Equestria/Ponyville" ||
timezone == "Equestria/Manehattan" ||
timezone == "Equestria/Fillydelphia" ||
timezone == "Equestria/Crystal_Empire" ||
timezone == "Equestria/Cloudsdale"
)
if (timezone == "" || timezone == config.options.commandsymbol + data.command || useEq)
timezone = "UTC";
if (moment.tz.zone(timezone)) {
if (useEq) {
var momentTime = moment.tz(now / 8760 + 93*365*24*60*60*1000 + 11*60*60*1000, timezone);
send(data.channelID, util.format(
strings.commands.time.message,
mention(data.userID),
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm:ss") + " (QST)",
Math.round(momentTime / 1000)
), true);
}
else {
var momentTime = moment.tz(now, timezone);
send(data.channelID, util.format(
strings.commands.time.message,
mention(data.userID),
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm:ss (z)"),
Math.round(momentTime / 1000)
), true);
}
}
else {
send(data.channelID, util.format(
strings.misc.timezone,
mention(data.userID)
), true);
}
};
// Command: !np
comm.np = function(data) {
if (np.nowplaying != undefined)
send(data.channelID, util.format(
strings.commands.np.message,
mention(data.userID),
np.nowplaying
), true);
else
send(data.channelID, util.format(
strings.commands.np.error,
mention(data.userID)
), true);
};
// Command: !phase
comm.phase = function(data) {
var dateNow = new Date();
var message;
var phaseNext;
var timezone = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (timezone == "" || timezone == config.options.commandsymbol + data.command)
timezone = "UTC";
if (moment.tz.zone(timezone)) {
var found = false;
phases.forEach(function(p) {
if (!found) {
var datePhase = new Date(p.date);
if (datePhase > dateNow) {
config.phases.forEach(function(n, i) {
if (n.name == p.phase)
phaseNext = config.phases[i].name;
});
message = util.format(
strings.commands.phase.messageA,
mention(data.userID),
getPhaseString(p.phase, -1),
getPhaseString(p.phase, 0),
getTimeLeft(dateNow, datePhase, timezone)
);
found = true;
}
}
});
if (found) {
if (phaseNext != config.moon.fullmoon) {
found = false;
phases.forEach(function(p) {
if (!found) {
var datePhase = new Date(p.date);
if (datePhase > dateNow && p.phase == config.moon.fullmoon) {
message += util.format(
" " + strings.commands.phase.messageB,
getPhaseString(config.moon.fullmoon, 0),
getTimeLeft(dateNow, datePhase, timezone)
);
found = true;
}
}
});
}
}
if (!found) {
send(data.channelID, util.format(
strings.commands.phase.error,
mention(data.userID)
), true);
}
else {
send(data.channelID, message, true);
}
}
else {
send(data.channelID, util.format(
strings.misc.timezone,
mention(data.userID)
), true);
}
};
// Command: !moon
comm.moon = function(data) {
var dateNow = new Date();
var found = false;
if (config.moon.lunamoon.enabled) {
moon.forEach(function(m, i) {
if (!found) {
var dateMoonNext = new Date(m.time);
if (dateMoonNext > dateNow) {
var id = i-1;
if (id < 0)
id = moon.length-1;
var p = moon[id];
var diff;
var age = {};
var dist = {};
p.moment = moment.tz(new Date(p.time), "UTC");
age.days = Math.floor(p.age);
diff = (p.age - age.days) * 24;
age.hours = Math.floor(diff);
diff = (diff - age.hours) * 60;
age.minutes = Math.floor(diff);
dist.a = Math.floor(p.distance / 1000);
dist.b = fillUpZeros(3, Math.floor(p.distance % 1000));
embed(data.channelID, util.format(
strings.commands.moon.messageB,
mention(data.userID),
p.phase,
age.days,
age.hours,
age.minutes,
dist.a,
dist.b,
p.diameter,
p.moment.format("ddd MMM DD, YYYY"),
p.moment.format("HH:mm (z)")
), util.format(
config.moon.lunamoon.pathmoon,
fillUpZeros(4, id)
), "Moon " + (new Date(p.date)) + ".png", true, false);
found = true;
}
}
});
}
else {
phases.forEach(function(p, i) {
if (!found && i > 0) {
var datePhasePrev = new Date(phases[i-1].date);
var datePhaseNext = new Date(p.date);
if (datePhaseNext > dateNow) {
var imagePh = "a";
if (phases[i-1].phase == config.phases[6].name)
imagePh = "b";
else if (phases[i-1].phase == config.phases[0].name)
imagePh = "c";
else if (phases[i-1].phase == config.phases[2].name)
imagePh = "d";
var offset = ((dateNow - datePhasePrev) / (datePhaseNext - datePhasePrev)) * 8;
var imageId = Math.round(offset);
if (imageId == 8) {
imageId = 0;
switch (imagePh) {
case "a": imagePh = "b"; break;
case "b": imagePh = "c"; break;
case "c": imagePh = "d"; break;
case "d": imagePh = "a"; break;
}
}
embed(data.channelID, util.format(
strings.commands.moon.messageA,
mention(data.userID)
), util.format(
config.moon.moonimg,
imagePh,
imageId
), "Moon " + (new Date()) + ".png", true, false);
found = true;
}
}
});
}
if (!found) {
send(data.channelID, util.format(
strings.commands.moon.error,
mention(data.userID)
), true);
}
};
// Command: !room
comm.room = function(data) {
var _key = varipass.main.key;
var payload = {
"key": _key,
"action": "all"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
console.log(strings.debug.varipass.done);
var diffCelly = (vpData.current - findVariable(vpData, varipass.main.ids.temperature).history[0].time);
var timeCelly = {};
timeCelly.seconds = Math.floor(diffCelly % 60);
diffCelly = Math.floor(diffCelly / 60);
timeCelly.minutes = Math.floor(diffCelly % 60);
diffCelly = Math.floor(diffCelly / 60);
timeCelly.hours = Math.floor(diffCelly % 24);
timeCelly.days = Math.floor(diffCelly / 24);
var diffChryssy = (vpData.current - findVariable(vpData, varipass.main.ids.counts).history[0].time);
var timeChryssy = {};
timeChryssy.seconds = Math.floor(diffChryssy % 60);
diffChryssy = Math.floor(diffChryssy / 60);
timeChryssy.minutes = Math.floor(diffChryssy % 60);
diffChryssy = Math.floor(diffChryssy / 60);
timeChryssy.hours = Math.floor(diffChryssy % 24);
timeChryssy.days = Math.floor(diffChryssy / 24);
var diffDashie = (vpData.current - findVariable(vpData, varipass.main.ids.pm010).history[0].time);
var timeDashie = {};
timeDashie.seconds = Math.floor(diffDashie % 60);
diffDashie = Math.floor(diffDashie / 60);
timeDashie.minutes = Math.floor(diffDashie % 60);
diffDashie = Math.floor(diffDashie / 60);
timeDashie.hours = Math.floor(diffDashie % 24);
timeDashie.days = Math.floor(diffDashie / 24);
send(data.channelID, util.format(
strings.commands.room.message,
mention(data.userID),
getTimeStringSimple(timeCelly),
findVariable(vpData, varipass.main.ids.temperature).history[0].value,
findVariable(vpData, varipass.main.ids.humidity).history[0].value,
findVariable(vpData, varipass.main.ids.pressure).history[0].value,
findVariable(vpData, varipass.main.ids.co2).history[0].value,
findVariable(vpData, varipass.main.ids.voc).history[0].value,
findVariable(vpData, varipass.main.ids.light).history[0].value,
findVariable(vpData, varipass.main.ids.magnitude).history[0].value,
findVariable(vpData, varipass.main.ids.inclination).history[0].value,
findVariable(vpData, varipass.main.ids.vibrations_x).history[0].value,
findVariable(vpData, varipass.main.ids.vibrations_y).history[0].value,
findVariable(vpData, varipass.main.ids.vibrations_z).history[0].value,
findVariable(vpData, varipass.main.ids.gravity_x).history[0].value,
findVariable(vpData, varipass.main.ids.gravity_y).history[0].value,
findVariable(vpData, varipass.main.ids.gravity_z).history[0].value,
getTimeStringSimple(timeChryssy),
findVariable(vpData, varipass.main.ids.doseema).history[0].value,
findVariable(vpData, varipass.main.ids.counts).history[0].value,
getTimeStringSimple(timeDashie),
findVariable(vpData, varipass.main.ids.pm010).history[0].value,
findVariable(vpData, varipass.main.ids.pm025).history[0].value,
findVariable(vpData, varipass.main.ids.pm100).history[0].value,
findVariable(vpData, varipass.main.ids.particles003).history[0].value,
findVariable(vpData, varipass.main.ids.particles005).history[0].value,
findVariable(vpData, varipass.main.ids.particles010).history[0].value,
findVariable(vpData, varipass.main.ids.particles025).history[0].value,
findVariable(vpData, varipass.main.ids.particles050).history[0].value,
findVariable(vpData, varipass.main.ids.particles100).history[0].value
), true);
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorR,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
console.log(strings.debug.varipass.load);
xhr.send(JSON.stringify(payload));
};
// Command: !power
comm.power = function(data) {
var dateNow = new Date() / 1000;
var diff = dateNow - statusGlobal.sparkle;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
var message = "";
if (powerStatus == null)
send(data.channelID, util.format(
strings.commands.power.error,
mention(data.userID)
), true);
else if (powerStatus == 0)
send(data.channelID, util.format(
strings.commands.power.messageA,
mention(data.userID),
getTimeString(time),
time.seconds
), true);
else if (powerStatus > 0)
send(data.channelID, util.format(
strings.commands.power.messageB,
mention(data.userID),
getTimeString(time),
time.seconds,
mention(config.options.adminid)
), true);
};
// Command: !eeg
comm.eeg = function(data) {
if (eegValues == undefined) {
send(data.channelID, util.format(
strings.commands.eeg.error,
mention(data.userID)
), true);
}
else {
var dateNow = new Date() / 1000;
var diff = dateNow - eegValues.time;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
var message = util.format(
strings.commands.eeg.messageA,
mention(data.userID),
getTimeString(time),
time.seconds
);
message += util.format(
strings.commands.eeg.messageB,
eegValues.battery,
eegValues.signal,
eegValuesEMA.attention.toFixed(2),
eegValuesEMA.meditation.toFixed(2),
eegValuesEMA.waves[0].toFixed(2),
eegValuesEMA.waves[1].toFixed(2),
eegValuesEMA.waves[2].toFixed(2),
eegValuesEMA.waves[3].toFixed(2),
eegValuesEMA.waves[4].toFixed(2),
eegValuesEMA.waves[5].toFixed(2),
eegValuesEMA.waves[6].toFixed(2),
eegValuesEMA.waves[7].toFixed(2)
);
send(data.channelID, message, true);
}
};
// Command: !printer
comm.printer = function(data) {
send(data.channelID, util.format(
strings.commands.printer.messageA,
mention(data.userID)
), true);
download(printer.baseurl + printer.webcam, config.printer.webimg, function(code) {
var xhr = new XMLHttpRequest();
xhr.open("GET", printer.baseurl + config.printer.urls.job + printer.key, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var message = "";
// Nightmare Rarity
if (response.progress.completion != null && response.state == "Printing") {
var left = response.progress.printTimeLeft;
var time = {};
time.seconds = Math.floor(left % 60);
left = Math.floor(left / 60);
time.minutes = Math.floor(left % 60);
left = Math.floor(left / 60);
time.hours = Math.floor(left % 24);
time.days = Math.floor(left / 24);
message += util.format(
strings.commands.printer.messageD,
response.job.file.name,
response.progress.completion.toFixed(1),
getTimeString(time)
);
}
else if (response.state == "Paused") {
message += util.format(
strings.commands.printer.messageC,
response.job.file.name
);
}
else {
message += strings.commands.printer.messageB;
}
// RariTUSH
if (tushEncL != undefined && tushEncR != undefined && tushWeight != undefined && tushRaw != undefined) {
var age = Math.floor((new Date()) / 1000) - statusGlobal.raritush;
var time = {};
time.seconds = Math.floor(age % 60);
age = Math.floor(age / 60);
time.minutes = Math.floor(age % 60);
age = Math.floor(age / 60);
time.hours = Math.floor(age % 24);
time.days = Math.floor(age / 24);
message += util.format(
strings.commands.printer.messageF,
tushWeight.toFixed(1),
tushEncL,
tushEncR,
getTimeString(time),
time.seconds
);
}
else {
message += strings.commands.printer.messageE;
}
message += strings.commands.printer.messageG;
if (code != 503)
embed(data.channelID, message, config.printer.webimg, "Nightmare Rarity Webcam.jpg", true, true);
else
send(data.channelID, message, true);
}
}
xhr.onerror = function(err) {
send(data.channelID, strings.commands.printer.error, true);
xhr.abort();
}
xhr.ontimeout = function() {
send(data.channelID, strings.commands.printer.error, true);
xhr.abort();
}
xhr.send();
}, function() {
send(data.channelID, strings.commands.printer.error, true);
}, 0);
};
// Command: !devices
comm.devices = function(data) {
var name = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (name == "" || name == config.options.commandsymbol + data.command) {
var message = util.format(
strings.commands.devices.messageA,
mention(data.userID)
);
devices.list.forEach(function(d) {
message += util.format(
strings.commands.devices.messageB,
d.name,
d.description
);
});
send(data.channelID, message, true);
}
else {
var found = false;
devices.list.forEach(function(d) {
if (d.name == name) {
found = true;
embed(data.channelID, util.format(
d.details,
mention(data.userID)
), devices.folder + d.picture, d.name + ".jpg", true, false);
}
});
if (!found)
send(data.channelID, util.format(
strings.commands.devices.error,
mention(data.userID)
), true);
}
};
// Command: !assault
comm.assault = function(data) {
var region = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (region == "" || region == config.options.commandsymbol + data.command)
region = "EU";
if (region == "NA" || region == "EU" || region == "OC") {
var dueTime = getAssault(region);
var dateNow = new Date();
var ending = dueTime - config.wow.assault.interval*1000 + config.wow.assault.duration*1000;
if (ending > dateNow) {
send(data.channelID, util.format(
strings.commands.assault.messageA,
mention(data.userID),
region,
getTimeLeft(dateNow, ending, "CET"),
getTimeLeft(dateNow, dueTime, "CET")
), true);
}
else {
send(data.channelID, util.format(
strings.commands.assault.messageB,
mention(data.userID),
region,
getTimeLeft(dateNow, dueTime, "CET")
), true);
}
}
else {
send(data.channelID, strings.commands.assault.error, true);
}
};
// Command: !blacklist
comm.blacklist = function(data) {
if (blacklist[data.userID] == undefined) {
blacklist[data.userID] = true;
send(data.channelID, util.format(
strings.commands.blacklist.messageA,
mention(data.userID)
), true);
console.log(util.format(
strings.debug.blacklist.add,
data.userID
));
}
else {
delete blacklist[data.userID];
send(data.channelID, util.format(
strings.commands.blacklist.messageB,
mention(data.userID)
), true);
console.log(util.format(
strings.debug.blacklist.remove,
data.userID
));
}
fs.writeFileSync(config.options.blacklistpath, JSON.stringify(blacklist), "utf-8");
};
// Command: !coin
comm.coin = function(data) {
send(data.channelID, strings.commands.coin.message, true);
setTimeout(function() {
if (Math.random() < 0.5)
send(data.channelID, strings.commands.coin.tails, true);
else
send(data.channelID, strings.commands.coin.heads, true);
}, 2000);
};
// Command: !minesweeper
comm.minesweeper = function(data) {
var difficulty = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (difficulty == "" || difficulty == config.options.commandsymbol + data.command || config.minesweeper.difficulties[difficulty] == undefined) {
send(data.channelID, util.format(
strings.commands.minesweeper.error,
mention(data.userID)
), true);
}
else {
// Prepare values.
var i, j, k, m, n, count;
var x = config.minesweeper.difficulties[difficulty].x;
var y = config.minesweeper.difficulties[difficulty].y;
var field = new Array(y);
// Prepare a new empty field.
for (i = 0; i < y; i++) {
field[i] = new Array(x);
}
// Randomly place mines.
for (k = 0; k < config.minesweeper.difficulties[difficulty].m; k++) {
do {
i = Math.floor(Math.random() * y);
j = Math.floor(Math.random() * x);
}
while (field[i][j] == strings.commands.minesweeper.icomine);
field[i][j] = strings.commands.minesweeper.icomine;
}
// Calculate numbers.
for (i = 0; i < y; i++)
for (j = 0; j < x; j++)
if (field[i][j] != strings.commands.minesweeper.icomine) {
count = 0;
for (m = -1; m <= 1; m++)
for (n = -1; n <= 1; n++)
if (i + m >= 0 && j + n >= 0 && i + m < y && j + n < x)
if (field[i + m][j + n] == strings.commands.minesweeper.icomine)
count++;
field[i][j] = strings.commands.minesweeper["ico" + count];
}
// Spoiler relevant tiles.
for (i = 0; i < y; i++)
for (j = 0; j < x; j++) {
count = 0;
for (m = -1; m <= 1; m++)
for (n = -1; n <= 1; n++)
if (i + m >= 0 && j + n >= 0 && i + m < y && j + n < x)
if (field[i + m][j + n] == strings.commands.minesweeper.ico0)
count++;
if (count == 0)
field[i][j] = strings.commands.minesweeper.spoiler + field[i][j] + strings.commands.minesweeper.spoiler;
}
// Construct messages.
var messages = [];
var message = "";
var messageNew = "";
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++)
messageNew += field[i][j];
messageNew += "\n";
if (message.length + messageNew.length > config.options.maxlength) {
messages.push(message);
message = "" + messageNew;
messageNew = "";
}
else {
message += messageNew;
messageNew = "";
}
}
messages.push(message);
// Dump messages.
send(data.channelID, util.format(
strings.commands.minesweeper.message,
mention(data.userID),
x,
y,
config.minesweeper.difficulties[difficulty].m
), true);
messages.forEach(function(m, i) {
setTimeout(function() {
send(data.channelID, m, true);
}, config.minesweeper.delay * (i+1));
});
}
};
// Command: !waifu
comm.waifu = function(data) {
var isPublicChannel = false
channels.list.forEach(function(c) {
if (data.channelID == c.id)
isPublicChannel = true;
});
if (isPublicChannel) {
if (annStatus.enabled) {
var parameters = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if ((parameters == "" || parameters == config.options.commandsymbol + data.command) && data.data.d.attachments[0] == undefined) {
send(data.channelID, util.format(
strings.commands.waifu.errorA,
mention(data.userID)
), true);
}
else {
if (data.data.d.attachments[0] != undefined) {
var image = data.data.d.attachments[0].url;
var parameterParts = parameters.split(" ");
var n = 0;
var s = 1;
var hasParameters = false;
parameterParts.forEach(function(p) {
if (p[0] == "n" || p[0] == "N") {
hasParameters = true;
n = p[1];
}
else if (p[0] == "s" || p[0] == "S") {
hasParameters = true;
s = p[1];
}
});
if (hasParameters) {
if (n == 0 || n == 1 || n == 2 || n == 3) {
if (s == 1 || s == 2 || s == 4 || s == 8) {
if (!(n == 0 && s == 1)) {
send(data.channelID, util.format(
strings.commands.waifu.message,
mention(data.userID),
n,
s
), true);
var url = util.format(
config.ann.waifu.request,
httpkey.key,
image,
data.channelID,
data.userID,
n,
s
);
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200)
setTimeout(function() {
send(data.channelID, util.format(
strings.commands.waifu.errorG,
mention(data.userID)
), true);
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.waifu.errorI,
mention(config.options.adminid)
), true);
}, 2000);
clearTimeout(waifuTimeout);
}
}
xhr.onerror = function(err) {
xhr.abort();
send(data.channelID, util.format(
strings.commands.waifu.errorG,
mention(data.userID)
), true);
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.waifu.errorI,
mention(config.options.adminid)
), true);
}
xhr.ontimeout = function() {
xhr.abort();
send(data.channelID, util.format(
strings.commands.waifu.errorH,
mention(data.userID)
), true);
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.waifu.errorJ,
mention(config.options.adminid)
), true);
}
xhr.send();
waifuTimeout = setTimeout(function() {
xhr.abort();
send(data.channelID, util.format(
strings.commands.waifu.errorH,
mention(data.userID)
), true);
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.waifu.errorJ,
mention(config.options.adminid)
), true);
}, config.ann.waifu.timeout * 1000);
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorK,
mention(data.userID)
), true);
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorE,
mention(data.userID),
s
), true);
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorD,
mention(data.userID),
n
), true);
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorC,
mention(data.userID)
), true);
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorB,
mention(data.userID)
), true);
}
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.paused,
mention(data.userID),
annStatus.message
), true);
}
}
else {
send(data.channelID, util.format(
strings.commands.waifu.errorF,
mention(data.userID)
), true);
}
};
// Command: !spools
comm.spools = function(data) {
if (Object.keys(spool).length > 0) {
var spools = [];
Object.keys(spool).sort().forEach(function(s) {
spools.push(util.format(
strings.commands.spools.messageB,
s,
spool[s]
));
});
sendLarge(data.channelID, spools, util.format(
strings.commands.spools.messageA,
mention(data.userID)
), false);
}
else {
send(data.channelID, util.format(
strings.commands.spools.error,
mention(data.userID)
), true);
}
};
// Command: !seismo
comm.seismo = function(data) {
var dateNow = new Date();
var heliString = ""
heliString += dateNow.getFullYear();
var month = dateNow.getMonth() + 1;
if (month < 10)
heliString += "0" + month;
else
heliString += month;
var day = dateNow.getDate();
if (day < 10)
heliString += "0" + day;
else
heliString += day;
var hours = dateNow.getUTCHours();
if (hours < 12)
heliString += "00";
else
heliString += "12";
if (lastQuake != undefined)
send(data.channelID, util.format(
strings.commands.seismo.messageA,
mention(data.userID),
lastQuake.format("YYYY-MM-DD"),
lastQuake.format("HH:mm:ss (z)"),
Math.sqrt(sampleMedian).toFixed(2),
sampleMedian.toFixed(2)
), true);
else
send(data.channelID, util.format(
strings.commands.seismo.messageB,
mention(data.userID),
Math.sqrt(sampleMedian).toFixed(2),
sampleMedian.toFixed(2)
), true);
download(util.format(
config.seismo.baseurl,
heliString)
, config.seismo.heliimage, function(code) {
if (code != 404)
embed(data.channelID, strings.commands.seismo.messageC, config.seismo.heliimage, "Maud (" + config.seismo.station + ") Helicorder " + (new Date()) + ".gif", true, true);
else
send(data.channelID, strings.commands.seismo.error, true);
}, function() {
send(data.channelID, strings.commands.seismo.error, true);
}, 0);
};
// Command: !pop
comm.pop = function(data) {
var message = util.format(
strings.commands.pop.message,
mention(data.userID)
);
for (var i = 0; i < config.options.popcount; i++) {
message += strings.commands.pop.pop;
}
send(data.channelID, message, true);
};
// Command: !owo
// The OwO functionality was mostly taken from LonelessCodes' TrixieBot (https://github.com/LonelessCodes/trixiebot).
// They have done an amazing job at fine tuning the text transformation so that it is as painful as cringy as possible.
// All credits for the string transformation goes to them.
comm.owo = function(data) {
var text = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (text == "" || text == config.options.commandsymbol + data.command) {
send(data.channelID, util.format(
strings.commands.owo.error,
mention(data.userID)
), true);
}
else {
send(data.channelID, util.format(
strings.commands.owo.message,
mention(data.userID),
owoFaces(owoStutter(owoCasing(owoTransform(text))))
), true);
}
};
// Command: !custom
comm.custom = function(data) {
var interractionCommands = ""
custom.list.forEach(function(c) {
if (interractionCommands != "")
interractionCommands += ", ";
interractionCommands += util.format(
strings.commands.custom.messageC,
config.options.commandsymbol,
c.command
);
});
var nocommand = true;
// Custom interractions
custom.list.forEach(function(c, i) {
// Server filtering
if (bot.channels[data.channelID] != undefined) {
c.servers.forEach(function(s) {
if (bot.channels[data.channelID].guild_id == s && nocommand) {
send(data.channelID, util.format(
strings.commands.custom.messageA,
mention(data.userID),
interractionCommands
), true);
nocommand = false;
}
});
}
// Channel filtering
c.channels.forEach(function(s) {
if (channelIDToName(data.channelID) == s && nocommand) {
send(data.channelID, util.format(
strings.commands.custom.messageB,
mention(data.userID),
interractionCommands
), true);
nocommand = false;
}
});
});
// Channel was not found
if (nocommand) {
send(data.channelID, util.format(
strings.commands.custom.error,
mention(data.userID),
), true);
}
};
// Command: !thori
comm.thori = function(data) {
var found = false;
if (data.userID == config.options.adminid)
found = true;
thori.whitelist.forEach(function(u) {
if (data.userID == u.id)
found = true;
});
if (found) {
var _key = varipass.main.key;
var _id = varipass.main.ids.location;
var payload = {
"key": _key,
"action": "read",
"id": _id
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
console.log(strings.debug.varipass.done);
var values = vpData.value.split("\\n");
var lat = 0.0;
var lng = 0.0;
var alt = 0.0;
values.forEach(function(v) {
var parts = v.split(":");
if (parts[0] == "lat")
lat = parseFloat(parts[1]);
else if (parts[0] == "lng")
lng = parseFloat(parts[1]);
else if (parts[0] == "alt")
alt = parseFloat(parts[1]);
});
var diff = vpData.current - vpData.time;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
var url = util.format(
config.options.mapsurl,
lat,
lng
);
bot.createDMChannel(data.userID, function(){});
getLocationInfo(function(locInfo) {
send(data.userID, util.format(
strings.commands.thori.messageB,
locInfo.town,
locInfo.country,
alt.toFixed(1),
getTimeString(time),
time.seconds,
url
), false);
if (bot.channels[data.channelID] != undefined)
send(data.channelID, util.format(
strings.commands.thori.messageA,
mention(data.userID)
), true);
}, lat, lng);
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorR,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
console.log(strings.debug.varipass.load);
xhr.send(JSON.stringify(payload));
}
else {
send(data.channelID, util.format(
strings.commands.thori.error,
mention(data.userID)
), true);
}
};
// Command: !temp
comm.temp = function(data) {
exec("sudo /home/luna/temp.sh", (error, stdout, stderr) => {
if (error) {
console.log(error);
send(data.channelID, util.format(
strings.commands.temp.errorA,
mention(data.userID)
), true);
return;
}
var lines = stdout.split("\n");
var cpu = parseFloat(lines[0].split("=")[1].split("'")[0]);
var gpu = parseFloat(lines[1].split("=")[1].split("'")[0]);
var raspi = ((cpu + gpu) / 2).toFixed(2);
var payload = {
"key": varipass.main.key,
"id": varipass.main.ids.body,
"action": "read"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
console.log(strings.debug.varipass.done);
var diff = vpData.current - vpData.time;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
send(data.channelID, util.format(
strings.commands.temp.message,
mention(data.userID),
raspi,
cpu,
gpu,
vpData.value.toFixed(2),
getTimeString(time),
time.seconds
), true);
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorR,
err.target.status
));
xhr.abort();
send(data.channelID, util.format(
strings.commands.temp.errorB,
mention(data.userID)
), true);
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
send(data.channelID, util.format(
strings.commands.temp.errorB,
mention(data.userID)
), true);
}
xhr.send(JSON.stringify(payload));
});
};
// Command: !stats
comm.stats = function(data) {
var dateNow = new Date();
var timezone = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (timezone == "" || timezone == config.options.commandsymbol + data.command)
timezone = "UTC";
if (moment.tz.zone(timezone)) {
var diff = (dateNow - startTime) / 1000;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
var momentTime = moment.tz(startTime, timezone);
var canLearn;
if (processWhitelist(data.channelID))
canLearn = strings.commands.stats.learnyes;
else
canLearn = strings.commands.stats.learnno;
send(data.channelID, util.format(
strings.commands.stats.message,
mention(data.userID),
package.version,
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm (z)"),
getTimeString(time),
time.seconds,
channelIDToName(data.channelID),
channelIDToBrain(data.channelID),
messages[channelIDToBrain(data.channelID)].length,
canLearn
), true);
}
else {
send(data.channelID, util.format(
strings.misc.timezone,
mention(data.userID)
), true);
}
};
// Command: !status
comm.status = function(data) {
send(data.channelID, util.format(
strings.commands.status.message,
mention(data.userID),
config.status.home
), true);
};
// Command: !about
comm.about = function(data) {
send(data.channelID, util.format(
strings.commands.about.message,
mention(data.userID),
package.homepage,
config.options.chrysalisgit
), true);
};
// Command: !help
comm.help = function(data) {
var reply = strings.commands.help.messageA;
commands.list.forEach(function(c, i) {
if (i < 8)
if (c.type == "public")
reply += util.format(
strings.commands.help.messageB,
config.options.commandsymbol,
c.command,
c.help
);
});
bot.createDMChannel(data.userID, function(){});
send(data.userID, reply, true);
setTimeout(function() {
var reply = "";
commands.list.forEach(function(c, i) {
if (i >= 8 && i < 16)
if (c.type == "public")
reply += util.format(
strings.commands.help.messageB,
config.options.commandsymbol,
c.command,
c.help
);
});
send(data.userID, reply, true);
}, 1000);
setTimeout(function() {
var reply = "";
commands.list.forEach(function(c, i) {
if (i >= 16)
if (c.type == "public")
reply += util.format(
strings.commands.help.messageB,
config.options.commandsymbol,
c.command,
c.help
);
});
send(data.userID, reply, true);
}, 2000);
setTimeout(function() {
var reply = strings.commands.help.messageC;
commands.list.forEach(function(c) {
if (c.type == "dj")
reply += util.format(
strings.commands.help.messageB,
config.options.commandsymbol,
c.command,
c.help
);
});
var interractionCommands = ""
commands.list.forEach(function(c) {
if (c.type == "interraction") {
if (interractionCommands != "")
interractionCommands += ", ";
interractionCommands += util.format(
strings.commands.help.messageD,
config.options.commandsymbol,
c.command
);
}
});
reply += util.format(
strings.commands.help.messageE,
interractionCommands
);
reply += strings.commands.help.messageF;
send(data.userID, reply, true);
}, 3000);
if (bot.channels[data.channelID] != undefined)
send(data.channelID, util.format(
strings.commands.help.message,
mention(data.userID)
), true);
};
// Interraction commands are called dynamically by type.
// Command: !lyrics
comm.lyrics = function(data) {
var param = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (param == "" || param == config.options.commandsymbol + data.command) {
if (lyrics[np.nowplaying] != undefined) {
sendLarge(data.channelID, lyrics[np.nowplaying].split("\n"), util.format(
strings.commands.lyrics.radio,
mention(data.userID)
), true);
}
else {
send(data.channelID, util.format(
strings.commands.lyrics.errorB,
mention(data.userID)
), true);
}
}
else if (param == "list") {
if (bot.channels[data.channelID] != undefined)
send(data.channelID, util.format(
strings.commands.lyrics.listA,
mention(data.userID)
), true);
bot.createDMChannel(data.userID, function(){});
sendLarge(data.userID, Object.keys(lyrics).sort(), util.format(
strings.commands.lyrics.listB
), false);
}
else if (lyrics[param] != undefined) {
sendLarge(data.channelID, lyrics[param].split("\n"), util.format(
strings.commands.lyrics.message,
mention(data.userID)
), true);
}
else {
send(data.channelID, util.format(
strings.commands.lyrics.errorA,
mention(data.userID)
), true);
}
};
// Command: !art
comm.art = function(data) {
var param = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (param == "" || param == config.options.commandsymbol + data.command) {
if (art[np.nowplaying] != undefined) {
send(data.channelID, util.format(
strings.commands.art.load,
mention(data.userID)
), true);
var parts = art[np.nowplaying].split(".");
var artimg = util.format(
config.options.artimg,
data.channelID,
parts[parts.length-1]
);
download(art[np.nowplaying], artimg, function() {
console.log(strings.debug.download.stop);
embed(data.channelID, strings.commands.art.radio, artimg, np.nowplaying + "." + parts[parts.length-1], true, true);
}, function() {
send(data.channelID, strings.commands.art.errorC, true);
}, 0);
}
else {
send(data.channelID, util.format(
strings.commands.art.errorB,
mention(data.userID)
), true);
}
}
else if (param == "list") {
if (bot.channels[data.channelID] != undefined)
send(data.channelID, util.format(
strings.commands.art.listA,
mention(data.userID)
), true);
bot.createDMChannel(data.userID, function(){});
sendLarge(data.userID, Object.keys(art).sort(), util.format(
strings.commands.art.listB
), false);
}
else if (art[param] != undefined) {
send(data.channelID, util.format(
strings.commands.art.load,
mention(data.userID)
), true);
var parts = art[param].split(".");
var artimg = util.format(
config.options.artimg,
data.channelID,
parts[parts.length-1]
);
download(art[param], artimg, function() {
console.log(strings.debug.download.stop);
embed(data.channelID, strings.commands.art.message, artimg, param + "." + parts[parts.length-1], true, true);
}, function() {
send(data.channelID, strings.commands.art.errorC, true);
}, 0);
}
else {
send(data.channelID, util.format(
strings.commands.art.errorA,
mention(data.userID)
), true);
}
};
// Command: !story
comm.story = function(data) {
var param = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (param == "" || param == config.options.commandsymbol + data.command) {
if (story[np.nowplaying] != undefined) {
send(data.channelID, util.format(
strings.commands.story.radio,
mention(data.userID),
story[np.nowplaying]
), true);
}
else {
send(data.channelID, util.format(
strings.commands.story.errorB,
mention(data.userID)
), true);
}
}
else if (param == "list") {
if (bot.channels[data.channelID] != undefined)
send(data.channelID, util.format(
strings.commands.story.listA,
mention(data.userID)
), true);
bot.createDMChannel(data.userID, function(){});
sendLarge(data.userID, Object.keys(story).sort(), util.format(
strings.commands.story.listB
), false);
}
else if (story[param] != undefined) {
send(data.channelID, util.format(
strings.commands.story.message,
mention(data.userID),
story[param]
), true);
}
else {
send(data.channelID, util.format(
strings.commands.story.errorA,
mention(data.userID)
), true);
}
};
// Command: !npt
comm.npt = function(data) {
if (nptoggles[data.channelID] == undefined) {
nptoggles[data.channelID] = true;
send(data.channelID, util.format(
strings.commands.npt.messageA,
mention(data.userID)
), true);
console.log(util.format(
strings.debug.nptoggles.add,
channelIDToName(data.channelID),
data.channelID
));
setTimeout(function() {
if (np.nowplaying != undefined) {
// Post track name
send(data.channelID, util.format(
strings.announcements.nowplaying,
np.nowplaying
), true);
}
else
send(data.channelID, strings.announcements.nperror, true);
}, 1000);
}
else {
delete nptoggles[data.channelID];
send(data.channelID, util.format(
strings.commands.npt.messageB,
mention(data.userID)
), true);
console.log(util.format(
strings.debug.nptoggles.remove,
channelIDToName(data.channelID),
data.channelID
));
}
fs.writeFileSync(config.options.nptogglespath, JSON.stringify(nptoggles), "utf-8");
};
// Command: !npo
comm.npo = function(data) {
var track = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, util.format(
strings.commands.npo.error,
mention(data.userID)
), false);
}
else {
send(data.channelID, util.format(
strings.commands.npo.message,
mention(data.userID),
track
), false);
isShowingLyrics = false;
isShowingStory = false;
isShowingArt = false;
np.nowplaying = track;
processNowPlayingChange();
}
};
// Command: !stop
comm.stop = function(data) {
if (isLive) {
isLive = false;
var livedata = {}
livedata.isLive = isLive;
fs.writeFileSync(config.options.livepath, JSON.stringify(livedata), "utf-8");
send(data.channelID, strings.commands.stop.message, false);
send(channelNameToID(config.options.channels.announceA), strings.announcements.gotn.afterA, true);
send(channelNameToID(config.options.channels.announceB), strings.announcements.gotn.afterB, true);
setMood("norm", function(result) {
if (!result)
send(channelNameToID(config.options.channels.debug), strings.misc.tradfrierror, false);
});
config.options.channels.nowplaying.forEach(function(n, i) {
if (nptoggles[channelNameToID(n)] != undefined)
delete nptoggles[channelNameToID(n)];
});
fs.writeFileSync(config.options.nptogglespath, JSON.stringify(nptoggles), "utf-8");
}
else {
send(data.channelID, strings.commands.stop.error, false);
}
};
// Command: !send
comm.send = function(data) {
var lines = data.message.split("\n");
var channel = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (channel == "" || channel == config.options.commandsymbol + data.command) {
send(channelNameToID(config.options.channels.debug), strings.commands.send.errorA, false);
}
else {
var text = "";
lines.forEach(function(l, i) {
if (i != 0) {
text += l + "\n";
}
});
if (text != "") {
send(channelNameToID(config.options.channels.debug), strings.commands.send.message, false);
send(channelNameToID(channel), text, true);
}
else {
send(channelNameToID(config.options.channels.debug), strings.commands.send.errorB, false);
}
}
};
// Command: !learn
comm.learn = function(data) {
var lines = data.message.split("\n");
var brain = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (brain == "" || brain == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.learn.errorA, false);
}
else {
if (brains[brain] != null) {
var text = "";
lines.forEach(function(l, i) {
if (i != 0) {
text += l + "\n";
}
});
if (text != "") {
var cleanText = cleanMessage(text);
brains[brain].addMass(cleanText);
messages[brain].push(cleanText);
send(data.channelID, strings.commands.learn.message, false);
}
else {
send(data.channelID, strings.commands.learn.errorC, false);
}
}
else {
send(data.channelID, strings.commands.learn.errorB, false);
}
}
};
// Command: !l
comm.l = function(data) {
if (lyrics[np.nowplaying] != undefined) {
isShowingLyrics = true;
send(data.channelID, strings.commands.l.messageA, false);
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
sendLarge(n, lyrics[np.nowplaying].split("\n"), strings.commands.l.messageB, true);
});
}
else {
send(data.channelID, strings.commands.l.error, false);
}
};
// Command: !purge
comm.purge = function(data) {
if (purgeReady) {
if (data.message == config.options.commandsymbol + data.command + " yes") {
var found = false;
var indexStart = -1;
messages[purgeBrain].forEach(function(l, i) {
if (l == purgeStart) {
found = true;
indexStart = i;
}
});
if (found) {
found = false;
var indexEnd = -1;
messages[purgeBrain].forEach(function(l, i) {
if (l == purgeEnd) {
found = true;
indexEnd = i;
}
});
if (found) {
messages[purgeBrain].splice(indexStart, indexEnd - indexStart + 1);
send(data.channelID, util.format(
strings.commands.purge.messageB,
messages[purgeBrain].length
), false);
purgeReady = false;
rebooting = true;
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npreboot, true);
});
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
process.exit();
}, config.options.reboottime * 1000);
}
else {
send(data.channelID, strings.commands.purge.errorG, false);
}
}
else {
send(data.channelID, strings.commands.purge.errorG, false);
}
}
else if (data.message == config.options.commandsymbol + data.command + " no") {
send(data.channelID, strings.commands.purge.messageC, false);
purgeReady = false;
}
else {
send(data.channelID, strings.commands.purge.errorF, false);
}
}
else {
var lines = data.message.split("\n");
var brain = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (brain == "" || brain == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.purge.errorA, false);
}
else {
if (brains[brain] != null) {
purgeBrain = brain;
purgeStart = lines[1];
purgeEnd = lines[2];
if (purgeStart != undefined && purgeEnd != undefined) {
var found = false;
var indexStart = -1;
messages[brain].forEach(function(l, i) {
if (l == purgeStart) {
found = true;
indexStart = i;
}
});
if (found) {
found = false;
var indexEnd = -1;
messages[brain].forEach(function(l, i) {
if (l == purgeEnd) {
found = true;
indexEnd = i;
}
});
if (found) {
send(data.channelID, util.format(
strings.commands.purge.messageA,
indexEnd - indexStart + 1,
purgeBrain,
messages[purgeBrain].length,
messages[purgeBrain].length - (indexEnd - indexStart + 1)
), false);
purgeReady = true;
}
else {
send(data.channelID, strings.commands.purge.errorE, false);
}
}
else {
send(data.channelID, strings.commands.purge.errorD, false);
}
}
else {
send(data.channelID, strings.commands.purge.errorC, false);
}
}
else {
send(data.channelID, strings.commands.purge.errorB, false);
}
}
}
};
// Command: !nppause
comm.nppause = function(data) {
if (!nppaused) {
send(data.channelID, strings.commands.nppause.messageA, false);
nppaused = true;
}
else {
send(data.channelID, strings.commands.nppause.messageB, false);
nppaused = false;
npradio = {};
}
};
// Command: !npstatus
comm.npstatus = function(data) {
if (Object.keys(nptoggles).length == 0)
send(channelNameToID(config.options.channels.debug), strings.commands.npstatus.error, false);
else {
var message = strings.commands.npstatus.messageA;
Object.keys(nptoggles).forEach(function(n, i) {
var type = "Public";
if (bot.channels[n] == undefined)
type = "Private";
message += util.format(
strings.commands.npstatus.messageB,
channelIDToName(n),
type
);
});
send(channelNameToID(config.options.channels.debug), message, false);
}
};
// Command: !nppurge
comm.nppurge = function(data) {
if (Object.keys(nptoggles).length == 0)
send(data.channelID, strings.commands.nppurge.error, false);
else {
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.commands.nppurge.notify, true);
});
nptoggles = {};
fs.writeFileSync(config.options.nptogglespath, JSON.stringify(nptoggles), "utf-8");
send(data.channelID, strings.commands.nppurge.message, false);
}
};
// Command: !lyricsadd
comm.lyricsadd = function(data) {
var lines = data.message.split("\n");
var track = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.lyricsadd.errorA, false);
}
else {
var lyriclines = "";
lines.forEach(function(l, i) {
if (i != 0) {
lyriclines += l + "\n";
}
});
if (lyriclines != "") {
if (lyrics[track] == undefined)
lyrics[track] = lyriclines;
else
lyrics[track] += lyriclines;
fs.writeFileSync(config.options.lyricspath, JSON.stringify(lyrics), "utf-8");
send(data.channelID, util.format(
strings.commands.lyricsadd.message,
track
), false);
}
else {
send(data.channelID, strings.commands.lyricsadd.errorB, false);
}
}
};
// Command: !lyricsdel
comm.lyricsdel = function(data) {
var track = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.lyricsdel.errorA, false);
}
else {
if (lyrics[track] != undefined) {
delete lyrics[track];
fs.writeFileSync(config.options.lyricspath, JSON.stringify(lyrics), "utf-8");
send(data.channelID, util.format(
strings.commands.lyricsdel.message,
track
), false);
}
else {
send(data.channelID, strings.commands.lyricsdel.errorB, false);
}
}
};
// Command: !artadd
comm.artadd = function(data) {
var lines = data.message.split("\n");
var track = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.artadd.errorA, false);
}
else {
if (lines[1] != undefined) {
var url = lines[1];
if (art[track] == undefined) {
art[track] = url;
fs.writeFileSync(config.options.artpath, JSON.stringify(art), "utf-8");
send(data.channelID, util.format(
strings.commands.artadd.messageA,
track
), false);
}
else {
art[track] = url;
fs.writeFileSync(config.options.artpath, JSON.stringify(art), "utf-8");
send(data.channelID, util.format(
strings.commands.artadd.messageB,
track
), false);
}
}
else {
send(data.channelID, strings.commands.artadd.errorB, false);
}
}
};
// Command: !artdel
comm.artdel = function(data) {
var track = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.artdel.errorA, false);
}
else {
if (art[track] != undefined) {
delete art[track];
fs.writeFileSync(config.options.artpath, JSON.stringify(art), "utf-8");
send(data.channelID, util.format(
strings.commands.artdel.message,
track
), false);
}
else {
send(data.channelID, strings.commands.artdel.errorB, false);
}
}
};
// Command: !storyadd
comm.storyadd = function(data) {
var lines = data.message.split("\n");
var track = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.storyadd.errorA, false);
}
else {
var storylines = "";
lines.forEach(function(l, i) {
if (i != 0) {
storylines += l + "\n";
}
});
if (storylines != "") {
if (story[track] == undefined)
story[track] = storylines;
else
story[track] += storylines;
fs.writeFileSync(config.options.storypath, JSON.stringify(story), "utf-8");
send(data.channelID, util.format(
strings.commands.storyadd.message,
track
), false);
}
else {
send(data.channelID, strings.commands.storyadd.errorB, false);
}
}
};
// Command: !storydel
comm.storydel = function(data) {
var track = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (track == "" || track == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.storydel.errorA, false);
}
else {
if (story[track] != undefined) {
delete story[track];
fs.writeFileSync(config.options.storypath, JSON.stringify(story), "utf-8");
send(data.channelID, util.format(
strings.commands.storydel.message,
track
), false);
}
else {
send(data.channelID, strings.commands.storydel.errorB, false);
}
}
};
// Command: !spooladd
comm.spooladd = function(data) {
var lines = data.message.split("\n");
var name = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if (name == "" || name == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.spooladd.errorA, false);
}
else {
var weight = lines[1];
if (weight != "" && weight != undefined) {
if (spool[name] == undefined)
send(data.channelID, util.format(
strings.commands.spooladd.messageA,
name
), false);
else
send(data.channelID, util.format(
strings.commands.spooladd.messageB,
name
), false);
spool[name] = parseInt(weight);
fs.writeFileSync(config.options.spoolpath, JSON.stringify(spool), "utf-8");
}
else {
send(data.channelID, strings.commands.spooladd.errorB, false);
}
}
};
// Command: !spooldel
comm.spooldel = function(data) {
var name = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (name == "" || name == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.spooldel.errorA, false);
}
else {
if (spool[name] != undefined) {
delete spool[name];
fs.writeFileSync(config.options.spoolpath, JSON.stringify(spool), "utf-8");
send(data.channelID, util.format(
strings.commands.spooldel.message,
name
), false);
}
else {
send(data.channelID, strings.commands.spooldel.errorB, false);
}
}
};
// Command: !h
comm.h = function(data) {
if (Object.keys(hTrack).length == 0)
send(channelNameToID(config.options.channels.debug), strings.commands.h.error, false);
else {
var message = strings.commands.h.messageA;
Object.keys(hTrack).forEach(function(h, i) {
var status = "Cooldown";
if (moment() - hTrack[h] >= config.options.htimeout * 1000)
status = "Expired";
message += util.format(
strings.commands.h.messageB,
channelIDToName(h),
moment.tz(new Date(hTrack[h]), "UTC").format("YYYY-MM-DD, HH:mm:ss"),
status
);
});
send(channelNameToID(config.options.channels.debug), message, false);
}
};
// Command: !ignore
comm.ignore = function(data) {
var user = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (user == "" || user == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.ignore.error, true);
}
else {
if (ignore[user] == undefined) {
ignore[user] = true;
send(data.channelID, strings.commands.ignore.messageA, true);
console.log(util.format(
strings.debug.ignore.add,
user
));
}
else {
delete ignore[user];
send(data.channelID, strings.commands.ignore.messageB, true);
console.log(util.format(
strings.debug.ignore.remove,
user
));
}
fs.writeFileSync(config.options.ignorepath, JSON.stringify(ignore), "utf-8");
}
};
// Command: !mood
comm.mood = function(data) {
var name = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (name == "" || name == config.options.commandsymbol + data.command) {
var message = strings.commands.mood.messageA;
tradfri.moods.forEach(function(m) {
message += util.format(
strings.commands.mood.messageB,
m.name
);
});
send(data.channelID, message, false);
}
else {
var found = false;
tradfri.moods.forEach(function(m) {
if (m.name == name) {
found = true;
setMood(m.name, function(result) {
if (result)
send(data.channelID, util.format(
strings.commands.mood.messageC,
m.name
), false);
else
send(data.channelID, strings.misc.tradfrierror, false);
});
}
});
if (!found)
send(data.channelID, strings.commands.mood.error, false);
}
};
// Command: !bulb
comm.bulb = function(data) {
var lines = data.message.split("\n");
var name = lines[0].replace(config.options.commandsymbol + data.command + " ", "");
if ((name == "" || name == config.options.commandsymbol + data.command) && lines.length <= 1) {
refreshTradfriDevices(function(result) {
if (result) {
var message = strings.commands.bulb.messageA;
tBulbs.forEach(function(d) {
var color = d.color;
if (color == "0")
color = "custom";
message += util.format(
strings.commands.bulb.messageB,
d.name,
color
);
});
send(data.channelID, message, false);
}
else {
send(data.channelID, strings.misc.tradfrierror, false);
}
});
}
else {
var found = false;
var id;
tBulbs.forEach(function(d) {
if (d.name == name) {
found = true;
id = d.id;
}
});
if (found) {
var bulb = {};
if (lines.length == 3) {
bulb.transitionTime = parseInt(lines[2]);
var rgb = color.RGB().hex(lines[1]);
rgb.r = rgb.R;
rgb.g = rgb.G;
rgb.b = rgb.B;
var cie = color.space.rgb['CIE-RGB'];
var XYZ = cie.XYZ(rgb);
var xyY = XYZ.xyY();
bulb.colorX = xyY.x;
bulb.colorY = xyY.y;
bulb.brightness = xyY.Y;
setBulb(bulb, id);
send(data.channelID, strings.commands.bulb.messageC, false);
}
else if (lines.length == 5) {
bulb.colorX = parseFloat(lines[1]);
bulb.colorY = parseFloat(lines[2]);
bulb.brightness = parseFloat(lines[3]);
bulb.transitionTime = parseInt(lines[4]);
setBulb(bulb, id);
send(data.channelID, strings.commands.bulb.messageC, false);
}
else {
send(data.channelID, strings.commands.bulb.errorA + strings.commands.bulb.errorB + strings.commands.bulb.errorC, false);
}
}
else {
send(data.channelID, strings.commands.bulb.errorD, false);
}
}
};
// Command: !toggle
comm.toggle = function(data) {
var name = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (name == "" || name == config.options.commandsymbol + data.command) {
refreshTradfriDevices(function(result) {
if (result) {
var message = strings.commands.toggle.messageA;
tDevices.forEach(function(d) {
var type = strings.commands.toggle.iconPlug;
if (d.color != undefined)
type = strings.commands.toggle.iconBulb;
if (d.on == true)
message += util.format(
strings.commands.toggle.messageBon,
type,
d.name
);
else
message += util.format(
strings.commands.toggle.messageBoff,
type,
d.name
);
});
send(data.channelID, message, false);
}
else {
send(data.channelID, strings.misc.tradfrierror, false);
}
});
}
else {
var found = false;
tDevices.forEach(function(d) {
if (d.name == name) {
found = true;
send(data.channelID, strings.commands.toggle.messageC, false);
hub.toggleDevice(d.id);
}
});
if (!found)
send(data.channelID, strings.commands.toggle.error, false);
}
};
// Command: !schedulestart
comm.schedulestart = function(data) {
var days = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (days == "" || days == config.options.commandsymbol + data.command) {
send(channelNameToID(config.options.channels.home), strings.commands.schedulestart.errorA, false);
}
else {
if (scheduleEntries != undefined && scheduleEntries.length > 0) {
send(channelNameToID(config.options.channels.home), strings.commands.schedulestart.errorB, false);
}
else {
scheduleEntries = [];
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
for (i = 0; i < parseInt(days); i++) {
schedule.schedules.forEach(function(s) {
var partsTime = s.time.split(config.separators.time);
var date = new Date(year, month, day + i, partsTime[0], partsTime[1], 0, 0);
var delta = Math.floor((Math.random() * (2 * 60000 * s.delta) - 60000 * s.delta));
var entry = {};
date.setTime(date.getTime() + delta);
entry.date = date;
entry.delta = delta;
entry.name = s.name;
entry.toggle = s.toggle;
entry.bulbs = s.bulbs;
scheduleEntries.push(entry);
});
}
var message = strings.commands.schedulestart.messageA;
var j = 0;
scheduleEntries.forEach(function(e, i) {
if (i % schedule.schedules.length == 0) {
j++;
message += util.format(
strings.commands.schedulestart.messageB,
j
);
}
var momentTime = moment.tz(e.date, config.options.mytimezone);
message += util.format(
strings.commands.schedulestart.messageC,
e.name,
e.toggle,
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm (z)")
);
var job = new CronJob(e.date, function() {
refreshTradfriDevices(function(result) {
if (result) {
var message = "";
e.bulbs.forEach(function(b) {
tDevices.forEach(function(d) {
if (b == d.name) {
if (e.toggle == "off" && d.on) {
hub.toggleDevice(d.id);
}
else if (e.toggle == "on" && !d.on) {
hub.toggleDevice(d.id);
}
}
});
if (message == "")
message += b;
else
message += ", " + b;
});
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.schedule,
e.toggle,
message
), false);
}
else {
send(channelNameToID(config.options.channels.home), strings.misc.tradfrierror, false);
}
});
}, function () {}, true);
scheduleJobs.push(job);
});
send(channelNameToID(config.options.channels.home), util.format(
message,
days
), false);
}
}
};
// Command: !schedulestart
comm.schedulestop = function(data) {
if (scheduleEntries != undefined && scheduleEntries.length > 0) {
scheduleJobs.forEach(function(j) {
j.stop();
});
scheduleJobs = [];
scheduleEntries = [];
send(channelNameToID(config.options.channels.home), strings.commands.schedulestop.message, false);
}
else {
send(channelNameToID(config.options.channels.home), strings.commands.schedulestop.error, false);
}
};
// Command: !eegstart
comm.eegstart = function(data) {
if (eegRecording) {
send(data.channelID, strings.commands.eegstart.error, true);
}
else {
eegTable = [];
eegTableEMA = [];
eegRecording = true;
send(data.channelID, strings.commands.eegstart.message, true);
}
};
// Command: !eegstop
comm.eegstop = function(data) {
if (!eegRecording) {
send(data.channelID, strings.commands.eegstop.errorA, true);
}
else {
eegRecording = false;
send(data.channelID, strings.commands.eegstop.messageA, true);
saveEEG();
setTimeout(function() {
if (fs.existsSync(config.eeg.basicpath)) {
embed(channelNameToID(config.options.channels.debug), strings.commands.eegstop.messageB, config.eeg.basicpath, util.format(
strings.misc.eeg.basic.upload,
(new Date(eegTable[0].time * 1000)),
(new Date(eegTable[eegTable.length - 1].time * 1000))
), true, true);
setTimeout(function() {
if (fs.existsSync(config.eeg.rawpath))
embed(channelNameToID(config.options.channels.debug), "", config.eeg.rawpath, util.format(
strings.misc.eeg.raw.upload,
(new Date(eegTable[0].time * 1000)),
(new Date(eegTable[eegTable.length - 1].time * 1000))
), true, true);
}, 1000);
setTimeout(function() {
if (fs.existsSync(config.eeg.emapath))
embed(channelNameToID(config.options.channels.debug), "", config.eeg.emapath, util.format(
strings.misc.eeg.ema.upload,
(new Date(eegTable[0].time * 1000)),
(new Date(eegTable[eegTable.length - 1].time * 1000))
), true, true);
}, 2000);
}
else
send(channelNameToID(config.options.channels.debug), strings.commands.eegstop.errorB, true);
}, 1000);
}
};
// Command: !eegset
comm.eegset = function(data) {
var lines = data.message.split("\n");
if (lines.length == 6) {
eegConfig.ema = parseInt(lines[1]);
eegConfig.type = lines[2];
eegConfig.value = lines[3];
eegConfig.max = parseInt(lines[4]);
eegConfig.expire = parseInt(lines[5]);
fs.writeFileSync(config.options.eegpath, JSON.stringify(eegConfig), "utf-8");
eegVaripassEdit();
send(data.channelID, strings.commands.eegset.message, false);
}
else {
send(data.channelID, strings.commands.eegset.errorA + strings.commands.eegset.errorB + strings.commands.eegset.errorC + util.format(
strings.commands.eegset.errorD,
eegConfig.ema,
eegConfig.type,
eegConfig.value,
eegConfig.max,
eegConfig.expire
), false);
}
};
// Command: !leave
comm.leave = function(data) {
var server = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (server == "" || server == config.options.commandsymbol + data.command) {
var message = strings.commands.leave.messageA;
Object.keys(bot.servers).forEach(function(s, i) {
message += util.format(
strings.commands.leave.messageB,
bot.servers[s].name,
s
);
});
send(channelNameToID(config.options.channels.debug), message, false);
}
else {
if (bot.servers[server] != undefined) {
var left = bot.servers[server].name;
bot.leaveServer(server);
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.leave.messageC,
left,
), false);
}
else {
send(channelNameToID(config.options.channels.debug), strings.commands.leave.error, false);
}
}
};
// Command: !camera
comm.camera = function(data) {
var params = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (params == "" || params == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.camera.errorA, true);
}
else {
params = params.split(" ");
if (params[1] != undefined && (params[1] == "on" || params[1] == "off")) {
if (params[0] == "luna") {
if (params[1] == "on") {
exec("sudo /home/luna/mjpg-streamer_norm.sh start");
send(data.channelID, util.format(
strings.commands.camera.messageA,
"my",
), true);
}
else if (params[1] == "off") {
exec("sudo /home/luna/mjpg-streamer_norm.sh stop");
send(data.channelID, util.format(
strings.commands.camera.messageB,
"my",
), true);
}
}
else if (params[0] == "chrysalis") {
send(data.channelID, util.format(
strings.commands.camera.messageC,
params[0]
), false);
var url = util.format(
config.ann.camera.request,
httpkey.key,
params[1]
);
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status != 200)
setTimeout(function() {
send(data.channelID, strings.commands.camera.errorC, true);
}, 2000);
clearTimeout(cameraTimeout);
}
}
xhr.onerror = function(err) {
xhr.abort();
send(data.channelID, strings.commands.camera.errorC, true);
}
xhr.ontimeout = function() {
xhr.abort();
send(data.channelID, strings.commands.camera.errorD, true);
}
xhr.send();
cameraTimeout = setTimeout(function() {
xhr.abort();
send(data.channelID, strings.commands.camera.errorD, true);
}, config.ann.camera.timeout * 1000);
}
else {
send(data.channelID, strings.commands.camera.errorE, true);
}
}
else {
send(data.channelID, strings.commands.camera.errorB, true);
}
}
};
// Command: !stream
comm.stream = function(data) {
var state = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (state == "" || state == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.camera.error, true);
}
else {
if (state == "start") {
exec("sudo -H -u luna bash -c \"/usr/bin/tmux new-session -d -s live '/home/luna/live.sh'\"");
send(data.channelID, strings.commands.stream.messageA, true);
}
else if (state == "stop") {
exec("sudo -H -u luna bash -c \"/usr/bin/tmux kill-session -t live\"");
send(data.channelID, strings.commands.stream.messageB, true);
}
else
send(data.channelID, strings.commands.stream.error, true);
}
};
// Command: !ann
comm.ann = function(data) {
var parts = data.message.split("\n");
var state = parts[0].replace(config.options.commandsymbol + data.command + " ", "");
if (state == "" || state == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.ann.errorA, true);
}
else {
if (state == "on") {
annStatus.enabled = true;
annStatus.message = "";
fs.writeFileSync(config.ann.path, JSON.stringify(annStatus), "utf-8");
send(data.channelID, strings.commands.ann.messageB, true);
}
else if (state == "off") {
if (parts[1] != undefined && parts[1] != "" && parts[1] != " ") {
annStatus.enabled = false;
annStatus.message = parts[1];
fs.writeFileSync(config.ann.path, JSON.stringify(annStatus), "utf-8");
send(data.channelID, strings.commands.ann.messageA, true);
}
else
send(data.channelID, strings.commands.ann.errorB, true);
}
else
send(data.channelID, strings.commands.ann.errorA, true);
}
};
// Command: !chase
comm.chase = function(data) {
var state = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (state == "" || state == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.chase.errorA, true);
}
else {
if (state == "start") {
if (!isChasing) {
isChasing = true;
connectChase(false);
send(data.channelID, strings.commands.chase.messageA, true);
}
else {
send(data.channelID, strings.commands.chase.errorB, true);
}
}
else if (state == "stop") {
if (isChasing) {
isChasing = false;
clearTimeout(chaseReconnect);
chasews.close();
if (chaseRange > blitzor.range) {
chaseRange = blitzor.range;
chaseNew = blitzor.range;
}
send(data.channelID, strings.commands.chase.messageB, true);
}
else {
send(data.channelID, strings.commands.chase.errorC, true);
}
}
else
send(data.channelID, strings.commands.chase.errorA, true);
}
};
// Command: !wake
comm.wake = function(data) {
var device = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (device == "" || device == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.wake.errorA, false);
}
else {
if (device in mac) {
send(data.channelID, util.format(
strings.commands.wake.message,
device
), false);
exec("sudo etherwake " + mac[device]);
}
else {
send(data.channelID, strings.commands.wake.errorB, false);
}
}
};
// Command: !reboot
comm.reboot = function(data) {
rebooting = true;
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npreboot, true);
});
send(data.channelID, strings.commands.reboot.message, false);
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
process.exit();
}, config.options.reboottime * 1000);
};
// Command: !reload
comm.reload = function(data) {
reloadConfig();
send(data.channelID, strings.commands.reload.message, false);
};
// Command: !backup
comm.backup = function(data) {
console.log(strings.debug.backup.start);
send(data.channelID, strings.commands.backup.messageA, false);
var output = fs.createWriteStream(config.backup.output.path);
var _zlib = config.backup.compression;
var archive = archiver("zip", {
"zlib": { "level": _zlib }
});
output.on('close', function() {
console.log(util.format(
strings.debug.backup.done,
archive.pointer()
));
embed(channelNameToID(config.options.channels.debug), strings.commands.backup.messageB, config.backup.output.path, util.format(
config.backup.output.file,
moment.tz(new Date(), "UTC").format("YYYY-MM-DD_HH-mm")
), false, true);
});
archive.on('warning', function(err) {
console.log(util.format(
strings.debug.backup.error,
"Warning: " + err
));
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.backup.error,
"Warning: " + err
), false);
});
archive.on('error', function(err) {
console.log(util.format(
strings.debug.backup.error,
"Error: " + err
));
send(channelNameToID(config.options.channels.debug), util.format(
strings.commands.backup.error,
"Error: " + err
), false);
});
archive.pipe(output);
config.backup.input.entries.forEach(function(e) {
archive.directory(config.backup.input.path + e + "/", e);
});
archive.finalize();
};
// Command: !system
comm.system = function(data) {
var command = data.message.replace(config.options.commandsymbol + data.command + " ", "");
if (command == "" || command == config.options.commandsymbol + data.command) {
send(data.channelID, strings.commands.system.errorA, false);
}
else {
var parts = command.split(" ");
switch (parts[0]) {
case "reboot":
rebooting = true;
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npreboot, true);
});
send(data.channelID, strings.commands.system.mreboot, false);
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
exec("sudo /sbin/reboot");
}, config.options.reboottime * 1000);
break;
default:
send(data.channelID, strings.commands.system.errorB, false);
break;
}
}
};
/*******************************
* COMPONENT AND CONFIG LOADING
*******************************/
/*
* Starts the loading procedure.
*/
function startupProcedure() {
startTime = new Date();
console.log(strings.debug.started);
console.log(util.format(
strings.debug.startedtime,
moment.tz(startTime, "UTC").format("YYYY-MM-DD, HH:mm")
));
loadAnnouncements();
loadPhases();
loadLyrics();
loadArt();
loadStory();
loadSpool();
loadNPToggles();
loadANN();
loadBlacklist();
loadIgnore();
loadCorona();
loadLive();
loadEEG();
loadTimezones();
loadTradfri();
loadAssaults();
loadDailyAvg();
loadBrain();
}
/*
* Loads all announcements from the config.
*/
function loadAnnouncements() {
// Long Message
var partsLong = gotn.announce.long.split(config.separators.time);
var long = (parseInt(partsLong[0]) * 60 + parseInt(partsLong[1])) * 60000;
var dateLong = {};
dateLong.hours = parseInt(partsLong[0]);
dateLong.minutes = parseInt(partsLong[1]);
// Short Message
var partsShort = gotn.announce.short.split(config.separators.time);
var short = (parseInt(partsShort[0]) * 60 + parseInt(partsShort[1])) * 60000;
var dateShort = {};
dateShort.hours = parseInt(partsShort[0]);
dateShort.minutes = parseInt(partsShort[1]);
console.log(strings.debug.announcements.load);
gotn.dates.forEach(function(d) {
var partsDate = d.split(config.separators.date);
var partsTime = gotn.time.split(config.separators.time);
var date = new Date(partsDate[0], parseInt(partsDate[1]) - 1, partsDate[2], partsTime[0], partsTime[1], 0, 0);
if (config.options.debuggotn)
console.log(util.format(
strings.debug.announcements.item,
date
));
// Long air-time announcement.
var jobLong = new CronJob(new Date(date - long), function() {
send(channelNameToID(config.options.channels.announceA), util.format(
strings.announcements.gotn.long,
getTimeString(dateLong)
), true);
}, function () {}, true);
// Short air-time announcement.
var jobShort = new CronJob(new Date(date - short), function() {
send(channelNameToID(config.options.channels.announceA), util.format(
strings.announcements.gotn.shortA,
getTimeString(dateShort)
), true);
send(channelNameToID(config.options.channels.announceB), util.format(
strings.announcements.gotn.shortB,
getTimeString(dateShort)
), true);
config.options.channels.announceC.forEach(function(c, i) {
send(c, util.format(
strings.announcements.gotn.shortC,
getTimeString(dateShort)
), true);
});
}, function () {}, true);
// Now air-time announcement.
var jobNow = new CronJob(new Date(date), function() {
isLive = true;
var livedata = {}
livedata.isLive = isLive;
fs.writeFileSync(config.options.livepath, JSON.stringify(livedata), "utf-8");
send(channelNameToID(config.options.channels.announceA), strings.announcements.gotn.nowA, true);
send(channelNameToID(config.options.channels.announceB), util.format(
strings.announcements.gotn.nowB,
mentionRole(config.options.squadid)
), true);
setMood(gotn.mood, function(result) {
if (!result)
send(channelNameToID(config.options.channels.debug), strings.misc.tradfrierror, false);
});
setTimeout(function() {
send(channelNameToID(config.options.channels.debug), strings.debug.nptoggles.autoon, false);
config.options.channels.nowplaying.forEach(function(n, i) {
nptoggles[channelNameToID(n)] = true;
});
fs.writeFileSync(config.options.nptogglespath, JSON.stringify(nptoggles), "utf-8");
}, config.options.starttime * 1000);
}, function () {}, true);
jobsGOTN.push(jobLong);
jobsGOTN.push(jobShort);
jobsGOTN.push(jobNow);
});
console.log(util.format(
strings.debug.announcements.done,
jobsGOTN.length
));
}
/*
* Loads the lyrics data, or creates new.
*/
function loadLyrics() {
lyrics = {};
if (fs.existsSync(config.options.lyricspath)) {
console.log(strings.debug.lyrics.old);
lyrics = JSON.parse(fs.readFileSync(config.options.lyricspath, "utf8"));
console.log(strings.debug.lyrics.done);
}
else {
fs.writeFileSync(config.options.lyricspath, JSON.stringify(lyrics), "utf-8");
console.log(strings.debug.lyrics.new);
}
}
/*
* Loads the art data, or creates new.
*/
function loadArt() {
art = {};
if (fs.existsSync(config.options.artpath)) {
console.log(strings.debug.art.old);
art = JSON.parse(fs.readFileSync(config.options.artpath, "utf8"));
console.log(strings.debug.art.done);
}
else {
fs.writeFileSync(config.options.artpath, JSON.stringify(art), "utf-8");
console.log(strings.debug.art.new);
}
}
/*
* Loads the story data, or creates new.
*/
function loadStory() {
story = {};
if (fs.existsSync(config.options.storypath)) {
console.log(strings.debug.story.old);
story = JSON.parse(fs.readFileSync(config.options.storypath, "utf8"));
console.log(strings.debug.story.done);
}
else {
fs.writeFileSync(config.options.storypath, JSON.stringify(story), "utf-8");
console.log(strings.debug.story.new);
}
}
/*
* Loads the spool data, or creates new.
*/
function loadSpool() {
spool = {};
if (fs.existsSync(config.options.spoolpath)) {
console.log(strings.debug.spool.old);
spool = JSON.parse(fs.readFileSync(config.options.spoolpath, "utf8"));
console.log(strings.debug.spool.done);
}
else {
fs.writeFileSync(config.options.spoolpath, JSON.stringify(spool), "utf-8");
console.log(strings.debug.spool.new);
}
}
/*
* Loads the Now Playing toggle data, or creates new.
*/
function loadNPToggles() {
nptoggles = {};
if (fs.existsSync(config.options.nptogglespath)) {
console.log(strings.debug.nptoggles.old);
nptoggles = JSON.parse(fs.readFileSync(config.options.nptogglespath, "utf8"));
console.log(strings.debug.nptoggles.done);
}
else {
fs.writeFileSync(config.options.nptogglespath, JSON.stringify(nptoggles), "utf-8");
console.log(strings.debug.nptoggles.new);
}
}
/*
* Loads the ANN toggle data, or creates new.
*/
function loadANN() {
annStatus = {};
if (fs.existsSync(config.ann.path)) {
console.log(strings.debug.ann.old);
annStatus = JSON.parse(fs.readFileSync(config.ann.path, "utf8"));
console.log(strings.debug.ann.done);
}
else {
annStatus.enabled = true;
annStatus.message = "";
fs.writeFileSync(config.ann.path, JSON.stringify(annStatus), "utf-8");
console.log(strings.debug.ann.new);
}
}
/*
* Loads the blacklist data, or creates new.
*/
function loadBlacklist() {
blacklist = {};
if (fs.existsSync(config.options.blacklistpath)) {
console.log(strings.debug.blacklist.old);
blacklist = JSON.parse(fs.readFileSync(config.options.blacklistpath, "utf8"));
console.log(strings.debug.blacklist.done);
}
else {
fs.writeFileSync(config.options.blacklistpath, JSON.stringify(blacklist), "utf-8");
console.log(strings.debug.blacklist.new);
}
}
/*
* Loads the ignore data, or creates new.
*/
function loadIgnore() {
ignore = {};
if (fs.existsSync(config.options.ignorepath)) {
console.log(strings.debug.ignore.old);
ignore = JSON.parse(fs.readFileSync(config.options.ignorepath, "utf8"));
console.log(strings.debug.ignore.done);
}
else {
fs.writeFileSync(config.options.ignorepath, JSON.stringify(ignore), "utf-8");
console.log(strings.debug.ignore.new);
}
}
/*
* Loads the corona data, or creates new and prepares it.
*/
function loadCorona() {
if (config.corona.enabled) {
if (fs.existsSync(config.corona.path)) {
console.log(strings.debug.corona.old);
corona = JSON.parse(fs.readFileSync(config.corona.path, "utf8"));
console.log(strings.debug.corona.done);
}
else {
corona = {};
corona.dateTotal = "";
corona.dateCounty = "";
fs.writeFileSync(config.corona.path, JSON.stringify(corona), "utf-8");
console.log(strings.debug.corona.new);
}
}
}
/*
* Loads the live data, or creates new and prepares it.
*/
function loadLive() {
if (fs.existsSync(config.options.livepath)) {
console.log(strings.debug.live.old);
var livedata = JSON.parse(fs.readFileSync(config.options.livepath, "utf8"));
isLive = livedata.isLive;
console.log(strings.debug.live.done);
}
else {
var livedata = {}
livedata.isLive = isLive;
fs.writeFileSync(config.options.livepath, JSON.stringify(livedata), "utf-8");
console.log(strings.debug.live.new);
}
}
/*
* Loads the EEG configuration, or creates new.
*/
function loadEEG() {
if (fs.existsSync(config.options.eegpath)) {
console.log(strings.debug.eeg.old);
eegConfig = JSON.parse(fs.readFileSync(config.options.eegpath, "utf8"));
console.log(strings.debug.eeg.done);
}
else {
eegConfig = {};
eegConfig.ema = config.eeg.ema;
eegConfig.type = config.eeg.varipass.type;
eegConfig.value = config.eeg.varipass.value;
eegConfig.max = config.eeg.varipass.max;
eegConfig.expire = config.eeg.varipass.expire;
fs.writeFileSync(config.options.eegpath, JSON.stringify(eegConfig), "utf-8");
console.log(strings.debug.eeg.new);
}
eegVaripassEdit();
}
/*
* Loads the timezone data.
*/
function loadTimezones() {
console.log(strings.debug.timezones.load);
var timezoneData = require("./node_modules/moment-timezone/data/packed/latest.json");
moment.tz.load(timezoneData);
console.log(strings.debug.timezones.done);
}
/*
* Initializes the Tradfri client.
*/
function loadTradfri() {
hub = tradfrilib.create({
"coapClientPath": config.options.coappath,
"identity": dtls.identity,
"preSharedKey": dtls.preSharedKey,
"hubIpAddress": dtls.hubIpAddress
});
}
/*
* Starts the REST API server.
*/
function loadServer() {
server = http.createServer(processRequest).listen(config.options.serverport);
}
/*
* Loads the WoW Faction Assault announcements.
*/
function loadAssaults() {
if (config.wow.assault.enabled) {
console.log(strings.debug.assaults.load);
prepareAssaultAnnounce();
console.log(strings.debug.assaults.done);
}
}
/*
* Loads the daily averaging procedures.
*/
function loadDailyAvg() {
console.log(strings.debug.dailyavg.load);
prepareDailyAvg();
console.log(strings.debug.dailyavg.done);
}
/*
* Processes the phase data for announcements.
*/
function loadPhases() {
console.log(strings.debug.phases.load);
phases.forEach(function(p) {
var date = new Date(p.date);
var message;
if (config.options.debugphase)
console.log(util.format(
strings.debug.phases.item,
date,
p.phase
));
if (p.phase == config.moon.fullmoon) {
message = util.format(
strings.announcements.phases.full,
getPhaseString(p.phase, 0)
);
}
else {
message = util.format(
strings.announcements.phases.else,
getPhaseString(p.phase, 0)
);
}
var job = new CronJob(date, function() {
send(channelNameToID(config.options.channels.phases), message, true);
}, function () {}, true);
jobsPhases.push(job);
});
console.log(util.format(
strings.debug.phases.done,
jobsPhases.length
));
}
/*
* Loads the brain data, or creates new.
*/
function loadBrain() {
console.log(strings.debug.brain.start);
channels.list.forEach(function(c) {
if (brains[c.brain] == undefined) {
brains[c.brain] = new jsmegahal(config.brain.markov, config.brain.default, config.brain.maxloop);
}
if (messages[c.brain] == undefined) {
messages[c.brain] = [];
}
});
console.log(util.format(
strings.debug.brain.prog,
brainProg,
Object.keys(brains).length
));
Object.keys(brains).forEach(function(b) {
if (fs.existsSync(config.brain.path + b)) {
if (config.brain.debug)
console.log(util.format(
strings.debug.brain.old,
b
));
openBrain(b);
if (config.brain.debug)
console.log(util.format(
strings.debug.brain.done,
b
));
}
else {
saveBrain(b);
console.log(util.format(
strings.debug.brain.new,
b
));
}
});
loadBrainWait();
}
/*
* Waits until all the brains were loaded.
*/
function loadBrainWait() {
var counter = 0;
Object.keys(brains).forEach(function(b) {
if (brains[b].loaded)
counter++;
});
if (counter > brainProg) {
brainProg = counter;
console.log(util.format(
strings.debug.brain.prog,
brainProg,
Object.keys(brains).length
));
}
if (counter == Object.keys(brains).length) {
console.log(strings.debug.brain.end);
loadBot();
}
else {
setTimeout(function() {
loadBrainWait();
}, 100);
}
}
/*
* Opens brain data from a file.
* @param name Name of the brain.
*/
function openBrain(name) {
var path = config.brain.path + name;
if (fs.existsSync(path)) {
readline.createInterface({
"input": fs.createReadStream(path),
"terminal": false
}).on("line", function(line) {
if (config.brain.cleanbrain) {
var newLine = cleanMessage(line);
if (isMessageNotEmpty(newLine)) {
messages[name].push(newLine);
brains[name].addMass(newLine);
}
}
else {
messages[name].push(line);
brains[name].addMass(line);
}
}).on("close", function() {
brains[name].loaded = true;
});
}
}
/*
* Loops to continuously save brain data.
*/
function loopBrainSave() {
if (!rebooting)
saveAllBrains();
setTimeout(loopBrainSave, config.brain.saveloop * 1000);
}
/*
* Saves all brain data.
*/
function saveAllBrains() {
Object.keys(brains).forEach(function(b) {
saveBrain(b);
});
}
/*
* Saves brain data to a file.
* @param name Name of the brain.
*/
function saveBrain(name) {
if (messages[name].length > config.brain.maxlines)
messages[name].splice(0, messages[name].length - config.brain.maxlines);
var path = config.brain.path + name;
var file = fs.createWriteStream(path + ".new");
file.on("error", function(err) {
console.log(util.format(
strings.debug.brain.error,
err
));
});
messages[name].forEach(function(m) {
file.write(m + "\n", "utf-8");
});
file.end();
brains[name].loaded = true;
setTimeout(function() {
fs.rename(path + ".new", path, function(e) {
});
}, 1000);
}
/*
* Loads the seizure data, or creates new and then cleans it up.
*/
function loadSeizure() {
var seizure = {};
if (fs.existsSync(config.options.seizurepath)) {
console.log(strings.debug.seizure.old);
seizure = JSON.parse(fs.readFileSync(config.options.seizurepath, "utf8"));
console.log(strings.debug.seizure.done);
}
else {
fs.writeFileSync(config.options.seizurepath, JSON.stringify(seizure), "utf-8");
console.log(strings.debug.seizure.new);
}
if (seizure.channel != undefined) {
send(seizure.channel, strings.announcements.seizure.return, false);
}
seizure = {};
fs.writeFileSync(config.options.seizurepath, JSON.stringify(seizure), "utf-8");
}
/********************
* REST API REQUESTS
********************/
/*
* Catches and processes the REST API requests.
* @param req The request object, containing parameters.
* @param res The returned result.
*/
var processRequest = function(req, res) {
if (req.method == "GET") {
var query = url.parse(req.url, true).query;
//console.log("Connection! " + res.socket.remoteAddress + " " + req.url);
if (query.key == httpkey.key) {
switch (query.action) {
// Action requests
case "power": processReqPower(query); break;
case "motion": processReqMotion(query); break;
case "boot": processReqBoot(query); break;
case "eeg": processReqEEG(query); break;
case "celly": processReqCelly(query); break;
case "toggle": processReqToggle(query); break;
case "state": processReqState(query); break;
case "mood": processReqMood(query); break;
case "camera": processReqCamera(query); break;
case "stream": processReqStream(query); break;
case "reboot": processReqReboot(query); break;
case "reload": processReqReload(query); break;
case "waifu": processReqWaifu(query); break;
case "tush": processReqTush(query); break;
// Data requests
case "ping": processResPing(res); return; break;
case "spools": processResSpools(res); return; break;
case "l": processResL(res); return; break;
case "lq": processResLQ(res); return; break;
// JSON Rquests
case "np": processJsonNp(res); return; break;
case "lyrics": processJsonLyrics(res); return; break;
case "storyart": processJsonStoryArt(res); return; break;
}
}
}
res.writeHead(200, [
["Content-Type", "text/plain"],
["Content-Length", 0]
]);
res.write("");
res.end();
};
/*
* Processes the "power" request.
* @param data Request parameters.
*/
function processReqPower(query) {
statusGlobal.sparkle = Math.floor((new Date()) / 1000);
if (query.power == "on") {
if (powerStatus != null && powerStatus != 0)
send(channelNameToID(config.options.channels.home), strings.announcements.power.on, false);
powerStatus = 0;
}
else if (query.power == "off") {
if (powerStatus == null || powerStatus == 0) {
send(channelNameToID(config.options.channels.home), strings.announcements.power.off1, false);
powerStatus = 1;
}
else if (powerStatus == 1) {
send(channelNameToID(config.options.channels.home), strings.announcements.power.off2, false);
powerStatus = 2;
}
else if (powerStatus == 2) {
send(channelNameToID(config.options.channels.home), strings.announcements.power.off3, false);
powerStatus = 3;
var xhr = new XMLHttpRequest();
xhr.open("GET", printer.baseurl + config.printer.urls.job + printer.key, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
if (response.progress.completion != null && response.state == "Printing") {
tushPaused = true;
console.log(strings.debug.printer.pause);
pausePrint(config.printer.pauseretry);
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.power.print,
mention(config.options.adminid)
), false);
}
}
}
xhr.onerror = function(err) {
send(data.channelID, strings.commands.printer.error, true);
xhr.abort();
}
xhr.ontimeout = function() {
send(data.channelID, strings.commands.printer.error, true);
xhr.abort();
}
xhr.send();
}
}
}
/*
* Processes the "motion" request.
* @param data Request parameters.
*/
function processReqMotion(query) {
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.motion,
query.camera
), false);
download(query.snapshot + "&_signature=" + query._signature, config.options.motionimg, function() {
console.log(strings.debug.download.stop);
embed(channelNameToID(config.options.channels.home), "", config.options.motionimg, query.camera + " " + (new Date()) + ".jpg", false, false);
}, function() {
console.log(strings.debug.download.cancel);
}, 0, false);
}
/*
* Processes the "boot" request.
* @param data Request parameters.
*/
function processReqBoot(query) {
if (query.device != undefined) {
var now = new Date();
var momentTime = moment.tz(now, "UTC");
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.boot,
query.device,
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm:ss (z)")
), false);
}
}
/*
* Processes the "eeg" request.
* @param data Request parameters.
*/
function processReqEEG(query) {
statusGlobal.lulu = Math.floor((new Date()) / 1000);
var w;
var alpha = parseFloat(1.0 / eegConfig.ema);
eegValues = {};
eegValues.waves = [];
eegValuesEMA = {};
eegValuesEMA.waves = [];
// Basic Data
eegValues.time = Math.floor((new Date()) / 1000);
eegValuesEMA.time = eegValues.time;
eegValues.battery = query.battery;
eegValues.signal = query.signal;
// Raw Attention/Meditation
eegValues.attention = query.attention;
eegValues.meditation = query.meditation;
// Raw Waves
for (w = 0; w <= 7; w++)
eegValues.waves.push(query["wave" + w]);
// Raw Averages
eegValues.sumlow = 0;
for (w = 0; w <= 3; w++)
eegValues.sumlow += parseFloat(eegValues.waves[w]);
eegValues.sumhigh = 0;
for (w = 4; w <= 7; w++)
eegValues.sumhigh += parseFloat(eegValues.waves[w]);
if (eegInitial) {
// EMA Attention/Meditation
eegValuesEMA.attention = eegValues.attention;
eegValuesEMA.meditation = eegValues.meditation;
// EMA Waves
for (w = 0; w <= 7; w++)
eegValuesEMA.waves.push(eegValues.waves[w]);
eegInitial = false;
}
else {
// EMA Attention/Meditation
eegValuesEMA.attention = alpha * eegValues.attention + (1.0 - alpha) * eegValuesEMAPrev.attention;
eegValuesEMA.meditation = alpha * eegValues.meditation + (1.0 - alpha) * eegValuesEMAPrev.meditation;
eegValuesEMA.waves = [];
for (w = 0; w <= 7; w++)
eegValuesEMA.waves.push(alpha * eegValues.waves[w] + (1.0 - alpha) * eegValuesEMAPrev.waves[w]);
}
// EMA Averages
eegValuesEMA.sumlow = 0;
for (w = 0; w <= 3; w++)
eegValuesEMA.sumlow += parseFloat(eegValuesEMA.waves[w]);
eegValuesEMA.sumhigh = 0;
for (w = 4; w <= 7; w++)
eegValuesEMA.sumhigh += parseFloat(eegValuesEMA.waves[w]);
// Copy data to previous.
eegValuesEMAPrev = JSON.parse(JSON.stringify(eegValuesEMA));
// Push data to array if recording.
if (eegRecording) {
eegTable.push(eegValues);
eegTableEMA.push(eegValuesEMA);
}
eegVaripassWrite();
}
/*
* Processes the "celly" request.
* @param data Request parameters.
*/
function processReqCelly(query) {
delete query.key;
delete query.action;
var message = strings.misc.celly.messageA;
Object.keys(query).forEach(function(q) {
message += util.format(
strings.misc.celly.messageB,
q,
query[q]
);
});
message += strings.misc.celly.messageC;
send(channelNameToID(config.options.channels.debug), message, false);
}
/*
* Processes the "toggle" request.
* @param data Request parameters.
*/
function processReqToggle(query) {
if (query.bulbs != undefined) {
refreshTradfriDevices(function(result) {
if (result) {
var found = false;
query.bulbs.split(",").forEach(function(b) {
tDevices.forEach(function(d) {
if (d.name == b) {
hub.toggleDevice(d.id);
found = true;
}
});
});
if (found)
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + util.format(
strings.voice.toggle.message,
query.bulbs
), false);
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.toggle.error, false);
}
else {
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.misc.tradfrierror, false);
}
});
}
}
/*
* Processes the "state" request.
* @param data Request parameters.
*/
function processReqState(query) {
if (query.bulbs != undefined && query.state != undefined) {
refreshTradfriDevices(function(result) {
if (result) {
var found = false;
query.bulbs.split(",").forEach(function(b) {
tDevices.forEach(function(d) {
if (d.name == b) {
if (d.on == true && query.state == "off") {
hub.toggleDevice(d.id);
found = true;
}
else if (d.on == false && query.state == "on") {
hub.toggleDevice(d.id);
found = true;
}
}
});
});
if (found)
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + util.format(
strings.voice.state.message,
query.state,
query.bulbs
), false);
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.state.error, false);
}
else {
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.misc.tradfrierror, false);
}
});
}
}
/*
* Processes the "mood" request.
* @param data Request parameters.
*/
function processReqMood(query) {
if (query.mood != undefined) {
var found = false;
var result = false;
tradfri.moods.forEach(function(m) {
if (m.name == query.mood) {
setMood(m.name, function(result) {
if (result)
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + util.format(
strings.commands.mood.messageC,
query.mood
), false);
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.misc.tradfrierror, false);
});
found = true;
}
});
if (!found) {
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.mood.error, false);
}
}
}
/*
* Processes the "camera" request.
* @param data Request parameters.
*/
function processReqCamera(query) {
if (query.state != undefined) {
if (query.state == "on") {
if (query.camera == httpkey.camera) {
exec("sudo /home/luna/mjpg-streamer_norm.sh start");
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.camera.messageA, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.camera.error, false);
}
else if (query.state == "off") {
if (query.camera == httpkey.camera) {
exec("sudo /home/luna/mjpg-streamer_norm.sh stop");
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.camera.messageB, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.camera.error, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.camera.error, false);
}
else if (query.device != undefined && query.response != undefined) {
if (query.response == "on" || query.response == "off") {
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.camera,
query.device,
query.response
), true);
}
}
}
/*
* Processes the "strean" request.
* @param data Request parameters.
*/
function processReqStream(query) {
if (query.state != undefined) {
if (query.state == "start") {
if (query.stream == httpkey.stream) {
exec("sudo -H -u luna bash -c \"/usr/bin/tmux new-session -d -s live '/home/luna/live.sh'\"");
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.stream.messageA, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.stream.error, false);
}
else if (query.state == "stop") {
if (query.stream == httpkey.stream) {
exec("sudo -H -u luna bash -c \"/usr/bin/tmux kill-session -t live\"");
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.stream.messageB, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.stream.error, false);
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.stream.error, false);
}
}
/*
* Processes the "reboot" request.
* @param data Request parameters.
*/
function processReqReboot(query) {
if (query.reboot != undefined) {
if (query.reboot == httpkey.reboot) {
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npreboot, true);
});
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.reboot.message, false);
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
process.exit();
}, config.options.reboottime * 1000);
rebooting = true;
}
else
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.voice.reboot.error, false);
}
}
/*
* Processes the "reload" request.
* @param data Request parameters.
*/
function processReqReload(query) {
reloadConfig();
send(channelNameToID(config.options.channels.debug), strings.misc.voicetag + strings.commands.reload.message, false);
}
/*
* Processes the "waifu" request.
* @param data Request parameters.
*/
function processReqWaifu(query) {
if (query.url != undefined && query.channelid != undefined && query.userid != undefined && query.time != undefined && query.size != undefined) {
send(query.channelid, util.format(
strings.misc.ann.waifu.message,
mention(query.userid),
query.time,
query.size,
query.url
), true);
}
else if (query.error != undefined && query.channelid != undefined && query.userid != undefined) {
send(query.channelid, util.format(
strings.misc.ann.waifu.errorA,
mention(query.userid)
), true);
send(channelNameToID(config.options.channels.debug), util.format(
strings.misc.ann.waifu.errorB,
mention(config.options.adminid)
), true);
}
else if (query.toobig != undefined && query.channelid != undefined && query.userid != undefined) {
send(query.channelid, util.format(
strings.misc.ann.waifu.toobig,
mention(query.userid)
), true);
}
else if (query.queue != undefined && query.channelid != undefined && query.userid != undefined) {
send(query.channelid, util.format(
strings.misc.ann.waifu.queue,
mention(query.userid),
query.queue
), true);
}
}
/*
* Processes the "tush" request.
* @param data Request parameters.
*/
function processReqTush(query) {
if (query.tush != undefined) {
if (query.tush == httpkey.tush) {
if (query.encL != undefined && query.encR != undefined && query.weight != undefined && query.raw != undefined) {
statusGlobal.raritush = Math.floor((new Date()) / 1000);
var tempEncL = parseInt(query.encL);
var tempEncR = parseInt(query.encR);
var tempWeight = parseFloat(query.weight);
var tempRaw = parseFloat(query.raw);
var xhr = new XMLHttpRequest();
xhr.open("GET", printer.baseurl + config.printer.urls.printer + printer.key, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
if (response.state.text == "Printing" &&
response.temperature.tool0.target > config.printer.constraints.tempmin &&
response.temperature.tool0.actual > response.temperature.tool0.target - config.printer.constraints.tempdiff) {
if (tushStep >= config.printer.constraints.rampup) {
// Spool Drop - Warn
if (tushRaw > config.printer.detections.spooldrop.threshold_weight) {
if (tempRaw <= config.printer.detections.spooldrop.threshold_weight) {
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spooldrop.warn,
mention(config.options.adminid),
tempRaw,
config.printer.interval
), true);
setMood("warn", function(result) {
if (!result)
send(channelNameToID(config.options.channels.printer), strings.misc.tradfrierror, false);
});
}
// Spool Stop - Warn
else if (tushEncL + tushEncR > config.printer.detections.spoolstop.threshold_count) {
if (tempEncL + tempEncR <= config.printer.detections.spoolstop.threshold_count) {
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spoolstop.warn,
mention(config.options.adminid),
tempEncL + tempEncR,
config.printer.interval
), true);
setMood("warn", function(result) {
if (!result)
send(channelNameToID(config.options.channels.printer), strings.misc.tradfrierror, false);
});
}
}
else if (tushEncL + tushEncR <= config.printer.detections.spoolstop.threshold_count) {
// Spool Stop - Stop
if (tempEncL + tempEncR <= config.printer.detections.spoolstop.threshold_count) {
if (!tushPaused) {
// PERFORM PAUSE
tushPaused = true;
console.log(strings.debug.printer.pause);
pausePrint(config.printer.pauseretry);
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spoolstop.stop,
mention(config.options.adminid)
), true);
}
}
// Spool Stop - Okay
else {
tushPaused = false;
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spoolstop.okay,
mention(config.options.adminid),
tempEncL + tempEncR
), true);
setMood("norm", function(result) {
if (!result)
send(channelNameToID(config.options.channels.printer), strings.misc.tradfrierror, false);
});
}
}
}
else if (tushRaw <= config.printer.detections.spooldrop.threshold_weight) {
// Spool Drop - Stop
if (tempRaw <= config.printer.detections.spooldrop.threshold_weight) {
if (!tushPaused) {
// PERFORM PAUSE
tushPaused = true;
console.log(strings.debug.printer.pause);
pausePrint(config.printer.pauseretry);
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spooldrop.stop,
mention(config.options.adminid)
), true);
}
}
// Spool Drop - Okay
else {
tushPaused = false;
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.spooldrop.okay,
mention(config.options.adminid),
tempRaw
), true);
setMood("norm", function(result) {
if (!result)
send(channelNameToID(config.options.channels.printer), strings.misc.tradfrierror, false);
});
}
}
}
else {
if (tushStep == 0) {
tushStart = Math.floor((new Date()) / 1000);
send(channelNameToID(config.options.channels.printer), strings.announcements.tush.start, false);
}
tushStep++;
if (tushStep >= config.printer.constraints.rampup)
console.log(util.format(
strings.debug.printer.rampB,
tushStep
));
else
console.log(util.format(
strings.debug.printer.rampA,
tushStep
));
}
}
else {
if (!tushPaused) {
if (tushStep > 0)
finishPrint();
tushStep = 0;
}
}
}
if (xhr.readyState == 4) {
if (xhr.status != 200 && !tushPaused) {
if (tushStep > 0)
finishPrint();
tushStep = 0;
}
if (!tushPaused) {
tushEncL = tempEncL;
tushEncR = tempEncR;
tushWeight = tempWeight;
tushRaw = tempRaw;
}
if (tushEncL != undefined && tushEncR != undefined) {
writeVariPass(varipass.main.key, varipass.main.ids.enc, tushEncL + tushEncR);
}
if (tushWeight != undefined) {
writeVariPass(varipass.main.key, varipass.main.ids.weight, tushWeight);
}
}
}
xhr.onerror = function(err) {
xhr.abort();
}
xhr.ontimeout = function() {
xhr.abort();
}
xhr.send();
}
}
}
}
/*
* Responds to the "ping" request.
* @param res The response object.
*/
function processResPing(res) {
res.writeHead(200, [
["Content-Type", "text/plain"],
["Content-Length", 4]
]);
res.write("pong");
res.end();
}
/*
* Responds to the "spools" request.
* @param res The response object.
*/
function processResSpools(res) {
var spools = Object.keys(spool).length.toString();
Object.keys(spool).sort().forEach(function(s) {
spools += "|" + s + "|" + spool[s];
});
res.writeHead(200, [
["Content-Type", "text/plain"],
["Content-Length", spools.length]
]);
res.write(spools);
res.end();
}
/*
* Responds to the "l" request.
* @param res The response object.
*/
function processResL(res) {
statusGlobal.exclaml = Math.floor((new Date()) / 1000);
var response = "no_lyrics";
if (lyrics[np.nowplaying] != undefined) {
response = "success";
isShowingLyrics = true;
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
sendLarge(n, lyrics[np.nowplaying].split("\n"), strings.commands.l.messageB, true);
});
}
res.writeHead(200, [
["Content-Type", "text/plain"],
["Content-Length", response.length]
]);
res.write(response);
res.end();
}
/*
* Responds to the "lq" request.
* @param res The response object.
*/
function processResLQ(res) {
statusGlobal.exclaml = Math.floor((new Date()) / 1000);
var response = "false"
if (lyrics[np.nowplaying] != undefined)
response = "true";
response += "|" + np.nowplaying;
res.writeHead(200, [
["Content-Type", "text/plain charset=UTF-8"],
["Content-Length", Buffer.byteLength(response, "utf8")]
]);
res.write(response);
res.end();
}
/*
* Responds to the "np" request.
* @param res The response object.
*/
function processJsonNp(res) {
statusGlobal.overlay_np = Math.floor((new Date()) / 1000);
var json = JSON.stringify(npover);
res.writeHead(200, [
["Access-Control-Allow-Origin", "*"],
["Content-Type", "application/json; charset=UTF-8"],
["Content-Length", Buffer.byteLength(json, "utf8")]
]);
res.write(json);
res.end();
}
/*
* Responds to the "lyrics" request.
* @param res The response object.
*/
function processJsonLyrics(res) {
statusGlobal.overlay_lyrics = Math.floor((new Date()) / 1000);
var data = {}
if(isShowingLyrics) {
if (lyrics[np.nowplaying] != undefined)
data.lyrics = lyrics[np.nowplaying].split("\n");
else
data.lyrics = [];
}
else {
data.lyrics = [];
}
var json = JSON.stringify(data);
res.writeHead(200, [
["Access-Control-Allow-Origin", "*"],
["Content-Type", "application/json; charset=UTF-8"],
["Content-Length", Buffer.byteLength(json, "utf8")]
]);
res.write(json);
res.end();
}
/*
* Responds to the "storyart" request.
* @param res The response object.
*/
function processJsonStoryArt(res) {
statusGlobal.overlay_storyart = Math.floor((new Date()) / 1000);
var data = {}
if(isShowingStory) {
if (story[np.nowplaying] != undefined)
data.story = story[np.nowplaying].split("\n");
else
data.story = [];
}
else {
data.story = [];
}
if(isShowingArt) {
if (art[np.nowplaying] != undefined)
data.art = art[np.nowplaying];
else
data.art = "";
}
else {
data.art = "";
}
var json = JSON.stringify(data);
res.writeHead(200, [
["Access-Control-Allow-Origin", "*"],
["Content-Type", "application/json; charset=UTF-8"],
["Content-Length", Buffer.byteLength(json, "utf8")]
]);
res.write(json);
res.end();
}
/************************
* DISCORD FUNCTIONALITY
************************/
/*
* Loads the Discord bot.
*/
function loadBot() {
bot = new Discord.Client({
"token": token.value,
"autorun": true
});
bot.on("ready", function() {
reconnectTime = 0;
bot.setPresence({
"game": {
"name": config.options.game
}
});
console.log(util.format(
strings.debug.join,
bot.username,
bot.id
));
if (!started) {
started = true;
send(channelNameToID(config.options.channels.debug), util.format(
strings.misc.load,
package.version
), false);
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npback, true);
});
loadServer();
loadSeizure();
connectBlitzortung(false);
startSeizmoServer();
loopLightning();
loopNowPlaying();
//loopCorona();
loopStatusPull();
loopStatusPush();
setTimeout(loopBrainSave, config.brain.saveloop * 1000);
prepareReactroleMessages();
}
});
bot.on("guildMemberAdd", function(user) {
if (user.guild_id == config.options.serverid) {
console.log(util.format(
strings.debug.welcome,
user.username
));
send(channelNameToID(config.options.channels.welcome), util.format(
strings.misc.welcome,
mention(user.id)
), true);
bot.addToRole( {
"serverID": user.guild_id,
"userID": user.id,
"roleID": config.options.roleid
}, function(err, response) {
if (err)
console.error(util.format(
strings.debug.welcomefail,
err
));
});
}
});
bot.on("message", function(user, userID, channelID, message, data) {
config.autoreact.channels.forEach(function(c, i) {
if (c == channelID)
react(channelID, data.d.id, config.autoreact.reacts[i]);
});
if (message[0] == config.options.commandsymbol) {
var nocommand = true;
var command = message.split("\n")[0];
command = command.split(" ")[0];
var lower = command.toLowerCase();
var packed = {};
packed.user = user;
packed.userID = userID;
packed.channelID = channelID;
packed.message = message;
packed.data = data;
packed.command = command.replace(config.options.commandsymbol, "");
commands.list.forEach(function(c) {
if (lower == config.options.commandsymbol + c.command && nocommand) {
// Private commands
if (c.type == "private") {
if (userID == config.options.adminid) {
comm[c.command](packed);
nocommand = false;
}
else {
send(channelID, util.format(
strings.misc.noadmin,
mention(userID)
), true);
nocommand = false;
}
}
// DJ only commands
else if (c.type == "dj") {
var roleFound = false;
if (userID == config.options.adminid)
roleFound = true;
if (!roleFound && data.d != undefined) {
if (data.d.member != undefined) {
if (data.d.member.roles != undefined) {
data.d.member.roles.forEach(function (r1, i) {
config.options.djroles.forEach(function (r2, j) {
if (r1 == r2) {
roleFound = true;
}
});
});
}
}
else {
if (lower == config.options.commandsymbol + "npt")
roleFound = true;
}
}
if (roleFound) {
comm[c.command](packed);
nocommand = false;
}
else {
send(channelID, util.format(
strings.misc.noperm,
mention(userID)
), true);
}
}
// Interractions
else if (c.type == "interraction") {
doInterraction(packed);
nocommand = false;
}
// Other commands
else {
comm[c.command](packed);
nocommand = false;
}
}
});
// Custom interractions
custom.list.forEach(function(c, i) {
if (lower == config.options.commandsymbol + c.command && nocommand) {
// Server filtering
if (bot.channels[channelID] != undefined) {
c.servers.forEach(function(s) {
if (bot.channels[channelID].guild_id == s && nocommand) {
doInterractionCustom(packed, i);
nocommand = false;
}
});
}
// Channel filtering
c.channels.forEach(function(s) {
if (channelIDToName(channelID) == s && nocommand) {
doInterractionCustom(packed, i);
nocommand = false;
}
});
}
});
}
else {
if (message == "h")
h(channelID);
// Clean up the message.
var newMessage = cleanMessage(message);
// When the bot is mentioned.
if (isMentioned(bot.id, data)) {
console.log(util.format(
strings.debug.chatting,
user,
channelIDToName(channelID),
message
));
if (config.seizure.enabled) {
process.on('uncaughtException', function (e) {
seizureReboot(channelID, userID, message);
});
tripwire.resetTripwire(config.seizure.timeout * 1000);
}
if (config.seizure.debug && newMessage == config.seizure.force)
while (true) {}
var genMessage = completeRoleplay(brains[channelIDToBrain(channelID)].getReplyFromSentence(newMessage));
send(channelID, mention(userID) + " " + genMessage, true);
if (config.seizure.enabled) {
tripwire.clearTripwire();
process.removeAllListeners();
}
}
// All other messages.
if (data.d.author.id != bot.id && processWhitelist(channelID) && processBlacklist(userID) && processIgnore(userID) && isMessageNotEmpty(newMessage)) {
if (config.seizure.enabled) {
process.on('uncaughtException', function (e) {
seizureReboot(channelID, userID, message);
});
tripwire.resetTripwire(config.seizure.timeout * 1000);
}
if (config.seizure.debug && newMessage == config.seizure.force)
while (true) {}
brains[channelIDToBrain(channelID)].addMass(newMessage);
messages[channelIDToBrain(channelID)].push(newMessage);
if (config.seizure.enabled) {
tripwire.clearTripwire();
process.removeAllListeners();
}
}
}
});
bot.on("messageReactionAdd", function(data) {
if (data.d.user_id != bot.id) {
reactrole.mapping.forEach(function(m) {
if (channelNameToID(m.channel) == data.d.channel_id && m.message == data.d.message_id) {
Object.keys(m.map).forEach(function (r) {
var clean = r.substring(2, r.length - 1);
var parts = clean.split(":");
if (parts[1] === "")
parts[1] = null;
if (data.d.emoji.name === parts[0] && data.d.emoji.id === parts[1]) {
bot.addToRole( {
"serverID": data.d.guild_id,
"userID": data.d.user_id,
"roleID": m.map[r]
}, function(err, response) {
bot.createDMChannel(data.d.user_id, function(){});
if (err) {
console.error(util.format(
strings.debug.reactrolefail,
m.map[r],
data.d.guild_id
));
send(data.d.user_id, util.format(
strings.misc.reactrole.error,
mention(data.d.user_id)
), false);
}
else {
send(data.d.user_id, util.format(
strings.misc.reactrole.add,
mention(data.d.user_id)
), false);
}
});
}
});
}
});
}
});
bot.on("messageReactionRemove", function(data) {
if (data.d.user_id != bot.id) {
reactrole.mapping.forEach(function(m) {
if (channelNameToID(m.channel) == data.d.channel_id && m.message == data.d.message_id) {
Object.keys(m.map).forEach(function (r) {
var clean = r.substring(2, r.length - 1);
var parts = clean.split(":");
if (parts[1] === "")
parts[1] = null;
if (data.d.emoji.name === parts[0] && data.d.emoji.id === parts[1]) {
bot.removeFromRole( {
"serverID": data.d.guild_id,
"userID": data.d.user_id,
"roleID": m.map[r]
}, function(err, response) {
bot.createDMChannel(data.d.user_id, function(){});
if (err) {
console.error(util.format(
strings.debug.reactrolefail,
m.map[r],
data.d.guild_id
));
send(data.d.user_id, util.format(
strings.misc.reactrole.error,
mention(data.d.user_id)
), false);
}
else {
send(data.d.user_id, util.format(
strings.misc.reactrole.remove,
mention(data.d.user_id)
), false);
}
});
}
});
}
});
}
});
bot.on("disconnect", function(erMsg, code) {
console.error(strings.debug.disconnected);
if (reconnectTime < config.options.reconnectmax) {
reconnectTime += config.options.reconnecttime;
// Wait for reconnect to prevent spamming.
setTimeout(function() {
bot.connect();
}, config.options.reconnecttime * 1000);
}
else {
rebooting = true;
console.log(util.format(
strings.debug.fullreconnect,
reconnectTime
));
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
process.exit();
}, config.options.reboottime * 1000);
}
});
}
/*
* Sends a message to a channel on Discord.
* @param id ID of the channel to send to.
* @param message String message to send.
* @param typing Whether the typing delay should be added.
*/
function send(id, message, typing, retry=0) {
if (retry < config.options.sendretry) {
if (message.length <= config.options.maxlength) {
var channel = channelIDToName(id);
var msg = {
"to": id,
"message": message
};
if (typing) {
bot.simulateTyping(id);
setTimeout(function() {
console.log(util.format(
strings.debug.message,
channel,
message
));
bot.sendMessage(msg, function(err) {
if (err != undefined) {
retry++;
console.log(strings.debug.failedm);
setTimeout(function() {
send(id, message, typing, retry);
}, 1000);
}
});
}, config.options.typetime * 1000);
}
else {
console.log(util.format(
strings.debug.message,
channel,
message
));
bot.sendMessage(msg, function(err) {
if (err != undefined) {
retry++;
console.log(strings.debug.failedm);
setTimeout(function() {
send(id, message, typing, retry);
}, 1000);
}
});
}
}
else {
send(id, strings.misc.toolong, typing);
}
}
else {
console.log(strings.debug.failgiveup);
}
};
/*
* Sends a large message to some chat using multiple messages. Used for lyrics and lists.
* @param id Data of the message.
* @param list List to be sent.
* @param message Initial message string.
* @param format Whether lyrics formatting should be used.
*/
function sendLarge(id, list, message, format) {
var length = message.length;
var multi = [];
list.forEach(function(l, i) {
var line = l;
if (format && line.length > 0) {
while (line[line.length - 1] == " ")
line = line.slice(0, -1);
line = config.options.lyricformat + line + config.options.lyricformat;
}
line += "\n";
if (length + line.length >= config.options.maxlength) {
multi.push(message);
length = line.length;
message = line;
}
else {
length += line.length;
message += line;
}
});
if (message != "")
multi.push(message);
multi.forEach(function(m, i){
setTimeout(function() {
send(id, m, true);
}, i * 1000);
});
};
/*
* Sends a message with image to a channel on Discord.
* @param id ID of the channel to send to.
* @param message String message to send.
* @param file Path to the image file.
* @param filename Name of the image as seeon on Discord.
* @param typing Whether the typing delay should be added.
* @param del Whether the file will be deleted after embedding.
*/
function embed(id, message, file, filename, typing, del) {
var channel = channelIDToName(id);
var msg = {
"to": id,
"file": file,
"filename": filename,
"message": message
};
if (typing) {
setTimeout(function() {
console.log(util.format(
strings.debug.embed,
channel,
message,
msg.filename,
msg.file
));
bot.uploadFile(msg);
if (del && fs.existsSync(file)) {
fs.unlinkSync(file);
}
}, config.options.typetime * 1000);
}
else {
console.log(util.format(
strings.debug.embed,
channel,
message,
msg.filename,
msg.file
));
bot.uploadFile(msg);
if (del && fs.existsSync(file)) {
fs.unlinkSync(file);
}
}
};
/*
* Adds a reaction to a message on Discord.
* @param channelID ID of the channel.
* @param messageID ID of the message.
* @param reaction String of the react to use.
* @param useUnicode Whether unicode emoji is to be used.
*/
function react(channelID, messageID, reaction) {
var clean = reaction.substring(2, reaction.length - 1);
if (clean.split(":")[1] === "")
clean = reaction.substring(2, reaction.length - 2);
var input = {
"channelID": channelID,
"messageID": messageID,
"reaction": clean
};
bot.addReaction(input, function(err) {
if (err != undefined) {
console.log(strings.debug.failedr);
react(channelID, messageID, reaction);
}
});
};
/*
* Executes an interraction command on one person or more people.
* @param data Data of the message.
*/
function doInterraction(data) {
data.command = data.command.toLowerCase();
if (!isplushie) {
if (data.data.d.mentions[0] != null) {
if (isMentioned(bot.id, data.data) && data.data.d.mentions.length == 1) {
if (data.command == "unplushie") {
send(data.channelID, strings.commands[data.command].error, true);
}
else {
if (data.command == "plushie")
isplushie = true;
if (data.command == "socks") {
send(data.channelID, util.format(
strings.commands[data.command].self,
generateSock()
), true);
}
else {
send(data.channelID, strings.commands[data.command].self, true);
}
}
}
else {
for (i = 0; i < data.data.d.mentions.length; i++)
if (bot.id == data.data.d.mentions[i].id)
data.data.d.mentions.splice(i, 1);
if (data.data.d.mentions.length <= 1) {
if (data.command == "socks") {
send(data.channelID, util.format(
strings.commands[data.command].single,
mention(data.data.d.mentions[0].id),
generateSock()
), true);
}
else {
send(data.channelID, util.format(
strings.commands[data.command].single,
mention(data.data.d.mentions[0].id)
), true);
}
}
else {
var mentions = "";
var i;
for (i = 0; i < data.data.d.mentions.length - 1; i++) {
mentions += mention(data.data.d.mentions[i].id);
if (i < data.data.d.mentions.length - 2) {
mentions += config.separators.list;
}
}
mentions += config.separators.lend + mention(data.data.d.mentions[i].id);
if (data.command == "socks") {
send(data.channelID, util.format(
strings.commands[data.command].multiple,
generateSocks(data.data.d.mentions.length),
mentions
), true);
}
else {
send(data.channelID, util.format(
strings.commands[data.command].multiple,
mentions
), true);
}
}
}
}
else {
if (data.command == "socks") {
send(data.channelID, util.format(
strings.commands[data.command].single,
mention(data.userID),
generateSock()
), true);
}
else {
send(data.channelID, util.format(
strings.commands[data.command].single,
mention(data.userID)
), true);
}
}
}
else {
if (data.command == "unplushie" && isMentioned(bot.id, data.data)) {
isplushie = false;
send(data.channelID, util.format(
strings.commands[data.command].self,
mention(data.userID)
), true);
}
else
send(data.channelID, strings.commands["plushie"].error, true);
}
};
/*
* Executes a custom interraction command on one person or more people.
* @param data Data of the message.
* @param index Index of the command.
*/
function doInterractionCustom(data, index) {
if (!isplushie) {
if (data.data.d.mentions[0] != null) {
if (isMentioned(bot.id, data.data) && data.data.d.mentions.length == 1) {
send(data.channelID, custom.list[index].strings.self, true);
}
else {
for (i = 0; i < data.data.d.mentions.length; i++)
if (bot.id == data.data.d.mentions[i].id)
data.data.d.mentions.splice(i, 1);
if (data.data.d.mentions.length <= 1) {
send(data.channelID, util.format(
custom.list[index].strings.single,
mention(data.data.d.mentions[0].id)
), true);
}
else {
var mentions = "";
var i;
for (i = 0; i < data.data.d.mentions.length - 1; i++) {
mentions += mention(data.data.d.mentions[i].id);
if (i < data.data.d.mentions.length - 2) {
mentions += config.separators.list;
}
}
mentions += config.separators.lend + mention(data.data.d.mentions[i].id);
send(data.channelID, util.format(
custom.list[index].strings.multiple,
mentions
), true);
}
}
}
else {
send(data.channelID, util.format(
custom.list[index].strings.single,
mention(data.userID)
), true);
}
}
else {
send(data.channelID, strings.commands["plushie"].error, true);
}
};
/*
* Loads specific reactrole messages into cache.
*/
function prepareReactroleMessages() {
reactrole.mapping.forEach(function(m) {
var message = {};
message.channelID = channelNameToID(m.channel);
message.messageID = m.message;
bot.getMessage(message, function(err, msg) {
if (msg != undefined) {
var i = 0;
Object.keys(m.map).forEach(function (r1) {
var clean = r1.substring(2, r1.length - 1);
var parts = clean.split(":");
if (parts[1] === "")
parts[1] = null;
var found = false;
if (msg.reactions != undefined)
msg.reactions.forEach(function (r2) {
if (r2.emoji.name === parts[0] && r2.emoji.id === parts[1])
found = true;
});
if (!found) {
setTimeout(function() {
react(message.channelID, message.messageID, r1);
}, i * 1000);
i++;
}
});
}
else {
console.log(util.format(
strings.debug.reactroleerr,
m.channel
));
setTimeout(function() {
prepareReactroleMessages();
}, config.options.reactroleretr * 1000);
}
});
});
}
/*************************
* VARIPASS FUNCTIONALITY
*************************/
/*
* Pulls all data from VariPass and does adequate processing.
*/
function statusVariPass() {
var payload = {
"key": varipass.main.key,
"action": "all"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
statusGlobal.varipass = Math.floor((new Date()) / 1000);
var vpData;
try {
vpData = JSON.parse(xhr.responseText);
}
catch(error) {
}
if (vpData != undefined) {
var timeOffset = Math.floor((new Date()) / 1000) - vpData.current;
statusGlobal.celly = findVariable(vpData, varipass.main.ids.temperature ).history[0].time + timeOffset;
statusGlobal.chryssy = findVariable(vpData, varipass.main.ids.counts ).history[0].time + timeOffset;
statusGlobal.dashie = findVariable(vpData, varipass.main.ids.pm010 ).history[0].time + timeOffset;
statusGlobal.unicorn = findVariable(vpData, varipass.main.ids.unicorn_temp).history[0].time + timeOffset;
statusGlobal.twilight = findVariable(vpData, varipass.main.ids.location ).history[0].time + timeOffset;
// Geiger Calculation
var vpDose = findVariable(vpData, varipass.main.ids.dose).history;
var vpDoseEMA = findVariable(vpData, varipass.main.ids.doseema).history;
if (!(vpTimeDose != undefined && vpDose[0].time <= vpTimeDose)) {
vpTimeDose = vpDose[0].time;
var alpha = parseFloat(1.0 / config.varipass.geiger.samples);
var value = alpha * vpDose[0].value + (1.0 - alpha) * vpDoseEMA[0].value;
sendDoseEMA(value);
if (value <= config.varipass.geiger.okay) {
if (doseWasWarned) {
doseWasWarned = false;
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.varipass.doseokay,
value.toFixed(4),
config.varipass.geiger.okay
), false);
}
}
else if (value >= config.varipass.geiger.warning) {
if (!doseWasWarned) {
doseWasWarned = true;
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.varipass.dosewarning,
config.varipass.geiger.warning,
value.toFixed(4)
), false);
}
}
}
// Pressure Alerts
var vpPressure = findVariable(vpData, varipass.main.ids.pressure).history;
if (!(vpTimePressure != undefined && vpPressure[0].time <= vpTimePressure)) {
vpTimePressure = vpPressure[0].time;
if (vpPressure[1].value != undefined) {
if (vpPressure[0].time - vpPressure[1].time <= config.varipass.pressure.pause) {
var value = vpPressure[0].value - vpPressure[1].value;
if (Math.abs(value) >= config.varipass.pressure.warning) {
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.varipass.pressure,
value.toFixed(2)
), false);
}
}
}
}
// Particle Alerts
var vpPM025 = findVariable(vpData, varipass.main.ids.pm025).history[0].value;
if (vpPM025 <= config.varipass.pm025.okay) {
if (pm025WasWarned) {
pm025WasWarned = false;
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.varipass.pm025okay,
mention(config.options.adminid),
strings.announcements.varipass.pm025okayname,
vpPM025.toFixed(2)
), false);
}
}
else if (vpPM025 >= config.varipass.pm025.warning) {
if (!pm025WasWarned) {
pm025WasWarned = true;
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.varipass.pm025warning,
mention(config.options.adminid),
strings.announcements.varipass.pm025warningname,
vpPM025.toFixed(2)
), false);
}
}
// Light Control Features
var vpLight = findVariable(vpData, varipass.main.ids.light).history[0].value;
refreshTradfriDevices(function(result) {
if (result) {
statusGlobal.tradfri = Math.floor((new Date()) / 1000);
// Day Lamp Off
if (vpLight >= config.varipass.daylight.threshold) {
config.varipass.daylight.bulbs.forEach(function(b) {
tDevices.forEach(function(d) {
if (d.name == b && d.on == true) {
hub.toggleDevice(d.id);
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.varipass.daylightoff,
mention(config.options.adminid),
b
), false);
}
});
});
}
// Night Lamp Off
var controlOn = false;
tDevices.forEach(function(d) {
if (d.name == config.varipass.nightlight.control && d.on == true) {
controlOn = true;
}
});
if (vpLight > config.varipass.nightlight.value - config.varipass.nightlight.delta &&
vpLight < config.varipass.nightlight.value + config.varipass.nightlight.delta &&
!controlOn) {
nightLightCount++;
if (nightLightCount >= config.varipass.nightlight.count)
config.varipass.nightlight.bulbs.forEach(function(b) {
tDevices.forEach(function(d) {
if (d.name == b && d.on == true) {
hub.toggleDevice(d.id);
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.varipass.nightlightoff,
mention(config.options.adminid),
b
), false);
}
});
});
}
else {
nightLightCount = 0;
}
}
});
}
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorR,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
/*
* Writes the radiation dose exponential moving average data to VariPass.
* @param value Dose value to write.
*/
function sendDoseEMA(value) {
var payload = {
"key": varipass.main.key,
"id": varipass.main.ids.doseema,
"action": "write",
"value": value.toFixed(4)
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorW,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
/*
* Writes the EEG data to VariPass.
*/
function eegVaripassWrite() {
var value;
if (eegConfig.type == "raw") {
switch (eegConfig.value) {
case "timestamp": value = eegValues.time; break;
case "battery": value = eegValues.battery; break;
case "signal": value = eegValues.signal; break;
case "attention": value = eegValues.attention; break;
case "meditation": value = eegValues.meditation; break;
case "wave0": value = eegValues.waves[0]; break;
case "wave1": value = eegValues.waves[1]; break;
case "wave2": value = eegValues.waves[2]; break;
case "wave3": value = eegValues.waves[3]; break;
case "wave4": value = eegValues.waves[4]; break;
case "wave5": value = eegValues.waves[5]; break;
case "wave6": value = eegValues.waves[6]; break;
case "wave7": value = eegValues.waves[7]; break;
case "sumlow": value = eegValues.sumlow; break;
case "sumhigh": value = eegValues.sumhigh; break;
}
}
else if (eegConfig.type == "ema") {
switch (eegConfig.value) {
case "timestamp": value = eegValuesEMA.time; break;
case "battery": value = eegValuesEMA.battery; break;
case "signal": value = eegValuesEMA.signal; break;
case "attention": value = eegValuesEMA.attention; break;
case "meditation": value = eegValuesEMA.meditation; break;
case "wave0": value = eegValuesEMA.waves[0]; break;
case "wave1": value = eegValuesEMA.waves[1]; break;
case "wave2": value = eegValuesEMA.waves[2]; break;
case "wave3": value = eegValuesEMA.waves[3]; break;
case "wave4": value = eegValuesEMA.waves[4]; break;
case "wave5": value = eegValuesEMA.waves[5]; break;
case "wave6": value = eegValuesEMA.waves[6]; break;
case "wave7": value = eegValuesEMA.waves[7]; break;
case "sumlow": value = eegValuesEMA.sumlow; break;
case "sumhigh": value = eegValuesEMA.sumhigh; break;
}
}
if (value != undefined) {
var payload = {
"key": varipass.eeg.key,
"action": "write",
"id": varipass.eeg.ids.eeg,
"value": value
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorW,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
}
function eegVaripassEdit() {
var name = util.format(
strings.commands.eegset.varipassA,
eegConfig.type,
eegConfig.value
);
var description = strings.commands.eegset.varipassB;
if (eegConfig.type == "ema")
description += util.format(
strings.commands.eegset.varipassC,
eegConfig.ema
);
var payload = {
"key": varipass.eeg.key,
"action": "edit",
"id": varipass.eeg.ids.eeg,
"type": "float",
"name": name,
"description": description,
"unit": "",
"graph": true,
"perc": false,
"max": eegConfig.max,
"expire": eegConfig.expire
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorW,
err.target.status
));
xhr.abort();
eegVaripassEdit();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
eegVaripassEdit();
}
xhr.send(JSON.stringify(payload));
}
/*
* Pulls all data from VariPass and does processes the average values. Pushes the data back once done.
*/
function avgVariPass() {
var payload = {
"key": varipass.main.key,
"action": "all"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
var vpPressure = findVariable(vpData, varipass.main.ids.pressure).history;
var vpMagnitude = findVariable(vpData, varipass.main.ids.magnitude).history;
var vpInclination = findVariable(vpData, varipass.main.ids.inclination).history;
var vpDoseEMA = findVariable(vpData, varipass.main.ids.doseema).history;
var avgPressure = 0.0;
vpPressure.forEach(function(v) {
avgPressure += v.value / vpPressure.length;
});
var avgMagnitude = 0.0;
vpMagnitude.forEach(function(v) {
avgMagnitude += v.value / vpMagnitude.length;
});
var avgInclination = 0.0;
vpInclination.forEach(function(v) {
avgInclination += v.value / vpInclination.length;
});
var avgDoseEMA = 0.0;
vpDoseEMA.forEach(function(v) {
avgDoseEMA += v.value / vpDoseEMA.length;
});
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.dailyavg,
avgPressure.toFixed(4),
avgMagnitude.toFixed(4),
avgInclination.toFixed(4),
avgDoseEMA.toFixed(4)
), true);
writeVariPass(varipass.main.key, varipass.main.ids.avgPressure, avgPressure);
writeVariPass(varipass.main.key, varipass.main.ids.avgMagnitude, avgMagnitude);
writeVariPass(varipass.main.key, varipass.main.ids.avgInclination, avgInclination);
writeVariPass(varipass.main.key, varipass.main.ids.avgDoseEMA, avgDoseEMA);
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorR,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
/*
* Writes a value to VariPass.
* @param key The key of the VariPass account.
* @param id The ID of the variable.
* @param val The value to write.
*/
function writeVariPass(key, id, val) {
var payload = {
"key": key,
"action": "write",
"id": id,
"value": val
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
if (vpData.result != "success" && vpData.result != "error_cooldown") {
console.log(util.format(
strings.debug.varipass.errorW,
vpData.result
));
}
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.varipass.errorW,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.varipass.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
/*
* Parses VariPass data to return a certain variable.
* @param data VariPass data to search in.
* @param id The ID of the variable to look for.
* @return The VariPass variable with all the data.
*/
function findVariable(data, id) {
var found = false;
var variable = null;
data.list.forEach(function(v) {
if (v.id == id && !found)
variable = v;
});
return variable;
}
/****************************
* BLITZORTUNG FUNCTIONALITY
****************************/
/*
* Connects to the Blitzortung API.
* @param reconnect Whether this is an automatic reconnect.
*/
function connectBlitzortung(reconnect) {
var area = {};
area.from = {};
area.from.latitude = blitzor.location.latitude + blitzor.expand;
area.from.longitude = blitzor.location.longitude - blitzor.expand;
area.to = {};
area.to.latitude = blitzor.location.latitude - blitzor.expand;
area.to.longitude = blitzor.location.longitude + blitzor.expand;
if (reconnect && blitzor.debugconnect)
console.log(util.format(
strings.debug.blitzor.reconnect,
area.from.latitude,
area.to.latitude,
area.from.longitude,
area.to.longitude
));
else if (!reconnect)
console.log(util.format(
strings.debug.blitzor.connect,
area.from.latitude,
area.to.latitude,
area.from.longitude,
area.to.longitude
));
blitzorws = new blitzorapi.Client({
make(address) {
if (blitzor.debugconnect)
console.log(" " + address);
return new WebSocket(address, {
rejectUnauthorized: blitzor.usecert
});
}
});
blitzorws.connect();
blitzorws.on("error", console.error);
blitzorws.on("connect", () => {
blitzorws.setArea(area);
});
blitzorws.on("data", strike => {
var distance = earthDistance(blitzor.location.latitude, blitzor.location.longitude, strike.location.latitude, strike.location.longitude);
if (distance < lightningNew) {
lightningNew = distance;
lightningLat = strike.location.latitude;
lightningLng = strike.location.longitude;
if (!blitzor.debugstrikes)
console.log(util.format(
strings.debug.blitzor.strike,
distance,
strike.location.latitude,
strike.location.longitude
));
}
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.blitzor.strike,
distance,
strike.location.latitude,
strike.location.longitude
));
});
lightningReconnect = setTimeout(function() {
blitzorws.close();
connectBlitzortung(true);
}, blitzor.reconnect * 1000);
if (reconnect && blitzor.debugconnect)
console.log(strings.debug.blitzor.done);
else if (!reconnect)
console.log(strings.debug.blitzor.done);
}
/*
* Connects to the Blitzortung API for storm chasing.
* @param reconnect Whether this is an automatic reconnect.
*/
function connectChase(reconnect) {
var payload = {
"key": varipass.main.key,
"action": "read",
"id": varipass.main.ids.location
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.options.varipassurl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var vpData = JSON.parse(xhr.responseText);
var values = vpData.value.split("\\n");
chaseThoriLat = 0.0;
chaseThoriLng = 0.0;
values.forEach(function(v) {
var parts = v.split(":");
if (parts[0] == "lat")
chaseThoriLat = parseFloat(parts[1]);
else if (parts[0] == "lng")
chaseThoriLng = parseFloat(parts[1]);
});
var area = {};
area.from = {};
area.from.latitude = chaseThoriLat + blitzor.expand;
area.from.longitude = chaseThoriLng - blitzor.expand;
area.to = {};
area.to.latitude = chaseThoriLat - blitzor.expand;
area.to.longitude = chaseThoriLng + blitzor.expand;
if (reconnect && blitzor.debugconnect)
console.log(util.format(
strings.debug.chase.reconnect,
area.from.latitude,
area.to.latitude,
area.from.longitude,
area.to.longitude
));
else if (!reconnect)
console.log(util.format(
strings.debug.chase.connect,
area.from.latitude,
area.to.latitude,
area.from.longitude,
area.to.longitude
));
chasews = new blitzorapi.Client({
make(address) {
return new WebSocket(address, {
rejectUnauthorized: blitzor.usecert
});
}
});
chasews.connect();
chasews.on("error", console.error);
chasews.on("connect", () => {
chasews.setArea(area);
});
chasews.on("data", strike => {
var distance = earthDistance(chaseThoriLat, chaseThoriLng, strike.location.latitude, strike.location.longitude);
if (distance < chaseNew) {
chaseNew = distance;
chaseLat = strike.location.latitude;
chaseLng = strike.location.longitude;
if (!blitzor.debugstrikes)
console.log(util.format(
strings.debug.chase.strike,
distance,
strike.location.latitude,
strike.location.longitude
));
}
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.chase.strike,
distance,
strike.location.latitude,
strike.location.longitude
));
});
chaseReconnect = setTimeout(function() {
chasews.close();
connectChase(true);
}, blitzor.chase * 1000);
if (reconnect && blitzor.debugconnect)
console.log(strings.debug.chase.done);
else if (!reconnect)
console.log(strings.debug.chase.done);
}
}
xhr.onerror = function(err) {
connectChase(true);
xhr.abort();
}
xhr.ontimeout = function() {
connectChase(true);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
}
/*
* Performs the lightning data checking in a loop.
*/
function loopLightning() {
if (lightningNew < lightningRange) {
lightningRange = lightningNew;
clearTimeout(lightningSpread);
lightningSpread = setTimeout(spreadLightning, blitzor.spread * 1000);
clearTimeout(lightningExpire);
lightningExpire = setTimeout(function() {
send(channelNameToID(config.options.channels.home), strings.announcements.blitzor.expire, false);
}, blitzor.expire * 1000);
var time = moment.tz(new Date(), "Europe/Zagreb").format("HH:mm:ss");
var rng = lightningRange;
var lat = lightningLat;
var lng = lightningLng;
var b = earthBearing(blitzor.location.latitude, blitzor.location.longitude, lat, lng);
var bear = "N";
if (b > 11.25 && b < 33.75) bear = "NNE";
else if (b > 33.75 && b < 56.25) bear = "NE";
else if (b > 56.25 && b < 78.75) bear = "ENE";
else if (b > 78.75 && b < 101.25) bear = "E";
else if (b > 101.25 && b < 123.75) bear = "ESE";
else if (b > 123.75 && b < 146.25) bear = "SE";
else if (b > 146.25 && b < 168.75) bear = "SSE";
else if (b > 168.75 && b < 191.25) bear = "S";
else if (b > 191.25 && b < 213.75) bear = "SSW";
else if (b > 213.75 && b < 236.25) bear = "SW";
else if (b > 236.25 && b < 258.75) bear = "WSW";
else if (b > 258.75 && b < 281.25) bear = "W";
else if (b > 281.25 && b < 303.75) bear = "WNW";
else if (b > 303.75 && b < 326.25) bear = "NW";
else if (b > 326.25 && b < 348.75) bear = "NNW";
getLocationInfo(function(locInfo) {
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.blitzor.strike,
rng.toFixed(2),
bear,
b.toFixed(2),
locInfo.town,
locInfo.country,
time
), false);
}, lat, lng);
}
if (chaseNew < chaseRange) {
chaseRange = chaseNew;
clearTimeout(chaseSpread);
chaseSpread = setTimeout(spreadChase, blitzor.spread * 1000);
clearTimeout(chaseExpire);
chaseExpire = setTimeout(function() {
send(config.options.adminid, strings.announcements.chase.expire, false);
}, blitzor.expire * 1000);
var time = moment.tz(new Date(), "Europe/Zagreb").format("HH:mm:ss");
var rng = chaseRange;
var lat = chaseLat;
var lng = chaseLng;
var b = earthBearing(chaseThoriLat, chaseThoriLng, lat, lng);
var bear = "N";
if (b > 11.25 && b < 33.75) bear = "NNE";
else if (b > 33.75 && b < 56.25) bear = "NE";
else if (b > 56.25 && b < 78.75) bear = "ENE";
else if (b > 78.75 && b < 101.25) bear = "E";
else if (b > 101.25 && b < 123.75) bear = "ESE";
else if (b > 123.75 && b < 146.25) bear = "SE";
else if (b > 146.25 && b < 168.75) bear = "SSE";
else if (b > 168.75 && b < 191.25) bear = "S";
else if (b > 191.25 && b < 213.75) bear = "SSW";
else if (b > 213.75 && b < 236.25) bear = "SW";
else if (b > 236.25 && b < 258.75) bear = "WSW";
else if (b > 258.75 && b < 281.25) bear = "W";
else if (b > 281.25 && b < 303.75) bear = "WNW";
else if (b > 303.75 && b < 326.25) bear = "NW";
else if (b > 326.25 && b < 348.75) bear = "NNW";
getLocationInfo(function(locInfo) {
send(config.options.adminid, util.format(
strings.announcements.chase.strike,
rng.toFixed(2),
bear,
b.toFixed(2),
locInfo.town,
locInfo.country,
time
), false);
}, lat, lng);
}
setTimeout(loopLightning, blitzor.loop * 1000);
}
/*
* Spread the lightning range when there is no new lightning.
*/
function spreadLightning() {
var rangeSpread = blitzor.range / (blitzor.expire / blitzor.spread);
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.blitzor.spread,
lightningRange,
lightningRange + rangeSpread
));
lightningRange = lightningRange + rangeSpread;
lightningNew = lightningNew + rangeSpread;
if (lightningRange > blitzor.range) {
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.blitzor.max,
blitzor.range
));
lightningRange = blitzor.range;
lightningNew = blitzor.range;
}
else {
lightningSpread = setTimeout(spreadLightning, blitzor.spread * 1000);
}
}
/*
* Spread the lightning range when there is no new lightning, used when storm chasing.
*/
function spreadChase() {
var rangeSpread = blitzor.range / (blitzor.expire / blitzor.spread);
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.chase.spread,
chaseRange,
chaseRange + rangeSpread
));
chaseRange = chaseRange + rangeSpread;
chaseNew = chaseNew + rangeSpread;
if (chaseRange > blitzor.range) {
if (blitzor.debugstrikes)
console.log(util.format(
strings.debug.chase.max,
blitzor.range
));
chaseRange = blitzor.range;
chaseNew = blitzor.range;
}
else {
chaseSpread = setTimeout(spreadChase, blitzor.spread * 1000);
}
}
/************************
* TRADFRI FUNCTIONALITY
************************/
/*
* Connects to the Tradfri hub and refreshes all devices.
* @param callback Function called once processing is done. Returns true if successful.
*/
function refreshTradfriDevices(callback) {
if (tradfri.debug)
console.log(strings.debug.tradfri.connect);
hub.getDevices().then((result) => {
tBulbs = result.filter(function(d) {
return d.color != undefined;
});
tBulbs.sort((a, b) => (a.name > b.name) ? 1 : -1);
tDevices = result.filter(function(d) {
return d.color != undefined || d.type == "TRADFRI control outlet";
});
tDevices.sort((a, b) => (a.name > b.name) ? 1 : -1);
if (tradfri.debug) {
console.log(util.format(
strings.debug.tradfri.doneb,
tBulbs.length
));
tBulbs.forEach(function(d) {
console.log(util.format(
strings.debug.tradfri.bulb,
d.name,
d.id,
d.type,
d.color,
d.brightness,
d.on
));
});
console.log(util.format(
strings.debug.tradfri.doned,
tBulbs.length
));
tDevices.forEach(function(d) {
console.log(util.format(
strings.debug.tradfri.device,
d.name,
d.id,
d.type,
d.on
));
});
}
hubRetry = 0;
callback(true);
}).catch((error) => {
if (hubRetry >= tradfri.retries)
console.log(util.format(
strings.debug.tradfri.errorA,
hubRetry
));
hubRetry++;
callback(false);
});
}
/*
* Sets the mood of the lighting.
* @param name Name of the mood to use.
* @param callback Function called once processing is done. Returns true if successful.
*/
function setMood(name, callback) {
tradfri.moods.forEach(function(m) {
if (m.name == name) {
refreshTradfriDevices(function(result) {
if (result) {
m.bulbs.forEach(function(d1) {
tBulbs.forEach(function(d2) {
if (d1.name == d2.name) {
setBulb(d1.config, d2.id);
}
});
});
callback(true);
}
else {
callback(false);
}
});
}
});
}
/*
* Sets the parameters of a specific bulb.
* @param bulb The bulb object.
* @param id ID of the bulb.
*/
function setBulb(bulb, id) {
var newBulb = normalize(bulb);
hub.setDeviceState(id, newBulb).then((result) => {
}).catch((error) => {
console.log(strings.debug.tradfri.errorB);
setBulb(bulb, id);
});
}
/*
* Normalizes the colors of a bulb.
* @param bulb The bulb object.
* @return New bulb object with normalized color.
*/
function normalize(bulb) {
var newBulb = Object.assign({}, bulb);
if (newBulb.colorX != undefined) {
newBulb.colorX = Math.round(newBulb.colorX * 65535);
}
if (newBulb.colorY != undefined) {
newBulb.colorY = Math.round(newBulb.colorY * 65535);
}
if (newBulb.brightness != undefined) {
newBulb.brightness = Math.round(newBulb.brightness * 254);
}
return newBulb;
}
/*******************************
* CHANNEL AND DATA TRANSLATION
*******************************/
/*
* Parses a given channel name to retrieve the correct ID.
* @param name The input name to look for.
* @return ID of the channel.
*/
function channelNameToID(name) {
var found = false;
var id = null;
channels.list.forEach(function(c) {
if (c.name == name && !found)
id = c.id;
});
return id;
};
/*
* Parses a given channel ID to retrieve the correct name.
* @param id The input ID to look for.
* @return Name of the channel.
*/
function channelIDToName(id) {
var found = false;
var name = "unknown";
channels.list.forEach(function(c) {
if (c.id == id && !found)
name = c.name;
});
return name;
};
/*
* Parses a given channel ID to retrieve the correct brain.
* @param id The input ID to look for.
* @return Brain of the channel.
*/
function channelIDToBrain(id) {
var found = false;
var brain = null;
channels.list.forEach(function(c) {
if (c.id == id && !found)
brain = c.brain;
});
if (brain == null)
brain = channels.default.brain;
return brain;
};
/*
* Processes the channel whitelist and checks if the channel is whitelisted.
* @param channelID ID of the channel to check whitelist of.
* @return Boolean whether the channel is whitelisted.
*/
function processWhitelist(channelID) {
var okay = false;
channels.list.forEach(function(c) {
if (c.id == channelID && c.learn)
okay = true;
});
return okay;
}
/*
* Processes the user blacklist and checks if the user is blacklisted.
* @param userID ID of the user to check blacklist of.
* @return Boolean whether the user is NOT blacklisted.
*/
function processBlacklist(userID) {
var okay = true;
if (blacklist[userID] != undefined) {
okay = false;
};
return okay;
}
/*
* Processes the user ignore list and checks if the user is ignored.
* @param userID ID of the user to check ignore list for.
* @return Boolean whether the user is NOT ignored.
*/
function processIgnore(userID) {
var okay = true;
if (ignore[userID] != undefined) {
okay = false;
};
return okay;
}
/*************************************
* STRING MANIPULATION AND GENERATION
*************************************/
/*
* Formats a mention string.
* @param id ID to mention.
* @return String usable by Discord as a mention.
*/
function mention(id) {
return util.format(config.options.mention, id);
};
/*
* Formats a role mention string.
* @param id ID to mention.
* @return String usable by Discord as a mention.
*/
function mentionRole(id) {
return util.format(config.options.mentionrole, id);
};
/*
* Checks whether a certain ID was mentioned.
* @param id ID to check the mentions of.
* @param data Discord's event data.
* @return Boolean whether the ID was mentioned.
*/
function isMentioned(id, data) {
var mentioned = false;
data.d.mentions.forEach(function(m) {
if (m.id == id)
mentioned = true;
});
return mentioned;
};
/*
* Uses regex to clean up a message.
* @param message Message text to clean up.
* @return The cleaned up message.
*/
function cleanMessage(message) {
return message.replace(/\*\*/g, "").replace(/<@.*>/g, "").replace(/\|\|.*\|\|/g, "").replace(/http(|s):\/\/(\S+)*/g, "");
}
/*
* Analyzes the message and completes it with _ or * for an RP action if needed.
* @param message Message text to analyze.
* @return The completed RP message.
*/
function completeRoleplay(message) {
var newMessage = message;
if (newMessage[0] == "*" && newMessage[1] == " ")
newMessage = "*" + newMessage.substring(2, newMessage.length);
if (newMessage[0] == "_" && newMessage[1] == " ")
newMessage = "_" + newMessage.substring(2, newMessage.length);
if (newMessage[newMessage.length - 1] == "*" && newMessage[newMessage.length - 2] == " ")
newMessage = newMessage.substring(0, newMessage.length - 2) + "*";
if (newMessage[newMessage.length - 1] == "_" && newMessage[newMessage.length - 2] == " ")
newMessage = newMessage.substring(0, newMessage.length - 2) + "_";
var words = newMessage.split(" ");
var startUnd = -1;
var startAst = -1;
var endUnd = -1;
var endAst = -1;
var doSUnd = false;
var doSAst = false;
var doEUnd = false;
var doEAst = false;
words.forEach(function (w, i) {
if (w[0] == "_")
startUnd = i;
if (w[0] == "*")
startAst = i;
if (w[w.length - 1] == "_")
endUnd = i;
if (w[w.length - 1] == "*")
endAst = i;
});
if (startUnd > -1 && endUnd == -1)
doEUnd = true;
if (startAst > -1 && endAst == -1)
doEAst = true;
if (startUnd == -1 && endUnd > -1)
doSUnd = true;
if (startAst == -1 && endAst > -1)
doSAst = true;
if (config.brain.debugrp) {
console.log(newMessage);
console.log("Ast Und - Ast Und: " + doSUnd + " " + doSAst + " " + doEUnd + " " + doEAst);
}
if (doEUnd && doEAst) {
if (startUnd < startAst)
newMessage = newMessage + "*_";
else
newMessage = newMessage + "_*";
}
else if (doEUnd)
newMessage = newMessage + "_";
else if (doEAst)
newMessage = newMessage + "*";
if (doSUnd && doSAst) {
if (endUnd < endAst)
newMessage = "*_" + newMessage;
else
newMessage = "_*" + newMessage;
}
else if (doSUnd)
newMessage = "_" + newMessage;
else if (doSAst)
newMessage = "*" + newMessage;
return newMessage;
}
/*
* Checks if a message has usable contents.
* @param message Message text analyze.
* @return Whether the message had contents.
*/
function isMessageNotEmpty(message) {
return message != "" && message != " " && message != "\n";
}
function toUpper(str) {
return str.toLowerCase().replace(/^[a-zA-Z0-9À-ž]|[-\r\n\t\f\v ][a-zA-Z0-9À-ž]/g, function (letter) {
return letter.toUpperCase();
})
}
/*
* Converts a given date to a more readable format.
* @param date The input date, this is not the JS Date object.
* @return Formatted string.
*/
function getTimeString(date) {
var string = "";
if (date.days != null && date.days != 0) {
string += date.days + " day";
if (date.days > 1)
string += "s";
}
if ((date.days != null && date.days != 0) && (date.hours != null && date.hours != 0) && (date.minutes == null || date.minutes == 0))
string += " and ";
else if ((date.days != null && date.days != 0) && (date.hours != null && date.hours != 0) && (date.minutes != null && date.minutes != 0))
string += ", ";
if (date.hours != null && date.hours != 0) {
string += date.hours + " hour";
if (date.hours > 1)
string += "s";
}
if ((date.hours != null && date.hours != 0) && (date.minutes != null && date.minutes != 0))
string += " and ";
else if ((date.days != null && date.days != 0) && (date.hours == null || date.hours == 0) && (date.minutes != null && date.minutes != 0))
string += " and ";
if (date.minutes != null && date.minutes != 0) {
string += date.minutes + " minute";
if (date.minutes > 1)
string += "s";
}
if (string == "")
string = "0 minutes";
return string;
}
/*
* Converts a given date to a simplified format.
* @param date The input date, this is not the JS Date object.
* @return Formatted string.
*/
function getTimeStringSimple(date) {
var string = "";
if (date.days != null && date.days != 0) {
string += date.days + "d ";
}
if (date.hours != null && date.hours != 0) {
string += date.hours + "h ";
}
if (date.minutes != null) {
string += date.minutes + "m ";
}
if (date.seconds != null) {
string += date.seconds + "s";
}
return string;
}
/*
* Parses two given dates to return the time left and final time.
* @param start Starting date.
* @param stop Final date.
* @param timezone The timezone to calculate for.
* @return String of time left and final time.
*/
function getTimeLeft(start, stop, timezone) {
var diff = (stop - start) / 60000;
var time = {};
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
var momentTime = moment.tz(stop, timezone);
return util.format(
strings.misc.left,
getTimeString(time),
momentTime.format("ddd MMM DD, YYYY"),
momentTime.format("HH:mm (z)")
);
}
/*
* Parses the phase list to return a string compatible with Discord chat.
* @param name Name of the Moon phse to look for.
* @param offset Offset of the phase.
* @return Formatted string.
*/
function getPhaseString(name, offset) {
var id = 0;
config.phases.forEach(function(n, i) {
if (n.name == name)
id = i;
});
id += offset;
if (id >= config.phases.length)
id -= config.phases.length;
else if (id < 0)
id += config.phases.length;
return config.phases[id].name + " " + config.phases[id].icon;
}
/*
* Generates a random color string for a single sock.
* @return Sock color string.
*/
function generateSock() {
if (Math.random() < 0.5) {
// Single color
return strings.misc.socks.single[Math.floor(Math.random() * strings.misc.socks.single.length)];
}
else {
// Double color
var colorA = strings.misc.socks.double[Math.floor(Math.random() * strings.misc.socks.double.length)];
var colorB = "";
do {
colorB = strings.misc.socks.double[Math.floor(Math.random() * strings.misc.socks.double.length)];
} while (colorB == colorA);
return colorA + "-" + colorB;
}
}
/*
* Generates a randomized string containing colors of multiple socks.
* @return A string of multiple sock colors.
*/
function generateSocks(count) {
var sockList = [];
var socks = "";
var i;
for (i = 0; i < count; i++)
sockList.push(generateSock());
for (i = 0; i < count - 1; i++) {
socks += sockList[i];
if (i < count - 2) {
socks += config.separators.list;
}
}
socks += config.separators.lend + sockList[i];
return socks;
}
/*
* Returns a random element in array.
* @param arr The array to process.
* @return The element.
*/
function random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
/*
* Inserts the OwO faces in a string.
* @param input The input string.
* @return The output string.
*/
function owoFaces(input) {
return input
.replace(/(?<![.?!])$/, Math.random() > 0.7 ? " " + random(strings.misc.faces["."]) : "")
.replace(/(!+|\?+|((?<!\.)\.(?!\.)))/g, match => (match[0] in strings.misc.faces ? " " + random(strings.misc.faces[match[0]]) : match));
}
/*
* Adjusts the casing of a string.
* @param input The input string.
* @return The output string.
*/
function owoCasing(input) {
return input
.split(/(?<=[!.?]\s*)/g)
.map(satz => satz[0].toUpperCase() + satz.slice(1).toLowerCase())
.join("");
}
/*
* Inserts stuttering to a string.
* @param input The input string.
* @return The output string.
*/
function owoStutter(input) {
return input
.split(/\s+/)
.map(word => {
const r = Math.random();
if (r > 0.15 || word === "") return word;
return word[0] + ("-" + word[0]).repeat(r > 0.05 ? 1 : 2) + word.slice(1);
})
.join(" ");
}
/*
* Performs the main OwO transformation.
* @param input The input string.
* @return The output string.
*/
function owoTransform(input) {
input = cleanMessage(input);
return input
.split(/\s+/g)
.map(word =>
word
.replace(/^you$/gi, "u")
.replace(/^your$/gi, "ur")
.replace(/^you're$/gi, "ur")
.replace(/l/gi, "w")
.replace(/v/gi, "w")
.replace(/th/gi, "t")
.replace(/^no/i, "nwo")
.replace(/d(?!$)/gi, "w")
.replace(/o$/i, "ow")
.replace(/r([aeiou])/gi, (_, match) => `w${match}`)
.replace(/([aeiou])r/gi, (_, match) => `${match}w`)
.replace(/(?<=\w)([^AEIOUaeiou]+)ou/, (_, match) => `${"w".repeat(match.length)}ou`)
.replace(/eou/, "ewou")
)
.join(" ");
}
/*
* Formats a WoW currency string (gold/silver/copper).
* @param price The price in copper.
* @return The formatted string.
*/
function getWoWPrice(price) {
var c = Math.floor(price % 100);
price = Math.floor(price / 100);
var s = Math.floor(price % 100);
price = Math.floor(price / 100);
var g = "";
while (price >= 1000) {
g = config.separators.price + Math.floor(price % 1000) + g;
price = Math.floor(price / 1000);
}
g = price + g;
return util.format(
strings.misc.gold,
g,
s,
c
);
}
/*
* Returns a string version of a number, with added zeros to start.
* @param digits Maximum number of digits.
* @param number The number to format for.
* @return The formatted string.
*/
function fillUpZeros(digits, number) {
var i = 0;
var res = number;
do {
i++;
res = Math.floor(res / 10);
} while (res > 0);
var out = number.toString();
i = digits - i;
while (i > 0) {
i--;
out = "0" + out;
}
return out;
}
/*****************************
* GEOGRAPHIC DATA PROCESSING
*****************************/
/*
* Uses an API to fetch a translated geo location of coordinates.
* @param callback Callback function called once done.
* @param lat The latitude coordinate.
* @param lng The longitude coordinate.
*/
function getLocationInfo(callback, lat, lng) {
var xhr = new XMLHttpRequest();
xhr.open("GET", util.format(
config.options.geourl,
lat,
lng,
blitzor.auth
), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var locInfo = {};
locInfo.town = "Unknown";
locInfo.country = "Unknown";
if (response.error != undefined && response.error.code == "008") {
if (response.suggestion != undefined) {
var north = response.suggestion.north;
var south = response.suggestion.south;
if (south != undefined && north != undefined && south.distance != undefined && north.distance != undefined) {
if (north.distance < south.distance) {
if (north.city != undefined)
locInfo.town = north.city;
if (north.prov != undefined)
locInfo.country = north.prov;
}
else {
if (south.city != undefined)
locInfo.town = south.city;
if (south.prov != undefined)
locInfo.country = south.prov;
}
}
else if (north != undefined && north.city != undefined) {
locInfo.town = north.city;
if (north.prov != undefined)
locInfo.country = north.prov;
}
else if (south != undefined && south.city != undefined) {
locInfo.town = south.city;
if (south.prov != undefined)
locInfo.country = south.prov;
}
}
}
else {
if (response.city != undefined)
locInfo.town = response.city;
if (response.prov != undefined)
locInfo.country = response.prov;
}
var locs = locInfo.town.split(" / ");
if (locs.length > 1)
locInfo.town = locs[1];
locInfo.town = toUpper(locInfo.town);
//console.log(response);
callback(locInfo);
}
}
xhr.send();
}
/*
* Calculates a realistic surface distance between two coordinate points on Earth.
* @param lat1 The starting latitude coordinate.
* @param lng1 The starting longitude coordinate.
* @param lat2 The ending latitude coordinate.
* @param lng2 The ending longitude coordinate.
* @return The distance in kilometers.
*/
function earthDistance(lat1, lng1, lat2, lng2) {
var R = 6371;
var dLat = degToRad(lat2-lat1);
var dLon = degToRad(lng2-lng1);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
/*
* Calculates a bearing towards a certain coordinate point on Earth.
* @param lat1 The standing latitude coordinate.
* @param lng1 The standing longitude coordinate.
* @param lat2 The targeted latitude coordinate.
* @param lng2 The targeted longitude coordinate.
* @return The angle in degrees.
*/
function earthBearing(lat1, lng1, lat2, lng2) {
var dLon = degToRad(lng2-lng1);
var y = Math.sin(dLon) * Math.cos(degToRad(lat2));
var x = Math.cos(degToRad(lat1)) * Math.sin(degToRad(lat2)) -
Math.sin(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
Math.cos(dLon);
var brng = radToDeg(Math.atan2(y, x));
return ((brng + 360) % 360);
}
/*
* Converts degrees to radians.
* @param deg Degree value.
* @return Radian value.
*/
function degToRad(deg) {
return deg * (Math.PI/180);
}
/*
* Converts radians to degrees.
* @param rad Radian value.
* @return Degree value.
*/
function radToDeg(rad) {
return rad * (180/Math.PI);
}
/******************************
* SEISMOGRAPH DATA PROCESSING
******************************/
/*
* Prepares the bandpass filter for processing seismographic data.
*/
function setupSeismoFilter() {
var firCalculator = new Fili.FirCoeffs();
var firFilterCoeffs = firCalculator.bandpass({
order: config.seismo.data.bandpass.order,
Fs: config.seismo.data.samplerate,
F1: config.seismo.data.bandpass.low,
F2: config.seismo.data.bandpass.high
});
seismoFilter = new Fili.FirFilter(firFilterCoeffs);
}
/*
* Calculates the median value of a data array.
* @param values An array of values.
* @return Median value.
*/
function median(values) {
if(values.length === 0) return 0;
values.sort(function(a, b) {
return a - b;
});
var half = Math.floor(values.length / 2);
if (values.length % 2)
return values[half];
return (values[half - 1] + values[half]) / 2.0;
}
/*
* Generates an emoji string for quake intensity.
* @param velocity The velocity value of the quake.
* @return A string of emojis representing quake intensity.
*/
function generateEmojigraph(velocity) {
var emojis = "";
var lowCnt = 0;
var mediumCnt = 0;
var highCnt = 0;
if (velocity < config.seismo.emojigraph.low.max) {
for (var i = 0; i < velocity; i += (config.seismo.emojigraph.low.max / config.seismo.emojigraph.low.seg))
lowCnt++;
}
else {
lowCnt = config.seismo.emojigraph.low.seg;
if (velocity < config.seismo.emojigraph.medium.max) {
var tempVelocity = velocity - config.seismo.emojigraph.low.max;
for (var i = 0; i < tempVelocity; i += ((config.seismo.emojigraph.medium.max - config.seismo.emojigraph.low.max) / config.seismo.emojigraph.medium.seg))
mediumCnt++;
}
else {
mediumCnt = config.seismo.emojigraph.medium.seg;
if (velocity < config.seismo.emojigraph.high.max) {
var tempVelocity = velocity - config.seismo.emojigraph.medium.max;
for (var i = 0; i < tempVelocity; i += ((config.seismo.emojigraph.high.max - config.seismo.emojigraph.medium.max) / config.seismo.emojigraph.high.seg))
highCnt++;
}
else {
highCnt = config.seismo.emojigraph.high.seg;
}
}
}
for (var i = 0; i < lowCnt; i++)
emojis += config.seismo.emojigraph.low.emoji;
for (var i = 0; i < mediumCnt; i++)
emojis += config.seismo.emojigraph.medium.emoji;
for (var i = 0; i < highCnt; i++)
emojis += config.seismo.emojigraph.high.emoji;
if (velocity >= config.seismo.emojigraph.high.max) {
emojis += config.seismo.emojigraph.overload;
}
return emojis;
}
/*
* Begins listening to the periodic UDP seismograph data.
*/
function startSeizmoServer() {
console.log(strings.debug.seismo.start);
setupSeismoFilter();
udpServer = dgram.createSocket("udp4");
udpServer.on("error", (err) => {
console.log("UDP Server Error:\n" + err.stack);
udpServer.close();
});
udpServer.on("message", (message, rinfo) => {
var now = new Date();
statusGlobal.maud = Math.floor(now / 1000);
seismoLatest = message.toString("utf8");
//console.log("server got: "+ seismoLatest + " from " + rinfo.address + ":" + rinfo.port);
if ((seismoReadyFilter && seismoSamplesBuf.length < config.seismo.data.samplerate) ||
(!seismoReadyFilter && seismoSamplesBuf.length < config.seismo.data.rampupsamples)) {
var sampleData = message.toString("utf8").replace("{", "").replace("}", "").split(", ");
for (var i = 2; i < sampleData.length; i++)
seismoSamplesBuf.push((parseInt(sampleData[i]) / config.seismo.data.normalization) * 1000);
}
if ((seismoReadyFilter && seismoSamplesBuf.length >= config.seismo.data.samplerate) ||
(!seismoReadyFilter && seismoSamplesBuf.length >= config.seismo.data.rampupsamples)) {
//var filteredSamples = seismoFilter.multiStep(seismoSamplesBuf);
var filtered = seismoFilter.multiStep(seismoSamplesBuf);
var stringSeismoRaw = "";
var stringSeismoFlt = "";
var stringSeismoMed = "";
if (config.seismo.outputfile) {
if (now.getMinutes() != seismoLastMinute) {
seismoLastMinute = now.getMinutes();
var outDate = moment.tz(now, "UTC");
stringSeismoRaw += outDate.format("YYYY-MM-DD") + " " + outDate.format("HH:mm:ss (z)") + ":\n";
stringSeismoFlt += outDate.format("YYYY-MM-DD") + " " + outDate.format("HH:mm:ss (z)") + ":\n";
stringSeismoMed += outDate.format("YYYY-MM-DD") + " " + outDate.format("HH:mm:ss (z)") + ":\n";
}
seismoSamplesBuf.forEach(function(s) {
stringSeismoRaw += s.toFixed(2) + "\n";
});
filtered.forEach(function(s) {
stringSeismoFlt += s.toFixed(2) + "\n";
});
}
seismoSamplesBuf = [];
filtered.forEach(function(s) {
seismoSamples.push(Math.pow(s, 2));
})
while(seismoSamples.length > config.seismo.data.sampletotal) {
seismoSamples.shift();
}
if (!seismoReadyEarthquake) {
if (seismoSampleCounter < config.seismo.data.sampletotal / config.seismo.data.samplerate) {
seismoSampleCounter++;
}
else {
seismoReadyEarthquake = true;
console.log(strings.debug.seismo.readye);
}
}
if (seismoReadyEarthquake) {
var samplesCopy = JSON.parse(JSON.stringify(seismoSamples));
sampleMedian = median(samplesCopy);
var nowS = Math.floor(now / 1000);
var velocity = Math.sqrt(sampleMedian);
//console.log("cnt: " + seismoSamples.length + " val: " + sampleMedian);
if (config.seismo.outputfile) {
stringSeismoMed += sampleMedian.toFixed(2) + "\n";
var outDate = moment.tz(now, "UTC");
fs.appendFile(util.format(
config.seismo.file,
outDate.format("YYYY-MM-DD"),
"raw"
), stringSeismoRaw, function (err) {
if (err)
throw err;
});
fs.appendFile(util.format(
config.seismo.file,
outDate.format("YYYY-MM-DD"),
"flt"
), stringSeismoFlt, function (err) {
if (err)
throw err;
});
fs.appendFile(util.format(
config.seismo.file,
outDate.format("YYYY-MM-DD"),
"med"
), stringSeismoMed, function (err) {
if (err)
throw err;
});
}
if (config.seismo.outputterm) {
console.log(velocity.toFixed(2) + " um/s");
}
if (!seismoIsShaking && !seismoIsQuake && velocity > config.seismo.detection.thresholdtrig) {
seismoIsShaking = true;
seismoQuakePrevTime = nowS;
seismoQuakeStartTimeTemp = nowS;
console.log(util.format(
strings.debug.seismo.qstartpr,
velocity.toFixed(2)
));
}
if (seismoIsShaking && !seismoIsQuake && velocity > config.seismo.detection.thresholdprel && nowS - seismoQuakePrevTime <= config.seismo.detection.wait) {
console.log(util.format(
strings.debug.seismo.qtickpr,
velocity.toFixed(2)
));
}
else if (seismoIsShaking && !seismoIsQuake && velocity > config.seismo.detection.thresholdprel && nowS - seismoQuakePrevTime > config.seismo.detection.wait) {
seismoIsQuake = true;
seismoQuakePrevTime = nowS;
seismoQuakeStartTime = seismoQuakeStartTimeTemp;
lastQuake = moment.tz(now, "UTC");
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.seismo.quake,
lastQuake.format("YYYY-MM-DD"),
lastQuake.format("HH:mm:ss (z)"),
generateEmojigraph(velocity),
velocity.toFixed(2)
), false);
console.log(util.format(
strings.debug.seismo.qstartrl,
velocity.toFixed(2)
));
}
if (seismoIsShaking && seismoIsQuake && velocity > config.seismo.detection.thresholdhold && nowS - seismoQuakePrevTime <= config.seismo.detection.hold) {
seismoQuakePrevTime = nowS;
seismoAccu.push(sampleMedian);
if (seismoAccu.length % config.seismo.detection.notice == 0) {
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.seismo.energy,
generateEmojigraph(velocity),
velocity.toFixed(2)
), false);
}
console.log(util.format(
strings.debug.seismo.qtickrl,
velocity.toFixed(2)
));
}
if (seismoIsShaking && seismoIsQuake && nowS - seismoQuakePrevTime > config.seismo.detection.hold) {
seismoIsShaking = false;
seismoIsQuake = false;
var diff = seismoQuakePrevTime - seismoQuakeStartTime + 1;
seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
minutes = Math.floor(diff % 60);
if (seconds < 10)
seconds = "0" + seconds;
var totalEnergy = 0;
seismoAccu.forEach(function(s) {
totalEnergy += s / seismoAccu.length;
});
seismoAccu.sort(function(a, b) {
return b - a;
});
var peakEnergy = seismoAccu[0];
seismoAccu = [];
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.seismo.end,
minutes,
seconds,
Math.sqrt(totalEnergy).toFixed(2),
totalEnergy.toFixed(2),
Math.sqrt(peakEnergy).toFixed(2),
peakEnergy.toFixed(2)
), false);
console.log(strings.debug.seismo.qendrl);
}
else if (seismoIsShaking && !seismoIsQuake && nowS - seismoQuakePrevTime > config.seismo.detection.hold) {
seismoIsShaking = false;
console.log(strings.debug.seismo.qendpr);
}
}
if (!seismoReadyFilter) {
seismoReadyFilter = true;
console.log(strings.debug.seismo.readyf);
}
}
});
udpServer.on("listening", () => {
const address = udpServer.address();
console.log(util.format(
strings.debug.seismo.done,
address.address,
address.port
));
});
udpServer.bind(config.seismo.udpPort);
}
/********************
* STATUS MONITORING
********************/
/*
* Periodically loops and checks status of various devices and components in the Lunar Infrastructure.
*/
function loopStatusPull() {
statusVariPass();
statusLuna();
statusChrysalis();
statusRarity();
statusFluttershy();
statusMoon();
statusTantabus();
setTimeout(loopStatusPull, config.options.statuspull * 1000);
}
/*
* Periodically loops and pushes status data to the status page.
*/
function loopStatusPush() {
var now = Math.floor((new Date()) / 1000);
var data = "";
data += generateStatus("luna_local", statusGlobal.luna_local, now);
data += generateStatus("luna_public", statusGlobal.luna_public, now);
data += generateStatus("chrysalis_file_local", statusGlobal.chrysalis_file_local, now);
data += generateStatus("chrysalis_file_public", statusGlobal.chrysalis_file_public, now);
data += generateStatus("chrysalis_icecast_local", statusGlobal.chrysalis_icecast_local, now);
data += generateStatus("chrysalis_icecast_public", statusGlobal.chrysalis_icecast_public, now);
data += generateStatus("chrysalis_ann", statusGlobal.chrysalis_ann, now);
data += generateStatus("pvfm", statusGlobal.pvfm, now);
data += generateStatus("overlay_np", statusGlobal.overlay_np, now);
data += generateStatus("overlay_lyrics", statusGlobal.overlay_lyrics, now);
data += generateStatus("overlay_storyart", statusGlobal.overlay_storyart, now);
data += generateStatus("exclaml", statusGlobal.exclaml, now);
data += generateStatus("rarity_local", statusGlobal.rarity_local, now);
data += generateStatus("rarity_public", statusGlobal.rarity_public, now);
data += generateStatus("fluttershy_local", statusGlobal.fluttershy_local, now);
data += generateStatus("moon_local", statusGlobal.moon_local, now);
data += generateStatus("raritush", statusGlobal.raritush, now);
data += generateStatus("tantabus_local", statusGlobal.tantabus_local, now);
data += generateStatus("tantabus_public", statusGlobal.tantabus_public, now);
data += generateStatus("varipass", statusGlobal.varipass, now);
data += generateStatus("celly", statusGlobal.celly, now);
data += generateStatus("chryssy", statusGlobal.chryssy, now);
data += generateStatus("dashie", statusGlobal.dashie, now);
data += generateStatus("unicorn", statusGlobal.unicorn, now);
data += generateStatus("twilight", statusGlobal.twilight, now);
data += generateStatus("tradfri", statusGlobal.tradfri, now);
data += generateStatus("sparkle", statusGlobal.sparkle, now);
data += generateStatus("maud", statusGlobal.maud, now);
data += generateStatus("lulu", statusGlobal.lulu, now);
var payload = {
"key": httpkey.key,
"data": data
};
var xhr = new XMLHttpRequest();
xhr.open("POST", config.status.api, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
//console.log("status ready state: " + xhr.readyState + " status: " + xhr.status);
if (xhr.readyState == 4)
if (xhr.status != 200 && xhr.status != 503) {
console.log(util.format(
strings.debug.status.error,
xhr.status
));
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.status.error,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.status.timeout);
xhr.abort();
}
xhr.send(JSON.stringify(payload));
setTimeout(loopStatusPush, config.options.statuspush * 1000);
}
/*
* Checks the status of Pricness Luna's API.
*/
function statusLuna() {
var url = util.format(
config.status.urls.luna_local,
httpkey.key
);
getStatus(url, statusTimeoutLunaLocal, function(r, s) {
if (s == 200)
if (r == config.status.responses.luna_local)
statusGlobal.luna_local = Math.floor((new Date()) / 1000);
});
url = util.format(
config.status.urls.luna_public,
httpkey.port,
httpkey.key
);
getStatus(url, statusTimeoutLunaPublic, function(r, s) {
if (s == 200)
if (r == config.status.responses.luna_public)
statusGlobal.luna_public = Math.floor((new Date()) / 1000);
});
}
/*
* Checks the status of Queen Chrysalis.
*/
function statusChrysalis() {
getStatus(config.status.urls.chrysalis_file_local, statusTimeoutChrysalisFileLocal, function(r, s) {
if (r == config.status.responses.chrysalis_file_local)
statusGlobal.chrysalis_file_local = Math.floor((new Date()) / 1000);
});
getStatus(config.status.urls.chrysalis_file_public, statusTimeoutChrysalisFilePublic, function(r, s) {
if (r == config.status.responses.chrysalis_file_public)
statusGlobal.chrysalis_file_public = Math.floor((new Date()) / 1000);
});
getStatus(config.status.urls.chrysalis_icecast_local, statusTimeoutChrysalisIcecastLocal, function(r, s) {
if (s == 200)
if (JSON.parse(r)[config.status.responses.chrysalis_icecast_local] != undefined)
statusGlobal.chrysalis_icecast_local = Math.floor((new Date()) / 1000);
});
getStatus(config.status.urls.chrysalis_icecast_public, statusTimeoutChrysalisIcecastPublic, function(r, s) {
if (s == 200)
if (JSON.parse(r)[config.status.responses.chrysalis_icecast_public] != undefined)
statusGlobal.chrysalis_icecast_public = Math.floor((new Date()) / 1000);
});
var url = util.format(
config.status.urls.chrysalis_ann,
httpkey.key
);
getStatus(url, statusTimeoutChrysalisAnn, function(r, s) {
if (s == 200)
if (r == config.status.responses.chrysalis_ann)
statusGlobal.chrysalis_ann = Math.floor((new Date()) / 1000);
});
}
/*
* Checks the status of Nightmare Rarity.
*/
function statusRarity() {
getStatus(config.status.urls.rarity_local, statusTimeoutRarityLocal, function(r, s) {
if (r == config.status.responses.rarity_local)
statusGlobal.rarity_local = Math.floor((new Date()) / 1000);
});
getStatus(printer.baseurl + config.status.urls.rarity_public, statusTimeoutRarityPublic, function(r, s) {
if (r == config.status.responses.rarity_public)
statusGlobal.rarity_public = Math.floor((new Date()) / 1000);
});
}
/*
* Checks the status of Nightmare Fluttershy.
*/
function statusFluttershy() {
getStatus(config.status.simple.fluttershy_local, statusTimeoutFluttershyLocal, function(r, s) {
if (s == 200)
statusGlobal.fluttershy_local = Math.floor((new Date()) / 1000);
});
}
/*
* Checks the status of Nightmare Moon.
*/
function statusMoon() {
getStatus(config.status.simple.moon_local, statusTimeoutMoonLocal, function(r, s) {
if (s == 200)
statusGlobal.moon_local = Math.floor((new Date()) / 1000);
});
}
/*
* Checks the status of Tantabus.
*/
function statusTantabus() {
getStatus(config.status.urls.tantabus_local, statusTimeoutTantabusLocal, function(r, s) {
if (r == config.status.responses.tantabus_local)
statusGlobal.tantabus_local = Math.floor((new Date()) / 1000);
});
getStatus(config.status.urls.tantabus_public, statusTimeoutTantabusPublic, function(r, s) {
if (r == config.status.responses.tantabus_public)
statusGlobal.tantabus_public = Math.floor((new Date()) / 1000);
});
}
/*
* Fetches the status of a device using REST API.
* @param url URL to connect to.
* @param timeout The timeout object to use.
* @param callback Callback function called once processing is done.
*/
function getStatus(url, timeout, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//console.log("Url: " + url);
//console.log(" status: " + xhr.status + " text: " + xhr.responseText);
callback(xhr.responseText, xhr.status);
clearTimeout(timeout);
}
}
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.status.error,
err.target.status
));
xhr.abort();
}
xhr.ontimeout = function() {
console.log(strings.debug.status.timeout);
xhr.abort();
}
xhr.send();
timeout = setTimeout(function() {
xhr.abort();
}, config.status.timeout * 1000);
}
/*
* Generates a status value string.
* @param key Key of the status.
* @param val Response timestamp to use.
* @param now Current timestamp to use.
* @return The formatted string.
*/
function generateStatus(key, val, now) {
var value;
if (val == undefined)
value = "undefined";
else
value = (now - val).toString();
return key + ":" + value + ",";
}
/**************************
* MISCELLANEOUS FUNCTIONS
**************************/
/*
* Processes the change to now plying data.
*/
function processNowPlayingChange() {
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
if (np.nowplaying != undefined) {
if (story[np.nowplaying] != undefined) {
// Post story
send(n, story[np.nowplaying], true);
// Post art
if (art[np.nowplaying] != undefined) {
setTimeout(function() {
var parts = art[np.nowplaying].split(".");
var artimg = util.format(
config.options.artimg,
n,
parts[parts.length-1]
);
download(art[np.nowplaying], artimg, function() {
console.log(strings.debug.download.stop);
embed(n, "", artimg, np.nowplaying + "." + parts[parts.length-1], true, true);
}, function() {
}, 0);
}, config.options.nptstoryart * 1000);
}
// Post track name with delay
setTimeout(function() {
send(n, util.format(
strings.announcements.nowplaying,
np.nowplaying
), true);
}, config.options.nptstorytrack * 1000);
}
else {
// Post track name normally
send(n, util.format(
strings.announcements.nowplaying,
np.nowplaying
), true);
// Post art
if (art[np.nowplaying] != undefined) {
setTimeout(function() {
var parts = art[np.nowplaying].split(".");
var artimg = util.format(
config.options.artimg,
n,
parts[parts.length-1]
);
download(art[np.nowplaying], artimg, function() {
console.log(strings.debug.download.stop);
embed(n, "", artimg, np.nowplaying + "." + parts[parts.length-1], true, true);
}, function() {
}, 0);
}, config.options.nptstoryart * 1000);
}
}
}
else
send(n, strings.announcements.nperror, true);
});
if (np.nowplaying != undefined) {
if (story[np.nowplaying] != undefined) {
// Show story
isShowingStory = true;
// Show art
if (art[np.nowplaying] != undefined) {
setTimeout(function() {
isShowingArt = true;
}, config.options.nptstoryart * 1000);
}
// Show track name with delay
setTimeout(function() {
npover = JSON.parse(JSON.stringify(np));
}, config.options.nptstorytrack * 1000);
}
else {
// Show track name normally
npover = JSON.parse(JSON.stringify(np));
// Show art
if (art[np.nowplaying] != undefined) {
setTimeout(function() {
isShowingArt = true;
}, config.options.nptstoryart * 1000);
}
}
}
else
send(n, strings.announcements.nperror, true);
}
/*
* Loops to continuously retrieve now playing data.
*/
function loopNowPlaying() {
if (!nppaused) {
var xhr = new XMLHttpRequest();
xhr.open("GET", config.nowplaying.url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response
try {
response = JSON.parse(xhr.responseText);
}
catch(error) {
}
statusGlobal.pvfm = Math.floor((new Date()) / 1000);
if (
response != undefined &&
response.icestats != undefined &&
response.icestats.source != undefined
) {
if (npradio == undefined || npradio.title != response.icestats.source.title || npradio.artist != response.icestats.source.artist) {
npradio = JSON.parse(xhr.responseText).icestats.source;
isShowingLyrics = false;
if (npradio.artist != undefined)
npradio.nowplaying = npradio.artist + config.separators.track + npradio.title;
else
npradio.nowplaying = npradio.title;
np = JSON.parse(xhr.responseText).icestats.source;
if (np.artist != undefined)
np.nowplaying = np.artist + config.separators.track + np.title;
else
np.nowplaying = np.title;
if (npstarted)
processNowPlayingChange();
else
npstarted = true;
}
}
}
}
xhr.send();
}
setTimeout(loopNowPlaying, config.nowplaying.timeout * 1000);
}
/*
* Loops to continuously retrieve corona data.
*/
function loopCorona() {
if (config.corona.enabled) {
var xhrTotal = new XMLHttpRequest();
xhrTotal.open("GET", config.corona.urls.total, true);
xhrTotal.onreadystatechange = function () {
if (xhrTotal.readyState == 4 && xhrTotal.status == 200) {
var response;
try {
response = JSON.parse(xhrTotal.responseText);
}
catch(error) {
}
if (response != undefined) {
var dateNew = response[0].Datum;
if (dateNew.trim() != corona.dateTotal.trim()) {
corona.dateTotal = dateNew;
fs.writeFileSync(config.corona.path, JSON.stringify(corona), "utf-8");
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.corona.total,
response[0].Datum,
response[0].SlucajeviHrvatska - response[1].SlucajeviHrvatska,
response[0].IzlijeceniHrvatska - response[1].IzlijeceniHrvatska,
response[0].UmrliHrvatska - response[1].UmrliHrvatska
), true);
}
}
}
}
xhrTotal.send();
var xhrCounty = new XMLHttpRequest();
xhrCounty.open("GET", config.corona.urls.county, true);
xhrCounty.onreadystatechange = function () {
if (xhrCounty.readyState == 4 && xhrCounty.status == 200) {
var response;
try {
response = JSON.parse(xhrCounty.responseText);
}
catch(error) {
}
if (response != undefined) {
var dateNew = response[0].Datum;
if (dateNew.trim() != corona.dateCounty.trim()) {
corona.dateCounty = dateNew;
fs.writeFileSync(config.corona.path, JSON.stringify(corona), "utf-8");
var infectedNew;
var infectedOld;
var diedNew;
var diedOld;
response[0].PodaciDetaljno.forEach(function (c) {
if (c.Zupanija.trim() == config.corona.county.trim()) {
infectedNew = c.broj_zarazenih;
diedNew = c.broj_umrlih;
}
});
response[1].PodaciDetaljno.forEach(function (c) {
if (c.Zupanija.trim() == config.corona.county.trim()) {
infectedOld = c.broj_zarazenih;
diedOld = c.broj_umrlih;
}
});
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.corona.county,
config.corona.county,
response[0].Datum,
infectedNew - infectedOld,
diedNew - diedOld
), true);
}
}
}
}
xhrCounty.send();
}
setTimeout(loopCorona, config.corona.timeout * 1000);
}
/*
* Reloads the configuration.
*/
function reloadConfig() {
token = JSON.parse(fs.readFileSync(config.options.configpath + "token.json", "utf8"));
config = JSON.parse(fs.readFileSync(config.options.configpath + "config.json", "utf8"));
commands = JSON.parse(fs.readFileSync(config.options.configpath + "commands.json", "utf8"));
custom = JSON.parse(fs.readFileSync(config.options.configpath + "custom.json", "utf8"));
strings = JSON.parse(fs.readFileSync(config.options.configpath + "strings.json", "utf8"));
gotn = JSON.parse(fs.readFileSync(config.options.configpath + "gotn.json", "utf8"));
mlp = JSON.parse(fs.readFileSync(config.options.configpath + "mlp.json", "utf8"));
channels = JSON.parse(fs.readFileSync(config.options.configpath + "channels.json", "utf8"));
varipass = JSON.parse(fs.readFileSync(config.options.configpath + "varipass.json", "utf8"));
printer = JSON.parse(fs.readFileSync(config.options.configpath + "printer.json", "utf8"));
dtls = JSON.parse(fs.readFileSync(config.options.configpath + "dtls.json", "utf8"));
tradfri = JSON.parse(fs.readFileSync(config.options.configpath + "tradfri.json", "utf8"));
schedule = JSON.parse(fs.readFileSync(config.options.configpath + "schedule.json", "utf8"));
httpkey = JSON.parse(fs.readFileSync(config.options.configpath + "httpkey.json", "utf8"));
mac = JSON.parse(fs.readFileSync(config.options.configpath + "mac.json", "utf8"));
blitzor = JSON.parse(fs.readFileSync(config.options.configpath + "blitzor.json", "utf8"));
thori = JSON.parse(fs.readFileSync(config.options.configpath + "thori.json", "utf8"));
devices = JSON.parse(fs.readFileSync(config.options.configpath + "devices.json", "utf8"));
reactrole = JSON.parse(fs.readFileSync(config.options.configpath + "reactrole.json", "utf8"));
moon = JSON.parse(fs.readFileSync(config.moon.lunamoon.pathdata, "utf8"));
clearTimeout(lightningReconnect);
blitzorws.close();
if (lightningRange > blitzor.range) {
lightningRange = blitzor.range;
lightningNew = blitzor.range;
}
connectBlitzortung(false);
if (isChasing) {
clearTimeout(chaseReconnect);
chasews.close();
if (chaseRange > blitzor.range) {
chaseRange = blitzor.range;
chaseNew = blitzor.range;
}
connectChase(false);
}
prepareReactroleMessages();
}
/*
* Saves EEG data to a CSV file.
*/
function saveEEG() {
var file;
if (eegTable.length > 0) {
file = fs.createWriteStream(config.eeg.basicpath);
file.on("error", function(err) {
console.log(util.format(
strings.debug.eegerror,
err
));
return;
});
file.write(strings.misc.eeg.basic.title, "utf-8");
eegTable.forEach(function(e) {
file.write(util.format(
strings.misc.eeg.basic.values,
e.time,
e.battery,
e.signal
), "utf-8");
});
file.end();
var file = fs.createWriteStream(config.eeg.rawpath);
file.on("error", function(err) {
console.log(util.format(
strings.debug.eegerror,
err
));
return;
});
file.write(strings.misc.eeg.raw.title, "utf-8");
eegTable.forEach(function(e) {
file.write(util.format(
strings.misc.eeg.raw.values,
e.time,
e.attention,
e.meditation,
e.waves[0],
e.waves[1],
e.waves[2],
e.waves[3],
e.waves[4],
e.waves[5],
e.waves[6],
e.waves[7],
e.sumlow,
e.sumhigh
), "utf-8");
});
file.end();
}
if (eegTableEMA.length > 0) {
var file = fs.createWriteStream(config.eeg.emapath);
file.on("error", function(err) {
console.log(util.format(
strings.debug.eegerror,
err
));
return;
});
file.write(strings.misc.eeg.ema.title, "utf-8");
eegTableEMA.forEach(function(e) {
file.write(util.format(
strings.misc.eeg.ema.values,
e.time,
e.attention,
e.meditation,
e.waves[0],
e.waves[1],
e.waves[2],
e.waves[3],
e.waves[4],
e.waves[5],
e.waves[6],
e.waves[7],
e.sumlow,
e.sumhigh
), "utf-8");
});
file.end();
}
}
/*
* Performs a seizure induced reboot.
* @param channelID Channel ID where the seizure happened.
* @param userID User ID who caused the seizure.
* @param message Message which caused the seizure.
*/
function seizureReboot(channelID, userID, message) {
rebooting = true;
Object.keys(nptoggles).forEach(function(n, i) {
if (nptoggles[n])
send(n, strings.announcements.npreboot, true);
});
send(channelNameToID(config.options.channels.debug), util.format(
strings.announcements.seizure.debug,
channelIDToName(channelID),
message
), false);
send(channelID, util.format(
strings.announcements.seizure.reply,
mention(userID)
), false);
var seizure = {};
seizure.channel = channelID;
seizure.user = userID;
fs.writeFileSync(config.options.seizurepath, JSON.stringify(seizure), "utf-8");
saveAllBrains();
blitzorws.close();
setTimeout(function() {
console.log(strings.debug.stopped);
process.exit();
}, config.options.reboottime * 1000);
}
/*
* h
* @param channelID h
*/
function h(channelID) {
if (hTrack[channelID] == undefined) {
hTrack[channelID] = moment();
setTimeout(function() {
send(channelID, strings.misc.h, true);
}, config.options.hmessage * 1000);
}
else if (moment() - hTrack[channelID] >= config.options.htimeout * 1000) {
hTrack[channelID] = moment();
setTimeout(function() {
send(channelID, strings.misc.h, true);
}, config.options.hmessage * 1000);
}
else {
hTrack[channelID] = moment();
}
}
/*
* Generates time for upcoming Faction Assault.
* @param region Region to return the assault time for.
* @return Time of the assault, as moment.
*/
function getAssault(region) {
var countDownDate = moment(1000 * config.wow.assault.regions[region]);
for (var o = moment(), n = countDownDate - o, r = countDownDate; n < 0;) {
//console.log((r + 0) / 1000);
n = (r = r.clone().add(19, "hours")) - o;
}
return r.clone();
}
/*
* Prepares an assult announcement.
*/
function prepareAssaultAnnounce() {
var dueTime = new Date(getAssault("EU"));
var job = new CronJob(dueTime, function() {
setTimeout(function() {
send(channelNameToID(config.options.channels.home), util.format(
strings.announcements.wow.assault,
getTimeLeft((new Date()) - 2000, new Date(getAssault("EU")), "CET")
), true);
prepareAssaultAnnounce();
}, 1000);
}, function () {}, true);
console.log(util.format(
strings.debug.assaults.date,
dueTime
));
}
/*
* Generates time for upcoming daily average procedure.
* @return Time of the procedure, as moment.
*/
function getDailyAvgTime() {
var partsTime = config.options.dailyavg.split(config.separators.time);
var parseDate = new Date();
parseDate.setHours(partsTime[0]);
parseDate.setMinutes(partsTime[1]);
parseDate.setSeconds(0);
parseDate.setMilliseconds(0);
var countDownDate = moment(parseDate);
for (var o = moment(), n = countDownDate - o, r = countDownDate; n < 0;) {
//console.log((r + 0) / 1000);
n = (r = r.clone().add(24, "hours")) - o;
}
return r.clone();
}
/*
* Prepares a daily average procedure.
*/
function prepareDailyAvg() {
var dueTime = new Date(getDailyAvgTime());
var job = new CronJob(dueTime, function() {
avgVariPass();
setTimeout(function() {
prepareDailyAvg();
}, 1000);
}, function () {}, true);
console.log(util.format(
strings.debug.dailyavg.date,
dueTime
));
}
/*
* Pauses the Octoprint job.
* @param retry Number of times to retry the command if connection fails.
*/
function pausePrint(retry) {
if (retry > 0) {
var payload = {
"command": "pause",
"action": "pause"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", printer.baseurl + config.printer.urls.job + printer.key, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onerror = function(err) {
console.log(util.format(
strings.debug.printer.error,
retry - 1
));
xhr.abort();
pausePrint(retry - 1);
}
xhr.ontimeout = function() {
console.log(util.format(
strings.debug.printer.error,
retry - 1
));
xhr.abort();
pausePrint(retry - 1);
}
xhr.send(JSON.stringify(payload));
}
}
/*
* Called when print is detected as finished. May also be called on cancelled.
*/
function finishPrint() {
console.log(strings.debug.printer.rampC);
var dateNow = Math.floor((new Date()) / 1000);
var diff = dateNow - tushStart;
var time = {};
time.seconds = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.minutes = Math.floor(diff % 60);
diff = Math.floor(diff / 60);
time.hours = Math.floor(diff % 24);
time.days = Math.floor(diff / 24);
send(channelNameToID(config.options.channels.printer), util.format(
strings.announcements.tush.finish,
mention(config.options.adminid),
getTimeString(time),
time.seconds
), false);
download(printer.baseurl + printer.webcam, config.printer.webimg, function(code) {
if (code != 503)
embed(channelNameToID(config.options.channels.printer), "", config.printer.webimg, "Nightmare Rarity Webcam.jpg", false, true);
else
send(channelNameToID(config.options.channels.printer), strings.announcements.tush.error, false);
}, function() {
send(channelNameToID(config.options.channels.printer), strings.announcements.tush.error, false);
}, 0);
}
/*
* Downloads a file from the web.
* @param uri URL to the file to download.
* @param filename Path to location where file will be saved.
* @param callback Callback function to call once done.
*/
var download = function(uri, filename, callbackDone, callbackErr, count, useJson = true) {
if (count < config.options.downloadtry) {
request.head(uri, function(err, res, body) {
console.log(util.format(
strings.debug.download.start,
uri
));
if (useJson)
request({
"method": "GET",
"rejectUnauthorized": false,
"url": uri,
"headers" : {"Content-Type": "application/json"},
function(err,data,body) {}
}).on("error", function(err) {
count++;
console.log(util.format(
strings.debug.download.error,
err
));
download(uri, filename, callbackDone, callbackErr, count);
}).pipe(fs.createWriteStream(filename)).on("close", callbackDone);
else
request({
"method": "GET",
"rejectUnauthorized": false,
"url": uri,
function(err,data,body) {}
}).on("error", function(err) {
count++;
console.log(util.format(
strings.debug.download.error,
err
));
download(uri, filename, callbackDone, callbackErr, count);
}).pipe(fs.createWriteStream(filename)).on("close", function() {
callbackDone(response.statusCode);
});
});
}
else {
callbackErr();
}
};
// Start the bot.
startupProcedure(); | mit |
xenserver/openpegasus | pegasus/src/SDK/samples/Clients/DefaultC++/EnumInstances/EnumInstances.cpp | 3390 | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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 <Pegasus/Common/Config.h>
#include <Pegasus/Client/CIMClient.h>
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;
int main(int argc, char** argv)
{
const CIMNamespaceName NAMESPACE =
CIMNamespaceName("SDKExamples/DefaultCXX");
const CIMName CLASSNAME = CIMName("Sample_InstanceProviderClass");
try
{
Boolean deepInheritance = true;
Boolean localOnly = true;
Boolean includeQualifiers = false;
Boolean includeClassOrigin = false;
Array<CIMInstance> cimInstances;
CIMClient client;
//
// The connectLocal Client API creates a connection to the server for
// local clients. The connection is automatically authenticated
// for the current user. The connect Client API, can be used to create
// an HTTP connection with the server defined by the URL in address.
// User name and Password information can be passed
// using the connect Client API.
//
client.connectLocal();
//
// Enumerate Instances.
//
cimInstances = client.enumerateInstances(
NAMESPACE,
CLASSNAME,
deepInheritance,
localOnly,
includeQualifiers,
includeClassOrigin);
cout << "Total Number of Instances: " << cimInstances.size() << endl;
}
catch (Exception& e)
{
cerr << "Error: " << e.getMessage() << endl;
exit(1);
}
return 0;
}
| mit |
yogeshchaudhari16991/MainGAIDS | src/IDS/packetReport.java | 20326 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* packetReport.java
*
* Created on Mar 15, 2012, 7:27:39 PM
*/
package IDS;
import FTPServer.DatabaseConnection;
import FTPServer.DatePicker;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
*
* @author Inbo
*/
public class packetReport extends javax.swing.JFrame implements Observer{
Vector data = new Vector();
Vector heading = new Vector();
DatabaseConnection db;
ResultSet rs;
String text="";
/** Creates new form packetReport */
public packetReport() {
initComponents();
db = new DatabaseConnection();
db.dbconnection();
String co="#FFFD66";
Color color=Color.decode(co);
packettable.getTableHeader().setBackground(color);
packettable.getTableHeader().setForeground(Color.magenta);
packettable.getTableHeader().setFont(new Font("Lucida Bright", Font.BOLD, 20));
setLocationRelativeTo(null);
setTitle("Packet Report");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
packettable.setAutoResizeMode(packettable.AUTO_RESIZE_OFF);
packettable.getColumnModel().getColumn(0).setPreferredWidth(100);
packettable.getColumnModel().getColumn(1).setPreferredWidth(200);
packettable.getColumnModel().getColumn(2).setPreferredWidth(200);
packettable.getColumnModel().getColumn(3).setPreferredWidth(180);
packettable.getColumnModel().getColumn(4).setPreferredWidth(110);
heading.add("Protocol");
heading.add("Destination IP");
heading.add("Source IP");
heading.add("Status");
heading.add("Date");
}
/** 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() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtFrom = new javax.swing.JTextField();
txtTo = new javax.swing.JTextField();
cmbstatus = new javax.swing.JComboBox();
btnFrom = new javax.swing.JButton();
btnTo = new javax.swing.JButton();
btnSearch = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
packettable = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel1.setFont(new java.awt.Font("Lucida Bright", 1, 14));
jLabel1.setText("From Date");
jLabel2.setFont(new java.awt.Font("Lucida Bright", 1, 14));
jLabel2.setText("Satus");
jLabel3.setFont(new java.awt.Font("Lucida Bright", 1, 14));
jLabel3.setText("To Date");
txtFrom.setEditable(false);
txtFrom.setFont(new java.awt.Font("Lucida Bright", 1, 14));
txtTo.setEditable(false);
txtTo.setFont(new java.awt.Font("Lucida Bright", 1, 14));
cmbstatus.setFont(new java.awt.Font("Lucida Bright", 1, 14));
cmbstatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select...", "Allowed", "Blocked" }));
btnFrom.setFont(new java.awt.Font("Lucida Bright", 1, 14));
try{
btnFrom.setIcon(new ImageIcon(new File("").getCanonicalPath() + "/images/calendar.gif"));
}
catch(Exception e){
e.printStackTrace();
}
btnFrom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFromActionPerformed(evt);
}
});
btnTo.setFont(new java.awt.Font("Lucida Bright", 1, 14));
try{
btnTo.setIcon(new ImageIcon(new File("").getCanonicalPath() + "/images/calendar.gif"));
}
catch(Exception e){
e.printStackTrace();
}
btnTo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnToActionPerformed(evt);
}
});
btnSearch.setFont(new java.awt.Font("Lucida Bright", 1, 14));
btnSearch.setText("Search");
btnSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSearchActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jLabel1)
.addGap(12, 12, 12)
.addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addGap(18, 18, 18))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cmbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(117, 117, 117)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnTo, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(190, 190, 190))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnTo, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(45, 45, 45)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26))
);
packettable.setFont(new java.awt.Font("Lucida Bright", 1, 14));
packettable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Protocol", "Destination IP", "Source IP", "Status", "Date"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
packettable.setRowHeight(20);
packettable.setSelectionBackground(new java.awt.Color(255, 204, 0));
packettable.setSelectionForeground(new java.awt.Color(0, 0, 0));
jScrollPane1.setViewportView(packettable);
jButton1.setFont(new java.awt.Font("Lucida Bright", 1, 14));
jButton1.setText("Close");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(712, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 793, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnFromActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFromActionPerformed
// TODO add your handling code here:
// DatePicker.str = "from";
// dd = new DateDialog(this, true);
// dd.setVisible(true);
DatePicker dp = new DatePicker(this, new Date());
// previously selected date
Date selectedDate = dp.parseDate(txtFrom.getText());
dp.setSelectedDate(selectedDate);
dp.start(txtFrom);
text = "from";
}//GEN-LAST:event_btnFromActionPerformed
private void btnToActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToActionPerformed
// TODO add your handling code here:
if (!txtFrom.equals("")) {
// instantiate the DatePicker
DatePicker dp = new DatePicker(this, new Date());
// previously selected date
Date selectedDate = dp.parseDate(txtTo.getText());
dp.setSelectedDate(selectedDate);
dp.start(txtTo);
text="to";
}
}//GEN-LAST:event_btnToActionPerformed
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
// TODO add your handling code here:
report();
}//GEN-LAST:event_btnSearchActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
public void report() {
try {
String from=txtFrom.getText();
String to=txtTo.getText();
System.out.println("From : "+from);
System.out.println("To : "+to);
packettable.removeAll();
data = new Vector();
String query = "";
System.err.println();
if ((txtFrom.getText().equals("") && cmbstatus.getSelectedItem().toString().equals("Select...")) || (txtTo.getText().equals("") && cmbstatus.getSelectedItem().toString().equals("Select..."))) {
JOptionPane.showMessageDialog(this, "Please Select Search Criteria");
}
if (!txtFrom.getText().equals("") && !txtTo.getText().equals("") && cmbstatus.getSelectedItem().equals("Select...")) {
query = "select * from packets where date between '" + txtFrom.getText() + "' and '" + txtTo.getText() + "'";
}
if (txtFrom.getText().equals("") || txtTo.getText().equals("") && !cmbstatus.getSelectedItem().equals("Select...")) {
query = "select * from packets where status like '" + cmbstatus.getSelectedItem().toString() + "%'";
}
if (!txtFrom.getText().equals("") && !txtTo.getText().equals("") && !cmbstatus.getSelectedItem().equals("Select...")) {
query = "select * from packets where date between '" + txtFrom.getText() + "' and '" + txtTo.getText() + "' and status like '" + cmbstatus.getSelectedItem().toString() + "%'";
}
rs = db.getResultSet(query);
Vector temp;
while (rs.next()) {
temp = new Vector();
temp.add(rs.getString(1));
temp.add(rs.getString(2));
temp.add(rs.getString(3));
temp.add(rs.getString(4));
temp.add(rs.getString(5));
data.add(temp);
}
packettable.setModel(new javax.swing.table.DefaultTableModel(data, heading));
packettable.setAutoResizeMode(packettable.AUTO_RESIZE_OFF);
packettable.getColumnModel().getColumn(0).setPreferredWidth(100);
packettable.getColumnModel().getColumn(1).setPreferredWidth(200);
packettable.getColumnModel().getColumn(2).setPreferredWidth(200);
packettable.getColumnModel().getColumn(3).setPreferredWidth(180);
packettable.getColumnModel().getColumn(4).setPreferredWidth(110);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @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(packetReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(packetReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(packetReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(packetReport.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 packetReport().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnFrom;
private javax.swing.JButton btnSearch;
private javax.swing.JButton btnTo;
private javax.swing.JComboBox cmbstatus;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable packettable;
public static javax.swing.JTextField txtFrom;
public static javax.swing.JTextField txtTo;
// End of variables declaration//GEN-END:variables
public void update(Observable o, Object arg) {
//update method
Calendar calendar = (Calendar) arg;
DatePicker dp = (DatePicker) o;
// System.out.println("picked=" + dp.formatDate(calendar));
if (text.equals("from")) {
txtFrom.setText(dp.formatDate(calendar, "yyyy-MM-dd"));
//Query = Query + " bookingdate between #" + txtFrom.getText() + "# and ";
}
if (text.equals("to")) {
txtTo.setText(dp.formatDate(calendar, "yyyy-MM-dd"));
//Query = Query + " #" + txtTo.getText() + "# ";
}
}
}
| mit |
wmira/react-icons-kit | src/md/ic_star_half_outline.js | 350 | export const ic_star_half_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4V6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"},"children":[]}]}; | mit |
pyxis0810/onepy | src/actions/index.js | 401 | export const PENDING = '_PENDING';
export const REJECTED = '_REJECTED';
export const FULFILLED = '_FULFILLED';
export const GET_LOCALE = 'GET_LOCALE';
export const locale = require('./locale');
export const GET_BLOG = 'GET_BLOG';
export const blog = require('./blog');
export const GET_INSTAGRAM = 'GET_INSTAGRAM';
export const instagram = require('./instagram');
export const baseUrl = '/apis';
| mit |
chelnak/BotStats | run.py | 75 | #!venv/bin/python
from app import app
app.run(debug=True, host='0.0.0.0')
| mit |
JohnLambe/JLCSUtils | JLCSUtils/MvpFramework/GridAttributes.cs | 6005 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JohnLambe.Util.Reflection;
using JohnLambe.Util.Validation;
using System.Reflection;
using JohnLambe.Util.Exceptions;
namespace MvpFramework
{
/// <summary>
/// Attributes for building queryies for the attributes class,
/// and/or specifying a tabular layout.
/// </summary>
public abstract class GridAttribute : Attribute, IFilteredAttribute
{
/// <summary>
/// Set to false to effectively remove the attribute for the specified Filter values.
/// </summary>
public virtual bool Enabled { get; set; } = true;
/// <summary>
/// Specifies which views/grids etc. these settings apply to.
/// </summary>
public virtual string[] Filter { get; set; }
/// <summary>
/// Sorting order.
/// e.g. Columns of a grid are sorted (in the text reading direction (left to right for English)) in ascending order of this value.
/// </summary>
public virtual int Order { get; set; }
}
/// <summary>
/// Controls the display of the attributed property in tabular views / reports / grids.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class ColumnDisplayAttribute : GridAttribute
{
/// <summary>
/// Human-readable caption (e.g. column title) for the attributed item.
/// </summary>
public virtual string DisplayName { get; set; } // ? Could use DataAnnotations instead.
/// <summary>
/// The width of the column etc. for the attributed item.
/// </summary>
public virtual int DisplayWidth { get; set; } = -1;
public virtual int DisplayMinimumWidth { get; set; } = -1;
public virtual int DisplayMaximumWidth { get; set; } = -1;
[PercentageValidation]
public virtual decimal DisplayWidthPercentage { get; set; } = -1;
/// <summary>
/// True iff this item should be shown in the grid.
/// </summary>
public virtual bool Visible { get; set; } = true;
#region UI capabilities
/// <summary>
/// The UI should allow sorting on this field.
/// </summary>
public virtual bool AllowSorting { get; set; }
/// <summary>
/// The UI should allow filtering on this field.
/// </summary>
public virtual bool AllowFiltering { get; set; }
#endregion
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ColumnFilterBaseAttribute : GridAttribute
{
public abstract bool TestFilter<T>(T value);
}
public class ColumnFilterAttribute : ColumnFilterBaseAttribute
{
public virtual object MinimumValue { get; set; }
public virtual object MaximumValue { get; set; }
/// <summary>
/// If > "", filters to values beginning with this string (based on the result of <see cref="object.ToString"/> of the value).
/// </summary>
public virtual string StartsWith { get; set; }
/// <summary>
/// Iff true, the filter condition is negated.
/// </summary>
public virtual bool Not { get; set; } = false;
public virtual object Value
{
get
{
return MinimumValue;
}
set
{
MinimumValue = value;
MaximumValue = value;
}
}
public override bool TestFilter<T>(T value)
{
if (value == null)
return true;
IComparable valueComparable = value as IComparable;
if (valueComparable == null)
throw new InternalErrorException("Invalid value for " + GetType().Name + ": " + value.GetType());
return (MinimumValue != null && valueComparable.CompareTo(MinimumValue) >= 0)
&& (MaximumValue != null && valueComparable.CompareTo(MaximumValue) <= 0);
}
}
/// <summary>
/// Specifies a sorting order.
/// <para>
/// Multiple instance of this attributing the same item are allowed to support different Filter values. Multiple attributes with the same Filter value is invalid.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class SortOrderAttribute : GridAttribute
{
public SortOrderAttribute(SortDirection direction = SortDirection.Ascending, int order = 0)
{
this.Direction = direction;
this.Order = order;
}
/// <summary>
/// Whether sorting on the attributed item is ascending or descending.
/// <para>This can be set to <see cref="SortDirection.None"/> to override an attribute on a superclass
/// and cause the item to not be included in the sorting order.</para>
/// </summary>
public virtual SortDirection Direction { get; set; }
//| Using SortDirection.None here is redundant. Enabled=false would do the same.
/*
/// <summary>
/// For sorting on multiple columns/properties, this determines what order they are applied in - the lowest value is the major order.
/// </summary>
public virtual int Order { get; set; }
*/
}
public enum SortDirection
{
/// <summary>
/// Don't sort on this item.
/// </summary>
None,
/// <summary>
/// Sort in ascending order.
/// </summary>
Ascending,
/// <summary>
/// Sort in descending order.
/// </summary>
Descending
}
//TODO: Filtering.
//TODO: Use methods to dynamically generate parts of the query.
//| Attribute on class for Report/View -level settings ?
}
| mit |
RyFry/leagueofdowning | app/database/database.py | 12564 | from sqlalchemy import Column, Integer, String, Float, ForeignKey, Table
from sqlalchemy import create_engine, insert, update
from sqlalchemy.sql import text
from sqlalchemy.orm import relationship, sessionmaker, backref
from sqlalchemy.ext.declarative import declarative_base
import json
from pprint import pprint
Base = declarative_base()
champion_to_item = Table('ChampionToItem', Base.metadata,
Column('id', Integer, primary_key=True),
Column('champion_id', Integer, ForeignKey('Champion.champion_id')),
Column('item_id', Integer, ForeignKey('Item.item_id'))
)
player_to_champion = Table('PlayerToChampion', Base.metadata,
Column('id', Integer, primary_key=True),
Column('player_id', Integer, ForeignKey('Player.player_id')),
Column('champion_id', Integer, ForeignKey('Champion.champion_id')))
item_to_item = Table('ItemToItem', Base.metadata,
Column('id', Integer, primary_key=True),
Column('from_id', Integer, ForeignKey('Item.item_id')),
Column('into_id', Integer, ForeignKey('Item.item_id'))
)
class Champion (Base) :
__tablename__ = "Champion"
# We need a primary key for SQLAlchemy to not puke on us, but we don't need
# to actually use the primary key, because 'id' is our unique key
id = Column(Integer, primary_key=True)
champion_id = Column(Integer, nullable=False, unique=True)
name = Column(String)
role = Column(String)
title = Column(String)
lore = Column(String(4000))
image = Column(String)
passive_name = Column(String)
passive_image = Column(String)
passive_description = Column(String)
q_name = Column(String)
q_image = Column(String)
q_description = Column(String)
w_name = Column(String)
w_image = Column(String)
w_description = Column(String)
e_name = Column(String)
e_image = Column(String)
e_description = Column(String)
r_name = Column(String)
r_image = Column(String)
r_description = Column(String)
recommended_items = relationship('Item', secondary=champion_to_item)
def __repr__ (self) :
return ("<Champion(name='%s', role='%s', title='%s', image='%s', passive_name='%s',"
"passive_image='%s', passive_description='%s', q_name='%s', q_image='%s',"
"q_description='%s', w_name='%s', w_image='%s', w_description='%s',"
"e_name='%s', e_image='%s', e_description='%s', r_name='%s', r_image='%s',"
"r_description='%s')>") % \
(self.name, self.role, self.title, self.image, self.passive_name, \
self.passive_image, self.passive_description, self.q_name, self.q_image,\
self.q_description, self.w_name, self.w_image, self.w_description, \
self.e_name, self.e_image, self.e_description, self.r_name, self.r_image, \
self.r_description)
"""
class ItemToItem (Base) :
__tablename__ = "ItemToItem"
from_id = relationship("Item", foreign_keys=[item_id])
into_id = relationship("Item", foreign_keys=[item_id])
def __repr__ (self) :
return ("<Item(from_id='%d', into_id='%d'") % \
(self.from_id, self.into_id)
"""
class Item (Base) :
__tablename__ = "Item"
id = Column(Integer, primary_key=True)
item_id = Column(Integer, unique=True, nullable=False)
name = Column(String, nullable=False)
description = Column(String, nullable=False)
base_gold = Column(Integer)
sell_gold = Column(Integer, nullable=False)
total_gold = Column(Integer, nullable=False)
image = Column(String, nullable=False)
from_into = relationship("Item", secondary=item_to_item,
primaryjoin=item_id==item_to_item.c.from_id,
secondaryjoin=item_id==item_to_item.c.into_id)
def __repr__ (self) :
return ("<Item(item_id='%d', name='%s', description='%s', base_gold='%d', sell_gold='%d',"\
"total_gold='%d', image='%s'") % \
(self.item_id, self.name, self.description, self.base_gold, self.sell_gold,\
self.total_gold, self.image)
class Player (Base) :
__tablename__ = "Player"
# We need a primary key for SQLAlchemy to not puke on us, but we don't need
# to actually use the primary key, because 'id' is our unique key
id = Column(Integer, primary_key=True)
player_id = Column(Integer, unique=True)
first_name = Column(String)
last_name = Column(String)
team_name = Column(String)
ign = Column(String)
bio = Column(String)
image = Column(String)
role = Column(String)
kda = Column(Float)
gpm = Column(Float)
total_gold = Column(Integer)
games_played = Column(Integer)
played_champions = relationship('Champion', secondary=player_to_champion)
def __repr__ (self) :
return ("<Player(first_name='%s', last_name='%s', ign='%s', bio='%s', image='%s', role='%s'"\
"kda='%f', gpm='%f', total_gold='%d', games_played='%d', player_id='%d')") % \
(self.first_name, self.last_name, self.ign, self.bio, self.image, self.role, \
self.kda, self.gpm, self.total_gold, self.games_played, self.player_id)
def load_items(items, session) :
for k, v in items.items() :
if not session.query(Item).filter_by(item_id=int(k)).first() :
item = Item(description=v['description'],
base_gold=int(v['gold']['base']),
sell_gold=int(v['gold']['sell']),
total_gold=int(v['gold']['total']),
name=v['name'],
image=v['image'],
item_id=int(k))
session.add(item)
session.commit()
"""
for frm in v['fromItem'] :
session.add(ItemToItem(from_id=int(frm), into_id=int(k)))
for into in v['intoItem'] :
session.add(ItemToItem(from_id=int(k), into_id=int(into)))
"""
def load_players(players, session):
'''
players is a dictionary of player information loaded from a json of the form:
{
"playername" : {"bio" : "",
"champions : [len <= 3 <champion_id>],
"firstname" : "",
"lastname" : "",
"name" : "<ign>",
"photoUrl" : "",
"role" : "",
"teamName" : "",
"id" : "<player_id>",
"kda" : "<float>",
"gpm" : "<int>",
"totalGold": "<int>",
"gamesPlayed": "<int>"
}
'''
with session.no_autoflush:
for k, v in players.items() :
if not session.query(Player).filter_by(player_id=int(k)).first() :
player = Player(bio=(v['bio'] if v['bio'] else ''),
first_name=(v['firstname'] if v['firstname'] else ''),
last_name=(v['lastname'] if v['lastname'] else ''),
ign=(v['name'] if v['name'] else ''),
player_id=(int(v['id']) if v['id'] else 0),
image=(v['photoUrl'] if v['photoUrl'] else ''),
role=(v['role'] if v['role'] else ''),
team_name=(v['teamName'] if v['teamName'] else 'No Team'),
kda=(float(v['kda']) if v['kda'] else 0.0),
gpm=(float(v['gpm']) if v['gpm'] else 0.0),
total_gold=(int(v['totalGold']) if v['totalGold'] else 0),
games_played=(int(v['gamesPlayed']) if v['gamesPlayed'] else 0))
session.add(player)
session.commit()
def load_players_to_champions(players, session):
with session.no_autoflush :
for k, v in players.items() :
player = session.query(Player).filter_by(player_id=int(k)).first()
for champ in v['champions'] :
if champ is not None:
champion = session.query(Champion).filter_by(champion_id=int(champ)).first()
if champion is not None :
player.played_champions.append(champion)
else :
champion = session.query(Champion).filter_by(name='dummy').first()
player.played_champions.append(champion)
if len(player.played_champions) == 0 :
print(player.played_champions)
session.add(player)
session.commit()
def load_item_to_item(items, session):
with session.no_autoflush :
for k, v in items.items() :
this_item = session.query(Item).filter_by(item_id=int(k)).first()
for into in v['intoItem'] :
into_itm = session.query(Item).filter_by(item_id=int(into)).first()
this_item.from_into.append(into_itm)
session.add(this_item)
session.commit()
def load_champions(champions, session, engine):
with session.no_autoflush :
for k, v in champions.items() :
engine.execute(text('update "Champion" set q_description = :desc where champion_id = :id'), desc = v['q_description'].replace('<br>', '\n'), id = int(v['key']))
engine.execute(text('update "Champion" set w_description = :desc where champion_id = :id'), desc = v['w_description'].replace('<br>', '\n'), id = int(v['key']))
engine.execute(text('update "Champion" set e_description = :desc where champion_id = :id'), desc = v['e_description'].replace('<br>', '\n'), id = int(v['key']))
engine.execute(text('update "Champion" set r_description = :desc where champion_id = :id'), desc = v['r_description'].replace('<br>', '\n'), id = int(v['key']))
'''
champion = Champion(champion_id = int(v['key']),
name = v['name'],
role = v['role'],
title = v['title'],
lore = v['lore'],
image = v['image'],
passive_name = v['passive_name'],
passive_image = v['passive_image'],
passive_description = v['passive_description'],
q_name = v['q_name'],
q_image = v['q_image'],
q_description = v['q_description'],
w_name = v['w_name'],
w_image = v['w_image'],
w_description = v['w_description'],
e_name = v['e_name'],
e_image = v['e_image'],
e_description = v['e_description'],
r_name = v['r_name'],
r_image = v['r_image'],
r_description = v['r_description'])
try:
for item in v['recommended_items'] :
i = session.query(Item).filter_by(item_id=int(item)).first()
champion.recommended_items.append(i)
session.add(champion)
except KeyError as e:
pass
'''
session.commit()
def delete_all(session) :
for row in session.query(Item).all():
session.delete(row)
session.commit()
if __name__ == "__main__" :
# Connect to the SQL database
engine = create_engine ('postgresql://postgres:h1Ngx0@localhost/leagueofdowning')
# Add all of the tables to the database, first checking to make sure that the table
# does not already exist
Session = sessionmaker(bind=engine)
session = Session()
#delete_all(session)
items = json.load(open("items"))
champions = json.load(open("champions"))
players = json.load(open("players"))
load_items(items, session)
load_champions(champions, session, engine)
load_players(players, session)
load_players_to_champions(players, session)
load_item_to_item(items, session)
session.close()
| mit |
mapado/rest-client-js-sdk | __tests__/TokenGenerator/PasswordGenerator.test.js | 7589 | import oauthClientCredentialsMock from '../../__mocks__/passwordCredentials.json';
import { PasswordGenerator } from '../../src/index';
import {
InternalServerError,
InvalidGrantError,
InvalidScopeError,
OauthError,
BadRequestError,
ResourceNotFoundError,
UnauthorizedError,
} from '../../src/ErrorFactory';
global.fetch = require('jest-fetch-mock');
global.FormData = require('form-data');
const tokenConfig = {
path: 'oauth.me',
scheme: 'https',
clientId: '8',
clientSecret: 'keep me secret',
};
describe('PasswordGenerator tests', () => {
beforeEach(fetch.resetMocks);
test('test that config is properly checked', () => {
function createTokenGenerator(config) {
return () => new PasswordGenerator(config);
}
expect(createTokenGenerator()).toThrowError(RangeError);
expect(createTokenGenerator({ foo: 'bar' })).toThrowError(RangeError);
expect(
createTokenGenerator({ path: 'oauth.me', scheme: 'https' })
).toThrowError(RangeError);
expect(createTokenGenerator(tokenConfig)).not.toThrowError('good config');
});
test('test generateToken method', async () => {
fetch.mockResponse(JSON.stringify(oauthClientCredentialsMock));
const tokenGenerator = new PasswordGenerator(tokenConfig);
expect(() => tokenGenerator.generateToken()).toThrowError(RangeError);
expect(() => tokenGenerator.generateToken({ foo: 'bar' })).toThrowError(
RangeError
);
const response = await tokenGenerator.generateToken({
username: 'foo',
password: 'bar',
});
expect(response).toBeInstanceOf(Response);
const token = await response.json();
expect(typeof token).toBe('object');
expect(token.access_token).toEqual(oauthClientCredentialsMock.access_token);
expect(token.refresh_token).toEqual(
oauthClientCredentialsMock.refresh_token
);
expect(fetch.mock.calls[0][0]).toEqual('https://oauth.me/');
});
test('test that refreshToken refresh the token ;)', async () => {
expect.assertions(3);
fetch.mockResponse(JSON.stringify(oauthClientCredentialsMock));
const tokenGenerator = new PasswordGenerator(tokenConfig);
try {
tokenGenerator.refreshToken();
} catch (err) {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe(
'refresh_token is not set. Did you called `generateToken` before ?'
);
}
const response = await tokenGenerator.generateToken({
username: 'foo',
password: 'bar',
});
const accessToken = await response.json();
const refreshTokenResponse = await tokenGenerator.refreshToken(accessToken);
const refreshToken = await refreshTokenResponse.json();
expect(refreshToken.access_token).toEqual(
oauthClientCredentialsMock.access_token
);
});
test('test that refreshToken throws OauthError on 400 with no json body', () => {
const tokenGenerator = new PasswordGenerator(tokenConfig);
fetch.mockResponseOnce(JSON.stringify(oauthClientCredentialsMock));
const generateTokenPromise = tokenGenerator.generateToken({
username: 'foo',
password: 'bar',
});
fetch.mockResponseOnce(null, { status: 400 });
return generateTokenPromise
.then((r) => r.json())
.then((accessToken) =>
tokenGenerator.refreshToken(accessToken).catch((err) => {
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof BadRequestError).toEqual(true);
})
);
});
test('test that refreshToken throws OauthError on 400 with no oauth error', async () => {
const tokenGenerator = new PasswordGenerator(tokenConfig);
fetch.mockResponseOnce(JSON.stringify(oauthClientCredentialsMock));
const response = await tokenGenerator.generateToken({
username: 'foo',
password: 'bar',
});
fetch.mockResponseOnce(JSON.stringify({ error: 'dummy error' }), {
status: 400,
});
const accessToken = await response.json();
const r2 = await tokenGenerator.refreshToken(accessToken);
expect(r2.status).toBe(400);
const body = await r2.json();
expect(body.error).toBe('dummy error');
});
test('test that OauthError is thrown on 403', async () => {
fetch.mockResponseOnce(null, { status: 403 });
const tokenGenerator = new PasswordGenerator(tokenConfig);
const response = await tokenGenerator.generateToken({
password: 'foo',
username: 'bar',
});
expect(response.status).toBe(403);
// expect(err instanceof OauthError).toEqual(true);
// expect(err.previousError instanceof ForbiddenError).toEqual(true);
// });
});
test('test that OauthError is thrown on 404', () => {
fetch.mockResponseOnce(null, { status: 404 });
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.generateToken({ password: 'foo', username: 'bar' })
.catch((err) => {
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof ResourceNotFoundError).toEqual(
true
);
});
});
test('test that OauthError is thrown on 400', () => {
fetch.mockResponseOnce(null, { status: 400 });
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.generateToken({ password: 'foo', username: 'bar' })
.catch((err) => {
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof BadRequestError).toEqual(true);
});
});
test('test that InvalidGrantError is thrown when getting a 400 with body error "invalid_grant"', () => {
fetch.mockResponse(JSON.stringify({ error: 'invalid_grant' }), {
status: 400,
});
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.refreshToken(oauthClientCredentialsMock)
.catch((err) => {
expect(err instanceof InvalidGrantError).toEqual(true);
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof BadRequestError).toEqual(true);
});
});
test('test that InvalidScopeError is thrown when getting a 400 with body error "invalid_scope"', () => {
fetch.mockResponse(JSON.stringify({ error: 'invalid_scope' }), {
status: 400,
});
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.refreshToken(oauthClientCredentialsMock)
.catch((err) => {
expect(err instanceof InvalidScopeError).toEqual(true);
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof BadRequestError).toEqual(true);
});
});
test('test that OauthError is thrown on 500', () => {
fetch.mockResponseOnce(null, { status: 500 });
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.generateToken({ password: 'foo', username: 'bar' })
.catch((err) => {
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof InternalServerError).toEqual(true);
});
});
test('test that OauthError error is thrown on 401', () => {
fetch.mockResponseOnce(null, { status: 401 });
const tokenGenerator = new PasswordGenerator(tokenConfig);
return tokenGenerator
.generateToken({ password: 'foo', username: 'bar' })
.catch((err) => {
expect(err instanceof OauthError).toEqual(true);
expect(err.previousError instanceof UnauthorizedError).toEqual(true);
});
});
});
| mit |
irobotnik8/LobbyCoin | src/qt/editaddressdialog.cpp | 3566 | #include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setDisabled(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid lobbycoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
| mit |
rkovacevic/firestarter | public/views/home/main.js | 2982 | 'use strict';
angular.module('app.home')
.controller('MainCtrl',
function($scope, $rootScope, $q, $timeout, growl, Restangular, Users) {
$scope.posts = null;
var loadPosts = function(toDate) {
Restangular.all('posts').getList({'toDate': toDate}).then(function(posts) {
if ($scope.posts) posts = _.sortBy(_.flatten([$scope.posts, posts]), function(post) {
return -1 * moment(post.postedDate).valueOf();
});
$scope.posts = _.uniq(posts, '_id');
$timeout(loadPosts, 5000);
}, function() {
growl.error('Error communicating with server');
})
}
$scope.loadNextPage = function() {
if (!$scope.posts) return;
loadPosts(_.last($scope.posts).postedDate);
}
$scope.$watch('user', function() {
if ($scope.user == null) return;
loadPosts();
Restangular.all('users/suggested').getList().then(function(users) {
$scope.suggestedUsers = users;
}, function() {
growl.error('Error communicating with server');
})
})
$scope.post = function() {
var deferred = $q.defer();
Restangular.all('posts').post({ text: $scope.postText }).then(function(result) {
if ($scope.posts == null) $scope.posts = [];
$scope.posts.unshift(result);
$scope.postText = null;
$scope.postForm.$setPristine(true);
deferred.resolve();
}, function(result) {
deferred.reject({
postText: { message: 'Error submitting' }
});
});
return deferred.promise;
}
$scope.subscribe = function(userToSubscribeTo) {
Restangular.all('users/me/subscriptions').post(userToSubscribeTo)
.then(function(result) {
_.without($scope.suggestedUsers, userToSubscribeTo);
$rootScope.user.subscriptions.push(userToSubscribeTo);
loadPosts();
}, function(result) {
growl.error('Error communicating with server');
})
}
$scope.unsubscribe = function(userToUnsubscribeFrom) {
Restangular.one('users/me/subscriptions', userToUnsubscribeFrom._id).remove()
.then(function(result) {
_.without($rootScope.user.subscriptions, userToUnsubscribeFrom);
$scope.suggestedUsers.push(userToUnsubscribeFrom);
$scope.posts = _.filter($scope.posts, function (post) {
return post.author._id != userToUnsubscribeFrom._id;
});
loadPosts();
}, function(result) {
growl.error('Error communicating with server');
})
}
}); | mit |
ruflin/Elastica | src/Search.php | 9988 | <?php
namespace Elastica;
use Elastica\Exception\InvalidException;
use Elastica\ResultSet\BuilderInterface;
use Elastica\ResultSet\DefaultBuilder;
/**
* Elastica search object.
*
* @author Nicolas Ruflin <[email protected]>
*/
class Search
{
/*
* Options
*/
public const OPTION_SEARCH_TYPE = 'search_type';
public const OPTION_ROUTING = 'routing';
public const OPTION_PREFERENCE = 'preference';
public const OPTION_VERSION = 'version';
public const OPTION_TIMEOUT = 'timeout';
public const OPTION_FROM = 'from';
public const OPTION_SIZE = 'size';
public const OPTION_SCROLL = 'scroll';
public const OPTION_SCROLL_ID = 'scroll_id';
public const OPTION_QUERY_CACHE = 'query_cache';
public const OPTION_TERMINATE_AFTER = 'terminate_after';
public const OPTION_SHARD_REQUEST_CACHE = 'request_cache';
public const OPTION_FILTER_PATH = 'filter_path';
public const OPTION_TYPED_KEYS = 'typed_keys';
/*
* Search types
*/
public const OPTION_SEARCH_TYPE_DFS_QUERY_THEN_FETCH = 'dfs_query_then_fetch';
public const OPTION_SEARCH_TYPE_QUERY_THEN_FETCH = 'query_then_fetch';
public const OPTION_SEARCH_TYPE_SUGGEST = 'suggest';
public const OPTION_SEARCH_IGNORE_UNAVAILABLE = 'ignore_unavailable';
/**
* Array of indices names.
*
* @var string[]
*/
protected $_indices = [];
/**
* @var Query
*/
protected $_query;
/**
* @var array
*/
protected $_options = [];
/**
* Client object.
*
* @var Client
*/
protected $_client;
/**
* @var BuilderInterface|null
*/
private $builder;
public function __construct(Client $client, ?BuilderInterface $builder = null)
{
$this->_client = $client;
$this->builder = $builder ?: new DefaultBuilder();
}
/**
* Adds a index to the list.
*
* @param Index|string $index Index object or string
*
* @throws InvalidException
*/
public function addIndex($index): self
{
if ($index instanceof Index) {
$index = $index->getName();
}
if (!\is_scalar($index)) {
throw new InvalidException('Invalid param type');
}
$this->_indices[] = (string) $index;
return $this;
}
/**
* Add array of indices at once.
*
* @param Index[]|string[] $indices
*/
public function addIndices(array $indices = []): self
{
foreach ($indices as $index) {
$this->addIndex($index);
}
return $this;
}
/**
* @param array|Query|Query\AbstractQuery|string|Suggest $query
*/
public function setQuery($query): self
{
$this->_query = Query::create($query);
return $this;
}
/**
* @param mixed $value
*/
public function setOption(string $key, $value): self
{
$this->validateOption($key);
$this->_options[$key] = $value;
return $this;
}
public function setOptions(array $options): self
{
$this->clearOptions();
foreach ($options as $key => $value) {
$this->setOption($key, $value);
}
return $this;
}
public function clearOptions(): self
{
$this->_options = [];
return $this;
}
/**
* @param mixed $value
*/
public function addOption(string $key, $value): self
{
$this->validateOption($key);
$this->_options[$key][] = $value;
return $this;
}
public function hasOption(string $key): bool
{
return isset($this->_options[$key]);
}
/**
* @throws InvalidException if the given key does not exists as an option
*
* @return mixed
*/
public function getOption(string $key)
{
if (!$this->hasOption($key)) {
throw new InvalidException('Option '.$key.' does not exist');
}
return $this->_options[$key];
}
public function getOptions(): array
{
return $this->_options;
}
/**
* Return client object.
*/
public function getClient(): Client
{
return $this->_client;
}
/**
* Return array of indices names.
*
* @return string[]
*/
public function getIndices(): array
{
return $this->_indices;
}
public function hasIndices(): bool
{
return \count($this->_indices) > 0;
}
/**
* @param Index|string $index
*/
public function hasIndex($index): bool
{
if ($index instanceof Index) {
$index = $index->getName();
}
return \in_array($index, $this->_indices, true);
}
public function getQuery(): Query
{
if (null === $this->_query) {
$this->_query = Query::create('');
}
return $this->_query;
}
/**
* Creates new search object.
*/
public static function create(SearchableInterface $searchObject): Search
{
return $searchObject->createSearch();
}
/**
* Combines indices to the search request path.
*/
public function getPath(): string
{
if (isset($this->_options[self::OPTION_SCROLL_ID])) {
return '_search/scroll';
}
return \implode(',', $this->getIndices()).'/_search';
}
/**
* Search in the set indices.
*
* @param array|Query|Query\AbstractQuery|string $query
* @param array|int $options Limit or associative array of options (option=>value)
*
* @throws InvalidException
*/
public function search($query = '', $options = null, string $method = Request::POST): ResultSet
{
$this->setOptionsAndQuery($options, $query);
$query = $this->getQuery();
$path = $this->getPath();
$params = $this->getOptions();
// Send scroll_id via raw HTTP body to handle cases of very large (> 4kb) ids.
if ('_search/scroll' === $path) {
$data = [self::OPTION_SCROLL_ID => $params[self::OPTION_SCROLL_ID]];
unset($params[self::OPTION_SCROLL_ID]);
} else {
$data = $query->toArray();
}
$response = $this->getClient()->request($path, $method, $data, $params);
return $this->builder->buildResultSet($response, $query);
}
/**
* @param array|Query|Query\AbstractQuery|string $query
* @param bool $fullResult By default only the total hit count is returned. If set to true, the full ResultSet including aggregations is returned
*
* @return int|ResultSet
*/
public function count($query = '', bool $fullResult = false, string $method = Request::POST)
{
$this->setOptionsAndQuery(null, $query);
// Clone the object as we do not want to modify the original query.
$query = clone $this->getQuery();
$query->setSize(0);
$query->setTrackTotalHits(true);
$path = $this->getPath();
$response = $this->getClient()->request(
$path,
$method,
$query->toArray(),
[self::OPTION_SEARCH_TYPE => self::OPTION_SEARCH_TYPE_QUERY_THEN_FETCH]
);
$resultSet = $this->builder->buildResultSet($response, $query);
return $fullResult ? $resultSet : $resultSet->getTotalHits();
}
/**
* @param array|int $options
* @param array|Query|Query\AbstractQuery|string|Suggest $query
*/
public function setOptionsAndQuery($options = null, $query = ''): self
{
if ('' !== $query) {
$this->setQuery($query);
}
if (\is_int($options)) {
\trigger_deprecation('ruflin/elastica', '7.1.3', 'Passing an int as 1st argument to "%s()" is deprecated, pass an array with the key "size" instead. It will be removed in 8.0.', __METHOD__);
$this->getQuery()->setSize($options);
} elseif (\is_array($options)) {
if (isset($options['limit'])) {
$this->getQuery()->setSize($options['limit']);
unset($options['limit']);
}
if (isset($options['explain'])) {
$this->getQuery()->setExplain($options['explain']);
unset($options['explain']);
}
$this->setOptions($options);
}
return $this;
}
public function setSuggest(Suggest $suggest): self
{
return $this->setOptionsAndQuery([self::OPTION_SEARCH_TYPE_SUGGEST => 'suggest'], $suggest);
}
/**
* Returns the Scroll Iterator.
*
* @see Scroll
*/
public function scroll(string $expiryTime = '1m'): Scroll
{
return new Scroll($this, $expiryTime);
}
public function getResultSetBuilder(): BuilderInterface
{
return $this->builder;
}
/**
* @throws InvalidException If the given key is not a valid option
*/
protected function validateOption(string $key): void
{
switch ($key) {
case self::OPTION_SEARCH_TYPE:
case self::OPTION_ROUTING:
case self::OPTION_PREFERENCE:
case self::OPTION_VERSION:
case self::OPTION_TIMEOUT:
case self::OPTION_FROM:
case self::OPTION_SIZE:
case self::OPTION_SCROLL:
case self::OPTION_SCROLL_ID:
case self::OPTION_SEARCH_TYPE_SUGGEST:
case self::OPTION_SEARCH_IGNORE_UNAVAILABLE:
case self::OPTION_QUERY_CACHE:
case self::OPTION_TERMINATE_AFTER:
case self::OPTION_SHARD_REQUEST_CACHE:
case self::OPTION_FILTER_PATH:
case self::OPTION_TYPED_KEYS:
return;
}
throw new InvalidException('Invalid option '.$key);
}
}
| mit |
mrymtmk/ChatworkNotificator | ChatworkNotificator/src/jp/mrymtmk/notificator/watcher/UserInfoWatcher.java | 874 | package jp.mrymtmk.notificator.watcher;
import jp.mrymtmk.notificator.bean.ChatworkUserInfo;
import jp.mrymtmk.notificator.event.ReceiveEvent;
import jp.mrymtmk.notificator.event.listener.ReceiveEventListener;
import jp.mrymtmk.notificator.util.PropertyUtil;
public class UserInfoWatcher extends ChatworkWatcher<ChatworkUserInfo> {
/**
* コンストラクタ
* @param listner イベントリスナ
*/
public UserInfoWatcher(ReceiveEventListener<ChatworkUserInfo> listner) {
super(listner);
}
@Override
public void run() {
ReceiveEvent<ChatworkUserInfo> e = new ReceiveEvent<>(this, this.doGet(), ChatworkUserInfo.class);
if (e.getInfo().failed()) {
this.fireErrorevent(e);
return;
}
this.fireReceiveEvent(e);
}
@Override
protected String getURI() {
return PropertyUtil.getProperty("endpoint.me");
}
}
| mit |
BVJin/personalWebsite | public/modules/blog/blog.client.module.js | 146 | 'use strict';
// Use application configuration module to register a new module
ApplicationConfiguration.registerModule('blog', ['textAngular']);
| mit |
rogeliog/flight-examples | public/examples/hello_world/js/ui/hello_world.js | 491 | define(function (require) {
'use strict';
var defineComponent = require('flight/lib/component');
return defineComponent(helloWorld);
function helloWorld() {
this.defaultAttrs({
inputSelector: '.inputField',
nameSelector: '.name'
});
this.updateName = function (e, data) {
this.select('nameSelector').text(data.el.value);
}
this.after('initialize', function () {
this.on("input", { inputSelector: this.updateName });
});
}
});
| mit |
mldb/react-native-persian-date-picker | index.android.js | 144 |
import {AppRegistry} from 'react-native';
import App from './PersianDatePicker';
AppRegistry.registerComponent('PersianDatePicker', () => App); | mit |
Uninassau-ProgramacaoIV/ProvaColegiada | src/java/br/edu/uninassau/provaColegiada/usuario/UsuarioFiltro.java | 2146 | package br.edu.uninassau.provaColegiada.usuario;
import br.edu.uninassau.provaColegiada.usuario.dao.ArquivoUsuarioDAO;
import br.edu.uninassau.provaColegiada.usuario.dao.UsuarioDAO;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Esta classe ira instanicar o DAO e repassara para os Servlets
*
* @author avld
*/
@WebFilter( "/usuario/*" )
public class UsuarioFiltro implements Filter
{
private UsuarioDAO dao;
public UsuarioFiltro()
{
// faz nada
}
@Override
public void init( FilterConfig filterConfig ) throws ServletException
{
try
{
// Troque o ArquivoUsuarioDAO por ArquivoUsuarioDAO e veja
// que vai continuar a mesma coisa...
dao = new ArquivoUsuarioDAO();
// Caso nao exista nenhum usuario no sistema, criar o 'admin'
// isso daqui nao e necessario para os outros modulos
if( dao.listar().isEmpty() )
{
Usuario usario = new Usuario();
usario.setNome( "Adminstrador" );
usario.setLogin( "admin" );
usario.setSenha( "admin" );
usario.setCategoria( Usuario.CATEGORIA_ADMIN );
dao.adicionar( usario );
}
}
catch( Exception err )
{
// Ocorreu um erro grave ao tentar inicializar o UsuarioDAO
throw new ServletException( err );
}
}
@Override
public void doFilter( ServletRequest request
, ServletResponse response
, FilterChain chain )
throws IOException, ServletException
{
request.setAttribute( "UsuarioDAO" , dao );
chain.doFilter( request , response );
}
@Override
public void destroy()
{
dao = null;
}
}
| mit |
stanislaw/simple_roles | spec/simple_roles/macros_spec.rb | 954 | require 'spec_helper'
describe 'SimpleRoles Macros' do
context "Macros availability" do
subject { Module }
before { require 'simple_roles' }
specify { should be_kind_of SimpleRoles::Macros }
end
context "When Macros is applied" do
subject { User }
specify { should be_kind_of SimpleRoles::Macros }
before do
class User < ActiveRecord::Base
simple_roles do
strategy :many
end
end
end
context "Changes in User" do
specify { should include SimpleRoles::Many::RolesMethods }
specify { should include SimpleRoles::Many::RolesMethods }
[:roles, :roles_list, :add_role, :roles=, :remove_role].each do |meth|
specify { subject.new.should respond_to meth }
end
end
context "Changes in SimpleRoles::Configuration" do
it "should set strategy" do
SimpleRoles::Configuration.strategy.should == :many
end
end
end
end
| mit |
alphagov/panopticon | test/unit/callbacks/update_router_callback_test.rb | 964 | require 'test_helper'
class UpdateRouterCallbackTest < ActiveSupport::TestCase
setup { Artefact.any_instance.stubs(:update_search) }
should 'submit a live artefact' do
mock_routable_artefact = mock("RoutableArtefact")
RoutableArtefact.stubs(:new).returns(mock_routable_artefact)
mock_routable_artefact.expects(:submit)
artefact = build(:live_artefact)
assert artefact.save
end
should 'submit an archived artefact' do
mock_routable_artefact = mock("RoutableArtefact")
RoutableArtefact.stubs(:new).returns(mock_routable_artefact)
mock_routable_artefact.expects(:submit)
artefact = build(:archived_artefact)
assert artefact.save
end
should 'submit a draft artefact' do
mock_routable_artefact = mock("RoutableArtefact")
RoutableArtefact.stubs(:new).returns(mock_routable_artefact)
mock_routable_artefact.expects(:submit)
artefact = build(:draft_artefact)
assert artefact.save
end
end
| mit |
mobilunity-user/ravendb-nodejs-client | src/Utility/TypeUtil.ts | 975 | import * as _ from 'lodash';
export class TypeUtil {
public static readonly MAX_INT32 = 2147483647;
public static isNull(value: any): boolean {
return ('undefined' === (typeof value)) || _.isNull(value);
}
public static isString(value: any): boolean {
return _.isString(value);
}
public static isNumber(value: any): boolean {
return _.isNumber(value);
}
public static isArray(value: any): boolean {
return _.isArray(value);
}
public static isObject(value: any): boolean {
return _.isObject(value) && !this.isArray(value);
}
public static isFunction(value: any): boolean {
return _.isFunction(value);
}
public static isDocumentConstructor(value: any): boolean {
return _.isFunction(value) && ('name' in value)
&& ('Object' !== value.name);
}
public static isDate(value: any): boolean {
return _.isDate(value);
}
public static isBool(value: any): boolean {
return _.isBoolean(value);
}
} | mit |
steveoro/goggles | db/migrate/20140218191029_add_aux_references_to_training_rows.rb | 270 | class AddAuxReferencesToTrainingRows < ActiveRecord::Migration
def change
change_table :training_rows do |t|
t.references :arm_aux_type
t.references :kick_aux_type
t.references :body_aux_type
t.references :breath_aux_type
end
end
end
| mit |
kazunetakahashi/atcoder | 2017/1105_ARC079/E.cpp | 1500 | #include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int main () {
int N;
cin >> N;
ll a[100];
for (auto i = 0; i < N; ++i) {
cin >> a[i];
}
ll ans = 0;
bool ok = false;
while (!ok) {
ok = true;
for (auto i = 0; i < N; ++i) {
if (a[i] <= N-1) {
continue;
} else {
ok = false;
break;
}
}
if (!ok) {
ll S = 0;
for (auto i = 0; i < N; ++i) {
S += a[i]/N;
}
for (auto i = 0; i < N; ++i) {
a[i] = a[i] - N * (a[i]/N) + S - a[i]/N;
}
ans += S;
}
}
cout << ans << endl;
}
| mit |
aalpgiray/rhl-3-typescript | src/pages/Visit/VisitPage.interfaces.tsx | 454 | import { IVisit } from '../../reducers/visit.reducer';
import { deleteVisit, rollbackDeleteVisit } from '../../actions/visit.actions';
export interface IVisitPage extends IStoreProps, IOwnProps, IActionProps {
}
export interface IStoreProps {
visits: IVisit[];
}
export interface IOwnProps {
}
export interface IActionProps {
actions?: {
deleteVisit: (visit: IVisit) => Promise<any>
rollbackDeleteVisit: (course: IVisit) => void;
};
}
| mit |
colbylwilliams/bugtrap | iOS/Code/Xamarin/bugTrap/bugTrapKit/Constants/Colors.cs | 851 | using UIKit;
namespace bugTrapKit
{
public static class Colors
{
public static UIColor Theme = new UIColor (252f / 255f, 17f / 255f, 63f / 255f, 255f / 255f);
public static UIColor Black = new UIColor (0f / 255f, 0f / 255f, 0f / 255f, 255f / 255f);
public static UIColor White = new UIColor (255f / 255f, 255f / 255f, 255f / 255f, 255f / 255f);
public static UIColor Clear = new UIColor (0f / 255f, 0f / 255f, 0f / 255f, 0f / 255f);
public static UIColor Gray = new UIColor (142f / 255f, 142f / 255f, 147f / 255f, 255f / 255f);
public static UIColor LightGray = new UIColor (199f / 255f, 199f / 255f, 204f / 255f, 255f / 255f);
public static UIColor LighterGray = new UIColor (248f / 255f, 248f / 255f, 252f / 255f, 255f / 255f);
public static UIColor Tool = new UIColor (147f / 255f, 146f / 255f, 145f / 255f, 255f / 255f);
}
} | mit |
P-P-Egg/Journey-of-Train | Assets/Demo/Scrips/talk/talk2_nr.cs | 3641 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class talk2_nr : MonoBehaviour {
private TextMesh text2;
public float daltatime;
private Color color = new Color(255, 255, 255, 0);
void Start()
{
text2 = gameObject.GetComponentInChildren<TextMesh>();
fuzhi();
}
void Update()
{
jian_bian();
xiao_hui();
}
void jian_bian() //一个颜色渐变的功能
{
if (daltatime <= 1) // 渐变增加透明度
{
daltatime += Time.deltaTime;
color = new Color(255, 255, 255, daltatime);
text2.color = color;
}
}
void xiao_hui() //自动销毁自己
{
Destroy(gameObject, 5);
}
void OnMouseOver() //鼠标t停留时变成黄色
{
text2.color = Color.yellow;
}
void OnMouseExit()//鼠标退出时变成白色
{
text2.color = Color.white;
}
void OnMouseUp() //当鼠标点击时,记录话,销毁自己talk2_boll
{
cun_jb.jao_bao_nei_rong = text2.text;
}
void OnDestroy() //销毁时
{
manager2.talk2_id++;
}
void fuzhi() //给TEXT赋值
{
if (manager2.talk2_id == 20000)
{
text2.text = "包里的照片是我儿子,他\n擅长用乐高创造的建筑。";
}
if (manager2.talk2_id == 20001)
{
text2.text = "小孩子都喜欢一边建造一\n边破坏。";
}
if (manager2.talk2_id == 20002)
{
text2.text = "照片里他正在试图推倒一\n面乐高拼起的围墙。";
}
if (manager2.talk2_id == 20003)
{
text2.text = "肯尼迪当年在柏林演讲时\n说:";
}
if (manager2.talk2_id == 20004)
{
text2.text = "我们从未建造一堵墙把人\n民关在里面,不准离开。";
}
if (manager2.talk2_id == 20005)
{
text2.text = "看来快要食言了。";
}
if (manager2.talk2_id == 20006)
{
text2.text = "别忘了肯尼迪的前两句话:";
}
if (manager2.talk2_id == 20007)
{
text2.text = "自由有许多困难,民主亦\n非完美。";
}
if (manager2.talk2_id == 20008)
{
text2.text = "现在可能是它不完美的时\n候。";
}
if (manager2.talk2_id == 20009)
{
text2.text = "你们上学就为了表达不满\n吗?成天示威。";
}
if (manager2.talk2_id == 20010)
{
text2.text = "身在福中不知福的家伙,\n应该把你们送到沙特,";
}
if (manager2.talk2_id == 20011)
{
text2.text = "在滚烫的沙漠里受苦,才\n知道国家有多好。";
}
if (manager2.talk2_id == 20012)
{
text2.text = "昨天遇到个学生,撞坏了\n我的车还直接跑了。";
}
if (manager2.talk2_id == 20013)
{
text2.text = "你们先学会做人吧。";
}
if (manager2.talk2_id == 20014)
{
text2.text = "我每天都会看特瑞普的演\n讲。";
}
if (manager2.talk2_id == 20015)
{
text2.text = "我敢发誓,那是我一天中\n最开心的时候。";
}
if (manager2.talk2_id == 20016)
{
text2.text = "特瑞普绝对是他妈的历史\n上最会用手演讲的总统。";
}
}
}
| mit |
zyhndesign/DesignCompetition | src/main/java/com/cidic/design/service/RuleService.java | 348 | package com.cidic.design.service;
import java.util.List;
import java.util.Optional;
import com.cidic.design.model.Rule;
public interface RuleService {
public void createRule(Rule rule);
public void updateRule(Rule rule);
public void deleteRule(int id);
public List<Rule> getAllRule();
public Optional<Rule> getRuleById(int id);
}
| mit |
iandees/all-the-places | locations/spiders/mcdonalds.py | 6114 | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class McDonaldsSpider(scrapy.Spider):
name = "mcdonalds"
allowed_domains = ["www.mcdonalds.com"]
start_urls = (
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=44.97&longitude=-93.21&radius=100000&maxResults=300000&country=us&language=en-us',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=44.97&longitude=-93.21&radius=100000&maxResults=300000&country=ca&language=en-ca',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=44.97&longitude=-93.21&radius=100000&maxResults=300000&country=gb&language=en-gb',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=44.97&longitude=-93.21&radius=100000&maxResults=300000&country=se&language=sv-se',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=55.9394691&longitude=10.17994550000003&radius=100000&maxResults=300000&country=dk&language=da-dk',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=60.7893233&longitude=10.689804200000026&radius=100000&maxResults=300000&country=no&language=en-no',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=24.0799008&longitude=45.29000099999996&radius=100000&maxResults=300000&country=saj&language=en-sa',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=29.3365728&longitude=47.67552909999995&radius=100000&maxResults=300000&country=kw&language=en-kw',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=24.1671413&longitude=56.114225300000044&radius=100000&maxResults=300000&country=om&language=en-om',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=23.659703&longitude=53.7042189&radius=100000&maxResults=300000&country=ae&language=en-ae',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=26.1621079&longitude=50.4501947&radius=100000&maxResults=300000&country=bh&language=en-bh',
'https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=25.2854473&longitude=51.53103979999992&radius=100000&maxResults=300000&country=qa&language=en-q'
)
def store_hours(self, store_hours):
if not store_hours:
return None
if all([h == '' for h in store_hours.values()]):
return None
day_groups = []
this_day_group = None
for day in ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'):
hours = store_hours.get('hours' + day)
if not hours:
continue
hours = hours.replace(' - ', '-')
day_short = day[:2]
if not this_day_group:
this_day_group = dict(from_day=day_short, to_day=day_short, hours=hours)
elif this_day_group['hours'] == hours:
this_day_group['to_day'] = day_short
elif this_day_group['hours'] != hours:
day_groups.append(this_day_group)
this_day_group = dict(from_day=day_short, to_day=day_short, hours=hours)
day_groups.append(this_day_group)
if len(day_groups) == 1:
opening_hours = day_groups[0]['hours']
if opening_hours == '04:00-04:00':
opening_hours = '24/7'
else:
opening_hours = ''
for day_group in day_groups:
if day_group['from_day'] == day_group['to_day']:
opening_hours += '{from_day} {hours}; '.format(**day_group)
else:
opening_hours += '{from_day}-{to_day} {hours}; '.format(**day_group)
opening_hours = opening_hours[:-2]
return opening_hours
def parse(self, response):
data = json.loads(response.body_as_unicode())
for store in data.get('features', []):
store_info = store['properties']
if store_info['addressLine4'] == 'USA':
properties = {
"ref": store_info['id'],
'addr_full': store_info['addressLine1'],
'city': store_info['addressLine3'],
'state': store_info['subDivision'],
'country': store_info['addressLine4'],
'postcode': store_info['postcode'],
'phone': store_info.get('telephone'),
'lon': store['geometry']['coordinates'][0],
'lat': store['geometry']['coordinates'][1],
'extras':
{
'number': store_info["identifierValue"] ## 4 digit identifier that is a store number for US McDonalds
}
}
else:
properties = {
"ref": store_info['id'],
'addr_full': store_info['addressLine1'],
'city': store_info['addressLine3'],
'state': store_info['subDivision'],
'country': store_info['addressLine4'],
'postcode': store_info['postcode'],
'phone': store_info.get('telephone'),
'lon': store['geometry']['coordinates'][0],
'lat': store['geometry']['coordinates'][1],
}
hours = store_info.get('restauranthours')
try:
hours = self.store_hours(hours)
if hours:
properties['opening_hours'] = hours
except:
self.logger.exception("Couldn't process opening hours: %s", hours)
yield GeojsonPointItem(**properties)
| mit |
artoodetoo/container | src/ContainerAwareInterface.php | 333 | <?php
namespace R2\DependencyInjection;
interface ContainerAwareInterface
{
/**
* Sets the Container.
* Provides a fluent interface.
*
* @param ContainerInterface $container A ContainerInterface instance
*
* @return $this
*/
public function setContainer(ContainerInterface $container);
}
| mit |
myron0330/caching-research | section_cmab/algorithms/recover.py | 1136 | # -*- coding: UTF-8 -*-
# **********************************************************************************#
# File: Recover methods
# **********************************************************************************#
def recover_from_(variables, c_bk):
"""
Recover from c_bk
Args:
variables(variables): variable parameters
c_bk(matrix): relaxing problem solution
"""
keys = range(c_bk.shape[1])
file_info = variables.file_info
base_stations = variables.base_stations
for index in xrange(c_bk.shape[0]):
result = dict(zip(keys, c_bk[index, :]))
sorted_keys = sorted(result, key=lambda _: result[_], reverse=True)
candidates, total_size = list(), 0
base_station = base_stations[index]
for candidate in sorted_keys:
if result[candidate] == 0 or total_size + file_info[candidate] > base_station.memory:
break
candidates.append(candidate)
total_size += file_info[candidate]
c_bk[index, :] = [0] * c_bk.shape[1]
c_bk[index, candidates] = [1] * len(candidates)
return c_bk
| mit |
gikusan/symfony25 | app/cache/dev/annotations/674aa954cf7567b8977e6a3466c5e760e3959a45$plainPassword.cache.php | 947 | <?php return unserialize('a:2:{i:0;O:48:"Symfony\\Component\\Validator\\Constraints\\NotBlank":3:{s:7:"message";s:31:"This value should not be blank.";s:7:"payload";N;s:6:"groups";a:1:{i:0;s:7:"Default";}}i:1;O:46:"Symfony\\Component\\Validator\\Constraints\\Length":9:{s:10:"maxMessage";s:140:"This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.";s:10:"minMessage";s:142:"This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.";s:12:"exactMessage";s:108:"This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.";s:14:"charsetMessage";s:61:"This value does not match the expected {{ charset }} charset.";s:3:"max";i:4096;s:3:"min";N;s:7:"charset";s:5:"UTF-8";s:7:"payload";N;s:6:"groups";a:1:{i:0;s:7:"Default";}}}'); | mit |
mpasternak/djorm-ext-filtered-contenttypes | filtered_contenttypes/tests/migrations/0002_promoitems.py | 777 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.db.migrations.operations.special import RunSQL
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__first__'),
('tests', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PromoItems',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField()),
('content_type', models.ForeignKey(to='contenttypes.ContentType')),
],
options={
},
bases=(models.Model,),
),
]
| mit |
phlexible/phlexible | src/Phlexible/Component/MediaTemplate/Previewer/PreviewerInterface.php | 561 | <?php
/*
* This file is part of the phlexible package.
*
* (c) Stephan Wentz <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Phlexible\Component\MediaTemplate\Previewer;
/**
* Previewer interface.
*
* @author Stephan Wentz <[email protected]>
*/
interface PreviewerInterface
{
/**
* @param string $filePath
* @param array $params
*
* @return array
*/
public function create($filePath, array $params);
}
| mit |
j3pic/magic-mirror | magic-mirror.rb | 22408 | begin
Rails
raise "MagicMirror is loading after Rails. This is no good."
rescue NameError
nil
end
require 'socket'
class MagicMirror
attr_reader :successful_loads
@successful_loads = {}
@failed_loads = []
@in_require = 0
@inferred_nesting = []
def self.inferred_nesting
@inferred_nesting
end
def self.push_nesting(klass)
@inferred_nesting.push(klass)
end
def self.pop_nesting
@inferred_nesting.pop
end
def self.report_loaded_file(file)
@successful_loads[file] = true
end
def self.with_temp_wd(wd)
oldwd = Dir.getwd
Dir.chdir(wd)
yield
ensure
Dir.chdir(oldwd)
end
def self.failed_loads
@failed_loads
end
def self.failed_loads=(new_value)
@failed_loads=new_value
end
def self.in_require=(new_value)
@in_require=new_value
end
def self.in_require
@in_require
end
def self.retry_failed_loads
@failed_loads -= @failed_loads.select do |directory,file|
with_temp_wd(directory) do
begin
puts "Up-front autoloading: #{file} from #{directory}"
require(file)
true
rescue NameError => e
puts "Warning: NameError #{e.message}\n\n#{e.backtrace.join("\n")}"
nil
end
end
end
end
end
class Method
alias :magic_mirror_real_source_location :source_location
def source_location
loc = magic_mirror_real_source_location
return loc unless loc
file,line = loc
[file.sub(MagicMirror.virtual_path, ''), line]
end
end
class UnboundMethod
alias :magic_mirror_real_source_location :source_location
def source_location
loc = magic_mirror_real_source_location
return loc unless loc
file,line = loc
[file.sub(MagicMirror.virtual_path, ''), line]
end
end
class Module
attr_reader :magic_mirror_source_locations
attr_reader :source_locations
attr_reader :module_included_by
alias :magic_mirror_real_append_features :append_features
def append_features(other_mod)
MagicMirror.add_includer(self,other_mod)
magic_mirror_real_append_features(other_mod)
end
#alias :magic_mirror_real_autoload :autoload
def dont_autoload(const_name, path)
unless Kernel.instance_method(:require).source_location
raise "MagicMirror require has been thwarted!"
end
MagicMirror.failed_loads << [Dir.getwd, path]
magic_mirror_real_autoload const_name, path
end
end
module NotKernel
alias :magic_mirror_real_require :require
class << self
alias :magic_mirror_real_private_method_defined? :private_method_defined?
def private_method_defined?(method)
if method.to_sym == :gem_original_require
false
else
magic_mirror_real_private_method_defined? method
end
end
end
def require(path)
MagicMirror.in_require += 1
puts "Loading #{path} at depth #{MagicMirror.in_require}"
ret=begin
magic_mirror_real_require(path)
rescue Gem::LoadError
gem_original_require(path)
end
if Kernel.instance_method(:require).source_location
puts "Loaded #{path} at depth #{MagicMirror.in_require}"
else
raise "MagicMirror require overridden by #{path}"
end
ret
ensure
MagicMirror.in_require -= 1
if MagicMirror.in_require == 0
puts "Reached depth 0 after loading #{path}"
puts "Require is #{Kernel.instance_method(:require).source_location}"
MagicMirror.in_require = 1
begin
MagicMirror.retry_failed_loads
ensure
MagicMirror.in_require = 0
end
end
end
end
class Class
attr_reader :source_locations
attr_reader :magic_mirror_source_locations
end
def filter_symbols(regex,symbols,prefix)
symbols.select do |symb|
symb.class == Symbol
end.map(&:to_s).select do |meth|
regex =~ meth
end.map do |meth|
"#{prefix}#{meth}"
end
end
# ActiveRecord::Fixtures really fucks with this method!
# This is a naive apropos function that works in a similar manner to Pry's
# introspection commands. It starts at Object, gets all the methods and
# constants, and then iterates through the nested classes found in the
# constants.
#
# The reason this doesn't work is that some classes override their
# :methods, :constants, and :instance_methods methods. The apropos
# in MagicMirror is better because it gets a chance to call these methods
# before they get overridden.
def naive_apropos(regex, accept: [:class, :module, :method], klass: Object,seen: [])
seen << klass
filter_symbols(regex,klass.methods,"#{klass}.").each do |match|
puts match
end
filter_symbols(regex,klass.instance_methods,"#{klass}#").each do |match|
puts match
end
filter_symbols(regex,klass.constants,"#{klass}::").each do |match|
puts match
end
klass.constants.each do |const_name|
const = klass.const_get(const_name)
if const.respond_to?(:methods) && const.respond_to?(:instance_methods) && const.respond_to?(:constants) &&
const != Object && !seen.include?(const)
apropos(regex, accept: accept, klass: const, seen: seen)
end
end
rescue => e
puts "Error while searching through #{klass}"
raise
end
class MutexedMagicMirror
def self.method_missing(name, *args)
MagicMirror.with_mutex do
MagicMirror.send(name, *args)
end
end
end
# Presentations
# Presentations were a feature of the Dynamic Windows system on the Symbolics Lisp Machine.
# They allow all data on the screen to retain a link to the in-memory objects they were
# taken from. This was combined with a universal Command Table system, which was integrated
# with the GUI.
#
# SLIME includes a crude attempt to implement presentations within its REPL. Anything
# displayed in red text can be copied and pasted into new Lisp code at the REPL, which
# can access the underlying objects. So you can do something like this:
#
# SLIME> (defvar *foobar* (make-hash-table :test 'equalp))
# #<HASH 0x38384d>
# ;; Copy the HASH above to the REPL
# SLIME> (setf (gethash #<HASH 0x38384d> 'foo) 'bar)
# BAR
# SLIME> (gethash *foobar* 'foo)
# BAR
# SLIME>
#
# You can also right-click on the red text and choose the Inspect option from
# the context menu. This launches an interactive object inspector.
#
# That is about the extent of what SLIME can do with presentations, and perhaps the extent of
# what it makes sense to do if you're not going to implement the GUI system and the command tables,
# perhaps with a few exceptions.
#
# One use-case that I think it's important to support in Ruby MagicMirror is to have the output of
# MagicMirror.apropos be clickable in EMACS. Clicking an apropos result should cause that class, module,
# or method to be opened in EMACS.
#
# An easy way to implement this would be to have MagicMirror specify a JavaScript-style on-click callback.
# The callback would be an Emacs Lisp function which would be passed the Emacs-side presentation object
# to do something with.
#
# The neat trick would be allowing any Ruby method to return an object that would automatically have
# a callback in Emacs, without having to explicitly tell MagicMirror to add it.
#
# SLIME presentations are weak references, so sometimes expressions involving them fail because the
# underlying objects got garbage collected.
#
# Implementing them requires that EMACS be given unique identifiers for each object sent to it for
# display. Ruby provides the .object_id method, which is suitable for this purpose. MagicMirror could
# store all returned objects in a hash, where the object_id is the key. These would be strong references,
# which would eliminate the problem of presentations getting GC'd.
#
# Emacs would have to keep track of which presentations still existed (either in the REPL or a source buffer),
# so it could tell MagicMirror when it can remove objects from the hash table. Some kind of reference-counting system
# would be the easiest to implement.
#
class MagicMirror
@active_record_associations = {}
@reverse_lookup_index = {}
@apropos = {}
@class_apropos = {}
@last_known_class_methods = {}
@last_known_class_instance_methods = {}
@last_known_class_constants = {}
@module_includers = {}
@defined_by_magic_mirror = {}
@in_eval_at = false
@mutex = Object::Mutex.new
module ActiveRecordAssociationInstruments
[:has_one, :has_many, :belongs_to, :has_and_belongs_to_many].each do |m|
define_method(m) do |*args|
name = args[0]
defined_at = caller[0].split(':').slice(0,2)
defined_at[1] = defined_at[1].to_i
MagicMirror.with_mutex do
MagicMirror.update_apropos_entry(name.to_s, { class: self,
type: :instance,
inherited: false,
filename: defined_at[0],
line: defined_at[1] })
MagicMirror.add_active_record_association(self, name, defined_at)
end
if block_given?
super(*args) do |*block_args|
yield *block_args
end
else
super(*args)
end
end
end
def association_locations(name)
MagicMirror.association_locations(self,name)
end
end
def self.add_active_record_association(klass, assoc_name, assoc_location)
@active_record_associations[[klass,assoc_name]] ||= []
@active_record_associations[[klass,assoc_name]] << assoc_location
end
def self.association_locations(klass,assoc_name)
@active_record_associations[[klass,assoc_name]]
end
def self.instrument_active_record_associations(klass)
klass.prepend(ActiveRecordAssociationInstruments)
end
def self.mutexed
MutexedMagicMirror
end
def self.add_includer(mod,includer)
@module_includers[mod] ||= []
@module_includers[mod] << includer
end
def self.included_by(mod)
@module_includers[mod]
end
def self.with_mutex
@mutex.lock
yield
ensure
@mutex.unlock
end
def self.virtual_path
my_pid=$$
"/tmp/magic-mirror-sources.#{my_pid}"
end
def self.dir_butlast(path)
path.split('/')[0..-2].join('/')
end
def self.make_directory_chain(full_path)
if Dir.exists?(full_path)
true
else
make_directory_chain(dir_butlast(full_path))
Dir.mkdir full_path
true
end
end
def self.make_virtual_dir(real_path)
make_directory_chain "#{virtual_path}/#{real_path}"
"#{virtual_path}/#{real_path}"
end
def self.get_real_path(path)
if path[0..virtual_path.length-1] == virtual_path
path[virtual_path.length..-1]
else
path
end
end
def self.write_to_virtual_file(real_path, data)
make_virtual_dir(dir_butlast(real_path))
File.open "#{virtual_path}/#{real_path}", "w" do |f|
f.write data
end
"#{virtual_path}/#{real_path}"
end
def self.with_data_in_file(real_path, data)
virtual_path = write_to_virtual_file(real_path, data)
yield virtual_path
# TODO: Delete the file and associated directories.
end
def self.eval_in_file(real_path, expr, line: 1)
(line-1).times do
expr = "\n" + expr
end
with_data_in_file(real_path, expr) do |virtual_path|
load virtual_path
end
end
def self.class_opening(klass)
if klass.class == Class
"class"
elsif klass.class == Module
"module"
else
raise "Constant #{full_class_name(klass)} is neither class nor module"
end
end
def self.build_class_opening(nesting)
nesting.reverse.map do |klass|
"#{class_opening(klass)} ::#{full_class_name(klass)}"
end.join(';') + ";"
end
def self.build_class_closing(nesting)
nesting.map do |klass| "end" end.join(';')
end
def self.eval_at(file, line, expr)
nesting = nesting_at(file,line)
opening = (nesting && build_class_opening(nesting)) || ""
closing = (nesting && build_class_closing(nesting)) || ""
eval_in_file(file, %{ #{opening} ::Thread.current[:magic_mirror_eval_at_result]=#{expr}; #{closing}}, line: line)
Thread.current[:magic_mirror_eval_at_result]
end
def self.dumb_eval_at(file, line, expr)
# Evaluates EXPR in the class that would contain an expression
# at the given file and line number, without doing anything to ensure that
# methods defined by EXPR will have reasonable source_locations.
#
# eval_at is the smart version that takes the extra trouble.
@in_eval_at = [file, line]
c = class_at(file,line)
if c.is_a? Module
c.module_eval(expr)
elsif c.is_a? Module
c.class_eval(expr)
else
Object.class_eval(expr)
end
ensure
@in_eval_at = false
end
def self.register_class(klass,outer=nil)
@class_apropos[klass] = outer || klass
end
def self.add_class_definition_range(klass, nesting, start_loc,end_loc)
filename,start_line = start_loc
end_line = end_loc[1]
@reverse_lookup_index[filename] ||= {}
@reverse_lookup_index[filename][start_line] = { class: klass,
length: end_line-start_line,
nesting: nesting }
end
def self.seen_file?(filename)
!!@reverse_lookup_index[filename]
end
def self.info_at(filename, line)
@reverse_lookup_index[filename] &&
@reverse_lookup_index[filename].each do |start_line,info|
if line >= start_line && line <= start_line+info[:length]
return info
end
end
nil
end
def self.class_at(filename, line)
info = info_at(filename, line)
info && info[:class]
end
def self.nesting_at(filename, line)
info = info_at(filename, line)
info && info[:nesting]
end
def self.update_apropos_entry(entry, new_def)
entry[new_def[:class]] = new_def
entry
rescue TypeError => e
entry
end
def self.safe_method_source(method_type, klass, method_name)
if method_type == :class
klass.method(method_name).source_location
else
klass.instance_method(method_name).source_location
end
rescue => e
# This is necessary because of all those fuckers who override
# the "method" method.
nil
end
def self.update_methods_for_class(klass,methods,method_type)
methods &&
methods.each do |meth|
next unless meth.class == Symbol
@apropos[meth.to_s] ||= {}
filename,line = safe_method_source(method_type, klass, meth)
update_apropos_entry(@apropos[meth.to_s], { class: klass, type: method_type, inherited: class_at(filename,line) != klass,
filename: filename, line: line })
end
nil
rescue ArgumentError
puts "MagicMirror WARNING: Class #{klass} patches one or more of the methods 'instance_method' or 'method'."
puts "MagicMirror WARNING: Unable to collect method-location information for #{klass}"
end
def self.get_methods(klass,type)
case type
when :class
klass.methods + klass.private_methods
when :instance
klass.instance_methods + klass.private_instance_methods
end
end
$total_constants = 0
def self.update_apropos(klass)
return unless klass
key = klass.to_s
if @last_known_class_methods[key] != klass.methods
update_methods_for_class(klass,get_methods(klass,:class),:class)
@last_known_class_methods[key] = klass.methods
end
if @last_known_class_instance_methods[key] != klass.instance_methods
update_methods_for_class(klass,get_methods(klass,:instance),:instance)
@last_known_class_instance_methods[key] = klass.instance_methods
end
if @last_known_class_constants[key] != klass.constants
klass.constants.each do |const|
register_class const,klass
end
@last_known_class_constants[key] = klass.constants
end
end
def self.fqmn(klass,name,type)
separator = if type == :class
'.'
else
'#'
end
"#{klass}#{separator}#{name}"
end
def self.apropos_entry_strings(name, entry, include_inherited)
result=[]
entry.each do |klass,definition|
next if !include_inherited && definition[:inherited]
result << fqmn(klass,name,definition[:type])
end
result
end
def self.render_class_name(klass,outer)
if klass == outer
"#{klass}"
else
"#{outer}::#{klass}"
end
end
def self.full_class_name(klass)
render_class_name(klass,@class_apropos[klass])
end
def self.apropos_data(regex,include_inherited: false, match_classes: true, match_methods: true)
results = []
if match_classes
@class_apropos.each do |klass,outer|
class_name = render_class_name(klass,outer)
if regex =~ class_name
results << class_name
end
end
end
if match_methods
@apropos.each do |method_name, entry|
apropos_entry_strings(method_name, entry, include_inherited).each do |fqmn|
if regex =~ fqmn
results << fqmn
end
end
end
end
results
end
def self.apropos(regex,include_inherited: false, match_classes: true, match_methods: true)
apropos_data(regex, include_inherited: include_inherited,
match_classes: match_classes, match_methods: match_methods).each do |datum|
puts datum
end
nil
end
end
TracePoint.new(:class,:end) do |tp|
tp.self.module_eval do
next if self.frozen?
next if /^#/ =~ begin
self.to_s
rescue Exception => e
next
end
case tp.event
when :class
MagicMirror.with_mutex do
MagicMirror.register_class(self)
MagicMirror.push_nesting(self)
MagicMirror.report_loaded_file(tp.path)
end
@magic_mirror_last_begin = [tp.path, tp.lineno]
@source_locations ||= []
@source_locations << @magic_mirror_last_begin
when :end
if @magic_mirror_last_begin.nil?
else
@magic_mirror_source_locations ||= []
@magic_mirror_source_locations << { begin: @magic_mirror_last_begin,
end: [tp.path, tp.lineno],
nesting: MagicMirror.inferred_nesting.reverse }
MagicMirror.with_mutex do
begin
if self.name == 'ActiveRecord::Associations::ClassMethods'
MagicMirror.instrument_active_record_associations(self)
end
rescue => e
end
MagicMirror.add_class_definition_range(self, MagicMirror.inferred_nesting.reverse, @magic_mirror_last_begin, [tp.path, tp.lineno])
MagicMirror.update_apropos(self)
MagicMirror.pop_nesting
end
end
end
end
end.enable
require 'ripper'
# FIXME: In Ruby, $stdin, $stdout, and $stderr and their associated constants
# are generated from scratch on a per-thread basis. They are not copied
# from the main thread's values, but rather are attached directly to
# the underlying Unix fd's 0, 1, and 2.
#
# This presents a serious problem, because we want threads that are
# created from SRIME to have $stdin/$stdout/$stderr that are redirected
# to the socket, just like the main MagicMirror server thread.
#
# The MagicMirror@multiplexed_streams are meant as a solution to a similar
# problem, but the wrong one. Multiplexed streams would be useful if
# $stdin, $stdout, and $stderr were global variables whose values
# cut across threads.
#
# Instead, we must abandon multiplexed streams. Instead, new threads
# created by threads that are attached to SRIME should have STDIO objects
# that are also attached to SRIME. while threads created elsewhere
# (eg, from the main thread) should continue to have Ruby's default
# behavior.
class ZThread
class << self
alias :magic_mirror_real_new :new
def new(*args, &block)
parent_stdin=$stdin.dup
parent_stdout=$stdout.dup
parent_stderr=$stderr.dup
MagicMirror.with_redirected_streams([$stdin,$stdout,$stderr],
[parent_stdin,parent_stdout,parent_stderr]) do
magic_mirror_real_new(*args, &block)
end
ensure
parent_stdin.close
parent_stdout.close
parent_stderr.close
end
end
end
class MagicMirror
def self.with_redirected_streams(original_streams, new_streams)
restores=[]
original_streams.zip(new_streams).each do |original_stream,new_stream|
restores << original_stream.dup
original_stream.reopen new_stream
end
yield
ensure
original_streams.zip(restores) do |original_stream,restore|
original_stream.reopen restore
end
end
class Server
def ripper_sexp_to_lisp(sexp)
if sexp.is_a?(Array)
'(' + (sexp.map do |elem|
ripper_sexp_to_lisp(elem)
end.join(' ')) + ')'
elsif sexp.is_a?(Symbol) || sexp.is_a?(Numeric)
sexp.to_s
elsif sexp.is_a?(String)
'"' + sexp + '"'
elsif sexp.is_a?(FalseClass)
"nil"
elsif sexp.is_a?(TrueClass)
"t"
elsif sexp.is_a?(NilClass)
"nil"
else
raise "Unable to translate a #{sexp.class} to Emacs Lisp."
end
end
def parse_ruby_to_lisp(ruby_text)
ripper_sexp_to_lisp(Ripper.sexp ruby_text)
end
def read_command(sock)
end
def handle_client(sock)
Thread.new do
# TODO: Forward STDIN and STDOUT to sockets.
# TODO: Full-duplex interaction.
# TODO: Accept commands from EMACS.
# TODO: Connect to this from EMACS.
# TODO: Implement a command to relay an interrupt from EMACS
# TODO: Figure out how byebug works and implement something like it here.
# TODO: Implement presentations
# TODO: Make MagicMirror.apropos return presentations that when clicked, cause
# EMACS to open the source file where the class or method is defined.
loop do
end
end
end
def initialize(socket_path: "/tmp/ruby-magic-mirror.sock")
Thread.new do
listener=UNIXServer.new socket_path
loop do
handle_client(listener.accept)
end
end
end
end
end
| mit |
Adam94PK/cars_client | app/views/cars/z-cars.component.js | 382 | /**
* Created by adam on 22.01.2017.
*/
angular.module('zCars').
component('zCars', {
templateUrl: 'views/cars/z-cars.tempalte.html',
controller: ['$scope', 'CarService', function ZCarsController($scope, CarService){
$scope.adress = CarService.addres;
CarService.getCars().then( function (response) {
$scope.cars = response.data;
});
}]
}); | mit |
tomsowerby/omnipay-metacharge | src/Omnipay/Metacharge/Gateway.php | 5218 | <?php
namespace Omnipay\Metacharge;
use Omnipay\Common\AbstractGateway;
/**
* Gateway.php
*
* Created on: 01/04/14
*
* @package Omnipay\Metacharge
* @author Thomas Sowerby <[email protected]>
*/
class Gateway extends AbstractGateway
{
/**
* getName.
*
*
* @return string
*/
public function getName()
{
return 'Metacharge (PayPoint.net)';
}
/**
* getDefaultParameters.
*
*
* @return array
*/
public function getDefaultParameters()
{
return array(
'instId' => '',
'sharedKey' => null,
'testMode' => false,
'3DSecureResponseUrl' => null,
'accountId' => null,
);
}
/**
* getInstId.
*
*
* @return int
*/
public function getInstId()
{
return $this->getParameter('instId');
}
/**
* setInstId.
*
* @param int $value
*
* @return $this
*/
public function setInstId($value)
{
return $this->setParameter('instId', $value);
}
/**
* getSharedKey.
*
*
* @return string
*/
public function getSharedKey()
{
return $this->getParameter('sharedKey');
}
/**
* setSharedKey.
*
* @param string $value
*
* @return $this
*/
public function setSharedKey($value)
{
return $this->setParameter('sharedKey', $value);
}
/**
* get3DSecureResponseUrl.
*
*
* @return string
*/
public function get3DSecureResponseUrl()
{
return $this->getParameter('3DSecureResponseUrl');
}
/**
* set3DSecureResponseUrl.
*
* @param string $value
*
* @return $this
*/
public function set3DSecureResponseUrl($value)
{
return $this->setParameter('3DSecureResponseUrl', $value);
}
//Payment, Payout, FraudGuard
/**
* getAccountId.
*
*
* @return int
*/
public function getAccountId()
{
return $this->getParameter('accountId');
}
/**
* setAccountId.
*
* @param int $value
*
* @return $this
*/
public function setAccountId($value)
{
return $this->setParameter('accountId', $value);
}
/**
* purchase.
*
* @param array $parameters
*
* @return \Omnipay\Common\Message\RequestInterface
*/
public function purchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\PaymentRequest', $parameters);
}
/**
* refund.
*
* @param array $parameters
*
* @return mixed
*/
public function refund(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\RefundRequest', $parameters);
}
/**
* payout.
*
* @param array $parameters
*
* @return mixed
*/
public function payout(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\PayoutRequest', $parameters);
}
/**
* repeatPayment.
*
* @param array $parameters
*
* @return mixed
*/
public function repeatPayment(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\RepeatPaymentRequest', $parameters);
}
/**
* preAuthCapture.
*
* @param array $parameters
*
* @return mixed
*/
public function preAuthCapture(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\PreAuthCaptureRequest', $parameters);
}
/**
* preAuthVoid.
*
* @param array $parameters
*
* @return mixed
*/
public function preAuthVoid(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\PreAuthVoidRequest', $parameters);
}
/**
* subscriptionCancellation.
*
* @param array $parameters
*
* @return mixed
*/
public function subscriptionCancellation(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\SubscriptionCancellationRequest', $parameters);
}
/**
* transactionConfirm.
*
* @param array $parameters
*
* @return mixed
*/
public function transactionConfirm(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\TransactionConfirmRequest', $parameters);
}
/**
* fraudGuardCheck.
*
* @param array $parameters
*
* @return mixed
*/
public function fraudGuardCheck(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\FraudGuardCheckRequest', $parameters);
}
/**
* s3DAuthorisationResume.
*
* @param array $parameters
*
* @return mixed
*/
public function s3DAuthorisationResume(array $parameters = array())
{
return $this->createRequest('\Omnipay\Metacharge\Message\S3DAuthorisationResumeRequest', $parameters);
}
}
| mit |
fdietz/jwz_threading | test/test_helper.rb | 685 | dir = File.dirname(__FILE__)
lib_path = File.expand_path(File.join(dir, '..', 'lib'))
#$LOAD_PATH.unshift lib_path unless $LOAD_PATH.include?(lib_path)
require 'test/unit'
require 'rubygems'
require 'lib/threading'
class Test::Unit::TestCase
# test "verify something" do
# ...
# end
def self.test(name, &block)
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
defined = instance_method(test_name) rescue false
raise "#{test_name} is already defined in #{self}" if defined
if block_given?
define_method(test_name, &block)
else
define_method(test_name) do
flunk "No implementation provided for #{name}"
end
end
end
end
| mit |
ChrisHuston/Wiki | app/php/editPagePrev.php | 710 | <?php
session_start();
$_POST = json_decode(file_get_contents("php://input"), true);
if (isset($_SESSION['wiki_id']) && isset($_POST['page_id'])) {
include("advanced_user_oo.php");
Define('DATABASE_SERVER', $hostname);
Define('DATABASE_USERNAME', $username);
Define('DATABASE_PASSWORD', $password);
Define('DATABASE_NAME', 'wiki');
$mysqli = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);
$page_id = $_POST['page_id'];
$prev = $mysqli->real_escape_string($_POST['prev']);
$query = "UPDATE pages SET prev='$prev' WHERE page_id='$page_id'; ";
$result = $mysqli->query($query);
$mysqli->close();
echo json_encode($result);
}
?> | mit |
akaraatanasov/JS-Core | JS Applications/Patterns and Routing - Lab/js/app.js | 1921 | const handlers = {};
$(() => {
const app = Sammy('#main', function () {
this.use('Handlebars', 'hbr');
this.get('index.html', displayWelcome);
//this.get('', displayWelcome);
function displayWelcome() {
this.loadPartials({
header: './templates/common/header.hbr',
footer: './templates/common/footer.hbr'
}).then(function () {
this.partial('./templates/welcome.hbr');
});
}
this.get('#/register', function () {
this.loadPartials({
header: './templates/common/header.hbr',
footer: './templates/common/footer.hbr'
}).then(function () {
this.partial('./templates/register.hbr');
});
});
this.get('#/contacts', handlers.contactsController);
this.get('#/profile', function () {
this.loadPartials({
header: './templates/common/header.hbr',
footer: './templates/common/footer.hbr'
}).then(function () {
this.partial('./templates/profile.hbr');
});
});
this.get('#/logout', function () {
auth.logout()
.then(() => {
localStorage.clear();
this.redirect('#');
})
});
this.post('#/login', function (context) {
let username = context.params.username;
let password = context.params.password;
auth.login(username, password)
.then(function (data) {
auth.saveSession(data);
context.redirect('#/contacts');
});
});
this.post('#/register', function () {
});
this.post('#/profile', function () {
});
});
app.run();
}); | mit |
BiserSirakov/TelerikAcademyHomeworks | C# - Part 2/Text Files/11.PrefixTest/PrefixTest.cs | 860 | //Write a program that deletes from a text file all words that start with the prefix test.
//Words contain only the symbols 0…9, a…z, A…Z, _.
using System;
using System.IO;
class PrefixTest
{
static void Main()
{
using (StreamReader reader = new StreamReader("test.txt"))
{
using (StreamWriter output = new StreamWriter("fixed.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
if ((line[0] != 't') || (line[1] != 'e') || (line[2] != 's') || (line[3] != 't'))
{
output.WriteLine(line);
}
line = reader.ReadLine();
}
}
}
Console.WriteLine("All words starting with \"test\" removed.");
}
} | mit |
HAZARDU5/gameboy | js/other/base64.js | 853 | "use strict";
function to_little_endian_dword(str) {
return to_little_endian_word(str) + to_little_endian_word(str >> 16);
}
function to_little_endian_word(str) {
return to_byte(str) + to_byte(str >> 8);
}
function to_byte(str) {
return String.fromCharCode(str & 0xFF);
}
function arrayToBase64(array) {
var binString = "";
var length = array.length;
for (var index = 0; index < length; ++index) {
if (typeof array[index] == "number") {
binString += String.fromCharCode(array[index]);
}
}
return window.btoa(binString);
}
function base64ToArray(b64String) {
var binString = window.atob(b64String);
var outArray = [];
var length = binString.length;
for (var index = 0; index < length;) {
outArray.push(binString.charCodeAt(index++) & 0xFF);
}
return outArray;
} | mit |
colorium/http | src/Colorium/Http/Response.php | 5681 | <?php
namespace Colorium\Http;
class Response
{
/** @var int */
public $code = 200;
/** @var string */
public $format = 'text/plain';
/** @var string */
public $charset = 'utf-8';
/** @var array */
public $headers = [];
/** @var string */
public $content;
/** @var bool */
public $raw = false;
/**
* New Response
*
* @param string $content
* @param int $code
* @param array $headers
*/
public function __construct($content = null, $code = 200, array $headers = [])
{
$this->content = $content;
$this->code = $code;
foreach($headers as $header => $value) {
$this->header($header, $value);
}
}
/**
* Set header
*
* @param string $name
* @param string $value
* @param bool $replace
*
* @return $this
*/
public function header($name, $value, $replace = true)
{
$name = strtolower($name);
if(isset($this->headers[$name]) and !$replace) {
if(is_array($this->headers[$name])) {
array_push($this->headers[$name], $value);
}
else {
$this->headers[$name] = [
$this->headers[$name],
$value
];
}
}
else {
$this->headers[$name] = $value;
}
return $this;
}
/**
* Set cookie
*
* @param string $name
* @param string $value
* @param int $expires
*
* @return $this
*/
public function cookie($name, $value, $expires = 0)
{
$cookie = urlencode($name);
// has value
if($value) {
$cookie .= '=' . urlencode($value) . ';';
$cookie .= ' expires=' . gmdate("D, d-M-Y H:i:s T", time() - 31536001) . ';';
}
// delete cookie
else {
$cookie .= '=deleted;';
if($expires) {
$cookie .= ' expires=' . gmdate("D, d-M-Y H:i:s T", time() - $expires);
}
}
return $this->header('Set-Cookie', $cookie, false);
}
/**
* Add no-cache headers
*
* @return $this
*/
public function noCache()
{
$this->header('Cache-Control', 'no-cache, must-revalidate');
$this->header('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
return $this;
}
/**
* Response already sent ?
*
* @return bool
*/
public function sent()
{
return headers_sent();
}
/**
* Send response
*
* @return string
*/
public function send()
{
// send headers
if(!$this->sent()) {
// set content type
if(!isset($this->headers['Content-Type'])) {
$header = 'Content-Type: ' . $this->format;
if($this->charset) {
$header .= '; charset=' . $this->charset;
}
header($header);
}
// set http code
header('HTTP/1.1 ' . $this->code . ' ' . Status::message($this->code), true, $this->code);
// compile header
foreach($this->headers as $name => $value) {
if(is_array($value)) {
foreach($value as $subvalue) {
header($name . ': ' . $subvalue);
}
}
else {
header($name . ': ' . $value);
}
}
}
// send content
echo (string)$this->content;
return $this->sent();
}
/**
* Raw response
*
* @param string $content
* @param int $code
* @param array $headers
* @return Response
*/
public static function create($content = null, $code = 200, array $headers = [])
{
return new Response($content, $code, $headers);
}
/**
* Create HTML response
*
* @param string $content
* @param int $code
* @param array $headers
* @return Response\Html
*/
public static function html($content = null, $code = 200, array $headers = [])
{
return new Response\Html($content, $code , $headers);
}
/**
* Create JSON response
*
* @param string $content
* @param int $code
* @param array $headers
* @return Response\Json
*/
public static function json($content = null, $code = 200, array $headers = [])
{
return new Response\Json($content, $code , $headers);
}
/**
* Create redirect response
*
* @param string $uri
* @param int $code
* @param array $headers
* @return Response\Redirect
*/
public static function redirect($uri, $code = 200, array $headers = [])
{
return new Response\Redirect($uri, $code , $headers);
}
/**
* Create download response
*
* @param string $filename
* @param int $code
* @param array $headers
* @return Response\Redirect
*/
public static function download($filename, $code = 200, array $headers = [])
{
return new Response\Download($filename, $code , $headers);
}
/**
* Create template response
*
* @param string $template
* @param array $vars
* @param int $code
* @param array $headers
* @return Response\Template
*/
public static function template($template, array $vars = [], $code = 200, array $headers = [])
{
return new Response\Template($template, $vars, $code , $headers);
}
} | mit |
tostegroo/rivescript-nginb-js | controllers/update.js | 2739 | var promise = require('bluebird');
var botconfig = require('../config/botconfig');
var debugutil = require('../utils/debugutil');
var stringutil = require('../utils/stringutil');
var mysql = require('easy-mysql-promise')(botconfig.database.config);
module.exports = function()
{
return new Updatectl();
}
function Updatectl(){}
Updatectl.prototype.processUpdate = function processUpdate(sender, page_id, update, current_data)
{
return new promise(function(resolve)
{
if(mysql && typeof(update)=='object')
{
for (var key in update)
{
var table = key;
var update_data = update[key];
if(current_data!=undefined)
update_data = getUpdateValue(update_data, current_data);
mysql.updateTable(table, update_data, 'sender_id="'+sender+'" AND page_id="'+page_id+'"')
.then(function(response)
{
debugutil.log('update_response', response);
resolve(response);
});
}
}
else
resolve(false);
});
}
function getUpdateValue(update_data, current_data, return_type)
{
return_type = return_type || 'object';
var to_update = {};
for (var k in update_data)
{
var key_array = k.split('.');
var base_key = key_array[0];
var parm_key = (key_array.length>1) ? key_array[1] : 'value';
var update_string = update_data[k].toString();
var current_value = parseInt(update_data[k]);
current_value = isNaN(current_value) ? update_string : current_value;
var update_value = current_value;
if(current_data!=undefined && current_data.hasOwnProperty(base_key))
{
current_value = current_data[base_key];
var newvalue = false;
if(typeof(current_value)=='string' && current_value.indexOf('{')!=-1)
{
try
{
var obj = stringutil.JSONparse(current_value);
if(obj.hasOwnProperty(parm_key))
{
newvalue = getNewValueFromString(update_string, obj[parm_key], update_value);
obj[parm_key] = newvalue;
}
to_update[base_key] = JSON.stringify(obj);
}
catch(err)
{
to_update[base_key] = current_value;
}
}
else
{
newvalue = getNewValueFromString(update_string, current_value, update_value);
to_update[base_key] = newvalue;
}
}
}
if(return_type=='string')
to_update = JSON.stringify(to_update);
return to_update;
}
function getNewValueFromString(string, current_value, update_value)
{
var new_value = current_value;
if(typeof(update_value)=='number')
{
if(string.indexOf('+')!=-1 || string.indexOf('-')!=-1)
new_value += update_value;
else if(string.indexOf('*')!=-1)
new_value *= update_value;
else if(string.indexOf('/')!=-1)
new_value /= update_value;
else
new_value = update_value;
}
else
new_value = update_value;
return new_value;
}
| mit |
derekstavis/bluntly | vendor/github.com/youtube/vitess/go/vt/tabletserver/splitquery/testutils_test.go | 3565 | package splitquery
// This file contains utility routines for used in splitquery tests.
import (
"fmt"
"strconv"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/vt/sqlparser"
"github.com/youtube/vitess/go/vt/tabletserver/engines/schema"
)
// getSchema returns a fake schema object that can be given to SplitParams
func getTestSchema() map[string]*schema.Table {
table := schema.Table{
Name: sqlparser.NewTableIdent("test_table"),
}
zero, _ := sqltypes.BuildValue(0)
table.AddColumn("id", sqltypes.Int64, zero, "")
table.AddColumn("int32_col", sqltypes.Int32, zero, "")
table.AddColumn("uint32_col", sqltypes.Uint32, zero, "")
table.AddColumn("int64_col", sqltypes.Int64, zero, "")
table.AddColumn("uint64_col", sqltypes.Uint64, zero, "")
table.AddColumn("float32_col", sqltypes.Float32, zero, "")
table.AddColumn("float64_col", sqltypes.Float64, zero, "")
table.AddColumn("user_id", sqltypes.Int64, zero, "")
table.AddColumn("user_id2", sqltypes.Int64, zero, "")
table.AddColumn("id2", sqltypes.Int64, zero, "")
table.AddColumn("count", sqltypes.Int64, zero, "")
table.PKColumns = []int{0, 7}
addIndexToTable(&table, "PRIMARY", "id", "user_id")
addIndexToTable(&table, "idx_id2", "id2")
addIndexToTable(&table, "idx_int64_col", "int64_col")
addIndexToTable(&table, "idx_uint64_col", "uint64_col")
addIndexToTable(&table, "idx_float64_col", "float64_col")
addIndexToTable(&table, "idx_id_user_id", "id", "user_id")
addIndexToTable(&table, "idx_id_user_id_user_id_2", "id", "user_id", "user_id2")
table.SetMysqlStats(
int64Value(1000), /* TableRows */
int64Value(100), /* DataLength */
int64Value(123), /* IndexLength */
int64Value(456), /* DataFree */
int64Value(457), /* MaxDataLength */
)
result := make(map[string]*schema.Table)
result["test_table"] = &table
tableNoPK := schema.Table{
Name: sqlparser.NewTableIdent("test_table_no_pk"),
}
tableNoPK.AddColumn("id", sqltypes.Int64, zero, "")
tableNoPK.PKColumns = []int{}
result["test_table_no_pk"] = &tableNoPK
return result
}
var testSchema = getTestSchema()
func getTestSchemaColumn(tableName, columnName string) *schema.TableColumn {
tableSchema := testSchema[tableName]
columnIndex := tableSchema.FindColumn(sqlparser.NewColIdent(columnName))
if columnIndex < 0 {
panic(fmt.Sprintf(
"Can't find columnName: %v (tableName: %v) in test schema.", columnName, tableName))
}
return &tableSchema.Columns[columnIndex]
}
// int64Value builds a sqltypes.Value of type sqltypes.Int64 containing the given int64 value.
func int64Value(value int64) sqltypes.Value {
return sqltypes.MakeTrusted(sqltypes.Int64, strconv.AppendInt([]byte{}, value, 10))
}
// uint64Value builds a sqltypes.Value of type sqltypes.Uint64 containing the given uint64 value.
func uint64Value(value uint64) sqltypes.Value {
return sqltypes.MakeTrusted(sqltypes.Uint64, strconv.AppendUint([]byte{}, value, 10))
}
// float64Value builds a sqltypes.Value of type sqltypes.Float64 containing the given float64 value.
func float64Value(value float64) sqltypes.Value {
return sqltypes.MakeTrusted(sqltypes.Float64, strconv.AppendFloat([]byte{}, value, 'f', -1, 64))
}
// addIndexToTable adds an index named 'indexName' to 'table' with the given 'indexCols'.
// It uses 12345 as the cardinality.
// It returns the new index.
func addIndexToTable(table *schema.Table, indexName string, indexCols ...string) *schema.Index {
index := table.AddIndex(indexName)
for _, indexCol := range indexCols {
index.AddColumn(indexCol, 12345)
}
return index
}
| mit |
phpinpractice/event-store | lib/eventstore-projections/Projector.php | 1041 | <?php
namespace PhpInPractice\EventStore\Projections;
use Rb\Specification\SpecificationInterface as Specification;
interface Projector
{
public function uses(array $streams);
public function filterUsing(Specification $specification);
public function on($eventCode, callable $projectorAction);
public function project(Snapshot $fromSnapshot = null);
/**
* Calculate a signature with which to determine if a snapshot can be loaded on this projector.
*
* Whenever a projector's projection parameters change (such as which streams to read from, what events
* to filter and which events to project) is an earlier created snapshot no longer valid. This means that
* when this occurs that any given snapshot is to be disregarded and a complete re-projection needs to be done.
*
* @return string
*/
public function signature();
public function lastIndex();
public function projection();
/**
* @return Snapshot
*/
public function createSnapshot();
}
| mit |
unsilo/uns_themes | app/assets/javascripts/uns_themes/themes/unsilo.js | 634 | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require uns_themes/themes/unsilo/background_anim
| mit |
filipgorny/oro-academy-project | src/IssuesBundle/Tests/Unit/Model/Service/IssueUpdateStampTest.php | 1546 | <?php
namespace IssuesBundle\Tests\Unit\Model\Service;
use IssuesBundle\Entity\Issue;
use IssuesBundle\Model\Service\IssueUpdateStamp;
use Oro\Bundle\UserBundle\Entity\User;
class IssueUpdateStampTest extends \PHPUnit_Framework_TestCase
{
public function testUpdatesDates()
{
$user = new User();
$user->setUsername('test user');
$token = $this->getMock('\Symfony\Component\Security\Core\Authentication\Token', ['getUser']);
$token->expects($this->any())
->method('getUser')
->will($this->returnValue($user));
$tokenManager = $this->getMockBuilder(
'Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface'
)
->disableOriginalConstructor()
->getMock();
$tokenManager->expects($this->any())
->method('getToken')
->will($this->returnValue($token));
$issueUpdateStamp = new IssueUpdateStamp($tokenManager);
$issue = new Issue();
$previousUpdatedAtDate = new \DateTime('now');
$previousUpdatedAtDate->modify('-5 days');
$issue->setUpdatedAt($previousUpdatedAtDate);
$issueUpdateStamp->populateCreationAndUpdateStamps($issue);
$this->assertInstanceOf('\DateTime', $issue->getCreatedAt());
$this->assertInstanceOf('\DateTime', $issue->getUpdatedAt());
$this->assertNotEquals($previousUpdatedAtDate, $issue->getUpdatedAt());
$this->assertEquals($user, $issue->getUpdatedBy());
}
}
| mit |
thebravoman/software_engineering_2016 | h16_nodejs_query_filtering/app_b_15/app.js | 842 |
var http = require('http');
var url = require('url');
var requestHandler = require('./modules/.js');
function handleRequest(request, response)
{
if (request.url ==='/favicon.ico')
{
console.log('Ignore facicon request...');
}
else
{
var get_params = url.parse(request.url, true);
if (get_params.query.image != null && get_params.query.image != null)
{
dataProvider.provideData('images/image.jpg',{'Content-Type': 'image/jpeg'}, response);
}
if else
{
dataProvider.provideData('data/data.json',{'Content-Type': 'application/json', 'Image-Url': 'http://localhost:8215/?image'}, response);
}
else{
dataProvider.provideList('data/data.json',{'Content-Type': 'application/json'}, response);
}
}
}
http.createServer(requestHandler.requestHandler).listen(8215, 'localhost');
| mit |
adamwight/WikiEduDashboard | spec/models/commons_upload_spec.rb | 753 | # == Schema Information
#
# Table name: commons_uploads
#
# id :integer not null, primary key
# user_id :integer
# file_name :string(255)
# uploaded_at :datetime
# usage_count :integer
# created_at :datetime
# updated_at :datetime
# thumburl :string(2000)
# thumbwidth :string(255)
# thumbheight :string(255)
# deleted :boolean default(FALSE)
#
require 'rails_helper'
RSpec.describe CommonsUpload, type: :model do
describe '#url' do
it 'should return the url of the Commons file page' do
upload = create(:commons_upload,
file_name: 'File:MyFile.jpg')
expect(upload.url)
.to eq('https://commons.wikimedia.org/wiki/File:MyFile.jpg')
end
end
end
| mit |
RectorPHP/Rector | vendor/ssch/typo3-rector/stubs/tslib_cObj.php | 160 | <?php
namespace RectorPrefix20210615;
if (\class_exists('tslib_cObj')) {
return;
}
class tslib_cObj
{
}
\class_alias('tslib_cObj', 'tslib_cObj', \false);
| mit |
alexratmanpl/QSF-plugin | src/js/script.js | 633 | $(document).ready(function() {
//QSF plugin init
$('#search-engine form').creoQSF({
slideUp: 300,
slideDown: 300,
dataPath: 'cities'
});
//Search field show/hide
function showSearchField() {
$(".return-trip").slideDown(400);
}
function hideSearchField() {
$(".return-trip").slideUp(400);
}
$("#return-trip-menu").on("click", showSearchField);
$("#oneway-trip-menu").on("click", hideSearchField);
// Datepicker (additional plugin)
//
// https://bootstrap-datepicker.readthedocs.org/en/latest/)
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
startDate: '-3d',
autoclose: true
});
}); | mit |
milosbem/myAmit | dbnet/db_net.hpp | 34 | extern "C"
{
#include "db_net.h"
} | mit |
baverman/fmd | fmd/fsutils.py | 2999 | import glib
import gio
NONE_CALLBACK = lambda *args: None
class Executor(object):
def __init__(self):
self.job_queue = []
self.is_run = False
self.cancel = gio.Cancellable()
def job_done(self, source, result, moved):
source.copy_finish(result)
if moved:
source.delete()
glib.idle_add(self.idle)
def job_move(self, source, target):
source.copy_async(target, self.job_done, NONE_CALLBACK, gio.FILE_COPY_NOFOLLOW_SYMLINKS,
cancellable=self.cancel, user_data=True)
def job_move_dir(self, source, target):
pass
def job_copy(self, source, target):
source.copy_async(target, self.job_done, NONE_CALLBACK, gio.FILE_COPY_NOFOLLOW_SYMLINKS,
cancellable=self.cancel, user_data=False)
def idle(self):
try:
job = self.job_queue.pop(0)
except IndexError:
self.is_run = False
return False
job[0](*job[1:])
return False
def check_and_run(self):
if not self.is_run:
self.is_run = True
glib.idle_add(self.idle)
def copy(self, filelist, target):
for f in filelist:
fi = f.query_info('standard::type', gio.FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
tf = target.get_child(f.get_basename())
self.push_copy_task(f, tf, fi.get_file_type())
self.check_and_run()
def push_copy_task(self, source, target, source_type=None):
if not source_type:
source_type = source.query_info('standard::type',
gio.FILE_QUERY_INFO_NOFOLLOW_SYMLINKS).get_file_type()
if source_type == gio.FILE_TYPE_DIRECTORY:
self.job_queue.append((None, source, target))
else:
self.job_queue.append((self.job_copy, source, target))
def push_move_task(self, source, target, source_type=None):
if not source_type:
source_type = source.query_info('standard::type',
gio.FILE_QUERY_INFO_NOFOLLOW_SYMLINKS).get_file_type()
if source_type == gio.FILE_TYPE_DIRECTORY:
self.job_queue.append((self.job_move_dir, source, target))
else:
self.job_queue.append((self.job_move, source, target))
def move(self, filelist, target):
target_fs = target.query_info('id::filesystem').get_attribute_as_string('id::filesystem')
for f in filelist:
if target.equal(f.get_parent()):
continue
fi = f.query_info('standard::type,id::filesystem', gio.FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
source_fs = fi.get_attribute_as_string('id::filesystem')
tf = target.get_child(f.get_basename())
if source_fs == target_fs:
f.move(tf, NONE_CALLBACK, gio.FILE_COPY_NOFOLLOW_SYMLINKS)
else:
self.push_move_task(f, tf, fi.get_file_type())
self.check_and_run()
def cancel(self):
pass | mit |
ryana/mulligan | mulligan.rb | 1068 | module RetryHarder
class RetryResult
attr_accessor :success
def initialize(options)
self.success = options[:success]
end
def on_failure(&block)
if !success
block.call
end
self
end
def on_success(&block)
if success
block.call
end
self
end
end
module InstanceMethods
def retry_harder(options, &block)
times_to_run = options.delete(:times) || 1
wait_time = options.delete(:wait_time) || 0.5
times_to_run.times do
begin
block.call
@success = true
break
rescue => e
sleep wait_time
@success = false
end
end
::RetryHarder::RetryResult.new(:success => @success)
end
end
def self.initialize
Object.send(:include, RetryHarder::InstanceMethods)
end
end
__END__
# Example
RetryHarder.initialize
puts "BEGIN"
retry_harder(:times => 4) do
puts "harder!"
#raise
end.on_failure do
puts "fail"
end.on_success do
puts "winning"
end
puts "DONE"
| mit |
secknv/pymod | mods/CompMod.py | 1225 | """
Scraps compliments from http://emergencycompliment.com/
Special thanks to Nate Beatty for taking time to give me some tips and help me scrap compliments
from the above mentioned website, where he "codes and does fancy internet stuff to everything"
This module is mostly code he provided to me, with a few changes, just to make it fit inside
the pymod program and python conventions.
http://natebeatty.com/
"""
import json
import requests
from random import randint
def reduce(asd):
return asd['gsx$compliments']['$t']
def get_compliment_list(url):
response = requests.get(url)
json_data = json.loads(response.text)
return list(map(reduce, json_data["feed"]["entry"]))
class CompMod:
rank = 0
help_dict = {'py_comp': 'Chats a random compliment.'}
url = 'https://spreadsheets.google.com/feeds/list/1eEa2ra2yHBXVZ' \
'_ctH4J15tFSGEu-VTSunsrvaCAV598/od6/public/values?alt=json'
def __init__(self, client, message):
self.client = client
self.message = message
async def py_comp(self):
complist = get_compliment_list(CompMod.url)
num = randint(0, len(complist))
await self.client.send_message(self.message.channel, complist[num]) | mit |
markus1978/modsoft_praktikum | plugins/de.hub.modsoft.exercise6.xtext.ui/xtend-gen/de/hub/modsoft/twittersearch/xtext/ui/outline/TwitterSearchOutlineTreeProvider.java | 417 | /**
* generated by Xtext
*/
package de.hub.modsoft.twittersearch.xtext.ui.outline;
import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider;
/**
* Customization of the default outline structure.
*
* See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#outline
*/
@SuppressWarnings("all")
public class TwitterSearchOutlineTreeProvider extends DefaultOutlineTreeProvider {
}
| mit |
carbonjs/carbon-form | lib/elements/recaptcha.js | 2569 | /**
* @Author: Amir Ahmetovic <choxnox>
* @License: MIT
*/
var Form = require("../index");
var Element = require("../element");
var util = require("util");
var _ = require("lodash");
function Recaptcha(name, options) {
Element.call(this, name, options);
this._render.htmlTag = "div";
var defaultOptions = {
secretKey: "",
siteKey: ""
};
this._options = _.extend(this._options, defaultOptions, options);
}
util.inherits(Recaptcha, Element);
Recaptcha.prototype.isValid = function(value, context, callback) {
var $this = this;
var $value = value;
Form.Element.prototype.isValid.call(this, value, context, function(err, value) {
if (err)
callback(err, value);
else
{
var request = require("request");
request.post("https://www.google.com/recaptcha/api/siteverify", {
form: {
secret: $this.getSecretKey(),
response: $value
}
}, function(err, httpResponse, body) {
if (err)
{
$this.setError(err);
callback(err, value);
}
else
{
body = JSON.parse(body);
if (body.success)
callback(null, value);
else
{
var error = "An error occurred. Please try again.";
$this.setError(error);
callback(error, value);
}
}
});
}
});
};
Recaptcha.prototype.render = function(callback) {
if (_.isFunction(callback))
{
var viewScriptString = "\tscript(src='https://www.google.com/recaptcha/api.js?hl=en')\r" +
"\tdiv.g-recaptcha(data-sitekey='" + this.getSiteKey() + "')\r"
;
this.setViewScriptString(viewScriptString);
Form.Element.prototype.render.call(this, callback);
}
else
return Form.Element.prototype.render.call(this);
};
Recaptcha.prototype.getSecretKey = function() { return this._options.secretKey; };
Recaptcha.prototype.getSiteKey = function() { return this._options.siteKey; };
Recaptcha.prototype.setSecretKey = function(secretKey) { this._options.secretKey = secretKey; };
Recaptcha.prototype.setSiteKey = function(siteKey) { this._options.siteKey = siteKey; };
module.exports = exports = Recaptcha;
| mit |
TimothyKlim/slick-jdbc-extension-scala | src/main/scala/com/github/tarao/slickjdbc/query/Translator.scala | 1500 | package com.github.tarao
package slickjdbc
package query
import slick.jdbc.SQLActionBuilder
trait Context {
import java.lang.StackTraceElement
def caller = Thread.currentThread.getStackTrace.reverse.takeWhile { trace =>
trace.getClassName != getClass.getName
}.lastOption getOrElse new StackTraceElement("Unknown", "method", null, -1)
}
trait Translator {
def apply(query: String, context: Context): String
}
object MarginStripper extends Translator {
def apply(query: String, context: Context) = query.stripMargin
}
object CallerCommenter extends Translator {
def apply(query: String, context: Context) =
new SQLComment(context.caller).embedTo(query)
}
case class SQLComment(comment: Any) {
import scala.util.matching.Regex
def escaped = comment.toString.replaceAllLiterally("*/", """*\\/""")
def embedTo(query: String) =
query.replaceFirst(" ", Regex.quoteReplacement(s" /* ${escaped} */ "))
}
object Translator extends Context {
implicit val default: Traversable[Translator] =
Seq(MarginStripper, CallerCommenter)
def translate(query: String)(implicit
translators: Traversable[Translator]
) = translators.foldLeft(query) { (q, translate) => translate(q, this) }
def translateBuilder(builder: SQLActionBuilder)(implicit
translators: Traversable[Translator]
): SQLActionBuilder = {
val query = builder.queryParts.iterator.map(String.valueOf).mkString
SQLActionBuilder(Seq(translate(query)(translators)), builder.unitPConv)
}
}
| mit |
3Pros/juxtapros | js/tab-ordering.js | 410 | function recomputeTabIndices() {
if (!$("input").length) {
return false;
}
$("input")[0].tabIndex = 1;
$("input")[1].tabIndex = 2;
var nextIndex = 3;
var lists = $(".js-list")
var indexGap = lists.toArray().length;
lists.each(function (index, element) {
$("input", element).each(function (i, elem) {
elem.tabIndex = nextIndex + i*indexGap;
});
++nextIndex;
});
};
recomputeTabIndices();
| mit |
gocodeclub/projects | webapps/part2/server.go | 1557 | package main
import (
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/sessions"
)
type User struct {
Username string
}
func main() {
m := martini.Classic()
// set up the session, and map it into martini
store := sessions.NewCookieStore([]byte("secret-pass"))
m.Use(sessions.Sessions("go-webapp", store))
//on login, we will set the users username in the session
m.Post("/login", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
username := r.FormValue("username")
session.Set("username", username)
http.Redirect(w, r, "/home", http.StatusFound)
return "OK"
})
//if the user has no username, we will redirect them to the login page
m.Get("/home", authorize, func(user *User) string {
return "Welcome back, " + user.Username
})
//on logout, clear the username in the session
m.Get("/logout", func(w http.ResponseWriter, r *http.Request, session sessions.Session) string {
session.Delete("username")
http.Redirect(w, r, "/login", http.StatusFound)
return "OK"
})
m.Run()
}
//The authorize middleware will search the session for a username
//if it doesnt find it, it will redirect to login
func authorize(w http.ResponseWriter, r *http.Request, session sessions.Session, c martini.Context) {
username := session.Get("username")
if username == nil {
http.Redirect(w, r, "/login", http.StatusFound)
}
//if we found the user, let's create a new user struct and map it into the request context
user := &User{}
user.Username = username.(string)
c.Map(user)
}
| mit |
jetfirephp/framework | src/Factories/View.php | 1177 | <?php
namespace JetFire\Framework\Factories;
use JetFire\Framework\App;
/**
* Class View
* @package JetFire\Framework\Factories
* @method static path($path = null, $params = [])
* @method static render($path, $data = [])
*/
class View
{
/**
* @var
*/
private static $instance;
/**
*
*/
public function __construct()
{
if (is_null(self::$instance)) {
self::$instance = App::getInstance()->get('response')->getView();
}
}
/**
* @return mixed
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = App::getInstance()->get('response')->getView();
}
return self::$instance;
}
/**
* @param $name
* @param $args
* @return mixed
*/
public static function __callStatic($name, $args)
{
return call_user_func_array([self::getInstance(), $name], $args);
}
/**
* @param $name
* @param $args
* @return mixed
*/
public function __call($name, $args)
{
return call_user_func_array([self::getInstance(), $name], $args);
}
} | mit |
djmarland/isin | src/ISIN/Exception/InvalidISINException.php | 118 | <?php
namespace Djmarland\ISIN\Exception;
use Exception;
class InvalidISINException extends Exception
{
}
| mit |
ministryofjustice/apvs-external-web | test/load/load-test-helper.js | 916 | const fs = require('fs')
module.exports = {
setVisitDate: setVisitDate,
attachImageFile: attachImageFile
}
// Date of visit needs to be dynamically set to a recent day in the past
function setVisitDate (requestParams, context, ee, next) {
const dateOfVisit = new Date()
dateOfVisit.setDate(dateOfVisit.getDate() - 7)
requestParams.json['date-of-journey-day'] = dateOfVisit.getDate()
requestParams.json['date-of-journey-month'] = (dateOfVisit.getMonth() + 1)
requestParams.json['date-of-journey-year'] = dateOfVisit.getFullYear()
return next()
}
// Load the dummy visit confirmation or receipt image from disk and add to form data
function attachImageFile (requestParams, context, ee, next) {
requestParams.formData._csrf = context.vars.token.value
const imageContents = fs.createReadStream('./data/visit-confirmation.jpg')
requestParams.formData.document = imageContents
return next()
}
| mit |
Symfony-Plugins/diemPlugin | dmAdminPlugin/data/generator/dmAdminDoctrineModule/dmAdmin/template/templates/_form_field.php | 4346 | [?php
$required = ($validator = $form->getValidatorSchema()->offsetGet($name)) ? $validator->getOption('required') : false;
$divClass = dmArray::toHtmlCssClasses(array(
$class,
($field->getConfig('is_big') || $field->getConfig('markdown')) ? 'big' : '',
$field->getConfig('is_link') ? 'dm_link_droppable' : '',
$required ? 'required' : ''
));
if('empty_' === $name)
{
echo '<div class="'.$divClass.'"></div>';
return;
}
?]
[?php if ($field->isPartial()): ?]
<div class="[?php echo $divClass ?]">[?php include_partial('<?php echo $this->getModuleName() ?>/'.$name, array('<?php echo $this->getModule()->getKey() ?>' => $form->getObject(), 'form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?]</div>
[?php elseif ($field->isComponent()): ?]
<div class="[?php echo $divClass ?]">[?php include_component('<?php echo $this->getModuleName() ?>', $name, array('<?php echo $this->getModuleName() ?>' => $form->getObject(), 'form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?]</div>
[?php elseif ($field->getConfig('markdown')): ?]
[?php include_partial("dmAdminGenerator/markdown", array("form" => $form, "field" => $field, "class" => $class, "name" => $name, "label" => $label, "attributes" => $attributes, "help" => $help)); ?]
[?php elseif(isset($form[$name])): ?]
<div class="[?php echo $divClass ?][?php $form[$name]->hasError() and print ' errors' ?]">
[?php if ($form[$name]->hasError()): ?]
<div class="error">
<div class="s16 s16_error">[?php echo __((string) $form[$name]->getError()) ?]</div>
</div>
[?php endif; ?]
<div class="sf_admin_form_row_inner clearfix">
[?php
echo '<div class="label_wrap">';
echo $form[$name]->renderLabel($label);
if($form[$name]->getWidget() instanceof sfWidgetFormDoctrineChoice && $form[$name]->getWidget()->getOption('multiple'))
{
echo sprintf('<div class="control selection"><span class="select_all">%s</span><span class="unselect_all">%s</span></div>', __('Select all'), __('Unselect all'));
}
echo '</div>';
echo '<div class="content">'.$form[$name]->render($attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes).'</div>';
if ($help)
{
echo '<div class="help">'.__($help).'</div>';
}
elseif($help = $form[$name]->renderHelp())
{
echo '<div class="help">'.$help.'</div>';
}
?]
</div>
</div>
[?php else: //check if is a media view ?]
<div class="[?php echo $divClass ?]">
[?php
$found = false;
if ('dm_gallery' === $name)
{
$found = true;
include_partial('dmMedia/galleryMedium', array('record' => $form->getObject()));
}
elseif (substr($name, -5) === '_view')
{
$found = true;
include_partial('dmMedia/viewBig', array('object' => $form->getObject()->getDmMediaByColumnName(substr($name, 0, strlen($name)-5))));
}
elseif (substr($name, -5) === '_list')
{
if (!$relation = $form->getObject()->getTable()->getRelationHolder()->get($alias = dmString::camelize(substr($name, 0, strlen($name)-5))))
{
$relation = $form->getObject()->getTable()->getRelationHolder()->get($alias = substr($name, 0, strlen($name)-5));
}
if ($relation)
{
echo '<div class="sf_admin_form_row_inner clearfix">';
echo '<div class="label_wrap">'.__($field->getConfig('label', '', true)).'</div>';
if($relation instanceof Doctrine_Relation_ForeignKey)
{
$found = true;
include_partial('dmAdminGenerator/relationForeign', array('record' => $form->getObject(), 'alias' => $alias));
}
elseif ($relation instanceof Doctrine_Relation_Association)
{
$found = true;
include_partial('dmAdminGenerator/relationAssociation', array('record' => $form->getObject(), 'alias' => $alias));
}
echo '</div>';
}
}
if(!$found)
{
if (sfConfig::get('sf_debug'))
{
throw new dmException($name.' is not a valid form field');
}
else
{
echo '?';
}
}
?]
</div>
[?php endif; ?] | mit |
ukrbublik/openssl_x509_gencrl | src/ASN1_SIMPLE.php | 397 | <?php
namespace Ukrbublik\openssl_x509_crl;
use Ukrbublik\openssl_x509_crl\ASN1;
/**
* ANS1 default type
*/
class ASN1_SIMPLE extends ASN1
{
/**
* Constructor
*
* @param string $str content
*/
public function __construct($str = null) {
$this->content = $str;
}
protected function encodeSimpleContent() {
return $this->content;
}
}
| mit |
mobarski/sandbox | fc/itsy/main_old.lua | 11079 | require "pal"
require "font"
-- TODO REFACTOR 128 (bank width)
--------------------------------------------------------------------------------
function get_tile(b,s,w,h,colorkey,raw)
w=w or 1
h=h or 1
local bw = math.floor(banks[b]:getWidth()/8)
local x,y = s%bw, math.floor(s/bw)
local tile = love.image.newImageData(w*8,h*8)
tile:paste(banks[b],0,0,x*8,y*8,w*8,h*8)
--tile:encode('png','xxx.png')
if not raw then tile = love.graphics.newImage(tile) end
return tile
end
function col_to_rgba(c)
if c==0 then
return {0,0,0,0}
else
return {c/255,0,0,1}
end
end
-- TODO
function rgb_to_col(r,g,b)
for c,col in pairs(colors) do
if col[1]/255==r and col[2]/255==g and col[3]/255==b then return c-1 end
end
end
function set_col(c)
c=c or COLOR
love.graphics.setColor(col_to_rgba(c))
end
-- TODO REFACTOR
function bank_from_text(b,text,chars,values,w,h,eol)
w=w or 128
h=h or 128
eol=eol or ';'
local img = love.image.newImageData(w,h)
local c,ch,bc
local x,y = 0,0
local val = {}
for i = 1,#chars do
val[chars:sub(i,i)] = values[i]
end
for i = 1,#text do
ch = text:sub(i,i)
if ch==eol then
y=y+1
x=0
end
c = val[ch]
if c then
bc = c / 255
--img:setPixel(x,y,bc,0,0,1) -- unpack(col_to_rgba)
img:setPixel(x,y,unpack(col_to_rgba(c))) -- unpack(col_to_rgba)
x=x+1
end
end
banks[b]=img
end
-- TODO REFACTOR
function map_from_text(text,chars,values,w,h,eol)
eol=eol or ';'
local val = {}
local out = {}
local x,y = 0,0
local t,ch
for i=1,#chars do
val[chars:sub(i,i)] = values[i]
end
for i = 1,#text do
ch = text:sub(i,i)
if ch==eol then
y=y+1
x=0
end
t = val[ch]
if t then
out[y*w+x] = t
x=x+1
end
end
out['w']=w
out['h']=h
return out
end
function img_from_page(p,b,remap)
b=b or BANK
p=p or PAGE
local _draw = love.graphics.draw
local key = PAGE -- TODO key=p+b
local img = map_cache[key]
if remap then img = nil end
if not img then
local t,tile
local w = pages[PAGE]['w']
local h = pages[PAGE]['h']
img = love.image.newImageData(w*8,h*8)
for x = 0,w-1 do
for y = 0,h-1 do
t = pages[PAGE][y*w+x]
if remap then
t = remap(t,x,y)
end
if t then
tile = get_tile(b,t,1,1,nil,true)
img:paste(tile,x*8,y*8,0,0,8,8)
end
end
end
map_cache[key] = img
end
return img
end
-- TODO separate calc_width function
function font_from_text(text,w,h,fg,bg,eol)
local cnv = love.graphics.newCanvas(128,128)
cnv:renderTo(function ()
love.graphics.clear({0,0,0,0}) -- TODO colorkey
end)
local img = cnv:newImageData()
local j,x,y,s = 0,0,0
font_width = {} -- GLOBAL
font_height = h
for i=0,255 do font_width[i]=0 end
local ch
for i = 1,#text do
ch = text:sub(i,i)
s = math.floor(x/8) + math.floor(y/8)*16
if ch==fg then
img:setPixel(x,y,{1,1,1,1}) -- TODO color
font_width[s] = math.max(font_width[s], 1+x%8)
x=x+1
if x%8 >= w then x = x + 8-x%8 end
elseif ch==bg then
x=x+1
if x%8 >= w then x = x + 8-x%8 end
elseif ch==eol then
y=y+1
x=0
end
end
return img
end
function export_bank(b,path)
banks[b]:encode('png',path)
end
function import_bank(b,path)
local bank = love.image.newImageData(128,128)
local img = love.image.newImageData(path)
bank:paste(img,0,0,0,0,128,128)
banks[b] = bank
end
recolor_code = [[
extern vec4 colors[256];
vec4 effect( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords )
{
vec4 orig_color = Texel(texture, texture_coords);
int c = int(orig_color[0]*255);
return colors[c];
}
]]
recolor_shader = love.graphics.newShader(recolor_code)
-- shader:sendColor('colors',unpack(rgba))
function update_shader()
local rgba = {}
local c
for i=0,255 do
c = colors[i]
if c then
rgba[i] = {c[1]/255,c[2]/255,c[3]/255,1}
trace('UPDATE_SHADER',i,c[1],c[2],c[3])
else
rgba[i] = {0,0,0,0}
end
end
recolor_shader:sendColor('colors',unpack(rgba))
end
---[ API ]----------------------------------------------------------------------
-- TODO KWARGS fixed scale sim xspace yspace
-- TODO return value
trace=print
function print(text,x,y,c,xmax,xmin,sim)
c=c or COLOR
x=x or CURX
y=y or CURY
xmin=xmin or x
xmax=xmax or scrw
local ch,ch2
local s
local skip = 0
local c_orig = c
text=string.upper(text)
for i=1,#text do
if skip>0 then
skip=skip-1
goto continue
end
ch = text:sub(i,i)
s = string.byte(ch)
if ch=='\n' then -- EOL
x=xmin
y=y+font_height+2
elseif ch=='^' then
ch2=text:sub(i+1,i+1)
if ch2>='0' and ch2<='9' then
c = tonumber(ch2)
skip = 1
elseif ch2=='^' then
c = c_orig
skip = 1
end
elseif s then
local w = font_width[s]
if x > xmax or x+w > xmax then
x=xmin
y=y+font_height+2
end
shadow(s,x,y,1,1,c,FONT_BANK)
if w==0 then w=5 else w=w+1 end
x=x+w
else
x=x+5
end
CURX = x
::continue::
-- TODO CURY
end
return x,y+font_height+1
end
function cursor(x,y)
if x==nil and y==nil then
CURX,CURY = 0,0
else
if x then CURX=x end
if y then CURY=y end
end
end
function bank(b) BANK=b end
function page(p) PAGE=p end
function camera(x,y)
camx = -x
camy = -y
end
-- TODO rest of args
function shadow(s,x,y, w,h, c,b)
w=w or 1
h=h or 1
b=b or BANK
cr,cg,cb,ca = col_to_rgba(c or COLOR)
-- get_shadow TODO refactor
local bw = math.floor(banks[b]:getWidth()/8)
local bx,by = s%bw, math.floor(s/bw)
local tile = love.image.newImageData(w*8,h*8)
tile:paste(banks[b],0,0,bx*8,by*8,w*8,h*8)
function use_colorkey(x,y,r,g,b,a)
if a>0
then return cr,cg,cb,1
else return 0,0,0,0
end
end
tile:mapPixel(use_colorkey)
love.graphics.setColor(1,1,1,1) -- required for colors to be ok
love.graphics.draw(love.graphics.newImage(tile), x+camx, y+camy)
end
-- draw sprite by id, can scale, flip, rotate and sheer
function spr(s,x,y, w,h, flip,scale, b)
w = w or 1
h = h or 1
b = b or BANK
flip = flip or 0
scale = scale or 1
local key = table.concat({b,s,COLORKEY,w,h},':')
local img = spr_cache[key]
if not img then
img = get_tile(b,s,w,h,COLORKEY)
spr_cache[key] = img
end
local scale_x,scale_y = scale,scale
local ori_x,ori_y = 0,0
if flip==1 or flip==3 then
scale_x = -scale
ori_x = 8*w
end
if flip==2 or flip==3 then
scale_y = -scale
ori_y = 8*h
end
love.graphics.setColor(1,1,1,1) -- required for colors to be ok
love.graphics.draw(img, x+camx, y+camy,
0, scale_x, scale_y, ori_x, ori_y)
end
function rectfill(x,y,w,h,c)
set_col(c)
love.graphics.rectangle('fill',x+camx,y+camy,w,h)
end
function rect(x,y,w,h,c)
set_col(c)
love.graphics.rectangle('line',x+camx,y+camy,w,h)
end
function circfill(x,y,r,c)
set_col(c)
love.graphics.circle('fill',x+camx,y+camy,r)
end
function circ(x,y,r,c)
set_col(c)
love.graphics.circle('line',x+camx,y+camy,r)
end
function pget(x,y)
love.graphics.setCanvas()
local img = scr:newImageData(nil,nil,x,y,1,1)
love.graphics.setCanvas(scr)
local r,g,b,a = img:getPixel(0,0)
return rgb_to_col(r,g,b) -- TODO
end
function pset(x,y,c)
set_col(c)
love.graphics.points(x+camx,y+camy)
end
function line(x0,y0,x1,y1,c)
set_col(c)
love.graphics.line(x0+camx,y0+camy,x1+camx,y1+camy)
end
function trifill(x1,y1,x2,y2,x3,y3,c)
set_col(c)
love.graphics.polygon('fill',x1+camx,y1+camy,x2+camx,y2+camy,x3+camx,y3+camy)
end
function tri(x1,y1,x2,y2,x3,y3,c)
set_col(c)
love.graphics.polygon('line',x1+camx,y1+camy,x2+camx,y2+camy,x3+camx,y3+camy)
end
function cls(c)
local c = c or 1
love.graphics.clear(col_to_rgba(c))
cursor()
clip()
end
function clip(x,y,w,h)
if true then return else
-- ERROR
if x then
love.graphics.setScissor(x*scrs,(scrh-y-h)*scrs,w*scrs,h*scrs) -- camx camy ???
else
love.graphics.setScissor(0,0,scrw*scrs,scrh*scrs)
end
end
end
function screen(w,h,s,pal)
s=s or scrs
w=w or scrw
h=h or scrh
scrw,scrh = w,h
scrs = s
if pal then
colors = {}
local c=1
local r,g,b
for r,g,b in string.gmatch(pal,'#(%w%w)(%w%w)(%w%w)') do
trace('COLORS',c,r,g,b)
colors[c] = {tonumber(r,16),tonumber(g,16),tonumber(b,16)} -- TODO x/255
trace('COLORS',c,unpack(colors[c]))
c=c+1
end
MAX_COLOR = c-1
trace('MAX_COLOR',MAX_COLOR)
end
love.window.setMode(w*s,h*s)
update_shader()
end
function fps()
return love.timer.getFPS()
end
function pal(c,r,g,b)
-- TODO
end
function color(c)
COLOR=c
set_col(c)
end
-- TODO invalidate cache
function transparent(c)
COLORKEY=c
end
---[ MAP ]----------------------------------------------------------------------
function map(x,y,p,remap)
x=x or 0
y=y or 0
p=p or PAGE
img = img_from_page(p,MAP_BANK,remap)
love.graphics.setColor(1,1,1,1)
love.graphics.draw(love.graphics.newImage(img),x+camx,y+camy)
end
function mget(mx,my)
local w = pages[PAGE]['w']
return pages[PAGE][my*w+mx]
end
function mset(mx,my,t)
local w = pages[PAGE]['w']
pages[PAGE][my*w+mx] = t
-- invalidate cache TODO key=p+b
map_cache[PAGE] = nil
end
---[ INPUT ]--------------------------------------------------------------------
function key(k)
return love.keyboard.isDown(k)
end
function keyp(k)
local d = love.keyboard.isDown(k)
local p = PRESSED[k]
if d and not p then
PRESSED[k] = 1
return true
elseif p and not d then
PRESSED[k] = nil
end
return false
end
function mouse()
local mx,my,b1,b2,b3
b1 = love.mouse.isDown(1)
b2 = love.mouse.isDown(2)
b3 = love.mouse.isDown(3)
mx,my = love.mouse.getPosition()
mx = math.floor(mx/scrs)
my = math.floor(my/scrs)
return {mx,my,b1,b2,b3}
end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-- TODO love.graphics.setBackgroundColor
function INIT(args,raw_args) end
function MAIN() end
function DRAW() end
function OVER() end -- TODO
function SCAN() end -- TODO
function POST() end -- TODO
function love.load(args,raw_args)
BANK = 1
PAGE = 1
COLORKEY = 0
COLOR = 1
CURX,CURY = 0,0 -- cursor
camx,camy = 0,0 -- TODO upper
scrw,scrh = 320,200 -- TODO upper
scrs = 2 -- TODO upper
spr_cache={}
map_cache={}
banks={}
pages={}
PRESSED={}
SPR_BANK = 1
MAP_BANK = 2
FONT_BANK = 3
MAX_COLOR = 16
banks[FONT_BANK] = font_from_text(moki4x,5,5,'X','.','-')
colors=pal_chromatic -- TODO upper
love.graphics.setLineStyle('rough')
love.graphics.setDefaultFilter('nearest','nearest')
screen(scrw,scrh,scrs)
for i,arg in pairs(args) do
trace('arg',i,arg)
end
local mod = args[1]
if mod then
package.path = package.path .. ";..;?.lua"
require(mod)
end
INIT(args,raw_args)
scr = love.graphics.newCanvas(scrw,scrh)
end
function love.update()
MAIN()
end
function love.draw()
-- BEFORE
love.graphics.setCanvas(scr)
love.graphics.setShader(recolor_shader)
DRAW()
-- AFTER
love.graphics.setShader()
love.graphics.setCanvas()
love.graphics.setColor(1,1,1,1) -- TODO store+restore color
love.graphics.draw(scr,0,0,0, scrs,scrs)
POST()
if key("f6") then love.graphics.captureScreenshot('screen.png') end
end
| mit |
afsardo/RoleBasedSecurity | db/migrate/20150219160841_create_delegations.rb | 173 | class CreateDelegations < ActiveRecord::Migration
def change
create_table :delegations do |t|
t.integer :user_id
t.integer :delegator_id
end
end
end
| mit |
PetitEucalyptus/symfonyTest | app/cache/dev/twig/5d/71/eaa95ec04119a43e7d180d9f34b1.php | 3217 | <?php
/* PetraeFichierPlanteBundle:Default:voir.html.twig */
class __TwigTemplate_5d71eaa95ec04119a43e7d180d9f34b1 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("PetraeFichierPlanteBundle::layout.html.twig");
$this->blocks = array(
'title' => array($this, 'block_title'),
'stylesheets' => array($this, 'block_stylesheets'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "PetraeFichierPlanteBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = array())
{
// line 4
echo " Fiche: ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["plante"]) ? $context["plante"] : $this->getContext($context, "plante")), "NomLatin"), "html", null, true);
echo "
";
}
// line 6
public function block_stylesheets($context, array $blocks = array())
{
// line 7
echo " ";
$this->displayParentBlock("stylesheets", $context, $blocks);
echo "
<link rel=\"stylesheet\" href=\"/css/modifier_plante.css\" type=\"text/css\"/>
";
}
// line 11
public function block_body($context, array $blocks = array())
{
// line 12
echo " <h2> ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["plante"]) ? $context["plante"] : $this->getContext($context, "plante")), "NomLatin"), "html", null, true);
echo " <a class=\"btn btn-primary modifier\"
href=\"";
// line 13
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("petrae_fichier_plante_modifier", array("id" => $this->getAttribute((isset($context["plante"]) ? $context["plante"] : $this->getContext($context, "plante")), "id"))), "html", null, true);
echo "\">
Modifier</a></h2>
<ul>
<li>
<b>Nom Français:</b> ";
// line 17
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["plante"]) ? $context["plante"] : $this->getContext($context, "plante")), "NomFrancais"), "html", null, true);
echo "
</li>
<li>
<b>Description:</b> ";
// line 20
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["plante"]) ? $context["plante"] : $this->getContext($context, "plante")), "Description"), "html", null, true);
echo "
</li>
</ul>
";
}
public function getTemplateName()
{
return "PetraeFichierPlanteBundle:Default:voir.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 72 => 20, 66 => 17, 59 => 13, 54 => 12, 51 => 11, 43 => 7, 40 => 6, 33 => 4, 30 => 3,);
}
}
| mit |
rramadev/Store-Manager-App | src/app/products/product-detail.component.ts | 2814 | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MdDialog } from '@angular/material';
import { Subscription } from 'rxjs/Subscription';
import { ProductDetailDialogComponent } from './product-detail-dialog.component';
import { ProductService } from './product.service';
import { LoggerService } from '../core/logger.service';
import { IProduct } from './product.model';
@Component({
moduleId: module.id,
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {
pageTitle: string = '';
errorMessage: string = '';
showBar: boolean = false;
updated: boolean = false;
updateMessage: string = ' - Updated!';
deleted: boolean = false;
deleteMessage: string = ' - Deleted!';
product: IProduct;
private subcription: Subscription;
constructor(private route: ActivatedRoute,
private router: Router,
private productService: ProductService,
public dialog: MdDialog,
private loggerService: LoggerService) { }
onBack(): void {
this.router.navigate(['/products']);
}
onRatingClicked(message: string): void {
this.setTitle(message);
}
setTitle(message = ''): void {
this.pageTitle = `Product Detail: ${this.product.productName} ${message}`;
}
openDialog(): void {
this.updated = false;
let dialogRef = this.dialog.open(ProductDetailDialogComponent);
dialogRef.componentInstance.product = this.product;
dialogRef.afterClosed().subscribe(result => {
(typeof result === 'object') ? (
this.showBar = true,
this.updateProduct(result))
: this.updated = false;
});
}
getProduct(id: number) {
this.productService.getProduct(id).subscribe(
product => {
this.product = product;
this.setTitle();
},
error => this.errorMessage = <any>error);
}
updateProduct(product: IProduct) {
this.productService.updateProduct(product).subscribe(
result => {
this.product = Object.assign({}, product);
this.showBar = false;
this.updated = true;
this.loggerService.log('Product updated successfully!');
},
error => {
this.errorMessage = <any>error;
this.showBar = false;
this.loggerService.error('Error on product update!');
});
}
deleteProduct(id: number) {
this.updated = false;
this.showBar = true;
this.productService.deleteProduct(id).subscribe(
result => {
// this.product = undefined;
this.showBar = false;
this.deleted = true;
this.setTitle();
this.loggerService.log('Product deleted successfully!');
},
error => this.errorMessage = <any>error);
}
ngOnInit(): void {
this.subcription = this.route.params.subscribe(
params => {
let id = +params['id'];
this.getProduct(id);
});
}
}
| mit |
chrisb/robvst | app/models/user.rb | 699 | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :name
validates_presence_of :subdomain
validates_uniqueness_of :subdomain
before_create :generate_subdomain
protected
def generate_subdomain
return if subdomain.present?
self.subdomain = name.to_s.parameterize
i = 0
while User.exists?(subdomain:self.subdomain) do
self.subdomain = "#{name.parameterize}-#{i+=1}"
end
end
end
| mit |
muthukumarsp/e-mail-application | src/app/dashboard/dashboard.module.ts | 564 | import { NgModule } from '@angular/core';
import { DashboardComponent } from './dashboard.component';
import { CommonModule } from '@angular/common';
import { routing } from './dashboard.routing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SharedModule } from '../shared/shared.module';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
SharedModule,
routing
],
declarations: [
DashboardComponent
],
bootstrap: [
DashboardComponent
]
})
export class DashboardModule {}
| mit |
digitalheir/java-rechtspraak-library | deprecated/crf/main/java/org/leibnizcenter/rechtspraak/markup/docs/features/IsAllCaps.java | 2502 | package org.leibnizcenter.rechtspraak.markup.docs.features;
import deprecated.org.crf.crf.CrfFeature;
import org.leibnizcenter.rechtspraak.markup.docs.Label;
import org.leibnizcenter.rechtspraak.markup.docs.RechtspraakElement;
import org.leibnizcenter.util.Doubles;
import org.leibnizcenter.util.Labels;
import java.util.EnumMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Created by Maarten on 3/7/2016.
*/
public class IsAllCaps {
public static final Map<Label, Feature> features = new EnumMap<>(Label.class);
public static final Map<Label, Filter> filters = new EnumMap<>(Label.class);
public static final Pattern ALL_CAPS = Pattern.compile("^[\\p{Lu}0-9 ]*\\p{Lu}+[\\p{Lu}0-9 ]*$");
static {
for (Label l : Labels.set) {
features.put(l, new Feature(l));
filters.put(l, new Filter(l));
}
}
public static String unspace(String normalizedText) {
return normalizedText.replaceAll("\\s", "");
}
public static boolean isSpaced(String normalizedText) {
return ALL_CAPS.matcher(normalizedText).matches();
}
public static class Feature extends CrfFeature<RechtspraakElement, Label> {
private final Label label;
public Feature(Label l) {
this.label = l;
}
@Override
public double value(RechtspraakElement[] sequence, int indexInSequence, Label currentTag, Label previousTag) {
return Doubles.asDouble(sequence[indexInSequence].isSpaced);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Feature feature = (Feature) o;
return label.equals(feature.label);
}
@Override
public int hashCode() {
return label.hashCode();
}
}
public static class Filter extends deprecated.org.crf.crf.filters.Filter<RechtspraakElement, Label> {
private final Label label;
public Filter(Label l) {
this.label = l;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Filter feature = (Filter) o;
return label.equals(feature.label);
}
@Override
public int hashCode() {
return label.hashCode();
}
}
}
| mit |
KentLeong/study-and-test-2-v-000 | config/initializers/devise.rb | 13873 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
config.authentication_keys = [ :login ]
# To have multiple models and create customized views
config.scoped_views = true
# Configure Devise to use username as reset password or confirmation keys
config.reset_password_keys = [ :username ]
config.confirmation_keys = [ :username ]
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '0389110b6d565776b0818bccbff59716cd7c8a64a530e3696584469287e6954d0b6f747d265e3526a245d8a0337d2dfad190d44938492627b8ff5d2442ab785d'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = '16fb0a55feab5c67d3382000bcd1b878e7a2aedc5ad6c361e55b5840694ab377818a02eb6f1b3d274520b4b802116a9bf3c9bffe2af85af49a704444e8d018e3'
# Send a notification email when the user's password is changed
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| mit |
EntityFX/GdcGame | Sources/EntityFX.Gdcame.GameEngine/NetworkGameEngine/IGameDataPersister.cs | 227 | using System.Collections.Generic;
namespace EntityFX.Gdcame.GameEngine.NetworkGameEngine
{
public interface IGameDataPersister
{
void PersistGamesData(IList<GameWithUserId> gamesWithUserIds);
}
} | mit |
netconstructor/ffcrm_direct_marketing_helpers | db/migrate/20120502102618_copy_job_from_extra_csv_fields.rb | 592 | class CopyJobFromExtraCsvFields < ActiveRecord::Migration
def up
if defined?(FatfreeCsvImport)
ver = FatfreeCsvImport::VERSION.split('.').collect { |n| n.to_i }
return if ver[0] == 0 && ver[1] == 0 && ver[2] < 8
Lead.transaction do
for lead in Lead.all
next if lead.extra_csv_data.nil?
extra_data = YAML.load(lead.extra_csv_data)
next if extra_data.nil?
lead.original_contact_job = extra_data['job']
lead.job ||= extra_data['job']
lead.save!
end
end
end
end
def down
end
end
| mit |
diegofelix/battleroad | app/Champ/Forms/CreateCouponForm.php | 520 | <?php
namespace Champ\Forms;
use Laracasts\Validation\FormValidator;
class CreateCouponForm extends FormValidator
{
protected $rules = [
'championship_id' => 'required',
'code' => 'required|unique:coupons',
'price' => 'required|numeric',
];
protected $messages = [
'required' => 'Você precisa preencher todos os campos.',
'unique' => 'O código gerado já existe, clique em gerar novamente',
'numeric' => 'O preço precisa ser um valor válido',
];
}
| mit |
UnityBaseJS/ub-net-client | src/UbClient/UbConnection.cs | 8672 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Softengi.UbClient.Configuration;
using Softengi.UbClient.Dto;
using Softengi.UbClient.Linq;
using Softengi.UbClient.Sessions;
namespace Softengi.UbClient
{
// TODO: query constructing syntax
// TODO: linq to UB
public class UbConnection
{
public UbConnection(UnityBaseConnectionConfiguration ubConnectionConfiguration) :
this(new Uri(ubConnectionConfiguration.BaseUri), AuthMethod.FromConfig(ubConnectionConfiguration))
{}
public UbConnection(Uri baseUri, AuthenticationBase auth)
{
_transport = new UbTransport(baseUri);
BaseUri = baseUri;
_auth = auth;
}
/// <summary>
/// Base Uri used for connection to UnityBase server.
/// </summary>
public Uri BaseUri { get; }
public IOrderedQueryable<T> Query<T>(string entityName)
{
return new QueryableUbData<T>();
}
public UbDocumentInfo SelectDocumentInfo(string entityName, string attributeName, long id)
{
var result = SelectByID(entityName, new[] {attributeName}, id);
return JsonConvert.DeserializeObject<UbDocumentInfo>((string) result[attributeName]);
}
public string GetDocument(string entityName, string attributeName, long id, UbDocumentInfo documentInfo = null, bool base64Response = false)
{
if (!IsAuthenticated)
Auth();
var docInfo = documentInfo ?? SelectDocumentInfo(entityName, attributeName, id);
var queryStringParams = new Dictionary<string, string>
{
{"entity", entityName},
{"attribute", attributeName},
{"ID", id.ToString()},
{"store", docInfo.Store},
{"origName", docInfo.OriginalName},
{"filename", docInfo.FileName}
};
return Get("getDocument", queryStringParams, base64Response);
}
public SetDocumentResponse SetDocument(string entity, string attribute, string fileName, long id, Stream data)
{
var queryStringParams = new Dictionary<string, string>
{
{"ID", id.ToString()},
{"ENTITY", entity},
{"ATTRIBUTE", attribute},
{"filename", fileName},
{"origName", fileName}
};
var response = Run("setDocument", data, queryStringParams);
return JsonConvert.DeserializeObject<SetDocumentResponse>(response);
}
public List<Dictionary<string, object>> Select(
string entity,
string[] fieldList,
UbFilter filter = null,
object orderByList = null)
{
return
RunList<RunListResponse>(
new {entity, method = "select", fieldList, whereList = filter?.ToDictionary(), orderByList})[0]
.ToDictionary();
}
public T SelectScalar<T>(string entity, string field, UbFilter filter = null, object orderByList = null)
{
return (T) Select(entity, new[] {field}, filter, orderByList)?[0][field];
}
public Dictionary<string, object> SelectByID(string entity, string[] fieldList, long id)
{
return Select(entity, fieldList, new UbFilter("ID", "=", id))?[0];
}
public long GetId(string entity)
{
var response = AddNew(entity, new[] {"ID"});
return (long) response.ResultData.Data[0][0];
}
public RunListResponse AddNew(string entity, string[] fieldList)
{
return RunList<RunListResponse>(
new {entity, method = "addnew", fieldList})[0];
}
public RunListResponse Insert(string entity, object entityInstance, string[] fieldsToReturn = null)
{
var responses = RunList<RunListResponse>(
new
{
entity,
method = "insert",
fieldList = fieldsToReturn,
execParams = entityInstance
});
return responses[0];
}
public RunListResponse Update(string entity, object entityInstance, bool skipOptimisticLock = false)
{
var responses = RunList<RunListResponse>(
new
{
entity,
method = "update",
execParams = entityInstance,
// TODO: support for other options, have flags object?
__skipOptimisticLock = skipOptimisticLock
});
return responses[0];
}
public RunListResponse Update(string entity, object entityInstance, string[] fieldsToReturn,
bool skipOptimisticLock = false)
{
var responses = RunList<RunListResponse>(
new
{
entity,
method = "update",
fieldList = fieldsToReturn,
execParams = entityInstance,
__skipOptimisticLock = skipOptimisticLock
});
return responses[0];
}
public RunListResponse Delete(string entity, long id)
{
var responses = RunList<RunListResponse>(new {entity, method = "delete", execParams = new {ID = id}});
return responses[0];
}
public T[] RunList<T>(object data) where T : RunListResponse
{
return RunList<T>(new[] {data});
}
public T[] RunList<T>(object[] data) where T : RunListResponse
{
var requestBody = JArray.FromObject(data).ToString();
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
return JsonConvert.DeserializeObject<T[]>(Run("ubql", stream));
}
// TODO: push handling of authentication (depending on endpoint) and handling of exceptions in some central place
public string Run(string endPoint, Stream data, Dictionary<string, string> queryStringParams = null)
{
if (!IsAuthenticated)
Auth();
try
{
return Post(endPoint, data, queryStringParams);
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.ConnectFailure)
{
const int retries = 3;
for (var i = 0; i < retries; i++)
{
Thread.Sleep(1000);
try
{
Auth();
return Post(endPoint, data, queryStringParams);
}
catch (WebException excf) when (excf.Status == WebExceptionStatus.ConnectFailure)
{}
}
throw;
}
catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Unauthorized)
{
try
{
IsAuthenticated = false;
Auth();
return Post(endPoint, data, queryStringParams);
}
catch (WebException authRetryException)
{
throw new UbException(BaseUri, "Authentication error", authRetryException);
}
}
catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.Forbidden)
{
throw new UbException(BaseUri, $"UnityBase does not support method '{endPoint}'", ex);
}
catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.InternalServerError)
{
throw new UbException(BaseUri, "Error", ex);
}
}
/// <summary>
/// Returns <c>true</c>, if user is authenticated.
/// </summary>
/// <remarks>
/// The class uses lazy authentication, it authenticates user when any method which requires authentication is called.
/// This property allows to know the current state of the connection.
/// </remarks>
public bool IsAuthenticated { get; private set; }
private void Auth()
{
_auth.Authenticate(_transport);
IsAuthenticated = true;
}
private string Get(string endPoint, Dictionary<string, string> queryStringParams, bool base64Response = false)
{
return Request("GET", endPoint, queryStringParams, null, base64Response);
}
private string Post(string endPoint, Stream data = null, Dictionary<string, string> queryStringParams = null)
{
return Request("POST", endPoint, queryStringParams, data);
}
private string Request(
string httpMethod, string endPoint,
Dictionary<string, string> queryStringParams,
Stream data = null, bool base64Response = false)
{
return _transport.Request(httpMethod, endPoint, queryStringParams, GetRequestHeaders(endPoint), data, base64Response);
}
private Dictionary<string, string> GetRequestHeaders(string endPoint)
{
return _authenticatedEndpoints.Contains(endPoint)
? new Dictionary<string, string> {{"Authorization", _auth.AuthHeader()}}
: null;
}
private readonly AuthenticationBase _auth;
private readonly UbTransport _transport;
private readonly HashSet<string> _authenticatedEndpoints = new HashSet<string>
{
"runList",
"setDocument",
"getDocument",
"getDomainInfo"
};
/*
public class AuthResponse
{
[JsonProperty("result")]
public string SessionID { get; set; }
[JsonProperty("logonname")]
public string LogonName { get; set; }
[JsonProperty("uData")]
public string UserData { get; set; }
[JsonProperty("data")]
public string Data { get; set; }
[JsonProperty("nonce")]
public string Nonce { get; set; }
[JsonProperty("connectionID")]
public string ConnectionID { get; set; }
[JsonProperty("realm")]
public string Realm { get; set; }
[JsonProperty("secretWord")]
public string SecretWord { get; set; }
}*/
}
} | mit |
HarvestMasternodecoin/Harvestcoin | src/test/key_tests.cpp | 5224 | #include <boost/test/unit_test.hpp>
#include <string>
#include <vector>
#include "key.h"
#include "base58.h"
#include "uint256.h"
#include "util.h"
using namespace std;
static const string strSecret1 ("5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj");
static const string strSecret2 ("5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3");
static const string strSecret1C ("Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw");
static const string strSecret2C ("L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g");
static const CHarvestcoinAddress addr1 ("1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ");
static const CHarvestcoinAddress addr2 ("1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ");
static const CHarvestcoinAddress addr1C("1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs");
static const CHarvestcoinAddress addr2C("1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs");
static const string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF");
#ifdef KEY_TESTS_DUMPINFO
void dumpKeyInfo(uint256 privkey)
{
CKey key;
key.resize(32);
memcpy(&secret[0], &privkey, 32);
vector<unsigned char> sec;
sec.resize(32);
memcpy(&sec[0], &secret[0], 32);
printf(" * secret (hex): %s\n", HexStr(sec).c_str());
for (int nCompressed=0; nCompressed<2; nCompressed++)
{
bool fCompressed = nCompressed == 1;
printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed");
CHarvestcoinSecret bsecret;
bsecret.SetSecret(secret, fCompressed);
printf(" * secret (base58): %s\n", bsecret.ToString().c_str());
CKey key;
key.SetSecret(secret, fCompressed);
vector<unsigned char> vchPubKey = key.GetPubKey();
printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str());
printf(" * address (base58): %s\n", CHarvestcoinAddress(vchPubKey).ToString().c_str());
}
}
#endif
BOOST_AUTO_TEST_SUITE(key_tests)
BOOST_AUTO_TEST_CASE(key_test1)
{
CHarvestcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1;
BOOST_CHECK( bsecret1.SetString (strSecret1));
BOOST_CHECK( bsecret2.SetString (strSecret2));
BOOST_CHECK( bsecret1C.SetString(strSecret1C));
BOOST_CHECK( bsecret2C.SetString(strSecret2C));
BOOST_CHECK(!baddress1.SetString(strAddressBad));
CKey key1 = bsecret1.GetKey();
BOOST_CHECK(key1.IsCompressed() == false);
CKey key2 = bsecret2.GetKey();
BOOST_CHECK(key2.IsCompressed() == false);
CKey key1C = bsecret1C.GetKey();
BOOST_CHECK(key1C.IsCompressed() == true);
CKey key2C = bsecret2C.GetKey();
BOOST_CHECK(key1C.IsCompressed() == true);
CPubKey pubkey1 = key1. GetPubKey();
CPubKey pubkey2 = key2. GetPubKey();
CPubKey pubkey1C = key1C.GetPubKey();
CPubKey pubkey2C = key2C.GetPubKey();
BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID()));
BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID()));
BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID()));
BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID()));
for (int n=0; n<16; n++)
{
string strMsg = strprintf("Very secret message %i: 11", n);
uint256 hashMsg = Hash(strMsg.begin(), strMsg.end());
// normal signatures
vector<unsigned char> sign1, sign2, sign1C, sign2C;
BOOST_CHECK(key1.Sign (hashMsg, sign1));
BOOST_CHECK(key2.Sign (hashMsg, sign2));
BOOST_CHECK(key1C.Sign(hashMsg, sign1C));
BOOST_CHECK(key2C.Sign(hashMsg, sign2C));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2.Verify(hashMsg, sign2C));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2));
BOOST_CHECK( pubkey1C.Verify(hashMsg, sign1C));
BOOST_CHECK(!pubkey1C.Verify(hashMsg, sign2C));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2));
BOOST_CHECK(!pubkey2C.Verify(hashMsg, sign1C));
BOOST_CHECK( pubkey2C.Verify(hashMsg, sign2C));
// compact signatures (with key recovery)
vector<unsigned char> csign1, csign2, csign1C, csign2C;
BOOST_CHECK(key1.SignCompact (hashMsg, csign1));
BOOST_CHECK(key2.SignCompact (hashMsg, csign2));
BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C));
BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C));
CPubKey rkey1, rkey2, rkey1C, rkey2C;
BOOST_CHECK(rkey1.RecoverCompact (hashMsg, csign1));
BOOST_CHECK(rkey2.RecoverCompact (hashMsg, csign2));
BOOST_CHECK(rkey1C.RecoverCompact(hashMsg, csign1C));
BOOST_CHECK(rkey2C.RecoverCompact(hashMsg, csign2C));
BOOST_CHECK(rkey1 == pubkey1);
BOOST_CHECK(rkey2 == pubkey2);
BOOST_CHECK(rkey1C == pubkey1C);
BOOST_CHECK(rkey2C == pubkey2C);
}
}
BOOST_AUTO_TEST_SUITE_END()
| mit |
taufique71/node-c-analyzer | lib/symbol_table/namespace_helper.js | 21773 | var _ = require("lodash");
var parse_tree_helper = require("../utility/parse_tree_helper");
var statement_helper = require("../statements/statement_helper");
var declarator_helper = require("./declarator_helper");
var handle_labeled_stmt;
var handle_function_definition;
var handle_declaration;
var handle_parameter_declaration;
var get_specifiers_qualifiers;
var get_type_qualifiers;
var get_storage_class_specifiers;
var get_type_specifiers;
var get_info_from_type_specifier;
var get_details_from_struct_or_union_specifier;
var get_members_from_struct_declaration_list;
var get_members_from_struct_declaration;
var get_details_from_enum_specifier;
var get_members_from_enumerator_list;
handle_labeled_stmt = function(labeled_stmt, namespace){
if(labeled_stmt.children[0].tokenClass === "IDENTIFIER"){
var name = {
"name": labeled_stmt.children[0].lexeme,
"token": _.clone(labeled_stmt.children[0]),
"name_type": "label"
};
namespace["labels"].push(name);
}
else return;
};
module.exports.handle_labeled_stmt = handle_labeled_stmt;
handle_function_definition = function(function_definition, namespace){
var traverse_init_declarator_list = function(subtree, specifiers_qualifiers){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "declarator"){
var first_identifier = parse_tree_helper.get_first_token(subtree, "IDENTIFIER");
var phrased_declarator = declarator_helper.get_phrasing_from_declarator(subtree);
if(first_identifier){
var splitted_phrased_declarator = phrased_declarator.trim().split(" ");
if((splitted_phrased_declarator.length > 0) && (splitted_phrased_declarator[0] === "function")){
var name = {
"name": first_identifier.lexeme,
"name_type": "function",
"token": _.clone(first_identifier),
"declarator": phrased_declarator,
"specifiers_qualifiers": _.clone(specifiers_qualifiers),
};
namespace["ordinary_ids"].push(name);
}
return;
}
else return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_init_declarator_list(subtree.children[i], specifiers_qualifiers);
}
}
}
};
if(function_definition.children[0].title === "declaration_specifiers"){
var specifiers_qualifiers = get_specifiers_qualifiers(function_definition.children[0], namespace);
traverse_init_declarator_list(function_definition.children[1], specifiers_qualifiers);
}
else if(function_definition.children[0].title === "type_name"){
var specifiers_qualifiers = get_specifiers_qualifiers(function_definition.children[0], namespace);
traverse_init_declarator_list(function_definition.children[1], specifiers_qualifiers);
}
};
module.exports.handle_function_definition = handle_function_definition;
handle_declaration = function(declaration, namespace){
var traverse_init_declarator_list = function(subtree, specifiers_qualifiers){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "declarator"){
var first_identifier = parse_tree_helper.get_first_token(subtree, "IDENTIFIER");
var phrased_declarator = declarator_helper.get_phrasing_from_declarator(subtree);
if(first_identifier){
var splitted_phrased_declarator = phrased_declarator.trim().split(" ");
if( ((splitted_phrased_declarator.length > 0) && (splitted_phrased_declarator[0] !== "function")) ||
(splitted_phrased_declarator.length === 0)){
var typedef_token = _.filter(specifiers_qualifiers.storage_class_specifiers, { "lexeme": "typedef" });
if(typedef_token.length > 0){
var name = {
"name": first_identifier.lexeme,
"name_type": "typedef",
"token": _.clone(first_identifier),
"declarator": phrased_declarator,
"specifiers_qualifiers": _.clone(specifiers_qualifiers),
"parameter": false
};
namespace["ordinary_ids"].push(name);
}
else{
var name = {
"name": first_identifier.lexeme,
"name_type": "variable",
"token": _.clone(first_identifier),
"declarator": phrased_declarator,
"specifiers_qualifiers": _.clone(specifiers_qualifiers),
"parameter": false
};
namespace["ordinary_ids"].push(name);
}
}
return;
}
else return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_init_declarator_list(subtree.children[i], specifiers_qualifiers);
}
}
}
};
if(declaration.children[0].title === "declaration_specifiers"){
if(declaration.children.length === 3){
var specifiers_qualifiers = get_specifiers_qualifiers(declaration.children[0], namespace);
traverse_init_declarator_list(declaration.children[1], specifiers_qualifiers);
}
else if(declaration.children.length === 2){
var specifiers_qualifiers = get_specifiers_qualifiers(declaration.children[0], namespace);
}
}
else if(declaration.children[0].title === "type_name"){
if(declaration.children.length === 3){
var specifiers_qualifiers = get_specifiers_qualifiers(declaration.children[0], namespace);
traverse_init_declarator_list(declaration.children[1], specifiers_qualifiers);
}
}
};
module.exports.handle_declaration = handle_declaration;
handle_parameter_declaration = function(parameter_declaration, namespace){
var traverse_init_declarator_list = function(subtree, specifiers_qualifiers){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "declarator"){
var first_identifier = parse_tree_helper.get_first_token(subtree, "IDENTIFIER");
var phrased_declarator = declarator_helper.get_phrasing_from_declarator(subtree);
if(first_identifier){
var splitted_phrased_declarator = phrased_declarator.trim().split(" ");
if( ((splitted_phrased_declarator.length > 0) && (splitted_phrased_declarator[0] !== "function")) ||
(splitted_phrased_declarator.length === 0)){
var name = {
"name": first_identifier.lexeme,
"name_type": "variable",
"token": _.clone(first_identifier),
"declarator": phrased_declarator,
"specifiers_qualifiers": _.clone(specifiers_qualifiers),
"parameter": true
};
namespace["ordinary_ids"].push(name);
}
return;
}
else return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_init_declarator_list(subtree.children[i], specifiers_qualifiers);
}
}
}
};
if(parameter_declaration.children[0].title === "declaration_specifiers"){
if(parameter_declaration.children.length === 2){
if(parameter_declaration.children[1].title === "declarator"){
var specifiers_qualifiers = get_specifiers_qualifiers(parameter_declaration.children[0], namespace);
traverse_init_declarator_list(parameter_declaration.children[1], specifiers_qualifiers);
}
else{
/* Abstract declarator, do nothing for now. */
}
}
else if(parameter_declaration.children.length === 1){
var specifiers_qualifiers = get_specifiers_qualifiers(parameter_declaration.children[0], namespace);
}
}
else if(parameter_declaration.children[0].title === "type_name"){
if(parameter_declaration.children.length === 3){
var specifiers_qualifiers = get_specifiers_qualifiers(parameter_declaration.children[0], namespace);
traverse_init_declarator_list(parameter_declaration.children[1], specifiers_qualifiers);
}
}
};
module.exports.handle_parameter_declaration = handle_parameter_declaration;
get_specifiers_qualifiers = function(specifiers_qualifiers, namespace){
var type_qualifiers = get_type_qualifiers(specifiers_qualifiers, namespace);
var storage_class_specifiers = get_storage_class_specifiers(specifiers_qualifiers, namespace);
var type_specifiers = get_type_specifiers(specifiers_qualifiers, namespace);
var obj = {
"type_qualifiers": type_qualifiers,
"storage_class_specifiers": storage_class_specifiers,
"type_specifiers": type_specifiers
};
return obj;
};
get_type_qualifiers = function(specifiers_qualifiers, namespace){
var type_qualifiers = [];
var traverse = function(subtree){
if( subtree.title === "type_qualifier" ){
type_qualifiers.push(subtree.children[0]);
return;
}
else{
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)) return;
else{
for(var i = 0 ; i < subtree.children.length; i++) traverse(subtree.children[i]);
return;
}
}
};
traverse(specifiers_qualifiers);
return type_qualifiers;
};
get_storage_class_specifiers = function(specifiers_qualifiers, namespace){
var storage_class_specifiers = [];
var traverse = function(subtree){
if( subtree.title === "storage_class_specifier"){
storage_class_specifiers.push(subtree.children[0]);
return;
}
else{
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)) return;
else{
for(var i = 0 ; i < subtree.children.length; i++) traverse(subtree.children[i]);
return;
}
}
};
traverse(specifiers_qualifiers);
return storage_class_specifiers;
};
get_type_specifiers = function(specifiers_qualifiers, namespace){
var type_specifiers = [];
var traverse = function(subtree){
if( (subtree.title === "type_specifier") || (subtree.title === "type_name") ){
var ts = get_info_from_type_specifier(subtree, namespace);
type_specifiers.push(ts);
return;
}
else{
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)) return;
else{
for(var i = 0 ; i < subtree.children.length; i++) traverse(subtree.children[i]);
return;
}
}
};
traverse(specifiers_qualifiers);
return type_specifiers;
};
get_info_from_type_specifier = function(type_specifier, namespace){
/*
* type_specifier -> VOID
* | CHAR
* | SHORT
* | INT
* | LONG
* | FLOAT
* | DOUBLE
* | SIGNED
* | UNSIGNED
* | BOOL
* | COMPLEX
* | IMAGINARY
* | struct_or_union_specifier
* | enum_specifier
*
* */
if(type_specifier.title === "type_specifier"){
var obj = {};
var first_token = parse_tree_helper.get_first_token(type_specifier);
obj["type"] = first_token.lexeme;
if((obj.type === "struct") || (obj.type === "union")){
obj["primitive"] = false;
var details = get_details_from_struct_or_union_specifier(type_specifier.children[0], namespace);
obj["details"] = details;
}
else if(obj.type === "enum"){
obj["primitive"] = false;
var details = get_details_from_enum_specifier(type_specifier.children[0], namespace);
obj["details"] = details;
}
else{
obj["primitive"] = true;
}
return obj;
}
else if(type_specifier.title === "type_name"){
var obj = {};
var first_token = parse_tree_helper.get_first_token(type_specifier);
obj["type"] = first_token.lexeme;
obj["primitive"] = false;
return obj;
}
};
get_details_from_struct_or_union_specifier = function(struct_or_union_specifier, namespace){
/*
* struct_or_union_specifier -> struct_or_union IDENTIFIER '{' struct_declaration_list '}'
* | struct_or_union '{' struct_declaration_list '}'
* | struct_or_union IDENTIFIER
* */
var struct_or_union = parse_tree_helper.get_first_title_matching_subtree(struct_or_union_specifier, "struct_or_union");
if(struct_or_union_specifier.children.length === 5 ){
var struct_or_union_name = struct_or_union_specifier.children[1].lexeme;
var struct_or_union_members = get_members_from_struct_declaration_list(struct_or_union_specifier.children[3], namespace);
var name = {
"name": struct_or_union_name,
"token": _.clone(struct_or_union_specifier.children[1]),
"name_type": struct_or_union.children[0].lexeme,
"members": struct_or_union_members
};
namespace["tags"].push(name);
return {
"name": struct_or_union_name
};
}
else if(struct_or_union_specifier.children.length === 4 ){
var struct_or_union_members = get_members_from_struct_declaration_list(struct_or_union_specifier.children[2], namespace);
return {
"members": struct_or_union_members
};
}
else if(struct_or_union_specifier.children.length === 2 ){
var struct_or_union_name = struct_or_union_specifier.children[1].lexeme;
return {
"name": struct_or_union_name
};
}
};
get_members_from_struct_declaration_list = function(struct_declaration_list, namespace){
var members = [];
var traverse_struct_declaration_list = function(subtree){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "struct_declaration"){
get_members_from_struct_declaration(subtree, namespace, members);
return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_struct_declaration_list(subtree.children[i]);
}
return;
}
}
};
traverse_struct_declaration_list(struct_declaration_list);
return members;
};
get_members_from_struct_declaration = function(struct_declaration, namespace, members){
/*
* struct_declaration -> specifier_qualifier_list struct_declarator_list ';'
* */
var traverse_struct_declarator_list = function(subtree, specifiers_qualifiers){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "declarator"){
var first_identifier = parse_tree_helper.get_first_token(subtree, "IDENTIFIER");
var phrased_declarator = declarator_helper.get_phrasing_from_declarator(subtree);
if(first_identifier){
var splitted_phrased_declarator = phrased_declarator.trim().split(" ");
if( ((splitted_phrased_declarator.length > 0) && (splitted_phrased_declarator[0] !== "function")) ||
(splitted_phrased_declarator.length === 0)){
var name = {
"name": first_identifier.lexeme,
"name_type": "member",
"token": _.clone(first_identifier),
"declarator": phrased_declarator,
"specifiers_qualifiers": _.clone(specifiers_qualifiers),
};
members.push(name);
}
return;
}
else return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_struct_declarator_list(subtree.children[i], specifiers_qualifiers);
}
}
}
};
var specifiers_qualifiers = get_specifiers_qualifiers(struct_declaration.children[0]);
traverse_struct_declarator_list(struct_declaration.children[1], specifiers_qualifiers);
};
get_details_from_enum_specifier = function(enum_specifier, namespace){
/*
* enum_specifier -> ENUM IDENTIFIER '{' enumerator_list '}'
* | ENUM '{' enumerator_list '}'
* | ENUM IDENTIFIER '{' enumerator_list ',' '}'
* | ENUM '{' enumerator_list ',' '}'
* | ENUM IDENTIFIER
* */
if(enum_specifier.children.length === 5){
if(enum_specifier.children[1].tokenClass && enum_specifier.children[1].tokenClass === "IDENTIFIER"){
var enum_name = enum_specifier.children[1].lexeme;
var enum_members = get_members_from_enumerator_list(enum_specifier.children[3], namespace);
var name = {
"name": enum_name,
"token": _.clone(enum_specifier.children[1]),
"name_type": "enum",
"members": enum_members
};
namespace["tags"].push(name);
return {
"name": enum_name
};
}
else if(enum_specifier.children[1].tokenClass && enum_specifier.children[1].tokenClass === "{"){
var enum_members = get_members_from_enumerator_list(enum_specifier.children[2], namespace);
var name = {
"name": enum_name,
"token": _.clone(enum_specifier.children[1]),
"name_type": "enum",
"members": enum_members
};
namespace["tags"].push(name);
return {
"members": enum_members
};
}
}
else if(enum_specifier.children.length === 4){
var enum_members = get_members_from_enumerator_list(enum_specifier.children[3], namespace);
return {
"members": enum_members
};
}
else if(enum_specifier.children.length === 6){
var enum_name = enum_specifier.children[1].lexeme;
var enum_members = get_members_from_enumerator_list(enum_specifier.children[3], namespace);
var name = {
"name": enum_name,
"token": _.clone(enum_specifier.children[1]),
"name_type": "enum",
"members": enum_members
};
namespace["tags"].push(name);
return {
"name": enum_name
};
}
else if(enum_specifier.children.length === 2){
var enum_name = enum_specifier.children[1].lexeme;
return {
"name": enum_name
};
}
};
get_members_from_enumerator_list = function(enumerator_list, namespace){
/*
* enumerator_list -> enumerator enumerator_list_p
* */
var members = [];
var traverse_enumerator_list = function(subtree){
if((subtree === null) || (subtree.title === "EPSILON") || (subtree.children === null)){
return;
}
else{
if(subtree.title === "enumerator"){
var first_identifier = parse_tree_helper.get_first_token(subtree, "IDENTIFIER");
if(first_identifier){
var name = {
"name": first_identifier.lexeme,
"token": _.clone(first_identifier),
"name_type": "enumerator"
};
members.push(name);
namespace["ordinary_ids"].push(name);
return;
}
else return;
}
else{
for(var i = 0; i < subtree.children.length; i++){
traverse_enumerator_list(subtree.children[i]);
}
}
}
};
traverse_enumerator_list(enumerator_list);
return members;
};
| mit |
pawloKoder/Chin | src/main.cpp | 354 | #include "mainwindow.h"
#include <QApplication>
#include "characterset.h"
int main(int argc, char *argv[])
{
qRegisterMetaTypeStreamOperators<CharacterSets>("CharacterSets");
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("Pawlo");
QCoreApplication::setApplicationName("Chin");
MainWindow w;
w.show();
return a.exec();
}
| mit |
stefanovnm/C-OOP | Common-Type-System/06.BinarySearchTree/Properties/AssemblyInfo.cs | 1414 | 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("06.BinarySearchTree")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06.BinarySearchTree")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d744318-a11c-4737-8a6a-ad6ed6e400fd")]
// 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 |
namics/eslint-config-namics | test/es6/rules/es6/prefer-const.js | 550 |
// DESCRIPTION = suggest using of const declaration for variables that are never modified after declared
// STATUS = 2
/* eslint require-jsdoc: 0*/
/* eslint no-use-before-define: 0*/
/* eslint no-undef: 0*/
/* eslint no-unused-vars: 0*/
/* eslint no-unreachable: 0*/
/* eslint no-empty: 0*/
/* eslint no-empty-function: 0*/
/* eslint no-shadow: 0*/
/* eslint no-redeclare: 0*/
/* eslint no-restricted-syntax: 0*/
// <!START
// Bad
/*
let a;
a = 0;
// `i` is redefined (not reassigned) on each loop step.
for (let i in [1, 2, 3]) {
}
*/
// END!>
| mit |
rdfio/rdf2smw | components/residxtoresaggrconv.go | 514 | package components
type ResourceIndexToTripleAggregates struct {
In chan *map[string]*TripleAggregate
Out chan *TripleAggregate
}
func NewResourceIndexToTripleAggregates() *ResourceIndexToTripleAggregates {
return &ResourceIndexToTripleAggregates{
In: make(chan *map[string]*TripleAggregate, BUFSIZE),
Out: make(chan *TripleAggregate, BUFSIZE),
}
}
func (p *ResourceIndexToTripleAggregates) Run() {
defer close(p.Out)
for idx := range p.In {
for _, aggr := range *idx {
p.Out <- aggr
}
}
}
| mit |
GearPlug/batchbook-python | batchbook/exception.py | 249 | class BaseError(Exception):
pass
class InvalidCredential(BaseError):
pass
class Bad_Request(BaseError):
pass
class Not_Found(BaseError):
pass
class InvalidFirstName(BaseError):
pass
class InvalidLastName(BaseError):
pass | mit |
alphagov/digitalmarketplace-api | scripts/update_service.py | 1413 | #!/usr/bin/env python
"""Update a service
Usage:
update_service.py <endpoint> <access_token> <service_id> <filename>
Example:
./update_service.py http://localhost:5000 myToken ~/update.json
"""
from __future__ import print_function
import json
import requests
import getpass
from docopt import docopt
def update(base_url, access_token, filename, service_id):
print(base_url)
print(access_token)
print(filename)
print(service_id)
endpoint = "{}/services/{}".format(base_url, service_id)
with open(filename) as data_file:
json_from_file = json.load(data_file)
data = {
'update_details': {
'updated_by': getpass.getuser()
},
'services': json_from_file
}
print(endpoint)
response = requests.post(
endpoint,
data=json.dumps(data),
headers={
"content-type": "application/json",
"authorization": "Bearer {}".format(access_token),
}
)
print(response.status_code)
print(response.text)
return service_id, response
if __name__ == "__main__":
arguments = docopt(__doc__)
update(
base_url=arguments['<endpoint>'],
access_token=arguments['<access_token>'],
service_id=arguments['<service_id>'],
filename=arguments['<filename>'],
)
| mit |
Grobim/pic-picker | src/containers/NotesResultsContainer.js | 640 | import { connect } from 'react-redux';
import NotesResults from 'components/NotesResults';
import { PICS_PER_FILE, PICS_PER_LINE } from 'store/pics';
const mapStateToProps = ({ notes }) => ({
notes : notes.notes.map((note, id) => {
const imageId = id % PICS_PER_FILE;
return {
id,
note,
file : `00${Math.floor(id / PICS_PER_FILE) + 1}.jpg`,
line : Math.floor(imageId / PICS_PER_LINE) + 1,
column : imageId % PICS_PER_LINE + 1
};
}).sort((note1, note2) => note2.note - note1.note)
});
export default connect(mapStateToProps)(NotesResults);
| mit |
ismasan/tecepe | lib/tecepe/tcp_connection.rb | 400 | module Tecepe
module TCPConnection
include Connection
HEARTBEAT = 5.freeze
def post_init
@heartbeat = setup_heartbeat
super
end
def unbind
@heartbeat.cancel
super
end
private
def setup_heartbeat
EventMachine::PeriodicTimer.new(HEARTBEAT) do
log :heartbeat
send_data ''
end
end
end
end | mit |
vixataaa/asp-project | src/SecondHand/SecondHand.Data/Repositories/UsersRepository.cs | 683 | using System;
using SecondHand.Data.Models;
using SecondHand.Data.Repositories.Base;
using SecondHand.Data.Repositories.Contracts;
using System.Linq;
namespace SecondHand.Data.Repositories
{
public class UsersRepository : EfRepository<ApplicationUser>, IUsersRepository
{
public UsersRepository(MsSqlDbContext context)
: base(context)
{
}
public ApplicationUser GetById(string id)
{
return this.All.FirstOrDefault(x => x.Id == id);
}
public ApplicationUser GetByUsername(string username)
{
return this.All.FirstOrDefault(x => x.UserName == username);
}
}
}
| mit |
keijiro/SSE | ShaderEditor/Assets/StrumpyShaderEditor/Editor/Graph/Nodes/Operations/SqrtNode.cs | 715 | using System.Runtime.Serialization;
namespace StrumpyShaderEditor
{
[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
[NodeMetaData("Sqrt", "Operation", typeof(SqrtNode),"Square Root. Internally more accurate then using Pow with 0.5, aswell as being faster. Has moderate use in ramping, particurally in the [0,1] range it has a distinct ramp with a vertical tangent on approach to zero.")]
public class SqrtNode : FunctionOneInput {
private const string NodeName = "Sqrt";
public override string NodeTypeName
{
get{ return NodeName; }
}
public override string FunctionName
{
get{ return "sqrt"; }
}
}
}
| mit |
largem/Java101 | json101/src/main/java/net/largem/java101/json102/dload/JsonBindable.java | 1140 | package net.largem.java101.json102.dload;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public interface JsonBindable {
static String toFullJsonString(ObjectMapper om, JsonBindable o) throws JsonProcessingException {
JsonNode node = om.valueToTree(o);
((ObjectNode)node).put("clazz", o.getClass().getName());
return om.writeValueAsString(node);
}
static JsonBindable fromJsonString(String jsonString, ObjectMapper om)
throws IOException, ClassNotFoundException {
JsonNode jsonNode = om.readTree(jsonString);
JsonNode classNode = jsonNode.findValue("clazz");
String className = classNode.asText();
((ObjectNode)jsonNode).remove("clazz");
//Class<? extends JsonBindable> clazz = (Class<? extends JsonBindable>)JsonBindable.class.getClassLoader().loadClass(className);
Class<?> clazz = Class.forName(className);
return om.treeToValue(jsonNode, (Class<? extends JsonBindable>)clazz);
}
}
| mit |
LSPOoO/com.lspooo.example | plugin_common/src/main/java/com/lspooo/plugin/common/common/swipe/SwipeTranslucentMethodUtils.java | 3219 | package com.lspooo.plugin.common.common.swipe;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityOptions;
import android.os.Build;
import com.lspooo.plugin.common.tools.SDKVersionUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class SwipeTranslucentMethodUtils {
private SwipeTranslucentMethodUtils() {
}
/**
* Convert a translucent themed Activity
* {@link android.R.attr#windowIsTranslucent} to a fullscreen opaque
* Activity.
* <p>
* Call this whenever the background of a translucent Activity has changed
* to become opaque. Doing so will allow the {@link android.view.Surface} of
* the Activity behind to be released.
* <p>
* This call has no effect on non-translucent activities or on activities
* with the {@link android.R.attr#windowIsFloating} attribute.
*/
public static boolean convertActivityFromTranslucent(Activity activity) {
try {
Method method = Activity.class.getDeclaredMethod("convertFromTranslucent");
method.setAccessible(true);
method.invoke(activity);
return true;
} catch (Throwable t) {
return false;
}
}
/**
* Convert a translucent themed Activity
* {@link android.R.attr#windowIsTranslucent} back from opaque to
* translucent following a call to
* {@link #convertActivityFromTranslucent(Activity)} .
* <p>
* Calling this allows the Activity behind this one to be seen again. Once
* all such Activities have been redrawn
* <p>
* This call has no effect on non-translucent activities or on activities
* with the {@link android.R.attr#windowIsFloating} attribute.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void convertActivityToTranslucent(Activity activity , MethodInvoke.SwipeInvocationHandler handler) {
try {
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
if(translucentConversionListenerClazz != null) {
Object proxy = Proxy.newProxyInstance(translucentConversionListenerClazz.getClassLoader(), new Class[] {translucentConversionListenerClazz}, handler);
if(!SDKVersionUtils.isGreatThanOrEqualTo(21)) {
Method method = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz);
method.setAccessible(true);
method.invoke(activity, proxy);
} else {
Method method = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz, ActivityOptions.class);
method.setAccessible(true);
method.invoke(activity, proxy,null);
}
}
} catch (Throwable t) {
}
}
}
| mit |
Need4Speed402/tessellator | src/model/modules/Start.js | 2838 | /**
* Copyright (c) 2015, Alexander Orzechowski.
*
* 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.
*/
/**
* Currently in beta stage. Changes can and will be made to the core mechanic
* making this not backwards compatible.
*
* Github: https://github.com/Need4Speed402/tessellator
*/
Tessellator.Initializer.setDefault("colorAttribEnabled", function (){
return true;
});
Tessellator.Model.prototype.start = function (type, drawType){
var start = new Tessellator.Model.Start(type, drawType);
this.add(start);
return start.geometry;
};
Tessellator.Model.Start = function (shapeType, drawType) {
this.drawType = drawType;
this.shapeType = shapeType;
};
Tessellator.Model.Start.prototype.init = function (interpreter){
if (
this.shapeType === Tessellator.INDICES ||
this.shapeType === Tessellator.TEXTURE ||
this.shapeType === Tessellator.NORMAL
){
var extra = interpreter.get("extraGeometry");
if (extra){
extra.type = this.shapeType;
this.geometry = extra;
}else{
this.geometry = new Tessellator.Geometry(this.shapeType);
interpreter.set("extraGeometry", this.geometry);
};
}else{
this.geometry = new Tessellator.Geometry(this.shapeType);
if (interpreter.get("colorAttribEnabled") && interpreter.get("draw") !== Tessellator.TEXTURE){
this.geometry.setColor(interpreter.get("color255"));
};
if (this.shapeType === Tessellator.LINE){
interpreter.set("draw", Tessellator.LINE);
};
interpreter.set("currentGeometry", this.geometry);
};
interpreter.set("geometryType", this.shapeType);
return null;
}; | mit |
bacta/swg | game-server/src/main/java/com/ocdsoft/bacta/swg/shared/chat/messages/ChatInviteAvatarToRoom.java | 860 | package com.ocdsoft.bacta.swg.shared.chat.messages;
import com.ocdsoft.bacta.engine.utils.BufferUtil;
import com.ocdsoft.bacta.soe.message.GameNetworkMessage;
import com.ocdsoft.bacta.soe.message.Priority;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.nio.ByteBuffer;
/**
* Created by crush on 5/20/2016.
*/
@Getter
@Priority(0x05)
@AllArgsConstructor
public final class ChatInviteAvatarToRoom extends GameNetworkMessage {
private final ChatAvatarId avatarId;
private final String roomName;
public ChatInviteAvatarToRoom(final ByteBuffer buffer) {
this.avatarId = new ChatAvatarId(buffer);
this.roomName = BufferUtil.getAscii(buffer);
}
@Override
public void writeToBuffer(final ByteBuffer buffer) {
BufferUtil.put(buffer, avatarId);
BufferUtil.put(buffer, roomName);
}
} | mit |
cryptorinium/num2 | src/qt/locale/bitcoin_th_TH.ts | 97840 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="th_TH" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Num2coin</source>
<translation>เกี่ยวกับ บิตคอย์น</translation>
</message>
<message>
<location line="+39"/>
<source><b>Num2coin</b> version</source>
<translation><b>บิตคอย์น<b>รุ่น</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Num2coin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>สมุดรายชื่อ</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>ดับเบิลคลิก เพื่อแก้ไขที่อยู่ หรือชื่อ</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>สร้างที่อยู่ใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Num2coin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Num2coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Num2coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>ลบ</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Num2coin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>ส่งออกรายชื่อทั้งหมด</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ไม่มีชื่อ)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ใส่รหัสผ่าน</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>รหัสผา่นใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>กระเป๋าสตางค์ที่เข้ารหัส</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>เปิดกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>ถอดรหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>เปลี่ยนรหัสผ่าน</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>กรอกรหัสผ่านเก่าและรหัสผ่านใหม่สำหรับกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ZETACOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation>
</message>
<message>
<location line="-56"/>
<source>Num2coin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your num2coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Num2coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Num2coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Num2coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Num2coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Num2coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Num2coin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Num2coin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Num2coin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Num2coin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Num2coin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Num2coin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Num2coin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Num2coin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Num2coin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Num2coin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Num2coin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Num2coin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Num2coin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Num2coin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Num2coin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Num2coin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start num2coin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Num2coin-Qt help message to get a list with possible Num2coin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Num2coin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Num2coin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Num2coin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Num2coin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Num2coin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Num2coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Num2coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Num2coin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Num2coin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+25"/>
<source>The Num2coin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>วันนี้</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Num2coin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or num2coind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: num2coin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: num2coind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=num2coinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Num2coin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Num2coin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Num2coin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>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.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Num2coin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Num2coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Num2coin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Num2coin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | mit |
codetech/codetechcomputerclub | app/webroot/js/tinymce/plugins/insertcode/plugin.min.js | 1034 | tinymce.PluginManager.add("insertcode",function(b){function d(a){b.insertContent("none"===a.name?"<pre><code>Code goes here.</code></pre>":'<pre><code class="'+a.type+'">'+a.name+" code goes here.</code></pre>")}var f=[{name:"none",type:""},{name:"Apache",type:"apache"},{name:"Bash",type:"bash"},{name:"C#",type:"cs"},{name:"C++",type:"cpp"},{name:"CSS",type:"css"},{name:"Diff",type:"diff"},{name:"DOS .bat",type:"dos"},{name:"HTML, XML",type:"xml"},{name:"HTTP",type:"http"},{name:"Ini",type:"ini"},
{name:"JSON",type:"json"},{name:"Java",type:"java"},{name:"JavaScript",type:"javascript"},{name:"PHP",type:"php"},{name:"Perl",type:"perl"},{name:"Python",type:"python"},{name:"Ruby",type:"ruby"},{name:"SQL",type:"sql"}],c=[],e;b.addButton("insertcode",{type:"splitbutton",title:"Insert code",onclick:function(){d(e||"")},menu:c});tinymce.each(b.settings.insertcode_formats||f,function(a){c.push({text:a.name,onclick:function(){e=a;d(a)}})});b.addMenuItem("insertcode",{icon:"code",text:"Insert code",
menu:c,context:"insert"})});
| 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.