repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
VicAMMON/totaljs-documentation
|
controllers/default.js
|
144
|
exports.install = function() {
F.route('/', redirect);
};
function redirect() {
this.redirect('/v' + CONFIG('version') + '/en.html');
}
|
mit
|
tomthebuzz/mix
|
src/QBasicNodeDefinition.cpp
|
1192
|
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file QBasicNodeDefinition.cpp
* @author Yann yann@ethdev.com
* @date 2014
*/
#include "QBasicNodeDefinition.h"
#include <libsolidity/AST.h>
namespace dev
{
namespace mix
{
QBasicNodeDefinition::QBasicNodeDefinition(QObject* _parent, solidity::Declaration const* _d):
QObject(_parent), m_name(QString::fromStdString(_d->name())), m_location(_d->location())
{
}
QBasicNodeDefinition::QBasicNodeDefinition(QObject* _parent, std::string const& _name):
QObject(_parent), m_name(QString::fromStdString(_name))
{
}
}
}
|
mit
|
ychaim/dark-test-v2
|
src/util.cpp
|
38557
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "BitcoinDark";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\BitcoinDark
// Windows >= Vista: C:\Users\Username\AppData\Roaming\BitcoinDark
// Mac: ~/Library/Application Support/BitcoinDark
// Unix: ~/.BitcoinDark
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "BitcoinDark";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "BitcoinDark";
#else
// Unix
return pathRet / ".BitcoinDark";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int32_t i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
void createConf()
{
srand(time(NULL));
ofstream pConf;
pConf.open(GetConfigFile().generic_string().c_str());
pConf << "rpcuser=user\nrpcpassword="
+ randomStrGen(15)
+ "\nrpcport=14632"
+ "\nport=14631"
+ "\ndaemon=1"
+ "\nserver=1"
+ "\naddnode=107.170.59.196"
+ "\naddnode=146.185.188.6"
+ "\naddnode=54.85.50.15:50288"
+ "\naddnode=107.170.44.31";
pConf.close();
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "BitcoinDark.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
{
createConf();
new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
if(!streamConfig.good())
return;
}
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "BitcoinDarkd.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong BitcoinDark will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("BitcoinDark"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
|
mit
|
kfatehi/node-protocol-analyzer
|
client/config_window.js
|
5169
|
module.exports = ConfigWindow;
var RollupWindow = require('./rollup_window');
var $ = require('jquery');
var EventEmitter = require('node-event-emitter').EventEmitter;
function ConfigWindow(){
this.emitter = new EventEmitter();
this.on = this.emitter.on;
this.emit = this.emitter.emit;
this.$el = $('.configuration.window');
this.initialize();
}
ConfigWindow.prototype = {
$: function(selector) {
return this.$el.find(selector)
},
initialize: function() {
var self = this;
this.$baudRate = this.$('#baudrate').change(function() {
self.handleBaudRateChange(this);
})
this.$('.sniffer-probe input.active').change(function() {
self.handleSnifferProbeChange(this);
})
this.$('.mitm-port select').change(function() {
self.handleMitmPortChange(this);
})
this.$('.sniffer-probe input.alias').keyup(function() {
self.handleAliasUpdate(this)
})
this.$('.mode-selection input').change(function() {
self.handleModeChange(this)
})
this.$('section[data-mode=mitm] button[value=run]').click(function() {
self.emit('mitm run', self.getMitmScript());
});
RollupWindow.setup(this.$el);
},
getAttributes: function() {
return {
baudRate: this.getBaudRate(),
mode: this.getSelectedMode(),
activeProbes: this.getSelectedPorts(),
probeAliases: this.getProbeAliases()
}
},
handleBaudRateChange: function(eventTarget) {
var $el = $(eventTarget)
var val = parseInt($el.val()) || 9600;
$el.val(val)
this.emit('change', ['baudRate'], this.getAttributes());
},
handleSnifferProbeChange: function(eventTarget) {
var ports = this.getSelectedPorts();
var $el = $(eventTarget);
var checked = $el.prop('checked');
var name = $el.val();
if (ports.length > 2) return $el.prop('checked', false);
this.emit('change', ['activeProbes'], this.getAttributes());
},
handleMitmPortChange: function(eventTarget) {
var $el = $(eventTarget);
var direction = $el.data('direction');
var value = $el.val();
var ports = this.getSelectedPorts();
var samePort = ports.upstream === ports.downstream;
if (value !== '' && samePort) return $el.val('');
this.emit('change', ['activeProbes'], this.getAttributes());
},
handleAliasUpdate: function(eventTarget) {
this.emit('change', ['probeAliases'], this.getAttributes());
},
handleModeChange: function() {
this.emit('change', ['mode'], this.getAttributes());
},
optionsWereChanged: function(options) {
var keys = Object.keys(options)
for (var i=0; i<keys.length; i++) {
var key = keys[i];
var value = options[key];
this.optionWasChanged[key](this, value);
}
},
optionWasChanged: {
baudRate: function(self, newBaudRate) {
self.$('select#baudrate').val(newBaudRate);
},
mode: function(self, newMode) {
self.$('.mode-selection input[value='+newMode+']').prop('checked', true);
self.emit('changed mode', newMode);
}
},
getBaudRate: function() {
return parseInt(this.$baudRate.val())
},
getSnifferProbeCheckbox: function(name) {
return this.$('.sniffer-probe input[value="'+name+'"]');
},
getMitmSelect: function(direction) {
var sel = '.mitm-port select[data-direction='+direction+']';
return this.$(sel);
},
getMitmValue: function(direction) {
var value = this.getMitmSelect(direction).val();
return value === '' ? null : value;
},
portWasClosed: function(name, modeWhenOpened, direction) {
this.caseMode({
sniffer: function() {
this.getSnifferProbeCheckbox(name).prop('checked', false);
},
mitm: function() {
this.getMitmSelect(direction).val('');
}
}, modeWhenOpened);
},
portWasOpened: function(name, mode, direction) {
this.caseMode({
sniffer: function() {
this.getSnifferProbeCheckbox(name).prop('checked', true);
},
mitm: function() {
this.getMitmSelect(direction).val(name);
}
})
},
caseMode: function(funcList, modeOverride) {
var mode = modeOverride || this.getSelectedMode();
if (mode === "sniffer") return funcList.sniffer.bind(this)();
else if (mode === "mitm") return funcList.mitm.bind(this)();
else throw new Error('Unsupported mode '+mode);
},
getSelectedPorts: function() {
return this.caseMode({
sniffer: this.getSnifferPorts,
mitm: this.getMitmPorts
})
},
getSnifferPorts: function() {
var out = []
this.$('.sniffer-probe input.active:checked').each(function(i, el) {
out.push(el.value);
})
return out;
},
getMitmPorts: function() {
return {
upstream: this.getMitmValue('upstream'),
downstream: this.getMitmValue('downstream')
};
},
getMitmScript: function() {
return this.$('.mitm-script').text();
},
getSelectedMode: function() {
return this.$('.mode-selection input:checked').val();
},
getProbeAliases: function() {
var out = {}
this.$('.probe input.alias').each(function(i, el) {
out[el.attributes['data-name'].value] = el.value
})
return out;
}
}
|
mit
|
naoned/phpoaipmh
|
src/Phpoaipmh/EndpointInterface.php
|
3339
|
<?php
/**
* PHPOAIPMH Library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/caseyamcl/phpoaipmh
* @version 2.0
* @package caseyamcl/phpoaipmh
* @author Casey McLaughlin <caseyamcl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* ------------------------------------------------------------------
*/
namespace Phpoaipmh;
/**
* OAI-PMH Endpoint Interface
*
* @since v2.3
* @author Casey McLaughlin <caseyamcl@gmail.com>
*/
interface EndpointInterface
{
/**
* Set the URL in the client
*
* @param string $url
*/
public function setUrl($url);
/**
* Identify the OAI-PMH Endpoint
*
* @return \SimpleXMLElement A XML document with attributes describing the
* repository
*/
public function identify();
/**
* List Metadata Formats
*
* Return the list of supported metadata format for a particular record (if
* $identifier is provided), or the entire repository (if no arguments are
* provided)
*
* @param string $identifier If specified, will return only those
* metadata formats that a particular
* record supports
* @return RecordIterator
*/
public function listMetadataFormats($identifier = null);
/**
* List Record Sets
*
* @return RecordIterator
*/
public function listSets();
/**
* Get a single record
*
* @param string $id Record Identifier
* @param string $metadataPrefix Required by OAI-PMH endpoint
* @return \SimpleXMLElement An XML document corresponding to the record
*/
public function getRecord($id, $metadataPrefix);
/**
* List Record identifiers
*
* Corresponds to OAI Verb to list record identifiers
*
* @param string $metadataPrefix Required by OAI-PMH endpoint
* @param \DateTime $from An optional 'from' date for
* selective harvesting
* @param \DateTime $until An optional 'until' date for
* selective harvesting
* @param string $set An optional setSpec for selective
* harvesting
* @return RecordIterator
*/
public function listIdentifiers($metadataPrefix, $from = null, $until = null, $set = null);
/**
* List Records
*
* Corresponds to OAI Verb to list records
*
* @param string $metadataPrefix Required by OAI-PMH endpoint
* @param \DateTime $from An optional 'from' date for
* selective harvesting
* @param \DateTime $until An optional 'from' date for
* selective harvesting
* @param string $set An optional setSpec for selective
* harvesting
* @return RecordIterator
*/
public function listRecords($metadataPrefix, $from = null, $until = null, $set = null);
}
|
mit
|
thiagormoreira/guia-comercial
|
src/AppBundle/Tests/Controller/StateControllerTest.php
|
1903
|
<?php
namespace AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class StateControllerTest extends WebTestCase
{
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Create a new entry in the database
$crawler = $client->request('GET', '/state/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /state/");
$crawler = $client->click($crawler->selectLink('Create a new entry')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Create')->form(array(
'appbundle_state[field_name]' => 'Test',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")');
// Edit the entity
$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Update')->form(array(
'appbundle_state[field_name]' => 'Foo',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
// Delete the entity
$client->submit($crawler->selectButton('Delete')->form());
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
}
|
mit
|
drostar/CrackerBarrel
|
Assets/ThirdParty/Zenject/OptionalExtras/CommandsAndSignals/Command/Binders/CommandBinder4.cs
|
3102
|
using System;
namespace Zenject
{
// Four parameters
public class CommandBinder<TCommand, TParam1, TParam2, TParam3, TParam4> : CommandBinderBase<TCommand, Action<TParam1, TParam2, TParam3, TParam4>>
where TCommand : Command<TParam1, TParam2, TParam3, TParam4>
{
public CommandBinder(string identifier, DiContainer container)
: base(identifier, container)
{
}
public ScopeArgBinder To<THandler>(Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
Finalizer = new CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2, TParam3, TParam4>(
BindInfo, methodGetter,
(container) => new TransientProvider(
typeof(THandler), container, BindInfo.Arguments, BindInfo.ConcreteIdentifier));
return new ScopeArgBinder(BindInfo);
}
public ScopeBinder ToResolve<THandler>(Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
return ToResolve<THandler>(null, methodGetter);
}
public ScopeBinder ToResolve<THandler>(
string identifier, Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
return ToResolveInternal<THandler>(identifier, methodGetter, false);
}
public ScopeBinder ToOptionalResolve<THandler>(Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
return ToOptionalResolve<THandler>(null, methodGetter);
}
public ScopeBinder ToOptionalResolve<THandler>(
string identifier, Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
return ToResolveInternal<THandler>(identifier, methodGetter, true);
}
public ConditionBinder ToNothing()
{
return ToMethod((p1, p2, p3, p4) => {});
}
// AsSingle / AsCached / etc. don't make sense in this case so just return ConditionBinder
public ConditionBinder ToMethod(Action<TParam1, TParam2, TParam3, TParam4> action)
{
// Create the command class once and re-use it everywhere
Finalizer = new SingleProviderBindingFinalizer(
BindInfo,
(container, _) => new CachedProvider(
new TransientProvider(
typeof(TCommand), container,
InjectUtil.CreateArgListExplicit(action), null)));
return new ConditionBinder(BindInfo);
}
ScopeBinder ToResolveInternal<THandler>(
string identifier, Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter, bool optional)
{
Finalizer = new CommandBindingFinalizer<TCommand, THandler, TParam1, TParam2, TParam3, TParam4>(
BindInfo, methodGetter,
(container) => new ResolveProvider(typeof(THandler), container, identifier, optional));
return new ScopeBinder(BindInfo);
}
}
}
|
mit
|
CodeForCharlotte/cmpd-holiday-gift-backend
|
backend/common/src/entities/abstract/user.ts
|
654
|
import { BaseEntity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
export default abstract class extends BaseEntity {
@PrimaryGeneratedColumn() id: number;
@Column('text', { name: 'name_first' })
firstName: string;
@Column('text', { name: 'name_last' })
lastName: string;
@Column('text') email: string;
@Column('boolean', { default: true })
active: boolean;
@Column('boolean', { default: false })
approved: boolean;
@Column('text', { nullable: true })
role: string;
@CreateDateColumn({ name: 'created_at' })
createdAt;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt;
}
|
mit
|
WeenAFK/core
|
core/src/com/stabilise/util/annotation/Unguarded.java
|
659
|
package com.stabilise.util.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the state of the specified field is technically unguarded and
* hence vulnerable to concurrent interference from foolish or malicious
* sources. As a rule of thumb, this annotation should never have any place in
* your program ever, and if it does, find a way to redesign it!
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
public @interface Unguarded {
}
|
mit
|
textmagic/textmagic-rest-csharp
|
TextmagicRest/Model/ContactsResult.cs
|
409
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp.Deserializers;
namespace TextmagicRest.Model
{
/// <summary>
/// List of Contact objects
/// </summary>
public class ContactsResult: BaseModelList
{
[DeserializeAs(Name = "resources")]
public List<Contact> Contacts { get; set; }
}
}
|
mit
|
svelto/svelto
|
src/widgets/remote/modal/modal.js
|
1076
|
// @require ../remote.js
// @require ../widget/widget.js
// @require widgets/modal/modal.js
(function ( $, _, Svelto, Widgets, Factory, Animations ) {
/* CONFIG */
let config = {
name: 'remoteModal',
templates: {
placeholder: _.template ( `
<div class="modal container <%= o.classes.placeholder %> <%= o.classes.placeholderExtra %>">
<svg class="spinner">
<circle cx="1.625em" cy="1.625em" r="1.25em">
</svg>
</div>
` )
},
options: {
widget: Widgets.Modal,
classes: {
placeholder: 'remote-modal-placeholder',
loaded: 'remote-modal-loaded',
resizing: 'remote-modal-resizing',
showing: 'remote-modal-showing'
},
animations: {
placeholder: Animations.normal,
resize: Animations.normal
}
}
};
/* REMOTE MODAL */
class RemoteModal extends Widgets.RemoteWidget {}
/* FACTORY */
Factory.make ( RemoteModal, config );
}( Svelto.$, Svelto._, Svelto, Svelto.Widgets, Svelto.Factory, Svelto.Animations ));
|
mit
|
ben-dent/PythonEditor
|
tests/spec/python-spec.js
|
7897
|
// An editor needs to be instantiated *before* the tests are run so the
// snippets are created so they can be referenced within the tests. Yay
// JavaScript. :-(
var faux_editor = pythonEditor('fooeditor');
// Test suite for the pythonEditor object.
describe("An editor for MicroPython on the BBC micro:bit:", function() {
describe("The editor initialises as expected.", function() {
beforeEach(function() {
affix("#editor");
});
it("The editor is associated with the referenced div.", function() {
var editor = pythonEditor('editor');
// An editor object is created
expect(editor).toBeDefined();
// The div with the id='editor' has been trapped for editing.
var dom_editor = $('#editor');
expect(dom_editor.children().length).toBeGreaterThan(0);
// It references the expected classes.
var expected_classes = ' ace_editor ace-kr-theme ace_dark';
expect(dom_editor.attr('class')).toEqual(expected_classes);
});
it("The expected theme is kr_theme.", function() {
var editor = pythonEditor('editor');
expect(editor.ACE.getTheme()).toEqual('ace/theme/kr_theme');
});
it("The editor mode is set to 'Python'.", function() {
var editor = pythonEditor('editor');
expect(editor.ACE.getOption('mode')).toEqual('ace/mode/python');
});
it("Snippets are enabled.", function() {
var editor = pythonEditor('editor');
expect(editor.ACE.getOption('enableSnippets')).toBe(true);
});
it("A tab is the same as 4 spaces.", function() {
var editor = pythonEditor('editor');
expect(editor.ACE.getOption('tabSize')).toBe(4);
})
it("A tab is 'soft'.", function() {
var editor = pythonEditor('editor');
expect(editor.ACE.getOption('useSoftTabs')).toBe(true);
});
});
describe("Getting and setting Python scripts is possible.", function() {
var editor;
var dom_editor;
beforeEach(function() {
affix("#editor");
editor = pythonEditor('editor');
dom_editor = $('#editor');
});
it("It's possible to set / get the code to be edited.", function() {
expect(editor.getCode()).toBe('');
var code = "print('Hello, World!')";
editor.setCode(code);
expect(editor.getCode()).toBe(code);
});
it("The editor can be given focus.", function() {
editor.focus();
expect(document.activeElement.className).toEqual('ace_text-input');
});
});
describe("Change events are handled as specified.", function() {
var editor;
var mock;
beforeEach(function() {
affix("#editor");
editor = pythonEditor('editor');
mock = {
handler: function(){ return null;}
};
spyOn(mock, 'handler');
editor.on_change(mock.handler);
editor.setCode('foo');
});
it("The editor calls the referenced function when the text changes.",
function() {
expect(mock.handler).toHaveBeenCalled();
});
});
describe("Code snippets function as expected.", function() {
var editor;
var snippetManager;
beforeEach(function() {
affix("#editor");
editor = pythonEditor('editor');
snippetManager = ace.require("ace/snippets").snippetManager;
spyOn(snippetManager, 'insertSnippet');
});
it("The editor returns all available snippet objects.", function() {
var result = editor.getSnippets();
expect(result.length).toBeGreaterThan(0);
});
it("It is possible to trigger an existing named snippet.", function() {
var snippets = editor.getSnippets();
var snippet = snippets[0];
editor.triggerSnippet(snippet.name);
expect(snippetManager.insertSnippet).toHaveBeenCalled();
expect(snippetManager.insertSnippet.calls.count()).toBe(1);
var call = snippetManager.insertSnippet.calls.argsFor(0);
expect(call[0]).toBe(editor.ACE);
expect(call[1]).toBe(snippet.content);
});
it("The editor will ignore unknown snippet names.", function() {
editor.triggerSnippet('foo');
expect(snippetManager.insertSnippet.calls.count()).toBe(0);
});
});
describe("It's possible to generate a hex file.", function() {
var editor;
beforeEach(function() {
affix("#editor");
editor = pythonEditor('editor');
});
it("The editor converts text into Intel's hex format.", function() {
var hexified = editor.hexlify('display.scroll("Hello")');
var expected = ':10E000004D501700646973706C61792E7363726F81\n' +
':10E010006C6C282248656C6C6F222900000000009F';
expect(hexified).toEqual(expected);
});
it("A hex file is generated from the script and template firmware.",
function() {
var template_hex = ":10E000004D500B004D6963726F507974686F6E00EC\n" +
":::::::::::::::::::::::::::::::::::::::::::\n" +
":10E000004D500B004D6963726F507974686F6E00EC";
editor.setCode('display.scroll("Hello")');
var result = editor.getHexFile(template_hex);
var expected = ":10E000004D500B004D6963726F507974686F6E00EC\n" +
":10E000004D501700646973706C61792E7363726F81\n" +
":10E010006C6C282248656C6C6F222900000000009F\n" +
":10E000004D500B004D6963726F507974686F6E00EC";
expect(result).toEqual(expected);
});
});
describe("It's possible to extract scripts from a hex file.", function() {
var editor;
beforeEach(function() {
affix("#editor");
editor = pythonEditor('editor');
});
it("The editor converts from Intel's hex format to text", function() {
var raw_hex = ":10E000004D501700646973706C61792E7363726F81\n" +
":10E010006C6C282248656C6C6F222900000000009F\n";
var result = editor.unhexlify(raw_hex);
var expected = 'display.scroll("Hello")';
expect(result).toEqual(expected);
});
it("A script is extracted from a hex file.", function() {
var raw_hex = ":10E000004D500B004D6963726F507974686F6E00EC\n" +
":020000040003F7\n" +
":10B2C00021620100E1780100198001000190010074\n" +
":04B2D0000D0100006C\n" +
":020000040003F7\n" +
":10E000004D501700646973706C61792E7363726F81\n" +
":10E010006C6C282248656C6C6F222900000000009F\n" +
":04000005000153EDB6\n" +
":00000001FF";
var result = editor.extractScript(raw_hex);
var expected = 'display.scroll("Hello")';
expect(result).toEqual(expected);
});
it("If no script in hex, return empty string.", function() {
var raw_hex = ":10E000004D500B004D6963726F507974686F6E00EC\n" +
":10B2C00021620100E1780100198001000190010074\n" +
":04B2D0000D0100006C\n" +
":10E000004D501700646973706C61792E7363726F81\n" +
":10E010006C6C282248656C6C6F222900000000009F\n" +
":04000005000153EDB6\n" +
":00000001FF";
var result = editor.extractScript(raw_hex);
var expected = '';
expect(result).toEqual(expected);
});
});
});
|
mit
|
greevex/mpcmf-web
|
src/apps/mpcmfWeb/modules/authex/routes.php
|
449
|
<?php
namespace mpcmf\modules\authex;
use mpcmf\modules\moduleBase\moduleRoutesBase;
use mpcmf\system\pattern\singleton;
/**
* Routes map class
*
* @author Gregory Ostrovsky <greevex@gmail.com>
* @date: 2/27/15 1:41 PM
*/
class routes
extends moduleRoutesBase
{
use singleton;
/**
* Register some routes
*
* @return mixed
*/
public function bind()
{
// TODO: Implement bind() method.
}
}
|
mit
|
nordsieck/wendigo
|
parser/lex_test.go
|
1200
|
package parser
import (
"go/token"
"testing"
"github.com/nordsieck/defect"
)
func TestScanner_Scan(t *testing.T) {
s := Scanner{}
expected := map[string][]token.Token{
`package main
`: {token.PACKAGE, token.IDENT, token.SEMICOLON},
`package main
import "fmt"
func main(){
fmt.Println("hello world")
}
`: {token.PACKAGE, token.IDENT, token.SEMICOLON,
token.IMPORT, token.STRING, token.SEMICOLON,
token.FUNC, token.IDENT, token.LPAREN, token.RPAREN, token.LBRACE,
token.IDENT, token.PERIOD, token.IDENT, token.LPAREN, token.STRING, token.RPAREN, token.SEMICOLON,
token.RBRACE, token.SEMICOLON},
}
for text, symbols := range expected {
s.Init([]byte(text))
i := 0
_, tok, _ := s.Scan()
for tok != token.EOF {
defect.Equal(t, tok, symbols[i])
_, tok, _ = s.Scan()
i++
}
}
}
func TestScanner_Peek(t *testing.T) {
s := Scanner{}
s.Init([]byte(`package main
func main(){}
`))
expected := []token.Token{
token.PACKAGE, token.IDENT, token.SEMICOLON,
token.FUNC, token.IDENT, token.LPAREN, token.RPAREN, token.LBRACE, token.RBRACE, token.SEMICOLON,
}
for _, e := range expected {
_, tok, _ := s.Peek()
defect.Equal(t, tok, e)
s.Scan()
}
}
|
mit
|
StefanSinapov/TelerikAcademy
|
16. ASP.NET Web Forms/12. ASP.NET AJAX/02. Web Chat (AJAX)/Account/Manage.aspx.designer.cs
|
1762
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebChat.Account {
public partial class Manage {
/// <summary>
/// successMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder successMessage;
/// <summary>
/// ChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink ChangePassword;
/// <summary>
/// CreatePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink CreatePassword;
/// <summary>
/// PhoneNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label PhoneNumber;
}
}
|
mit
|
zksailor534/react-adminlte-dash
|
__tests__/navbar_navitem.test.js
|
1593
|
/* eslint-env jest */
/* eslint-disable react/jsx-filename-extension */
import React from 'react';
import { ThemeProvider } from 'styled-components';
import renderer from 'react-test-renderer';
import { mount } from 'enzyme';
import red from '../src/styles/skin-red';
import NavItem from '../src/components/Navbar/NavItem';
describe('<NavItem />', () => {
it('renders correctly with default options', () => {
const component = renderer.create(<NavItem />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('renders correctly with theme', () => {
const component = renderer.create(<ThemeProvider theme={red}>
<NavItem />
</ThemeProvider>);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('renders onClick correctly', () => {
const func = () => null;
const wrapper = mount(<NavItem onClick={func} />);
expect(wrapper.find('a').props().onClick).toEqual(func);
});
it('renders link correctly', () => {
const component = renderer.create(<NavItem href="/a/link" />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('renders correctly with icon class', () => {
const component = renderer.create(<NavItem href="/a/link" iconClass="fa fa-github" />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('renders correctly with image', () => {
const component = renderer.create(<NavItem href="/a/link" image="/some/path" />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
mit
|
sanu82624/HealthApp
|
platforms/android/assets/www/appjs/controllers/vendorModule/vendorRequestController.js
|
2494
|
'use strict';
angular.module('cmaManagementApp').controller('vendorRequestController',
function(commonUtility, vendorBusiness, constantLoader, serviceLoader){
var vm = this;
vm.requests = [];
function initialized(){
loadAssignedRequests();
}
function loadAssignedRequests(){
vendorBusiness.getAssignedRequests(commonUtility.getRootScopeProperty(
constantLoader.rootScopeTypes.ID)).then(function(response){
vm.requests = serviceLoader.filter('filter')(response.data.result,
{status: constantLoader.ticketStatusTypes.ASSIGNED});
for(var index=0; index<vm.requests.length; index++){
var statusCss = commonUtility.getFilterArray(
commonUtility.getJsonFromString(constantLoader.defaultValues.TCK_STATUSES),
{"code": vm.requests[index].status});
if(statusCss.length > 0){
vm.requests[index].statusTheme = statusCss[0].color;
}
}
}, function(error){
commonUtility.showAlert(error.data.statusText);
});
}
vm.onTicketStatusClick = function(state, assignmentId, vendId){
var status = ((state > 0) ?
constantLoader.ticketStatusTypes.ACCEPTED :
constantLoader.ticketStatusTypes.DECLINED);
vendorBusiness.updateTicketStatusByVendor(status,
assignmentId, vendId).then(function(response){
if(response.data.success){
commonUtility.showAlert(response.data.statusText,
constantLoader.alertTypes.SUCCESS);
loadAssignedRequests();
} else{
commonUtility.showAlert(response.data.statusText);
}
}, function(error){
commonUtility.showAlert(error.data.statusText);
});
};
vm.onTicketDetailsClick = function(assignmentId){
commonUtility.setRootScopeProperty(constantLoader.rootScopeTypes.ASSN_ID,
assignmentId);
commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_ASSN_DTLS);
};
vm.onBackClick = function(){
commonUtility.redirectTo(constantLoader.routeTypes.VENDOR_HOME);
};
initialized();
}
);
|
mit
|
safris-src/org
|
libx4j/xsb/compiler/src/main/java/org/libx4j/xsb/compiler/processor/model/element/HasPropertyModel.java
|
1505
|
/* Copyright (c) 2008 lib4j
*
* 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.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.libx4j.xsb.compiler.processor.model.element;
import org.libx4j.xsb.compiler.processor.model.Model;
import org.libx4j.xsb.compiler.processor.model.NamedModel;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public final class HasPropertyModel extends NamedModel {
private String value = null;
protected HasPropertyModel(final Node node, final Model parent) {
super(node, parent);
final NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Node attribute = attributes.item(i);
if ("value".equals(attribute.getLocalName()))
value = attribute.getNodeValue();
}
}
public final String getValue() {
return value;
}
}
|
mit
|
Coregraph/Ayllu
|
JigSaw - AYPUY - CS/Ayllu_V0.1/src/co/edu/javeriana/ayllu/agents/sessionmanageragent/SMA_ReceiveCARequestGuard.java
|
6281
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.javeriana.ayllu.agents.sessionmanageragent;
import BESA.Kernel.Agent.Event.DataBESA;
import BESA.Kernel.Agent.Event.EventBESA;
import BESA.Kernel.Agent.GuardBESA;
import BESA.Kernel.System.Directory.AgHandlerBESA;
import BESA.Log.ReportBESA;
import co.edu.javeriana.ayllu.agents.interfaceagentagent.IA_ReceiveSMRequestGuard;
import co.edu.javeriana.ayllu.agents.representativeagent.RA_ReceiveSMQuestionGuard;
import co.edu.javeriana.ayllu.data.Ayllu_AwarenessMessageRequestData;
import co.edu.javeriana.ayllu.data.Ayllu_CoopServCreationMessage;
import co.edu.javeriana.ayllu.data.Ayllu_Data_Message;
import co.edu.javeriana.ayllu.data.Ayllu_EventTypes;
import co.edu.javeriana.ayllu.data.Ayllu_NumberOfStudensAwarenessData;
import co.edu.javeriana.ayllu.data.Ayllu_WallMessageData;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* GUard that receives a request from a CA
* @author AYLLU
*/
public class SMA_ReceiveCARequestGuard extends GuardBESA {
@Override
public void funcExecGuard(EventBESA ebesa) {
try {
handleCARequest(ebesa.getData());
} catch (Exception ex) {
ReportBESA.error("[" + this.getClass().getName() + ":funcExecGuard]->" + ex.toString());
}
}
/**
* Handles the request of a CA, if it is a Question it rill redirect it to a RA, is it is a message TODO _SMA and if if its a display event it will redirect it to the Active IAs
* @param theData
*/
public void handleCARequest(DataBESA aData) {
SessionManagerAgentState myState = (SessionManagerAgentState) this.getAgent().getState();
if (aData instanceof Ayllu_Data_Message) {
Ayllu_Data_Message theData = (Ayllu_Data_Message) aData;
switch (theData.getEventType()) {
case MESSAGE:
handleCAMessage(theData, myState);
break;
case QUEST_REQUEST:
handleCAQuestion(theData, myState);
break;
case DISPLAY:
handleDisplayEvent(theData, myState);
break;
case DISPLAYESPECIFIC:
handleDisplayEspecificEvent(theData, myState);
break;
}
} else if (aData instanceof Ayllu_WallMessageData) {
Ayllu_WallMessageData theData = (Ayllu_WallMessageData) aData;
handleDisplayEvent(theData, myState);
} else if (aData instanceof Ayllu_CoopServCreationMessage) {
} else if (aData instanceof Ayllu_NumberOfStudensAwarenessData) {
Ayllu_NumberOfStudensAwarenessData theData = (Ayllu_NumberOfStudensAwarenessData) aData;
handleNumberStudentsUpdate(myState, theData);
} else if (aData instanceof Ayllu_AwarenessMessageRequestData) {
Ayllu_AwarenessMessageRequestData theData = (Ayllu_AwarenessMessageRequestData) aData;
// myState.addAwarenessMessage(theData.getCooperativeServiceId(),theData.getReqForm());
reportToIa(myState, aData);
}
}
private void handleNumberStudentsUpdate(SessionManagerAgentState myState, Ayllu_NumberOfStudensAwarenessData theData) {
// myState.updateNumberOfStudents(theData.getCoopservId(), theData.getNumstudents());
reportToIa(myState, theData);
}
private void handleCAQuestion(Ayllu_Data_Message theData, SessionManagerAgentState state) {
ReportBESA.info("RECIBI PETICION DE SERVICIO y SOY: " + this.getAgent().getAlias());
try {
Ayllu_Data_Message newData = new Ayllu_Data_Message(Ayllu_EventTypes.QUEST_REQUEST, this.getAgent().getAdmLocal().getHandlerByAid(this.getAgent().getAid()), theData.getMessage());
newData.setGuardToActivate(theData.getGuardToActivate());
newData.setReceiverHandler(theData.getReceiverHandler());
state.addSender(newData.getMessageId(), theData.getSenderHandler());
EventBESA event = new EventBESA(RA_ReceiveSMQuestionGuard.class.getName(), newData);
state.getRepresentativeAgentHandler().sendEvent(event);
} catch (Exception ex) {
ReportBESA.error("[" + this.getClass().getName() + "] => Error calling the RA" + ex.toString());
}
}
private void handleCAMessage(Ayllu_Data_Message theData, SessionManagerAgentState state) {
EventBESA event = new EventBESA(RA_ReceiveSMQuestionGuard.class.getName(), theData);
try {
state.getRepresentativeAgentHandler().sendEvent(event);
} catch (Exception ex) {
ReportBESA.error("[" + this.getClass().getName() + "] => Error calling the RA" + ex.toString());
}
}
private void handleDisplayEvent(DataBESA theData, SessionManagerAgentState state) {
// state.addMessageToWall(theData);
reportToIa(state, theData);
}
private void handleDisplayEspecificEvent(DataBESA theData, SessionManagerAgentState state) {
// state.addMessageToWall(theData);
reportToOneIa(state, theData);
}
private void reportToIa(SessionManagerAgentState myState, DataBESA regmsj) {
List<AgHandlerBESA> iaList = myState.getInterfaceAgentsID();
for (AgHandlerBESA agHandler : iaList) {
EventBESA iaEvent = new EventBESA(IA_ReceiveSMRequestGuard.class.getName(), regmsj);
try {
agHandler.sendEvent(iaEvent);
} catch (Exception ex) {
Logger.getLogger(SMA_ReceiveCARequestGuard.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void reportToOneIa(SessionManagerAgentState myState, DataBESA regmsj) {
Ayllu_Data_Message data = (Ayllu_Data_Message) regmsj;
AgHandlerBESA agHandler = data.getReceiverHandler();
EventBESA iaEvent = new EventBESA(IA_ReceiveSMRequestGuard.class.getName(), regmsj);
try {
agHandler.sendEvent(iaEvent);
} catch (Exception ex) {
Logger.getLogger(SMA_ReceiveCARequestGuard.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
mit
|
bus-detective/bus-detective
|
app/serializers/agency_serializer.rb
|
125
|
class AgencySerializer < ApplicationSerializer
attributes :id, :remote_id, :name, :url, :fare_url, :phone, :timezone
end
|
mit
|
shiftkey/SignalR
|
SignalR/Transports/ITransportHeartBeat.cs
|
210
|
namespace SignalR.Transports
{
public interface ITransportHeartBeat
{
void AddConnection(ITrackingConnection connection);
void MarkConnection(ITrackingConnection connection);
}
}
|
mit
|
jeraldfeller/jbenterprises
|
google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201705/o/RelatedToQuerySearchParameter.php
|
910
|
<?php
namespace Google\AdsApi\AdWords\v201705\o;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class RelatedToQuerySearchParameter extends \Google\AdsApi\AdWords\v201705\o\SearchParameter
{
/**
* @var string[] $queries
*/
protected $queries = null;
/**
* @param string $SearchParameterType
* @param string[] $queries
*/
public function __construct($SearchParameterType = null, array $queries = null)
{
parent::__construct($SearchParameterType);
$this->queries = $queries;
}
/**
* @return string[]
*/
public function getQueries()
{
return $this->queries;
}
/**
* @param string[] $queries
* @return \Google\AdsApi\AdWords\v201705\o\RelatedToQuerySearchParameter
*/
public function setQueries(array $queries)
{
$this->queries = $queries;
return $this;
}
}
|
mit
|
dsherret/type-info-ts
|
src/binders/ts/base/TsDefaultExpressionedBinder.ts
|
528
|
import {TsNode} from "./../../../compiler";
import {TsFactory} from "./../../../factories";
import {DefaultExpressionedBinder} from "./../../base";
export class TsDefaultExpressionedBinder extends DefaultExpressionedBinder {
constructor(private readonly factory: TsFactory, private readonly node: TsNode) {
super();
}
getDefaultExpression() {
const tsExpression = this.node.getDefaultExpression();
return (tsExpression == null) ? null : this.factory.getExpression(tsExpression);
}
}
|
mit
|
cyeagy/dorm
|
src/main/java/io/github/yeagy/bss/ConnectionSupplier.java
|
351
|
package io.github.yeagy.bss;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@FunctionalInterface
public interface ConnectionSupplier {
Connection get() throws SQLException;
default ConnectionSupplier from(DataSource dataSource) throws SQLException {
return dataSource::getConnection;
}
}
|
mit
|
technoweenie/model_stubbing
|
lib/model_stubbing.rb
|
3480
|
require 'model_stubbing/extensions'
require 'model_stubbing/definition'
require 'model_stubbing/model'
require 'model_stubbing/stub'
module ModelStubbing
# Gets a hash of all current definitions.
def self.definitions() @definitions ||= {} end
# stores {stub => record_id} so that identical stubs keep the same ID
def self.record_ids() @record_ids ||= {} end
# stores {record_id => instantiated stubs}. reset after each spec
def self.records() @records ||= {} end
# Creates a new ModelStubbing::Definition. If called from within a class,
# it is automatically setup (See Definition#setup_on).
#
# Creates or updates a definition going by the given name as a key. If
# no name is given, it defaults to the current class or :default. Multiple
# #define_models calls with the same name will modify the definition.
#
# By default, only validations are run before inserting records. You can
# configure this with the :validate or :callbacks options.
#
# Options:
# * :copy - set to false if you don't want this definition to be a dup of
# the :default definition
# * :insert - set to false if you don't want to insert this definition
# into the database.
# * :validate - set to false if you don't want to validate model data, or run callbacks
# * :callbacks - set to true if you want to run callbacks.
def self.define_models(name = nil, options = {}, &block)
if name.is_a? Hash
options = name
name = nil
end
name ||= is_a?(Class) ? self : :default
base_name = options[:copy] || :default
base = name == base_name ? nil : ModelStubbing.definitions[base_name]
defn = ModelStubbing.definitions[name] ||= (base && options[:copy] != false) ? base.dup : ModelStubbing::Definition.new(name)
options = base.options.merge(options) if base
defn.setup_on options[:target] || self, options, &block
end
# Included into the base TestCase and Spec Example classes
module Methods
# By default, any model stubbing definitions specified inside of a spec or test with a block is a COPY of a named definition.
# Therefore, reopening a model stubbing definition inside of a spec will not update the definition for other specs. Whew!
def define_models(base_name = :default, options = {}, &block)
case base_name
# if options are given first, assume that base_name is default
when Hash
options = base_name
base_name = self
when nil
else
unless options[:copy] || block.nil?
options[:copy] = base_name
base_name = self
end
end
ModelStubbing.define_models(base_name, options.update(:target => self), &block)
end
end
protected
@@mock_framework = nil
def self.stub_current_time_with(time)
guess_mock_framework!
case @@mock_framework
when :rspec then Time.stub!(:now).and_return(time)
when :mocha then Time.stubs(:now).returns(time)
end
end
def self.guess_mock_framework!
if @@mock_framework.nil?
@@mock_framework =
if Time.respond_to?(:stub!)
:rspec
elsif Time.respond_to?(:stubs)
:mocha
else
raise "Unknown mock framework."
end
end
end
end
Test::Unit::TestCase.extend ModelStubbing::Methods
Spec::Example::ExampleGroup.extend ModelStubbing::Methods if defined? Spec::Example::ExampleGroup
|
mit
|
pennersr/django-allauth
|
allauth/socialaccount/providers/oauth2/views.py
|
5634
|
from __future__ import absolute_import
from datetime import timedelta
from requests import RequestException
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
from allauth.exceptions import ImmediateHttpResponse
from allauth.socialaccount import providers
from allauth.socialaccount.helpers import (
complete_social_login,
render_authentication_error,
)
from allauth.socialaccount.models import SocialLogin, SocialToken
from allauth.socialaccount.providers.base import ProviderException
from allauth.socialaccount.providers.base.constants import (
AuthAction,
AuthError,
)
from allauth.socialaccount.providers.base.mixins import OAuthLoginMixin
from allauth.socialaccount.providers.oauth2.client import (
OAuth2Client,
OAuth2Error,
)
from allauth.utils import build_absolute_uri, get_request_param
class OAuth2Adapter(object):
expires_in_key = "expires_in"
client_class = OAuth2Client
supports_state = True
redirect_uri_protocol = None
access_token_method = "POST"
login_cancelled_error = "access_denied"
scope_delimiter = " "
basic_auth = False
headers = None
def __init__(self, request):
self.request = request
def get_provider(self):
return providers.registry.by_id(self.provider_id, self.request)
def complete_login(self, request, app, access_token, **kwargs):
"""
Returns a SocialLogin instance
"""
raise NotImplementedError
def get_callback_url(self, request, app):
callback_url = reverse(self.provider_id + "_callback")
protocol = self.redirect_uri_protocol
return build_absolute_uri(request, callback_url, protocol)
def parse_token(self, data):
token = SocialToken(token=data["access_token"])
token.token_secret = data.get("refresh_token", "")
expires_in = data.get(self.expires_in_key, None)
if expires_in:
token.expires_at = timezone.now() + timedelta(seconds=int(expires_in))
return token
def get_access_token_data(self, request, app, client):
code = get_request_param(self.request, "code")
return client.get_access_token(code)
class OAuth2View(object):
@classmethod
def adapter_view(cls, adapter):
def view(request, *args, **kwargs):
self = cls()
self.request = request
self.adapter = adapter(request)
try:
return self.dispatch(request, *args, **kwargs)
except ImmediateHttpResponse as e:
return e.response
return view
def get_client(self, request, app):
callback_url = self.adapter.get_callback_url(request, app)
provider = self.adapter.get_provider()
scope = provider.get_scope(request)
client = self.adapter.client_class(
self.request,
app.client_id,
app.secret,
self.adapter.access_token_method,
self.adapter.access_token_url,
callback_url,
scope,
scope_delimiter=self.adapter.scope_delimiter,
headers=self.adapter.headers,
basic_auth=self.adapter.basic_auth,
)
return client
class OAuth2LoginView(OAuthLoginMixin, OAuth2View):
def login(self, request, *args, **kwargs):
provider = self.adapter.get_provider()
app = provider.get_app(self.request)
client = self.get_client(request, app)
action = request.GET.get("action", AuthAction.AUTHENTICATE)
auth_url = self.adapter.authorize_url
auth_params = provider.get_auth_params(request, action)
client.state = SocialLogin.stash_state(request)
try:
return HttpResponseRedirect(client.get_redirect_url(auth_url, auth_params))
except OAuth2Error as e:
return render_authentication_error(request, provider.id, exception=e)
class OAuth2CallbackView(OAuth2View):
def dispatch(self, request, *args, **kwargs):
if "error" in request.GET or "code" not in request.GET:
# Distinguish cancel from error
auth_error = request.GET.get("error", None)
if auth_error == self.adapter.login_cancelled_error:
error = AuthError.CANCELLED
else:
error = AuthError.UNKNOWN
return render_authentication_error(
request, self.adapter.provider_id, error=error
)
app = self.adapter.get_provider().get_app(self.request)
client = self.get_client(self.request, app)
try:
access_token = self.adapter.get_access_token_data(request, app, client)
token = self.adapter.parse_token(access_token)
token.app = app
login = self.adapter.complete_login(
request, app, token, response=access_token
)
login.token = token
if self.adapter.supports_state:
login.state = SocialLogin.verify_and_unstash_state(
request, get_request_param(request, "state")
)
else:
login.state = SocialLogin.unstash_state(request)
return complete_social_login(request, login)
except (
PermissionDenied,
OAuth2Error,
RequestException,
ProviderException,
) as e:
return render_authentication_error(
request, self.adapter.provider_id, exception=e
)
|
mit
|
plotly/plotly.py
|
packages/python/plotly/plotly/graph_objs/scattermapbox/marker/colorbar/title/_font.py
|
8624
|
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattermapbox.marker.colorbar.title"
_path_str = "scattermapbox.marker.colorbar.title.font"
_valid_props = {"color", "family", "size"}
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
# family
# ------
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
# size
# ----
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
"""
def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Font object
Sets this color bar's title font. Note that the title's font
used to be set by the now deprecated `titlefont` attribute.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattermapbox.
marker.colorbar.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.scattermapbox.marker.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattermapbox.marker.colorbar.title.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
|
mit
|
marbemac/whoot-symfony2
|
web/slir/pel-0.9.2/src/PelIfd.php
|
38023
|
<?php
/* PEL: PHP Exif Library. A library with support for reading and
* writing all Exif headers in JPEG and TIFF images using PHP.
*
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Martin Geisler.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program in the file COPYING; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/* $Id$ */
/**
* Classes for dealing with Exif IFDs.
*
* @author Martin Geisler <mgeisler@users.sourceforge.net>
* @version $Revision$
* @date $Date$
* @license http://www.gnu.org/licenses/gpl.html GNU General Public
* License (GPL)
* @package PEL
*/
/**#@+ Required class definitions. */
require_once('PelEntryUndefined.php');
require_once('PelEntryRational.php');
require_once('PelDataWindow.php');
require_once('PelEntryAscii.php');
require_once('PelEntryShort.php');
require_once('PelEntryByte.php');
require_once('PelEntryLong.php');
require_once('PelException.php');
require_once('PelFormat.php');
require_once('PelEntry.php');
require_once('PelTag.php');
require_once('Pel.php');
/**#@-*/
/**
* Exception indicating a general problem with the IFD.
*
* @author Martin Geisler <mgeisler@users.sourceforge.net>
* @package PEL
* @subpackage Exception
*/
class PelIfdException extends PelException {}
/**
* Class representing an Image File Directory (IFD).
*
* {@link PelTiff TIFF data} is structured as a number of Image File
* Directories, IFDs for short. Each IFD contains a number of {@link
* PelEntry entries}, some data and finally a link to the next IFD.
*
* @author Martin Geisler <mgeisler@users.sourceforge.net>
* @package PEL
*/
class PelIfd implements IteratorAggregate, ArrayAccess {
/**
* Main image IFD.
*
* Pass this to the constructor when creating an IFD which will be
* the IFD of the main image.
*/
const IFD0 = 0;
/**
* Thumbnail image IFD.
*
* Pass this to the constructor when creating an IFD which will be
* the IFD of the thumbnail image.
*/
const IFD1 = 1;
/**
* Exif IFD.
*
* Pass this to the constructor when creating an IFD which will be
* the Exif sub-IFD.
*/
const EXIF = 2;
/**
* GPS IFD.
*
* Pass this to the constructor when creating an IFD which will be
* the GPS sub-IFD.
*/
const GPS = 3;
/**
* Interoperability IFD.
*
* Pass this to the constructor when creating an IFD which will be
* the interoperability sub-IFD.
*/
const INTEROPERABILITY = 4;
/**
* The entries held by this directory.
*
* Each tag in the directory is represented by a {@link PelEntry}
* object in this array.
*
* @var array
*/
private $entries = array();
/**
* The type of this directory.
*
* Initialized in the constructor. Must be one of {@link IFD0},
* {@link IFD1}, {@link EXIF}, {@link GPS}, or {@link
* INTEROPERABILITY}.
*
* @var int
*/
private $type;
/**
* The next directory.
*
* This will be initialized in the constructor, or be left as null
* if this is the last directory.
*
* @var PelIfd
*/
private $next = null;
/**
* Sub-directories pointed to by this directory.
*
* This will be an array of ({@link PelTag}, {@link PelIfd}) pairs.
*
* @var array
*/
private $sub = array();
/**
* The thumbnail data.
*
* This will be initialized in the constructor, or be left as null
* if there are no thumbnail as part of this directory.
*
* @var PelDataWindow
*/
private $thumb_data = null;
// TODO: use this format to choose between the
// JPEG_INTERCHANGE_FORMAT and STRIP_OFFSETS tags.
// private $thumb_format;
/**
* Construct a new Image File Directory (IFD).
*
* The IFD will be empty, use the {@link addEntry()} method to add
* an {@link PelEntry}. Use the {@link setNext()} method to link
* this IFD to another.
*
* @param int type the type of this IFD. Must be one of {@link
* IFD0}, {@link IFD1}, {@link EXIF}, {@link GPS}, or {@link
* INTEROPERABILITY}. An {@link PelIfdException} will be thrown
* otherwise.
*/
function __construct($type) {
if ($type != PelIfd::IFD0 && $type != PelIfd::IFD1 &&
$type != PelIfd::EXIF && $type != PelIfd::GPS &&
$type != PelIfd::INTEROPERABILITY)
throw new PelIfdException('Unknown IFD type: %d', $type);
$this->type = $type;
}
/**
* Load data into a Image File Directory (IFD).
*
* @param PelDataWindow the data window that will provide the data.
*
* @param int the offset within the window where the directory will
* be found.
*/
function load(PelDataWindow $d, $offset) {
$thumb_offset = 0;
$thumb_length = 0;
Pel::debug('Constructing IFD at offset %d from %d bytes...',
$offset, $d->getSize());
/* Read the number of entries */
$n = $d->getShort($offset);
Pel::debug('Loading %d entries...', $n);
$offset += 2;
/* Check if we have enough data. */
if ($offset + 12 * $n > $d->getSize()) {
$n = floor(($offset - $d->getSize()) / 12);
Pel::maybeThrow(new PelIfdException('Adjusted to: %d.', $n));
}
for ($i = 0; $i < $n; $i++) {
// TODO: increment window start instead of using offsets.
$tag = $d->getShort($offset + 12 * $i);
Pel::debug('Loading entry with tag 0x%04X: %s (%d of %d)...',
$tag, PelTag::getName($this->type, $tag), $i + 1, $n);
switch ($tag) {
case PelTag::EXIF_IFD_POINTER:
case PelTag::GPS_INFO_IFD_POINTER:
case PelTag::INTEROPERABILITY_IFD_POINTER:
$o = $d->getLong($offset + 12 * $i + 8);
Pel::debug('Found sub IFD at offset %d', $o);
/* Map tag to IFD type. */
if ($tag == PelTag::EXIF_IFD_POINTER)
$type = PelIfd::EXIF;
elseif ($tag == PelTag::GPS_INFO_IFD_POINTER)
$type = PelIfd::GPS;
elseif ($tag == PelTag::INTEROPERABILITY_IFD_POINTER)
$type = PelIfd::INTEROPERABILITY;
$this->sub[$type] = new PelIfd($type);
$this->sub[$type]->load($d, $o);
break;
case PelTag::JPEG_INTERCHANGE_FORMAT:
$thumb_offset = $d->getLong($offset + 12 * $i + 8);
$this->safeSetThumbnail($d, $thumb_offset, $thumb_length);
break;
case PelTag::JPEG_INTERCHANGE_FORMAT_LENGTH:
$thumb_length = $d->getLong($offset + 12 * $i + 8);
$this->safeSetThumbnail($d, $thumb_offset, $thumb_length);
break;
default:
$format = $d->getShort($offset + 12 * $i + 2);
$components = $d->getLong($offset + 12 * $i + 4);
/* The data size. If bigger than 4 bytes, the actual data is
* not in the entry but somewhere else, with the offset stored
* in the entry.
*/
$s = PelFormat::getSize($format) * $components;
if ($s > 0) {
$doff = $offset + 12 * $i + 8;
if ($s > 4)
$doff = $d->getLong($doff);
$data = $d->getClone($doff, $s);
} else {
$data = new PelDataWindow();
}
try {
$entry = $this->newEntryFromData($tag, $format, $components, $data);
$this->addEntry($entry);
} catch (PelException $e) {
/* Throw the exception when running in strict mode, store
* otherwise. */
Pel::maybeThrow($e);
}
/* The format of the thumbnail is stored in this tag. */
// TODO: handle TIFF thumbnail.
// if ($tag == PelTag::COMPRESSION) {
// $this->thumb_format = $data->getShort();
// }
break;
}
}
/* Offset to next IFD */
$o = $d->getLong($offset + 12 * $n);
Pel::debug('Current offset is %d, link at %d points to %d.',
$offset, $offset + 12 * $n, $o);
if ($o > 0) {
/* Sanity check: we need 6 bytes */
if ($o > $d->getSize() - 6) {
Pel::maybeThrow(new PelIfdException('Bogus offset to next IFD: ' .
'%d > %d!',
$o, $d->getSize() - 6));
} else {
if ($this->type == PelIfd::IFD1) // IFD1 shouldn't link further...
Pel::maybeThrow(new PelIfdException('IFD1 links to another IFD!'));
$this->next = new PelIfd(PelIfd::IFD1);
$this->next->load($d, $o);
}
} else {
Pel::debug('Last IFD.');
}
}
/**
* Make a new entry from a bunch of bytes.
*
* This method will create the proper subclass of {@link PelEntry}
* corresponding to the {@link PelTag} and {@link PelFormat} given.
* The entry will be initialized with the data given.
*
* Please note that the data you pass to this method should come
* from an image, that is, it should be raw bytes. If instead you
* want to create an entry for holding, say, an short integer, then
* create a {@link PelEntryShort} object directly and load the data
* into it.
*
* A {@link PelUnexpectedFormatException} is thrown if a mismatch is
* discovered between the tag and format, and likewise a {@link
* PelWrongComponentCountException} is thrown if the number of
* components does not match the requirements of the tag. The
* requirements for a given tag (if any) can be found in the
* documentation for {@link PelTag}.
*
* @param PelTag the tag of the entry.
*
* @param PelFormat the format of the entry.
*
* @param int the components in the entry.
*
* @param PelDataWindow the data which will be used to construct the
* entry.
*
* @return PelEntry a newly created entry, holding the data given.
*/
function newEntryFromData($tag, $format, $components, PelDataWindow $data) {
/* First handle tags for which we have a specific PelEntryXXX
* class. */
switch ($this->type) {
case self::IFD0:
case self::IFD1:
case self::EXIF:
case self::INTEROPERABILITY:
switch ($tag) {
case PelTag::DATE_TIME:
case PelTag::DATE_TIME_ORIGINAL:
case PelTag::DATE_TIME_DIGITIZED:
if ($format != PelFormat::ASCII)
throw new PelUnexpectedFormatException($this->type, $tag, $format,
PelFormat::ASCII);
if ($components != 20)
throw new PelWrongComponentCountException($this->type, $tag, $components, 20);
// TODO: handle timezones.
return new PelEntryTime($tag, $data->getBytes(0, -1), PelEntryTime::EXIF_STRING);
case PelTag::COPYRIGHT:
if ($format != PelFormat::ASCII)
throw new PelUnexpectedFormatException($this->type, $tag, $format,
PelFormat::ASCII);
$v = explode("\0", trim($data->getBytes(), ' '));
return new PelEntryCopyright($v[0], $v[1]);
case PelTag::EXIF_VERSION:
case PelTag::FLASH_PIX_VERSION:
case PelTag::INTEROPERABILITY_VERSION:
if ($format != PelFormat::UNDEFINED)
throw new PelUnexpectedFormatException($this->type, $tag, $format,
PelFormat::UNDEFINED);
return new PelEntryVersion($tag, $data->getBytes() / 100);
case PelTag::USER_COMMENT:
if ($format != PelFormat::UNDEFINED)
throw new PelUnexpectedFormatException($this->type, $tag, $format,
PelFormat::UNDEFINED);
if ($data->getSize() < 8) {
return new PelEntryUserComment();
} else {
return new PelEntryUserComment($data->getBytes(8),
rtrim($data->getBytes(0, 8)));
}
case PelTag::XP_TITLE:
case PelTag::XP_COMMENT:
case PelTag::XP_AUTHOR:
case PelTag::XP_KEYWORDS:
case PelTag::XP_SUBJECT:
if ($format != PelFormat::BYTE)
throw new PelUnexpectedFormatException($this->type, $tag, $format,
PelFormat::BYTE);
$v = '';
for ($i = 0; $i < $components; $i++) {
$b = $data->getByte($i);
/* Convert the byte to a character if it is non-null ---
* information about the character encoding of these entries
* would be very nice to have! So far my tests have shown
* that characters in the Latin-1 character set are stored in
* a single byte followed by a NULL byte. */
if ($b != 0)
$v .= chr($b);
}
return new PelEntryWindowsString($tag, $v);
}
case self::GPS:
default:
/* Then handle the basic formats. */
switch ($format) {
case PelFormat::BYTE:
$v = new PelEntryByte($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getByte($i));
return $v;
case PelFormat::SBYTE:
$v = new PelEntrySByte($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getSByte($i));
return $v;
case PelFormat::ASCII:
return new PelEntryAscii($tag, $data->getBytes(0, -1));
case PelFormat::SHORT:
$v = new PelEntryShort($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getShort($i*2));
return $v;
case PelFormat::SSHORT:
$v = new PelEntrySShort($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getSShort($i*2));
return $v;
case PelFormat::LONG:
$v = new PelEntryLong($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getLong($i*4));
return $v;
case PelFormat::SLONG:
$v = new PelEntrySLong($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getSLong($i*4));
return $v;
case PelFormat::RATIONAL:
$v = new PelEntryRational($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getRational($i*8));
return $v;
case PelFormat::SRATIONAL:
$v = new PelEntrySRational($tag);
for ($i = 0; $i < $components; $i++)
$v->addNumber($data->getSRational($i*8));
return $v;
case PelFormat::UNDEFINED:
return new PelEntryUndefined($tag, $data->getBytes());
default:
throw new PelException('Unsupported format: %s',
PelFormat::getName($format));
}
}
}
/**
* Extract thumbnail data safely.
*
* It is safe to call this method repeatedly with either the offset
* or the length set to zero, since it requires both of these
* arguments to be positive before the thumbnail is extracted.
*
* When both parameters are set it will check the length against the
* available data and adjust as necessary. Only then is the
* thumbnail data loaded.
*
* @param PelDataWindow the data from which the thumbnail will be
* extracted.
*
* @param int the offset into the data.
*
* @param int the length of the thumbnail.
*/
private function safeSetThumbnail(PelDataWindow $d, $offset, $length) {
/* Load the thumbnail if both the offset and the length is
* available. */
if ($offset > 0 && $length > 0) {
/* Some images have a broken length, so we try to carefully
* check the length before we store the thumbnail. */
if ($offset + $length > $d->getSize()) {
Pel::maybeThrow(new PelIfdException('Thumbnail length %d bytes ' .
'adjusted to %d bytes.',
$length,
$d->getSize() - $offset));
$length = $d->getSize() - $offset;
}
/* Now set the thumbnail normally. */
$this->setThumbnail($d->getClone($offset, $length));
}
}
/**
* Set thumbnail data.
*
* Use this to embed an arbitrary JPEG image within this IFD. The
* data will be checked to ensure that it has a proper {@link
* PelJpegMarker::EOI} at the end. If not, then the length is
* adjusted until one if found. An {@link PelIfdException} might be
* thrown (depending on {@link Pel::$strict}) this case.
*
* @param PelDataWindow the thumbnail data.
*/
function setThumbnail(PelDataWindow $d) {
$size = $d->getSize();
/* Now move backwards until we find the EOI JPEG marker. */
while ($d->getByte($size - 2) != 0xFF ||
$d->getByte($size - 1) != PelJpegMarker::EOI) {
$size--;
}
if ($size != $d->getSize())
Pel::maybeThrow(new PelIfdException('Decrementing thumbnail size ' .
'to %d bytes', $size));
$this->thumb_data = $d->getClone(0, $size);
}
/**
* Get the type of this directory.
*
* @return int of {@link PelIfd::IFD0}, {@link PelIfd::IFD1}, {@link
* PelIfd::EXIF}, {@link PelIfd::GPS}, or {@link
* PelIfd::INTEROPERABILITY}.
*/
function getType() {
return $this->type;
}
/**
* Is a given tag valid for this IFD?
*
* Different types of IFDs can contain different kinds of tags ---
* the {@link IFD0} type, for example, cannot contain a {@link
* PelTag::GPS_LONGITUDE} tag.
*
* A special exception is tags with values above 0xF000. They are
* treated as private tags and will be allowed everywhere (use this
* for testing or for implementing your own types of tags).
*
* @param PelTag the tag.
*
* @return boolean true if the tag is considered valid in this IFD,
* false otherwise.
*
* @see getValidTags()
*/
function isValidTag($tag) {
return $tag > 0xF000 || in_array($tag, $this->getValidTags());
}
/**
* Returns a list of valid tags for this IFD.
*
* @return array an array of {@link PelTag}s which are valid for
* this IFD.
*/
function getValidTags() {
switch ($this->type) {
case PelIfd::IFD0:
case PelIfd::IFD1:
return array(PelTag::IMAGE_WIDTH,
PelTag::IMAGE_LENGTH,
PelTag::BITS_PER_SAMPLE,
PelTag::COMPRESSION,
PelTag::PHOTOMETRIC_INTERPRETATION,
PelTag::IMAGE_DESCRIPTION,
PelTag::MAKE,
PelTag::MODEL,
PelTag::STRIP_OFFSETS,
PelTag::ORIENTATION,
PelTag::SAMPLES_PER_PIXEL,
PelTag::ROWS_PER_STRIP,
PelTag::STRIP_BYTE_COUNTS,
PelTag::X_RESOLUTION,
PelTag::Y_RESOLUTION,
PelTag::PLANAR_CONFIGURATION,
PelTag::RESOLUTION_UNIT,
PelTag::TRANSFER_FUNCTION,
PelTag::SOFTWARE,
PelTag::DATE_TIME,
PelTag::ARTIST,
PelTag::WHITE_POINT,
PelTag::PRIMARY_CHROMATICITIES,
PelTag::JPEG_INTERCHANGE_FORMAT,
PelTag::JPEG_INTERCHANGE_FORMAT_LENGTH,
PelTag::YCBCR_COEFFICIENTS,
PelTag::YCBCR_SUB_SAMPLING,
PelTag::YCBCR_POSITIONING,
PelTag::REFERENCE_BLACK_WHITE,
PelTag::COPYRIGHT,
PelTag::EXIF_IFD_POINTER,
PelTag::GPS_INFO_IFD_POINTER,
PelTag::PRINT_IM,
PelTag::XP_TITLE,
PelTag::XP_COMMENT,
PelTag::XP_AUTHOR,
PelTag::XP_KEYWORDS,
PelTag::XP_SUBJECT);
case PelIfd::EXIF:
return array(PelTag::EXPOSURE_TIME,
PelTag::FNUMBER,
PelTag::EXPOSURE_PROGRAM,
PelTag::SPECTRAL_SENSITIVITY,
PelTag::ISO_SPEED_RATINGS,
PelTag::OECF,
PelTag::EXIF_VERSION,
PelTag::DATE_TIME_ORIGINAL,
PelTag::DATE_TIME_DIGITIZED,
PelTag::COMPONENTS_CONFIGURATION,
PelTag::COMPRESSED_BITS_PER_PIXEL,
PelTag::SHUTTER_SPEED_VALUE,
PelTag::APERTURE_VALUE,
PelTag::BRIGHTNESS_VALUE,
PelTag::EXPOSURE_BIAS_VALUE,
PelTag::MAX_APERTURE_VALUE,
PelTag::SUBJECT_DISTANCE,
PelTag::METERING_MODE,
PelTag::LIGHT_SOURCE,
PelTag::FLASH,
PelTag::FOCAL_LENGTH,
PelTag::MAKER_NOTE,
PelTag::USER_COMMENT,
PelTag::SUB_SEC_TIME,
PelTag::SUB_SEC_TIME_ORIGINAL,
PelTag::SUB_SEC_TIME_DIGITIZED,
PelTag::FLASH_PIX_VERSION,
PelTag::COLOR_SPACE,
PelTag::PIXEL_X_DIMENSION,
PelTag::PIXEL_Y_DIMENSION,
PelTag::RELATED_SOUND_FILE,
PelTag::FLASH_ENERGY,
PelTag::SPATIAL_FREQUENCY_RESPONSE,
PelTag::FOCAL_PLANE_X_RESOLUTION,
PelTag::FOCAL_PLANE_Y_RESOLUTION,
PelTag::FOCAL_PLANE_RESOLUTION_UNIT,
PelTag::SUBJECT_LOCATION,
PelTag::EXPOSURE_INDEX,
PelTag::SENSING_METHOD,
PelTag::FILE_SOURCE,
PelTag::SCENE_TYPE,
PelTag::CFA_PATTERN,
PelTag::CUSTOM_RENDERED,
PelTag::EXPOSURE_MODE,
PelTag::WHITE_BALANCE,
PelTag::DIGITAL_ZOOM_RATIO,
PelTag::FOCAL_LENGTH_IN_35MM_FILM,
PelTag::SCENE_CAPTURE_TYPE,
PelTag::GAIN_CONTROL,
PelTag::CONTRAST,
PelTag::SATURATION,
PelTag::SHARPNESS,
PelTag::DEVICE_SETTING_DESCRIPTION,
PelTag::SUBJECT_DISTANCE_RANGE,
PelTag::IMAGE_UNIQUE_ID,
PelTag::INTEROPERABILITY_IFD_POINTER,
PelTag::GAMMA);
case PelIfd::GPS:
return array(PelTag::GPS_VERSION_ID,
PelTag::GPS_LATITUDE_REF,
PelTag::GPS_LATITUDE,
PelTag::GPS_LONGITUDE_REF,
PelTag::GPS_LONGITUDE,
PelTag::GPS_ALTITUDE_REF,
PelTag::GPS_ALTITUDE,
PelTag::GPS_TIME_STAMP,
PelTag::GPS_SATELLITES,
PelTag::GPS_STATUS,
PelTag::GPS_MEASURE_MODE,
PelTag::GPS_DOP,
PelTag::GPS_SPEED_REF,
PelTag::GPS_SPEED,
PelTag::GPS_TRACK_REF,
PelTag::GPS_TRACK,
PelTag::GPS_IMG_DIRECTION_REF,
PelTag::GPS_IMG_DIRECTION,
PelTag::GPS_MAP_DATUM,
PelTag::GPS_DEST_LATITUDE_REF,
PelTag::GPS_DEST_LATITUDE,
PelTag::GPS_DEST_LONGITUDE_REF,
PelTag::GPS_DEST_LONGITUDE,
PelTag::GPS_DEST_BEARING_REF,
PelTag::GPS_DEST_BEARING,
PelTag::GPS_DEST_DISTANCE_REF,
PelTag::GPS_DEST_DISTANCE,
PelTag::GPS_PROCESSING_METHOD,
PelTag::GPS_AREA_INFORMATION,
PelTag::GPS_DATE_STAMP,
PelTag::GPS_DIFFERENTIAL);
case PelIfd::INTEROPERABILITY:
return array(PelTag::INTEROPERABILITY_INDEX,
PelTag::INTEROPERABILITY_VERSION,
PelTag::RELATED_IMAGE_FILE_FORMAT,
PelTag::RELATED_IMAGE_WIDTH,
PelTag::RELATED_IMAGE_LENGTH);
/* TODO: Where do these tags belong?
PelTag::FILL_ORDER,
PelTag::DOCUMENT_NAME,
PelTag::TRANSFER_RANGE,
PelTag::JPEG_PROC,
PelTag::BATTERY_LEVEL,
PelTag::IPTC_NAA,
PelTag::INTER_COLOR_PROFILE,
PelTag::CFA_REPEAT_PATTERN_DIM,
*/
}
}
/**
* Get the name of an IFD type.
*
* @param int one of {@link PelIfd::IFD0}, {@link PelIfd::IFD1},
* {@link PelIfd::EXIF}, {@link PelIfd::GPS}, or {@link
* PelIfd::INTEROPERABILITY}.
*
* @return string the name of type.
*/
static function getTypeName($type) {
switch ($type) {
case self::IFD0:
return '0';
case self::IFD1:
return '1';
case self::EXIF:
return 'Exif';
case self::GPS:
return 'GPS';
case self::INTEROPERABILITY:
return 'Interoperability';
default:
throw new PelIfdException('Unknown IFD type: %d', $type);
}
}
/**
* Get the name of this directory.
*
* @return string the name of this directory.
*/
function getName() {
return $this->getTypeName($this->type);
}
/**
* Adds an entry to the directory.
*
* @param PelEntry the entry that will be added. If the entry is not
* valid in this IFD (as per {@link isValidTag()}) an
* {@link PelInvalidDataException} is thrown.
*
* @todo The entry will be identified with its tag, so each
* directory can only contain one entry with each tag. Is this a
* bug?
*/
function addEntry(PelEntry $e) {
if ($this->isValidTag($e->getTag())) {
$e->setIfdType($this->type);
$this->entries[$e->getTag()] = $e;
} else {
throw new PelInvalidDataException("IFD %s cannot hold\n%s",
$this->getName(), $e->__toString());
}
}
/**
* Does a given tag exist in this IFD?
*
* This methods is part of the ArrayAccess SPL interface for
* overriding array access of objects, it allows you to check for
* existance of an entry in the IFD:
*
* <code>
* if (isset($ifd[PelTag::FNUMBER]))
* // ... do something with the F-number.
* </code>
*
* @param PelTag the offset to check.
*
* @return boolean whether the tag exists.
*/
function offsetExists($tag) {
return isset($this->entries[$tag]);
}
/**
* Retrieve a given tag from this IFD.
*
* This methods is part of the ArrayAccess SPL interface for
* overriding array access of objects, it allows you to read entries
* from the IFD the same was as for an array:
*
* <code>
* $entry = $ifd[PelTag::FNUMBER];
* </code>
*
* @param PelTag the tag to return. It is an error to ask for a tag
* which is not in the IFD, just like asking for a non-existant
* array entry.
*
* @return PelEntry the entry.
*/
function offsetGet($tag) {
return $this->entries[$tag];
}
/**
* Set or update a given tag in this IFD.
*
* This methods is part of the ArrayAccess SPL interface for
* overriding array access of objects, it allows you to add new
* entries or replace esisting entries by doing:
*
* <code>
* $ifd[PelTag::EXPOSURE_BIAS_VALUE] = $entry;
* </code>
*
* Note that the actual array index passed is ignored! Instead the
* {@link PelTag} from the entry is used.
*
* @param PelTag the offset to update.
*
* @param PelEntry the new value.
*/
function offsetSet($tag, $e) {
if ($e instanceof PelEntry) {
$tag = $e->getTag();
$this->entries[$tag] = $e;
} else {
throw new PelInvalidArgumentException('Argument "%s" must be a PelEntry.', $e);
}
}
/**
* Unset a given tag in this IFD.
*
* This methods is part of the ArrayAccess SPL interface for
* overriding array access of objects, it allows you to delete
* entries in the IFD by doing:
*
* <code>
* unset($ifd[PelTag::EXPOSURE_BIAS_VALUE])
* </code>
*
* @param PelTag the offset to delete.
*/
function offsetUnset($tag) {
unset($this->entries[$tag]);
}
/**
* Retrieve an entry.
*
* @param PelTag the tag identifying the entry.
*
* @return PelEntry the entry associated with the tag, or null if no
* such entry exists.
*/
function getEntry($tag) {
if (isset($this->entries[$tag]))
return $this->entries[$tag];
else
return null;
}
/**
* Returns all entries contained in this IFD.
*
* @return array an array of {@link PelEntry} objects, or rather
* descendant classes. The array has {@link PelTag}s as keys
* and the entries as values.
*
* @see getEntry
* @see getIterator
*/
function getEntries() {
return $this->entries;
}
/**
* Return an iterator for all entries contained in this IFD.
*
* Used with foreach as in
*
* <code>
* foreach ($ifd as $tag => $entry) {
* // $tag is now a PelTag and $entry is a PelEntry object.
* }
* </code>
*
* @return Iterator an iterator using the {@link PelTag tags} as
* keys and the entries as values.
*/
function getIterator() {
return new ArrayIterator($this->entries);
}
/**
* Returns available thumbnail data.
*
* @return string the bytes in the thumbnail, if any. If the IFD
* does not contain any thumbnail data, the empty string is
* returned.
*
* @todo Throw an exception instead when no data is available?
*
* @todo Return the $this->thumb_data object instead of the bytes?
*/
function getThumbnailData() {
if ($this->thumb_data != null)
return $this->thumb_data->getBytes();
else
return '';
}
/**
* Make this directory point to a new directory.
*
* @param PelIfd the IFD that this directory will point to.
*/
function setNextIfd(PelIfd $i) {
$this->next = $i;
}
/**
* Return the IFD pointed to by this directory.
*
* @return PelIfd the next IFD, following this IFD. If this is the
* last IFD, null is returned.
*/
function getNextIfd() {
return $this->next;
}
/**
* Check if this is the last IFD.
*
* @return boolean true if there are no following IFD, false
* otherwise.
*/
function isLastIfd() {
return $this->next == null;
}
/**
* Add a sub-IFD.
*
* Any previous sub-IFD of the same type will be overwritten.
*
* @param PelIfd the sub IFD. The type of must be one of {@link
* PelIfd::EXIF}, {@link PelIfd::GPS}, or {@link
* PelIfd::INTEROPERABILITY}.
*/
function addSubIfd(PelIfd $sub) {
$this->sub[$sub->type] = $sub;
}
/**
* Return a sub IFD.
*
* @param int the type of the sub IFD. This must be one of {@link
* PelIfd::EXIF}, {@link PelIfd::GPS}, or {@link
* PelIfd::INTEROPERABILITY}.
*
* @return PelIfd the IFD associated with the type, or null if that
* sub IFD does not exist.
*/
function getSubIfd($type) {
if (isset($this->sub[$type]))
return $this->sub[$type];
else
return null;
}
/**
* Get all sub IFDs.
*
* @return array an associative array with (IFD-type, {@link
* PelIfd}) pairs.
*/
function getSubIfds() {
return $this->sub;
}
/**
* Turn this directory into bytes.
*
* This directory will be turned into a byte string, with the
* specified byte order. The offsets will be calculated from the
* offset given.
*
* @param int the offset of the first byte of this directory.
*
* @param PelByteOrder the byte order that should be used when
* turning integers into bytes. This should be one of {@link
* PelConvert::LITTLE_ENDIAN} and {@link PelConvert::BIG_ENDIAN}.
*/
function getBytes($offset, $order) {
$bytes = '';
$extra_bytes = '';
Pel::debug('Bytes from IDF will start at offset %d within Exif data',
$offset);
$n = count($this->entries) + count($this->sub);
if ($this->thumb_data != null) {
/* We need two extra entries for the thumbnail offset and
* length. */
$n += 2;
}
$bytes .= PelConvert::shortToBytes($n, $order);
/* Initialize offset of extra data. This included the bytes
* preceding this IFD, the bytes needed for the count of entries,
* the entries themselves (and sub entries), the extra data in the
* entries, and the IFD link.
*/
$end = $offset + 2 + 12 * $n + 4;
foreach ($this->entries as $tag => $entry) {
/* Each entry is 12 bytes long. */
$bytes .= PelConvert::shortToBytes($entry->getTag(), $order);
$bytes .= PelConvert::shortToBytes($entry->getFormat(), $order);
$bytes .= PelConvert::longToBytes($entry->getComponents(), $order);
/*
* Size? If bigger than 4 bytes, the actual data is not in
* the entry but somewhere else.
*/
$data = $entry->getBytes($order);
$s = strlen($data);
if ($s > 4) {
Pel::debug('Data size %d too big, storing at offset %d instead.',
$s, $end);
$bytes .= PelConvert::longToBytes($end, $order);
$extra_bytes .= $data;
$end += $s;
} else {
Pel::debug('Data size %d fits.', $s);
/* Copy data directly, pad with NULL bytes as necessary to
* fill out the four bytes available.*/
$bytes .= $data . str_repeat(chr(0), 4 - $s);
}
}
if ($this->thumb_data != null) {
Pel::debug('Appending %d bytes of thumbnail data at %d',
$this->thumb_data->getSize(), $end);
// TODO: make PelEntry a class that can be constructed with
// arguments corresponding to the newt four lines.
$bytes .= PelConvert::shortToBytes(PelTag::JPEG_INTERCHANGE_FORMAT_LENGTH,
$order);
$bytes .= PelConvert::shortToBytes(PelFormat::LONG, $order);
$bytes .= PelConvert::longToBytes(1, $order);
$bytes .= PelConvert::longToBytes($this->thumb_data->getSize(),
$order);
$bytes .= PelConvert::shortToBytes(PelTag::JPEG_INTERCHANGE_FORMAT,
$order);
$bytes .= PelConvert::shortToBytes(PelFormat::LONG, $order);
$bytes .= PelConvert::longToBytes(1, $order);
$bytes .= PelConvert::longToBytes($end, $order);
$extra_bytes .= $this->thumb_data->getBytes();
$end += $this->thumb_data->getSize();
}
/* Find bytes from sub IFDs. */
$sub_bytes = '';
foreach ($this->sub as $type => $sub) {
if ($type == PelIfd::EXIF)
$tag = PelTag::EXIF_IFD_POINTER;
elseif ($type == PelIfd::GPS)
$tag = PelTag::GPS_INFO_IFD_POINTER;
elseif ($type == PelIfd::INTEROPERABILITY)
$tag = PelTag::INTEROPERABILITY_IFD_POINTER;
/* Make an aditional entry with the pointer. */
$bytes .= PelConvert::shortToBytes($tag, $order);
/* Next the format, which is always unsigned long. */
$bytes .= PelConvert::shortToBytes(PelFormat::LONG, $order);
/* There is only one component. */
$bytes .= PelConvert::longToBytes(1, $order);
$data = $sub->getBytes($end, $order);
$s = strlen($data);
$sub_bytes .= $data;
$bytes .= PelConvert::longToBytes($end, $order);
$end += $s;
}
/* Make link to next IFD, if any*/
if ($this->isLastIFD()) {
$link = 0;
} else {
$link = $end;
}
Pel::debug('Link to next IFD: %d', $link);
$bytes .= PelConvert::longtoBytes($link, $order);
$bytes .= $extra_bytes . $sub_bytes;
if (!$this->isLastIfd())
$bytes .= $this->next->getBytes($end, $order);
return $bytes;
}
/**
* Turn this directory into text.
*
* @return string information about the directory, mainly for
* debugging.
*/
function __toString() {
$str = Pel::fmt("Dumping IFD %s with %d entries...\n",
$this->getName(), count($this->entries));
foreach ($this->entries as $entry)
$str .= $entry->__toString();
$str .= Pel::fmt("Dumping %d sub IFDs...\n", count($this->sub));
foreach ($this->sub as $type => $ifd)
$str .= $ifd->__toString();
if ($this->next != null)
$str .= $this->next->__toString();
return $str;
}
}
?>
|
mit
|
mickaelbaudoin/simple-php
|
src/Core/Dispatcher.php
|
958
|
<?php
namespace MickaelBaudoin\SimplePhp;
class Dispatcher{
protected $_request;
protected $_controller;
protected $_view;
public function __construct($request, $view)
{
$this->_request = $request;
$this->_view = $view;
$this->_resolveController();
}
public function getRequest()
{
return $this->_request;
}
protected function _resolveController()
{
$controller = sprintf("\\App\\Modules\\%s\\Controllers\\%sController", ucfirst($this->_request->getModuleName()), ucfirst($this->_request->getControllerName()));
if(!class_exists($controller)){
throw new \Exception("Controller $controller not found");
}
$this->_controller = new $controller($this->_request, $this->_view);
}
public function dispatch()
{
$action = ucfirst($this->_request->getActionName()) . "Action";
if(!method_exists($this->_controller, $action)){
throw new \Exception("$action action not found");
}
$this->_controller->$action();
}
}
|
mit
|
CTAPbIuMABP/solaris
|
assets/js/solaris/models/dwarfs/sedna.js
|
670
|
define([
"require",
"./dwarf"
],function (require, AbstractPlanet) {
"use strict";
var _ = require("underscore");
var Sedna = function () {
};
Sedna.prototype = new AbstractPlanet();
_.extend(Sedna.prototype, {
_options: {
body: {
fillStyle: "#ff00ff"
}
},
_params: {
name: "Sedna",
index: 12 + 90377,
mass: null,
diameter: null,
days: 11400 * 365, // approx
orbit: {
aphelion: 140173,
perihelion: 11369
}
}
});
return new Sedna();
});
|
mit
|
dharapvj/learning-webpack2
|
gen/step-02/e56.js
|
142
|
let addEmp56 = (employees) => {
employees.push(
{id:56, name: 'Evelyn Becker'}
)
return employees;
};
export {addEmp56};
|
mit
|
Rainbow-Sprinkles/starter-todo4
|
application/views/itemlist.php
|
152
|
{pagination}
<table class="table">
<tr>
<th>ID</th>
<th>Task</th>
<th>Status</th>
</tr>
{display_tasks}
</table>
|
mit
|
furbrain/Coherence
|
coherence/upnp/core/test/test_utils.py
|
6241
|
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <coherence@beebits.net>
"""
Test cases for L{upnp.core.utils}
"""
import os
from twisted.trial import unittest
from twisted.python.filepath import FilePath
from twisted.internet import reactor
from twisted.web import static, server
from twisted.protocols import policies
from coherence.upnp.core import utils
# This data is joined using CRLF pairs.
testChunkedData = ['200',
'<?xml version="1.0" ?> ',
'<root xmlns="urn:schemas-upnp-org:device-1-0">',
' <specVersion>',
' <major>1</major> ',
' <minor>0</minor> ',
' </specVersion>',
' <device>',
' <deviceType>urn:schemas-upnp-org:device:MediaRenderer:1</deviceType> ',
' <friendlyName>DMA201</friendlyName> ',
' <manufacturer> </manufacturer> ',
' <manufacturerURL> </manufacturerURL> ',
' <modelDescription>DMA201</modelDescription> ',
' <modelName>DMA</modelName> ',
' <modelNumber>201</modelNumber> ',
' <modelURL> </modelURL> ',
' <serialNumber>0',
'200',
'00000000001</serialNumber> ',
' <UDN>uuid:BE1C49F2-572D-3617-8F4C-BB1DEC3954FD</UDN> ',
' <UPC /> ',
' <serviceList>',
' <service>',
' <serviceType>urn:schemas-upnp-org:service:ConnectionManager:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:ConnectionManager</serviceId>',
' <controlURL>http://10.63.1.113:4444/CMSControl</controlURL>',
' <eventSubURL>http://10.63.1.113:4445/CMSEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/ConnectionManager.xml</SCPDURL>',
' </service>',
' <service>',
' <serv',
'223',
'iceType>urn:schemas-upnp-org:service:AVTransport:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:AVTransport</serviceId>',
' <controlURL>http://10.63.1.113:4444/AVTControl</controlURL>',
' <eventSubURL>http://10.63.1.113:4445/AVTEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/AVTransport.xml</SCPDURL>',
' </service>',
' <service>',
' <serviceType>urn:schemas-upnp-org:service:RenderingControl:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:RenderingControl</serviceId>',
' <controlURL>http://10.63.1.113:4444/RCSControl</',
'c4',
'controlURL>',
' <eventSubURL>http://10.63.1.113:4445/RCSEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/RenderingControl.xml</SCPDURL>',
' </service>',
' </serviceList>',
' </device>',
'</root>'
'',
'0',
'']
testChunkedDataResult = ['<?xml version="1.0" ?> ',
'<root xmlns="urn:schemas-upnp-org:device-1-0">',
' <specVersion>',
' <major>1</major> ',
' <minor>0</minor> ',
' </specVersion>',
' <device>',
' <deviceType>urn:schemas-upnp-org:device:MediaRenderer:1</deviceType> ',
' <friendlyName>DMA201</friendlyName> ',
' <manufacturer> </manufacturer> ',
' <manufacturerURL> </manufacturerURL> ',
' <modelDescription>DMA201</modelDescription> ',
' <modelName>DMA</modelName> ',
' <modelNumber>201</modelNumber> ',
' <modelURL> </modelURL> ',
' <serialNumber>000000000001</serialNumber> ',
' <UDN>uuid:BE1C49F2-572D-3617-8F4C-BB1DEC3954FD</UDN> ',
' <UPC /> ',
' <serviceList>',
' <service>',
' <serviceType>urn:schemas-upnp-org:service:ConnectionManager:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:ConnectionManager</serviceId>',
' <controlURL>http://10.63.1.113:4444/CMSControl</controlURL>',
' <eventSubURL>http://10.63.1.113:4445/CMSEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/ConnectionManager.xml</SCPDURL>',
' </service>',
' <service>',
' <serviceType>urn:schemas-upnp-org:service:AVTransport:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:AVTransport</serviceId>',
' <controlURL>http://10.63.1.113:4444/AVTControl</controlURL>',
' <eventSubURL>http://10.63.1.113:4445/AVTEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/AVTransport.xml</SCPDURL>',
' </service>',
' <service>',
' <serviceType>urn:schemas-upnp-org:service:RenderingControl:1</serviceType>',
' <serviceId>urn:upnp-org:serviceId:RenderingControl</serviceId>',
' <controlURL>http://10.63.1.113:4444/RCSControl</controlURL>',
' <eventSubURL>http://10.63.1.113:4445/RCSEvent</eventSubURL>',
' <SCPDURL>/upnpdev.cgi?file=/RenderingControl.xml</SCPDURL>',
' </service>',
' </serviceList>',
' </device>',
'</root>',
''
]
class TestUpnpUtils(unittest.TestCase):
def test_chunked_data(self):
""" tests proper reassembling of a chunked http-response
based on a test and data provided by Lawrence
"""
testData = '\r\n'.join(testChunkedData)
newData = utils.de_chunk_payload(testData)
# see whether we can parse the result
self.assertEqual(newData, '\r\n'.join(testChunkedDataResult))
class TestClient(unittest.TestCase):
def _listen(self, site):
return reactor.listenTCP(0, site, interface="127.0.0.1")
def setUp(self):
name = self.mktemp()
os.mkdir(name)
FilePath(name).child("file").setContent("0123456789")
r = static.File(name)
self.site = server.Site(r, timeout=None)
self.wrapper = policies.WrappingFactory(self.site)
self.port = self._listen(self.wrapper)
self.portno = self.port.getHost().port
def tearDown(self):
return self.port.stopListening()
def getURL(self, path):
return "http://127.0.0.1:%d/%s" % (self.portno, path)
def assertResponse(self, original, content, headers):
self.assertIsInstance(original, tuple)
self.assertEqual(original[0], content)
originalHeaders = original[1]
for header in headers:
self.assertIn(header, originalHeaders)
self.assertEqual(originalHeaders[header], headers[header])
def test_getPage(self):
content = '0123456789'
headers = {'accept-ranges': ['bytes'],
'content-length': ['10'],
'content-type': ['text/html']}
d = utils.getPage(self.getURL("file"))
d.addCallback(self.assertResponse, content, headers)
return d
# $Id:$
|
mit
|
ceolter/angular-grid
|
grid-packages/ag-grid-docs/documentation/src/pages/cell-editing/examples/stop-edit-when-grid-loses-focus/main.js
|
2549
|
var gridOptions = {
columnDefs: [
{ field: 'athlete', minWidth: 160 },
{ field: 'age' },
{ field: 'country', minWidth: 140 },
{ field: 'year', cellEditor: 'yearCellEditor' },
{ field: 'date', minWidth: 140 },
{ field: 'sport', minWidth: 160 },
{ field: 'gold' },
{ field: 'silver' },
{ field: 'bronze' },
{ field: 'total' },
],
defaultColDef: {
flex: 1,
minWidth: 100,
filter: true,
editable: true,
},
components: {
yearCellEditor: getYearCellEditor()
},
// this property tells grid to stop editing if the
// grid loses focus
stopEditingWhenGridLosesFocus: true
};
function getYearCellEditor() {
function YearCellEditor() { }
YearCellEditor.prototype.getGui = function() {
return this.eGui;
};
YearCellEditor.prototype.getValue = function() {
return this.value;
};
YearCellEditor.prototype.isPopup = function() {
return true;
};
YearCellEditor.prototype.init = function(params) {
this.value = params.value;
var tempElement = document.createElement('div');
tempElement.innerHTML =
'<div class="yearSelect">' +
'<div>Clicking here does not close the popup!</div>' +
'<button id="bt2006" class="yearButton">2006</button>' +
'<button id="bt2008" class="yearButton">2008</button>' +
'<button id="bt2010" class="yearButton">2010</button>' +
'<button id="bt2012" class="yearButton">2012</button>' +
'<div>' +
'<input type="text" style="width: 100%;" placeholder="clicking on this text field does not close"/>' +
'</div>' +
'</div>';
var that = this;
[2006, 2008, 2010, 2012].forEach(function(year) {
tempElement.querySelector('#bt' + year).addEventListener('click', function() {
that.value = year;
params.stopEditing();
});
});
this.eGui = tempElement.firstChild;
};
return YearCellEditor;
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' })
.then(function(data) {
gridOptions.api.setRowData(data);
});
});
|
mit
|
rlugojr/jenkins
|
core/src/main/java/hudson/model/listeners/ItemListener.java
|
9366
|
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model.listeners;
import com.google.common.base.Function;
import hudson.ExtensionPoint;
import hudson.ExtensionList;
import hudson.Extension;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Items;
import hudson.security.ACL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.security.NotReallyRoleSensitiveCallable;
/**
* Receives notifications about CRUD operations of {@link Item}.
*
* @since 1.74
* @author Kohsuke Kawaguchi
*/
public class ItemListener implements ExtensionPoint {
private static final Logger LOGGER = Logger.getLogger(ItemListener.class.getName());
/**
* Called after a new job is created and added to {@link jenkins.model.Jenkins},
* before the initial configuration page is provided.
* <p>
* This is useful for changing the default initial configuration of newly created jobs.
* For example, you can enable/add builders, etc.
*/
public void onCreated(Item item) {
}
/**
* Called after a new job is created by copying from an existing job.
*
* For backward compatibility, the default implementation of this method calls {@link #onCreated(Item)}.
* If you choose to handle this method, think about whether you want to call super.onCopied or not.
*
*
* @param src
* The source item that the new one was copied from. Never null.
* @param item
* The newly created item. Never null.
*
* @since 1.325
* Before this version, a copy triggered {@link #onCreated(Item)}.
*/
public void onCopied(Item src, Item item) {
onCreated(item);
}
/**
* Called after all the jobs are loaded from disk into {@link jenkins.model.Jenkins}
* object.
*/
public void onLoaded() {
}
/**
* Called right before a job is going to be deleted.
*
* At this point the data files of the job is already gone.
*/
public void onDeleted(Item item) {
}
/**
* Called after a job is renamed.
* Most implementers should rather use {@link #onLocationChanged}.
* @param item
* The job being renamed.
* @param oldName
* The old name of the job.
* @param newName
* The new name of the job. Same as {@link Item#getName()}.
* @since 1.146
*/
public void onRenamed(Item item, String oldName, String newName) {
}
/**
* Called after an item’s fully-qualified location has changed.
* This might be because:
* <ul>
* <li>This item was renamed.
* <li>Some ancestor folder was renamed.
* <li>This item was moved between folders (or from a folder to Jenkins root or vice-versa).
* <li>Some ancestor folder was moved.
* </ul>
* Where applicable, {@link #onRenamed} will already have been called on this item or an ancestor.
* And where applicable, {@link #onLocationChanged} will already have been called on its ancestors.
* <p>This method should be used (instead of {@link #onRenamed}) by any code
* which seeks to keep (absolute) references to items up to date:
* if a persisted reference matches {@code oldFullName}, replace it with {@code newFullName}.
* @param item an item whose absolute position is now different
* @param oldFullName the former {@link Item#getFullName}
* @param newFullName the current {@link Item#getFullName}
* @see Items#computeRelativeNamesAfterRenaming
* @since 1.548
*/
public void onLocationChanged(Item item, String oldFullName, String newFullName) {}
/**
* Called after a job has its configuration updated.
*
* @since 1.460
*/
public void onUpdated(Item item) {
}
/**
* @since 1.446
* Called at the beginning of the orderly shutdown sequence to
* allow plugins to clean up stuff
*/
public void onBeforeShutdown() {
}
/**
* Registers this instance to Hudson and start getting notifications.
*
* @deprecated as of 1.286
* put {@link Extension} on your class to have it auto-registered.
*/
@Deprecated
public void register() {
all().add(this);
}
/**
* All the registered {@link ItemListener}s.
*/
public static ExtensionList<ItemListener> all() {
return ExtensionList.lookup(ItemListener.class);
}
// TODO JENKINS-21224 generalize this to a method perhaps in ExtensionList and use consistently from all listeners
private static void forAll(final /* java.util.function.Consumer<ItemListener> */Function<ItemListener,Void> consumer) {
for (ItemListener l : all()) {
try {
consumer.apply(l);
} catch (RuntimeException x) {
LOGGER.log(Level.WARNING, "failed to send event to listener of " + l.getClass(), x);
}
}
}
public static void fireOnCopied(final Item src, final Item result) {
forAll(new Function<ItemListener,Void>() {
@Override public Void apply(ItemListener l) {
l.onCopied(src, result);
return null;
}
});
}
public static void fireOnCreated(final Item item) {
forAll(new Function<ItemListener,Void>() {
@Override public Void apply(ItemListener l) {
l.onCreated(item);
return null;
}
});
}
public static void fireOnUpdated(final Item item) {
forAll(new Function<ItemListener,Void>() {
@Override public Void apply(ItemListener l) {
l.onUpdated(item);
return null;
}
});
}
/** @since 1.548 */
public static void fireOnDeleted(final Item item) {
forAll(new Function<ItemListener,Void>() {
@Override public Void apply(ItemListener l) {
l.onDeleted(item);
return null;
}
});
}
/**
* Calls {@link #onRenamed} and {@link #onLocationChanged} as appropriate.
* @param rootItem the topmost item whose location has just changed
* @param oldFullName the previous {@link Item#getFullName}
* @since 1.548
*/
public static void fireLocationChange(final Item rootItem, final String oldFullName) {
String prefix = rootItem.getParent().getFullName();
if (!prefix.isEmpty()) {
prefix += '/';
}
final String newFullName = rootItem.getFullName();
assert newFullName.startsWith(prefix);
int prefixS = prefix.length();
if (oldFullName.startsWith(prefix) && oldFullName.indexOf('/', prefixS) == -1) {
final String oldName = oldFullName.substring(prefixS);
final String newName = rootItem.getName();
assert newName.equals(newFullName.substring(prefixS));
forAll(new Function<ItemListener, Void>() {
@Override public Void apply(ItemListener l) {
l.onRenamed(rootItem, oldName, newName);
return null;
}
});
}
forAll(new Function<ItemListener, Void>() {
@Override public Void apply(ItemListener l) {
l.onLocationChanged(rootItem, oldFullName, newFullName);
return null;
}
});
if (rootItem instanceof ItemGroup) {
for (final Item child : Items.allItems(ACL.SYSTEM, (ItemGroup)rootItem, Item.class)) {
final String childNew = child.getFullName();
assert childNew.startsWith(newFullName);
assert childNew.charAt(newFullName.length()) == '/';
final String childOld = oldFullName + childNew.substring(newFullName.length());
forAll(new Function<ItemListener, Void>() {
@Override public Void apply(ItemListener l) {
l.onLocationChanged(child, childOld, childNew);
return null;
}
});
}
}
}
}
|
mit
|
alphagov/signonotron2
|
test/helpers/batch_invitations_helper_test.rb
|
1979
|
require "test_helper"
class BatchInvitationsHelperTest < ActionView::TestCase
context "#batch_invite_organisation_for_user" do
context "when the batch invitation user raises an invalid slug error when asked for organisation_id" do
setup do
@user = FactoryBot.create(:batch_invitation_user, organisation_slug: "department-of-hats")
end
should "return the empty string" do
assert_equal "", batch_invite_organisation_for_user(@user)
end
end
context "when the batch invitation user raises an active record not found error when asked for organisation_id" do
setup do
@invite = FactoryBot.create(:batch_invitation, organisation_id: -1)
@user = FactoryBot.create(:batch_invitation_user, organisation_slug: nil, batch_invitation: @invite)
end
should "return the empty string" do
assert_equal "", batch_invite_organisation_for_user(@user)
end
end
context "when the batch invitation user has a valid organisation_slug" do
setup do
@org = FactoryBot.create(:organisation, name: "Department of Hats", slug: "department-of-hats")
@user = FactoryBot.create(:batch_invitation_user, organisation_slug: @org.slug)
end
should "return the name of the organisation" do
assert_equal "Department of Hats", batch_invite_organisation_for_user(@user)
end
end
context "when the batch invitation user has a valid organisation from the batch invite" do
setup do
@org = FactoryBot.create(:organisation, name: "Department of Hats", slug: "department-of-hats")
@invite = FactoryBot.create(:batch_invitation, organisation: @org)
@user = FactoryBot.create(:batch_invitation_user, organisation_slug: nil, batch_invitation: @invite)
end
should "return the name of the organisation" do
assert_equal "Department of Hats", batch_invite_organisation_for_user(@user)
end
end
end
end
|
mit
|
lsui/zui
|
src/js/button.js
|
3250
|
/* ========================================================================
* Bootstrap: button.js v3.0.3
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($){
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function(element, options)
{
this.$element = $(element)
this.options = $.extend(
{}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function(state)
{
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (!data.resetText) $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function()
{
if (state == 'loadingText')
{
this.isLoading = true
$el.addClass(d).attr(d, d)
}
else if (this.isLoading)
{
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function()
{
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length)
{
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio')
{
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
var old = $.fn.button
$.fn.button = function(option)
{
return this.each(function()
{
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function()
{
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^=button]', function(e)
{
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
e.preventDefault()
})
}(jQuery);
|
mit
|
huoyaoyuan/osu
|
osu.Game/Beatmaps/Drawables/UpdateableBeatmapBackgroundSprite.cs
|
2436
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Beatmaps.Drawables
{
/// <summary>
/// Display a beatmap background from a local source, but fallback to online source if not available.
/// </summary>
public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo>
{
public readonly Bindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>();
protected override double LoadDelay => 500;
[Resolved]
private BeatmapManager beatmaps { get; set; }
private readonly BeatmapSetCoverType beatmapSetCoverType;
public UpdateableBeatmapBackgroundSprite(BeatmapSetCoverType beatmapSetCoverType = BeatmapSetCoverType.Cover)
{
Beatmap.BindValueChanged(b => Model = b.NewValue);
this.beatmapSetCoverType = beatmapSetCoverType;
}
/// <summary>
/// Delay before the background is unloaded while off-screen.
/// </summary>
protected virtual double UnloadDelay => 10000;
protected override DelayedLoadWrapper CreateDelayedLoadWrapper(Func<Drawable> createContentFunc, double timeBeforeLoad) =>
new DelayedLoadUnloadWrapper(createContentFunc, timeBeforeLoad, UnloadDelay) { RelativeSizeAxes = Axes.Both };
protected override double TransformDuration => 400;
protected override Drawable CreateDrawable(BeatmapInfo model)
{
var drawable = getDrawableForModel(model);
drawable.RelativeSizeAxes = Axes.Both;
drawable.Anchor = Anchor.Centre;
drawable.Origin = Anchor.Centre;
drawable.FillMode = FillMode.Fill;
return drawable;
}
private Drawable getDrawableForModel(BeatmapInfo model)
{
// prefer online cover where available.
if (model?.BeatmapSet?.OnlineInfo != null)
return new BeatmapSetCover(model.BeatmapSet, beatmapSetCoverType);
return model?.ID > 0
? new BeatmapBackgroundSprite(beatmaps.GetWorkingBeatmap(model))
: new BeatmapBackgroundSprite(beatmaps.DefaultBeatmap);
}
}
}
|
mit
|
alexanderkenndy/music-soa-api
|
src/main/java/com/kascend/music2/api3/service/security/UserSecurityService.java
|
1929
|
package com.kascend.music2.api3.service.security;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.kascend.frameworkcommons.config.Configer;
public class UserSecurityService extends SecurityService{
private static final Logger log = Logger
.getLogger(UserSecurityService.class);
@SuppressWarnings({ "unchecked", "rawtypes" })
protected List<Map> getAbnormalList(int status){
List<Map> list=(List<Map>)getDao().queryForList("security.getUserList", status);
return list;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected List<Map> queryAbnormalList(int intervalTime, int accessCount){
Map params=new HashMap();
params.put("intervalTime", intervalTime);
params.put("accessCount", accessCount);
List<Map> list=(List<Map>)getDao().queryForList("security.queryAbnormalUser", params);
return list;
}
@Override
protected void initConfig() {
intervalTime=Configer.getValueInt("security.blockUser.time");
accessCount=Configer.getValueInt("security.blockUser.accessCount");
releaseTime=Configer.getValueInt("security.blockUser.releaseTime");
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void updateStatus(int id, int status) {
Map params=new HashMap();
params.put("id", id);
params.put("status", status);
getDao().update("security.updateUserStatus", params);
}
@Override
@SuppressWarnings({ "rawtypes" })
public boolean check(Object params) {
if(params==null){
return false;
}
long uid=(Long)params;
if(uid==0){
return false;
}
for(int i=0; i<exceptList.size(); i++ ){
Map map=exceptList.get(i);
long uid2=(Long)map.get("uid");
if(uid==uid2){
return false;
}
}
for(int i=0; i<blockList.size(); i++ ){
Map map=blockList.get(i);
long uid2=(Long)map.get("uid");
if(uid==uid2){
return true;
}
}
return false;
}
}
|
mit
|
tmcgee/cmv-wab-widgets
|
wab/2.13/widgets/DistanceAndDirection/nls/ro/strings.js
|
6522
|
define({
"_widgetLabel": "Distanță și direcție",
"tabLineTitle": "Linie",
"tabCircleTitle": "Cerc",
"tabEllipseTitle": "Elipsă",
"tabRingsTitle": "Inele",
"multipleNotationsMessage": " notaţii care se potrivesc cu introducerea dvs. Confirmaţi ce doriţi să folosiţi:",
"invalidCoordinateMessage": "Coordonată invalidă",
"confirmInputNotationMessage": "Confirmare notare intrare",
"prefixSuffixMessage": "Coordonata de intrare a fost detectată ca având şi prefix şi sufix pentru valoarea de latitudine sau longitudine, coordonata returnată se bazează pe prefix.",
"rememberDecisionMessage": "Se reţine decizia şi nu mai sunt întrebat în viitor.<br/>",
"majorAxisTooltipMessage": "Faceți clic pe lungimea axei majore",
"minorAxisTooltipMessage": "Deplasați mouse-ul înapoi la poziția de pornire pentru a seta axa minoră și a finaliza desenul elipsei",
"clickToFinishLineMessage": "Faceți clic pentru a finaliza linia de trasare",
"doubleClickEllipseMesage": "Faceţi dublu clic pentru a finaliza trasarea inelelor de interval",
"invalidCoordinateTypeMessage": "Imposibil de introdus tipul de coordonate. Verificaţi datele introduse",
"noCenterPointSetMessage": "Nu este setat un punct central. Verificați datele introduse",
"ellipseMajorAxis": "Axa majoră",
"ellipseMinorAxis": "Axa minoră",
"degreesRangeMessage": "Valoarea trebuie să fie între 0 şi 360",
"millsRangeMessage": "Valoarea trebuie să fie între 0 şi 6400",
"lengthLabel": "Lungime",
"angleLabel": "Unghi",
"startPointLabel": "Punct de pornire",
"endPointLabel": "Punct final",
"centerPointLabel": "Punct central",
"distanceTableErrorMessage": "Tabelul de distanțe este gol. Asigurați-vă că ați introdus unele distanțe.",
"setCoordFormatStringMessage": "Setare şir format coordonate",
"prefixMessage": "Adăugați prefixul „+/-” la numerele pozitive și negative",
"ddLabel": "DD",
"ddmLabel": "DDM",
"dmsLabel": "DMS",
"garsLabel": "GARS",
"georefLabel": "GEOREF",
"mgrsLabel": "MGRS",
"usngLabel": "USNG",
"utmLabel": "UTM",
"utmhLabel": "UTM (H)",
"DDLatLongNotation": "Grade zecimale - latitudine/longitudine",
"DDLongLatNotation": "Grade zecimale - longitudine/latitudine",
"DDMLatLongNotation": "Grade zecimale minute - latitudine/longitudine",
"DDMLongLatNotation": "Grade zecimale minute - longitudine/latitudine",
"DMSLatLongNotation": "Grade minute secunde - latitudine/longitudine",
"DMSLongLatNotation": "Grade minute secunde - longitudine/latitudine",
"GARSNotation": "GARS",
"GEOREFNotation": "GEOREF",
"MGRSNotation": "MGRS",
"USNGNotation": "USNG",
"UTMBandNotation": "UTM - literă bandă",
"UTMHemNotation": "UTM - emisferă (N/S)",
"circleTitle": "Creați cerc din",
"radiusLabel": "Rază",
"diameterLabel": "Diametru",
"startPointPlaceHolderLabel": "Introducere coordonate",
"formatInputLabel": "Intrare format",
"drawCircleLabel": "Trasare cerc",
"drawLineLabel": "Trasare linie",
"createCircleInteractivelyLabel": "Creați cerc interactiv",
"rangeErrorMessage": "Rază sau diametru invalid",
"numericInvalidMessage": "Introduceţi o valoare numerică",
"timeLabel": "Oră",
"invalidTimeMessage": "Valoare timp nevalidă",
"hoursLabel": "Ore",
"minutesLabel": "Minute",
"secondsLabel": "Secunde",
"rateLabel": "Acordare calificativ",
"invalidDistanceMessage": "Valoare distanţă nevalidă",
"feetSecondsLabel": "Picioare / secundă",
"feetHourLabel": "Picioare / oră",
"kmSecondLabel": "Kilometri / secundă",
"kmHourLabel": "Kilometri / oră",
"metersSecondLabel": "Metri / secundă",
"metersHourLabel": "Metri / oră",
"milesSecondLabel": "Mile / secundă",
"milesHourLabel": "Mile / oră",
"nauticalMilesSecondLabel": "Mile nautice / secundă",
"nauticalMilesHourLabel": "Mile nautice / oră",
"clearGraphicsLabel": "Șterge elemente grafice",
"ellipseTypeLabel": "Tip elipsă",
"ellipseSemiLabel": "Semi",
"ellipseFullLabel": "Complet",
"drawEllipseLabel": "Trasare elipsă",
"createEllipseInteractively": "Creați elipsă interactiv",
"axisLabel": "Axă",
"unitLabel": "Unitate",
"majorRadiusLabel": "Majoră (Rază)",
"majorDiameterLabel": "Majoră (diametru)",
"axisErrorMessage": "Valoarea trebuie să fie mai mare decât 0",
"minorRadiusLabel": "Minoră (Rază)",
"minorDiameterLabel": "Minoră (diametru)",
"orientationLabel": "Orientare",
"orientationErrorMessage": "Valoarea trebuie să fie între 0 şi 360",
"warningMessage": "Avertizare: elementele grafice generate cu ajutorul instrumentului elipsă nu sunt geodezice",
"fromLabel": "De la",
"distanceBearingLabel": "Distanță și orientare",
"pointsLabel": "Puncte",
"createLineInteractively": "Creați linie interactiv",
"lineLengthErrorMessage": "Lungime linie nevalidă",
"degreesLabel": "Grade",
"milsLabel": "Mile",
"lineTypeLabel": "Tip",
"interactiveLabel": "Interactiv",
"fixedLabel": "Fixat",
"originLabel": "Origine",
"cumulativeLabel": "Cumulativ",
"numberOfRingsLabel": "Număr de inele",
"ringsErrorMessage": "Număr de inele nevalid",
"distanceBetweenRingsLabel": "Distanța dintre inele",
"ringsDecimalErrorMessage": "Introduceți o valoare numerică în două locuri zecimale",
"distanceUnitsLabel": "Unităţi distanţă",
"distancesLabel": "Distanţe",
"numberOfRadialsLabel": "Număr de raze",
"upLabel": "Sus",
"downLabel": "Jos",
"deleteLabel": "Ştergere",
"radialsErrorMessage": "Număr de raze nevalid. Numărul maxim permis este 360",
"radialsInvalidMessage": "Valoare nevalidă pentru raze",
"addPointLabel": "Adăugarea unui punct",
"valueLabel": "Valoare",
"valueText": "Introduceţi o valoare",
"actionLabel": "Acţiune",
"distanceCalculatorLabel": "Calculator distanță",
"abbrevMetersLabel": "m",
"abbrevFeetLabel": "ft",
"abbrevKmLabel": "km",
"abbrevMilesLabel": "mi",
"abbrevYardsLabel": "yd",
"abbrevNauticalMilesLabel": "nm",
"abbrevDegreesLabel": "°",
"abbrevMilsLabel": "mil",
"abbrevHoursLabel": "h",
"abbrevMinutesLabel": "m",
"abbrevSecondsLabel": "s",
"abbrevFeetSecondsLabel": "ft/s",
"abbrevFeetHourLabel": "ft/h",
"abbrevKmSecondLabel": "km/s",
"abbrevKmHourLabel": "km/h",
"abbrevMetersSecondLabel": "m/s",
"abbrevMetersHourLabel": "m/h",
"abbrevMilesSecondLabel": "mi/s",
"abbrevMilesHourLabel": "mi/h",
"abbrevNauticalMilesSecondLabel": "nm/s",
"abbrevNauticalMilesHourLabel": "nm/h"
});
|
mit
|
jonathanmarvens/jeeves
|
test/testCaching.py
|
33230
|
import unittest
import macropy.activate
from sourcetrans.macro_module import macros, jeeves
import JeevesLib
import operator
@jeeves
class TestClass:
def __init__(self, a, b):
self.a = a
self.b = b
@jeeves
class TestClassMethod:
def __init__(self, a, b):
self.a = a
self.b = b
def add_a_to_b(self):
self.b += self.a
def return_sum(self):
return self.a + self.b
@jeeves
class TestClass1:
def __init__(self, a):
self.a = a
def __getstate__(self):
if hasattr(self.a, '__getstate__'):
return "(TestClass1:%s)" % self.a.__getstate__()
else:
return "(TestClass1:%s)" % repr(self.a)
@jeeves
class TestClass1Eq:
def __init__(self, a):
self.a = a
def __eq__(self, other):
return self.a == other.a
def __ne__(self, other):
return self.a != other.a
def __lt__(self, other):
return self.a < other.a
def __gt__(self, other):
return self.a > other.a
def __le__(self, other):
return self.a <= other.a
def __ge__(self, other):
return self.a >= other.a
"""
class TestCaching(unittest.TestCase):
def setUp(self):
# reset the Jeeves state
JeevesLib.init()
JeevesLib.start_caching()
@jeeves
def test_restrict_all_permissive(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda _: True)
self.assertTrue(JeevesLib.concretize(None, x))
# Now we test the cache.
self.assertTrue(JeevesLib.concretize(None, x))
self.assertEqual(len(JeevesLib.get_cache()), 1)
@jeeves
def test_restrict_all_restrictive(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda _: False)
self.assertFalse(JeevesLib.concretize(None, x))
self.assertFalse(JeevesLib.concretize(None, x))
@jeeves
def test_restrict_with_context(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda y: y == 2)
self.assertTrue(JeevesLib.concretize(2, x))
self.assertTrue(JeevesLib.concretize(2, x))
self.assertFalse(JeevesLib.concretize(3, x))
self.assertFalse(JeevesLib.concretize(3, x))
@jeeves
def test_restrict_with_sensitive_value(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda y: y == 2)
value = JeevesLib.mkSensitive(x, 42, 41)
self.assertEquals(JeevesLib.concretize(2, value), 42)
self.assertEquals(JeevesLib.concretize(2, value), 42)
self.assertEquals(JeevesLib.concretize(1, value), 41)
self.assertEquals(JeevesLib.concretize(1, value), 41)
self.assertEquals(len(JeevesLib.get_cache()), 2)
@jeeves
def test_restrict_with_cyclic(self):
jl = JeevesLib
jl.clear_cache()
# use the value itself as the context
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt == 42)
value = jl.mkSensitive(x, 42, 20)
self.assertEquals(jl.concretize(value, value), 42)
self.assertEquals(jl.concretize(value, value), 42)
value = jl.mkSensitive(x, 41, 20)
self.assertEquals(jl.concretize(value, value), 20)
self.assertEquals(jl.concretize(value, value), 20)
@jeeves
def test_restrict_under_conditional(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
value = JeevesLib.mkSensitive(x, 42, 0)
if value == 42:
JeevesLib.restrict(x, lambda ctxt : ctxt == 1)
self.assertEquals(JeevesLib.concretize(0, value), 0)
self.assertEquals(JeevesLib.concretize(0, value), 0)
self.assertEquals(JeevesLib.concretize(1, value), 42)
self.assertEquals(JeevesLib.concretize(1, value), 42)
y = JeevesLib.mkLabel('y')
value = JeevesLib.mkSensitive(y, 43, 0)
if value == 42:
JeevesLib.restrict(y, lambda ctxt : ctxt == 1)
self.assertEquals(JeevesLib.concretize(0, value), 43)
self.assertEquals(JeevesLib.concretize(0, value), 43)
self.assertEquals(JeevesLib.concretize(1, value), 43)
self.assertEquals(JeevesLib.concretize(1, value), 43)
@jeeves
def test_jbool_functions_fexprs(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda (a,_) : a == 42)
for lh in (True, False):
for ll in (True, False):
for rh in (True, False):
for rl in (True, False):
l = jl.mkSensitive(x, lh, ll)
r = jl.mkSensitive(x, rh, rl)
self.assertEquals(
jl.concretize((42,0), l and r)
, operator.and_(lh, rh))
self.assertEquals(
jl.concretize((42,0), l and r)
, operator.and_(lh, rh))
self.assertEquals(
jl.concretize((10,0), l and r)
, operator.and_(ll, rl))
self.assertEquals(
jl.concretize((10,0), l and r)
, operator.and_(ll, rl))
@jeeves
def test_jif_with_assign(self):
jl = JeevesLib
jl.clear_cache()
y = jl.mkLabel('y')
jl.restrict(y, lambda ctxt : ctxt == 42)
value0 = jl.mkSensitive(y, 0, 1)
value2 = jl.mkSensitive(y, 2, 3)
value = value0
value = value2
self.assertEquals(jl.concretize(42, value), 2)
self.assertEquals(jl.concretize(10, value), 3)
self.assertEquals(jl.concretize(42, value), 2)
self.assertEquals(jl.concretize(10, value), 3)
value = 100
value = value2
self.assertEquals(jl.concretize(42, value), 2)
self.assertEquals(jl.concretize(10, value), 3)
self.assertEquals(jl.concretize(42, value), 2)
self.assertEquals(jl.concretize(10, value), 3)
value = value0
value = 200
self.assertEquals(jl.concretize(42, value), 200)
self.assertEquals(jl.concretize(10, value), 200)
self.assertEquals(jl.concretize(42, value), 200)
self.assertEquals(jl.concretize(10, value), 200)
value = 100
value = 200
self.assertEquals(jl.concretize(42, value), 200)
self.assertEquals(jl.concretize(10, value), 200)
self.assertEquals(jl.concretize(42, value), 200)
self.assertEquals(jl.concretize(10, value), 200)
@jeeves
def test_jif_with_assign_with_pathvars(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
y = jl.mkLabel('y')
jl.restrict(x, lambda (a,_) : a)
jl.restrict(y, lambda (_,b) : b)
value0 = jl.mkSensitive(y, 0, 1)
value2 = jl.mkSensitive(y, 2, 3)
value = value0
if x:
value = value2
self.assertEquals(jl.concretize((True, True), value), 2)
self.assertEquals(jl.concretize((True, False), value), 3)
self.assertEquals(jl.concretize((False, True), value), 0)
self.assertEquals(jl.concretize((False, False), value), 1)
self.assertEquals(jl.concretize((True, True), value), 2)
self.assertEquals(jl.concretize((True, False), value), 3)
self.assertEquals(jl.concretize((False, True), value), 0)
self.assertEquals(jl.concretize((False, False), value), 1)
value = value0
if not x:
value = value2
self.assertEquals(jl.concretize((False, True), value), 2)
self.assertEquals(jl.concretize((False, False), value), 3)
self.assertEquals(jl.concretize((True, True), value), 0)
self.assertEquals(jl.concretize((True, False), value), 1)
self.assertEquals(jl.concretize((False, True), value), 2)
self.assertEquals(jl.concretize((False, False), value), 3)
self.assertEquals(jl.concretize((True, True), value), 0)
self.assertEquals(jl.concretize((True, False), value), 1)
@jeeves
def test_function_facets(self):
def add1(a):
return a+1
def add2(a):
return a+2
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt == 42)
fun = jl.mkSensitive(x, add1, add2)
value = fun(15)
self.assertEquals(jl.concretize(42, value), 16)
self.assertEquals(jl.concretize(41, value), 17)
self.assertEquals(jl.concretize(42, value), 16)
self.assertEquals(jl.concretize(41, value), 17)
@jeeves
def test_objects_faceted(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt)
y = jl.mkSensitive(x,
TestClass(1, 2),
TestClass(3, 4))
self.assertEquals(jl.concretize(True, y.a), 1)
self.assertEquals(jl.concretize(True, y.b), 2)
self.assertEquals(jl.concretize(False, y.a), 3)
self.assertEquals(jl.concretize(False, y.b), 4)
self.assertEquals(jl.concretize(True, y.a), 1)
self.assertEquals(jl.concretize(True, y.b), 2)
self.assertEquals(jl.concretize(False, y.a), 3)
self.assertEquals(jl.concretize(False, y.b), 4)
@jeeves
def test_objects_mutate(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt)
s = TestClass(1, None)
t = TestClass(3, None)
y = jl.mkSensitive(x, s, t)
if y.a == 1:
y.a = y.a + 100
self.assertEquals(jl.concretize(True, y.a), 101)
self.assertEquals(jl.concretize(True, s.a), 101)
self.assertEquals(jl.concretize(True, t.a), 3)
self.assertEquals(jl.concretize(False, y.a), 3)
self.assertEquals(jl.concretize(False, s.a), 1)
self.assertEquals(jl.concretize(False, t.a), 3)
self.assertEquals(jl.concretize(True, y.a), 101)
self.assertEquals(jl.concretize(True, s.a), 101)
self.assertEquals(jl.concretize(True, t.a), 3)
self.assertEquals(jl.concretize(False, y.a), 3)
self.assertEquals(jl.concretize(False, s.a), 1)
self.assertEquals(jl.concretize(False, t.a), 3)
@jeeves
def test_context_mutate(self):
jl = JeevesLib
jl.clear_cache()
test_alice = TestClass(1, 1)
test_bob = TestClass(2, 2)
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt: ctxt.a == 1)
y = jl.mkSensitive(x, 42, 0)
self.assertEquals(jl.concretize(test_alice, y), 42)
self.assertEquals(jl.concretize(test_bob, y), 0)
test_alice.a = 2
test_bob.a = 1
self.assertEquals(jl.concretize(test_alice, y), 0)
self.assertEquals(jl.concretize(test_bob, y), 42)
@jeeves
def test_objects_methodcall(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt)
s = TestClassMethod(1, 10)
t = TestClassMethod(100, 1000)
y = jl.mkSensitive(x, s, t)
self.assertEquals(jl.concretize(True, y.return_sum()), 11)
self.assertEquals(jl.concretize(False, y.return_sum()), 1100)
self.assertEquals(jl.concretize(True, y.return_sum()), 11)
self.assertEquals(jl.concretize(False, y.return_sum()), 1100)
y.add_a_to_b()
self.assertEquals(jl.concretize(True, s.a), 1)
self.assertEquals(jl.concretize(True, s.b), 11)
self.assertEquals(jl.concretize(True, t.a), 100)
self.assertEquals(jl.concretize(True, t.b), 1000)
self.assertEquals(jl.concretize(True, y.a), 1)
self.assertEquals(jl.concretize(True, y.b), 11)
self.assertEquals(jl.concretize(False, s.a), 1)
self.assertEquals(jl.concretize(False, s.b), 10)
self.assertEquals(jl.concretize(False, t.a), 100)
self.assertEquals(jl.concretize(False, t.b), 1100)
self.assertEquals(jl.concretize(False, y.a), 100)
self.assertEquals(jl.concretize(False, y.b), 1100)
self.assertEquals(jl.concretize(True, s.a), 1)
self.assertEquals(jl.concretize(True, s.b), 11)
self.assertEquals(jl.concretize(True, t.a), 100)
self.assertEquals(jl.concretize(True, t.b), 1000)
self.assertEquals(jl.concretize(True, y.a), 1)
self.assertEquals(jl.concretize(True, y.b), 11)
self.assertEquals(jl.concretize(False, s.a), 1)
self.assertEquals(jl.concretize(False, s.b), 10)
self.assertEquals(jl.concretize(False, t.a), 100)
self.assertEquals(jl.concretize(False, t.b), 1100)
self.assertEquals(jl.concretize(False, y.a), 100)
self.assertEquals(jl.concretize(False, y.b), 1100)
@jeeves
def test_objects_eq_is(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt)
a = TestClass1(3)
b = TestClass1(3)
c = TestClass1(2)
# Ensure that a < b and b < c (will probably be true anyway,
# just making sure)
s = sorted((a, b, c))
a = s[0]
b = s[1]
c = s[2]
a.a = 3
b.a = 3
c.a = 2
v1 = jl.mkSensitive(x, a, c)
v2 = jl.mkSensitive(x, b, c)
v3 = jl.mkSensitive(x, c, a)
self.assertEquals(jl.concretize(True, v1 == v1), True)
self.assertEquals(jl.concretize(True, v2 == v2), True)
self.assertEquals(jl.concretize(True, v3 == v3), True)
self.assertEquals(jl.concretize(True, v1 == v2), False)
self.assertEquals(jl.concretize(True, v2 == v3), False)
self.assertEquals(jl.concretize(True, v3 == v1), False)
self.assertEquals(jl.concretize(True, v1 == v1), True)
self.assertEquals(jl.concretize(True, v2 == v2), True)
self.assertEquals(jl.concretize(True, v3 == v3), True)
self.assertEquals(jl.concretize(True, v1 == v2), False)
self.assertEquals(jl.concretize(True, v2 == v3), False)
self.assertEquals(jl.concretize(True, v3 == v1), False)
self.assertEquals(jl.concretize(True, v1 != v1), False)
self.assertEquals(jl.concretize(True, v2 != v2), False)
self.assertEquals(jl.concretize(True, v3 != v3), False)
self.assertEquals(jl.concretize(True, v1 != v2), True)
self.assertEquals(jl.concretize(True, v2 != v3), True)
self.assertEquals(jl.concretize(True, v3 != v1), True)
self.assertEquals(jl.concretize(True, v1 != v1), False)
self.assertEquals(jl.concretize(True, v2 != v2), False)
self.assertEquals(jl.concretize(True, v3 != v3), False)
self.assertEquals(jl.concretize(True, v1 != v2), True)
self.assertEquals(jl.concretize(True, v2 != v3), True)
self.assertEquals(jl.concretize(True, v3 != v1), True)
self.assertEquals(jl.concretize(True, v1 < v1), False)
self.assertEquals(jl.concretize(True, v2 < v2), False)
self.assertEquals(jl.concretize(True, v3 < v3), False)
self.assertEquals(jl.concretize(True, v1 < v2), True)
self.assertEquals(jl.concretize(True, v2 < v3), True)
self.assertEquals(jl.concretize(True, v3 < v1), False)
self.assertEquals(jl.concretize(True, v1 < v1), False)
self.assertEquals(jl.concretize(True, v2 < v2), False)
self.assertEquals(jl.concretize(True, v3 < v3), False)
self.assertEquals(jl.concretize(True, v1 < v2), True)
self.assertEquals(jl.concretize(True, v2 < v3), True)
self.assertEquals(jl.concretize(True, v3 < v1), False)
self.assertEquals(jl.concretize(True, v1 > v1), False)
self.assertEquals(jl.concretize(True, v2 > v2), False)
self.assertEquals(jl.concretize(True, v3 > v3), False)
self.assertEquals(jl.concretize(True, v1 > v2), False)
self.assertEquals(jl.concretize(True, v2 > v3), False)
self.assertEquals(jl.concretize(True, v3 > v1), True)
self.assertEquals(jl.concretize(True, v1 > v1), False)
self.assertEquals(jl.concretize(True, v2 > v2), False)
self.assertEquals(jl.concretize(True, v3 > v3), False)
self.assertEquals(jl.concretize(True, v1 > v2), False)
self.assertEquals(jl.concretize(True, v2 > v3), False)
self.assertEquals(jl.concretize(True, v3 > v1), True)
self.assertEquals(jl.concretize(True, v1 <= v1), True)
self.assertEquals(jl.concretize(True, v2 <= v2), True)
self.assertEquals(jl.concretize(True, v3 <= v3), True)
self.assertEquals(jl.concretize(True, v1 <= v2), True)
self.assertEquals(jl.concretize(True, v2 <= v3), True)
self.assertEquals(jl.concretize(True, v3 <= v1), False)
self.assertEquals(jl.concretize(True, v1 <= v1), True)
self.assertEquals(jl.concretize(True, v2 <= v2), True)
self.assertEquals(jl.concretize(True, v3 <= v3), True)
self.assertEquals(jl.concretize(True, v1 <= v2), True)
self.assertEquals(jl.concretize(True, v2 <= v3), True)
self.assertEquals(jl.concretize(True, v3 <= v1), False)
self.assertEquals(jl.concretize(True, v1 >= v1), True)
self.assertEquals(jl.concretize(True, v2 >= v2), True)
self.assertEquals(jl.concretize(True, v3 >= v3), True)
self.assertEquals(jl.concretize(True, v1 >= v2), False)
self.assertEquals(jl.concretize(True, v2 >= v3), False)
self.assertEquals(jl.concretize(True, v3 >= v1), True)
self.assertEquals(jl.concretize(True, v1 >= v1), True)
self.assertEquals(jl.concretize(True, v2 >= v2), True)
self.assertEquals(jl.concretize(True, v3 >= v3), True)
self.assertEquals(jl.concretize(True, v1 >= v2), False)
self.assertEquals(jl.concretize(True, v2 >= v3), False)
self.assertEquals(jl.concretize(True, v3 >= v1), True)
self.assertEquals(jl.concretize(False, v2 == v3), False)
self.assertEquals(jl.concretize(False, v2 != v3), True)
self.assertEquals(jl.concretize(False, v2 < v3), False)
self.assertEquals(jl.concretize(False, v2 > v3), True)
self.assertEquals(jl.concretize(False, v2 <= v3), False)
self.assertEquals(jl.concretize(False, v2 >= v3), True)
self.assertEquals(jl.concretize(False, v2 == v3), False)
self.assertEquals(jl.concretize(False, v2 != v3), True)
self.assertEquals(jl.concretize(False, v2 < v3), False)
self.assertEquals(jl.concretize(False, v2 > v3), True)
self.assertEquals(jl.concretize(False, v2 <= v3), False)
self.assertEquals(jl.concretize(False, v2 >= v3), True)
a = TestClass1Eq(3)
b = TestClass1Eq(3)
c = TestClass1Eq(2)
v1 = jl.mkSensitive(x, a, c)
v2 = jl.mkSensitive(x, b, c)
v3 = jl.mkSensitive(x, c, a)
self.assertEquals(jl.concretize(True, v1 == v1), True)
self.assertEquals(jl.concretize(True, v2 == v2), True)
self.assertEquals(jl.concretize(True, v3 == v3), True)
self.assertEquals(jl.concretize(True, v1 == v2), True)
self.assertEquals(jl.concretize(True, v2 == v3), False)
self.assertEquals(jl.concretize(True, v3 == v1), False)
self.assertEquals(jl.concretize(True, v1 == v1), True)
self.assertEquals(jl.concretize(True, v2 == v2), True)
self.assertEquals(jl.concretize(True, v3 == v3), True)
self.assertEquals(jl.concretize(True, v1 == v2), True)
self.assertEquals(jl.concretize(True, v2 == v3), False)
self.assertEquals(jl.concretize(True, v3 == v1), False)
self.assertEquals(jl.concretize(True, v1 != v1), False)
self.assertEquals(jl.concretize(True, v2 != v2), False)
self.assertEquals(jl.concretize(True, v3 != v3), False)
self.assertEquals(jl.concretize(True, v1 != v2), False)
self.assertEquals(jl.concretize(True, v2 != v3), True)
self.assertEquals(jl.concretize(True, v3 != v1), True)
self.assertEquals(jl.concretize(True, v1 != v1), False)
self.assertEquals(jl.concretize(True, v2 != v2), False)
self.assertEquals(jl.concretize(True, v3 != v3), False)
self.assertEquals(jl.concretize(True, v1 != v2), False)
self.assertEquals(jl.concretize(True, v2 != v3), True)
self.assertEquals(jl.concretize(True, v3 != v1), True)
self.assertEquals(jl.concretize(True, v1 < v1), False)
self.assertEquals(jl.concretize(True, v2 < v2), False)
self.assertEquals(jl.concretize(True, v3 < v3), False)
self.assertEquals(jl.concretize(True, v1 < v2), False)
self.assertEquals(jl.concretize(True, v2 < v3), False)
self.assertEquals(jl.concretize(True, v3 < v1), True)
self.assertEquals(jl.concretize(True, v1 < v1), False)
self.assertEquals(jl.concretize(True, v2 < v2), False)
self.assertEquals(jl.concretize(True, v3 < v3), False)
self.assertEquals(jl.concretize(True, v1 < v2), False)
self.assertEquals(jl.concretize(True, v2 < v3), False)
self.assertEquals(jl.concretize(True, v3 < v1), True)
self.assertEquals(jl.concretize(True, v1 > v1), False)
self.assertEquals(jl.concretize(True, v2 > v2), False)
self.assertEquals(jl.concretize(True, v3 > v3), False)
self.assertEquals(jl.concretize(True, v1 > v2), False)
self.assertEquals(jl.concretize(True, v2 > v3), True)
self.assertEquals(jl.concretize(True, v3 > v1), False)
self.assertEquals(jl.concretize(True, v1 > v1), False)
self.assertEquals(jl.concretize(True, v2 > v2), False)
self.assertEquals(jl.concretize(True, v3 > v3), False)
self.assertEquals(jl.concretize(True, v1 > v2), False)
self.assertEquals(jl.concretize(True, v2 > v3), True)
self.assertEquals(jl.concretize(True, v3 > v1), False)
self.assertEquals(jl.concretize(True, v1 <= v1), True)
self.assertEquals(jl.concretize(True, v2 <= v2), True)
self.assertEquals(jl.concretize(True, v3 <= v3), True)
self.assertEquals(jl.concretize(True, v1 <= v2), True)
self.assertEquals(jl.concretize(True, v2 <= v3), False)
self.assertEquals(jl.concretize(True, v3 <= v1), True)
self.assertEquals(jl.concretize(True, v1 <= v1), True)
self.assertEquals(jl.concretize(True, v2 <= v2), True)
self.assertEquals(jl.concretize(True, v3 <= v3), True)
self.assertEquals(jl.concretize(True, v1 <= v2), True)
self.assertEquals(jl.concretize(True, v2 <= v3), False)
self.assertEquals(jl.concretize(True, v3 <= v1), True)
self.assertEquals(jl.concretize(True, v1 >= v1), True)
self.assertEquals(jl.concretize(True, v2 >= v2), True)
self.assertEquals(jl.concretize(True, v3 >= v3), True)
self.assertEquals(jl.concretize(True, v1 >= v2), True)
self.assertEquals(jl.concretize(True, v2 >= v3), True)
self.assertEquals(jl.concretize(True, v3 >= v1), False)
self.assertEquals(jl.concretize(True, v1 >= v1), True)
self.assertEquals(jl.concretize(True, v2 >= v2), True)
self.assertEquals(jl.concretize(True, v3 >= v3), True)
self.assertEquals(jl.concretize(True, v1 >= v2), True)
self.assertEquals(jl.concretize(True, v2 >= v3), True)
self.assertEquals(jl.concretize(True, v3 >= v1), False)
self.assertEquals(jl.concretize(False, v2 == v3), False)
self.assertEquals(jl.concretize(False, v2 != v3), True)
self.assertEquals(jl.concretize(False, v2 < v3), True)
self.assertEquals(jl.concretize(False, v2 > v3), False)
self.assertEquals(jl.concretize(False, v2 <= v3), True)
self.assertEquals(jl.concretize(False, v2 >= v3), False)
self.assertEquals(jl.concretize(False, v2 == v3), False)
self.assertEquals(jl.concretize(False, v2 != v3), True)
self.assertEquals(jl.concretize(False, v2 < v3), True)
self.assertEquals(jl.concretize(False, v2 > v3), False)
self.assertEquals(jl.concretize(False, v2 <= v3), True)
self.assertEquals(jl.concretize(False, v2 >= v3), False)
@jeeves
def test_jhasElt(self):
jl = JeevesLib
jl.clear_cache()
a = jl.mkLabel ()
jl.restrict(a, lambda x: x)
xS = jl.mkSensitive(a, 42, 1)
b = jl.mkLabel ()
jl.restrict(b, lambda x: x)
yS = jl.mkSensitive(b, 43, 3)
lst = [xS, 2, yS]
self.assertEquals(jl.concretize(True, 42 in lst) , True)
self.assertEquals(jl.concretize(False, 42 in lst) , False)
self.assertEquals(jl.concretize(True, 1 in lst) , False)
self.assertEquals(jl.concretize(False, 1 in lst) , True)
self.assertEquals(jl.concretize(True, 43 in lst) , True)
self.assertEquals(jl.concretize(False, 43 in lst) , False)
self.assertEquals(jl.concretize(True, 3 in lst) , False)
self.assertEquals(jl.concretize(False, 3 in lst) , True)
self.assertEquals(jl.concretize(True, 42 in lst) , True)
self.assertEquals(jl.concretize(False, 42 in lst) , False)
self.assertEquals(jl.concretize(True, 1 in lst) , False)
self.assertEquals(jl.concretize(False, 1 in lst) , True)
self.assertEquals(jl.concretize(True, 43 in lst) , True)
self.assertEquals(jl.concretize(False, 43 in lst) , False)
self.assertEquals(jl.concretize(True, 3 in lst) , False)
self.assertEquals(jl.concretize(False, 3 in lst) , True)
@jeeves
def test_list(self):
jl = JeevesLib
jl.clear_cache()
x = jl.mkLabel('x')
jl.restrict(x, lambda ctxt : ctxt)
l = jl.mkSensitive(x, [40,41,42], [0,1,2,3])
self.assertEqual(jl.concretize(True, l[0]), 40)
self.assertEqual(jl.concretize(True, l[1]), 41)
self.assertEqual(jl.concretize(True, l[2]), 42)
self.assertEqual(jl.concretize(False, l[0]), 0)
self.assertEqual(jl.concretize(False, l[1]), 1)
self.assertEqual(jl.concretize(False, l[2]), 2)
self.assertEqual(jl.concretize(False, l[3]), 3)
self.assertEqual(jl.concretize(True, l[0]), 40)
self.assertEqual(jl.concretize(True, l[1]), 41)
self.assertEqual(jl.concretize(True, l[2]), 42)
self.assertEqual(jl.concretize(False, l[0]), 0)
self.assertEqual(jl.concretize(False, l[1]), 1)
self.assertEqual(jl.concretize(False, l[2]), 2)
self.assertEqual(jl.concretize(False, l[3]), 3)
self.assertEqual(jl.concretize(True, l.__len__()), 3)
self.assertEqual(jl.concretize(False, l.__len__()), 4)
self.assertEqual(jl.concretize(True, l.__len__()), 3)
self.assertEqual(jl.concretize(False, l.__len__()), 4)
l[1] = 19
self.assertEqual(jl.concretize(True, l[0]), 40)
self.assertEqual(jl.concretize(True, l[1]), 19)
self.assertEqual(jl.concretize(True, l[2]), 42)
self.assertEqual(jl.concretize(False, l[0]), 0)
self.assertEqual(jl.concretize(False, l[1]), 19)
self.assertEqual(jl.concretize(False, l[2]), 2)
self.assertEqual(jl.concretize(False, l[3]), 3)
self.assertEqual(jl.concretize(True, l[0]), 40)
self.assertEqual(jl.concretize(True, l[1]), 19)
self.assertEqual(jl.concretize(True, l[2]), 42)
self.assertEqual(jl.concretize(False, l[0]), 0)
self.assertEqual(jl.concretize(False, l[1]), 19)
self.assertEqual(jl.concretize(False, l[2]), 2)
self.assertEqual(jl.concretize(False, l[3]), 3)
@jeeves
def test_jmap(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda ctxt : ctxt)
l = JeevesLib.mkSensitive(x, [0,1,2], [3,4,5,6])
m = [x*x for x in l]
self.assertEqual(JeevesLib.concretize(True, m[0]), 0)
self.assertEqual(JeevesLib.concretize(True, m[1]), 1)
self.assertEqual(JeevesLib.concretize(True, m[2]), 4)
self.assertEqual(JeevesLib.concretize(False, m[0]), 9)
self.assertEqual(JeevesLib.concretize(False, m[1]), 16)
self.assertEqual(JeevesLib.concretize(False, m[2]), 25)
self.assertEqual(JeevesLib.concretize(False, m[3]), 36)
self.assertEqual(JeevesLib.concretize(True, m[0]), 0)
self.assertEqual(JeevesLib.concretize(True, m[1]), 1)
self.assertEqual(JeevesLib.concretize(True, m[2]), 4)
self.assertEqual(JeevesLib.concretize(False, m[0]), 9)
self.assertEqual(JeevesLib.concretize(False, m[1]), 16)
self.assertEqual(JeevesLib.concretize(False, m[2]), 25)
self.assertEqual(JeevesLib.concretize(False, m[3]), 36)
@jeeves
def test_jmap_for(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda ctxt : ctxt)
l = JeevesLib.mkSensitive(x, [0,1,2], [3,4,5,6])
m = 0
for t in l:
m = m + t*t
self.assertEqual(JeevesLib.concretize(True, m), 5)
self.assertEqual(JeevesLib.concretize(False, m), 86)
self.assertEqual(JeevesLib.concretize(True, m), 5)
self.assertEqual(JeevesLib.concretize(False, m), 86)
@jeeves
def test_jlist(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda ctxt : ctxt)
l = JeevesLib.mkSensitive(x, [0,1,2], [3,4,5,6])
if x:
l.append(10)
else:
l.append(11)
self.assertEqual(JeevesLib.concretize(True, l[0]), 0)
self.assertEqual(JeevesLib.concretize(True, l[1]), 1)
self.assertEqual(JeevesLib.concretize(True, l[2]), 2)
self.assertEqual(JeevesLib.concretize(True, l[3]), 10)
self.assertEqual(JeevesLib.concretize(False, l[0]), 3)
self.assertEqual(JeevesLib.concretize(False, l[1]), 4)
self.assertEqual(JeevesLib.concretize(False, l[2]), 5)
self.assertEqual(JeevesLib.concretize(False, l[3]), 6)
self.assertEqual(JeevesLib.concretize(False, l[4]), 11)
self.assertEqual(JeevesLib.concretize(True, l[0]), 0)
self.assertEqual(JeevesLib.concretize(True, l[1]), 1)
self.assertEqual(JeevesLib.concretize(True, l[2]), 2)
self.assertEqual(JeevesLib.concretize(True, l[3]), 10)
self.assertEqual(JeevesLib.concretize(False, l[0]), 3)
self.assertEqual(JeevesLib.concretize(False, l[1]), 4)
self.assertEqual(JeevesLib.concretize(False, l[2]), 5)
self.assertEqual(JeevesLib.concretize(False, l[3]), 6)
self.assertEqual(JeevesLib.concretize(False, l[4]), 11)
if x:
l[0] = 20
self.assertEqual(JeevesLib.concretize(True, l[0]), 20)
self.assertEqual(JeevesLib.concretize(False, l[0]), 3)
self.assertEqual(JeevesLib.concretize(True, l[0]), 20)
self.assertEqual(JeevesLib.concretize(False, l[0]), 3)
@jeeves
def test_scope(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda ctxt : ctxt)
y = 5
def awesome_function():
y = 7
if x:
return 30
y = 19
return 17
z = awesome_function()
self.assertEqual(JeevesLib.concretize(True, y), 5)
self.assertEqual(JeevesLib.concretize(False, y), 5)
self.assertEqual(JeevesLib.concretize(True, z), 30)
self.assertEqual(JeevesLib.concretize(False, z), 17)
self.assertEqual(JeevesLib.concretize(True, y), 5)
self.assertEqual(JeevesLib.concretize(False, y), 5)
self.assertEqual(JeevesLib.concretize(True, z), 30)
self.assertEqual(JeevesLib.concretize(False, z), 17)
@jeeves
def test_jfun(self):
JeevesLib.clear_cache()
x = JeevesLib.mkLabel('x')
JeevesLib.restrict(x, lambda ctxt : ctxt)
y = JeevesLib.mkSensitive(x, [1,2,3], [4,5,6,7])
z = [x*x for x in y]
self.assertEqual(JeevesLib.concretize(True, z[0]), 1)
self.assertEqual(JeevesLib.concretize(True, z[1]), 4)
self.assertEqual(JeevesLib.concretize(True, z[2]), 9)
self.assertEqual(JeevesLib.concretize(False, z[0]), 16)
self.assertEqual(JeevesLib.concretize(False, z[1]), 25)
self.assertEqual(JeevesLib.concretize(False, z[2]), 36)
self.assertEqual(JeevesLib.concretize(False, z[3]), 49)
self.assertEqual(JeevesLib.concretize(True, z[0]), 1)
self.assertEqual(JeevesLib.concretize(True, z[1]), 4)
self.assertEqual(JeevesLib.concretize(True, z[2]), 9)
self.assertEqual(JeevesLib.concretize(False, z[0]), 16)
self.assertEqual(JeevesLib.concretize(False, z[1]), 25)
self.assertEqual(JeevesLib.concretize(False, z[2]), 36)
self.assertEqual(JeevesLib.concretize(False, z[3]), 49)
"""
|
mit
|
inikoo/fact
|
libs/yui/yui-2in3/src/lib/yui/2.9.0pr1.2725/build/tabview/tabview.js
|
33686
|
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0pr1
*/
(function() {
/**
* The tabview module provides a widget for managing content bound to tabs.
* @module tabview
* @requires yahoo, dom, event, element
*
*/
var Y = YAHOO.util,
Dom = Y.Dom,
Event = Y.Event,
document = window.document,
// STRING CONSTANTS
ACTIVE = 'active',
ACTIVE_INDEX = 'activeIndex',
ACTIVE_TAB = 'activeTab',
DISABLED = 'disabled',
CONTENT_EL = 'contentEl',
ELEMENT = 'element',
/**
* A widget to control tabbed views.
* @namespace YAHOO.widget
* @class TabView
* @extends YAHOO.util.Element
* @constructor
* @param {HTMLElement | String | Object} el(optional) The html
* element that represents the TabView, or the attribute object to use.
* An element will be created if none provided.
* @param {Object} attr (optional) A key map of the tabView's
* initial attributes. Ignored if first arg is attributes object.
*/
TabView = function(el, attr) {
attr = attr || {};
if (arguments.length == 1 && !YAHOO.lang.isString(el) && !el.nodeName) {
attr = el; // treat first arg as attr object
el = attr.element || null;
}
if (!el && !attr.element) { // create if we dont have one
el = this._createTabViewElement(attr);
}
TabView.superclass.constructor.call(this, el, attr);
};
YAHOO.extend(TabView, Y.Element, {
/**
* The className to add when building from scratch.
* @property CLASSNAME
* @default "navset"
*/
CLASSNAME: 'yui-navset',
/**
* The className of the HTMLElement containing the TabView's tab elements
* to look for when building from existing markup, or to add when building
* from scratch.
* All childNodes of the tab container are treated as Tabs when building
* from existing markup.
* @property TAB_PARENT_CLASSNAME
* @default "nav"
*/
TAB_PARENT_CLASSNAME: 'yui-nav',
/**
* The className of the HTMLElement containing the TabView's label elements
* to look for when building from existing markup, or to add when building
* from scratch.
* All childNodes of the content container are treated as content elements when
* building from existing markup.
* @property CONTENT_PARENT_CLASSNAME
* @default "nav-content"
*/
CONTENT_PARENT_CLASSNAME: 'yui-content',
_tabParent: null,
_contentParent: null,
/**
* Adds a Tab to the TabView instance.
* If no index is specified, the tab is added to the end of the tab list.
* @method addTab
* @param {YAHOO.widget.Tab} tab A Tab instance to add.
* @param {Integer} index The position to add the tab.
* @return void
*/
addTab: function(tab, index) {
var tabs = this.get('tabs'),
tabParent = this._tabParent,
contentParent = this._contentParent,
tabElement = tab.get(ELEMENT),
contentEl = tab.get(CONTENT_EL),
activeIndex = this.get(ACTIVE_INDEX),
before;
if (!tabs) { // not ready yet
this._queue[this._queue.length] = ['addTab', arguments];
return false;
}
before = this.getTab(index);
index = (index === undefined) ? tabs.length : index;
tabs.splice(index, 0, tab);
if (before) {
tabParent.insertBefore(tabElement, before.get(ELEMENT));
if (contentEl) {
contentParent.appendChild(contentEl);
}
} else {
tabParent.appendChild(tabElement);
if (contentEl) {
contentParent.appendChild(contentEl);
}
}
if ( !tab.get(ACTIVE) ) {
tab.set('contentVisible', false, true); /* hide if not active */
if (index <= activeIndex) {
this.set(ACTIVE_INDEX, activeIndex + 1, true);
}
} else {
this.set(ACTIVE_TAB, tab, true);
this.set('activeIndex', index, true);
}
this._initTabEvents(tab);
},
_initTabEvents: function(tab) {
tab.addListener( tab.get('activationEvent'), tab._onActivate, this, tab);
tab.addListener('activationEventChange', tab._onActivationEventChange, this, tab);
},
_removeTabEvents: function(tab) {
tab.removeListener(tab.get('activationEvent'), tab._onActivate, this, tab);
tab.removeListener('activationEventChange', tab._onActivationEventChange, this, tab);
},
/**
* Routes childNode events.
* @method DOMEventHandler
* @param {event} e The Dom event that is being handled.
* @return void
*/
DOMEventHandler: function(e) {
var target = Event.getTarget(e),
tabParent = this._tabParent,
tabs = this.get('tabs'),
tab,
tabEl,
contentEl;
if (Dom.isAncestor(tabParent, target) ) {
for (var i = 0, len = tabs.length; i < len; i++) {
tabEl = tabs[i].get(ELEMENT);
contentEl = tabs[i].get(CONTENT_EL);
if ( target == tabEl || Dom.isAncestor(tabEl, target) ) {
tab = tabs[i];
break; // note break
}
}
if (tab) {
tab.fireEvent(e.type, e);
}
}
},
/**
* Returns the Tab instance at the specified index.
* @method getTab
* @param {Integer} index The position of the Tab.
* @return YAHOO.widget.Tab
*/
getTab: function(index) {
return this.get('tabs')[index];
},
/**
* Returns the index of given tab.
* @method getTabIndex
* @param {YAHOO.widget.Tab} tab The tab whose index will be returned.
* @return int
*/
getTabIndex: function(tab) {
var index = null,
tabs = this.get('tabs');
for (var i = 0, len = tabs.length; i < len; ++i) {
if (tab == tabs[i]) {
index = i;
break;
}
}
return index;
},
/**
* Removes the specified Tab from the TabView.
* @method removeTab
* @param {YAHOO.widget.Tab} item The Tab instance to be removed.
* @return void
*/
removeTab: function(tab) {
var tabCount = this.get('tabs').length,
activeIndex = this.get(ACTIVE_INDEX),
index = this.getTabIndex(tab);
if ( tab === this.get(ACTIVE_TAB) ) {
if (tabCount > 1) { // select another tab
if (index + 1 === tabCount) { // if last, activate previous
this.set(ACTIVE_INDEX, index - 1);
} else { // activate next tab
this.set(ACTIVE_INDEX, index + 1);
}
} else { // no more tabs
this.set(ACTIVE_TAB, null);
}
} else if (index < activeIndex) {
this.set(ACTIVE_INDEX, activeIndex - 1, true);
}
this._removeTabEvents(tab);
this._tabParent.removeChild( tab.get(ELEMENT) );
this._contentParent.removeChild( tab.get(CONTENT_EL) );
this._configs.tabs.value.splice(index, 1);
tab.fireEvent('remove', { type: 'remove', tabview: this });
},
/**
* Provides a readable name for the TabView instance.
* @method toString
* @return String
*/
toString: function() {
var name = this.get('id') || this.get('tagName');
return "TabView " + name;
},
/**
* The transiton to use when switching between tabs.
* @method contentTransition
*/
contentTransition: function(newTab, oldTab) {
if (newTab) {
newTab.set('contentVisible', true);
}
if (oldTab) {
oldTab.set('contentVisible', false);
}
},
/**
* setAttributeConfigs TabView specific properties.
* @method initAttributes
* @param {Object} attr Hash of initial attributes
*/
initAttributes: function(attr) {
TabView.superclass.initAttributes.call(this, attr);
if (!attr.orientation) {
attr.orientation = 'top';
}
var el = this.get(ELEMENT);
if (!this.hasClass(this.CLASSNAME)) {
this.addClass(this.CLASSNAME);
}
/**
* The Tabs belonging to the TabView instance.
* @attribute tabs
* @type Array
*/
this.setAttributeConfig('tabs', {
value: [],
readOnly: true
});
/**
* The container of the tabView's label elements.
* @property _tabParent
* @private
* @type HTMLElement
*/
this._tabParent =
this.getElementsByClassName(this.TAB_PARENT_CLASSNAME,
'ul' )[0] || this._createTabParent();
/**
* The container of the tabView's content elements.
* @property _contentParent
* @type HTMLElement
* @private
*/
this._contentParent =
this.getElementsByClassName(this.CONTENT_PARENT_CLASSNAME,
'div')[0] || this._createContentParent();
/**
* How the Tabs should be oriented relative to the TabView.
* @attribute orientation
* @type String
* @default "top"
*/
this.setAttributeConfig('orientation', {
value: attr.orientation,
method: function(value) {
var current = this.get('orientation');
this.addClass('yui-navset-' + value);
if (current != value) {
this.removeClass('yui-navset-' + current);
}
if (value === 'bottom') {
this.appendChild(this._tabParent);
}
}
});
/**
* The index of the tab currently active.
* @attribute activeIndex
* @type Int
*/
this.setAttributeConfig(ACTIVE_INDEX, {
value: attr.activeIndex,
validator: function(value) {
var ret = true,
tab;
if (value) { // cannot activate if disabled
tab = this.getTab(value);
if (tab && tab.get(DISABLED)) {
ret = false;
}
}
return ret;
}
});
/**
* The tab currently active.
* @attribute activeTab
* @type YAHOO.widget.Tab
*/
this.setAttributeConfig(ACTIVE_TAB, {
value: attr[ACTIVE_TAB],
method: function(tab) {
var activeTab = this.get(ACTIVE_TAB);
if (tab) {
tab.set(ACTIVE, true);
}
if (activeTab && activeTab !== tab) {
activeTab.set(ACTIVE, false);
}
if (activeTab && tab !== activeTab) { // no transition if only 1
this.contentTransition(tab, activeTab);
} else if (tab) {
tab.set('contentVisible', true);
}
},
validator: function(value) {
var ret = true;
if (value && value.get(DISABLED)) { // cannot activate if disabled
ret = false;
}
return ret;
}
});
this.on('activeTabChange', this._onActiveTabChange);
this.on('activeIndexChange', this._onActiveIndexChange);
if ( this._tabParent ) {
this._initTabs();
}
// Due to delegation we add all DOM_EVENTS to the TabView container
// but IE will leak when unsupported events are added, so remove these
this.DOM_EVENTS.submit = false;
this.DOM_EVENTS.focus = false;
this.DOM_EVENTS.blur = false;
this.DOM_EVENTS.change = false;
for (var type in this.DOM_EVENTS) {
if ( YAHOO.lang.hasOwnProperty(this.DOM_EVENTS, type) ) {
this.addListener.call(this, type, this.DOMEventHandler);
}
}
},
/**
* Removes selected state from the given tab if it is the activeTab
* @method deselectTab
* @param {Int} index The tab index to deselect
*/
deselectTab: function(index) {
if (this.getTab(index) === this.get(ACTIVE_TAB)) {
this.set(ACTIVE_TAB, null);
}
},
/**
* Makes the tab at the given index the active tab
* @method selectTab
* @param {Int} index The tab index to be made active
*/
selectTab: function(index) {
this.set(ACTIVE_TAB, this.getTab(index));
},
_onActiveTabChange: function(e) {
var activeIndex = this.get(ACTIVE_INDEX),
newIndex = this.getTabIndex(e.newValue);
if (activeIndex !== newIndex) {
if (!(this.set(ACTIVE_INDEX, newIndex)) ) { // NOTE: setting
// revert if activeIndex update fails (cancelled via beforeChange)
this.set(ACTIVE_TAB, e.prevValue);
}
}
},
_onActiveIndexChange: function(e) {
// no set if called from ActiveTabChange event
if (e.newValue !== this.getTabIndex(this.get(ACTIVE_TAB))) {
if (!(this.set(ACTIVE_TAB, this.getTab(e.newValue))) ) { // NOTE: setting
// revert if activeTab update fails (cancelled via beforeChange)
this.set(ACTIVE_INDEX, e.prevValue);
}
}
},
/**
* Creates Tab instances from a collection of HTMLElements.
* @method _initTabs
* @private
* @return void
*/
_initTabs: function() {
var tabs = Dom.getChildren(this._tabParent),
contentElements = Dom.getChildren(this._contentParent),
activeIndex = this.get(ACTIVE_INDEX),
tab,
attr,
active;
for (var i = 0, len = tabs.length; i < len; ++i) {
attr = {};
if (contentElements[i]) {
attr.contentEl = contentElements[i];
}
tab = new YAHOO.widget.Tab(tabs[i], attr);
this.addTab(tab);
if (tab.hasClass(tab.ACTIVE_CLASSNAME) ) {
active = tab;
}
}
if (activeIndex != undefined) { // not null or undefined
this.set(ACTIVE_TAB, this.getTab(activeIndex));
} else {
this._configs[ACTIVE_TAB].value = active; // dont invoke method
this._configs[ACTIVE_INDEX].value = this.getTabIndex(active);
}
},
_createTabViewElement: function(attr) {
var el = document.createElement('div');
if ( this.CLASSNAME ) {
el.className = this.CLASSNAME;
}
return el;
},
_createTabParent: function(attr) {
var el = document.createElement('ul');
if ( this.TAB_PARENT_CLASSNAME ) {
el.className = this.TAB_PARENT_CLASSNAME;
}
this.get(ELEMENT).appendChild(el);
return el;
},
_createContentParent: function(attr) {
var el = document.createElement('div');
if ( this.CONTENT_PARENT_CLASSNAME ) {
el.className = this.CONTENT_PARENT_CLASSNAME;
}
this.get(ELEMENT).appendChild(el);
return el;
}
});
YAHOO.widget.TabView = TabView;
})();
(function() {
var Y = YAHOO.util,
Dom = Y.Dom,
Lang = YAHOO.lang,
// STRING CONSTANTS
ACTIVE_TAB = 'activeTab',
LABEL = 'label',
LABEL_EL = 'labelEl',
CONTENT = 'content',
CONTENT_EL = 'contentEl',
ELEMENT = 'element',
CACHE_DATA = 'cacheData',
DATA_SRC = 'dataSrc',
DATA_LOADED = 'dataLoaded',
DATA_TIMEOUT = 'dataTimeout',
LOAD_METHOD = 'loadMethod',
POST_DATA = 'postData',
DISABLED = 'disabled',
/**
* A representation of a Tab's label and content.
* @namespace YAHOO.widget
* @class Tab
* @extends YAHOO.util.Element
* @constructor
* @param element {HTMLElement | String} (optional) The html element that
* represents the Tab. An element will be created if none provided.
* @param {Object} properties A key map of initial properties
*/
Tab = function(el, attr) {
attr = attr || {};
if (arguments.length == 1 && !Lang.isString(el) && !el.nodeName) {
attr = el;
el = attr.element;
}
if (!el && !attr.element) {
el = this._createTabElement(attr);
}
this.loadHandler = {
success: function(o) {
this.set(CONTENT, o.responseText);
},
failure: function(o) {
}
};
Tab.superclass.constructor.call(this, el, attr);
this.DOM_EVENTS = {}; // delegating to tabView
};
YAHOO.extend(Tab, YAHOO.util.Element, {
/**
* The default tag name for a Tab's inner element.
* @property LABEL_INNER_TAGNAME
* @type String
* @default "em"
*/
LABEL_TAGNAME: 'em',
/**
* The class name applied to active tabs.
* @property ACTIVE_CLASSNAME
* @type String
* @default "selected"
*/
ACTIVE_CLASSNAME: 'selected',
/**
* The class name applied to active tabs.
* @property HIDDEN_CLASSNAME
* @type String
* @default "yui-hidden"
*/
HIDDEN_CLASSNAME: 'yui-hidden',
/**
* The title applied to active tabs.
* @property ACTIVE_TITLE
* @type String
* @default "active"
*/
ACTIVE_TITLE: 'active',
/**
* The class name applied to disabled tabs.
* @property DISABLED_CLASSNAME
* @type String
* @default "disabled"
*/
DISABLED_CLASSNAME: DISABLED,
/**
* The class name applied to dynamic tabs while loading.
* @property LOADING_CLASSNAME
* @type String
* @default "disabled"
*/
LOADING_CLASSNAME: 'loading',
/**
* Provides a reference to the connection request object when data is
* loaded dynamically.
* @property dataConnection
* @type Object
*/
dataConnection: null,
/**
* Object containing success and failure callbacks for loading data.
* @property loadHandler
* @type object
*/
loadHandler: null,
_loading: false,
/**
* Provides a readable name for the tab.
* @method toString
* @return String
*/
toString: function() {
var el = this.get(ELEMENT),
id = el.id || el.tagName;
return "Tab " + id;
},
/**
* setAttributeConfigs Tab specific properties.
* @method initAttributes
* @param {Object} attr Hash of initial attributes
*/
initAttributes: function(attr) {
attr = attr || {};
Tab.superclass.initAttributes.call(this, attr);
/**
* The event that triggers the tab's activation.
* @attribute activationEvent
* @type String
*/
this.setAttributeConfig('activationEvent', {
value: attr.activationEvent || 'click'
});
/**
* The element that contains the tab's label.
* @attribute labelEl
* @type HTMLElement
*/
this.setAttributeConfig(LABEL_EL, {
value: attr[LABEL_EL] || this._getLabelEl(),
method: function(value) {
value = Dom.get(value);
var current = this.get(LABEL_EL);
if (current) {
if (current == value) {
return false; // already set
}
current.parentNode.replaceChild(value, current);
this.set(LABEL, value.innerHTML);
}
}
});
/**
* The tab's label text (or innerHTML).
* @attribute label
* @type String
*/
this.setAttributeConfig(LABEL, {
value: attr.label || this._getLabel(),
method: function(value) {
var labelEl = this.get(LABEL_EL);
if (!labelEl) { // create if needed
this.set(LABEL_EL, this._createLabelEl());
}
labelEl.innerHTML = value;
}
});
/**
* The HTMLElement that contains the tab's content.
* @attribute contentEl
* @type HTMLElement
*/
this.setAttributeConfig(CONTENT_EL, {
value: attr[CONTENT_EL] || document.createElement('div'),
method: function(value) {
value = Dom.get(value);
var current = this.get(CONTENT_EL);
if (current) {
if (current === value) {
return false; // already set
}
if (!this.get('selected')) {
Dom.addClass(value, this.HIDDEN_CLASSNAME);
}
current.parentNode.replaceChild(value, current);
this.set(CONTENT, value.innerHTML);
}
}
});
/**
* The tab's content.
* @attribute content
* @type String
*/
this.setAttributeConfig(CONTENT, {
value: attr[CONTENT] || this.get(CONTENT_EL).innerHTML,
method: function(value) {
this.get(CONTENT_EL).innerHTML = value;
}
});
/**
* The tab's data source, used for loading content dynamically.
* @attribute dataSrc
* @type String
*/
this.setAttributeConfig(DATA_SRC, {
value: attr.dataSrc
});
/**
* Whether or not content should be reloaded for every view.
* @attribute cacheData
* @type Boolean
* @default false
*/
this.setAttributeConfig(CACHE_DATA, {
value: attr.cacheData || false,
validator: Lang.isBoolean
});
/**
* The method to use for the data request.
* @attribute loadMethod
* @type String
* @default "GET"
*/
this.setAttributeConfig(LOAD_METHOD, {
value: attr.loadMethod || 'GET',
validator: Lang.isString
});
/**
* Whether or not any data has been loaded from the server.
* @attribute dataLoaded
* @type Boolean
*/
this.setAttributeConfig(DATA_LOADED, {
value: false,
validator: Lang.isBoolean,
writeOnce: true
});
/**
* Number if milliseconds before aborting and calling failure handler.
* @attribute dataTimeout
* @type Number
* @default null
*/
this.setAttributeConfig(DATA_TIMEOUT, {
value: attr.dataTimeout || null,
validator: Lang.isNumber
});
/**
* Arguments to pass when POST method is used
* @attribute postData
* @default null
*/
this.setAttributeConfig(POST_DATA, {
value: attr.postData || null
});
/**
* Whether or not the tab is currently active.
* If a dataSrc is set for the tab, the content will be loaded from
* the given source.
* @attribute active
* @type Boolean
*/
this.setAttributeConfig('active', {
value: attr.active || this.hasClass(this.ACTIVE_CLASSNAME),
method: function(value) {
if (value === true) {
this.addClass(this.ACTIVE_CLASSNAME);
this.set('title', this.ACTIVE_TITLE);
} else {
this.removeClass(this.ACTIVE_CLASSNAME);
this.set('title', '');
}
},
validator: function(value) {
return Lang.isBoolean(value) && !this.get(DISABLED) ;
}
});
/**
* Whether or not the tab is disabled.
* @attribute disabled
* @type Boolean
*/
this.setAttributeConfig(DISABLED, {
value: attr.disabled || this.hasClass(this.DISABLED_CLASSNAME),
method: function(value) {
if (value === true) {
this.addClass(this.DISABLED_CLASSNAME);
} else {
this.removeClass(this.DISABLED_CLASSNAME);
}
},
validator: Lang.isBoolean
});
/**
* The href of the tab's anchor element.
* @attribute href
* @type String
* @default '#'
*/
this.setAttributeConfig('href', {
value: attr.href ||
this.getElementsByTagName('a')[0].getAttribute('href', 2) || '#',
method: function(value) {
this.getElementsByTagName('a')[0].href = value;
},
validator: Lang.isString
});
/**
* The Whether or not the tab's content is visible.
* @attribute contentVisible
* @type Boolean
* @default false
*/
this.setAttributeConfig('contentVisible', {
value: attr.contentVisible,
method: function(value) {
if (value) {
Dom.removeClass(this.get(CONTENT_EL), this.HIDDEN_CLASSNAME);
if ( this.get(DATA_SRC) ) {
// load dynamic content unless already loading or loaded and caching
if ( !this._loading && !(this.get(DATA_LOADED) && this.get(CACHE_DATA)) ) {
this._dataConnect();
}
}
} else {
Dom.addClass(this.get(CONTENT_EL), this.HIDDEN_CLASSNAME);
}
},
validator: Lang.isBoolean
});
},
_dataConnect: function() {
if (!Y.Connect) {
return false;
}
Dom.addClass(this.get(CONTENT_EL).parentNode, this.LOADING_CLASSNAME);
this._loading = true;
this.dataConnection = Y.Connect.asyncRequest(
this.get(LOAD_METHOD),
this.get(DATA_SRC),
{
success: function(o) {
this.loadHandler.success.call(this, o);
this.set(DATA_LOADED, true);
this.dataConnection = null;
Dom.removeClass(this.get(CONTENT_EL).parentNode,
this.LOADING_CLASSNAME);
this._loading = false;
},
failure: function(o) {
this.loadHandler.failure.call(this, o);
this.dataConnection = null;
Dom.removeClass(this.get(CONTENT_EL).parentNode,
this.LOADING_CLASSNAME);
this._loading = false;
},
scope: this,
timeout: this.get(DATA_TIMEOUT)
},
this.get(POST_DATA)
);
},
_createTabElement: function(attr) {
var el = document.createElement('li'),
a = document.createElement('a'),
label = attr.label || null,
labelEl = attr.labelEl || null;
a.href = attr.href || '#'; // TODO: Use Dom.setAttribute?
el.appendChild(a);
if (labelEl) { // user supplied labelEl
if (!label) { // user supplied label
label = this._getLabel();
}
} else {
labelEl = this._createLabelEl();
}
a.appendChild(labelEl);
return el;
},
_getLabelEl: function() {
return this.getElementsByTagName(this.LABEL_TAGNAME)[0];
},
_createLabelEl: function() {
var el = document.createElement(this.LABEL_TAGNAME);
return el;
},
_getLabel: function() {
var el = this.get(LABEL_EL);
if (!el) {
return undefined;
}
return el.innerHTML;
},
_onActivate: function(e, tabview) {
var tab = this,
silent = false;
Y.Event.preventDefault(e);
if (tab === tabview.get(ACTIVE_TAB)) {
silent = true; // dont fire activeTabChange if already active
}
tabview.set(ACTIVE_TAB, tab, silent);
},
_onActivationEventChange: function(e) {
var tab = this;
if (e.prevValue != e.newValue) {
tab.removeListener(e.prevValue, tab._onActivate);
tab.addListener(e.newValue, tab._onActivate, this, tab);
}
}
});
/**
* Fires when a tab is removed from the tabview
* @event remove
* @type CustomEvent
* @param {Event} An event object with fields for "type" ("remove")
* and "tabview" (the tabview instance it was removed from)
*/
YAHOO.widget.Tab = Tab;
})();
YAHOO.register("tabview", YAHOO.widget.TabView, {version: "2.9.0pr1", build: "2725"});
|
mit
|
EndzoneSoftware/CT-patternlib
|
vendor/pattern-lab/core/src/PatternLab/PatternData/Rule.php
|
5029
|
<?php
/*!
* Pattern Data Rule Class
*
* Copyright (c) 2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*
*/
namespace PatternLab\PatternData;
use \PatternLab\Timer;
class Rule {
protected $depthProp;
protected $extProp;
protected $isDirProp;
protected $isFileProp;
protected $searchProp;
protected $ignoreProp;
public function __construct($options) {
// nothing here yet
}
/**
* Test the Pattern Data Rules to see if a Rule matches the supplied values
* @param {Integer} the depth of the item
* @param {String} the extension of the item
* @param {Boolean} if the item is a directory
* @param {Boolean} if the item is a file
* @param {String} the name of the item
*
* @return {Boolean} whether the test was succesful or not
*/
public function test($depth, $ext, $isDir, $isFile, $name) {
if (($this->depthProp != 3) && ($depth != $this->depthProp)) {
return false;
}
if (($this->compareProp($ext,$this->extProp, true)) && ($isDir == $this->isDirProp) && ($isFile == $this->isFileProp)) {
$result = true;
if ($this->searchProp != "") {
$result = $this->compareProp($name,$this->searchProp);
}
if ($this->ignoreProp != "") {
$result = ($this->compareProp($name,$this->ignoreProp)) ? false : true;
}
return $result;
}
return false;
}
/**
* Compare the search and ignore props against the name.
* Can use && or || in the comparison
* @param {String} the name of the item
* @param {String} the value of the property to compare
*
* @return {Boolean} whether the compare was successful or not
*/
protected function compareProp($name, $propCompare, $exact = false) {
if (($name == "") && ($propCompare == "")) {
$result = true;
} else if ((($name == "") && ($propCompare != "")) || (($name != "") && ($propCompare == ""))) {
$result = false;
} else if (strpos($propCompare,"&&") !== false) {
$result = true;
$props = explode("&&",$propCompare);
foreach ($props as $prop) {
$pos = $this->testProp($name, $prop, $exact);
$result = ($result && $pos);
}
} else if (strpos($propCompare,"||") !== false) {
$result = false;
$props = explode("||",$propCompare);
foreach ($props as $prop) {
$pos = $this->testProp($name, $prop, $exact);
$result = ($result || $pos);
}
} else {
$result = $this->testProp($name, $propCompare, $exact);
}
return $result;
}
/**
* Get the name for a given pattern sans any possible digits used for reordering
* @param {String} the pattern based on the filesystem name
* @param {Boolean} whether or not to strip slashes from the pattern name
*
* @return {String} a lower-cased version of the pattern name
*/
protected function getPatternName($pattern, $clean = true) {
$patternBits = explode("-",$pattern,2);
$patternName = (((int)$patternBits[0] != 0) || ($patternBits[0] == '00')) ? $patternBits[1] : $pattern;
return ($clean) ? (str_replace("-"," ",$patternName)) : $patternName;
}
/**
* Get the value for a property on the current PatternData rule
* @param {String} the name of the property
*
* @return {Boolean} whether the set was successful
*/
public function getProp($propName) {
if (isset($this->$propName)) {
return $this->$propName;
}
return false;
}
/**
* Set a value for a property on the current PatternData rule
* @param {String} the name of the property
* @param {String} the value of the property
*
* @return {Boolean} whether the set was successful
*/
public function setProp($propName, $propValue) {
$this->$propName = $this->$propValue;
return true;
}
/**
* Test the given property
* @param {String} the value of the property to be tested
* @param {String} the value of the property to be tested against
* @param {Boolean} if this should be an exact match or just a string appearing in another
*
* @return {Boolean} the test result
*/
protected function testProp($propToTest, $propToTestAgainst, $beExact) {
if ($beExact) {
$result = ($propToTest === $propToTestAgainst);
} else {
$result = (strpos($propToTest,$propToTestAgainst) !== false) ? true : false;
}
return $result;
}
/**
* Update a property on a given rule
* @param {String} the name of the property
* @param {String} the value of the property
* @param {String} the action that should be taken with the new value
*
* @return {Boolean} whether the update was successful
*/
public function updateProp($propName, $propValue, $action = "or") {
if (!isset($this->$propName) || !is_scalar($propValue)) {
return false;
}
if ($action == "or") {
$propValue = $this->$propName."||".$propValue;
} else if ($action == "and") {
$propValue = $this->$propName."&&".$propValue;
}
return $this->setProp($this->$propName,$propValue);
}
}
|
mit
|
tonysneed/Experimental
|
vNext/VS2015/AspNet5/HelloAspNet5/src/HelloAspNet5.Web/Controllers/ValuesController.cs
|
539
|
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace HelloAspNet5.Web.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
static readonly List<string> Items = new List<string>
{
"value1", "value2", "value3"
};
[HttpGet]
public List<string> GetAll()
{
return Items;
}
}
}
|
mit
|
nothing628/manga-titan
|
app/Events/TagAdded.php
|
589
|
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Database\Eloquent\Model;
class TagAdded
{
use SerializesModels;
/** @var \Illuminate\Database\Eloquent\Model **/
public $model;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Model $model)
{
$this->model = $model;
}
}
|
mit
|
johan--/blynk-server
|
server/tcp-server/src/main/java/cc/blynk/server/handlers/app/logic/RefreshTokenLogic.java
|
1260
|
package cc.blynk.server.handlers.app.logic;
import cc.blynk.common.model.messages.Message;
import cc.blynk.server.dao.UserRegistry;
import cc.blynk.server.exceptions.NotAllowedException;
import cc.blynk.server.model.auth.User;
import io.netty.channel.ChannelHandlerContext;
import static cc.blynk.common.model.messages.MessageFactory.produce;
/**
* The Blynk Project.
* Created by Dmitriy Dumanskiy.
* Created on 2/1/2015.
*
*/
public class RefreshTokenLogic {
private final UserRegistry userRegistry;
public RefreshTokenLogic(UserRegistry userRegistry) {
this.userRegistry = userRegistry;
}
public void messageReceived(ChannelHandlerContext ctx, User user, Message message) {
String dashBoardIdString = message.body;
int dashBoardId;
try {
dashBoardId = Integer.parseInt(dashBoardIdString);
} catch (NumberFormatException ex) {
throw new NotAllowedException(String.format("Dash board id '%s' not valid.", dashBoardIdString), message.id);
}
user.getProfile().validateDashId(dashBoardId, message.id);
String token = userRegistry.refreshToken(user, dashBoardId);
ctx.writeAndFlush(produce(message.id, message.command, token));
}
}
|
mit
|
ericshortcut/IAL-002
|
src/aula5/Numeracao1A100.java
|
228
|
package aula5;
public class Numeracao1A100
{
public static void mostrarNumeros()
{
for (int i = 1; i <= 100; i++)
{
System.out.println(i);
}
}
public static void main(String ...strings)
{
mostrarNumeros();
}
}
|
mit
|
xtremeraceriv/OpenOBC
|
lib/SPI/SPI.cpp
|
4348
|
/*
Copyright (c) 2012 <benemorius@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "SPI.h"
#include <lpc17xx_pinsel.h>
#include <lpc17xx_clkpwr.h>
SPI::SPI(uint8_t mosiPort, uint8_t mosiPin, uint8_t misoPort, uint8_t misoPin, uint8_t sckPort, uint8_t sckPin, uint32_t clockRate)
{
this->mosiPort = mosiPort;
this->mosiPin = mosiPin;
this->misoPort = misoPort;
this->misoPin = misoPin;
this->sckPort = sckPort;
this->sckPin = sckPin;
this->clockRate = clockRate;
PINSEL_CFG_Type PinCfg;
if(mosiPort == 0 && mosiPin == 9)
{
PinCfg.Funcnum = 2;
this->peripheral = LPC_SSP1;
}
else if(mosiPort == 0 && mosiPin == 18)
{
PinCfg.Funcnum = 2;
this->peripheral = LPC_SSP0;
}
else if(mosiPort == 1 && mosiPin == 24)
{
PinCfg.Funcnum = 3;
this->peripheral = LPC_SSP0;
}
else
{
//invalid port/pin specified
while(1);
}
PinCfg.OpenDrain = PINSEL_PINMODE_NORMAL;
PinCfg.Pinmode = PINSEL_PINMODE_PULLUP;
PinCfg.Portnum = mosiPort;
PinCfg.Pinnum = mosiPin;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = misoPort;
PinCfg.Pinnum = misoPin;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = sckPort;
PinCfg.Pinnum = sckPin;
PINSEL_ConfigPin(&PinCfg);
// SSP Configuration structure variable
SSP_CFG_Type SSP_ConfigStruct;
// initialize SSP configuration structure to default
SSP_ConfigStructInit(&SSP_ConfigStruct);
SSP_ConfigStruct.CPHA = SSP_CPHA_FIRST; //TODO make these configurable
// SSP_ConfigStruct.CPHA = SSP_CPHA_SECOND;
SSP_ConfigStruct.CPOL = SSP_CPOL_HI;
// SSP_ConfigStruct.CPOL = SSP_CPOL_LO;
SSP_ConfigStruct.ClockRate = this->clockRate;
// SSP_ConfigStruct.DataOrder = SPI_DATA_MSB_FIRST;
SSP_ConfigStruct.Databit = SSP_DATABIT_8;
SSP_ConfigStruct.Mode = SSP_MASTER_MODE;
// Initialize SSP peripheral with parameter given in structure above
SSP_Init(this->peripheral, &SSP_ConfigStruct);
// Enable SSP peripheral
SSP_Cmd(this->peripheral, ENABLE);
}
void SPI::setClockRate(uint32_t hz)
{
if(hz == this->clockRate)
return;
this->clockRate = hz;
CLKPWR_SetPCLKDiv(CLKPWR_PCLKSEL_SSP1, CLKPWR_PCLKSEL_CCLK_DIV_1);
SSP_CFG_Type SSP_ConfigStruct;
SSP_ConfigStructInit(&SSP_ConfigStruct);
SSP_ConfigStruct.CPHA = SSP_CPHA_FIRST; //TODO make these configurable
SSP_ConfigStruct.CPOL = SSP_CPOL_HI;
SSP_ConfigStruct.ClockRate = this->clockRate;
SSP_ConfigStruct.Databit = SSP_DATABIT_8;
SSP_ConfigStruct.Mode = SSP_MASTER_MODE;
SSP_Init(this->peripheral, &SSP_ConfigStruct);
SSP_Cmd(this->peripheral, ENABLE);
}
void SPI::setPullup(bool isEnabled)
{
PINSEL_CFG_Type PinCfg;
if(mosiPort == 0 && mosiPin == 9)
PinCfg.Funcnum = 2;
else if(mosiPort == 0 && mosiPin == 18)
PinCfg.Funcnum = 2;
else if(mosiPort == 1 && mosiPin == 24)
PinCfg.Funcnum = 3;
else //invalid port/pin specified
while(1);
PinCfg.OpenDrain = PINSEL_PINMODE_NORMAL;
PinCfg.Pinmode = isEnabled ? PINSEL_PINMODE_PULLUP : PINSEL_PINMODE_TRISTATE;
PinCfg.Portnum = misoPort;
PinCfg.Pinnum = misoPin;
PINSEL_ConfigPin(&PinCfg);
}
uint8_t SPI::readWrite(uint8_t writeByte)
{
uint8_t readByte;
SSP_DATA_SETUP_Type xferConfig;
xferConfig.tx_data = &writeByte;
xferConfig.rx_data = &readByte;
xferConfig.length = 1;
SSP_ReadWrite(this->peripheral, &xferConfig, SSP_TRANSFER_POLLING);
return readByte;
}
|
mit
|
IOCoin/iocoin
|
src/qt/locale/bitcoin_en.ts
|
122293
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About I/OCoin</source>
<translation>About I/OCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>I/OCoin</b> version</source>
<translation><b>I/OCoin</b> version</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The I/OCoin developers</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Address Book</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Double-click to edit address or label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Create a new address</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copy the currently selected address to the system clipboard</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&New Address</translation>
</message>
<message>
<location line="-46"/>
<source>These are your I/OCoin 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>These are your I/OCoin 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.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Copy Address</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Show &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a I/OCoin address</source>
<translation>Sign a message to prove you own a I/OCoin address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation></translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation></translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified I/OCoin address</source>
<translation>Verify a message to ensure it was signed with a specified I/OCoin address</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Delete</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copy &Label</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Edit</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Export Address Book Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(no label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrase Dialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enter passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>New passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repeat new passphrase</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Encrypt wallet</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>This operation needs your wallet passphrase to unlock the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Unlock wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>This operation needs your wallet passphrase to decrypt the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Change passphrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enter the old and new passphrase to the wallet.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirm wallet encryption</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Are you sure you wish to encrypt your wallet?</translation>
</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></translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warning: The Caps Lock key is on!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Wallet encrypted</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+82"/>
<source>I/OCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>I/OCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Wallet encryption failed</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>The supplied passphrases do not match.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Wallet unlock failed</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>The passphrase entered for the wallet decryption was incorrect.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Wallet decryption failed</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Wallet passphrase was successfully changed.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation>Sign &message...</translation>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>Synchronizing with network...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>&Overview</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Show general overview of wallet</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Browse transaction history</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Address Book</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edit the list of stored addresses and labels</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Receive coins</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Show the list of addresses for receiving payments</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&Send coins</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>E&xit</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quit application</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about I/OCoin</source>
<translation>Show information about I/OCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>About &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Show information about Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Encrypt Wallet...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup Wallet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Change Passphrase...</translation>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation>
<numerusform>~%n block remaining</numerusform>
<numerusform>~%n blocks remaining</numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Downloaded %1 of %2 blocks of transaction history (%3% done).</translation>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation>&Export...</translation>
</message>
<message>
<location line="-62"/>
<source>Send coins to a I/OCoin address</source>
<translation>Send coins to a I/OCoin address</translation>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for I/OCoin</source>
<translation>Modify configuration options for I/OCoin</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Encrypt or decrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Backup wallet to another location</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Change the passphrase used for wallet encryption</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Debug window</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging and diagnostic console</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verify message...</translation>
</message>
<message>
<location line="-200"/>
<source>I/OCoin</source>
<translation>I/OCoin</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+178"/>
<source>&About I/OCoin</source>
<translation>&About I/OCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Show / Hide</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished">Unlock wallet</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Settings</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tabs toolbar</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Actions toolbar</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>I/OCoin client</source>
<translation>I/OCoin client</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to I/OCoin network</source>
<translation>
<numerusform>%n active connection to I/OCoin network</numerusform>
<numerusform>%n active connections to I/OCoin network</numerusform>
</translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Downloaded %1 blocks of transaction history.</translation>
</message>
<message>
<location line="+427"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation></translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation></translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation></translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation></translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation></translation>
</message>
<message numerus="yes">
<location line="-417"/>
<source>%n second(s) ago</source>
<translation>
<numerusform>%n second ago</numerusform>
<numerusform>%n seconds ago</numerusform>
</translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation></translation>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation>
<numerusform>%n minute ago</numerusform>
<numerusform>%n minutes ago</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation>
<numerusform>%n hour ago</numerusform>
<numerusform>%n hours ago</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation>
<numerusform>%n day ago</numerusform>
<numerusform>%n days ago</numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Up to date</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Catching up...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Last received block was generated %1.</translation>
</message>
<message>
<location line="+59"/>
<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></translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Confirm transaction fee</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Sent transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Incoming transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date: %1
Amount: %2
Type: %3
Address: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI handling</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid I/OCoin address or malformed URI parameters.</source>
<translation>URI can not be parsed! This can be caused by an invalid I/OCoin address or malformed URI parameters.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>unlocked</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>locked</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Backup Wallet</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Wallet Data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup Failed</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>There was an error trying to save the wallet data to the new location.</translation>
</message>
<message numerus="yes">
<location line="+90"/>
<source>%n second(s)</source>
<translation>
<numerusform>%n second</numerusform>
<numerusform>%n seconds</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation>
<numerusform>%n minute</numerusform>
<numerusform>%n minutes</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation>
<numerusform>%n hour</numerusform>
<numerusform>%n hours</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation>
<numerusform>%n day</numerusform>
<numerusform>%n days</numerusform>
</translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. I/OCoin can no longer continue safely and will quit.</source>
<translation>A fatal error occurred. I/OCoin can no longer continue safely and will quit.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+98"/>
<source>Network Alert</source>
<translation>Network Alert</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished">Amount:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished">Amount</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished">Label</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation type="unfinished">Address</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished">Date</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished">Confirmed</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished">Copy address</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished">Copy label</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished">Copy amount</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished">Copy transaction ID</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation></translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation></translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished">(no label)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Edit Address</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>The label associated with this address book entry</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Address</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>The address associated with this address book entry. This can only be modified for sending addresses.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>New receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>New sending address</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Edit receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Edit sending address</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>The entered address "%1" is already in the address book.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid I/OCoin address.</source>
<translation>The entered address "%1" is not a valid I/OCoin address.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Could not unlock wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>New key generation failed.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>I/OCoin-Qt</source>
<translation>I/OCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>command-line options</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI options</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Set language, for example "de_DE" (default: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimized</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Show splash screen on startup (default: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Main</translation>
</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. Fee 0.01 recommended.</source>
<translation>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pay transaction &fee</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation></translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation></translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start I/OCoin after logging in to the system.</source>
<translation>Automatically start I/OCoin after logging in to the system.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start I/OCoin on system login</source>
<translation>&Start I/OCoin on system login</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Network</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the I/OCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatically open the I/OCoin client port on the router. This only works when your router supports UPnP and it is enabled.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Map port using &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the I/OCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connect to the I/OCoin network through a SOCKS proxy (e.g. when connecting through Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connect through SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP address of the proxy (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port of the proxy (e.g. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS version of the proxy (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Show only a tray icon after minimizing the window.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimize to the tray instead of the taskbar</translation>
</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>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.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimize on close</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Display</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>User Interface &language:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting I/OCoin.</source>
<translation>The user interface language can be set here. This setting will take effect after restarting I/OCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit to show amounts in:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show I/OCoin addresses in the transaction list or not.</source>
<translation>Whether to show I/OCoin addresses in the transaction list or not.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Display addresses in transaction list</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation></translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation></translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancel</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apply</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>default</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting I/OCoin.</source>
<translation>This setting will take effect after restarting I/OCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>The supplied proxy address is invalid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the I/OCoin network after a connection is established, but this process has not completed yet.</source>
<translation>The displayed information may be out of date. Your wallet automatically synchronizes with the I/OCoin network after a connection is established, but this process has not completed yet.</translation>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unconfirmed:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Immature:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Mined balance that has not yet matured</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recent transactions</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Total of coins that was staked, and do not yet count toward the current balance</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>out of sync</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Request Payment</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Amount:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Save As...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error encoding URI into QR Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>The entered amount is invalid, please check.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulting URI too long, try to reduce the text for label / message.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Save QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Images (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Client name</translation>
</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="+348"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Client version</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Using OpenSSL version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startup time</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Network</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Number of connections</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>On testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Current number of blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimated total blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Last block time</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Command-line options</translation>
</message>
<message>
<location line="+7"/>
<source>Show the I/OCoin-Qt help message to get a list with possible I/OCoin command-line options.</source>
<translation>Show the I/OCoin-Qt help message to get a list with possible I/OCoin command-line options.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Build date</translation>
</message>
<message>
<location line="-104"/>
<source>I/OCoin - Debug window</source>
<translation>I/OCoin - Debug window</translation>
</message>
<message>
<location line="+25"/>
<source>I/OCoin Core</source>
<translation>I/OCoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug log file</translation>
</message>
<message>
<location line="+7"/>
<source>Open the I/OCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open the I/OCoin debug log file from the current data directory. This can take a few seconds for large log files.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Clear console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the I/OCoin RPC console.</source>
<translation>Welcome to the I/OCoin RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Type <b>help</b> for an overview of available commands.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished">Amount:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 I/O</source>
<translation type="unfinished">123.456 I/O {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Send to multiple recipients at once</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remove all transaction fields</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 I/O</source>
<translation>123.456 I/O</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirm the send action</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copy amount</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation></translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirm send coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Are you sure you want to send %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> and </translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>The recipient address is not valid, please recheck.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>The amount to pay must be larger than 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>The amount exceeds your balance.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>The total exceeds your balance when the %1 transaction fee is included.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplicate address found, can only send to each address once per send operation.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Error: Transaction creation failed.</translation>
</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>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.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid I/OCoin address</source>
<translation></translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished">(no label)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation></translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&mount:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Pay &To:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Enter a label for this address to add it to your address book</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation></translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Choose address from address book</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Remove this recipient</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Sign / Verify a Message</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Sign Message</translation>
</message>
<message>
<location line="-118"/>
<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>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.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation>The address to sign the message with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Choose an address from the address book</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Enter the message you want to sign here</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copy the current signature to the system clipboard</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this I/OCoin address</source>
<translation>Sign the message to prove you own this I/OCoin address</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Reset all sign message fields</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="-64"/>
<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>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.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation>The address the message was signed with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified I/OCoin address</source>
<translation>Verify the message to ensure it was signed with the specified I/OCoin address</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Reset all verify message fields</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Sign Message" to generate signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter I/OCoin signature</source>
<translation>Enter I/OCoin signature</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>The entered address is invalid.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Please check the address and try again.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>The entered address does not refer to a key.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet unlock was cancelled.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Private key for the entered address is not available.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Message signing failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Message signed.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>The signature could not be decoded.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Please check the signature and try again.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>The signature did not match the message digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Message verification failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message verified.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation></translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unconfirmed</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, broadcast through %n node</numerusform>
<numerusform>, broadcast through %n nodes</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generated</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>From</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>To</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>own address</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>matures in %n more block</numerusform>
<numerusform>matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>not accepted</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net amount</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comment</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaction ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 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>Generated coins must mature 110 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.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, has not been successfully broadcast yet</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished">
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+71"/>
<source>unknown</source>
<translation>unknown</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaction details</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>This pane shows a detailed description of the transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+230"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmed (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation></translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation></translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation></translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation></translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation></translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>This block was not received by any other nodes and will probably not be accepted!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generated but not accepted</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Received from</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Payment to yourself</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaction status. Hover over this field to show number of confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date and time that the transaction was received.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Destination address of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Amount removed from or added to balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>All</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Today</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>This week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>This month</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Last month</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>This year</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Range...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>To yourself</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Enter address or label to search</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min amount</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copy address</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copy label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copy amount</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copy transaction ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edit label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Show transaction details</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Export Transaction Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmed</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Range:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>to</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+219"/>
<source>Sending...</source>
<translation>Sending...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>I/OCoin version</source>
<translation>I/OCoin version</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or iocoind</source>
<translation>Send command to -server or iocoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>List commands</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Get help for a command</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Options:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: iocoin.conf)</source>
<translation>Specify configuration file (default: iocoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: iocoind.pid)</source>
<translation>Specify pid file (default: iocoind.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Specify wallet file (within data directory)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specify data directory</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Set database cache size in megabytes (default: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Set database disk log size in megabytes (default: 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Listen for connections on <port> (default: 15714 or testnet: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maintain at most <n> connections to peers (default: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Connect to a node to retrieve peer addresses, and disconnect</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Specify your own public address</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Bind to given address. Use [host]:port notation for IPv6</translation>
</message>
<message>
<location line="+6"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Threshold for disconnecting misbehaving peers (default: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</translation>
</message>
<message>
<location line="-43"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation></translation>
</message>
<message>
<location line="+157"/>
<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></translation>
</message>
<message>
<location line="-5"/>
<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></translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation></translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accept command line and JSON-RPC commands</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation></translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation></translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation></translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Run in the background as a daemon and accept commands</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Use the test network</translation>
</message>
<message>
<location line="-21"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation></translation>
</message>
<message>
<location line="+115"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation></translation>
</message>
<message>
<location line="-21"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong I/OCoin will not work properly.</source>
<translation>Warning: Please check that your computer's date and time are correct! If your clock is wrong I/OCoin will not work properly.</translation>
</message>
<message>
<location line="-30"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation>
</message>
<message>
<location line="-18"/>
<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>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.</translation>
</message>
<message>
<location line="-31"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Attempt to recover private keys from a corrupt wallet.dat</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Block creation options:</translation>
</message>
<message>
<location line="-59"/>
<source>Connect only to the specified node(s)</source>
<translation>Connect only to the specified node(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Discover own IP address (default: 1 when listening and no -externalip)</translation>
</message>
<message>
<location line="+92"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Failed to listen on any port. Use -listen=0 if you want this.</translation>
</message>
<message>
<location line="-88"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Find peers using DNS lookup (default: 1)</translation>
</message>
<message>
<location line="+4"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Sync checkpoints policy (default: strict)</translation>
</message>
<message>
<location line="+82"/>
<source>Invalid -tor address: '%s'</source>
<translation>Invalid -tor address: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation></translation>
</message>
<message>
<location line="-81"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</translation>
</message>
<message>
<location line="-15"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+25"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output extra debugging information. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output extra network debugging information</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Prepend debug output with timestamp</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="-71"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Select the version of socks proxy to use (4-5, default: 5)</translation>
</message>
<message>
<location line="+38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send trace/debug info to console instead of debug.log file</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send trace/debug info to debugger</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Set maximum block size in bytes (default: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Set minimum block size in bytes (default: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation>
</message>
<message>
<location line="-39"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specify connection timeout in milliseconds (default: 5000)</translation>
</message>
<message>
<location line="+107"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation></translation>
</message>
<message>
<location line="-79"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Use UPnP to map the listening port (default: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Use UPnP to map the listening port (default: 1 when listening)</translation>
</message>
<message>
<location line="-24"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Use proxy to reach tor hidden services (default: same as -proxy)</translation>
</message>
<message>
<location line="+39"/>
<source>Username for JSON-RPC connections</source>
<translation>Username for JSON-RPC connections</translation>
</message>
<message>
<location line="+48"/>
<source>Verifying database integrity...</source>
<translation></translation>
</message>
<message>
<location line="+56"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Warning: Disk space is low!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warning: This version is obsolete, upgrade required!</translation>
</message>
<message>
<location line="-47"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation></translation>
</message>
<message>
<location line="-55"/>
<source>Password for JSON-RPC connections</source>
<translation>Password for JSON-RPC connections</translation>
</message>
<message>
<location line="-81"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=iocoinrpc
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 "I/OCoin Alert" admin@foo.com
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished">Find peers using internet relay chat (default: 1) {0)?}</translation>
</message>
<message>
<location line="+4"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation></translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Allow JSON-RPC connections from specified IP address</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send commands to node running on <ip> (default: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation></translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation></translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Upgrade wallet to latest format</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Set key pool size to <n> (default: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescan the block chain for missing wallet transactions</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>How many blocks to check at startup (default: 2500, 0 = all)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>How thorough the block verification is (0-6, default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Imports blocks from external blk000?.dat file</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Use OpenSSL (https) for JSON-RPC connections</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Server certificate file (default: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private key (default: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. I/OCoin is shutting down.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+45"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation></translation>
</message>
<message>
<location line="-155"/>
<source>This help message</source>
<translation>This help message</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Wallet %s resides outside data directory %s.</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. I/OCoin is probably already running.</source>
<translation>Cannot obtain a lock on data directory %s. I/OCoin is probably already running.</translation>
</message>
<message>
<location line="-96"/>
<source>I/OCoin</source>
<translation>I/OCoin</translation>
</message>
<message>
<location line="+137"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Unable to bind to %s on this computer (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-127"/>
<source>Connect through socks proxy</source>
<translation>Connect through socks proxy</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Allow DNS lookups for -addnode, -seednode and -connect</translation>
</message>
<message>
<location line="+119"/>
<source>Loading addresses...</source>
<translation>Loading addresses...</translation>
</message>
<message>
<location line="-14"/>
<source>Error loading blkindex.dat</source>
<translation>Error loading blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error loading wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of I/OCoin</source>
<translation>Error loading wallet.dat: Wallet requires newer version of I/OCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart I/OCoin to complete</source>
<translation>Wallet needed to be rewritten: restart I/OCoin to complete</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Error loading wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Invalid -proxy address: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unknown network specified in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unknown -socks proxy version requested: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Cannot resolve -bind address: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Cannot resolve -externalip address: '%s'</translation>
</message>
<message>
<location line="-25"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Error: could not start node</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Sending...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Invalid amount</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Insufficient funds</translation>
</message>
<message>
<location line="-33"/>
<source>Loading block index...</source>
<translation>Loading block index...</translation>
</message>
<message>
<location line="-101"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Add a node to connect to and attempt to keep the connection open</translation>
</message>
<message>
<location line="+119"/>
<source>Unable to bind to %s on this computer. I/OCoin is probably already running.</source>
<translation>Unable to bind to %s on this computer. I/OCoin is probably already running.</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Fee per KB to add to transactions you send</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation></translation>
</message>
<message>
<location line="+26"/>
<source>Loading wallet...</source>
<translation>Loading wallet...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Cannot downgrade wallet</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Cannot write default address</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Rescanning...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Done loading</translation>
</message>
<message>
<location line="-164"/>
<source>To use the %s option</source>
<translation>To use the %s option</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+6"/>
<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>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</translation>
</message>
</context>
</TS>
|
mit
|
peastman/deepchem
|
deepchem/models/tests/test_torch_model.py
|
14787
|
import os
import pytest
import deepchem as dc
import numpy as np
import math
import unittest
try:
import torch
import torch.nn.functional as F
has_pytorch = True
except:
has_pytorch = False
try:
import wandb
has_wandb = True
except:
has_wandb = False
@pytest.mark.torch
def test_overfit_subclass_model():
"""Test fitting a TorchModel defined by subclassing Module."""
n_data_points = 10
n_features = 2
np.random.seed(1234)
X = np.random.rand(n_data_points, n_features)
y = (X[:, 0] > X[:, 1]).astype(np.float32)
dataset = dc.data.NumpyDataset(X, y)
class ExampleModel(torch.nn.Module):
def __init__(self, layer_sizes):
super(ExampleModel, self).__init__()
self.layers = torch.nn.ModuleList()
in_size = n_features
for out_size in layer_sizes:
self.layers.append(torch.nn.Linear(in_size, out_size))
in_size = out_size
def forward(self, x):
for i, layer in enumerate(self.layers):
x = layer(x)
if i < len(self.layers) - 1:
x = F.relu(x)
return torch.sigmoid(x), x
pytorch_model = ExampleModel([10, 1])
model = dc.models.TorchModel(
pytorch_model,
dc.models.losses.SigmoidCrossEntropy(),
output_types=['prediction', 'loss'],
learning_rate=0.005)
model.fit(dataset, nb_epoch=1000)
prediction = np.squeeze(model.predict_on_batch(X))
assert np.array_equal(y, np.round(prediction))
metric = dc.metrics.Metric(dc.metrics.roc_auc_score)
scores = model.evaluate(dataset, [metric])
assert scores[metric.name] > 0.9
@pytest.mark.torch
def test_overfit_sequential_model():
"""Test fitting a TorchModel defined as a sequential model."""
n_data_points = 10
n_features = 2
X = np.random.rand(n_data_points, n_features)
y = (X[:, 0] > X[:, 1]).astype(np.float32)
dataset = dc.data.NumpyDataset(X, y)
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(2, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1),
torch.nn.Sigmoid())
model = dc.models.TorchModel(
pytorch_model, dc.models.losses.BinaryCrossEntropy(), learning_rate=0.005)
model.fit(dataset, nb_epoch=1000)
prediction = np.squeeze(model.predict_on_batch(X))
assert np.array_equal(y, np.round(prediction))
metric = dc.metrics.Metric(dc.metrics.roc_auc_score)
generator = model.default_generator(dataset, pad_batches=False)
scores = model.evaluate_generator(generator, [metric])
assert scores[metric.name] > 0.9
@pytest.mark.torch
def test_fit_use_all_losses():
"""Test fitting a TorchModel and getting a loss curve back."""
n_data_points = 10
n_features = 2
X = np.random.rand(n_data_points, n_features)
y = (X[:, 0] > X[:, 1]).astype(np.float32)
dataset = dc.data.NumpyDataset(X, y)
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(2, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1),
torch.nn.Sigmoid())
model = dc.models.TorchModel(
pytorch_model,
dc.models.losses.BinaryCrossEntropy(),
learning_rate=0.005,
log_frequency=10)
losses = []
model.fit(dataset, nb_epoch=1000, all_losses=losses)
# Each epoch is a single step for this model
assert len(losses) == 100
assert np.count_nonzero(np.array(losses)) == 100
@pytest.mark.torch
def test_fit_on_batch():
"""Test fitting a TorchModel to individual batches."""
n_data_points = 10
n_features = 2
X = np.random.rand(n_data_points, n_features)
y = (X[:, 0] > X[:, 1]).astype(np.float32)
dataset = dc.data.NumpyDataset(X, y)
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(2, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1),
torch.nn.Sigmoid())
model = dc.models.TorchModel(
pytorch_model, dc.models.losses.BinaryCrossEntropy(), learning_rate=0.005)
i = 0
for X, y, w, ids in dataset.iterbatches(model.batch_size, 500):
i += 1
model.fit_on_batch(X, y, w, checkpoint=False)
prediction = np.squeeze(model.predict_on_batch(X))
assert np.array_equal(y, np.round(prediction))
metric = dc.metrics.Metric(dc.metrics.roc_auc_score)
generator = model.default_generator(dataset, pad_batches=False)
scores = model.evaluate_generator(generator, [metric])
assert scores[metric.name] > 0.9
@pytest.mark.torch
def test_checkpointing():
"""Test loading and saving checkpoints with TorchModel."""
# Create two models using the same model directory.
pytorch_model1 = torch.nn.Sequential(torch.nn.Linear(5, 10))
pytorch_model2 = torch.nn.Sequential(torch.nn.Linear(5, 10))
model1 = dc.models.TorchModel(pytorch_model1, dc.models.losses.L2Loss())
model2 = dc.models.TorchModel(
pytorch_model2, dc.models.losses.L2Loss(), model_dir=model1.model_dir)
# Check that they produce different results.
X = np.random.rand(5, 5)
y1 = model1.predict_on_batch(X)
y2 = model2.predict_on_batch(X)
assert not np.array_equal(y1, y2)
# Save a checkpoint from the first model and load it into the second one,
# and make sure they now match.
model1.save_checkpoint()
model2.restore()
y3 = model1.predict_on_batch(X)
y4 = model2.predict_on_batch(X)
assert np.array_equal(y1, y3)
assert np.array_equal(y1, y4)
@pytest.mark.torch
def test_fit_restore():
"""Test specifying restore=True when calling fit()."""
n_data_points = 10
n_features = 2
X = np.random.rand(n_data_points, n_features)
y = (X[:, 0] > X[:, 1]).astype(np.float32)
dataset = dc.data.NumpyDataset(X, y)
# Train a model to overfit the dataset.
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(2, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1),
torch.nn.Sigmoid())
model = dc.models.TorchModel(
pytorch_model, dc.models.losses.BinaryCrossEntropy(), learning_rate=0.005)
model.fit(dataset, nb_epoch=1000)
prediction = np.squeeze(model.predict_on_batch(X))
assert np.array_equal(y, np.round(prediction))
# Create an identical model, do a single step of fitting with restore=True,
# and make sure it got restored correctly.
pytorch_model2 = torch.nn.Sequential(
torch.nn.Linear(2, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1),
torch.nn.Sigmoid())
model2 = dc.models.TorchModel(
pytorch_model2,
dc.models.losses.BinaryCrossEntropy(),
model_dir=model.model_dir)
model2.fit(dataset, nb_epoch=1, restore=True)
prediction = np.squeeze(model2.predict_on_batch(X))
assert np.array_equal(y, np.round(prediction))
@pytest.mark.torch
def test_uncertainty():
"""Test estimating uncertainty a TorchModel."""
n_samples = 30
n_features = 1
noise = 0.1
X = np.random.rand(n_samples, n_features)
y = (10 * X + np.random.normal(scale=noise, size=(n_samples, n_features)))
dataset = dc.data.NumpyDataset(X, y)
# Build a model that predicts uncertainty.
class PyTorchUncertainty(torch.nn.Module):
def __init__(self):
super(PyTorchUncertainty, self).__init__()
self.hidden = torch.nn.Linear(n_features, 200)
self.output = torch.nn.Linear(200, n_features)
self.log_var = torch.nn.Linear(200, n_features)
def forward(self, inputs):
x, use_dropout = inputs
x = self.hidden(x)
if use_dropout:
x = F.dropout(x, 0.1)
output = self.output(x)
log_var = self.log_var(x)
var = torch.exp(log_var)
return (output, var, output, log_var)
def loss(outputs, labels, weights):
diff = labels[0] - outputs[0]
log_var = outputs[1]
var = torch.exp(log_var)
return torch.mean(diff * diff / var + log_var)
class UncertaintyModel(dc.models.TorchModel):
def default_generator(self,
dataset,
epochs=1,
mode='fit',
deterministic=True,
pad_batches=True):
for epoch in range(epochs):
for (X_b, y_b, w_b, ids_b) in dataset.iterbatches(
batch_size=self.batch_size,
deterministic=deterministic,
pad_batches=pad_batches):
if mode == 'predict':
dropout = np.array(False)
else:
dropout = np.array(True)
yield ([X_b, dropout], [y_b], [w_b])
pytorch_model = PyTorchUncertainty()
model = UncertaintyModel(
pytorch_model,
loss,
output_types=['prediction', 'variance', 'loss', 'loss'],
learning_rate=0.003)
# Fit the model and see if its predictions are correct.
model.fit(dataset, nb_epoch=2500)
pred, std = model.predict_uncertainty(dataset)
assert np.mean(np.abs(y - pred)) < 1.0
assert noise < np.mean(std) < 1.0
@pytest.mark.torch
def test_saliency_mapping():
"""Test computing a saliency map."""
n_tasks = 3
n_features = 5
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(n_features, 20), torch.nn.Tanh(),
torch.nn.Linear(20, n_tasks))
model = dc.models.TorchModel(pytorch_model, dc.models.losses.L2Loss())
x = np.random.random(n_features)
s = model.compute_saliency(x)
assert s.shape[0] == n_tasks
assert s.shape[1] == n_features
# Take a tiny step in the direction of s and see if the output changes by
# the expected amount.
delta = 0.01
for task in range(n_tasks):
norm = np.sqrt(np.sum(s[task]**2))
step = 0.5 * delta / norm
pred1 = model.predict_on_batch((x + s[task] * step).reshape(
(1, n_features))).flatten()
pred2 = model.predict_on_batch((x - s[task] * step).reshape(
(1, n_features))).flatten()
assert np.allclose(pred1[task], (pred2 + norm * delta)[task], atol=1e-6)
@pytest.mark.torch
def test_saliency_shapes():
"""Test computing saliency maps for multiple outputs with multiple dimensions."""
class SaliencyModel(torch.nn.Module):
def __init__(self):
super(SaliencyModel, self).__init__()
self.layer1 = torch.nn.Linear(6, 4)
self.layer2 = torch.nn.Linear(6, 5)
def forward(self, x):
x = torch.flatten(x)
output1 = self.layer1(x).reshape(1, 4, 1)
output2 = self.layer2(x).reshape(1, 1, 5)
return output1, output2
pytorch_model = SaliencyModel()
model = dc.models.TorchModel(pytorch_model, dc.models.losses.L2Loss())
x = np.random.random((2, 3))
s = model.compute_saliency(x)
assert len(s) == 2
assert s[0].shape == (4, 1, 2, 3)
assert s[1].shape == (1, 5, 2, 3)
@pytest.mark.torch
def test_tensorboard():
"""Test logging to Tensorboard."""
n_data_points = 20
n_features = 2
X = np.random.rand(n_data_points, n_features)
y = [[0.0, 1.0] for x in range(n_data_points)]
dataset = dc.data.NumpyDataset(X, y)
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(n_features, 2), torch.nn.Softmax(dim=1))
model = dc.models.TorchModel(
pytorch_model,
dc.models.losses.CategoricalCrossEntropy(),
tensorboard=True,
log_frequency=1)
model.fit(dataset, nb_epoch=10)
files_in_dir = os.listdir(model.model_dir)
event_file = list(filter(lambda x: x.startswith("events"), files_in_dir))
assert len(event_file) > 0
event_file = os.path.join(model.model_dir, event_file[0])
file_size = os.stat(event_file).st_size
assert file_size > 0
@pytest.mark.torch
@unittest.skipIf((not has_pytorch) or (not has_wandb),
'PyTorch and/or Wandb is not installed')
def test_wandblogger():
"""Test logging to Weights & Biases."""
# Load dataset and Models
tasks, datasets, transformers = dc.molnet.load_delaney(
featurizer='ECFP', splitter='random')
train_dataset, valid_dataset, test_dataset = datasets
metric = dc.metrics.Metric(dc.metrics.pearson_r2_score)
wandblogger = dc.models.WandbLogger(anonymous="allow", save_run_history=True)
pytorch_model = torch.nn.Sequential(
torch.nn.Linear(1024, 1000),
torch.nn.Dropout(p=0.5),
torch.nn.Linear(1000, 1))
model = dc.models.TorchModel(
pytorch_model, dc.models.losses.L2Loss(), wandb_logger=wandblogger)
vc_train = dc.models.ValidationCallback(train_dataset, 1, [metric])
vc_valid = dc.models.ValidationCallback(valid_dataset, 1, [metric])
model.fit(train_dataset, nb_epoch=10, callbacks=[vc_train, vc_valid])
# call model.fit again to test multiple fit() calls
model.fit(train_dataset, nb_epoch=10, callbacks=[vc_train, vc_valid])
wandblogger.finish()
run_data = wandblogger.run_history
valid_score = model.evaluate(valid_dataset, [metric], transformers)
assert math.isclose(
valid_score["pearson_r2_score"],
run_data['eval/pearson_r2_score_(1)'],
abs_tol=0.0005)
@pytest.mark.torch
def test_fit_variables():
"""Test training a subset of the variables in a model."""
class VarModel(torch.nn.Module):
def __init__(self, **kwargs):
super(VarModel, self).__init__(**kwargs)
self.var1 = torch.nn.Parameter(torch.Tensor([0.5]))
self.var2 = torch.nn.Parameter(torch.Tensor([0.5]))
def forward(self, inputs):
return [self.var1, self.var2]
def loss(outputs, labels, weights):
return (outputs[0] * outputs[1] - labels[0])**2
pytorch_model = VarModel()
model = dc.models.TorchModel(pytorch_model, loss, learning_rate=0.02)
x = np.ones((1, 1))
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 0.5)
assert np.allclose(vars[1], 0.5)
model.fit_generator([(x, x, x)] * 300)
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 1.0)
assert np.allclose(vars[1], 1.0)
model.fit_generator([(x, 2 * x, x)] * 300, variables=[pytorch_model.var1])
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 2.0)
assert np.allclose(vars[1], 1.0)
model.fit_generator([(x, x, x)] * 300, variables=[pytorch_model.var2])
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 2.0)
assert np.allclose(vars[1], 0.5)
@pytest.mark.torch
def test_fit_loss():
"""Test specifying a different loss function when calling fit()."""
class VarModel(torch.nn.Module):
def __init__(self):
super(VarModel, self).__init__()
self.var1 = torch.nn.Parameter(torch.Tensor([0.5]))
self.var2 = torch.nn.Parameter(torch.Tensor([0.5]))
def forward(self, inputs):
return [self.var1, self.var2]
def loss1(outputs, labels, weights):
return (outputs[0] * outputs[1] - labels[0])**2
def loss2(outputs, labels, weights):
return (outputs[0] + outputs[1] - labels[0])**2
pytorch_model = VarModel()
model = dc.models.TorchModel(pytorch_model, loss1, learning_rate=0.01)
x = np.ones((1, 1))
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 0.5)
assert np.allclose(vars[1], 0.5)
model.fit_generator([(x, x, x)] * 300)
vars = model.predict_on_batch(x)
assert np.allclose(vars[0], 1.0)
assert np.allclose(vars[1], 1.0)
model.fit_generator([(x, 3 * x, x)] * 300, loss=loss2)
vars = model.predict_on_batch(x)
assert np.allclose(vars[0] + vars[1], 3.0)
|
mit
|
goncalvesjoao/react-to-commonJS
|
boilerplates/basic/spa/js/routes.js
|
680
|
import Home from './components/Home';
import Layout from './components/Layout';
import ApiDocs from './components/ApiDocs';
import NotFound from './components/NotFound';
import SetConfigExample from './components/ApiDocs/SetConfigExample';
const routes = {
component: Layout,
childRoutes: [
{ path: '/', component: Home },
{ path: '/index.html', onEnter: (nextState, replaceState) => replaceState(null, '/') },
{
path: '/api_docs',
component: ApiDocs,
childRoutes: [
{
path: 'set_config',
component: SetConfigExample,
},
],
},
{ path: '*', component: NotFound },
],
};
export default routes;
|
mit
|
radical-cybertools/ExTASY
|
examples/grlsd-on-stampede/extasy_gromacs_lsdmap.py
|
13334
|
#!/usr/bin/env python
__author__ = "Vivek <vivek.balasubramanian@rutgers.edu>"
__copyright__ = "Copyright 2014, http://radical.rutgers.edu"
__license__ = "MIT"
__use_case_name__ = "'Gromacs + LSDMap' simulation-analysis proof-of-concept (ExTASY)."
from radical.ensemblemd import Kernel
from radical.ensemblemd import SimulationAnalysisLoop
from radical.ensemblemd import EnsemblemdError
from radical.ensemblemd import SimulationAnalysisLoop
from radical.ensemblemd import SingleClusterEnvironment
import sys
import imp
import argparse
import os
import json
from radical.ensemblemd.engine import get_engine
# ------------------------------------------------------------------------------
# Set default verbosity
if os.environ.get('RADICAL_ENMD_VERBOSE') == None:
os.environ['RADICAL_ENMD_VERBOSE'] = 'REPORT'
# ------------------------------------------------------------------------------
#Load all custom Kernels
from kernel_defs.pre_grlsd_loop import kernel_pre_grlsd_loop
get_engine().add_kernel_plugin(kernel_pre_grlsd_loop)
from kernel_defs.gromacs import kernel_gromacs
get_engine().add_kernel_plugin(kernel_gromacs)
from kernel_defs.pre_lsdmap import kernel_pre_lsdmap
get_engine().add_kernel_plugin(kernel_pre_lsdmap)
from kernel_defs.lsdmap import kernel_lsdmap
get_engine().add_kernel_plugin(kernel_lsdmap)
from kernel_defs.post_lsdmap import kernel_post_lsdmap
get_engine().add_kernel_plugin(kernel_post_lsdmap)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
#
class Gromacs_LSDMap(SimulationAnalysisLoop):
# TODO Vivek: add description.
def __init__(self, maxiterations, simulation_instances=1, analysis_instances=1):
SimulationAnalysisLoop.__init__(self, maxiterations, simulation_instances, analysis_instances)
def pre_loop(self):
'''
function : transfers input files and intermediate executables
pre_grlsd_loop :-
Purpose : Transfers files, Split the input file into smaller files to be used by each of the
gromacs instances in the first iteration.
Arguments : --inputfile = file to be split
--numCUs = number of simulation instances/ number of smaller files
'''
k = Kernel(name="custom.pre_grlsd_loop")
k.arguments = ["--inputfile={0}".format(os.path.basename(Kconfig.md_input_file)),"--numCUs={0}".format(Kconfig.num_CUs)]
k.copy_input_data = [ '$SHARED/{0}'.format(os.path.basename(Kconfig.md_input_file)),
'$SHARED/spliter.py',
'$SHARED/gro.py'
]
return k
def simulation_step(self, iteration, instance):
'''
function : In iter=1, use the input files from pre_loop, else use the outputs of the analysis stage in the
previous iteration. Run gromacs in each instance using these files.
gromacs :-
Purpose : Run the gromacs simulation on each of the smaller files. Parameter files and executables are input
from pre_loop. There are 'numCUs' number of instances of gromacs per iteration.
Arguments : --grompp = gromacs parameters filename
--topol = topology filename
'''
gromacs = Kernel(name="custom.gromacs")
gromacs.arguments = ["--grompp={0}".format(os.path.basename(Kconfig.mdp_file)),
"--topol={0}".format(os.path.basename(Kconfig.top_file))]
gromacs.link_input_data = ['$SHARED/{0} > {0}'.format(os.path.basename(Kconfig.mdp_file)),
'$SHARED/{0} > {0}'.format(os.path.basename(Kconfig.top_file)),
'$SHARED/run.py > run.py']
if (iteration-1==0):
gromacs.link_input_data.append('$PRE_LOOP/temp/start{0}.gro > start.gro'.format(instance-1))
else:
gromacs.link_input_data.append('$ANALYSIS_ITERATION_{0}_INSTANCE_1/temp/start{1}.gro > start.gro'.format(iteration-1,instance-1))
if Kconfig.grompp_options is not None:
gromacs.environment = {'grompp_options':Kconfig.grompp_options}
if Kconfig.mdrun_options is not None:
gromacs.environment = {'mdrun_options':Kconfig.mdrun_options}
if Kconfig.ndx_file is not None:
gromacs.environment = {'ndxfile',os.path.basename(Kconfig.ndx_file)}
gromacs.link_input_data.append('$SHARED/{0}'.format(os.path.basename(Kconfig.ndx_file)))
return gromacs
def analysis_step(self, iteration, instance):
'''
function : Merge the results of each of the simulation instances and run LSDMap analysis to generate the
new coordinate file. Split this new coordinate file into smaller files to be used by the simulation stage
in the next iteration.
If a step as multiple kernels (say k1, k2), data generated in k1 is implicitly moved to k2 (if k2 requires).
Data which needs to be moved between the various steps (pre_loop, simulation_step, analysis_step) needs to
be mentioned by the user.
pre_lsdmap :-
Purpose : The output of each gromacs instance in the simulation_step is a small coordinate file. Concatenate
such files from each of the gromacs instances to form a larger file. There is one instance of pre_lsdmap per
iteration.
Arguments : --numCUs = number of simulation instances / number of small files to be concatenated
lsdmap :-
Purpose : Perform LSDMap on the large coordinate file to generate weights and eigen values. There is one instance
of lsdmap per iteration (MSSA : Multiple Simulation Single Analysis model).
Arguments : --config = name of the config file to be used during LSDMap
post_lsdmap :-
Purpose : Use the weights, eigen values generated in lsdmap along with other parameter files from pre_loop
to generate the new coordinate file to be used by the simulation_step in the next iteration. There is one
instance of post_lsdmap per iteration.
post_ana.arguments = ["--num_runs={0}".format(Kconfig.num_runs),
"--out=out.gro",
"--cycle={0}".format(iteration-1),
"--max_dead_neighbors={0}".format(Kconfig.max_dead_neighbors),
"--max_alive_neighbors={0}".format(Kconfig.max_alive_neighbors),
"--numCUs={0}".format(Kconfig.num_CUs)]
Arguments : --num_runs = number of configurations to be generated in the new coordinate file
--out = output filename
--cycle = iteration number
--max_dead_neighbors = max dead neighbors to be considered
--max_alive_neighbors = max alive neighbors to be considered
--numCUs = number of simulation instances/ number of smaller files
'''
pre_ana = Kernel(name="custom.pre_lsdmap")
pre_ana.arguments = ["--numCUs={0}".format(Kconfig.num_CUs)]
pre_ana.link_input_data = ["$SHARED/pre_analyze.py > pre_analyze.py"]
for i in range(1,Kconfig.num_CUs+1):
pre_ana.link_input_data = pre_ana.link_input_data + ["$SIMULATION_ITERATION_{2}_INSTANCE_{0}/out.gro > out{1}.gro".format(i,i-1,iteration)]
pre_ana.copy_output_data = ['tmpha.gro > $SHARED/iter_{0}/tmpha.gro'.format(iteration-1),'tmp.gro > $SHARED/iter_{0}/tmp.gro'.format(iteration-1)]
lsdmap = Kernel(name="md.lsdmap")
lsdmap.arguments = ["--config={0}".format(os.path.basename(Kconfig.lsdm_config_file))]
lsdmap.link_input_data = ['$SHARED/{0} > {0}'.format(os.path.basename(Kconfig.lsdm_config_file)),'$SHARED/iter_{0}/tmpha.gro > tmpha.gro'.format(iteration-1)]
lsdmap.cores = 1
if iteration > 1:
lsdmap.link_input_data += ['$ANALYSIS_ITERATION_{0}_INSTANCE_1/weight.w > weight.w'.format(iteration-1)]
lsdmap.copy_output_data = ['weight.w > $SHARED/iter_{0}/weight.w'.format(iteration-1)]
lsdmap.copy_output_data = ['tmpha.ev > $SHARED/iter_{0}/tmpha.ev'.format(iteration-1),'out.nn > $SHARED/iter_{0}/out.nn'.format(iteration-1)]
if(iteration%Kconfig.nsave==0):
lsdmap.download_output_data=['lsdmap.log > output/iter{0}/lsdmap.log'.format(iteration-1)]
post_ana = Kernel(name="custom.post_lsdmap")
post_ana.link_input_data = ["$SHARED/post_analyze.py > post_analyze.py",
"$SHARED/selection.py > selection.py",
"$SHARED/reweighting.py > reweighting.py",
"$SHARED/spliter.py > spliter.py",
"$SHARED/gro.py > gro.py",
"$SHARED/iter_{0}/tmp.gro > tmp.gro".format(iteration-1),
"$SHARED/iter_{0}/tmpha.ev > tmpha.ev".format(iteration-1),
"$SHARED/iter_{0}/out.nn > out.nn".format(iteration-1),
"$SHARED/input.gro > input.gro"]
post_ana.arguments = ["--num_runs={0}".format(Kconfig.num_runs),
"--out=out.gro",
"--cycle={0}".format(iteration-1),
"--max_dead_neighbors={0}".format(Kconfig.max_dead_neighbors),
"--max_alive_neighbors={0}".format(Kconfig.max_alive_neighbors),
"--numCUs={0}".format(Kconfig.num_CUs)]
if iteration > 1:
post_ana.link_input_data += ['$ANALYSIS_ITERATION_{0}_INSTANCE_1/weight.w > weight_new.w'.format(iteration-1)]
if(iteration%Kconfig.nsave==0):
post_ana.download_output_data = ['out.gro > output/iter{0}/out.gro'.format(iteration),
'weight.w > output/iter{0}/weight.w'.format(iteration)]
return [pre_ana,lsdmap,post_ana]
# ------------------------------------------------------------------------------
#
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser()
parser.add_argument('--RPconfig', help='link to Radical Pilot related configurations file')
parser.add_argument('--Kconfig', help='link to Kernel configurations file')
args = parser.parse_args()
if args.RPconfig is None:
parser.error('Please enter a RP configuration file')
sys.exit(1)
if args.Kconfig is None:
parser.error('Please enter a Kernel configuration file')
sys.exit(0)
RPconfig = imp.load_source('RPconfig', args.RPconfig)
Kconfig = imp.load_source('Kconfig', args.Kconfig)
# Create a new static execution context with one resource and a fixed
# number of cores and runtime.
cluster = SingleClusterEnvironment(
resource=RPconfig.REMOTE_HOST,
cores=RPconfig.PILOTSIZE,
walltime=RPconfig.WALLTIME,
username = RPconfig.UNAME, #username
project = RPconfig.ALLOCATION, #project
queue = RPconfig.QUEUE,
database_url = RPconfig.DBURL
)
cluster.shared_data = [
Kconfig.md_input_file,
Kconfig.lsdm_config_file,
Kconfig.top_file,
Kconfig.mdp_file,
'{0}/spliter.py'.format(Kconfig.helper_scripts),
'{0}/gro.py'.format(Kconfig.helper_scripts),
'{0}/run.py'.format(Kconfig.helper_scripts),
'{0}/pre_analyze.py'.format(Kconfig.helper_scripts),
'{0}/post_analyze.py'.format(Kconfig.helper_scripts),
'{0}/selection.py'.format(Kconfig.helper_scripts),
'{0}/reweighting.py'.format(Kconfig.helper_scripts)
]
if Kconfig.ndx_file is not None:
cluster.shared_data.append(Kconfig.ndx_file)
cluster.allocate()
# We set the 'instances' of the simulation step to 16. This means that 16
# instances of the simulation are executed every iteration.
# We set the 'instances' of the analysis step to 1. This means that only
# one instance of the analysis is executed for each iteration
randomsa = Gromacs_LSDMap(maxiterations=Kconfig.num_iterations, simulation_instances=Kconfig.num_CUs, analysis_instances=1)
cluster.run(randomsa)
cluster.deallocate()
except EnsemblemdError, er:
print "Ensemble MD Toolkit Error: {0}".format(str(er))
raise # Just raise the execption again to get the backtrace
|
mit
|
mk12/scribbler-bot
|
src/scribbler/programs/base.py
|
6803
|
# Copyright 2014 Mitchell Kember. Subject to the MIT License.
"""Implements common functionality for Scribbler programs."""
import math
from time import time
# Short codes for the parameters of the program.
PARAM_CODES = {
'bl': 'beep_len',
'bf': 'beep_freq',
's': 'speed',
'dtt': 'dist_to_time',
'att': 'angle_to_time'
}
# Default values for the parameters of the program.
PARAM_DEFAULTS = {
'beep_len': 0.5, # s
'beep_freq': 2000, # Hz
'speed': 0.4, # from 0.0 to 1.0
'dist_to_time': 0.07, # cm/s
'angle_to_time': 0.009 # rad/s
}
# Prefix used in commands that change the value of a parameter.
PARAM_PREFIX = 'set:'
class BaseProgram(object):
"""Implements the general aspects of robot programs and basic server
communcation. Also manages the parameter dictionary."""
def __init__(self):
"""Creates a new base program."""
self.defaults = PARAM_DEFAULTS.copy()
self.params = PARAM_DEFAULTS.copy()
self.codes = PARAM_CODES.copy()
def add_params(self, defaults, codes):
"""Adds parameters to the program given their default values and their
short codes, which must be dictionaries similar to PARAM_CODES and
PARAM_DEFAULTS (defined above)."""
self.defaults.update(defaults)
self.params.update(defaults)
self.codes.update(codes)
@property
def speed(self):
"""Returns the nominal speed of the robot."""
return self.params['speed']
def dist_to_time(self, dist):
"""Returns how long the robot should drive at its current speed in order
to cover `dist` centimetres."""
return self.params['dist_to_time'] * dist / self.speed
def angle_to_time(self, angle):
"""Returns how long the robot should rotate at its current speed in
order to rotate by `angle` degrees."""
return self.params['angle_to_time'] * angle / self.speed
def time_to_dist(self, time):
"""The inverse of `dist_to_time`."""
return self.speed * time / self.params['dist_to_time']
def time_to_angle(self, time):
"""The inverse of `angle_to_time`."""
return self.speed * time / self.params['angle_to_time']
# Subclasses should override the following methods (and call super).
# `__call__` must return a status, and `loop` should sometimes.
def __call__(self, command):
"""Performs an action according to the command passed down from the
controller, and returns a status message."""
if command == 'other:beep':
myro.beep(self.params['beep_len'], self.params['beep_freq'])
return "successful beep"
if command == 'other:info':
return "battery: " + str(myro.getBattery())
if command.startswith(PARAM_PREFIX):
code, value = command[len(PARAM_PREFIX):].split('=')
if not code in self.codes:
return "invalid code: " + code
name = self.codes[code]
# Return the value of the parameter.
if value == "" or value == "?":
return name + " = " + str(self.params[name])
# Reset the parameter to its default.
if "default".startswith(value):
n = self.defaults[name]
else:
try:
n = float(value)
except ValueError:
return "NaN: " + value
# Set the parameter to the new value.
self.params[name] = n
return name + " = " + str(n)
def start(self):
"""Called when the controller is started."""
pass
def stop(self):
"""Called when the controller is stopped."""
myro.stop()
def reset(self):
"""Resets the program to its initial state."""
pass
def loop(self):
"""The main loop of the program."""
pass
class ModeProgram(BaseProgram):
"""A program that operates in one mode per distinct motion."""
def __init__(self, initial_mode):
"""Creates a new ModeProgram it its default state."""
BaseProgram.__init__(self)
self.initial_mode = initial_mode
self.reset()
def reset(self):
"""Stops and resets the program to the first mode."""
BaseProgram.reset(self)
self.mode = self.initial_mode
self.start_time = 0
self.pause_time = 0
def stop(self):
"""Pauses and records the current time."""
BaseProgram.stop(self)
self.pause_time = time()
def no_start(self):
"""If the program cannot be started at this time, returns a string
providing a reason. Otherwise, returns False."""
return False
def start(self):
"""Resumes the program and fixes the timer so that the time while the
program was paused doesn't count towards the mode's time."""
BaseProgram.start(self)
self.start_time += time() - self.pause_time
self.move()
def goto_mode(self, mode):
"""Stops the robot and switches to the given mode. Resets the timer and
starts the new mode immediately."""
myro.stop()
self.end_mode()
self.mode = mode
self.start_time = time()
self.begin_mode()
self.move()
def mode_time(self):
"""Returns the time that has elapsed since the mode begun."""
return time() - self.start_time
def has_elapsed(self, t):
"""Returns true if `t` seconds have elapsed sicne the current mode begun
and false otherwise."""
return self.mode_time() > t
def has_travelled(self, dist):
"""Returns true if the robot has driven `dist` centimetres driving the
current mode (assuming it is driving straight) and false otherwise."""
return self.has_elapsed(self.dist_to_time(dist))
def has_rotated(self, angle):
"""Returns true if the robot has rotated by `angle` degrees during the
current mode (assuming it is pivoting) and false otherwise."""
t = self.angle_to_time(angle)
return self.has_elapsed(t)
def at_right_angle(self):
"""Returns true if the robot has rotated 90 degrees during the current
mode (assuming it is pivoting) and false otherwise."""
return self.has_rotated(90)
# Subclasses should override the following three methods and `loop`.
def move(self):
"""Makes Myro calls to move the robot according to the current mode.
Called when the mode is begun and whenever the program is resumed."""
pass
def begin_mode(self):
"""Called when a new mode is begun."""
pass
def end_mode(self):
"""Called when the mode is about to switch."""
pass
|
mit
|
hirsch88/generator-hirsch
|
app/templates/tasks/install.js
|
349
|
'use strict';
var gulp = require('gulp');
var install = require('gulp-install');
/**
* INSTALL
* Automatically install npm and bower packages if package.json or
* bower.json is found in the gulp file stream respectively
*/
gulp.task('install', function () {
return gulp
.src(['./bower.json', './package.json'])
.pipe(install());
});
|
mit
|
gxy001/Office365-FiveMinuteMeeting
|
FiveMinuteMeeting.iOS/NewEventDateViewController.designer.cs
|
982
|
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace FiveMinuteMeeting.iOS
{
[Register ("NewEventDateViewController")]
partial class NewEventDateViewController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton ButtonSchedule { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIDatePicker DatePickerDate { get; set; }
[Action ("ButtonSchedule_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void ButtonSchedule_TouchUpInside (UIButton sender);
void ReleaseDesignerOutlets ()
{
if (ButtonSchedule != null) {
ButtonSchedule.Dispose ();
ButtonSchedule = null;
}
if (DatePickerDate != null) {
DatePickerDate.Dispose ();
DatePickerDate = null;
}
}
}
}
|
mit
|
anhstudios/swganh
|
data/scripts/templates/object/tangible/ship/crafted/reverse_engineering/shared_armor_analysis_tool.py
|
491
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/reverse_engineering/shared_armor_analysis_tool.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","armor_analysis_tool")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result
|
mit
|
sdgdsffdsfff/websocket-injection
|
src/views/views.py
|
904
|
import tornado.gen
from tornado.escape import parse_qs_bytes
from core.base import BaseHandler
from core.exceptions import UnexpectedReuqestDataException, InvalidWebSocketURLException
class SQLMapHandler(BaseHandler):
def get(self):
self.post()
@tornado.gen.coroutine
def post(self):
url = self.get_argument('url', default=None)
if not url:
raise UnexpectedReuqestDataException
if not url.startswith('ws://') and not url.startswith('wss://'):
raise InvalidWebSocketURLException
self.connect(url)
def get_argument(self, name, default=None, strip=True):
return self._get_argument(name, default=default,
source=parse_qs_bytes(self.request.query),
strip=strip)
class MainHandler(BaseHandler):
def get(self):
self.render('index.html')
|
mit
|
qtto/RuneCord
|
commands/user/sinkhole.js
|
555
|
module.exports = {
desc: 'Tells you when the next Sinkhole D&D will be.',
cooldown: 5,
task(bot, msg) {
let d = new Date();
let secondsUntil = 3600 - (d.getUTCMinutes() + 30) % 60 * 60 - d.getUTCSeconds();
let minutesUntil = Math.floor(secondsUntil / 60);
let timestr = '';
if (minutesUntil === 0) {
timestr += '1 hour';
}
if (minutesUntil > 0) {
timestr += `${minutesUntil} minute${minutesUntil > 0 && minutesUntil < 1 ? '' : 's'}`;
}
bot.createMessage(msg.channel.id, `The next Sinkhole will start in **${timestr}**.`)
}
}
|
mit
|
szymach/admin-bundle
|
spec/FSi/Bundle/AdminBundle/Factory/Worker/RequestStackWorkerSpec.php
|
675
|
<?php
namespace spec\FSi\Bundle\AdminBundle\Factory\Worker;
use FSi\Bundle\AdminBundle\spec\fixtures\Admin\RequestStackAwareElement;
use PhpSpec\ObjectBehavior;
use Symfony\Component\HttpFoundation\RequestStack;
class RequestStackWorkerSpec extends ObjectBehavior
{
public function let(RequestStack $requestStack): void
{
$this->beConstructedWith($requestStack);
}
public function it_mount_request_stack_to_elements_that_are_request_stack_aware(
RequestStackAwareElement $element,
RequestStack $requestStack
): void {
$element->setRequestStack($requestStack)->shouldBeCalled();
$this->mount($element);
}
}
|
mit
|
kbase/kbase-ui
|
src/client/modules/lib/kb_lib/props.ts
|
5233
|
type PropPath = Array<string> | string;
export function getProp<T>(obj: any, propPath: PropPath): T | undefined {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
for (let i = 0; i < propPath.length; i += 1) {
if ((obj === undefined) ||
(typeof obj !== 'object') ||
(obj === null)) {
return undefined;
}
obj = obj[propPath[i]];
}
if (typeof obj === 'undefined') {
return undefined;
}
return obj as T;
}
export function getPropWithDefault<T>(obj: any, propPath: PropPath, defaultValue: T): T {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
for (let i = 0; i < propPath.length; i += 1) {
if ((obj === undefined) ||
(typeof obj !== 'object') ||
(obj === null)) {
return defaultValue;
}
obj = obj[propPath[i]];
}
if (typeof obj === 'undefined') {
return defaultValue;
}
return obj as T;
}
export function hasProp(obj: any, propPath: PropPath): boolean {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
for (let i = 0; i < propPath.length; i += 1) {
if ((obj === undefined) ||
(typeof obj !== 'object') ||
(obj === null)) {
return false;
}
obj = obj[propPath[i]];
}
if (obj === undefined) {
return false;
}
return true;
}
export function setProp<T>(obj: any, propPath: PropPath, value: T) {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
if (propPath.length === 0) {
return;
}
// pop off the last property for setting at the end.
const propKey = propPath[propPath.length - 1];
let key;
// Walk the path, creating empty objects if need be.
for (let i = 0; i < propPath.length - 1; i += 1) {
key = propPath[i];
if (obj[key] === undefined) {
obj[key] = {};
}
obj = obj[key];
}
// Finally set the property.
obj[propKey] = value;
}
export function incrProp(obj: any, propPath: PropPath, increment?: number): number {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
if (propPath.length === 0) {
throw new TypeError('Property path must have at least one element');
}
increment = (typeof increment === 'undefined') ? 1 : increment;
const propKey = propPath[propPath.length - 1];
for (let i = 0; i < propPath.length - 1; i += 1) {
const key = propPath[i];
if (obj[key] === undefined) {
obj[key] = {};
}
obj = obj[key];
}
if (typeof obj[propKey] === 'undefined') {
obj[propKey] = increment;
} else {
if (typeof obj[propKey] === 'number') {
obj[propKey] += increment;
} else {
throw new Error('Can only increment a number');
}
}
return obj[propKey];
}
export function deleteProp(obj: any, propPath: PropPath) {
if (typeof propPath === 'string') {
propPath = propPath.split('.');
} else if (!(propPath instanceof Array)) {
throw new TypeError('Invalid type for key: ' + (typeof propPath));
}
if (propPath.length === 0) {
return false;
}
const propKey = propPath[propPath.length - 1];
for (let i = 0; i < propPath.length - 1; i += 1) {
const key = propPath[i];
if (obj[key] === undefined) {
// for idempotency, and utility, do not throw error if
// the key doesn't exist.
return false;
}
obj = obj[key];
}
if (obj[propKey] === undefined) {
return false;
}
delete obj[propKey];
return true;
}
export class Props {
obj: any;
constructor({ data }: { data?: any; }) {
this.obj = typeof data === 'undefined' ? {} : data;
}
getItemWithDefault<T>(props: PropPath, defaultValue: T) {
return getPropWithDefault<T>(this.obj, props, defaultValue);
}
getItem<T>(props: PropPath) {
return getProp<T>(this.obj, props);
}
hasItem(propPath: PropPath) {
return hasProp(this.obj, propPath);
}
setItem(path: PropPath, value: any) {
return setProp(this.obj, path, value);
}
incrItem(path: PropPath, increment?: number) {
return incrProp(this.obj, path, increment);
}
deleteItem(path: PropPath) {
return deleteProp(this.obj, path);
}
getRaw() {
return this.obj;
}
}
|
mit
|
kataras/gapi
|
_examples/file-server/basic/main.go
|
2385
|
package main
import (
"github.com/kataras/iris/v12"
)
func newApp() *iris.Application {
app := iris.New()
app.Favicon("./assets/favicon.ico")
// first parameter is the request path
// second is the system directory
//
// app.HandleDir("/css", iris.Dir("./assets/css"))
// app.HandleDir("/js", iris.Dir("./assets/js"))
v1 := app.Party("/v1")
v1.HandleDir("/static", iris.Dir("./assets"), iris.DirOptions{
// Defaults to "/index.html", if request path is ending with **/*/$IndexName
// then it redirects to **/*(/) which another handler is handling it,
// that another handler, called index handler, is auto-registered by the framework
// if end developer does not managed to handle it by hand.
IndexName: "/index.html",
// When files should served under compression.
Compress: false,
// List the files inside the current requested directory if `IndexName` not found.
ShowList: false,
// When ShowList is true you can configure if you want to show or hide hidden files.
ShowHidden: false,
Cache: iris.DirCacheOptions{
// enable in-memory cache and pre-compress the files.
Enable: true,
// ignore image types (and pdf).
CompressIgnore: iris.MatchImagesAssets,
// do not compress files smaller than size.
CompressMinSize: 300,
// available encodings that will be negotiated with client's needs.
Encodings: []string{"gzip", "br" /* you can also add: deflate, snappy */},
},
DirList: iris.DirListRich(),
// If `ShowList` is true then this function will be used instead of the default
// one to show the list of files of a current requested directory(dir).
// DirList: func(ctx iris.Context, dirName string, dir http.File) error { ... }
//
// Optional validator that loops through each requested resource.
// AssetValidator: func(ctx iris.Context, name string) bool { ... }
})
// You can also register any index handler manually, order of registration does not matter:
// v1.Get("/static", [...custom middleware...], func(ctx iris.Context) {
// [...custom code...]
// ctx.ServeFile("./assets/index.html")
// })
// http://localhost:8080/v1/static
// http://localhost:8080/v1/static/css/main.css
// http://localhost:8080/v1/static/js/jquery-2.1.1.js
// http://localhost:8080/v1/static/favicon.ico
return app
}
func main() {
app := newApp()
app.Logger().SetLevel("debug")
app.Listen(":8080")
}
|
mit
|
seekmas/makoto.local
|
vendor/sonata-project/formatter-bundle/Resources/public/vendor/ckeditor/plugins/placeholder/lang/pl.js
|
436
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("placeholder","pl",{title:"Właściwości wypełniacza",toolbar:"Utwórz wypełniacz",name:"Nazwa wypełniacza",invalidName:"Wypełniacz nie może być pusty ani nie może zawierać żadnego z następujących znaków: [, ], < oraz >",pathName:"wypełniacz"});
|
mit
|
radamanthus/bayes_motel
|
lib/bayes_motel/memory_interface.rb
|
2765
|
module BayesMotel
module Persistence
class MemoryInterface
def initialize(name)
@classifier = {:name=>name,:data=>{},:total_count=>0}
@documents = {}
end
def delete
@classifier = {:name=>'',:data=>{},:total_count=>0}
end
def increment_total
@classifier[:total_count] += 1
end
def total_count
@classifier[:total_count]
end
def cleanup
delete
end
def raw_counts(node)
@classifier[:data][node] || []
end
def save_training(category, node, score, polarity)
incrementer = polarity == "positive" ? 1 : -1
#If we haven't seen this v, we always treat polarity as positive.
#Make it look like this: {@classifier=>{:data=>{node=>{category=>{score=>count,otherscore=>othercount}}}}
#score/count clarification: score can be more than 1 if you have multiple incidences in the same doc.
#Count is the number of times we've seen that particular incidence.
@classifier[:data][node] ? @classifier[:data][node][category] ? @classifier[:data][node][category][score] ? @classifier[:data][node][category][score] += incrementer : @classifier[:data][node][category].store(score,1) : @classifier[:data][node].store(category, {score=>1}) : @classifier[:data].store(node, {category => {score=>1}})
end
def create_document(doc_id,category)
@documents.store(doc_id,category)
end
def edit_document(doc_id,category)
@documents[doc_id] = category
end
def document_category(doc_id)
@documents[doc_id]
end
def destroy_document(doc_id)
#call BayesMotel::Corpus.destroy_document in order to decrement the training corpus - this method only destroys the document link itself
@documents.delete(doc_id)
end
def destroy_classifier
@classifier = nil
@documents = nil
end
def save_to_mongo
#note that checking for duplicates and changing categorization must be done using MongoInterface directly-
#this batch job does not have the info to do a granular decrement.
@mongo = BayesMotel::Persistence::MongomapperInterface.new(@classifier[:name])
@documents.each do |doc_id, category_name|
@mongo.increment_total
@mongo.create_document(doc_id, category_name)
end
@classifier[:data].each do |node_name, category_hash|
category_hash.each do |category_name, score_hash|
score_hash.each do |score, count|
count.times do
@mongo.save_training(category_name, node_name, score, "positive")
end
end
end
end
end
end
end
end
|
mit
|
alexko13/block-and-frame
|
app/components/Footer.js
|
2464
|
import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<div className="ui vertical footer inverted segment" id="footer">
<div className="ui center aligned container">
<div className="ui inverted stackable divided grid">
<div className="five wide column">
<h4 className="ui inverted header">Navigation</h4>
<div className="ui inverted link list">
<a href="/" className="item">Home</a>
<a href="#" className="item">Dashboard</a>
<a href="#" className="item">View Spreads</a>
<a href="#" className="item">Host a Spread</a>
</div>
</div>
<div className="five wide column">
<h4 className="ui inverted header">Follow Us:</h4>
<div className="ui inverted link list">
<div className="item">
<button className="social ui circular instagram icon button">
<i className="instagram icon"></i>
</button>
</div>
<div className="item">
<button className="social ui circular facebook icon button">
<i className="facebook icon"></i>
</button>
</div>
<div className="item">
<button className="social ui circular github icon button">
<i className="github icon"></i>
</button>
</div>
</div>
</div>
<div className="six wide column">
<h4 className="ui inverted header">Spread Out</h4>
<p>Making the world a better place by connecting new friends around communal food-centered experiences</p>
</div>
</div>
<div className="ui inverted section divider"></div>
<div className="ui inverted horizontal small divided link list">
<a href="https://github.com/Block-and-Frame/block-and-frame/blob/master/PRIVACY-POLICY.md" className="item">Privacy Policy</a>
<a href="/about" className="item">About Us</a>
<a href="#" className="item">Contact Us</a>
</div>
</div>
</div>
);
}
}
export default Footer;
|
mit
|
vickeetran/hackd.in
|
compiled/client/lib/lodash/fp/subtract.js
|
830
|
'use strict';
var convert = require('./convert'),
func = convert('subtract', require('../subtract'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL3N1YnRyYWN0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFkO0lBQ0ksT0FBTyxRQUFRLFVBQVIsRUFBb0IsUUFBUSxhQUFSLENBQXBCLENBRFg7O0FBR0EsS0FBSyxXQUFMLEdBQW1CLFFBQVEsZUFBUixDQUFuQjtBQUNBLE9BQU8sT0FBUCxHQUFpQixJQUFqQiIsImZpbGUiOiJzdWJ0cmFjdC5qcyIsInNvdXJjZXNDb250ZW50IjpbInZhciBjb252ZXJ0ID0gcmVxdWlyZSgnLi9jb252ZXJ0JyksXG4gICAgZnVuYyA9IGNvbnZlcnQoJ3N1YnRyYWN0JywgcmVxdWlyZSgnLi4vc3VidHJhY3QnKSk7XG5cbmZ1bmMucGxhY2Vob2xkZXIgPSByZXF1aXJlKCcuL3BsYWNlaG9sZGVyJyk7XG5tb2R1bGUuZXhwb3J0cyA9IGZ1bmM7XG4iXX0=
|
mit
|
oliviertassinari/material-ui
|
packages/mui-icons-material/lib/esm/TransgenderSharp.js
|
592
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 8c1.93 0 3.5 1.57 3.5 3.5S13.93 15 12 15s-3.5-1.57-3.5-3.5S10.07 8 12 8zm4.53.38 3.97-3.96V7h2V1h-6v2h2.58l-3.97 3.97C14.23 6.36 13.16 6 12 6s-2.23.36-3.11.97l-.65-.65 1.41-1.41-1.41-1.42L6.82 4.9 4.92 3H7.5V1h-6v6h2V4.42l1.91 1.9-1.42 1.42L5.4 9.15l1.41-1.41.65.65c-.6.88-.96 1.95-.96 3.11 0 2.7 1.94 4.94 4.5 5.41V19H9v2h2v2h2v-2h2v-2h-2v-2.09c2.56-.47 4.5-2.71 4.5-5.41 0-1.16-.36-2.23-.97-3.12z"
}), 'TransgenderSharp');
|
mit
|
3b-fly/controlsjs-jsdoc
|
node_modules/less/lib/less/tree/paren.js
|
590
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Paren = function (node) {
this.value = node;
};
Paren.prototype = Object.assign(new node_1.default(), {
type: 'Paren',
genCSS: function (context, output) {
output.add('(');
this.value.genCSS(context, output);
output.add(')');
},
eval: function (context) {
return new Paren(this.value.eval(context));
}
});
exports.default = Paren;
//# sourceMappingURL=paren.js.map
|
mit
|
reneepadgham/diverseui
|
static/scripts/menu.js
|
444
|
var menuButton = document.querySelector('.mobile-menu-button');
if (menuButton) {
menuButton.addEventListener('click', function() {
if (document.body.className === 'site') {
document.body.className = 'site open';
} else {
document.body.className = 'site';
}
});
}
var hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", function() {
hamburger.classList.toggle("is-active");
});
|
mit
|
sanity-io/sanity
|
dev/test-studio/parts/tools/css-variables/propertyPreview.js
|
2710
|
import PropTypes from 'prop-types'
import React from 'react'
import styles from './propertyPreview.css'
// eslint-disable-next-line complexity
export function ThemePropertyPreview({property}) {
if (property.type === 'color') {
return (
<div
className={styles.root}
data-type={property.type}
style={{background: property.value, height: '2.5em'}}
/>
)
}
if (property.type === 'size') {
return <div className={styles.root} data-type={property.type} style={{width: property.value}} />
}
if (property.type === 'font-family') {
return (
<div className={styles.root} data-type={property.type} style={{fontFamily: property.value}}>
Hamburgefonstiv
</div>
)
}
if (property.type === 'font-size') {
return (
<div className={styles.root} data-type={property.type} style={{fontSize: property.value}}>
Hamburgefonstiv
</div>
)
}
if (property.type === 'font-weight') {
return (
<div className={styles.root} data-type={property.type} style={{fontWeight: property.value}}>
Hamburgefonstiv
</div>
)
}
if (property.type === 'z-index') {
// no preview
return null
}
if (property.type === 'border-radius') {
return (
<div className={styles.root} data-type={property.type}>
<div style={{borderTopLeftRadius: property.value}} />
</div>
)
}
if (property.type === 'cursor') {
return (
<div className={styles.root} data-type={property.type} style={{cursor: property.value}}>
Hover me
</div>
)
}
if (property.type === 'border-width') {
return (
<div className={styles.root} data-type={property.type}>
<div style={{borderTop: `${property.value} solid #000`}} />
</div>
)
}
if (property.type === 'border') {
return (
<div className={styles.root} data-type={property.type}>
<div style={{borderTop: property.value}} />
</div>
)
}
if (property.type === 'line-height') {
return (
<div className={styles.root} data-type={property.type} style={{lineHeight: property.value}}>
Hamburgefonstiv
</div>
)
}
if (property.type === 'box-shadow') {
return (
<div className={styles.root} data-type={property.type} style={{boxShadow: property.value}} />
)
}
return (
<>
<div className={styles.unknown}>
Unknown var type: <code>{property.type}</code>
</div>
</>
)
}
ThemePropertyPreview.propTypes = {
property: PropTypes.shape({
name: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
}).isRequired,
}
|
mit
|
Microsoft/ChakraCore
|
test/Lib/tostring.js
|
5754
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function write(v) { WScript.Echo(v + ""); }
var errorCount = 0;
// global
var globalList = [
["eval",1],
["parseInt",2],
["parseFloat",1],
["isNaN",1],
["isFinite",1],
["decodeURI",1],
["encodeURI",1],
["decodeURIComponent",1],
["encodeURIComponent",1],
["Object",0],
["Function",1],
["Array",1],
["String",1],
["Boolean",1],
["Number",1],
["Date",7],
["RegExp",2],
["Error",1],
["EvalError",1],
["RangeError",1],
["ReferenceError",1],
["SyntaxError",1],
["TypeError",1],
["URIError",1]
]
// Object
var objList = [
//TODO ["constructor",0],
["toString",0],
["toLocaleString",0],
["valueOf",0],
["hasOwnProperty",1] ,
["isPrototypeOf",1] ,
["propertyIsEnumerable",1]
]
// Function
var funcList = [
["constructor",1],
["toString",0],
["apply",2 ],
["call", 1]
]
// Array
var arrList = [
// FuncName, length
["constructor",1],
["toString",0],
["toLocaleString", 0],
["concat", 1],
["join",1],
["pop",0],
["push",1],
["reverse",0],
["shift",0],
["slice",2],
["sort",1],
["splice",2],
["unshift",1]
];
// String
var stringList = [
["constructor",1],
["toString",0],
["valueOf",0],
["charAt",1],
["charCodeAt",1],
["concat",1],
["indexOf",2],
["lastIndexOf",2],
["localeCompare",1],
["match",1],
["replace",1],
["search",0],
["slice",0],
["split",2],
["substring",2],
["toLowerCase",0],
["toLocaleLowerCase",0],
["toUpperCase",0],
["toLocaleUpperCase",0],
// not in ECMA spec
["anchor",1],
["big",0],
["blink",0],
["bold",0],
["fixed",0],
["fontcolor",1],
["fontsize",1],
["italics",0],
["link",1],
["small",0],
["strike",0],
["sub",0],
["sup",0],
["substr",2]
]
var stringList2 = [
["fromCharCode", 0]
];
// Boolean
var boolList = [
["constructor",1],
["toString",0],
["valueOf",0]
]
//Number
var numberList = [
["constructor",1],
["toString",1],
["toLocaleString",0],
["valueOf",0],
["toFixed",1],
["toExponential",1],
["toPrecision",1]
]
// Math object is a single object - 18
var mathList = [
["abs",1],
["acos",1],
["asin",1],
["atan",1],
["atan2",2],
["ceil",1],
["cos",1],
["exp",1],
["floor",1],
["log",1],
["max",2],
["min",2],
["pow",2],
["random",0],
["round",1],
["sin",1],
["sqrt",1],
["tan",1]
]
// Date Prototype object
var dateList = [
["constructor",7],
["toString",0],
["toDateString",0],
["toTimeString",0],
["toLocaleString",0],
["toLocaleDateString",0],
["valueOf",0],
["getTime",0],
["getFullYear",0],
["getUTCFullYear",0],
["getMonth",0],
["getUTCMonth",0],
["getDate",0],
["getUTCDate",0],
["getDay",0],
["getUTCDay",0],
["getHours",0],
["getUTCHours",0],
["getMinutes",0],
["getUTCMinutes",0],
["getSeconds",0],
["getUTCSeconds",0],
["getMilliseconds",0],
["getUTCMilliseconds",0],
["getTimezoneOffset",0],
["setTime",1],
["setMilliseconds",1],
["setUTCMilliseconds",1],
["setSeconds",2],
["setUTCSeconds",2],
["setMinutes",3],
["setUTCMinutes",3],
["setHours",4],
["setUTCHours",4],
["setDate",1],
["setUTCDate",1],
["setMonth",2],
["setUTCMonth",2],
["setFullYear",3],
["setUTCFullYear",3],
["toUTCString",0],
["toGMTString",0],
["toLocaleTimeString",0 ],
["toUTCString",0],
["setYear",1],
["getYear",0]
]
// static date functions
var dateList2 = [
["parse",1],
["UTC",7]
]
// RegExp object
var regxpList = [
["constructor",2],
["exec",1],
["test",1],
["toString",0] //,
// not in ECMA spec
// TODO ["compile",2]
]
// Error object
var errorList = [
["constructor",1],
["name",5],
["message",0],
["toString",0]
]
function doEval(scen) {
try {
var res = eval(scen);
write(res);
} catch (e) {
write(" Exception: " + scen + ". :: " + e.message);
}
}
var somevar = 0;
function TestToString(list, str) {
for (var i=0; i<list.length; i++) {
var fname = list[i][0];
var fullStr = str+fname+".toString()";
doEval(fullStr);
}
}
TestToString(globalList,"");
TestToString(objList, "Object.prototype.");
TestToString(funcList, "Function.prototype.");
TestToString(arrList, "Array.prototype.");
TestToString(stringList, "String.prototype.");
TestToString(stringList2, "String.");
TestToString(boolList, "Boolean.prototype.");
TestToString(numberList, "Number.prototype.");
TestToString(mathList, "Math.");
TestToString(dateList, "Date.prototype.");
TestToString(dateList2,"Date.");
TestToString(regxpList, "RegExp.prototype.");
TestToString(errorList, "Error.prototype.");
if ( errorCount > 0 ) {
throw Error(errorCount + " Test(s) Failed");
}
|
mit
|
Kiandr/CrackingCodingInterview
|
Java_SecondVersion/Ch 16. Moderate/Q16_16_Sub_Sort/QuestionB.java
|
1038
|
package Q16_16_Sub_Sort;
public class QuestionB {
public static int findRightSequenceStart(int[] array) {
int max = Integer.MIN_VALUE;
int lastNo = 0;
for (int i = 0; i < array.length; i++) {
if (max > array[i]) {
lastNo = i;
}
max = Math.max(array[i], max);
}
return lastNo;
}
public static int findLeftSequenceEnd(int[] array) {
int min = Integer.MAX_VALUE;
int lastNo = 0;
for (int i = array.length - 1; i >= 0; i--) {
if (min < array[i]) {
lastNo = i;
}
min = Math.min(array[i], min);
}
return lastNo;
}
public static Range findUnsortedSequence(int[] array) {
int leftSequenceEnd = findRightSequenceStart(array);
int rightSequenceEnd = findLeftSequenceEnd(array);
return new Range(leftSequenceEnd, rightSequenceEnd);
}
public static void main(String[] args) {
int[] array = {1, 2, 4, 7, 10, 11, 8, 12, 5, 6, 16, 18, 19};
Range r = findUnsortedSequence(array);
System.out.println(r.toString());
System.out.println(array[r.start] + ", " + array[r.end]);
}
}
|
mit
|
MrOrz/rumors-api
|
src/graphql/dataLoaders/__fixtures__/analyticsLoaderFactory.js
|
8489
|
export default {
'/analytics/doc/article_article0_2019-12-10': {
date: '2019-12-10T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 1, webUser: 1, lineVisit: 1, lineUser: 1 },
},
'/analytics/doc/article_article0_2019-12-11': {
date: '2019-12-11T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 2, webUser: 2, lineVisit: 2, lineUser: 2 },
},
'/analytics/doc/article_article0_2019-12-12': {
date: '2019-12-12T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 3, webUser: 3, lineVisit: 3, lineUser: 3 },
},
'/analytics/doc/article_article0_2019-12-13': {
date: '2019-12-13T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 4, webUser: 4, lineVisit: 4, lineUser: 4 },
},
'/analytics/doc/article_article0_2019-12-14': {
date: '2019-12-14T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 5, webUser: 5, lineVisit: 5, lineUser: 5 },
},
'/analytics/doc/article_article0_2019-12-15': {
date: '2019-12-15T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 6, webUser: 6, lineVisit: 6, lineUser: 6 },
},
'/analytics/doc/article_article0_2019-12-16': {
date: '2019-12-16T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 7, webUser: 7, lineVisit: 7, lineUser: 7 },
},
'/analytics/doc/article_article0_2019-12-17': {
date: '2019-12-17T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 8, webUser: 8, lineVisit: 8, lineUser: 8 },
},
'/analytics/doc/article_article0_2019-12-18': {
date: '2019-12-18T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 9, webUser: 9, lineVisit: 9, lineUser: 9 },
},
'/analytics/doc/article_article0_2019-12-19': {
date: '2019-12-19T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 10, webUser: 10, lineVisit: 10, lineUser: 10 },
},
'/analytics/doc/article_article0_2019-12-20': {
date: '2019-12-20T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 11, webUser: 11, lineVisit: 11, lineUser: 11 },
},
'/analytics/doc/article_article0_2019-12-21': {
date: '2019-12-21T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 12, webUser: 12, lineVisit: 12, lineUser: 12 },
},
'/analytics/doc/article_article0_2019-12-22': {
date: '2019-12-22T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 13, webUser: 13, lineVisit: 13, lineUser: 13 },
},
'/analytics/doc/article_article0_2019-12-23': {
date: '2019-12-23T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 14, webUser: 14, lineVisit: 14, lineUser: 14 },
},
'/analytics/doc/article_article0_2019-12-24': {
date: '2019-12-24T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 15, webUser: 15, lineVisit: 15, lineUser: 15 },
},
'/analytics/doc/article_article0_2019-12-25': {
date: '2019-12-25T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 16, webUser: 16, lineVisit: 16, lineUser: 16 },
},
'/analytics/doc/article_article0_2019-12-26': {
date: '2019-12-26T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 17, webUser: 17, lineVisit: 17, lineUser: 17 },
},
'/analytics/doc/article_article0_2019-12-27': {
date: '2019-12-27T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 18, webUser: 18, lineVisit: 18, lineUser: 18 },
},
'/analytics/doc/article_article0_2019-12-28': {
date: '2019-12-28T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 19, webUser: 19, lineVisit: 19, lineUser: 19 },
},
'/analytics/doc/article_article0_2019-12-29': {
date: '2019-12-29T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 20, webUser: 20, lineVisit: 20, lineUser: 20 },
},
'/analytics/doc/article_article0_2019-12-30': {
date: '2019-12-30T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 21, webUser: 21, lineVisit: 21, lineUser: 21 },
},
'/analytics/doc/article_article0_2019-12-31': {
date: '2019-12-31T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 22, webUser: 22, lineVisit: 22, lineUser: 22 },
},
'/analytics/doc/article_article0_2020-01-01': {
date: '2020-01-01T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 23, webUser: 23, lineVisit: 23, lineUser: 23 },
},
'/analytics/doc/article_article0_2020-01-02': {
date: '2020-01-02T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 24, webUser: 24, lineVisit: 24, lineUser: 24 },
},
'/analytics/doc/article_article0_2020-01-03': {
date: '2020-01-03T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 25, webUser: 25, lineVisit: 25, lineUser: 25 },
},
'/analytics/doc/article_article0_2020-01-04': {
date: '2020-01-04T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 26, webUser: 26, lineVisit: 26, lineUser: 26 },
},
'/analytics/doc/article_article0_2020-01-05': {
date: '2020-01-05T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 27, webUser: 27, lineVisit: 27, lineUser: 27 },
},
'/analytics/doc/article_article0_2020-01-06': {
date: '2020-01-06T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 28, webUser: 28, lineVisit: 28, lineUser: 28 },
},
'/analytics/doc/article_article0_2020-01-07': {
date: '2020-01-07T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 29, webUser: 29, lineVisit: 29, lineUser: 29 },
},
'/analytics/doc/article_article0_2020-01-08': {
date: '2020-01-08T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 30, webUser: 30, lineVisit: 30, lineUser: 30 },
},
'/analytics/doc/article_article0_2020-01-09': {
date: '2020-01-09T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 31, webUser: 31, lineVisit: 31, lineUser: 31 },
},
'/analytics/doc/article_article0_2020-01-10': {
date: '2020-01-10T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 32, webUser: 32, lineVisit: 32, lineUser: 32 },
},
'/analytics/doc/article_article0_2020-01-11': {
date: '2020-01-11T00:00:00.000+08:00',
docId: 'article0',
type: 'article',
stats: { webVisit: 33, webUser: 33, lineVisit: 33, lineUser: 33 },
},
'/analytics/doc/article_articleId1_2020-01-03': {
date: '2020-01-03T00:00:00.000+08:00',
docId: 'articleId1',
type: 'article',
stats: { webVisit: 33, webUser: 27, lineVisit: 16, lineUser: 5 },
},
'/analytics/doc/article_articleId1_2020-01-04': {
date: '2020-01-04T00:00:00.000+08:00',
docId: 'articleId1',
type: 'article',
stats: { webVisit: 35, webUser: 1, lineVisit: 14, lineUser: 10 },
},
'/analytics/doc/article_articleId1_2020-01-05': {
date: '2020-01-05T00:00:00.000+08:00',
docId: 'articleId1',
type: 'article',
stats: { webVisit: 20, webUser: 13, lineVisit: 16, lineUser: 15 },
},
'/analytics/doc/reply_replyId1_2020-01-06': {
date: '2020-01-06T00:00:00.000+08:00',
docId: 'replyId1',
type: 'reply',
stats: { webVisit: 8, webUser: 2, lineVisit: 14, lineUser: 3 },
},
'/analytics/doc/reply_replyId2_2020-01-01': {
date: '2020-01-01T00:00:00.000+08:00',
docId: 'replyId2',
type: 'reply',
stats: { webVisit: 25, webUser: 6, lineVisit: 20, lineUser: 6 },
},
'/analytics/doc/reply_replyId2_2020-01-02': {
date: '2020-01-02T00:00:00.000+08:00',
docId: 'replyId2',
type: 'reply',
stats: { webVisit: 35, webUser: 10, lineVisit: 1, lineUser: 1 },
},
'/analytics/doc/reply_replyId2_2020-01-03': {
date: '2020-01-03T00:00:00.000+08:00',
docId: 'replyId2',
type: 'reply',
stats: { webVisit: 18, webUser: 4, lineVisit: 3, lineUser: 1 },
},
};
|
mit
|
terraswat/hexagram
|
www/imports/mapPage/shortlist/ShortEntryPres_forBarCharts.js
|
5161
|
// Presentational component for the short list entry.
import React from 'react';
import PropTypes from 'prop-types';
//import Slider, { Range } from 'rc-slider';
// We can just import Slider or Range to reduce bundle size
// import Slider from 'rc-slider/lib/Slider';
// import Range from 'rc-slider/lib/Range';
//import 'rc-slider/assets/index.css';
import BarChart from '/imports/mapPage/shortlist/BarChart'
import Icon, { icons } from '/imports/component/Icon'
import './shortEntry.css';
const filterIcon = (able) => {
// Render the filter icon.
if (able.indexOf('filtering') < 0) {
return null
}
let widget =
<Icon
icon = 'filter'
title = "Map is being filtered by this attribute's values"
className = 'hot filter circle'
/>
return widget;
}
const renderMetadata = (able, metadata) => {
// Render the metadata.
if (able.indexOf('metadata') < 0) {
return null
}
// TODO remove extra classes
let widget =
<table
className = 'layer-metadata'
>
<tbody>
{ metadata.map((row, i) =>
<tr key = { i }
>
<td className = 'rightAlign'
>
{ row[0] + ':' }
</td>
<td>
{ row[1] }
</td>
</tr>
)}
</tbody>
</table>
return widget
}
const barChart = (able) => {
// Render a bar chart for discrete values.
if (!able.includes('barChart')) {
return null
}
let widget = <BarChart />
return widget
}
const histogram = (able) => {
// Render a histogram for continuous values.
if (!able.includes('historgram')) {
return null
}
let widget = <Histogram />
return widget
}
const zeroTick = (able) => {
// Render the zero tickmark.
if (able.indexOf('zeroTick') < 0) {
return null
}
let widget =
<div
className = 'zero_tick'
>
</div>
return widget
}
const zero = (able) => {
// Render the zero.
if (able.indexOf('zero') < 0) {
return null
}
let widget =
<div
className = 'zero'
>
0
</div>
return widget
}
const rangeValues = (able, low, high) => {
// Render the range values for a continuous attr.
if (able.indexOf('rangeValues') < 0) {
return null
}
let widget =
<div
className = 'range_values'
>
{ zeroTick(able) }
{ zero(able) }
<div>
<div
className = 'range_low'
>
{ low }
</div>
<div
className = 'range_high'
>
{ high }
</div>
</div>
</div>
return widget;
}
const filterContents = (able, range) => {
// Render the filter content.
if (able.indexOf('filterContents') < 0) {
return null
}
let widget =
<div
className = 'filter_contents'
>
<div
className = 'range_slider'
value = { range }
data = {{ layer: 'TODO' }}
>
<div
className = 'low_mask mask'
>
</div>
<div
className = 'high_mask mask'
>
</div>
</div>
</div>
return widget;
}
const ShortEntryPres = ({ able, dynamic, floatControl, high, id,
low, metadata, range, zero, onMouseEnter, onMouseLeave }) => (
<div
className = { 'shortEntryRoot layer-entry ' + dynamic }
data = {{ layer: id }}
onMouseEnter = { onMouseEnter }
onMouseLeave = { onMouseLeave }
>
{ filterIcon(able) }
<div
className = 'attrLabel'
>
{ id }
</div>
{ renderMetadata(able, metadata) }
<div>
{ barChart(able) }
{ histogram(able) }
{ rangeValues(able, low, high) }
{ filterContents(able) }
</div>
<div
className = 'controls'
>
</div>
</div>
)
ShortEntryPres.propTypes = {
able: PropTypes.array, // capabilities to determine displayables
dynamic: PropTypes.string, // 'dynamic' indicates this is a dynamic attr
floatControl: PropTypes.string, // controls displayed on hover
high: PropTypes.number, // high range value
id: PropTypes.string, // attribute name
low: PropTypes.number, // low range value
metadata: PropTypes.array, // metadata rows
range: PropTypes.array, // range of ?
zero: PropTypes.bool, // show the zero tick mark
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
}
export default ShortEntryPres;
|
mit
|
ericlink/adms-server
|
playframework-dist/1.1-src/framework/src/play/mvc/results/RenderTemplate.java
|
960
|
package play.mvc.results;
import java.util.Map;
import play.exceptions.UnexpectedException;
import play.libs.MimeTypes;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.templates.Template;
/**
* 200 OK with a template rendering
*/
public class RenderTemplate extends Result {
private String name;
private String content;
public RenderTemplate(Template template, Map<String, Object> args) {
this.name = template.name;
this.content = template.render(args);
}
public void apply(Request request, Response response) {
try {
final String contentType = MimeTypes.getContentType(name, "text/plain");
response.out.write(content.getBytes("utf-8"));
setContentTypeIfNotSet(response, contentType);
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public String getContent() {
return content;
}
}
|
mit
|
YogiAi/site
|
resources/views/admin/partials/departments-selector.blade.php
|
371
|
<select name="departments[]" id="departments" multiple="true" class="form-control">
@foreach($departments as $department)
<option value="{{ $department->id }}" {{ in_array($department->id, old('departments', [])) || (isset($object) && $object->departments->contains($department)) ? 'selected' : '' }}>{{ $department->name }}</option>
@endforeach
</select>
|
mit
|
Bugfry/exercises
|
codeeval/ruby/racing.rb
|
201
|
last = nil
symbols = ["\\", "|", "/"]
IO.foreach(ARGV[0]){|line|
index = line.index("C") || line.index("_")
line[index] = last.nil? ? "|" : symbols[(last <=> index)+1]
puts line
last = index
}
|
mit
|
KaloyanchoSt/Telerik-Academy-HW
|
1. Programming C#/2. CSharp-Part-2/02. Multidimensional-Arrays/07. LargestAreaInMatrix/Properties/AssemblyInfo.cs
|
1446
|
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("07. Largest area in matrix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("07. Largest area in matrix")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("6d2a6341-0956-42cc-b147-eb264f87ea50")]
// 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
|
headwayio/voyage
|
lib/voyage/templates/api_users_controller.rb
|
1480
|
module Api
module V1
class UsersController < BaseApiController
# Warning:
# By default the ability to create an account via API is left wide open
load_and_authorize_resource except: [:create]
skip_authorization_check only: [:create]
skip_before_action :authenticate_user!, only: [:create]
def index
jsonapi_render json: User.all
end
def show
jsonapi_render json: @user
end
def create
@user = User.new(user_params)
# @user.roles << :user
if @user.save
# On successful creation, generate token and return in response
token = Tiddle.create_and_return_token(@user, request)
json = JSONAPI::ResourceSerializer
.new(Api::V1::UserResource)
.serialize_to_hash(Api::V1::UserResource.new(@user, nil))
render json: json.merge(
meta: {
authentication_token: token,
},
)
else
jsonapi_render_errors json: @user, status: :unprocessable_entity
end
end
def update
if @user.update_attributes(user_params)
jsonapi_render json: @user
else
jsonapi_render_errors json: @user, status: :unprocessable_entity
end
end
def destroy
@user.destroy
head :no_content
end
private
def user_params
resource_params
end
end
end
end
|
mit
|
maurer/tiamat
|
samples/Juliet/testcases/CWE134_Uncontrolled_Format_String/s02/CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B.cpp
|
1612
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-83_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: environment Read input from an environment variable
* GoodSource: Copy a fixed string into data
* Sinks: printf
* GoodSink: printf with "%s" as the first argument and data as the second
* BadSink : printf with only data as an argument
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__char_environment_printf_83.h"
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
namespace CWE134_Uncontrolled_Format_String__char_environment_printf_83
{
CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B::CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B(char * dataCopy)
{
data = dataCopy;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
}
CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B::~CWE134_Uncontrolled_Format_String__char_environment_printf_83_goodG2B()
{
/* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
printf(data);
}
}
#endif /* OMITGOOD */
|
mit
|
cowthan/Ayo2022
|
Ayo/ayo-extra/src/main/java/org/ayo/notify/sweet/ProgressHelper.java
|
4456
|
package org.ayo.notify.sweet;
import android.content.Context;
import org.ayo.notify.R;
public class ProgressHelper {
private ProgressWheel mProgressWheel;
private boolean mToSpin;
private float mSpinSpeed;
private int mBarWidth;
private int mBarColor;
private int mRimWidth;
private int mRimColor;
private boolean mIsInstantProgress;
private float mProgressVal;
private int mCircleRadius;
public ProgressHelper(Context ctx) {
mToSpin = true;
mSpinSpeed = 0.75f;
mBarWidth = ctx.getResources().getDimensionPixelSize(R.dimen.common_circle_width) + 1;
mBarColor = ctx.getResources().getColor(R.color.success_stroke_color);
mRimWidth = 0;
mRimColor = 0x00000000;
mIsInstantProgress = false;
mProgressVal = -1;
mCircleRadius = ctx.getResources().getDimensionPixelOffset(R.dimen.progress_circle_radius);
}
public ProgressWheel getProgressWheel () {
return mProgressWheel;
}
public void setProgressWheel (ProgressWheel progressWheel) {
mProgressWheel = progressWheel;
updatePropsIfNeed();
}
private void updatePropsIfNeed () {
if (mProgressWheel != null) {
if (!mToSpin && mProgressWheel.isSpinning()) {
mProgressWheel.stopSpinning();
} else if (mToSpin && !mProgressWheel.isSpinning()) {
mProgressWheel.spin();
}
if (mSpinSpeed != mProgressWheel.getSpinSpeed()) {
mProgressWheel.setSpinSpeed(mSpinSpeed);
}
if (mBarWidth != mProgressWheel.getBarWidth()) {
mProgressWheel.setBarWidth(mBarWidth);
}
if (mBarColor != mProgressWheel.getBarColor()) {
mProgressWheel.setBarColor(mBarColor);
}
if (mRimWidth != mProgressWheel.getRimWidth()) {
mProgressWheel.setRimWidth(mRimWidth);
}
if (mRimColor != mProgressWheel.getRimColor()) {
mProgressWheel.setRimColor(mRimColor);
}
if (mProgressVal != mProgressWheel.getProgress()) {
if (mIsInstantProgress) {
mProgressWheel.setInstantProgress(mProgressVal);
} else {
mProgressWheel.setProgress(mProgressVal);
}
}
if (mCircleRadius != mProgressWheel.getCircleRadius()) {
mProgressWheel.setCircleRadius(mCircleRadius);
}
}
}
public void resetCount() {
if (mProgressWheel != null) {
mProgressWheel.resetCount();
}
}
public boolean isSpinning() {
return mToSpin;
}
public void spin() {
mToSpin = true;
updatePropsIfNeed();
}
public void stopSpinning() {
mToSpin = false;
updatePropsIfNeed();
}
public float getProgress() {
return mProgressVal;
}
public void setProgress(float progress) {
mIsInstantProgress = false;
mProgressVal = progress;
updatePropsIfNeed();
}
public void setInstantProgress(float progress) {
mProgressVal = progress;
mIsInstantProgress = true;
updatePropsIfNeed();
}
public int getCircleRadius() {
return mCircleRadius;
}
/**
* @param circleRadius units using pixel
* **/
public void setCircleRadius(int circleRadius) {
mCircleRadius = circleRadius;
updatePropsIfNeed();
}
public int getBarWidth() {
return mBarWidth;
}
public void setBarWidth(int barWidth) {
mBarWidth = barWidth;
updatePropsIfNeed();
}
public int getBarColor() {
return mBarColor;
}
public void setBarColor(int barColor) {
mBarColor = barColor;
updatePropsIfNeed();
}
public int getRimWidth() {
return mRimWidth;
}
public void setRimWidth(int rimWidth) {
mRimWidth = rimWidth;
updatePropsIfNeed();
}
public int getRimColor() {
return mRimColor;
}
public void setRimColor(int rimColor) {
mRimColor = rimColor;
updatePropsIfNeed();
}
public float getSpinSpeed() {
return mSpinSpeed;
}
public void setSpinSpeed(float spinSpeed) {
mSpinSpeed = spinSpeed;
updatePropsIfNeed();
}
}
|
mit
|
arantebillywilson/python-snippets
|
py2/htp/ch06/fig06_10.py
|
1267
|
#!/usr/bin/python
#
# fig06_10.py
# Demonstrates use of cgi.FieldStorage with XHTML form.
#
# Author: Billy Wison Arante
# Created: 2016/09/01 EST (America/New York)
#
# Attribution: Python How to Program, 1st Ed. by Deitel & Deitel
#
import cgi
def print_header(title):
"""Prints a simple header"""
print """Content-type: text/html
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>%s</title>
</head>
<body>
""" % title
def main():
"""Main"""
print_header("Using cgi.FieldStorage with forms")
print """
<p>Enter one of your favorite words here:<br /></p>
<form method="post" action="fig06_10.py">
<p>
<input type="text" name="word" />
<input type="submit" value="Submit Word" />
</p>
</form>
"""
form = cgi.FieldStorage()
if form.has_key("word"):
print """
<p>Your word is: <span style="font-weight:bold;">%s</span></p>
""" % cgi.escape(form["word"].value)
print """
</body>
</html>
"""
if __name__ == "__main__":
main()
|
mit
|
codeclimate/codeclimate-eslint
|
lib/batch_sanitizer.js
|
942
|
var fs = require("fs");
var MINIFIED_AVG_LINE_LENGTH_CUTOFF = 100;
function BatchSanitizer(files, stderr) {
this.files = files;
this.stderr = stderr || process.stderr;
}
BatchSanitizer.prototype.sanitizedFiles = function() {
var sanitizedFiles = [];
for(var i = 0; i < this.files.length; i++) {
if (this.isMinified(this.files[i])) {
this.stderr.write("WARN: Skipping " + this.files[i] + ": it appears to be minified\n");
} else {
sanitizedFiles.push(this.files[i]);
}
}
return sanitizedFiles;
};
BatchSanitizer.prototype.isMinified = function(path) {
var buf = fs.readFileSync(path)
, newline = "\n".charCodeAt(0)
, lineCount = 0
, charsSeen = 0;
for(var i = 0; i < buf.length; i++) {
if (buf[i] === newline) {
lineCount++;
} else {
charsSeen++;
}
}
return (charsSeen / lineCount) >= MINIFIED_AVG_LINE_LENGTH_CUTOFF;
};
module.exports = BatchSanitizer;
|
mit
|
lrakhman/DontParkThereChicago
|
db/schema.rb
|
2519
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140708192007) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
enable_extension "postgis"
create_table "delayed_jobs", force: true do |t|
t.integer "priority", default: 0, null: false
t.integer "attempts", default: 0, null: false
t.text "handler", null: false
t.text "last_error"
t.datetime "run_at"
t.datetime "locked_at"
t.datetime "failed_at"
t.string "locked_by"
t.string "queue"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "delayed_jobs", ["priority", "run_at"], :name => "delayed_jobs_priority"
create_table "notifications", force: true do |t|
t.integer "user_id"
t.integer "region_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email"
t.date "sent_at"
t.string "phone"
end
create_table "users", force: true do |t|
t.string "firstname"
t.string "lastname"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "phone"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
|
mit
|
theplant/qor_test
|
lib/qor_test/gemfile.rb
|
1841
|
module Qor
module Test
class Gemfile
attr_accessor :options
def initialize options={}
self.options = options
end
def ruby_versions
versions = Qor::Test::Configuration.ruby_versions(options)
versions.empty? ? [RUBY_VERSION] : versions
end
def group_name
Qor::Test::Configuration.envs(options)[0]
end
def generate_gemfiles
gems_set_from_config = Qor::Test::Configuration.gems_set_from_config(options)
gems_hash_from_gemfile = Qor::Test::Configuration.gems_hash_from_gemfile(options)
gemfile_length = [gems_set_from_config.length, 1].max
gemfile_dir = File.join(Qor::Test::CLI.temp_directory, Qor::Test::Configuration.configuration_digest(options))
if File.exist?(gemfile_dir)
Dir[File.join(gemfile_dir, '*')].select {|x| x !~ /.lock$/ }
else
FileUtils.mkdir_p(gemfile_dir)
(0...gemfile_length).map do |index|
filename = File.join(gemfile_dir, "Gemfile.#{index}")
write_gemfile(gems_set_from_config[index] || {}, gems_hash_from_gemfile, filename)
end
end
end
def generate_gems_entry(gems_from_config, gems_from_gemfile)
gem_names = [gems_from_config.keys, gems_from_gemfile.keys].flatten.compact.uniq
gem_names.map do |name|
gems_from_config[name] || gems_from_gemfile[name]
end.compact.map(&:to_s).join("\n")
end
def write_gemfile(gems_from_config, gems_from_gemfile, filename)
File.open(filename, "w+") do |f|
f << Qor::Test::Configuration.combined_sources(options)
f << Qor::Test::Configuration.combined_gemspecs(options)
f << generate_gems_entry(gems_from_config, gems_from_gemfile)
end.path
end
end
end
end
|
mit
|
chiepomme/TwitterMVGenerator
|
Assets/UTJ/FrameCapturer/Editor/GBufferRecorderEditor.cs
|
2501
|
using System;
using UnityEditor;
using UnityEngine;
namespace UTJ.FrameCapturer
{
[CustomEditor(typeof(GBufferRecorder))]
public class ImageSequenceRecorderEditor : RecorderBaseEditor
{
public override void OnInspectorGUI()
{
//DrawDefaultInspector();
var recorder = target as GBufferRecorder;
var so = serializedObject;
CommonConfig();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Capture Components");
EditorGUI.indentLevel++;
{
EditorGUI.BeginChangeCheck();
var fbc = recorder.fbComponents;
fbc.frameBuffer = EditorGUILayout.Toggle("Frame Buffer", fbc.frameBuffer);
if(fbc.frameBuffer)
{
EditorGUI.indentLevel++;
fbc.fbColor = EditorGUILayout.Toggle("Color", fbc.fbColor);
fbc.fbAlpha = EditorGUILayout.Toggle("Alpha", fbc.fbAlpha);
EditorGUI.indentLevel--;
}
fbc.GBuffer = EditorGUILayout.Toggle("GBuffer", fbc.GBuffer);
if (fbc.GBuffer)
{
EditorGUI.indentLevel++;
fbc.gbAlbedo = EditorGUILayout.Toggle("Albedo", fbc.gbAlbedo);
fbc.gbOcclusion = EditorGUILayout.Toggle("Occlusion", fbc.gbOcclusion);
fbc.gbSpecular = EditorGUILayout.Toggle("Specular", fbc.gbSpecular);
fbc.gbSmoothness= EditorGUILayout.Toggle("Smoothness", fbc.gbSmoothness);
fbc.gbNormal = EditorGUILayout.Toggle("Normal", fbc.gbNormal);
fbc.gbEmission = EditorGUILayout.Toggle("Emission", fbc.gbEmission);
fbc.gbDepth = EditorGUILayout.Toggle("Depth", fbc.gbDepth);
fbc.gbVelocity = EditorGUILayout.Toggle("Velocity", fbc.gbVelocity);
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
recorder.fbComponents = fbc;
EditorUtility.SetDirty(recorder);
}
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
ResolutionControl();
FramerateControl();
EditorGUILayout.Space();
RecordingControl();
so.ApplyModifiedProperties();
}
}
}
|
mit
|
jeraldfeller/jbenterprises
|
google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201705/cm/RateExceededErrorReason.php
|
191
|
<?php
namespace Google\AdsApi\AdWords\v201705\cm;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class RateExceededErrorReason
{
const RATE_EXCEEDED = 'RATE_EXCEEDED';
}
|
mit
|
non/scalaz-contrib
|
spire/main/scala/conversions.scala
|
2469
|
package scalaz.contrib
package spire
import scalaz.@@
import scalaz.Tags.Multiplication
import _root_.spire.algebra
private[scalaz] trait ToSpireConversions0 {
implicit def scalazSemigroup2Spire[F](implicit m: scalaz.Semigroup[F]): algebra.Semigroup[F] = m.asSpire
implicit def scalazAddSemigroup2Spire[F](implicit m: scalaz.Semigroup[F]): algebra.AdditiveSemigroup[F] = m.asSpireAdditive
implicit def scalazMulSemigroup2Spire[F](implicit m: scalaz.Semigroup[F @@ Multiplication]): algebra.MultiplicativeSemigroup[F] = m.asSpire
implicit def scalazEqual2Spire[F](implicit m: scalaz.Equal[F]): algebra.Eq[F] = m.asSpire
}
private[scalaz] trait ToSpireConversions extends ToSpireConversions0 {
implicit def scalazMonoid2Spire[F](implicit m: scalaz.Monoid[F]): algebra.Monoid[F] = m.asSpire
implicit def scalazAddMonoid2Spire[F](implicit m: scalaz.Monoid[F]): algebra.AdditiveMonoid[F] = m.asSpireAdditive
implicit def scalazMulMonoid2Spire[F](implicit m: scalaz.Monoid[F @@ Multiplication]): algebra.MultiplicativeMonoid[F] = m.asSpire
implicit def scalazOrder2Spire[F](implicit m: scalaz.Order[F]): algebra.Order[F] = m.asSpire
}
private[scalaz] trait ToScalazConversions2 {
implicit def spireAddSemigroup2Scalaz[F](implicit m: algebra.AdditiveSemigroup[F]): scalaz.Semigroup[F] = m.asScalaz
}
private[scalaz] trait ToScalazConversions1 extends ToScalazConversions2 {
implicit def spireAddMonoid2Scalaz[F](implicit m: algebra.AdditiveMonoid[F]): scalaz.Monoid[F] = m.asScalaz
}
private[scalaz] trait ToScalazConversions0 extends ToScalazConversions1 {
implicit def spireSemigroup2Scalaz[F](implicit m: algebra.Semigroup[F]): scalaz.Semigroup[F] = m.asScalaz
implicit def spireMulSemigroup2Scalaz[F](implicit m: algebra.MultiplicativeSemigroup[F]): scalaz.Semigroup[F @@ Multiplication] = m.asScalaz
implicit def spireEq2Scalaz[F](implicit m: algebra.Eq[F]): scalaz.Equal[F] = m.asScalaz
}
private[scalaz] trait ToScalazConversions extends ToScalazConversions0 {
implicit def spireMonoid2Scalaz[F](implicit m: algebra.Monoid[F]): scalaz.Monoid[F] = m.asScalaz
implicit def spireMulMonoid2Scalaz[F](implicit m: algebra.MultiplicativeMonoid[F]): scalaz.Monoid[F @@ Multiplication] = m.asScalaz
implicit def spireOrder2Scalaz[F](implicit m: algebra.Order[F]): scalaz.Order[F] = m.asScalaz
}
object conversions {
object toSpire extends ToSpireConversions
object toScalaz extends ToScalazConversions
}
// vim: expandtab:ts=2:sw=2
|
mit
|
darshanhs90/Java-InterviewPrep
|
src/LeetcodeTemplate/_0476NumberComplement.java
|
244
|
package LeetcodeTemplate;
public class _0476NumberComplement {
public static void main(String[] args) {
System.out.println(findComplement(5));
System.out.println(findComplement(1));
}
public static int findComplement(int num) {
}
}
|
mit
|
Narentharaa/evnts
|
app/src/main/java/com/code/hacks/codered/evnts/evnts/adapters/EventListAdapter.java
|
8847
|
package com.code.hacks.codered.evnts.evnts.adapters;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.code.hacks.codered.evnts.evnts.DetailActivity;
import com.code.hacks.codered.evnts.evnts.MainActivity;
import com.code.hacks.codered.evnts.evnts.R;
import com.code.hacks.codered.evnts.evnts.bean.Event;
import com.code.hacks.codered.evnts.evnts.bean.Favored;
import com.code.hacks.codered.evnts.evnts.bean.Session;
import com.code.hacks.codered.evnts.evnts.util.Constants;
import com.code.hacks.codered.evnts.evnts.views.CustomButton;
import com.code.hacks.codered.evnts.evnts.views.CustomTextView;
import com.code.hacks.codered.evnts.evnts.views.CustomTextViewBold;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sudharti on 11/21/15.
*/
public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder> {
private Context context;
private ArrayList<Event> eventArrayList;
private SharedPreferences pref;
private String eventPref = "EVENT_PREF";
public EventListAdapter(Context context, ArrayList<Event> eventsArrayList) {
this.context = context;
this.eventArrayList = eventsArrayList;
}
@Override
public EventListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(EventListAdapter.ViewHolder holder, int position) {
final Event event = eventArrayList.get(position);
holder.eventName.setText(event.getName());
holder.eventLocation.setText(event.getLocation());
holder.eventDate.setText(event.getDate());
Picasso.with(context)
.load(event.getImageUrl())
.into(holder.eventImage);
pref = context.getSharedPreferences(eventPref, Context.MODE_PRIVATE);
isBookmarked(context, eventArrayList.get(position).getId(), pref.getString("current_user_id", "0"), holder.bookmarkButton);
}
@Override
public int getItemCount() {
return eventArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView eventImage;
private CustomTextViewBold eventName;
private CustomTextView eventDate;
private CustomTextView eventLocation;
private ImageButton shareButton;
private ImageButton bookmarkButton;
private CustomButton moreDetailButton;
public ViewHolder(View itemView) {
super(itemView);
eventImage = (ImageView) itemView.findViewById(R.id.event_image);
eventName = (CustomTextViewBold) itemView.findViewById(R.id.event_name);
eventLocation = (CustomTextView) itemView.findViewById(R.id.event_location);
eventDate = (CustomTextView) itemView.findViewById(R.id.event_date);
shareButton = (ImageButton) itemView.findViewById(R.id.share_button);
bookmarkButton = (ImageButton) itemView.findViewById(R.id.bookmark_button);
moreDetailButton = (CustomButton) itemView.findViewById(R.id.more_detail_button);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
v.getContext().startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
bookmarkButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
for(Event event : eventArrayList) {
if (event.getName().trim().equals(eventName.getText().toString().trim())) {
pref = context.getSharedPreferences(eventPref, Context.MODE_PRIVATE);
createBookmark(context, event.getId(), pref.getString("current_user_id", "0"));
break;
}
}
}
});
moreDetailButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent detail = new Intent(v.getContext(), DetailActivity.class);
for(Event event : eventArrayList) {
if (event.getName().trim().equals(eventName.getText().toString().trim())) {
detail.putExtra("event_id", event.getId());
break;
}
}
v.getContext().startActivity(detail);
}
});
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent detail = new Intent(v.getContext(), DetailActivity.class);
//Call the Event Detail Intent here
for(Event event : eventArrayList) {
if (event.getName().trim().equals(eventName.getText().toString().trim())) {
detail.putExtra("event_id", event.getId());
break;
}
}
v.getContext().startActivity(detail);
}
}
public void createBookmark(final Context context, final int eventId, final String userId) {
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, Constants.API_URL + "favourites/", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
Favored favored = gson.fromJson(response, Favored.class);
Toast.makeText(context, "Bookmarked Event", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String,String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userId);
params.put("event_id", String.valueOf(eventId));
return params;
}
};
queue.add(sr);
}
public void isBookmarked(final Context context, final int eventId, final String userId, final ImageButton favButton) {
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, Constants.API_URL + "favourites/favored?user_id" + userId + "&event_id=" + eventId, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
Favored favored = gson.fromJson(response, Favored.class);
if(favored.isFavored()) {
favButton.setImageDrawable(context.getResources().getDrawable(R.mipmap.ic_action_bookmark));
} else {
favButton.setImageDrawable(context.getResources().getDrawable(R.mipmap.ic_action_bookmark));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String,String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(sr);
}
}
|
mit
|
nicoddemus/repo-test
|
_pytest/unittest.py
|
6386
|
""" discovery and running of std-library "unittest" style tests. """
from __future__ import absolute_import
import traceback
import sys
import pytest
import py
# for transfering markers
from _pytest.python import transfer_markers
def pytest_pycollect_makeitem(collector, name, obj):
# has unittest been imported and is obj a subclass of its TestCase?
try:
if not issubclass(obj, sys.modules["unittest"].TestCase):
return
except Exception:
return
# yes, so let's collect it
return UnitTestCase(name, parent=collector)
class UnitTestCase(pytest.Class):
nofuncargs = True # marker for fixturemanger.getfixtureinfo()
# to declare that our children do not support funcargs
#
def setup(self):
cls = self.obj
if getattr(cls, '__unittest_skip__', False):
return # skipped
setup = getattr(cls, 'setUpClass', None)
if setup is not None:
setup()
teardown = getattr(cls, 'tearDownClass', None)
if teardown is not None:
self.addfinalizer(teardown)
super(UnitTestCase, self).setup()
def collect(self):
from unittest import TestLoader
cls = self.obj
if not getattr(cls, "__test__", True):
return
self.session._fixturemanager.parsefactories(self, unittest=True)
loader = TestLoader()
module = self.getparent(pytest.Module).obj
foundsomething = False
for name in loader.getTestCaseNames(self.obj):
x = getattr(self.obj, name)
funcobj = getattr(x, 'im_func', x)
transfer_markers(funcobj, cls, module)
yield TestCaseFunction(name, parent=self)
foundsomething = True
if not foundsomething:
runtest = getattr(self.obj, 'runTest', None)
if runtest is not None:
ut = sys.modules.get("twisted.trial.unittest", None)
if ut is None or runtest != ut.TestCase.runTest:
yield TestCaseFunction('runTest', parent=self)
class TestCaseFunction(pytest.Function):
_excinfo = None
def setup(self):
self._testcase = self.parent.obj(self.name)
self._obj = getattr(self._testcase, self.name)
if hasattr(self._testcase, 'setup_method'):
self._testcase.setup_method(self._obj)
if hasattr(self, "_request"):
self._request._fillfixtures()
def teardown(self):
if hasattr(self._testcase, 'teardown_method'):
self._testcase.teardown_method(self._obj)
def startTest(self, testcase):
pass
def _addexcinfo(self, rawexcinfo):
# unwrap potential exception info (see twisted trial support below)
rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo)
try:
excinfo = py.code.ExceptionInfo(rawexcinfo)
except TypeError:
try:
try:
l = traceback.format_exception(*rawexcinfo)
l.insert(0, "NOTE: Incompatible Exception Representation, "
"displaying natively:\n\n")
pytest.fail("".join(l), pytrace=False)
except (pytest.fail.Exception, KeyboardInterrupt):
raise
except:
pytest.fail("ERROR: Unknown Incompatible Exception "
"representation:\n%r" %(rawexcinfo,), pytrace=False)
except KeyboardInterrupt:
raise
except pytest.fail.Exception:
excinfo = py.code.ExceptionInfo()
self.__dict__.setdefault('_excinfo', []).append(excinfo)
def addError(self, testcase, rawexcinfo):
self._addexcinfo(rawexcinfo)
def addFailure(self, testcase, rawexcinfo):
self._addexcinfo(rawexcinfo)
def addSkip(self, testcase, reason):
try:
pytest.skip(reason)
except pytest.skip.Exception:
self._addexcinfo(sys.exc_info())
def addExpectedFailure(self, testcase, rawexcinfo, reason=""):
try:
pytest.xfail(str(reason))
except pytest.xfail.Exception:
self._addexcinfo(sys.exc_info())
def addUnexpectedSuccess(self, testcase, reason=""):
self._unexpectedsuccess = reason
def addSuccess(self, testcase):
pass
def stopTest(self, testcase):
pass
def runtest(self):
self._testcase(result=self)
def _prunetraceback(self, excinfo):
pytest.Function._prunetraceback(self, excinfo)
traceback = excinfo.traceback.filter(
lambda x:not x.frame.f_globals.get('__unittest'))
if traceback:
excinfo.traceback = traceback
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_makereport(item, call):
if isinstance(item, TestCaseFunction):
if item._excinfo:
call.excinfo = item._excinfo.pop(0)
try:
del call.result
except AttributeError:
pass
# twisted trial support
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item):
if isinstance(item, TestCaseFunction) and \
'twisted.trial.unittest' in sys.modules:
ut = sys.modules['twisted.python.failure']
Failure__init__ = ut.Failure.__init__
check_testcase_implements_trial_reporter()
def excstore(self, exc_value=None, exc_type=None, exc_tb=None,
captureVars=None):
if exc_value is None:
self._rawexcinfo = sys.exc_info()
else:
if exc_type is None:
exc_type = type(exc_value)
self._rawexcinfo = (exc_type, exc_value, exc_tb)
try:
Failure__init__(self, exc_value, exc_type, exc_tb,
captureVars=captureVars)
except TypeError:
Failure__init__(self, exc_value, exc_type, exc_tb)
ut.Failure.__init__ = excstore
yield
ut.Failure.__init__ = Failure__init__
else:
yield
def check_testcase_implements_trial_reporter(done=[]):
if done:
return
from zope.interface import classImplements
from twisted.trial.itrial import IReporter
classImplements(TestCaseFunction, IReporter)
done.append(1)
|
mit
|
StratifyLabs/StratifyAPI
|
src/ux/Progress.cpp
|
665
|
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include "ux/Progress.hpp"
using namespace ux;
Progress::Progress(const var::String& name) : ComponentAccess<Progress>(name){
m_value = 0;
m_maximum = 100;
}
void Progress::handle_event(const ux::Event & event){
//change the state when an event happens in the component
if( event.type() == ux::TouchEvent::event_type() ){
const ux::TouchEvent & touch_event
= event.reinterpret<ux::TouchEvent>();
if( (touch_event.id() == ux::TouchEvent::id_released) &&
contains(touch_event.point()) ){
redraw();
}
}
Component::handle_event(event);
}
|
mit
|
anhstudios/swganh
|
data/scripts/templates/object/tangible/deed/city_deed/shared_garden_tatooine_lrg_03_deed.py
|
477
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/deed/city_deed/shared_garden_tatooine_lrg_03_deed.iff"
result.attribute_template_id = 2
result.stfName("deed","garden_tatooine_lrg_03_deed")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result
|
mit
|
ValtoFrameworks/Angular-2
|
packages/platform-browser-dynamic/test/testing_public_browser_spec.ts
|
5206
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ResourceLoader} from '@angular/compiler';
import {Compiler, Component, NgModule} from '@angular/core';
import {TestBed, async, fakeAsync, inject, tick} from '@angular/core/testing';
import {ResourceLoaderImpl} from '../src/resource_loader/resource_loader_impl';
// Components for the tests.
class FancyService {
value: string = 'real value';
getAsyncValue() { return Promise.resolve('async value'); }
getTimeoutValue() {
return new Promise(
(resolve, reject) => { setTimeout(() => { resolve('timeout value'); }, 10); });
}
}
@Component({
selector: 'external-template-comp',
templateUrl: '/base/angular/packages/platform-browser/test/static_assets/test.html'
})
class ExternalTemplateComp {
}
@Component({selector: 'bad-template-comp', templateUrl: 'non-existent.html'})
class BadTemplateUrl {
}
// Tests for angular/testing bundle specific to the browser environment.
// For general tests, see test/testing/testing_public_spec.ts.
if (isBrowser) {
describe('test APIs for the browser', () => {
describe('using the async helper', () => {
let actuallyDone: boolean;
beforeEach(() => { actuallyDone = false; });
afterEach(() => { expect(actuallyDone).toEqual(true); });
it('should run async tests with ResourceLoaders', async(() => {
const resourceLoader = new ResourceLoaderImpl();
resourceLoader
.get('/base/angular/packages/platform-browser/test/static_assets/test.html')
.then(() => { actuallyDone = true; });
}),
10000); // Long timeout here because this test makes an actual ResourceLoader.
});
describe('using the test injector with the inject helper', () => {
describe('setting up Providers', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: FancyService, useValue: new FancyService()}]});
});
it('provides a real ResourceLoader instance',
inject([ResourceLoader], (resourceLoader: ResourceLoader) => {
expect(resourceLoader instanceof ResourceLoaderImpl).toBeTruthy();
}));
it('should allow the use of fakeAsync',
fakeAsync(inject([FancyService], (service: any /** TODO #9100 */) => {
let value: any /** TODO #9100 */;
service.getAsyncValue().then(function(val: any /** TODO #9100 */) { value = val; });
tick();
expect(value).toEqual('async value');
})));
});
});
describe('Compiler', () => {
it('should return NgModule id when asked', () => {
@NgModule({
id: 'test-module',
})
class TestModule {
}
TestBed.configureTestingModule({
imports: [TestModule],
});
const compiler = TestBed.get(Compiler) as Compiler;
expect(compiler.getModuleId(TestModule)).toBe('test-module');
});
});
describe('errors', () => {
let originalJasmineIt: any;
const patchJasmineIt = () => {
let resolve: (result: any) => void;
let reject: (error: any) => void;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
originalJasmineIt = jasmine.getEnv().it;
jasmine.getEnv().it = (description: string, fn: (done: DoneFn) => void): any => {
const done = (() => resolve(null)) as DoneFn;
done.fail = reject;
fn(done);
return null;
};
return promise;
};
const restoreJasmineIt = () => { jasmine.getEnv().it = originalJasmineIt; };
it('should fail when an ResourceLoader fails', done => {
const itPromise = patchJasmineIt();
it('should fail with an error from a promise', async(() => {
TestBed.configureTestingModule({declarations: [BadTemplateUrl]});
TestBed.compileComponents();
}));
itPromise.then(
() => { done.fail('Expected test to fail, but it did not'); },
(err: any) => {
expect(err.message)
.toEqual('Uncaught (in promise): Failed to load non-existent.html');
done();
});
restoreJasmineIt();
}, 10000);
});
describe('TestBed createComponent', function() {
it('should allow an external templateUrl', async(() => {
TestBed.configureTestingModule({declarations: [ExternalTemplateComp]});
TestBed.compileComponents().then(() => {
const componentFixture = TestBed.createComponent(ExternalTemplateComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement.textContent).toEqual('from external template');
});
}),
10000); // Long timeout here because this test makes an actual ResourceLoader request, and
// is slow
// on Edge.
});
});
}
|
mit
|
tapomayukh/projects_in_c_cpp
|
Phantom Control Program/Cpp_pos_enc/GetState/src/GetStateValues.cpp
|
3367
|
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#if defined(WIN32)
# include <conio.h>
#else
# include "conio.h"
#endif
#include <HD/hd.h>
#include <HDU/hdu.h>
#include <HDU/hduError.h>
#include <HDU/hduVector.h>
#include "GetStateValues.h"
#include "C:\Program Files\SensAble\3DTouch\examples\HD\console\Arindam\Cpp_pos_enc\GetState\TimeTick.h"
static int gNumEncoders;
CTimeTick gTime;
FILE* f;
FILE* p = fopen("values.txt", "w");
HDSchedulerHandle gCallbackHandle = HD_INVALID_HANDLE;
HDCallbackCode HDCALLBACK GetDeviceStateCallback(void *pUserData)
{
gTime.SetEnd();
float time=gTime.GetTick();
fprintf(f,"%f\n",time);
gTime.SetStart();
//int fty = 22;
GetStateValues *pState = (GetStateValues *) pUserData;
hdBeginFrame(hdGetCurrentDevice());
hdGetLongv(HD_CURRENT_ENCODER_VALUES, pState->encoder_values);
hdGetDoublev(HD_CURRENT_POSITION, pState->position);
hdGetDoublev(HD_CURRENT_TRANSFORM,pState->transform);
fprintf(p,"%f\n",pState->position[0]);
hdEndFrame(hdGetCurrentDevice());
return HD_CALLBACK_CONTINUE;
}
void GetStateValues::GetDeviceState()
{
hdScheduleAsynchronous(GetDeviceStateCallback, this,HD_DEFAULT_SCHEDULER_PRIORITY);
}
void GetStateValues::printDeviceState()
{
int i,j;
system("cls");
printf("\n");
printf("Encoder Values:");
for (i = 0; i < gNumEncoders; i++)
{
printf(" %d \t", this->encoder_values[i]);
}
printf("\n \n");
printf("Position:");
for (i = 0; i < 3; i++)
{
printf(" %f \t", this->position[i]);
}
printf("\n \n");
printf("Transformation Matrix Values: \n \n");
for (i = 0; i < 4; i++)
{
for(j=0;j<4;j++)
{
printf(" %f ", this->transform[i*4+j]);
//if((i+1) % 3 == 0 )
//printf("\n");
}
printf("\n");
}
}
/*******************************************************************************
Main function.
*******************************************************************************/
int main(int argc, char* argv[])
{
f=fopen("time.txt","w");
HDErrorInfo error;
HDboolean bDone = FALSE;
HHD hHD = hdInitDevice(HD_DEFAULT_DEVICE);
if (HD_DEVICE_ERROR(error = hdGetError()))
{
hduPrintError(stderr, &error, "Failed to initialize haptic device");
fprintf(stderr, "\nPress any key to quit.\n");
getch();
return -1;
}
hdGetIntegerv(HD_INPUT_DOF, &gNumEncoders);
/* Start the haptic rendering loop */
hdStartScheduler();
if (HD_DEVICE_ERROR(error = hdGetError()))
{
hduPrintError(stderr, &error, "Failed to start servoloop");
fprintf(stderr, "\nPress any key to quit.\n");
getch();
hdDisableDevice(hHD);
return -1;
}
GetStateValues state;
state.GetDeviceState();
do
{
state.printDeviceState();
/* Check if the scheduled callback has stopped running */
/*if (!hdWaitForCompletion(gCallbackHandle, HD_WAIT_CHECK_STATUS))
{
fprintf(stderr, "\nThe main scheduler callback has exited\n");
fprintf(stderr, "\nPress any key to quit.\n");
getch();
}*/
if (1)
{
Sleep(5);
}
} while (!_kbhit());
hdStopScheduler();
hdDisableDevice(hHD);
return 0;
}
|
mit
|
hmehr/OSS
|
MemoryLifter/Development/Current/MLifter.DAL/CSV/Exceptions/MalformedCsvException.cs
|
7644
|
// MLifter.DAL.CSV.MalformedCsvException
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_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.
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using MLifter.DAL.CSV.Resources;
namespace MLifter.DAL.CSV
{
/// <summary>
/// Represents the exception that is thrown when a CSV file is malformed.
/// </summary>
[Serializable()]
public class MalformedCsvException
: Exception
{
#region Fields
/// <summary>
/// Contains the message that describes the error.
/// </summary>
private string _message;
/// <summary>
/// Contains the raw data when the error occured.
/// </summary>
private string _rawData;
/// <summary>
/// Contains the current field index.
/// </summary>
private int _currentFieldIndex;
/// <summary>
/// Contains the current record index.
/// </summary>
private long _currentRecordIndex;
/// <summary>
/// Contains the current position in the raw data.
/// </summary>
private int _currentPosition;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
public MalformedCsvException()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public MalformedCsvException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MalformedCsvException(string message, Exception innerException)
: base(String.Empty, innerException)
{
_message = (message == null ? string.Empty : message);
_rawData = string.Empty;
_currentPosition = -1;
_currentRecordIndex = -1;
_currentFieldIndex = -1;
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
public MalformedCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex)
: this(rawData, currentPosition, currentRecordIndex, currentFieldIndex, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MalformedCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex, Exception innerException)
: base(String.Empty, innerException)
{
_rawData = (rawData == null ? string.Empty : rawData);
_currentPosition = currentPosition;
_currentRecordIndex = currentRecordIndex;
_currentFieldIndex = currentFieldIndex;
_message = String.Format(CultureInfo.InvariantCulture, ExceptionMessage.MalformedCsvException, _currentRecordIndex, _currentFieldIndex, _currentPosition, _rawData);
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:StreamingContext"/> that contains contextual information about the source or destination.</param>
protected MalformedCsvException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_message = info.GetString("MyMessage");
_rawData = info.GetString("RawData");
_currentPosition = info.GetInt32("CurrentPosition");
_currentRecordIndex = info.GetInt64("CurrentRecordIndex");
_currentFieldIndex = info.GetInt32("CurrentFieldIndex");
}
#endregion
#region Properties
/// <summary>
/// Gets the raw data when the error occured.
/// </summary>
/// <value>The raw data when the error occured.</value>
public string RawData
{
get { return _rawData; }
}
/// <summary>
/// Gets the current position in the raw data.
/// </summary>
/// <value>The current position in the raw data.</value>
public int CurrentPosition
{
get { return _currentPosition; }
}
/// <summary>
/// Gets the current record index.
/// </summary>
/// <value>The current record index.</value>
public long CurrentRecordIndex
{
get { return _currentRecordIndex; }
}
/// <summary>
/// Gets the current field index.
/// </summary>
/// <value>The current record index.</value>
public int CurrentFieldIndex
{
get { return _currentFieldIndex; }
}
#endregion
#region Overrides
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <value>A message that describes the current exception.</value>
public override string Message
{
get { return _message; }
}
/// <summary>
/// When overridden in a derived class, sets the <see cref="T:SerializationInfo"/> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:StreamingContext"/> that contains contextual information about the source or destination.</param>
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("MyMessage", _message);
info.AddValue("RawData", _rawData);
info.AddValue("CurrentPosition", _currentPosition);
info.AddValue("CurrentRecordIndex", _currentRecordIndex);
info.AddValue("CurrentFieldIndex", _currentFieldIndex);
}
#endregion
}
}
|
mit
|
maccman/wysiwyg
|
lib/wysiwyg.js
|
4881
|
// Generated by CoffeeScript 1.6.2
(function() {
var $, Wysiwyg;
$ = this.jQuery || require('jquery');
Wysiwyg = (function() {
Wysiwyg.prototype.className = 'wysiwyg';
Wysiwyg.prototype.events = {
'click [data-type=bold]': 'bold',
'click [data-type=italic]': 'italic',
'click [data-type=list]': 'list',
'click [data-type=link]': 'link',
'click [data-type=h2]': 'h2',
'click [data-type=h3]': 'h3',
'click a': 'cancel'
};
Wysiwyg.prototype.document = document;
function Wysiwyg(options) {
var key, value, _ref;
this.options = options != null ? options : {};
this.el = $('<div />');
_ref = this.options;
for (key in _ref) {
value = _ref[key];
this[key] = value;
}
this.el.addClass(this.className);
this.delegateEvents(this.events);
this.render();
}
Wysiwyg.prototype.render = function() {
this.el.empty();
this.el.append('<a href="#" data-type="bold">Bold</a>');
this.el.append('<a href="#" data-type="italic">Italic</a>');
this.el.append('<a href="#" data-type="list">List</a>');
this.el.append('<a href="#" data-type="link">Link</a>');
this.el.append('<a href="#" data-type="h2">Large</a>');
this.el.append('<a href="#" data-type="h3">Medium</a>');
return this;
};
Wysiwyg.prototype.bold = function(e) {
e.preventDefault();
if (!this.selectTest()) {
return;
}
return this.exec('bold');
};
Wysiwyg.prototype.italic = function(e) {
e.preventDefault();
if (!this.selectTest()) {
return;
}
return this.exec('italic');
};
Wysiwyg.prototype.list = function(e) {
e.preventDefault();
return this.exec('insertUnorderedList');
};
Wysiwyg.prototype.link = function(e) {
var href, parentElement;
e.preventDefault();
if (!this.selectTest()) {
return;
}
href = 'http://';
parentElement = window.getSelection().focusNode.parentElement;
if (parentElement != null ? parentElement.href : void 0) {
href = parentElement.href;
}
this.exec('unlink');
href = prompt('Enter a link:', href);
if (!href || href === 'http://') {
return;
}
if (!/:\/\//.test(href)) {
href = 'http://' + href;
}
return this.exec('createLink', href);
};
Wysiwyg.prototype.h2 = function(e) {
e.preventDefault();
if (this.query('formatBlock') === 'h2') {
return this.exec('formatBlock', 'p');
} else {
return this.exec('formatBlock', 'h2');
}
};
Wysiwyg.prototype.h3 = function(e) {
e.preventDefault();
if (this.query('formatBlock') === 'h3') {
return this.exec('formatBlock', 'p');
} else {
return this.exec('formatBlock', 'h3');
}
};
Wysiwyg.prototype.move = function(position) {
return this.el.css(position);
};
Wysiwyg.prototype.cancel = function(e) {
e.preventDefault();
return e.stopImmediatePropagation();
};
Wysiwyg.prototype.getSelectedText = function() {
var _ref;
if ((_ref = this.document) != null ? _ref.selection : void 0) {
return document.selection.createRange().text;
} else if (this.document) {
return document.getSelection().toString();
}
};
Wysiwyg.prototype.selectTest = function() {
if (this.getSelectedText().length === 0) {
alert('Select some text first.');
return false;
}
return true;
};
Wysiwyg.prototype.exec = function(type, arg) {
if (arg == null) {
arg = null;
}
return this.document.execCommand(type, false, arg);
};
Wysiwyg.prototype.query = function(type) {
return this.document.queryCommandValue(type);
};
Wysiwyg.prototype.delegateEvents = function(events) {
var eventName, key, match, method, selector, _results,
_this = this;
_results = [];
for (key in events) {
method = events[key];
if (typeof method !== 'function') {
method = (function(method) {
return function() {
_this[method].apply(_this, arguments);
return true;
};
})(method);
}
match = key.match(/^(\S+)\s*(.*)$/);
eventName = match[1];
selector = match[2];
if (selector === '') {
_results.push(this.el.bind(eventName, method));
} else {
_results.push(this.el.delegate(selector, eventName, method));
}
}
return _results;
};
return Wysiwyg;
})();
if (typeof module !== "undefined" && module !== null) {
module.exports = Wysiwyg;
} else {
this.Wysiwyg = Wysiwyg;
}
}).call(this);
|
mit
|
davisk/gateway
|
gateway/static/js/test/core_movement_test.js
|
896
|
describe("core game logic movement", function() {
var object = {};
beforeEach(function() {
object.x = 0;
object.y = 0;
});
// Testing regular movement
it("will move object left when left key is pressed", function() {
move(object, 37, '');
expect(object.x).toBe(-5);
expect(object.y).toBe(0);
});
it("will move object up when up key is pressed", function() {
move(object, 38, '');
expect(object.x).toBe(0);
expect(object.y).toBe(-5);
});
it("will move object right when right key is pressed", function() {
move(object, 39, '');
expect(object.x).toBe(5);
expect(object.y).toBe(0);
});
it("will move object down when down key is pressed", function() {
move(object, 40, '');
expect(object.x).toBe(0);
expect(object.y).toBe(5);
});
});
|
mit
|
panzer13/v2ray-core
|
main/confloader/errors.generated.go
|
208
|
package confloader
import "v2ray.com/core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
|
mit
|
nakov/OpenJudgeSystem
|
Open Judge System/Web/OJS.Web/Areas/Users/ViewModels/UserParticipationViewModel.cs
|
496
|
namespace OJS.Web.Areas.Users.ViewModels
{
using System;
public class UserParticipationViewModel
{
public int ContestId { get; set; }
public string ContestName { get; set; }
public int? CompeteResult { get; set; }
public int? PracticeResult { get; set; }
public int? ContestCompeteMaximumPoints { get; set; }
public int? ContestPracticeMaximumPoints { get; set; }
public DateTime RegistrationTime { get; set; }
}
}
|
mit
|
amervitz/xRM-Portals-Community-Edition
|
Framework/Adxstudio.Xrm/Web/Mvc/Liquid/CategoryFunctions.cs
|
2755
|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Web.Mvc.Liquid
{
using System;
using System.Collections.Generic;
/// <summary>
/// Category Functions
/// </summary>
public class CategoryFunctions
{
/// <summary>
/// Implementation of Category Drop "Top Level" - Retrieves categories with ParentCategoryId = null
/// </summary>
/// <param name="categoriesDrop">Categories Drop</param>
/// <param name="pageSize">Results Page Size</param>
/// <returns>IEnumerable collection of Category Drop</returns>
public static IEnumerable<CategoryDrop> TopLevel(CategoriesDrop categoriesDrop, int pageSize = 5)
{
return new CategoriesDrop(categoriesDrop.PortalLiquidContext, categoriesDrop.Dependencies, pageSize).TopLevel;
}
/// <summary>
/// Implementation of Category Drop "Recent"
/// </summary>
/// <param name="categoriesDrop">Categories Drop</param>
/// <param name="pageSize">Results Page Size</param>
/// <returns>IEnumerable collection of Category Drop</returns>
public static IEnumerable<CategoryDrop> Recent(CategoriesDrop categoriesDrop, int pageSize = 5)
{
return new CategoriesDrop(categoriesDrop.PortalLiquidContext, categoriesDrop.Dependencies, pageSize).Recent;
}
/// <summary>
/// Implementation of Category Drop "Related"
/// </summary>
/// <param name="categoriesDrop">Categories Drop</param>
/// <param name="categoryId">Category Id of Parent Category</param>
/// <param name="pageSize">Results Page Size</param>
/// <returns>IEnumerable collection of Category Drop</returns>
public static IEnumerable<CategoryDrop> Related(CategoriesDrop categoriesDrop, Guid categoryId, int pageSize = 5)
{
return new CategoriesDrop(categoriesDrop.PortalLiquidContext, categoriesDrop.Dependencies, pageSize).GetRelatedCategories(categoryId, pageSize);
}
/// <summary>
/// Implementation of Category Drop "Recent"
/// </summary>
/// <param name="categoriesDrop">Categories Drop</param>
/// <param name="categoryNumber">Category Number</param>
/// <returns>IEnumerable collection of Category Drop</returns>
public static CategoryDrop CategoryNumber(CategoriesDrop categoriesDrop, string categoryNumber)
{
return new CategoriesDrop(categoriesDrop.PortalLiquidContext, categoriesDrop.Dependencies).SelectByCategoryNumber(categoryNumber);
}
}
}
|
mit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.