code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
def get_related_fields(model):
pass
def get_table_size(model):
pass
def get_row_size(model):
pass
|
unbracketed/snowbird
|
snowbird/analyzer.py
|
Python
|
mit
| 112
|
<!DOCTYPE html>
<html>
<head>
<title>GrooveStomp</title>
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
<div id="navigation">
<ul>
<li><a href="/">/home</a></li>
<li><a href="/tags">/post_tags</a></li>
<li><a href="/projects">/projects</a></li>
<li><a href="/about">/about</a></li>
<li><a href="/post/index.xml">/rss</a></li>
</ul>
</div>
<div id="content-container">
<h1>Posts Tagged "emulation"</h1>
<table>
<tr>
<th>Page</th>
<th>Date</th>
</tr>
<tr>
<td><a href="/2019/02/13/riscv-go-qemu/">RISC-V, Go and QEMU</a></td>
<td>2019-02-13</td>
</tr>
<tr>
<td><a href="/2018/12/07/qemu-riscv/">qemu and RISC-V</a></td>
<td>2018-12-07</td>
</tr>
</table>
</div>
</body>
</html>
|
GrooveStomp/groovestomp.github.io
|
tags/emulation/index.html
|
HTML
|
mit
| 870
|
<!--partial-->
<style>
/* SVG styles */
.page-container .clickme.clicked svg #circle-group #circle-one{
stroke:rgb(0,113,151);
}
.page-container .clickme.clicked svg #circle-group #circle-two{
stroke:rgb(0,113,151);
}
.page-container .clickme.clicked svg #circle-group #circle-plus{
fill:rgb(0,113,151);
}
.slotWrapper {
top: 60px;
text-align: left;
width: 620px;
}
.machineBorder{
display:inline-block;
border: 3px double orange;
margin-right: 10px;
-webkit-border-radius: 14px;
-moz-border-radius: 14px;
border-radius: 14px;
background-color: #fff;
overflow: hidden;
height: 320px;
width:190px;
}
.machineContainer{
background-color: #000;
overflow: hidden;
height: 320px;
width:190px;
}
.slotMachine{
height: 320px;
width:100%;
/*border: 5px solid #000;*/
padding: 0px;
overflow: hidden;
display: inline-block;
text-align: center;
/*margin: 0px 5px;*/
/*border: 5px solid #000;*/
background-color: #ffffff;
}
.machineResult{
color:#fff;
text-align:center;
font-weight: 900;
}
.noBorder{
border:none !important;
background: transparent !important;
}
.slotMachine .slot {
height: 320px;
width: 190px;
background-size: cover;
background-position-x: 50%;
background-repeat: no-repeat;
}
.slot1{
background-image: url("img/slot-1.jpg");
}
.slot2{
background-image: url("img/slot-2.jpg");
}
.slot3{
background-image: url("img/slot-3.jpg"); }
.slot4{
background-image: url("img/slot-4.jpg"); }
.slot5{
background-image: url("img/slot-5.jpg"); }
.slot6{
background-image: url("img/slot-6.jpg"); }
.slot7{
background-image: url("img/slot-7.jpg"); }
.slot8{
background-image: url("img/slot-8.jpg"); }
.slot9{
background-image: url("img/slot-9.jpg"); }
.slot10{
background-image: url("img/slot-10.jpg"); }
#textMachine, #textMachine2{
width:520px;
height: 67px;
overflow: hidden;
display: inline-block;
text-align: left;
}
#textMachine > *, #textMachine2 > *{
padding: 0px 0px;
}
.slotMachineButton{
width:100px;
height: 100px;
overflow: hidden;
display: inline-block;
text-align: center;
}
.slotMachineButton {
-moz-box-shadow:inset 0px 1px 0px 0px #fce2c1;
-webkit-box-shadow:inset 0px 1px 0px 0px #fce2c1;
box-shadow:inset 0px 1px 0px 0px #fce2c1;
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #fb9e25) );
background:-moz-linear-gradient( center top, #ffc477 5%, #fb9e25 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#fb9e25');
background-color:#ffc477;
border-radius: 75px;
text-indent:0px;
border:6px solid #eeb44f;
display:inline-block;
color:#ffffff;
font-size:40px;
font-weight:bold;
font-style:normal;
height:100px;
line-height:90px;
margin-top:10px;
width:100px;
text-decoration:none;
text-align:center;
text-shadow:1px 1px 0px #cc9f52;
cursor:pointer;
}
.slotMachineButton:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #fb9e25), color-stop(1, #ffc477) );
background:-moz-linear-gradient( center top, #fb9e25 5%, #ffc477 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fb9e25', endColorstr='#ffc477');
background-color:#fb9e25;
}.slotMachineButton:active {
position:relative;
top:1px;
}
.slotWrapper{
width:620px;
position:absolute;
}
</style>
<div class="page5 page-container">
<img id="play-dot" src="img/page_05_circle.png" alt="play">
<div class="headline">
<h1 class="amatic pantone633">Mid-day Mind Play</h1>
<h2 class="cantarell pantone166">Laugh like you won the jackpot!</h2>
<p class="headline">Our rotating selection of signature brain fitness programs encourage a little friendly competition, active participation, and mental calisthenics to keep the mind sharp.</p>
</div>
<div id="slots">
<div class="content" style="text-align: center">
<div class="slotWrapper">
<div class="machineBorder">
<div class="machineContainer">
<div id="machineFake1" class="slotMachine">
<div class="slot slot1"></div>
<div class="slot slot2"></div>
<div class="slot slot3"></div>
<div class="slot slot4"></div>
<div class="slot slot5"></div>
<div class="slot slot6"></div>
<div class="slot slot7"></div>
<div class="slot slot8"></div>
<div class="slot slot9"></div>
<div class="slot slot10"></div>
</div>
</div>
</div>
<div class="machineBorder">
<div class="machineContainer">
<div id="machineFake2" class="slotMachine">
<div class="slot slot1"></div>
<div class="slot slot2"></div>
<div class="slot slot3"></div>
<div class="slot slot4"></div>
<div class="slot slot5"></div>
<div class="slot slot6"></div>
<div class="slot slot7"></div>
<div class="slot slot8"></div>
<div class="slot slot9"></div>
<div class="slot slot10"></div>
</div>
</div>
</div>
<div class="machineBorder">
<div class="machineContainer">
<div id="machineFake3" class="slotMachine">
<div class="slot slot1"></div>
<div class="slot slot2"></div>
<div class="slot slot3"></div>
<div class="slot slot4"></div>
<div class="slot slot5"></div>
<div class="slot slot6"></div>
<div class="slot slot7"></div>
<div class="slot slot8"></div>
<div class="slot slot9"></div>
<div class="slot slot10"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="click-layer" ng-class="{'clicked': targetState != 'none'}" ng-click="setTargetState()" ng-init="setTargetState()" ></div>
<div class="one targetWrapper" ng-click="setTargetState('one')" ng-class="{'clicked': targetState == 'one'}">
<div id="clickme" class="clickme"><ng-include src="addSVG()"></ng-include></div>
<div id="clicktext" class="clicktext">
<h4 class="pantone633 cantarell bold">Join the Club</h4>
<p>Keep your mind sharp, as well as your card-shark skills as part of the bridge or poker club. Or if you are more of the creative type, a poetry club might be a new challenge. And for those world travelers, it is never too late to learn a new language- bueno!</p>
</div>
</div>
</div>
|
lorier/emag
|
app/partials/page5.html
|
HTML
|
mit
| 6,365
|
/*****************************************************************************
* Z-Wave enabled Radiation, Temperature and Humidity Monitor with LCD Display
******************************************************************************
* 24 hour data logging class. It logs integer values in 3 different intervals:
* - 1 minute interval during 5 minutes
* - 5 minute interval during the next 55 minutes -> 1 hour in total
* - 1 hour interval during the next 23 hours -> 24 hours in total
* Mean values are calculated for the last 5 minutes, last hour and last 24
* hours.
*
* Copyright (C) 2017 Andreas Drollinger
*****************************************************************************
* See the file "LICENSE" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
\****************************************************************************/
#include "DataLog24H.h"
// Get mean values
int DataLog24H::GetMean1M() {
return Mean1M;}
int DataLog24H::GetMean5M() {
return Mean5M;}
int DataLog24H::GetMean1H() {
return Mean1H;}
int DataLog24H::GetMean24H() {
return Mean24H;}
// Get the data arrays
int *DataLog24H::GetData() {
return Data;}
int *DataLog24H::GetData1M() {
return Data;}
int *DataLog24H::GetData5M() {
return Data+5;}
int *DataLog24H::GetData1H() {
return Data+5+11;}
// Constructor - Set all data to IntNA (not available). Reset the interval
// counter.
DataLog24H::DataLog24H() {
for (byte i=0; i<5+11+23; i++)
Data[i]=IntNA;
Mean1M=Mean5M=Mean1H=Mean24H=IntNA;
Counter=0;
}
// AddData - Log a new data value. This method should be called exactly once
// per minute.
// Each time a value is added the 5 1-minute interval values are shifted by
// one position and the mean value is calculated. Every 5 minutes this mean
// value is shifted into the 5-minute interval array. The mean value of this
// array is shifted into the 1-hour interval array every hour.
void DataLog24H::AddData(int NewData1M) {
Counter++; // Increment the interval counter
Mean1M=NewData1M; // The provided value is considered as 1M mean value
// Shift the new value into the 1-minute interval array
int ValOld;
int Mean=0;
int ValNew=Mean1M;
for (byte i=0; i<5; i++) {
ValOld=Data[i];
Data[i]=ValNew;
Mean+=ValOld;
ValNew=ValOld;
}
// Update the 5-minute mean value. Skip this update if less than 5 minutes
// are registered. Skip updating the 5-minute interval array if the time is
// not a multiple of 5 minutes.
if (Counter<6)
return;
Mean/=5;
Mean5M=Mean;
if (Counter%5!=1)
return;
// Every 5 minutes, shift mean value from the 1-minute interval array into
// the 5-minute interval array
ValNew=Mean; // Mean value from the 1st 5 minutes
for (byte i=5; i<5+11; i++) {
ValOld=Data[i];
Data[i]=ValNew;
Mean+=ValOld;
ValNew=ValOld;
}
// Update the 1-hour mean value. Skip this update if less than 1 hour
// is registered. Skip updating the 1-hour interval array if the time is
// not a multiple of 1 hour.
if (Counter<5*12+1)
return;
Mean/=12;
Mean1H=Mean;
if (Counter%(5*12)!=1)
return;
// Every hour, shift mean value from the 5-minute interval array into the
// 1-hour interval array
ValNew=Mean; // Mean value from the 1st hour
for (byte i=5+11; i<5+11+23; i++) {
ValOld=Data[i];
Data[i]=ValNew;
Mean+=ValOld;
ValNew=ValOld;
}
// Update the 24-hours mean value. Skip this update if less than 24 hours
// are registered.
if (Counter<5*12*24+1)
return;
Mean/=24;
Mean24H=Mean;
}
|
Drolla/ZUNO_RM80_RadiationMonitor
|
DataLog24H.cpp
|
C++
|
mit
| 3,536
|
// 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 <map>
#include <openssl/obj_mac.h>
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
#include <openssl/ecdsa.h>
#endif
#include "key.h"
#include "ecies/ecies.h"
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key) {
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if(!eckey) return(0);
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if(!pub_key)
goto err;
if(!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if(pub_key)
EC_POINT_free(pub_key);
if(ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is non-zero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const uchar *msg,
int msglen, int recid, int check) {
if(!eckey) return(0);
#if (OPENSSL_VERSION_NUMBER > 0x10100000L)
const BIGNUM *sig_r, *sig_s;
ECDSA_SIG_get0(ecsig, &sig_r, &sig_s);
#endif
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if(!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if(!BN_copy(x, order)) { ret = -1; goto err; }
if(!BN_mul_word(x, i)) { ret = -1; goto err; }
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
if(!BN_add(x, x, ecsig->r)) { ret = -1; goto err; }
#else
if(!BN_add(x, x, sig_r)) { ret = -1; goto err; }
#endif
field = BN_CTX_get(ctx);
if(!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret = -2; goto err; }
if(BN_cmp(x, field) >= 0) { ret = 0; goto err; }
if((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if(!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret = 0; goto err; }
if(check) {
if((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if(!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret = -2; goto err; }
if(!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if(!BN_bin2bn(msg, msglen, e)) { ret = -1; goto err; }
if((8 * msglen) > n) BN_rshift(e, e, 8 - (n & 7));
zero = BN_CTX_get(ctx);
if(!BN_zero(zero)) { ret = -1; goto err; }
if(!BN_mod_sub(e, zero, e, order, ctx)) { ret = -1; goto err; }
rr = BN_CTX_get(ctx);
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
if(!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret = -1; goto err; }
#else
if(!BN_mod_inverse(rr, sig_r, order, ctx)) { ret = -1; goto err; }
#endif
sor = BN_CTX_get(ctx);
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
if(!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret = -1; goto err; }
#else
if(!BN_mod_mul(sor, sig_s, rr, order, ctx)) { ret = -1; goto err; }
#endif
eor = BN_CTX_get(ctx);
if(!BN_mod_mul(eor, e, rr, order, ctx)) { ret = -1; goto err; }
if(!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret = -2; goto err; }
if(!EC_KEY_set_public_key(eckey, Q)) { ret = -2; goto err; }
ret = 1;
err:
if(ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if(R != NULL) EC_POINT_free(R);
if(O != NULL) EC_POINT_free(O);
if(Q != NULL) EC_POINT_free(Q);
return(ret);
}
void CKey::SetCompressedPubKey(bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
fCompressedPubKey = true;
}
void CKey::Reset() {
fCompressedPubKey = false;
if(pkey)
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if(!pkey)
throw(key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed"));
fSet = false;
}
CKey::CKey() {
pkey = NULL;
Reset();
}
CKey::CKey(const CKey &b) {
pkey = EC_KEY_dup(b.pkey);
if(!pkey)
throw(key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed"));
fSet = b.fSet;
}
CKey &CKey::operator=(const CKey &b) {
if(!EC_KEY_copy(pkey, b.pkey))
throw(key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed"));
fSet = b.fSet;
return(*this);
}
CKey::~CKey() {
EC_KEY_free(pkey);
}
bool CKey::IsNull() const {
return(!fSet);
}
bool CKey::IsCompressed() const {
return(fCompressedPubKey);
}
void CKey::MakeNewKey(bool fCompressed) {
if(!EC_KEY_generate_key(pkey))
throw(key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed"));
if(fCompressed)
SetCompressedPubKey();
fSet = true;
}
bool CKey::SetPrivKey(const CPrivKey &vchPrivKey) {
const uchar *pbegin = &vchPrivKey[0];
if(d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size())) {
// In testing, d2i_ECPrivateKey can return true
// but fill in pkey with a key that fails
// EC_KEY_check_key, so:
if(EC_KEY_check_key(pkey)) {
fSet = true;
return true;
}
}
// If vchPrivKey data is bad d2i_ECPrivateKey() can
// leave pkey in a state where calling EC_KEY_free()
// crashes. To avoid that, set pkey to NULL and
// leak the memory (a leak is better than a crash)
pkey = NULL;
Reset();
return(false);
}
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed) {
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if(!pkey)
throw(key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed"));
if(vchSecret.size() != 32)
throw(key_error("CKey::SetSecret() : secret must be 32 bytes"));
BIGNUM *bn = BN_bin2bn(&vchSecret[0], 32, BN_new());
if(!bn)
throw(key_error("CKey::SetSecret() : BN_bin2bn failed"));
if(!EC_KEY_regenerate_key(pkey, bn)) {
BN_clear_free(bn);
throw(key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed"));
}
BN_clear_free(bn);
fSet = true;
if(fCompressed || fCompressedPubKey)
SetCompressedPubKey();
return(true);
}
CSecret CKey::GetSecret(bool &fCompressed) const {
CSecret vchRet;
vchRet.resize(32);
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
int nBytes = BN_num_bytes(bn);
if(!bn)
throw(key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed"));
int n = BN_bn2bin(bn, &vchRet[32 - nBytes]);
if(n != nBytes)
throw(key_error("CKey::GetSecret(): BN_bn2bin failed"));
fCompressed = fCompressedPubKey;
return(vchRet);
}
CPrivKey CKey::GetPrivKey() const {
int nSize = i2d_ECPrivateKey(pkey, NULL);
if(!nSize)
throw(key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed"));
CPrivKey vchPrivKey(nSize, 0);
uchar *pbegin = &vchPrivKey[0];
if(i2d_ECPrivateKey(pkey, &pbegin) != nSize)
throw(key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size"));
return(vchPrivKey);
}
bool CKey::SetPubKey(const CPubKey &vchPubKey) {
const uchar *pbegin = &vchPubKey.vchPubKey[0];
if(o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size())) {
fSet = true;
if(vchPubKey.vchPubKey.size() == 33)
SetCompressedPubKey();
return(true);
}
pkey = NULL;
Reset();
return(false);
}
CPubKey CKey::GetPubKey() const {
int nSize = i2o_ECPublicKey(pkey, NULL);
if(!nSize)
throw(key_error("CKey::GetPubKey() : i2o_ECPublicKey failed"));
std::vector<uchar> vchPubKey(nSize, 0);
uchar *pbegin = &vchPubKey[0];
if(i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw(key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size"));
return(CPubKey(vchPubKey));
}
bool CKey::Sign(uint256 hash, std::vector<uchar> &vchSig) {
uint nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
if(!ECDSA_sign(0, (uchar *) &hash, sizeof(hash), &vchSig[0], &nSize, pkey)) {
vchSig.clear();
return(false);
}
vchSig.resize(nSize); // Shrink to fit actual size
return(true);
}
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool CKey::SignCompact(uint256 hash, std::vector<uchar> &vchSig) {
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((uchar *) &hash, sizeof(hash), pkey);
if(!sig) return(false);
vchSig.clear();
vchSig.resize(65, 0);
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
#else
const BIGNUM *sig_r, *sig_s;
ECDSA_SIG_get0(sig, &sig_r, &sig_s);
int nBitsR = BN_num_bits(sig_r);
int nBitsS = BN_num_bits(sig_s);
#endif
int i;
if((nBitsR <= 256) && (nBitsS <= 256)) {
int nRecId = -1;
for(i = 0; i < 4; i++) {
CKey keyRec;
keyRec.fSet = true;
if(fCompressedPubKey)
keyRec.SetCompressedPubKey();
if(ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (uchar *) &hash, sizeof(hash), i, 1) == 1) {
if(keyRec.GetPubKey() == this->GetPubKey()) {
nRecId = i;
break;
}
}
}
if(nRecId == -1)
throw(key_error("CKey::SignCompact() : unable to construct recoverable key"));
vchSig[0] = nRecId + 27 + (fCompressedPubKey ? 4 : 0);
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
BN_bn2bin(sig->r, &vchSig[33 - (nBitsR + 7) / 8]);
BN_bn2bin(sig->s, &vchSig[65 - (nBitsS + 7) / 8]);
#else
BN_bn2bin(sig_r, &vchSig[33 - (nBitsR + 7) / 8]);
BN_bn2bin(sig_s, &vchSig[65 - (nBitsS + 7) / 8]);
#endif
fOk = true;
}
ECDSA_SIG_free(sig);
return(fOk);
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool CKey::SetCompactSignature(uint256 hash, const std::vector<uchar> &vchSig) {
if(vchSig.size() != 65) return(false);
int nV = vchSig[0];
if((nV < 27) || (nV >= 35)) return(false);
ECDSA_SIG *sig = ECDSA_SIG_new();
if(!sig) return(false);
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
BN_bin2bn(&vchSig[1], 32, sig->r);
BN_bin2bn(&vchSig[33], 32, sig->s);
#else
/* sig_r and sig_s are deallocated by ECDSA_SIG_free(sig); */
BIGNUM *sig_r = BN_bin2bn(&vchSig[1], 32, BN_new());
BIGNUM *sig_s = BN_bin2bn(&vchSig[33], 32, BN_new());
if(!sig_r || !sig_s) return(false);
/* Copy and transfer ownership */
ECDSA_SIG_set0(sig, sig_r, sig_s);
#endif
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if(nV >= 31) {
SetCompressedPubKey();
nV -= 4;
}
if(ECDSA_SIG_recover_key_GFp(pkey, sig, (uchar *) &hash, sizeof(hash), nV - 27, 0) == 1) {
fSet = true;
ECDSA_SIG_free(sig);
return(true);
}
return(false);
}
bool CKey::Verify(uint256 hash, const std::vector<uchar> &vchSig) {
// -1 = error, 0 = bad sig, 1 = good
if(ECDSA_verify(0, (uchar *) &hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return(false);
return(true);
}
bool CKey::VerifyCompact(uint256 hash, const std::vector<uchar> &vchSig) {
CKey key;
if(!key.SetCompactSignature(hash, vchSig))
return(false);
if(GetPubKey() != key.GetPubKey())
return(false);
return(true);
}
bool CKey::IsValid() {
if(!fSet) return(false);
if(!EC_KEY_check_key(pkey)) return(false);
bool fCompr;
CSecret secret = GetSecret(fCompr);
CKey key2;
key2.SetSecret(secret, fCompr);
return GetPubKey() == key2.GetPubKey();
}
void CPubKey::EncryptData(const std::vector<uchar> &plaindata, std::vector<uchar> &encdata) {
CKey key;
key.SetPubKey(*this);
key.EncryptData(plaindata, encdata);
}
void CKey::EncryptData(const std::vector<uchar> &plaindata, std::vector<uchar> &encdata) {
ecies_ctx_t *ctx = new ecies_ctx_t;
char error[256] = "Unknown error";
secure_t *cryptex;
ctx->cipher = EVP_aes_128_cbc();
ctx->md = EVP_ripemd160();
ctx->kdf_md = EVP_ripemd160();
ctx->stored_key_length = 33;
ctx->user_key = pkey;
if(!EC_KEY_get0_public_key(ctx->user_key))
throw(key_error("Invalid public key"));
cryptex = ecies_encrypt(ctx, (uchar *) &plaindata[0], plaindata.size(), error);
if(!cryptex) {
free(ctx);
throw(key_error(std::string("Error in encryption: ") + error));
}
encdata.resize(secure_data_sum_length(cryptex));
memcpy(&encdata[0], secure_key_data(cryptex), encdata.size());
secure_free(cryptex);
free(ctx);
}
void CKey::DecryptData(const std::vector<uchar> &encdata, std::vector<uchar> &plaindata) {
ecies_ctx_t *ctx = new ecies_ctx_t;
char error[256] = "Unknown error";
secure_t *cryptex;
uchar *decrypted;
size_t length;
ctx->cipher = EVP_aes_128_cbc();
ctx->md = EVP_ripemd160();
ctx->kdf_md = EVP_ripemd160();
ctx->stored_key_length = 33;
ctx->user_key = pkey;
if(!EC_KEY_get0_private_key(ctx->user_key))
throw(key_error("Invalid private key"));
size_t key_length = ctx->stored_key_length;
size_t mac_length = EVP_MD_size(ctx->md);
cryptex = secure_alloc(key_length, mac_length, encdata.size() - key_length - mac_length);
memcpy(secure_key_data(cryptex), &encdata[0], encdata.size());
decrypted = ecies_decrypt(ctx, cryptex, &length, error);
secure_free(cryptex);
free(ctx);
if(!decrypted) {
throw(key_error(std::string("Error in decryption: ") + error));
}
plaindata.resize(length);
memcpy(&plaindata[0], decrypted, length);
free(decrypted);
}
|
ghostlander/Orbitcoin
|
src/key.cpp
|
C++
|
mit
| 14,921
|
import os, requests, tempfile, time, webbrowser
import lacuna.bc
import lacuna.exceptions as err
### Dev notes:
### The tempfile containing the captcha image is not deleted until solveit()
### has been called.
###
### Allowing the tempfile to delete itself (delete=True during tempfile
### creation), or using the tempfile in conjunction with a 'with:' expression,
### have both been attempted.
###
### The problem is that, when using those auto-deletion methods, the tempfile
### is occasionally being removed from the system before the image viewer
### we're firing off actually gets a chance to read it. Everything is
### happening in the right order, it's just that the image viewer startup is
### too slow.
###
### Deleting the tempfile manually in solveit() works - don't decide to get
### clever and replace the unlink() in solveit() with some form of tempfile
### autodeletion without a lot of testing.
class Captcha(lacuna.bc.LacunaObject):
""" Fetches, displays, and solves graphical captchas.
General usage will be::
cap = my_client.get_captcha()
cap.showit() # display the captcha image
cap.prompt_user() # ask the user for a solution
cap.solveit() # check the user's solution
"""
path = 'captcha'
@lacuna.bc.LacunaObject.call_returning_meth
def fetch( self, **kwargs ):
""" Fetches a captcha for the user to solve from the server.
This mirrors the TLE API, but you generally don't need to call this.
Returns a :class:`lacuna.captcha.Puzzle` object.
"""
return Puzzle( self.client, kwargs['rslt'] )
def showit( self ):
""" Actually downloads the captcha image, and attempts to display it
to the user in one of several browsers.
If :meth:`fetch` is called first, :meth:`showit` uses that fetched data, but
this is not necessary. :meth:`showit` will call fetch for you.
Raises :class:`lacuna.exceptions.RequestError` if the image is not
fetchable (network error or the TLE servers have gone down).
Raises EnvironmentError if it cannot find an image viewer to use to
display the captcha image.
"""
if not hasattr(self,'url') or not hasattr(self,'guid'):
puzzle = self.fetch()
self.url = puzzle.url
self.guid = puzzle.guid
img_resp = requests.get( self.url )
if img_resp.status_code != 200:
raise err.RequestError("The captcha image URL is not responding.")
f = tempfile.NamedTemporaryFile( suffix='.png', prefix='tle_capcha_', delete=False );
self.tempfile = f.name
f.write( img_resp.content )
if hasattr(img_resp, 'connection'):
img_resp.connection.close()
local_url = 'file://' + f.name
found_browser = False
for b in [ None, 'windows-default', 'macosx', 'safari', 'firefox',
'google-chrome', 'chrome', 'chromium-browser', 'chromium' ]:
try:
browser = webbrowser.get( b )
browser.open( local_url, 0, True )
found_browser = True
break
except webbrowser.Error as e:
pass
if not found_browser:
raise EnvironmentError("Unable to find a browser to show the captcha image. Captcha solution is required.")
def prompt_user(self):
""" Prompts the user to solve the displayed captcha.
It's not illegal to call this without first calling :meth:`solveit`,
but doing so makes no sense.
"""
self.resp = input("Enter the solution to the captcha here: ")
return self.resp
def solveit(self):
""" Sends the user's response to the server to check for accuracy.
Returns True if the user's response was correct. Raises
:class:`lacuna.exceptions.CaptchaResponseError` otherwise.
"""
if not hasattr(self,'resp'):
raise AttributeError("You must prompt the user for a response before calling solveit().")
try:
self.solve( self.guid, self.resp )
except err.ServerError as e:
raise err.CaptchaResponseError("Incorrect captcha response")
finally:
delattr( self, 'url' )
delattr( self, 'guid' )
delattr( self, 'resp' )
if os.path.isfile(self.tempfile):
os.unlink( self.tempfile )
return True
@lacuna.bc.LacunaObject.call_member_meth
def solve( self, guid:str, solution:str, **kwargs ):
""" Mirrors the TLE Captcha module's :meth:`solve` method, but unless you
really need this and you really know why, use :meth:`solveit` instead.
"""
pass
class Puzzle(lacuna.bc.SubClass):
"""
Object Attributes::
url FQ URL to the puzzle image
guid uuid attached to the puzzle; must be passed back along with
the solution.
"""
|
tmtowtdi/MontyLacuna
|
lib/lacuna/captcha.py
|
Python
|
mit
| 5,055
|
all: tex view
tex:
pdflatex solution.tex
view:
gnome-open solution.pdf
|
camilstaps/OO1415
|
Week9 Webshop/docs/Makefile
|
Makefile
|
mit
| 74
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
// ESLint configuration
// http://eslint.org/docs/user-guide/configuring
module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:flowtype/recommended',
'plugin:css-modules/recommended',
'prettier',
'prettier/flowtype',
'prettier/react',
],
plugins: ['flowtype', 'css-modules', 'prettier'],
globals: {
__DEV__: true,
},
env: {
browser: true,
},
rules: {
// `js` and `jsx` are common extensions
// `mjs` is for `universal-router` only, for now
'import/extensions': [
'error',
'always',
{
js: 'never',
jsx: 'never',
mjs: 'never',
},
],
// Not supporting nested package.json yet
// https://github.com/benmosher/eslint-plugin-import/issues/458
'import/no-extraneous-dependencies': 'off',
// Recommend not to leave any console.log in your code
// Use console.error, console.warn and console.info instead
'no-console': [
'error',
{
allow: ['warn', 'error', 'info'],
},
],
// a11y removed rule, ignore them
'jsx-a11y/href-no-hash': 'off',
// https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/308#issuecomment-322954274
'jsx-a11y/label-has-for': 'warn',
// Allow js files to use jsx syntax, too
'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }],
// Automatically convert pure class to function by
// babel-plugin-transform-react-pure-class-to-function
// https://github.com/kriasoft/react-starter-kit/pull/961
'react/prefer-stateless-function': 'off',
// ESLint plugin for prettier formatting
// https://github.com/prettier/eslint-plugin-prettier
'prettier/prettier': [
'error',
{
// https://github.com/prettier/prettier#options
singleQuote: true,
trailingComma: 'all',
},
],
},
settings: {
// Allow absolute paths in imports, e.g. import Button from 'components/Button'
// https://github.com/benmosher/eslint-plugin-import/tree/master/resolvers
'import/resolver': {
node: {
moduleDirectory: ['node_modules', 'src'],
},
},
},
};
|
bmatthews/haze-lea
|
.eslintrc.js
|
JavaScript
|
mit
| 2,454
|
using Lib;
using static XJS.Nodes;
public partial class XJS {
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
/// <summary>
/// <para> Program Nodes hold: </para>
/// <para> import-export? - List of imports and exports </para>
/// <para> stmts? - List of statements to execute for the program.</para>
/// </summary>
public static Node ParseProgram(this Tokenizer tok) {
Node prog = new Node(PROGRAM);
prog.Map("imports-exports", tok.ParseImportsExports());
prog.Map("stmts", tok.ParseStatementList());
return prog;
}
/// <summary> Constant Array for import/export keywords </summary>
public static readonly string[] IMP_EXP = { "import", "export" };
/// <summary> Parses import/export lists at the begining of the program. </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseImportsExports(this Tokenizer tok) {
Node impexp = new Node(IMPORT_EXPORT);
Node imports = impexp.Map("imports", new Node(IMPORTS));
Node exports = impexp.Map("exports", new Node(EXPORTS));
while (tok.At(IMP_EXP)) {
if (tok.At("import")) {
imports.Add(tok.peekToken);
tok.Next();
Token importPath = tok.ParseFixedPath();
Node import = new Node(IMPORT_RENAME);
//tok.Next();
if (tok.At("as")) {
tok.Next();
import.Map("thing", importPath);
import.Map("as", tok.peekToken);
tok.Next();
imports.List(import);
} else {
imports.List(importPath);
}
} else if (tok.At("export")) { // Redundant, but more clear.
tok.Next();
exports.List(tok.ParseFixedPath());
}
if (tok.At(";")) { tok.Next(); } // Consume, but don't require ';'
}
return impexp;
}
/// <summary> Parses a 'path' which is a series of names separated by '.' </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Token ParseFixedPath(this Tokenizer tok) {
tok.Require(NAME);
StringBuilder path = new StringBuilder(tok.content);
Token start = tok.Next();
while (tok.At(".")) {
path.Append('.');
tok.Next();
tok.Require(NAME);
path.Append(tok.content);
tok.Next();
}
return new Token(path.ToString(), "!PATH", start.line, start.col);
}
public static Node ParseExprPath(this Tokenizer tok) {
// All paths start with a name.
tok.Require(NAME);
Node path = new Node(PATHEXPR);
Node first = new Node(ATOM);
first.Map("const", tok.peekToken);
path.List(first);
tok.Next();
while (tok.At(".") || tok.At("[")) {
if (tok.At(".")) {
tok.Next();
Node next = new Node(ATOM);
tok.Require(NAME);
next.Map("const", tok.peekToken);
path.List(next);
tok.Next();
} else if (tok.At("[")) {
tok.Next();
Node next = tok.ParseExpression();
tok.RequireNext("]");
path.List(next);
}
}
return path;
}
/// <summary> Parses a label string. This is prefixed/suffixed with ':' </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Label string that is at the front of the tokenizer. </returns>
public static string ParseLabel(this Tokenizer tok) {
tok.RequireNext(":");
tok.Require(NAME);
string label = tok.peekToken.content;
tok.Next();
tok.RequireNext(":");
return label;
}
public const int SAFETYWALL = 1000000;
/// <summary> Parses a statement list. </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseStatementList(this Tokenizer tok) {
Node stmts = new Node(STMTLIST);
int safetyWall = 0;
while (!(tok.Done || tok.At("}"))) {
stmts.List(tok.ParseStatement());
if (++safetyWall > SAFETYWALL) { Debug.LogWarning("Broke out of STMTLIST debug safetywall!\n" + tok); break; }
}
return stmts;
}
/// <summary> Labelable statements (loops) </summary>
public static readonly string[] LABEL_ABLE_LOOP_TOKEN = { "for", "each", "do", "while", };
/// <summary> Parses a single Statement node. </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseStatement(this Tokenizer tok) {
if (tok.At(";")) { tok.Next(); return null; }
else if (tok.At("if")) { return tok.ParseIfStmt(); }
else if (tok.At("var")) { return tok.ParseDecStmt(); }
else if (tok.At("{")) { return tok.ParseCodeBlock(); }
else if (tok.At("return")) { return tok.ParseReturnStmt(); }
else if (tok.At("for")) { return tok.ParseForLoop(); }
else if (tok.At("each")) { return tok.ParseEachLoop(); }
else if (tok.At("do")) { return tok.ParseDoWhileLoop(); }
else if (tok.At("while")) { return tok.ParseWhileLoop(); }
else if (tok.At("break")) { return tok.ParseBreakStmt(); }
else if (tok.At("continue")) { return tok.ParseContinueStmt(); }
else if (tok.At(":")) {
string label = tok.ParseLabel();
tok.Require(LABEL_ABLE_LOOP_TOKEN);
Node loop = null;
if (tok.At("for")) { loop = tok.ParseForLoop(); }
else if (tok.At("each")) { loop = tok.ParseEachLoop(); }
else if (tok.At("do")) { loop = tok.ParseDoWhileLoop(); }
else if (tok.At("while")) { loop = tok.ParseWhileLoop(); }
loop?.Map("label", label);
return loop;
}
else if (tok.At(STRING) || tok.At(NUMBER) || tok.At(NAME)
|| tok.At("(") || tok.At("-") || tok.At("[")
|| tok.At("++") | tok.At("--")) {
return tok.ParseExpression();
}
return null;
}
/// <summary>
/// <para> Parses a CodeBlock node </para>
/// <para> CodeBlock node holds: </para>
/// <para> [nodelist]? - List of statements to execute, in order. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseCodeBlock(this Tokenizer tok) {
Node codeblock = new Node(CODEBLOCK);
tok.RequireNext("{");
int safetyWall = 0;
while (!tok.At("}")) {
codeblock.List(tok.ParseStatement());
if (safetyWall++ > SAFETYWALL) { Debug.LogWarning("Broke out of CODEBLOCK safetywall!\n" + tok); break; }
}
tok.RequireNext("}");
return codeblock;
}
/// <summary>
/// <para> Parses a ForLoop node. </para>
/// <para> The ForLoop node contains: </para>
/// <para> init? - Initializer. If not present, nothing happens. </para>
/// <para> cond? - Loop condition. If not present, is always true. </para>
/// <para> incr? - Loop increment. If not present, nothing happens. </para>
/// <para> body - Statements to run. </para>
/// <para> label? - Label of the loop. Actually attached by <see cref="ParseStatement(Tokenizer)"/> </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseForLoop(this Tokenizer tok) {
Node forloop = new Node(FORLOOP);
tok.RequireNext("for");
tok.RequireNext("(");
if (!tok.At(";")) {
Node assign;
if (tok.At("var")) { assign = tok.ParseDecStmt(); }
else {
assign = tok.ParseFromName();
if (assign.type != ASSIGN) { tok.Error("For loop initializer can only have a declaration or assignment statement!"); }
}
forloop.Map("init", assign);
}
tok.RequireNext(";");
if (!tok.At(";")) { forloop.Map("cond", tok.ParseExpression()); }
tok.RequireNext(";");
if (!tok.At(")")) {
Node assign = tok.ParseFromName();
if (assign.type != ASSIGN) { tok.Error("For loop increment can only have an assignment statement!"); }
forloop.Map("incr", assign);
}
tok.RequireNext(")");
forloop.Map("body", tok.ParseStatement());
return forloop;
}
/// <summary>
/// <para> Parses an EachLoop node. </para>
/// <para> The EachLoop node contains: </para>
/// <para> name - name of variable inside of loop body. </para>
/// <para> path - path of collection to loop over. </para>
/// <para> body - Statements to run </para>
/// <para> label? - Label of the loop. Actually attached by <see cref="ParseStatement(Tokenizer)"/> </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseEachLoop(this Tokenizer tok) {
Node eachloop = new Node(EACHLOOP);
tok.RequireNext("each");
tok.RequireNext("(");
if (tok.At(NAME)) {
eachloop.Map("name", tok.peekToken);
tok.Next();
} else {
tok.Require("(");
eachloop.Map("names", tok.ParseVarList());
}
tok.RequireNext("in");
// Todo: Change to ParseExprPath
eachloop.Map("path", tok.ParseExprPath());
tok.RequireNext(")");
eachloop.Map("body", tok.ParseStatement());
return eachloop;
}
/// <summary>
/// <para> Parses a DoWhileLoop node. </para>
/// <para> Always runs its body at least once, and then repeats it so long as its condition is true. </para>
/// <para> The DoWhileLoop node contains: </para>
/// <para> cond - loop condition </para>
/// <para> body - Statements to run </para>
/// <para> label? - Label of the loop. Actually attached by <see cref="ParseStatement(Tokenizer)"/> </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseDoWhileLoop(this Tokenizer tok) {
Node dowhileloop = new Node(DOWHILELOOP);
tok.RequireNext("do");
dowhileloop.Map("body", tok.ParseStatement());
tok.RequireNext("while");
tok.RequireNext("(");
dowhileloop.Map("cond", tok.ParseExpression());
tok.RequireNext(")");
return dowhileloop;
}
/// <summary>
/// <para> Parses a WhileLoop node. </para>
/// <para> Only enters its body if its condition is true when reached. </para>
/// <para> The DoWhileLoop node contains: </para>
/// <para> cond - loop condition </para>
/// <para> body - Statements to run </para>
/// <para> label? - Label of the loop. Actually attached by <see cref="ParseStatement(Tokenizer)"/> </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseWhileLoop(this Tokenizer tok) {
Node whileloop = new Node(WHILELOOP);
tok.RequireNext("while");
tok.RequireNext("(");
whileloop.Map("cond", tok.ParseExpression());
tok.RequireNext(")");
whileloop.Map("body", tok.ParseStatement());
return whileloop;
}
/// <summary>
/// <para> Parses a BreakStatement node. </para>
/// <para> The BreakStatement node may contain: </para>
/// <para> target? - the target label for the loop that the break statement will break from </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseBreakStmt(this Tokenizer tok) {
Node breakstmt = new Node(BREAKSTMT);
tok.RequireNext("break");
if (tok.At(":")) { breakstmt.Map("target", tok.ParseLabel()); }
return breakstmt;
}
/// <summary>
/// <para> Parses a ContinueStatement node. </para>
/// <para> The ContinueStatement node may contain: </para>
/// <para> target? - the target label for the loop that the continue statement will repeat </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseContinueStmt(this Tokenizer tok) {
Node continuestmt = new Node(CONTINUESTMT);
tok.RequireNext("continue");
if (tok.At(":")) { continuestmt.Map("target", tok.ParseLabel()); }
return continuestmt;
}
/// <summary>
/// <para> Parses a ReturnStatement node. </para>
/// <para> The ReturnStatement node may contain: </para>
/// <para> expr? - the expression of the value to return </para>
/// </summary>
/// <param name="tok"></param>
/// <returns></returns>
public static Node ParseReturnStmt(this Tokenizer tok) {
Node returnstmt = new Node(RETURNSTMT);
tok.RequireNext("return");
if (!tok.At(";")) {
returnstmt.Map("expr", tok.ParseExpression());
} else {
tok.Next(); // Consume ;.
}
return returnstmt;
}
/// <summary>
/// <para> Parses an IfStatment node. </para>
/// <para>If Statement Node holds:</para>
/// <para>cond - condition expression to evaluate</para>
/// <para>stmt - statement to execute if cond evaluates true</para>
/// <para>[nodelist]? - list of condition Expression (even) and Statement (odd)
/// pairs to check in turn if cond evaluates false</para>
/// <para>else? - statement to execute if all condition expressions evaluate false. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseIfStmt(this Tokenizer tok) {
Node ifStmt = new Node(IFSTMT);
tok.RequireNext("if");
tok.RequireNext("(");
ifStmt.Map("cond", tok.ParseExpression() );
tok.RequireNext(")");
ifStmt.Map("stmt", tok.ParseStatement() );
while (tok.At("else")) {
tok.Next();
if (tok.At("if")) {
tok.Next();
// Contains if...else if... else if... chain
// Even elements contain condition expressions in order
ifStmt.List(tok.ParseExpression() );
// Odd elements contain statements to run if the paired expression is true
ifStmt.List(tok.ParseStatement() );
} else {
// Else block if no others run
ifStmt.Map("else", tok.ParseStatement() );
}
}
return ifStmt;
}
/// <summary>
/// <para> Parses a variable declaration. </para>
/// <para>Dec statements are distinct in that they do not escape their block, and override anything with the same name. </para>
/// <para>They may contain:
/// <para> target - the name of the variable that is being stored. </para>
/// <para> assign? - the kind of assignment to do. (default values are treated as null or 0) </para>
/// <para> expr? - The expression to assign, to the target </para>
/// </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseDecStmt(this Tokenizer tok) {
Node decStmt = new Node(DECSTMT);
tok.RequireNext("var");
decStmt.Map("target", tok.content);
tok.Next();
if (tok.At(ASSIGN_TOKEN)) {
decStmt.Map("assign", tok.content);
tok.Next();
decStmt.Map("expr", tok.ParseExpression());
}
return decStmt;
}
/// <summary>
/// <para> Parses a full expression </para>
/// <para> Expressions start with a 'boolean expression' even if they aren't just a true or false value. </para>
/// <para> Every value has a 'truthyness' to it. </para>
/// <para> BooleanExpressions are one or more BooleanTerms linked by '||' </para>
/// <para> They Contain:
/// <para> value - the starting value on the left hand side </para>
/// <para> [nodelist]? - all linked expressions to apply via '||' </para>
/// </para>
/// <para> Will instead just return the value if there are no linked BooleanTerms </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseExpression(this Tokenizer tok) {
Node boolexpr = new Node(EXPR);
Node val = boolexpr.Map("value", tok.ParseBoolTerm());
// List out each bool term. All are ||
while (tok.At("||")) {
tok.Next();
boolexpr.List(tok.ParseBoolTerm());
//boolexpr.Map("rhs", tok.ParseBoolTerm());
}
return (boolexpr.NodesListed == 0) ? val : boolexpr;
}
/// <summary>
/// <para> Parses a BooleanTerm </para>
/// <para> BooleanTerms are one or more BooleanFactors linked by '&&' </para>
/// <para> They Contain:
/// <para> value - the starting value on the left hand side </para>
/// <para> [nodelist]? - all linked expressions to apply via '&&' </para>
/// </para>
/// <para> Will instead just return the value if there are no linked BooleanFactors </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseBoolTerm(this Tokenizer tok) {
Node boolterm = new Node(BOOLTERM);
Node val = boolterm.Map("value", tok.ParseBoolFactor());
// List out each bool factor. All are &&
while (tok.At("&&")) {
tok.Next();
boolterm.List(tok.ParseBoolFactor());
//boolterm.Map("rhs", tok.ParseBoolFactor());
}
return (boolterm.NodesListed == 0) ? val : boolterm;
}
/// <summary> Constant array of comparison tokens to detect boolean comparisons </summary>
public static readonly string[] COMPARISON_TOKEN = { "<", ">", "!=", "==", "<=", ">=" };
/// <summary>
/// <para> Parses a BooleanFactor </para>
/// <para> They contain:
/// <para> value - leftmost ArithExpr value </para>
/// <para> negate? - present/true if there was a '!' in front of the factor. </para>
/// <para> comparison? - present, and one of the tokens in </para>
/// </para>
/// <para> Will instead just return the value if there is no comparison or negation </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseBoolFactor(this Tokenizer tok) {
Node boolfact = new Node(BOOLFACTOR);
if (tok.At("!")) {
boolfact.Map("negate", "true");
tok.Next();
boolfact.Map("value", tok.ParseExpression());
} else {
Node value = boolfact.Map("value", tok.ParseArithExpr());
if (tok.At(COMPARISON_TOKEN)) {
boolfact.Map("comparison", tok.peekToken);
tok.Next();
boolfact.Map("rhs", tok.ParseArithExpr());
} else {
return value;
}
}
return boolfact;
}
/// <summary> Constant array of add/subtract operators </summary>
public static readonly string[] ADD_SUB_TOKEN = { "+", "-" };
/// <summary>
/// <para> Parses an ArithmaticExpression </para>
/// <para> ArithmaticExpressions are one or more ArithmaticTerms linked by '+' or '-' operators. </para>
/// <para> They contain:
/// <para> value - leftmost value to start applying operators to </para>
/// <para> [datalist]? - operators separating value and other ArithmaticTerms </para>
/// <para> [nodelist]? - other linked ArithmaticTerms </para>
/// </para>
/// <para> Will instead just return the value if there are no operators. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseArithExpr(this Tokenizer tok) {
Node arithexpr = new Node(ARITHEXPR);
Node val = arithexpr.Map("value", tok.ParseArithTerm());
while (tok.At(ADD_SUB_TOKEN)) {
arithexpr.List(tok.peekToken);
tok.Next();
arithexpr.List(tok.ParseArithTerm());
}
// If there are no chained operators, we just care about the value
return (arithexpr.NodesListed == 0) ? val : arithexpr;
}
/// <summary> COnstant array of multiplication/division/modulo division operators </summary>
public static readonly string[] MUL_DIV_MOD_TOKEN = { "*", "/", "%" };
/// <summary>
/// <para> Parses an ArithmaticTerm </para>
/// <para> ArithmaticTerms are one or more ArithmaticFactors linked by '*', '/' or '%' operators. </para>
/// <para> They contain:
/// <para> value - leftmost value to start applying operators to </para>
/// <para> [datalist]? - operators separating value and other ArithmaticFactors </para>
/// <para> [nodelist]? - other linked ArithmaticFactors </para>
/// </para>
/// <para> Will instead just return the value if there are no operators. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseArithTerm(this Tokenizer tok) {
Node arithterm = new Node(ARITHTERM);
Node val = arithterm.Map("value", tok.ParseArithFactor());
while (tok.At(MUL_DIV_MOD_TOKEN)) {
arithterm.List(tok.peekToken);
tok.Next();
arithterm.List(tok.ParseArithFactor());
}
// If there are no chained operators, we just care about the value
return (arithterm.NodesListed == 0) ? val : arithterm;
}
/// <summary>
/// <para> Parses an ArithmaticFactor </para>
/// <para> ArithmaticFactors are a negated ArithmaticFactor, an embedded Expression, or an Atom. </para>
/// <para> They may contain:
/// <para> negate - ArithmaticFactor to negate </para>
/// </para>
/// <para> If there is no negation applied, returns the embedded node returned by
/// <see cref="ParseAtom(Tokenizer)"/> or
/// <see cref="ParseExpression(Tokenizer)"/>
/// </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseArithFactor(this Tokenizer tok) {
Node arithfact = new Node(ARITHFACTOR);
Node node = null;
if (tok.At("-")) {
tok.Next();
arithfact.Map("negate", tok.ParseArithFactor());
} else if (tok.At("(")) {
tok.Next();
node = tok.ParseExpression();
tok.RequireNext(")");
} else {
node = tok.ParseAtom();
}
// Only time we care about the arithfactor itself,
// is if it is present to negate the value of its child.
return (node == null) ? arithfact : node;
}
/// <summary> Constant array of tokens that represent a constant value </summary>
public static readonly string[] CONST_TOKEN = { "null", NUMBER, STRING, "true", "false", };
/// <summary> Constant array of tokens that represent different kinds of assignments </summary>
public static readonly string[] ASSIGN_TOKEN = { "=", "+=", "-=", "*=", "/=", "%=", "^=", "|=", "&=", "<<=", ">>=", };
/// <summary> Constant array of tokens that represent an INCrement or DECrement operation on a single variable </summary>
public static readonly string[] INC_DEC_TOKEN = { "++", "--" };
/// <summary>
/// <para> Parses an Atom node </para>
/// <para> An Atom node may be a:
/// <para> object - In-line Object </para>
/// <para> array - In-line Array</para>
/// <para> func - Function definition </para>
/// <para> value - Variable value from <see cref="ParseFromName(Tokenizer)"/></para>
/// </para>
/// <para> Or be a node containing:
/// <para> const? - Constant values (number/string values, true/false/null) </para>
/// <para> inner? - Assignment with value generation, or function call from <see cref="ParseFromName(Tokenizer)"/></para>
/// </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseAtom(this Tokenizer tok) {
Node atom = new Node(ATOM);
if (tok.At(CONST_TOKEN)) {
string content = tok.peekToken.content;
// Strip out ""s or ''s around strings
if (tok.peekToken.Is(STRING)) { content = content.Substring(1, content.Length-2); }
atom.Map("const", content);
tok.Next();
} else if (tok.At("{")) {
return tok.ParseObject();
} else if (tok.At("[")) {
return tok.ParseArray();
} else if (tok.At("func")) {
return atom.Map("func", tok.ParseFunc());
} else {
Node check = atom.Map("inner", tok.ParseFromName());
if (check.type == VALUE) { return check; }
}
return atom;
}
/// <summary>
/// <para> Parses a value, assignment statement, or a function call </para>
/// <para>
/// Due to the way the grammar rules work, it is difficult to determine if
/// a PATH is the start of a value, assignment or a function call.
/// We don't know what it is until later on, after we get the PATH.
/// </para>
/// <para>
/// If the next token is an ASSIGN_TYPE token, it is an assignment
/// Otherwise, if it is an '(', it is a function call.
/// </para>
/// <para>
/// This also parses out an indexer.
/// Functions can be stored inside of indexable collections, and called, ex funcs["doThing"]()
/// </para>
/// <para>
/// The output of this function can be one of many things:
/// <para> funcCall - contains target, indexExpr?, plist </para>
/// <para> assign - contains target, indexExpr?, assignType, expr, pre?, post? </para>
/// <para> value - contains target, indexExpr? </para>
/// </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseFromName(this Tokenizer tok) {
Node node = new Node(VALUE);
if (tok.At(INC_DEC_TOKEN)) {
node.Map("pre", tok.content);
tok.Next();
node.type = ASSIGN;
}
// Token path = tok.ParseFixedPath();
Node path = tok.ParseExprPath();
Node funcCallParams = null;
// Included in ParseExprPath
// if (tok.At("[")) { indexExpr = tok.ParseIndexer(); }
if (tok.At("(")) {
// Detect function calls
funcCallParams = tok.ParseParamsList();
node.type = FUNCCALL;
} else if (tok.At(ASSIGN_TOKEN)) {
node.Map("assignType", tok.peekToken);
tok.Next();
node.Map("expr", tok.ParseExpression());
node.type = ASSIGN;
} else if (tok.At(INC_DEC_TOKEN)) {
node.Map("post", tok.content);
tok.Next();
node.type = ASSIGN;
}
// Anything that is null does not get mapped.
node.Map("target", path);
node.Map("params", funcCallParams);
return node;
}
/// <summary> Parses an Indexer. They have the form <code>[ EXPR ]</code> </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseIndexer(this Tokenizer tok) {
tok.RequireNext("[");
Node indexExpr = tok.ParseExpression();
tok.RequireNext("]");
return indexExpr;
}
/// <summary>
/// <para> Parses a live parameters list </para>
/// <para> Parameters lists contain:
/// <para> [nodelist]? - List of Expression nodes for the parameters list </para>
/// </para>
/// <para> The list will just be empty if there are no parameters. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseParamsList(this Tokenizer tok) {
Node funcCallParams = new Node(PARAMSLIST);
// Start with '('
tok.RequireNext("(");
while (!tok.At(")")) {
funcCallParams.List(tok.ParseExpression());
// Consume separator ','
if (tok.At(",")) { tok.Next(); }
}
// End with ')'
tok.RequireNext(")");
return funcCallParams;
}
/// <summary>
/// <para> Parses an object literal. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseObject(this Tokenizer tok) {
Node obj = new Node(OBJECTLITERAL);
tok.RequireNext("{");
while (!tok.At("}")) {
if (tok.At("...")) {
tok.Next();
Node spread = new Node(SPREAD);
spread.Map("target", tok.ParseFromName());
obj.List(spread);
} else {
tok.Require(NAME);
var name = tok.peekToken;
tok.Next();
if (tok.At(":")) {
tok.RequireNext(":");
var expr = tok.ParseExpression();
obj.Map(name.content, expr);
} else {
obj.List(name);
}
}
if (tok.At(",")) {
tok.Next();
}
}
tok.RequireNext("}");
return obj;
}
/// <summary>
/// <para> Parses an array literal. </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseArray(this Tokenizer tok) {
Node arr = new Node(ARRAYLITERAL);
tok.RequireNext("[");
while (!tok.At("]")) {
if (tok.At("...")) {
tok.Next();
Node spread = new Node(SPREAD);
spread.Map("target", tok.ParseFromName());
arr.List(spread);
} else {
arr.List(tok.ParseExpression());
}
// Consume but do not require commas.
if (tok.At(",")) { tok.Next(); }
}
tok.RequireNext("]");
return arr;
}
/// <summary> Const array of tokens for 'rockets' for syntactic purposes. </summary>
public static readonly string[] ROCKET_TOKENS = { "=>", "->" };
/// <summary>
/// <para> Parses a function declaration </para>
/// <para> Function Declarations contain:
/// <para> varlist - list of parameter variables that get passed into this function </para>
/// <para> codeblock - Body of code that belongs to the function </para>
/// </para>
/// </summary>
/// <param name="tok"> Token Stream to read from </param>
/// <returns> Program node built from tokenizer stream </returns>
public static Node ParseFunc(this Tokenizer tok) {
Node func = new Node(FUNCDEC);
tok.RequireNext("func");
func.Map("varlist", tok.ParseVarList());
// tok.RequireNext(ROCKET_TOKENS);
if (tok.At(ROCKET_TOKENS)) { tok.Next(); }
func.Map("codeblock", tok.ParseCodeBlock());
return func;
}
/// <summary>
/// <para> Parses a VariableList </para>
/// <para> VariableLists contain:
/// <para> [datalist]? - The names of variables for use inside of the function body </para>
/// </para>
/// <para> Will be empty if there were no variables declared. </para>
/// </summary>
/// <param name="tok"></param>
/// <returns></returns>
public static Node ParseVarList(this Tokenizer tok) {
Node vars = new Node(VARLIST);
// var list must be a comma-separated list of valid names inside ()
tok.RequireNext("(");
while (!tok.At(")")) {
// Must be a name
tok.Require(NAME);
// List it
vars.List(tok.peekToken);
// Then consume it
tok.Next();
// Consume separator ','
if (tok.At(",")) { tok.Next(); }
}
// End with ')'
tok.RequireNext(")");
return vars;
}
}
|
ninjapretzel/XtoJSON
|
XJS/XJSParser.cs
|
C#
|
mit
| 30,081
|
function getShortMessages(messages) {
return messages.map(function(m) {
return m.message;
}).filter(function(message) { return message.length < 50; })
}
module.exports = getShortMessages;
|
gothy/functional-javascript-workshop
|
task4.js
|
JavaScript
|
mit
| 197
|
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
$scope.authentication = Authentication;
// If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/');
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
console.log(response);
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
|
ShreyKumar/MagicFlow
|
public/modules/users/controllers/authentication.client.controller.js
|
JavaScript
|
mit
| 1,113
|
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
$("#slide0").addClass("active");
$("#data0").addClass("active");
// JavaScript to be fired on the about us page
}
},
'process': {
init: function() {
$("#design_slide0").addClass("active");
$("#design_data0").addClass("active");
$("#construction_slide0").addClass("active");
$("#administration_slide0").addClass("active");
// JavaScript to be fired on the about us page
}
},
// About us page, note the change from about-us to about_us.
'single_project': {
init: function() {
$("#slide0").addClass("active");
$("#data0").addClass("active");
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
$(function(){
$('#carousel-project-page').carousel({
interval:false
});
});
})(jQuery); // Fully reference jQuery after this point.
|
erikkowalski/Horst-Buchanan-Architects
|
assets/scripts/main.js
|
JavaScript
|
mit
| 2,836
|
# pylint: disable=C0111,R0903
"""Shows that debug is enabled"""
import platform
import core.module
import core.widget
import core.decorators
class Module(core.module.Module):
@core.decorators.every(minutes=60)
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.full_text))
def full_text(self, widgets):
return "debug"
def state(self, widget):
return "warning"
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
tobi-wan-kenobi/bumblebee-status
|
bumblebee_status/modules/core/debug.py
|
Python
|
mit
| 503
|
package md.frolov.legume.client.gin;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.inject.Provides;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import md.frolov.legume.client.mvp.AppActivityMapper;
import md.frolov.legume.client.mvp.AppPlaceHistoryMapper;
public class MVPModule extends AbstractGinModule {
@Override
protected void configure() {
bind(ActivityMapper.class).to(AppActivityMapper.class);
bind(PlaceHistoryMapper.class).to(AppPlaceHistoryMapper.class);
bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
}
@Provides
@Singleton
@Inject
public ActivityManager getActivityManager(ActivityMapper mapper, EventBus eventBus) {
return new ActivityManager(mapper, eventBus);
}
@Provides
@Singleton
@Inject
public PlaceHistoryHandler getPlaceHistoryHandler(PlaceHistoryMapper mapper) {
return new PlaceHistoryHandler(mapper);
}
@Provides
@Singleton
@Inject
public PlaceController getPlaceController(EventBus eventBus) {
return new PlaceController(eventBus);
}
}
|
ivanfrolovmd/legume
|
legume/src/main/java/md/frolov/legume/client/gin/MVPModule.java
|
Java
|
mit
| 1,539
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目 </b></th><td class="std2">不露鋒芒</td></tr>
<tr><th class="std1"><b>注音 </b></th><td class="std2">ㄅㄨ<sup class="subfont">ˋ</sup> ㄌㄡ<sup class="subfont">ˋ</sup> ㄈㄥ ㄇㄤ<sup class="subfont">ˊ</sup></td></tr>
<tr><th class="std1"><b>漢語拼音 </b></th><td class="std2"><font class="english_word">bù lòu fēng máng</font></td></tr>
<tr><th class="std1"><b>釋義 </b></th><td class="std2">才華內斂,不讓自己顯得突出。如:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>這年輕人氣定神閒,不露鋒芒,修養真好。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr>
<tr><th class="std1"><b><font class="fltypefont">附錄</font> </b></th><td class="std2">修訂本參考資料</td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
|
BuzzAcademy/idioms-moe-unformatted-data
|
all-data/14000-14999/14197-22.html
|
HTML
|
mit
| 1,330
|
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目 </b></th><td class="std2">百二關山</td></tr>
<tr><th class="std1"><b>注音 </b></th><td class="std2">ㄅㄞ<sup class="subfont">ˇ</sup> ㄦ<sup class="subfont">ˋ</sup> ㄍㄨㄢ ㄕㄢ</td></tr>
<tr><th class="std1"><b>漢語拼音 </b></th><td class="std2"><font class="english_word">bǎi èr guān shān</font></td></tr>
<tr><th class="std1"><b>釋義 </b></th><td class="std2">形容形勢險要,防事牢固,兵力強盛。見<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>百二山河<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>條。唐˙溫庭筠˙老君廟詩:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>百二關山扶玉座,五千文字閟瑤緘。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr>
<tr><th class="std1"><b><font class="fltypefont">附錄</font> </b></th><td class="std2">修訂本參考資料</td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
|
BuzzAcademy/idioms-moe-unformatted-data
|
all-data/21000-21999/21013-22.html
|
HTML
|
mit
| 1,499
|
from ctypes import c_float, cast, POINTER
import numpy as np
import OpenGL.GL as gl
import openvr
from openvr.gl_renderer import OpenVrFramebuffer as OpenVRFramebuffer
from openvr.gl_renderer import matrixForOpenVrMatrix as matrixForOpenVRMatrix
from openvr.tracked_devices_actor import TrackedDevicesActor
import gltfutils as gltfu
c_float_p = POINTER(c_float)
class OpenVRRenderer(object):
def __init__(self, multisample=0, znear=0.1, zfar=1000):
self.vr_system = openvr.init(openvr.VRApplication_Scene)
w, h = self.vr_system.getRecommendedRenderTargetSize()
self.vr_framebuffers = (OpenVRFramebuffer(w, h, multisample=multisample),
OpenVRFramebuffer(w, h, multisample=multisample))
self.vr_compositor = openvr.VRCompositor()
if self.vr_compositor is None:
raise Exception('unable to create compositor')
self.vr_framebuffers[0].init_gl()
self.vr_framebuffers[1].init_gl()
poses_t = openvr.TrackedDevicePose_t * openvr.k_unMaxTrackedDeviceCount
self.poses = poses_t()
self.projection_matrices = (np.asarray(matrixForOpenVRMatrix(self.vr_system.getProjectionMatrix(openvr.Eye_Left,
znear, zfar))),
np.asarray(matrixForOpenVRMatrix(self.vr_system.getProjectionMatrix(openvr.Eye_Right,
znear, zfar))))
self.eye_transforms = (np.asarray(matrixForOpenVRMatrix(self.vr_system.getEyeToHeadTransform(openvr.Eye_Left)).I),
np.asarray(matrixForOpenVRMatrix(self.vr_system.getEyeToHeadTransform(openvr.Eye_Right)).I))
self.view = np.eye(4, dtype=np.float32)
self.view_matrices = (np.empty((4,4), dtype=np.float32),
np.empty((4,4), dtype=np.float32))
self.controllers = TrackedDevicesActor(self.poses)
self.controllers.show_controllers_only = False
self.controllers.init_gl()
self.vr_event = openvr.VREvent_t()
def render(self, gltf, nodes, window_size=(800, 600)):
self.vr_compositor.waitGetPoses(self.poses, openvr.k_unMaxTrackedDeviceCount, None, 0)
hmd_pose = self.poses[openvr.k_unTrackedDeviceIndex_Hmd]
if not hmd_pose.bPoseIsValid:
return
hmd_34 = np.ctypeslib.as_array(cast(hmd_pose.mDeviceToAbsoluteTracking.m, c_float_p),
shape=(3,4))
self.view[:3,:] = hmd_34
view = np.linalg.inv(self.view.T)
view.dot(self.eye_transforms[0], out=self.view_matrices[0])
view.dot(self.eye_transforms[1], out=self.view_matrices[1])
gl.glViewport(0, 0, self.vr_framebuffers[0].width, self.vr_framebuffers[0].height)
for eye in (0, 1):
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.vr_framebuffers[eye].fb)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gltfu.set_material_state.current_material = None
gltfu.set_technique_state.current_technique = None
for node in nodes:
gltfu.draw_node(node, gltf,
projection_matrix=self.projection_matrices[eye],
view_matrix=self.view_matrices[eye])
self.controllers.display_gl(self.view_matrices[eye], self.projection_matrices[eye])
self.vr_compositor.submit(openvr.Eye_Left, self.vr_framebuffers[0].texture)
self.vr_compositor.submit(openvr.Eye_Right, self.vr_framebuffers[1].texture)
# mirror left eye framebuffer to screen:
gl.glBlitNamedFramebuffer(self.vr_framebuffers[0].fb, 0,
0, 0, self.vr_framebuffers[0].width, self.vr_framebuffers[0].height,
0, 0, window_size[0], window_size[1],
gl.GL_COLOR_BUFFER_BIT, gl.GL_NEAREST)
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
def process_input(self):
pass
# state = self.vr_system.getControllerState(1)
# if state and state.rAxis[1].x > 0.05:
# self.vr_system.triggerHapticPulse(1, 0, int(3200 * state.rAxis[1].x))
# state = self.vr_system.getControllerState(2)
# if state and state.rAxis[1].x > 0.05:
# self.vr_system.triggerHapticPulse(2, 0, int(3200 * state.rAxis[1].x))
# if self.vr_system.pollNextEvent(self.vr_event):
# if self.vr_event.eventType == openvr.VREvent_ButtonPress:
# pass #print('vr controller button pressed')
# elif self.vr_event.eventType == openvr.VREvent_ButtonUnpress:
# pass #print('vr controller button unpressed')
def shutdown(self):
self.controllers.dispose_gl()
openvr.shutdown()
|
jzitelli/python-gltf-experiments
|
OpenVRRenderer.py
|
Python
|
mit
| 4,971
|
// Type definitions for Angular Protractor 1.5.0
// Project: https://github.com/angular/protractor
// Definitions by: Bill Armstrong <https://github.com/BillArmstrong>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../selenium-webdriver/selenium-webdriver.d.ts" />
declare module protractor {
//region Wrapped webdriver Items
class ActionSequence extends webdriver.ActionSequence {}
class Builder extends webdriver.Builder {}
class Capabilities extends webdriver.Capabilities {}
class Command extends webdriver.Command {}
class EventEmitter extends webdriver.EventEmitter {}
class Session extends webdriver.Session {}
class WebDriver extends webdriver.WebDriver {}
class WebElement extends webdriver.WebElement {}
class WebElementPromise extends webdriver.WebElementPromise { }
var Browser: webdriver.IBrowser;
var Button: webdriver.IButton;
var Capability: webdriver.ICapability;
var CommandName: webdriver.ICommandName;
var Key: webdriver.IKey;
module error {
class Error extends webdriver.error.Error {}
var ErrorCode: webdriver.error.IErrorCode;
}
module logging {
class Preferences extends webdriver.logging.Preferences { }
class Entry extends webdriver.logging.Entry { }
var Type: webdriver.logging.IType;
var Level: webdriver.logging.ILevelValues;
function getLevel(nameOrValue: string): webdriver.logging.ILevel;
function getLevel(nameOrValue: number): webdriver.logging.ILevel;
}
module promise {
class Thenable<T> extends webdriver.promise.Thenable<T> { }
class Promise<T> extends webdriver.promise.Promise<T> { }
class Deferred<T> extends webdriver.promise.Deferred<T> { }
class ControlFlow extends webdriver.promise.ControlFlow { }
class CancellationError extends webdriver.promise.CancellationError { }
/**
* Given an array of promises, will return a promise that will be fulfilled
* with the fulfillment values of the input array's values. If any of the
* input array's promises are rejected, the returned promise will be rejected
* with the same reason.
*
* @param {!Array.<(T|!webdriver.promise.Promise.<T>)>} arr An array of
* promises to wait on.
* @return {!webdriver.promise.Promise.<!Array.<T>>} A promise that is
* fulfilled with an array containing the fulfilled values of the
* input array, or rejected with the same reason as the first
* rejected value.
* @template T
*/
function all(arr: webdriver.promise.Promise<any>[]): webdriver.promise.Promise<any[]>;
/**
* Invokes the appropriate callback function as soon as a promised
* {@code value} is resolved. This function is similar to
* {@link webdriver.promise.when}, except it does not return a new promise.
* @param {*} value The value to observe.
* @param {Function} callback The function to call when the value is
* resolved successfully.
* @param {Function=} opt_errback The function to call when the value is
* rejected.
*/
function asap(value: any, callback: Function, opt_errback?: Function): void;
/**
* @return {!webdriver.promise.ControlFlow} The currently active control flow.
*/
function controlFlow(): webdriver.promise.ControlFlow;
/**
* Creates a new control flow. The provided callback will be invoked as the
* first task within the new flow, with the flow as its sole argument. Returns
* a promise that resolves to the callback result.
* @param {function(!webdriver.promise.ControlFlow)} callback The entry point
* to the newly created flow.
* @return {!webdriver.promise.Promise} A promise that resolves to the callback
* result.
*/
function createFlow<R>(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise<R>;
/**
* Determines whether a {@code value} should be treated as a promise.
* Any object whose "then" property is a function will be considered a promise.
*
* @param {*} value The value to test.
* @return {boolean} Whether the value is a promise.
*/
function isPromise(value: any): boolean;
/**
* Tests is a function is a generator.
* @param {!Function} fn The function to test.
* @return {boolean} Whether the function is a generator.
*/
function isGenerator(fn: Function): boolean;
/**
* Creates a promise that will be resolved at a set time in the future.
* @param {number} ms The amount of time, in milliseconds, to wait before
* resolving the promise.
* @return {!webdriver.promise.Promise} The promise.
*/
function delayed(ms: number): webdriver.promise.Promise<void>;
/**
* Calls a function for each element in an array, and if the function returns
* true adds the element to a new array.
*
* <p>If the return value of the filter function is a promise, this function
* will wait for it to be fulfilled before determining whether to insert the
* element into the new array.
*
* <p>If the filter function throws or returns a rejected promise, the promise
* returned by this function will be rejected with the same reason. Only the
* first failure will be reported; all subsequent errors will be silently
* ignored.
*
* @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The
* array to iterator over, or a promise that will resolve to said array.
* @param {function(this: SELF, TYPE, number, !Array.<TYPE>): (
* boolean|webdriver.promise.Promise.<boolean>)} fn The function
* to call for each element in the array.
* @param {SELF=} opt_self The object to be used as the value of 'this' within
* {@code fn}.
* @template TYPE, SELF
*/
function filter<T>(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise<T[]>;
function filter<T>(arr: webdriver.promise.Promise<T[]>, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise<T[]>
/**
* Creates a new deferred object.
* @return {!webdriver.promise.Deferred} The new deferred object.
*/
function defer<T>(): webdriver.promise.Deferred<T>;
/**
* Creates a promise that has been resolved with the given value.
* @param {*=} opt_value The resolved value.
* @return {!webdriver.promise.Promise} The resolved promise.
*/
function fulfilled<T>(opt_value?: T): webdriver.promise.Promise<T>;
/**
* Calls a function for each element in an array and inserts the result into a
* new array, which is used as the fulfillment value of the promise returned
* by this function.
*
* <p>If the return value of the mapping function is a promise, this function
* will wait for it to be fulfilled before inserting it into the new array.
*
* <p>If the mapping function throws or returns a rejected promise, the
* promise returned by this function will be rejected with the same reason.
* Only the first failure will be reported; all subsequent errors will be
* silently ignored.
*
* @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The
* array to iterator over, or a promise that will resolve to said array.
* @param {function(this: SELF, TYPE, number, !Array.<TYPE>): ?} fn The
* function to call for each element in the array. This function should
* expect three arguments (the element, the index, and the array itself.
* @param {SELF=} opt_self The object to be used as the value of 'this' within
* {@code fn}.
* @template TYPE, SELF
*/
function map<T>(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise<T[]>
function map<T>(arr: webdriver.promise.Promise<T[]>, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise<T[]>
/**
* Creates a promise that has been rejected with the given reason.
* @param {*=} opt_reason The rejection reason; may be any value, but is
* usually an Error or a string.
* @return {!webdriver.promise.Promise} The rejected promise.
*/
function rejected(opt_reason?: any): webdriver.promise.Promise<void>;
/**
* Wraps a function that is assumed to be a node-style callback as its final
* argument. This callback takes two arguments: an error value (which will be
* null if the call succeeded), and the success value as the second argument.
* If the call fails, the returned promise will be rejected, otherwise it will
* be resolved with the result.
* @param {!Function} fn The function to wrap.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* result of the provided function's callback.
*/
function checkedNodeCall<T>(fn: Function, ...var_args: any[]): webdriver.promise.Promise<T>;
/**
* Consumes a {@code GeneratorFunction}. Each time the generator yields a
* promise, this function will wait for it to be fulfilled before feeding the
* fulfilled value back into {@code next}. Likewise, if a yielded promise is
* rejected, the rejection error will be passed to {@code throw}.
*
* <p>Example 1: the Fibonacci Sequence.
* <pre><code>
* webdriver.promise.consume(function* fibonacci() {
* var n1 = 1, n2 = 1;
* for (var i = 0; i < 4; ++i) {
* var tmp = yield n1 + n2;
* n1 = n2;
* n2 = tmp;
* }
* return n1 + n2;
* }).then(function(result) {
* console.log(result); // 13
* });
* </code></pre>
*
* <p>Example 2: a generator that throws.
* <pre><code>
* webdriver.promise.consume(function* () {
* yield webdriver.promise.delayed(250).then(function() {
* throw Error('boom');
* });
* }).thenCatch(function(e) {
* console.log(e.toString()); // Error: boom
* });
* </code></pre>
*
* @param {!Function} generatorFn The generator function to execute.
* @param {Object=} opt_self The object to use as "this" when invoking the
* initial generator.
* @param {...*} var_args Any arguments to pass to the initial generator.
* @return {!webdriver.promise.Promise.<?>} A promise that will resolve to the
* generator's final result.
* @throws {TypeError} If the given function is not a generator.
*/
function consume<T>(generatorFn: Function, opt_self?: any, ...var_args: any[]): webdriver.promise.Promise<T>;
/**
* Registers an observer on a promised {@code value}, returning a new promise
* that will be resolved when the value is. If {@code value} is not a promise,
* then the return promise will be immediately resolved.
* @param {*} value The value to observe.
* @param {Function=} opt_callback The function to call when the value is
* resolved successfully.
* @param {Function=} opt_errback The function to call when the value is
* rejected.
* @return {!webdriver.promise.Promise} A new promise.
*/
function when<T, R>(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise<R>;
function when<T, R>(value: webdriver.promise.Promise<T>, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise<R>;
/**
* Returns a promise that will be resolved with the input value in a
* fully-resolved state. If the value is an array, each element will be fully
* resolved. Likewise, if the value is an object, all keys will be fully
* resolved. In both cases, all nested arrays and objects will also be
* fully resolved. All fields are resolved in place; the returned promise will
* resolve on {@code value} and not a copy.
*
* Warning: This function makes no checks against objects that contain
* cyclical references:
*
* var value = {};
* value['self'] = value;
* webdriver.promise.fullyResolved(value); // Stack overflow.
*
* @param {*} value The value to fully resolve.
* @return {!webdriver.promise.Promise} A promise for a fully resolved version
* of the input value.
*/
function fullyResolved<T>(value: any): webdriver.promise.Promise<T>;
/**
* Changes the default flow to use when no others are active.
* @param {!webdriver.promise.ControlFlow} flow The new default flow.
* @throws {Error} If the default flow is not currently active.
*/
function setDefaultFlow(flow: webdriver.promise.ControlFlow): void;
}
module stacktrace {
class Frame extends webdriver.stacktrace.Frame { }
class Snapshot extends webdriver.stacktrace.Snapshot { }
/**
* Formats an error's stack trace.
* @param {!(Error|goog.testing.JsUnitException)} error The error to format.
* @return {!(Error|goog.testing.JsUnitException)} The formatted error.
*/
function format(error: any): any;
/**
* Gets the native stack trace if available otherwise follows the call chain.
* The generated trace will exclude all frames up to and including the call to
* this function.
* @return {!Array.<!webdriver.stacktrace.Frame>} The frames of the stack trace.
*/
function get(): webdriver.stacktrace.Frame[];
/**
* Whether the current browser supports stack traces.
*
* @constructor {boolean}
* @const
*/
var BROWSER_SUPPORTED: boolean;
}
module until {
class Condition<T> extends webdriver.until.Condition<T> { }
/**
* Creates a condition that will wait until the input driver is able to switch
* to the designated frame. The target frame may be specified as:
* <ol>
* <li>A numeric index into {@code window.frames} for the currently selected
* frame.
* <li>A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME
* element on the current page.
* <li>A locator which may be used to first locate a FRAME or IFRAME on the
* current page before attempting to switch to it.
* </ol>
*
* <p>Upon successful resolution of this condition, the driver will be left
* focused on the new frame.
*
* @param {!(number|webdriver.WebElement|
* webdriver.Locator|webdriver.By.Hash|
* function(!webdriver.WebDriver): !webdriver.WebElement)} frame
* The frame identifier.
* @return {!until.Condition.<boolean>} A new condition.
*/
function ableToSwitchToFrame(frame: number): webdriver.until.Condition<boolean>;
function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition<boolean>;
function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition<boolean>;
function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition<boolean>;
function ableToSwitchToFrame(frame: any): webdriver.until.Condition<boolean>;
/**
* Creates a condition that waits for an alert to be opened. Upon success, the
* returned promise will be fulfilled with the handle for the opened alert.
*
* @return {!until.Condition.<!webdriver.Alert>} The new condition.
*/
function alertIsPresent(): webdriver.until.Condition<webdriver.Alert>;
/**
* Creates a condition that will wait for the given element to be disabled.
*
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isEnabled
*/
function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element to be enabled.
*
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isEnabled
*/
function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element to be deselected.
*
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isSelected
*/
function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element to be in the DOM,
* yet not visible to the user.
*
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isDisplayed
*/
function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element to be selected.
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isSelected
*/
function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element to become visible.
*
* @param {!webdriver.WebElement} element The element to test.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#isDisplayed
*/
function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will loop until an element is
* {@link webdriver.WebDriver#findElement found} with the given locator.
*
* @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator
* to use.
* @return {!until.Condition.<!webdriver.WebElement>} The new condition.
*/
function elementLocated(locator: webdriver.Locator): webdriver.until.Condition<webdriver.IWebElement>;
function elementLocated(locator: any): webdriver.until.Condition<webdriver.IWebElement>;
/**
* Creates a condition that will wait for the given element's
* {@link webdriver.WebDriver#getText visible text} to contain the given
* substring.
*
* @param {!webdriver.WebElement} element The element to test.
* @param {string} substr The substring to search for.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#getText
*/
function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element's
* {@link webdriver.WebDriver#getText visible text} to match the given
* {@code text} exactly.
*
* @param {!webdriver.WebElement} element The element to test.
* @param {string} text The expected text.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#getText
*/
function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the given element's
* {@link webdriver.WebDriver#getText visible text} to match a regular
* expression.
*
* @param {!webdriver.WebElement} element The element to test.
* @param {!RegExp} regex The regular expression to test against.
* @return {!until.Condition.<boolean>} The new condition.
* @see webdriver.WebDriver#getText
*/
function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will loop until at least get element is
* {@link webdriver.WebDriver#findElement found} with the given locator.
*
* @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator
* to use.
* @return {!until.Condition.<!Array.<!webdriver.WebElement>>} The new
* condition.
*/
function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition<webdriver.IWebElement[]>;
function elementsLocated(locator: any): webdriver.until.Condition<webdriver.IWebElement[]>;
/**
* Creates a condition that will wait for the given element to become stale. An
* element is considered stale once it is removed from the DOM, or a new page
* has loaded.
*
* @param {!webdriver.WebElement} element The element that should become stale.
* @return {!until.Condition.<boolean>} The new condition.
*/
function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the current page's title to contain
* the given substring.
*
* @param {string} substr The substring that should be present in the page
* title.
* @return {!until.Condition.<boolean>} The new condition.
*/
function titleContains(substr: string): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the current page's title to match the
* given value.
*
* @param {string} title The expected page title.
* @return {!until.Condition.<boolean>} The new condition.
*/
function titleIs(title: string): webdriver.until.Condition<boolean>;
/**
* Creates a condition that will wait for the current page's title to match the
* given regular expression.
*
* @param {!RegExp} regex The regular expression to test against.
* @return {!until.Condition.<boolean>} The new condition.
*/
function titleMatches(regex: RegExp): webdriver.until.Condition<boolean>;
}
//endregion
/**
* Use as: element(locator)
*
* The ElementFinder can be treated as a WebElement for most purposes, in
* particular, you may perform actions (i.e. click, getText) on them as you
* would a WebElement. ElementFinders extend Promise, and once an action
* is performed on an ElementFinder, the latest result from the chain can be
* accessed using then. Unlike a WebElement, an ElementFinder will wait for
* angular to settle before performing finds or actions.
*
* ElementFinder can be used to build a chain of locators that is used to find
* an element. An ElementFinder does not actually attempt to find the element
* until an action is called, which means they can be set up in helper files
* before the page is available.
*
* @param {webdriver.Locator} locator An element locator.
* @return {ElementFinder}
*/
interface Element {
(locator: webdriver.Locator): ElementFinder;
/**
* ElementArrayFinder is used for operations on an array of elements (as opposed
* to a single element).
*
* @param {webdriver.Locator} locator An element locator.
* @return {ElementArrayFinder}
*/
all(locator: webdriver.Locator): ElementArrayFinder;
}
interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable<any> {
/**
* Calls to element may be chained to find elements within a parent.
*
* @alias element(locator).element(locator)
* @view
* <div class="parent">
* <div class="child">
* Child text
* <div>{{person.phone}}</div>
* </div>
* </div>
*
* @example
* // Chain 2 element calls.
* var child = element(by.css('.parent')).
* element(by.css('.child'));
* expect(child.getText()).toBe('Child text\n555-123-4567');
*
* // Chain 3 element calls.
* var triple = element(by.css('.parent')).
* element(by.css('.child')).
* element(by.binding('person.phone'));
* expect(triple.getText()).toBe('555-123-4567');
*
* @param {webdriver.Locator} subLocator
* @return {ElementFinder}
*/
element(subLocator: webdriver.Locator): ElementFinder;
/**
* Calls to element may be chained to find an array of elements within a parent.
*
* @alias element(locator).all(locator)
* @view
* <div class="parent">
* <ul>
* <li class="get">First</li>
* <li class="two">Second</li>
* <li class="three">Third</li>
* </ul>
* </div>
*
* @example
* var items = element(by.css('.parent')).all(by.tagName('li'))
*
* @param {webdriver.Locator} subLocator
* @return {ElementArrayFinder}
*/
all(subLocator: webdriver.Locator): ElementArrayFinder;
/**
* Shortcut for querying the document directly with css.
*
* @alias $(cssSelector)
* @view
* <div class="count">
* <span class="get">First</span>
* <span class="two">Second</span>
* </div>
*
* @example
* var get = $('.count .two');
* expect(get.getText()).toBe('Second');
*
* @param {string} selector A css selector
* @return {ElementFinder} which identifies the located
* {@link webdriver.WebElement}
*/
$(selector: string): ElementFinder;
/**
* Shortcut for querying the document directly with css.
*
* @alias $$(cssSelector)
* @view
* <div class="count">
* <span class="get">First</span>
* <span class="two">Second</span>
* </div>
*
* @example
* // The following protractor expressions are equivalent.
* var list = element.all(by.css('.count span'));
* expect(list.count()).toBe(2);
*
* list = $$('.count span');
* expect(list.count()).toBe(2);
* expect(list.get(0).getText()).toBe('First');
* expect(list.get(1).getText()).toBe('Second');
*
* @param {string} selector a css selector
* @return {ElementArrayFinder} which identifies the
* array of the located {@link webdriver.WebElement}s.
*/
$$(selector: string): ElementArrayFinder;
/**
* Determine whether the element is present on the page.
*
* @view
* <span>{{person.name}}</span>
*
* @example
* // Element exists.
* expect(element(by.binding('person.name')).isPresent()).toBe(true);
*
* // Element not present.
* expect(element(by.binding('notPresent')).isPresent()).toBe(false);
*
* @return {ElementFinder} which resolves to whether
* the element is present on the page.
*/
isPresent(): webdriver.promise.Promise<boolean>;
/**
* Override for WebElement.prototype.isElementPresent so that protractor waits
* for Angular to settle before making the check.
*
* @see ElementFinder.isPresent
*
* @param {webdriver.Locator} subLocator Locator for element to look for.
* @return {ElementFinder} which resolves to whether
* the element is present on the page.
*/
isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise<boolean>;
/**
* @see ElementArrayFinder.prototype.locator
*
* @return {webdriver.Locator}
*/
locator(): webdriver.Locator;
/**
* Returns the WebElement represented by this ElementFinder.
* Throws the WebDriver error if the element doesn't exist.
*
* @example
* The following three expressions are equivalent.
* element(by.css('.parent')).getWebElement();
* browser.waitForAngular(); browser.driver.findElement(by.css('.parent'));
* browser.findElement(by.css('.parent'));
*
* @alias element(locator).getWebElement()
* @return {webdriver.WebElement}
*/
getWebElement(): webdriver.WebElement;
/**
* Evaluates the input as if it were on the scope of the current element.
* @see ElementArrayFinder.evaluate
*
* @param {string} expression
*
* @return {ElementFinder} which resolves to the evaluated expression.
*/
evaluate(expression: string): ElementFinder;
/**
* @see ElementArrayFinder.prototype.allowAnimations.
* @param {string} value
*
* @return {ElementFinder} which resolves to whether animation is allowed.
*/
allowAnimations(value: string): ElementFinder;
/**
* Create a shallow copy of ElementFinder.
*
* @return {!ElementFinder} A shallow copy of this.
*/
clone(): ElementFinder;
}
interface ElementArrayFinder extends webdriver.promise.IThenable<ElementFinder[]> {
/**
* Returns the elements as an array of WebElements.
*/
getWebElements(): webdriver.WebElement[];
/**
* Get an element within the ElementArrayFinder by index. The index starts at 0.
* Negative indices are wrapped (i.e. -i means ith element from last)
* This does not actually retrieve the underlying element.
*
* @alias element.all(locator).get(index)
* @view
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* @example
* var list = element.all(by.css('.items li'));
* expect(list.get(0).getText()).toBe('First');
* expect(list.get(1).getText()).toBe('Second');
*
* @param {number} index Element index.
* @return {ElementFinder} finder representing element at the given index.
*/
get(index: number): ElementFinder;
/**
* Get the first matching element for the ElementArrayFinder. This does not
* actually retrieve the underlying element.
*
* @alias element.all(locator).first()
* @view
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* @example
* var first = element.all(by.css('.items li')).first();
* expect(first.getText()).toBe('First');
*
* @return {ElementFinder} finder representing the first matching element
*/
first(): ElementFinder;
/**
* Get the last matching element for the ElementArrayFinder. This does not
* actually retrieve the underlying element.
*
* @alias element.all(locator).last()
* @view
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* @example
* var last = element.all(by.css('.items li')).last();
* expect(last.getText()).toBe('Third');
*
* @return {ElementFinder} finder representing the last matching element
*/
last(): ElementFinder;
/**
* Count the number of elements represented by the ElementArrayFinder.
*
* @alias element.all(locator).count()
* @view
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* @example
* var list = element.all(by.css('.items li'));
* expect(list.count()).toBe(3);
*
* @return {!webdriver.promise.Promise} A promise which resolves to the
* number of elements matching the locator.
*/
count(): webdriver.promise.Promise<number>;
/**
* Calls the input function on each ElementFinder represented by the ElementArrayFinder.
*
* @alias element.all(locator).each(eachFunction)
* @view
* <ul class="items">
* <li>First</li>
* <li>Second</li>
* <li>Third</li>
* </ul>
*
* @example
* element.all(by.css('.items li')).each(function(element) {
* // Will print First, Second, Third.
* element.getText().then(console.log);
* });
*
* @param {function(ElementFinder)} fn Input function
*/
each(fn: (element: ElementFinder, index: number) => void): void;
/**
* Apply a map function to each element within the ElementArrayFinder. The
* callback receives the ElementFinder as the first argument and the index as
* a second arg.
*
* @alias element.all(locator).map(mapFunction)
* @view
* <ul class="items">
* <li class="get">First</li>
* <li class="two">Second</li>
* <li class="three">Third</li>
* </ul>
*
* @example
* var items = element.all(by.css('.items li')).map(function(elm, index) {
* return {
* index: index,
* text: elm.getText(),
* class: elm.getAttribute('class')
* };
* });
* expect(items).toEqual([
* {index: 0, text: 'First', class: 'get'},
* {index: 1, text: 'Second', class: 'two'},
* {index: 2, text: 'Third', class: 'three'}
* ]);
*
* @param {function(ElementFinder, number)} mapFn Map function that
* will be applied to each element.
* @return {!webdriver.promise.Promise} A promise that resolves to an array
* of values returned by the map function.
*/
map<T>(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise<T[]>;
/**
* Apply a filter function to each element within the ElementArrayFinder. Returns
* a new ElementArrayFinder with all elements that pass the filter function. The
* filter function receives the ElementFinder as the first argument
* and the index as a second arg.
* This does not actually retrieve the underlying list of elements, so it can
* be used in page objects.
*
* @alias element.all(locator).filter(filterFn)
* @view
* <ul class="items">
* <li class="get">First</li>
* <li class="two">Second</li>
* <li class="three">Third</li>
* </ul>
*
* @example
* element.all(by.css('.items li')).filter(function(elem, index) {
* return elem.getText().then(function(text) {
* return text === 'Third';
* });
* }).then(function(filteredElements) {
* filteredElements[0].click();
* });
*
* @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn
* Filter function that will test if an element should be returned.
* filterFn can either return a boolean or a promise that resolves to a boolean.
* @return {!ElementArrayFinder} A ElementArrayFinder that represents an array
* of element that satisfy the filter function.
*/
filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder;
/**
* Apply a reduce function against an accumulator and every element found
* using the locator (from left-to-right). The reduce function has to reduce
* every element into a single value (the accumulator). Returns promise of
* the accumulator. The reduce function receives the accumulator, current
* ElementFinder, the index, and the entire array of ElementFinders,
* respectively.
*
* @alias element.all(locator).reduce(reduceFn)
* @view
* <ul class="items">
* <li class="get">First</li>
* <li class="two">Second</li>
* <li class="three">Third</li>
* </ul>
*
* @example
* var value = element.all(by.css('.items li')).reduce(function(acc, elem) {
* return elem.getText().then(function(text) {
* return acc + text + ' ';
* });
* });
*
* expect(value).toEqual('First Second Third ');
*
* @param {function(number, ElementFinder, number, Array.<ElementFinder>)}
* reduceFn Reduce function that reduces every element into a single value.
* @param {*} initialValue Initial value of the accumulator.
* @return {!webdriver.promise.Promise} A promise that resolves to the final
* value of the accumulator.
*/
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise<T>, initialValue: T): webdriver.promise.Promise<T>;
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise<T>;
/**
* Represents the ElementArrayFinder as an array of ElementFinders.
*
* @return {Array.<ElementFinder>} Return a promise, which resolves to a list
* of ElementFinders specified by the locator.
*/
asElementFinders_(): webdriver.promise.Promise<ElementFinder[]>;
/**
* Create a shallow copy of ElementArrayFinder.
*
* @return {!ElementArrayFinder} A shallow copy of this.
*/
clone(): ElementArrayFinder;
/**
* Calls to ElementArrayFinder may be chained to find an array of elements
* using the current elements in this ElementArrayFinder as the starting point.
* This function returns a new ElementArrayFinder which would contain the
* children elements found (and could also be empty).
*
* @alias element.all(locator).all(locator)
* @view
* <div id='id1' class="parent">
* <ul>
* <li class="foo">1a</li>
* <li class="baz">1b</li>
* </ul>
* </div>
* <div id='id2' class="parent">
* <ul>
* <li class="foo">2a</li>
* <li class="bar">2b</li>
* </ul>
* </div>
*
* @example
* var foo = element.all(by.css('.parent')).all(by.css('.foo'))
* expect(foo.getText()).toEqual(['1a', '2a'])
* var baz = element.all(by.css('.parent')).all(by.css('.baz'))
* expect(baz.getText()).toEqual(['1b'])
* var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT'))
* expect(nonexistent.getText()).toEqual([''])
*
* @param {webdriver.Locator} subLocator
* @return {ElementArrayFinder}
*/
all(locator: webdriver.Locator): ElementArrayFinder;
/**
* Shorthand function for finding arrays of elements by css.
*
* @constructor {function(string): ElementArrayFinder}
*/
$$(selector: string): ElementArrayFinder;
/**
* Returns an ElementFinder representation of ElementArrayFinder. It ensures
* that the ElementArrayFinder resolves to get and only get underlying element.
*
* @return {ElementFinder} An ElementFinder representation
* @private
*/
toElementFinder_(): ElementFinder;
/**
* Returns the most relevant locator.
*
* @example
* $('#ID1').locator() // returns by.css('#ID1')
* $('#ID1').$('#ID2').locator() // returns by.css('#ID2')
* $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1')
*
* @return {webdriver.Locator}
*/
locator(): webdriver.Locator;
/**
* Evaluates the input as if it were on the scope of the current underlying
* elements.
*
* @view
* <span id="foo">{{variableInScope}}</span>
*
* @example
* var value = element(by.id('foo')).evaluate('variableInScope');
*
* @param {string} expression
*
* @return {ElementArrayFinder} which resolves to the
* evaluated expression for each underlying element.
* The result will be resolved as in
* {@link webdriver.WebDriver.executeScript}. In summary - primitives will
* be resolved as is, functions will be converted to string, and elements
* will be returned as a WebElement.
*/
evaluate(expression: string): ElementArrayFinder;
/**
* Determine if animation is allowed on the current underlying elements.
* @param {string} value
*
* @example
* // Turns off ng-animate animations for all elements in the <body>
* element(by.css('body')).allowAnimations(false);
*
* @return {ElementArrayFinder} which resolves to whether animation is allowed.
*/
allowAnimations(value: boolean): ElementArrayFinder;
/**
* Schedules a command to click on this element.
* @return {!webdriver.promise.Promise} A promise that will be resolved when
* the click command has completed.
*/
click(): webdriver.promise.Promise<void>;
/**
* Schedules a command to constructor a sequence on the DOM element represented by this
* instance.
* <p/>
* Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
* processed in the keysequence, that key state is toggled until get of the
* following occurs:
* <ul>
* <li>The modifier key is encountered again in the sequence. At this point the
* state of the key is toggled (along with the appropriate keyup/down events).
* </li>
* <li>The {@code webdriver.Key.NULL} key is encountered in the sequence. When
* this key is encountered, all modifier keys current in the down state are
* released (with accompanying keyup events). The NULL key can be used to
* simulate common keyboard shortcuts:
* <code>
* element.sendKeys("text was",
* webdriver.Key.CONTROL, "a", webdriver.Key.NULL,
* "now text is");
* // Alternatively:
* element.sendKeys("text was",
* webdriver.Key.chord(webdriver.Key.CONTROL, "a"),
* "now text is");
* </code></li>
* <li>The end of the keysequence is encountered. When there are no more keys
* to constructor, all depressed modifier keys are released (with accompanying keyup
* events).
* </li>
* </ul>
* <strong>Note:</strong> On browsers where native keyboard events are not yet
* supported (e.g. Firefox on OS X), key events will be synthesized. Special
* punctionation keys will be synthesized according to a standard QWERTY en-us
* keyboard layout.
*
* @param {...string} var_args The sequence of keys to
* constructor. All arguments will be joined into a single sequence (var_args is
* permitted for convenience).
* @return {!webdriver.promise.Promise} A promise that will be resolved when all
* keys have been typed.
*/
sendKeys(...var_args: string[]): webdriver.promise.Promise<void>;
/**
* Schedules a command to query for the tag/node name of this element.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* element's tag name.
*/
getTagName(): webdriver.promise.Promise<string[]>;
/**
* Schedules a command to query for the computed style of the element
* represented by this instance. If the element inherits the named style from
* its parent, the parent will be queried for its value. Where possible, color
* values will be converted to their hex representation (e.g. #00ff00 instead of
* rgb(0, 255, 0)).
* <p/>
* <em>Warning:</em> the value returned will be as the browser interprets it, so
* it may be tricky to form a proper assertion.
*
* @param {string} cssStyleProperty The name of the CSS style property to look
* up.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* requested CSS value.
*/
getCssValue(cssStyleProperty: string): webdriver.promise.Promise<string[]>;
/**
* Schedules a command to query for the value of the given attribute of the
* element. Will return the current value even if it has been modified after the
* page has been loaded. More exactly, this method will return the value of the
* given attribute, unless that attribute is not present, in which case the
* value of the property with the same name is returned. If neither value is
* set, null is returned. The "style" attribute is converted as best can be to a
* text representation with a trailing semi-colon. The following are deemed to
* be "boolean" attributes and will be returned as thus:
*
* <p>async, autofocus, autoplay, checked, compact, complete, controls, declare,
* defaultchecked, defaultselected, defer, disabled, draggable, ended,
* formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
* loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
* paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
* selected, spellcheck, truespeed, willvalidate
*
* <p>Finally, the following commonly mis-capitalized attribute/property names
* are evaluated as expected:
* <ul>
* <li>"class"
* <li>"readonly"
* </ul>
* @param {string} attributeName The name of the attribute to query.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* attribute's value.
*/
getAttribute(attributeName: string): webdriver.promise.Promise<string[]>;
/**
* Get the visible (i.e. not hidden by CSS) innerText of this element, including
* sub-elements, without any leading or trailing whitespace.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* element's visible text.
*/
getText(): webdriver.promise.Promise<string[]>;
/**
* Schedules a command to compute the size of this element's bounding box, in
* pixels.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* element's size as a {@code {width:number, height:number}} object.
*/
getSize(): webdriver.promise.Promise<webdriver.ISize[]>;
/**
* Schedules a command to compute the location of this element in page space.
* @return {!webdriver.promise.Promise} A promise that will be resolved to the
* element's location as a {@code {x:number, y:number}} object.
*/
getLocation(): webdriver.promise.Promise<webdriver.ILocation[]>;
/**
* Schedules a command to query whether the DOM element represented by this
* instance is enabled, as dicted by the {@code disabled} attribute.
* @return {!webdriver.promise.Promise} A promise that will be resolved with
* whether this element is currently enabled.
*/
isEnabled(): webdriver.promise.Promise<boolean[]>;
/**
* Schedules a command to query whether this element is selected.
* @return {!webdriver.promise.Promise} A promise that will be resolved with
* whether this element is currently selected.
*/
isSelected(): webdriver.promise.Promise<boolean[]>;
/**
* Schedules a command to submit the form containing this element (or this
* element if it is a FORM element). This command is a no-op if the element is
* not contained in a form.
* @return {!webdriver.promise.Promise} A promise that will be resolved when
* the form has been submitted.
*/
submit(): webdriver.promise.Promise<void>;
/**
* Schedules a command to clear the {@code value} of this element. This command
* has no effect if the underlying DOM element is neither a text INPUT element
* nor a TEXTAREA element.
* @return {!webdriver.promise.Promise} A promise that will be resolved when
* the element has been cleared.
*/
clear(): webdriver.promise.Promise<void>;
/**
* Schedules a command to test whether this element is currently displayed.
* @return {!webdriver.promise.Promise} A promise that will be resolved with
* whether this element is currently visible on the page.
*/
isDisplayed(): webdriver.promise.Promise<boolean[]>;
/**
* Schedules a command to retrieve the outer HTML of this element.
* @return {!webdriver.promise.Promise} A promise that will be resolved with
* the element's outer HTML.
*/
getOuterHtml(): webdriver.promise.Promise<string[]>;
/**
* @return {!webdriver.promise.Promise.<webdriver.WebElement.Id>} A promise
* that resolves to this element's JSON representation as defined by the
* WebDriver wire protocol.
* @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
*/
getId(): webdriver.promise.Promise<webdriver.IWebElementId[]>
/**
* Schedules a command to retrieve the inner HTML of this element.
* @return {!webdriver.promise.Promise} A promise that will be resolved with the
* element's inner HTML.
*/
getInnerHtml(): webdriver.promise.Promise<string[]>;
}
interface LocatorWithColumn extends webdriver.Locator {
column(index: number): webdriver.Locator;
column(name: string): webdriver.Locator;
}
interface RepeaterLocator extends LocatorWithColumn {
row(index: number): LocatorWithColumn;
}
interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy {
/**
* Add a locator to this instance of ProtractorBy. This locator can then be
* used with element(by.locatorName(args)).
*
* @view
* <button ng-click="doAddition()">Go!</button>
*
* @example
* // Add the custom locator.
* by.addLocator('buttonTextSimple',
* function(buttonText, opt_parentElement, opt_rootSelector) {
* // This function will be serialized as a string and will execute in the
* // browser. The first argument is the text for the button. The second
* // argument is the parent element, if any.
* var using = opt_parentElement,
* buttons = using.querySelectorAll('button');
*
* // Return an array of buttons with the text.
* return Array.prototype.filter.call(buttons, function(button) {
* return button.textContent === buttonText;
* });
* });
*
* // Use the custom locator.
* element(by.buttonTextSimple('Go!')).click();
*
* @alias by.addLocator(locatorName, functionOrScript)
* @param {string} name The name of the new locator.
* @param {Function|string} script A script to be run in the context of
* the browser. This script will be passed an array of arguments
* that contains any args passed into the locator followed by the
* element scoping the search and the css selector for the root angular
* element. It should return an array of elements.
*/
addLocator(name: string, script: string): void;
addLocator(name: string, script: Function): void;
/**
* Find an element by binding.
*
* @view
* <span>{{person.name}}</span>
* <span ng-bind="person.email"></span>
*
* @example
* var span1 = element(by.binding('person.name'));
* expect(span1.getText()).toBe('Foo');
*
* var span2 = element(by.binding('person.email'));
* expect(span2.getText()).toBe('foo@bar.com');
*
* @param {string} bindingDescriptor
* @return {{findElementsOverride: findElementsOverride, toString: Function|string}}
*/
binding(bindingDescriptor: string): webdriver.Locator;
/**
* Find an element by exact binding.
*
* @view
* <span>{{ person.name }}</span>
* <span ng-bind="person-email"></span>
* <span>{{person_phone|uppercase}}</span>
*
* @example
* expect(element(by.exactBinding('person.name')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person-email')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person')).isPresent()).toBe(false);
* expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true);
* expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true);
* expect(element(by.exactBinding('phone')).isPresent()).toBe(false);
*
* @param {string} bindingDescriptor
* @return {{findElementsOverride: findElementsOverride, toString: Function|string}}
*/
exactBinding(bindingDescriptor: string): webdriver.Locator;
/**
* Find an element by ng-model expression.
*
* @alias by.model(modelName)
* @view
* <input constructor="text" ng-model="person.name"/>
*
* @example
* var input = element(by.model('person.name'));
* input.sendKeys('123');
* expect(input.getAttribute('value')).toBe('Foo123');
*
* @param {string} model ng-model expression.
*/
model(model: string): webdriver.Locator;
/**
* Find a button by text.
*
* @view
* <button>Save</button>
*
* @example
* element(by.buttonText('Save'));
*
* @param {string} searchText
* @return {{findElementsOverride: findElementsOverride, toString: Function|string}}
*/
buttonText(searchText: string): webdriver.Locator;
/**
* Find a button by partial text.
*
* @view
* <button>Save my file</button>
*
* @example
* element(by.partialButtonText('Save'));
*
* @param {string} searchText
* @return {{findElementsOverride: findElementsOverride, toString: Function|string}}
*/
partialButtonText(searchText: string): webdriver.Locator;
/**
* Find elements inside an ng-repeat.
*
* @view
* <div ng-repeat="cat in pets">
* <span>{{cat.name}}</span>
* <span>{{cat.age}}</span>
* </div>
*
* <div class="book-img" ng-repeat-start="book in library">
* <span>{{$index}}</span>
* </div>
* <div class="book-info" ng-repeat-end>
* <h4>{{book.name}}</h4>
* <p>{{book.blurb}}</p>
* </div>
*
* @example
* // Returns the DIV for the second cat.
* var secondCat = element(by.repeater('cat in pets').row(1));
*
* // Returns the SPAN for the first cat's name.
* var firstCatName = element(by.repeater('cat in pets').
* row(0).column('{{cat.name}}'));
*
* // Returns a promise that resolves to an array of WebElements from a column
* var ages = element.all(
* by.repeater('cat in pets').column('{{cat.age}}'));
*
* // Returns a promise that resolves to an array of WebElements containing
* // all top level elements repeated by the repeater. For 2 pets rows resolves
* // to an array of 2 elements.
* var rows = element.all(by.repeater('cat in pets'));
*
* // Returns a promise that resolves to an array of WebElements containing all
* // the elements with a binding to the book's name.
* var divs = element.all(by.repeater('book in library').column('book.name'));
*
* // Returns a promise that resolves to an array of WebElements containing
* // the DIVs for the second book.
* var bookInfo = element.all(by.repeater('book in library').row(1));
*
* // Returns the H4 for the first book's name.
* var firstBookName = element(by.repeater('book in library').
* row(0).column('{{book.name}}'));
*
* // Returns a promise that resolves to an array of WebElements containing
* // all top level elements repeated by the repeater. For 2 books divs
* // resolves to an array of 4 elements.
* var divs = element.all(by.repeater('book in library'));
*/
repeater(repeatDescriptor: string): RepeaterLocator;
/**
* Find elements by CSS which contain a certain string.
*
* @view
* <ul>
* <li class="pet">Dog</li>
* <li class="pet">Cat</li>
* </ul>
*
* @example
* // Returns the DIV for the dog, but not cat.
* var dog = element(by.cssContainingText('.pet', 'Dog'));
*/
cssContainingText(cssSelector: string, searchText: string): webdriver.Locator;
/**
* Find an element by ng-options expression.
*
* @alias by.options(optionsDescriptor)
* @view
* <select ng-model="color" ng-options="c for c in colors">
* <option value="0" selected="selected">red</option>
* <option value="1">green</option>
* </select>
*
* @example
* var allOptions = element.all(by.options('c for c in colors'));
* expect(allOptions.count()).toEqual(2);
* var firstOption = allOptions.first();
* expect(firstOption.getText()).toEqual('red');
*
* @param {string} optionsDescriptor ng-options expression.
*/
options(optionsDescriptor: string): webdriver.Locator;
}
var By: IProtractorLocatorStrategy;
interface Protractor extends webdriver.WebDriver {
/**
* The wrapped webdriver instance. Use this to interact with pages that do
* not contain Angular (such as a log-in screen).
*
* @type {webdriver.WebDriver}
*/
driver: webdriver.WebDriver;
/**
* Helper function for finding elements.
*
* @constructor {function(webdriver.Locator): ElementFinder}
*/
element(locator: webdriver.Locator): ElementFinder;
/**
* Shorthand function for finding elements by css.
*
* @constructor {function(string): ElementFinder}
*/
$(selector: string): ElementFinder;
/**
* Shorthand function for finding arrays of elements by css.
*
* @constructor {function(string): ElementArrayFinder}
*/
$$(selector: string): ElementArrayFinder;
/**
* All get methods will be resolved against this base URL. Relative URLs are =
* resolved the way anchor tags resolve.
*
* @type {string}
*/
baseUrl: string;
/**
* The css selector for an element on which to find Angular. This is usually
* 'body' but if your ng-app is on a subsection of the page it may be
* a subelement.
*
* @type {string}
*/
rootEl: string;
/**
* If true, Protractor will not attempt to synchronize with the page before
* performing actions. This can be harmful because Protractor will not wait
* until $timeouts and $http calls have been processed, which can cause
* tests to become flaky. This should be used only when necessary, such as
* when a page continuously polls an API using $timeout.
*
* @type {boolean}
*/
ignoreSynchronization: boolean;
/**
* Timeout in milliseconds to wait for pages to load when calling `get`.
*
* @type {number}
*/
getPageTimeout: number;
/**
* An object that holds custom test parameters.
*
* @type {Object}
*/
params: any;
/**
* The reset URL to use between page loads.
*
* @type {string}
*/
resetUrl: string;
/**
* Instruct webdriver to wait until Angular has finished rendering and has
* no outstanding $http calls before continuing.
*
* @return {!webdriver.promise.Promise} A promise that will resolve to the
* scripts return value.
*/
waitForAngular(): webdriver.promise.Promise<void>;
/**
* Add a module to load before Angular whenever Protractor.get is called.
* Modules will be registered after existing modules already on the page,
* so any module registered here will override preexisting modules with the same
* name.
*
* @example
* browser.addMockModule('modName', function() {
* angular.module('modName', []).value('foo', 'bar');
* });
*
* @param {!string} name The name of the module to load or override.
* @param {!string|Function} script The JavaScript to load the module.
* @param {...*} varArgs Any additional arguments will be provided to
* the script and may be referenced using the `arguments` object.
*/
addMockModule(name: string, script: string, ...varArgs: any[]): void;
addMockModule(name: string, script: Function, ...varArgs: any[]): void;
/**
* Clear the list of registered mock modules.
*/
clearMockModules(): void;
/**
* Remove a registered mock module.
*
* @example
* browser.removeMockModule('modName');
*
* @param {!string} name The name of the module to remove.
*/
removeMockModule(name: string): void;
/**
* @see webdriver.WebDriver.get
*
* Navigate to the given destination and loads mock modules before
* Angular. Assumes that the page being loaded uses Angular.
* If you need to access a page which does not have Angular on load, use
* the wrapped webdriver directly.
*
* @param {string} destination Destination URL.
* @param {number=} opt_timeout Number of milliseconds to wait for Angular to
* start.
*/
get(destination: string, opt_timeout?: number): webdriver.promise.Promise<void>;
/**
* See webdriver.WebDriver.refresh
*
* Makes a full reload of the current page and loads mock modules before
* Angular. Assumes that the page being loaded uses Angular.
* If you need to access a page which does not have Angular on load, use
* the wrapped webdriver directly.
*
* @param {number=} opt_timeout Number of seconds to wait for Angular to start.
*/
refresh(opt_timeout?: number): webdriver.promise.Promise<void>;
/**
* Browse to another page using in-page navigation.
*
* @param {string} url In page URL using the same syntax as $location.url()
* @returns {!webdriver.promise.Promise} A promise that will resolve once
* page has been changed.
*/
setLocation(url: string): webdriver.promise.Promise<void>;
/**
* Returns the current absolute url from AngularJS.
*/
getLocationAbsUrl(): webdriver.promise.Promise<string>;
/**
* Pauses the test and injects some helper functions into the browser, so that
* debugging may be done in the browser console.
*
* This should be used under node in debug mode, i.e. with
* protractor debug <configuration.js>
*
* @example
* While in the debugger, commands can be scheduled through webdriver by
* entering the repl:
* debug> repl
* Press Ctrl + C to leave rdebug repl
* > ptor.findElement(protractor.By.input('user').sendKeys('Laura'));
* > ptor.debugger();
* debug> c
*
* This will run the sendKeys command as the next task, then re-enter the
* debugger.
*/
debugger(): void;
/**
* Beta (unstable) pause function for debugging webdriver tests. Use
* browser.pause() in your test to enter the protractor debugger from that
* point in the control flow.
* Does not require changes to the command line (no need to add 'debug').
*
* @example
* element(by.id('foo')).click();
* browser.pause();
* // Execution will stop before the next click action.
* element(by.id('bar')).click();
*
* @param {number=} opt_debugPort Optional port to use for the debugging process
*/
pause(opt_debugPort?: number): void;
}
// Interface for the global browser object.
interface IBrowser extends Protractor {
/**
* Fork another instance of protractor for use in interactive tests.
*
* @param {boolean} opt_useSameUrl Whether to navigate to current url on creation
* @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation
* @return {Protractor} a protractor instance.
*/
forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor;
}
/**
* Create a new instance of Protractor by wrapping a webdriver instance.
*
* @param {webdriver.WebDriver} webdriver The configured webdriver instance.
* @param {string=} opt_baseUrl A URL to prepend to relative gets.
* @return {Protractor}
*/
function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor;
}
interface cssSelectorHelper {
(cssLocator: string): protractor.ElementFinder;
}
interface cssArraySelectorHelper {
(cssLocator: string): protractor.ElementArrayFinder;
}
declare var browser: protractor.IBrowser;
declare var by: protractor.IProtractorLocatorStrategy;
declare var By: protractor.IProtractorLocatorStrategy;
declare var element: protractor.Element;
declare var $: cssSelectorHelper;
declare var $$: cssArraySelectorHelper;
declare module 'protractor' {
export = protractor;
}
|
RathaR/protractor-page-object
|
src/typings/angular-protractor/angular-protractor.d.ts
|
TypeScript
|
mit
| 69,732
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
using System.Collections.Immutable;
using System.Linq;
using System.Text.RegularExpressions;
public class MarkdownNpTableBlockRule : IMarkdownRule
{
public virtual string Name => "NpTable";
public virtual Regex NpTable => Regexes.Block.Tables.NpTable;
public virtual IMarkdownToken TryMatch(IMarkdownParser parser, IMarkdownParsingContext context)
{
var match = NpTable.Match(context.CurrentMarkdown);
if (match.Length == 0)
{
return null;
}
var header = match.Groups[1].Value.ReplaceRegex(Regexes.Lexers.UselessTableHeader, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter);
var align = ParseAligns(match.Groups[2].Value.ReplaceRegex(Regexes.Lexers.UselessTableAlign, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter));
if (header.Length > align.Length)
{
return null;
}
var sourceInfo = context.Consume(match.Length);
var rows = (from row in match.Groups[3].Value.ReplaceRegex(Regexes.Lexers.EndWithNewLine, string.Empty).Split('\n')
select row.ReplaceRegex(Regexes.Lexers.UselessTableRow, string.Empty)).ToList();
var cells = new string[rows.Count][];
for (int i = 0; i < rows.Count; i++)
{
var columns = rows[i].SplitRegex(Regexes.Lexers.TableSplitter);
if (columns.Length == header.Length)
{
cells[i] = columns;
}
else if (columns.Length < header.Length)
{
cells[i] = new string[header.Length];
for (int j = 0; j < columns.Length; j++)
{
cells[i][j] = columns[j];
}
for (int j = columns.Length; j < cells[i].Length; j++)
{
cells[i][j] = string.Empty;
}
}
else // columns.Length > header.Length
{
cells[i] = new string[header.Length];
for (int j = 0; j < header.Length; j++)
{
cells[i][j] = columns[j];
}
}
}
return new TwoPhaseBlockToken(
this,
parser.Context,
sourceInfo,
(p, t) =>
new MarkdownTableBlockToken(
t.Rule,
t.Context,
(from text in header
let si = t.SourceInfo.Copy(text)
select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray(),
align.ToImmutableArray(),
cells.Select(
(row, index) =>
(from col in row
let si = t.SourceInfo.Copy(col, index + 2)
select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray()
).ToImmutableArray(),
t.SourceInfo));
}
protected virtual Align[] ParseAligns(string[] aligns)
{
var result = new Align[aligns.Length];
for (int i = 0; i < aligns.Length; i++)
{
if (Regexes.Lexers.TableAlignRight.IsMatch(aligns[i]))
{
result[i] = Align.Right;
}
else if (Regexes.Lexers.TableAlignCenter.IsMatch(aligns[i]))
{
result[i] = Align.Center;
}
else if (Regexes.Lexers.TableAlignLeft.IsMatch(aligns[i]))
{
result[i] = Align.Left;
}
else
{
result[i] = Align.NotSpec;
}
}
return result;
}
}
}
|
LordZoltan/docfx
|
src/Microsoft.DocAsCode.MarkdownLite/Tables/MarkdownNpTableBlockRule.cs
|
C#
|
mit
| 4,398
|
//{block name="backend/connect/store/import/local_products"}
Ext.define('Shopware.apps.Connect.store.import.LocalProducts', {
extend : 'Ext.data.Store',
autoLoad: false,
pageSize: 10,
fields: [
{ name: 'Article_id', type: 'integer' },
{ name: 'Detail_number', type: 'string' },
{ name: 'Article_name', type: 'string' },
{ name: 'Supplier_name', type: 'string' },
{ name: 'Article_active', type: 'boolean' },
{ name: 'Detail_purchasePrice', type: 'float' },
{ name: 'Price_price', type: 'float' },
{ name: 'Tax_name', type: 'string' },
{ name: 'Attribute_connectMappedCategory', type: 'int' }
],
proxy : {
type : 'ajax',
api : {
read : '{url controller=Import action=loadBothArticleTypes}'
},
reader : {
type : 'json',
root: 'data',
totalProperty:'total'
}
}
});
//{/block}
|
shopware/SwagConnect
|
Views/backend/connect/store/import/local_products.js
|
JavaScript
|
mit
| 969
|
import Microcosm from 'microcosm'
describe('History node children', function() {
const action = n => n
it('can determine children', function() {
const repo = new Microcosm()
const a = repo.append(action)
const b = repo.append(action)
repo.checkout(a)
const c = repo.append(action)
expect(a.children.map(n => n.id)).toEqual([b.id, c.id])
})
it('does not lose children when checking out nodes on the left', function() {
const repo = new Microcosm()
repo.append(action)
const b = repo.append(action)
const c = repo.append(action)
repo.checkout(b)
const d = repo.append(action)
expect(b.children).toEqual([c, d])
})
it('does not lose children when checking out nodes on the right', function() {
const repo = new Microcosm()
repo.append(action)
const b = repo.append(action)
const c = repo.append(action)
repo.checkout(b)
const d = repo.append(action)
repo.checkout(c)
expect(b.children).toEqual([c, d])
})
})
|
vigetlabs/microcosm
|
test/unit/history/children.test.js
|
JavaScript
|
mit
| 1,022
|
\n
static inline void mapping_set_error(struct address_space *mapping, int error)
static inline void mapping_set_unevictable(struct address_space *mapping)
static inline void mapping_clear_unevictable(struct address_space *mapping)
static inline int mapping_unevictable(struct address_space *mapping)
static inline void mapping_set_exiting(struct address_space *mapping)
static inline int mapping_exiting(struct address_space *mapping)
static inline void mapping_set_no_writeback_tags(struct address_space *mapping)
static inline int mapping_use_writeback_tags(struct address_space *mapping)
static inline gfp_t mapping_gfp_mask(struct address_space * mapping)
static inline gfp_t mapping_gfp_constraint(struct address_space *mapping, gfp_t gfp_mask)
static inline void mapping_set_gfp_mask(struct address_space *m, gfp_t mask)
static inline int page_cache_get_speculative(struct page *page)
static inline int page_cache_add_speculative(struct page *page, int count)
extern struct page *__page_cache_alloc(gfp_t gfp)
; static inline struct page *__page_cache_alloc(gfp_t gfp)
static inline struct page *page_cache_alloc(struct address_space *x)
static inline gfp_t readahead_gfp_mask(struct address_space *x)
static inline struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
static inline struct page *find_get_page_flags(struct address_space *mapping, pgoff_t offset, int fgp_flags)
static inline struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
static inline struct page *find_or_create_page(struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask)
static inline struct page *grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
; struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
; unsigned find_get_entries(struct address_space *mapping, pgoff_t start, unsigned int nr_entries, struct page **entries, pgoff_t *indices)
; unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start, pgoff_t end, unsigned int nr_pages, struct page **pages)
; static inline unsigned find_get_pages(struct address_space *mapping, pgoff_t *start, unsigned int nr_pages, struct page **pages)
struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
; struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
; unsigned find_get_entries(struct address_space *mapping, pgoff_t start, unsigned int nr_entries, struct page **entries, pgoff_t *indices)
; unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start, pgoff_t end, unsigned int nr_pages, struct page **pages)
; static inline unsigned find_get_pages(struct address_space *mapping, pgoff_t *start, unsigned int nr_pages, struct page **pages)
return find_get_pages_range(mapping, start, (pgoff_t)
-1, nr_pages, pages)
; } unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t start, unsigned int nr_pages, struct page **pages)
; unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index, pgoff_t end, xa_mark_t tag, unsigned int nr_pages, struct page **pages)
; static inline unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index, xa_mark_t tag, unsigned int nr_pages, struct page **pages)
static inline struct page *grab_cache_page(struct address_space *mapping, pgoff_t index)
static inline struct page *read_mapping_page(struct address_space *mapping, pgoff_t index, void *data)
static inline pgoff_t page_to_index(struct page *page)
static inline pgoff_t page_to_pgoff(struct page *page)
static inline loff_t page_offset(struct page *page)
static inline loff_t page_file_offset(struct page *page)
static inline pgoff_t linear_page_index(struct vm_area_struct *vma, unsigned long address)
static inline int trylock_page(struct page *page)
static inline void lock_page(struct page *page)
static inline int lock_page_killable(struct page *page)
static inline int lock_page_or_retry(struct page *page, struct mm_struct *mm, unsigned int flags)
static inline void wait_on_page_locked(struct page *page)
static inline int wait_on_page_locked_killable(struct page *page)
static inline void wait_on_page_writeback(struct page *page)
static inline int fault_in_pages_writeable(char __user *uaddr, int size)
static inline int fault_in_pages_readable(const char __user *uaddr, int size)
static inline int add_to_page_cache(struct page *page, struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask)
static inline unsigned long dir_pages(struct inode *inode)
\n
30 struct address_space *mapping
14 struct page *page
9 pgoff_t offset
7 unsigned int nr_pages
7 struct page **pages
4 pgoff_t *start
3 pgoff_t start
3 pgoff_t index
3 pgoff_t end
3 gfp_t gfp_mask
2 xa_mark_t tag
2 unsigned int nr_entries
2 struct page **entries
2 struct address_space *x
2 pgoff_t *indices
2 pgoff_t *index
2 int size
2 gfp_t gfp
1 void *data
1 unsigned long address
1 unsigned int flags
1 struct vm_area_struct *vma
1 struct mm_struct *mm
1 struct inode *inode
1 struct address_space * mapping
1 struct address_space *m
1 start
1 pgoff_t
1 mapping
1 int fgp_flags
1 int error
1 int count
1 gfp_t mask
1 const char __user *uaddr
1 char __user *uaddr
|
liker12134/my-kernel-dev-environment
|
code-readpad/kernel-schema/include_linux_pagemap.h.h
|
C
|
mit
| 5,473
|
package org.simpleflatmapper.util;
public interface CheckedConsumer<T> {
void accept(T t) throws Exception;
//IFJAVA8_START
default Consumer<T> toConsumer() {
return t -> {
try {
accept(t);
} catch (Exception e) {
ErrorHelper.rethrow(e);
}
};
}
static <T> Consumer<T> toConsumer(CheckedConsumer<T> consumer) {
return consumer.toConsumer();
}
//IFJAVA8_END
}
|
arnaudroger/SimpleFlatMapper
|
sfm-util/src/main/java/org/simpleflatmapper/util/CheckedConsumer.java
|
Java
|
mit
| 483
|
__author__ = 'shinyorke_mbp'
|
Shinichi-Nakagawa/xp2015_baseball_tools
|
service/__init__.py
|
Python
|
mit
| 29
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ErrlockConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ErrlockConsole")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("0fb18e97-7c20-4964-b738-963309d6ff72")]
[assembly: AssemblyVersion("1.1.163.15177")]
[assembly: AssemblyFileVersion("1.1.163.15177")]
|
segrived/Errlock
|
Errlock.Console/Properties/AssemblyInfo.cs
|
C#
|
mit
| 561
|
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
import {Parser} from "./state"
import {types as tt} from "./tokentype"
import {lineBreak} from "./whitespace"
export class TokContext {
constructor(token, isExpr, preserveSpace, override) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override
}
}
export const types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, p => p.readTmplToken()),
new TokContext("function", true);
}
const pp = Parser.prototype;
pp.initialContext = function() {
return [types.b_stat]
};
pp.braceIsBlock = function(prevType) {
if (prevType === tt.colon) {
let parent = this.curContext();
if (parent === types.b_stat || parent === types.b_expr)
return !parent.isExpr
}
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR)
return true;
if (prevType == tt.braceL)
return this.curContext() === types.b_stat;
return !this.exprAllowed
};
pp.updateContext = function(prevType) {
let update, type = this.type;
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false;
else if (update = type.updateContext)
update.call(this, prevType);
else
this.exprAllowed = type.beforeExpr
};
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true;
return
}
let out = this.context.pop();
if (out === types.b_stat && this.curContext() === types.f_expr) {
this.context.pop();
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
};
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
this.exprAllowed = true
};
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl);
this.exprAllowed = true
};
tt.parenL.updateContext = function(prevType) {
let statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
this.context.push(statementParens ? types.p_stat : types.p_expr);
this.exprAllowed = true
};
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
};
tt._function.updateContext = function() {
if (this.curContext() !== types.b_stat)
this.context.push(types.f_expr);
this.exprAllowed = false
};
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop();
else
this.context.push(types.q_tmpl);
this.exprAllowed = false
};
|
Berkmann18/Essencejs
|
1.0/node_modules/eslint/node_modules/espree/node_modules/acorn-jsx/node_modules/acorn/src/tokencontext.js
|
JavaScript
|
mit
| 3,109
|
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
# not sure about line 7
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^dropzone-drag-drop/$', include('dragdrop.urls', namespace="dragdrop", app_name="dragdrop")),
url(r'^index/$', 'dragdrop.views.GetUserImages'),
url(r'^$', 'signups.views.home', name='home'),
url(r'^register/$', 'drinker.views.DrinkerRegistration'),
url(r'^login/$', 'drinker.views.LoginRequest'),
url(r'^logout/$', 'drinker.views.LogOutRequest'),
url(r'^index/filter/$', 'filter.views.changeBright'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# not sure if I need an actual url wrapper in this code.
# url(r'^admin/varnish/', include('varnishapp.urls')),
)
if settings.DEBUG:
# urlpatterns add STATIC_URL and serves the STATIC_ROOT file
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
|
vdmann/cse-360-image-hosting-website
|
src/mvp_landing/urls.py
|
Python
|
mit
| 1,288
|
title: Background Images in React Native
---
A [common question][1] amongst React Native developers is how to put a background image on a view.
On the web, it’s a piece of cake:
```
<div style={{ backgroundImage: 'url(/my-image.png)' }}>...</div>
```
In React Native, there’s no `background-image` tag; instead, the `<Image>` component does the heavy lifting.
## Layouts
<a href="https://s15.postimg.org/tw2qkvmcb/400px.png" target="_blank" class="right-image">
<img src="https://s15.postimg.org/tw2qkvmcb/400px.png" />
<small>Our sample image</small>
</a>
There’s [5 layouts][2] to be aware of that an image can take.
- `center` - Centers the image, without resizing it.
- `repeat` - Repeats the image, without resizing it.
- `stretch` - Stretches the image to fit its bounds, without preserving the image's aspect ratio.
- `contain` - Resizes the image to fit its bounds, while also preserving its aspect ratio.
- `cover` - Resizes the image so its shorter side fits its bounds, while also preserving its aspect ratio. In practice, this means that the longer side while overlap the borders of its bounds.
Here's examples of each in practice:
<div class="flex-table">
<a href="assets/400px/center.png" target="_blank">
<img src="assets/400px/center.png" /> Center
</a>
<a href="assets/400px/repeat.png" target="_blank">
<img src="assets/400px/repeat.png" /> Repeat
</a>
<a href="assets/400px/stretch.png" target="_blank">
<img src="assets/400px/stretch.png" /> Stretch
</a>
<a href="assets/400px/contain.png" target="_blank">
<img src="assets/400px/contain.png" /> Contain
</a>
<a href="assets/400px/cover.png" target="_blank">
<img src="assets/400px/cover.png" /> Cover
</a>
</div>
## Referencing images
If you haven't used `<Image />` before, a quick note on assets. There's two ways of serving images, over the network and locally. Using local images will be faster but result in a larger app binary, and can't be updated on the fly.
If you're using remote images, keep in mind two things:
1 - Use `https` links instead of `http`. [Apple will block non-`https` links][3], and in my experience this error will happen silently.
2 - For larger images, explore the caching policies [detailed here][4] to reduce network requests for your users.
If instead you decide to serve images locally, keep in mind images are served relative from your app root folder. I usually put my local images into an assets folder with other media, so from `index.ios.js` I can call them with:
`require('./assets/my-image.png')`
Finally, if you add a new image to your app and come across an error like this:
<img src="assets/error.png" title="Unexpected character ?" />
It probably means you need to restart your packager, so it can pick up the imported image.
## Examples
Let’s show an example where we fetch an image from a public URL and position it absolutely:
<div class="flex-table">
<script src="https://gist.github.com/thekevinscott/0381ad0ff8e2fe29c47f0e1ab71d5b74.js"></script>
<img src="assets/examples/BasicImage.png" style="border: 1px solid #ddd;" />
</div>
Easy as that! The key is the use of `flex: 1`, which will cause the `<Image />` component to fill its container. You can read [more about Flexbox here][5].
You can play around with `resizeMode` to see the different layout options.
## With Text
Usually a background image sits behind something else. There’s two ways to achieve that: using the `<Image />` as the view layer itself, or wrapping it in another `<View />`.
Here’s an example using the `<Image />` as the wrapper component:
<div class="flex-table">
<script src="https://gist.github.com/thekevinscott/0b2ba3dbd3e3c0b2efd9fd91a08a7696.js"></script>
<img src="assets/examples/ImageWithText.png" style="border: 1px solid #ddd;" />
</div>
And here’s an example wrapping the `<Image />` in a container `<View />`:
<div class="flex-table">
<script src="https://gist.github.com/thekevinscott/114fc100d47f68b5bd805c9fd32c35c0.js"></script>
<img src="assets/examples/AbsoluteImage.png" style="border: 1px solid #ddd;" />
</div>
I slightly prefer the latter approach, as I think it's more flexible if you need to make further adjustments or include other elements, but either approach works.
[1]: http://stackoverflow.com/questions/29322973/whats-the-best-way-to-add-a-full-screen-background-image-in-react-native
[2]: https://facebook.github.io/react-native/docs/image.html#resizemode
[3]: https://developer.apple.com/news/?id=12212016b
[4]: https://facebook.github.io/react-native/docs/images.html#cache-control-ios-only
[5]: https://facebook.github.io/react-native/docs/flexbox.html
|
thekevinscott/Hero-test
|
source/background-images/index.md
|
Markdown
|
mit
| 4,682
|
import {eventMixin} from "./event"
export class MarkedRange {
constructor(from, to, options) {
this.options = options || {}
this.from = from
this.to = to
}
clear() {
this.signal("removed", this.from)
this.from = this.to = null
}
}
eventMixin(MarkedRange)
class RangeSorter {
constructor() {
this.sorted = []
}
find(at) {
let min = 0, max = this.sorted.length
for (;;) {
if (max < min + 10) {
for (let i = min; i < max; i++)
if (this.sorted[i].at.cmp(at) >= 0) return i
return max
}
let mid = (min + max) >> 1
if (this.sorted[mid].at.cmp(at) > 0) max = mid
else min = mid
}
}
insert(obj) {
this.sorted.splice(this.find(obj.at), 0, obj)
}
remove(at, range) {
let pos = this.find(at)
for (let dist = 0;; dist++) {
let leftPos = pos - dist - 1, rightPos = pos + dist
if (leftPos >= 0 && this.sorted[leftPos].range == range) {
this.sorted.splice(leftPos, 1)
return
} else if (rightPos < this.sorted.length && this.sorted[rightPos].range == range) {
this.sorted.splice(rightPos, 1)
return
}
}
}
resort() {
for (let i = 0; i < this.sorted.length; i++) {
let cur = this.sorted[i]
let at = cur.at = cur.type == "open" ? cur.range.from : cur.range.to
let pos = i
while (pos > 0 && this.sorted[pos - 1].at.cmp(at) > 0) {
this.sorted[pos] = this.sorted[pos - 1]
this.sorted[--pos] = cur
}
}
}
}
export class RangeStore {
constructor(pm) {
this.pm = pm
this.ranges = []
this.sorted = new RangeSorter
}
addRange(range) {
this.ranges.push(range)
this.sorted.insert({type: "open", at: range.from, range: range})
this.sorted.insert({type: "close", at: range.to, range: range})
this.pm.markRangeDirty(range)
}
removeRange(range) {
let found = this.ranges.indexOf(range)
if (found > -1) {
this.ranges.splice(found, 1)
this.sorted.remove(range.from, range)
this.sorted.remove(range.to, range)
this.pm.markRangeDirty(range)
range.clear()
}
}
transform(mapping) {
for (let i = 0; i < this.ranges.length; i++) {
let range = this.ranges[i]
range.from = mapping.map(range.from, range.options.inclusiveLeft ? -1 : 1).pos
range.to = mapping.map(range.to, range.options.inclusiveRight ? 1 : -1).pos
let diff = range.from.cmp(range.to)
if (range.options.clearWhenEmpty !== false && diff >= 0) {
this.removeRange(range)
i--
} else if (diff > 0) {
range.to = range.from
}
}
this.sorted.resort()
}
activeRangeTracker() {
return new RangeTracker(this.sorted.sorted)
}
}
class RangeTracker {
constructor(sorted) {
this.sorted = sorted
this.pos = 0
this.current = []
}
advanceTo(pos) {
let next
while (this.pos < this.sorted.length && (next = this.sorted[this.pos]).at.cmp(pos) <= 0) {
let className = next.range.options.className
if (!className) continue
if (next.type == "open")
this.current.push(className)
else
this.current.splice(this.current.indexOf(className), 1)
this.pos++
}
}
nextChangeBefore(pos) {
for (;;) {
if (this.pos == this.sorted.length) return null
let next = this.sorted[this.pos]
if (!next.range.options.className)
this.pos++
else if (next.at.cmp(pos) >= 0)
return null
else
return next.at.offset
}
}
}
|
tecnogram888/prosemirror
|
src/edit/range.js
|
JavaScript
|
mit
| 3,568
|
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Http\Request;
use Remp\Journal\JournalException;
class JournalProxyController extends Controller
{
private $journalClient;
public function __construct(Client $journalClient)
{
$this->journalClient = $journalClient;
}
public function pageviewsProgressCount(Request $request)
{
return $this->proxyCall($request, '/journal/pageviews/actions/progress/count');
}
public function pageviewsUniqueBrowsersCount(Request $request)
{
return $this->proxyCall($request, '/journal/pageviews/actions/load/unique/browsers');
}
public function commercePurchaseCount(Request $request)
{
return $this->proxyCall($request, '/journal/commerce/steps/purchase/count');
}
private function proxyCall(Request $request, string $journalUri)
{
$requestJson = $request->json()->all();
try {
$segmentsResponse = $this->journalClient->post($journalUri, [
'json' => $requestJson
]);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal $journalUri endpoint: {$e->getMessage()}");
}
return response()->json(json_decode($segmentsResponse->getBody()));
}
}
|
remp2020/remp
|
Beam/app/Http/Controllers/JournalProxyController.php
|
PHP
|
mit
| 1,374
|
---
layout: post
date: '2016-03-27'
title: "SWEET 16 Short Lace One Shoulder Prom Dress In Pink/White"
category: SWEET 16
tags: [SWEET 16]
---
### SWEET 16 Short Lace One Shoulder Prom Dress In Pink/White
Just **$426.99**
###
<a href="https://www.eudances.com/en/sweet-16/2488-short-lace-one-shoulder-prom-dress-in-pink-white.html"><img src="//www.eudances.com/6737-thickbox_default/short-lace-one-shoulder-prom-dress-in-pink-white.jpg" alt="Short Lace One Shoulder Prom Dress In Pink/White" style="width:100%;" /></a>
<!-- break --><a href="https://www.eudances.com/en/sweet-16/2488-short-lace-one-shoulder-prom-dress-in-pink-white.html"><img src="//www.eudances.com/6738-thickbox_default/short-lace-one-shoulder-prom-dress-in-pink-white.jpg" alt="Short Lace One Shoulder Prom Dress In Pink/White" style="width:100%;" /></a>
<a href="https://www.eudances.com/en/sweet-16/2488-short-lace-one-shoulder-prom-dress-in-pink-white.html"><img src="//www.eudances.com/6736-thickbox_default/short-lace-one-shoulder-prom-dress-in-pink-white.jpg" alt="Short Lace One Shoulder Prom Dress In Pink/White" style="width:100%;" /></a>
Buy it: [https://www.eudances.com/en/sweet-16/2488-short-lace-one-shoulder-prom-dress-in-pink-white.html](https://www.eudances.com/en/sweet-16/2488-short-lace-one-shoulder-prom-dress-in-pink-white.html)
|
lastgown/lastgown.github.io
|
_posts/2016-03-27-SWEET-16-Short-Lace-One-Shoulder-Prom-Dress-In-PinkWhite.md
|
Markdown
|
mit
| 1,332
|
<?php
namespace Inferno\Foundation\Repositories;
class AbstractRepository implements AbstractInterface
{
public function getById($id)
{
return $this->model->where('id', $id)->first();
}
public function getAll($limit = 10)
{
return $this->model->select()
->orderBy('created_at', 'desc')
->paginate($limit);
}
public function getAllNoLimit()
{
return $this->model->select()
->orderBy('created_at', 'desc')
->get();
}
public function update(array $attributes, $id, $getDataBack = false)
{
$update = $this->model->where('id', $id)->update($attributes);
if ($getDataBack) {
$update = $this->getById($id);
}
return $update;
}
public function remove($id)
{
return $this->model->where('id', $id)->delete();
}
public function create(array $attributes)
{
$data = $this->model->create($attributes);
return $data;
}
}
|
amitavdevzone/foundation
|
src/Repositories/AbstractRepository.php
|
PHP
|
mit
| 1,029
|
<!DOCTYPE html>
<html>
<head>
<!-- Origin Trial Token, feature = WebVR (For Chrome M59+), origin = https://aframe.io, expires = 2017-07-28 -->
<meta http-equiv="origin-trial" data-feature="WebVR (For Chrome M59+)" data-expires="2017-07-28" content="ArFv1ZeTwzkhjNE00uAE+XtiQB41fwqG/TqlFMLrepd9sforQSvQE/tgfIbUMYNuNre4QR1k4/z8xp2mV3dbhwwAAABeeyJvcmlnaW4iOiJodHRwczovL2FmcmFtZS5pbzo0NDMiLCJmZWF0dXJlIjoiV2ViVlIxLjEiLCJleHBpcnkiOjE1MDEyMTcwMDIsImlzU3ViZG9tYWluIjp0cnVlfQ==">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=examples/">
</head>
<body></body>
</html>
|
KerPerr/website
|
node_modules/aframe/gh-pages/index.html
|
HTML
|
mit
| 600
|
# The set of languages for which implicit dependencies are needed:
SET(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
"/Users/darrentsung/Documents/Personal/Coding/funky-terrain-generator/src/main.cpp" "/Users/darrentsung/Documents/Personal/Coding/funky-terrain-generator/CMakeFiles/Untitled.dir/src/main.cpp.o"
)
SET(CMAKE_CXX_COMPILER_ID "Clang")
# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
"/Users/darrentsung/Documents/Personal/Coding/funky-terrain-generator/lib/glfw/src/CMakeFiles/glfw.dir/DependInfo.cmake"
)
# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
"/System/Library/Frameworks/GLUT.framework/Headers"
"lib/glfw/include"
"src"
)
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
|
DarrenTsung/ocean-breeze
|
CMakeFiles/Untitled.dir/DependInfo.cmake
|
CMake
|
mit
| 989
|
# General controller for the app
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user_session, :current_user, :admin?
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def require_user
logger.debug 'ApplicationController::require_user'
unless current_user
store_location
flash[:notice] = 'You must be logged in to access this page'
redirect_to new_user_session_url
return false
end
end
def require_no_user
logger.debug 'ApplicationController::require_no_user'
if current_user
store_location
flash[:notice] = 'You must be logged out to access this page'
return false
end
end
def require_admin
logger.debug 'ApplicationController::require_admin'
unless admin?
store_location
flash[:notice] = 'You must be an administrator to access this page'
redirect_to '/students'
return false
end
end
def store_location
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def admin?
return current_user.admin
end
# Send a text message
def txtmsg
end
end
|
CSC322-Grinnell/notifications
|
app/controllers/application_controller.rb
|
Ruby
|
mit
| 1,465
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('receive-for', 'Integration | Component | receive for', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });"
this.render(hbs`{{receive-for}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:"
this.render(hbs`
{{#receive-for}}
{{else}}
template block text
{{/receive-for}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
knownasilya/ember-receive
|
tests/integration/components/receive-for/component-test.js
|
JavaScript
|
mit
| 665
|
---
author: miky
comments: true
date: 2009-01-09 16:18:23+00:00
layout: post
slug: pagaria-por-estar-alli
title: Pagaría por estar allí
categories: day-by-day
---
Paseándome por el Maikelnai he descubierto el [post ](http://www.maikelnai.es/2008/10/24/conferencia-de-solvay-1927-la-mayor-aglomeracion-de-genios-de-la-historia/)y esta foto:

Pagaría por tomarme un café con muchos de ellos....de hecho el post original me resulta interesantísimo. Aun diría más, aunque me tomaran por idiota, aunque estuvieran realmente locos algunos de ellos, aunque se mearan en botellas de cerveza...pagaría por haber vivido en primera persona esa época de la evolución de la física :P
> (Hilera superior, de izquierda a derecha)
A. Piccard, E. Henriot, P. Ehrenfest, Ed. Herzen, Th. De Donder, E. Schrödinger, E. Verschaffelt, W. Pauli, W. Heisenberg, R.H. Fowler, L. Brillouin.
(Hilera intermedia, de izquierda a derecha)
P. Debye, M. Knudsen, W.L. Bragg, H.A. Kramers, P.A.M. Dirac, A.H. Compton, L. de Broglie, M. Born, N. Bohr.
(Hilera inferior, de izquierda a derecha)
I. Langmuir, M. Planck, Madame. Curie, H.A. Lorentz, A. Einstein, P. Langevin, Ch. E. Guye, C.T.R. Wilson, y O.W. Richardson.
|
figarocorso/figarocorso.github.io
|
_dosidiotas/2009-01-09-pagaria-por-estar-alli.markdown
|
Markdown
|
mit
| 1,299
|
// Invoke 'strict' JavaScript mode
'use strict';
var app = angular.module('dashboards', ['ngMaterial']);
// Create the 'Dashboards' controller
angular.module('dashboards').controller('DashboardsController', ['$scope','$http','$q','$mdDialog','$window','$timeout' ,'$routeParams', '$location', 'Authentication', 'Dashboards','Powers','Devices','SmartPlugs','ngDialog','$interval', 'roundProgressService',
function($scope,$http,$q,$mdDialog,$window,$timeout, $routeParams, $location, Authentication, Dashboards,Powers,Devices,SmartPlugs,ngDialog,$interval, roundProgressService) {
// Expose the Authentication service
$scope.authentication = Authentication;
var dashboardList ={};
dashboardList._id='';
dashboardList.creator ='';
dashboardList.devices='';
dashboardList.smartplugs='';
dashboardList.consumption='';
dashboardList.pid='';
dashboardList.created='';
$scope.dashboards= dashboardList;
$scope.search_date_range='';
///////////////////////////////////////////////
//device list and functions
$scope.switchdata = {
cb1: true,
cb4: true,
cb5: false
};
///////////////////////////////////////////////
///////////////////////////////////////////////////
//angular material table
$scope.data = {
selectedIndex: 0,
secondLocked: false,
secondLabel: "Item Two",
bottom: false
};
$scope.next = function() {
$scope.data.selectedIndex = Math.min($scope.data.selectedIndex + 1, 2) ;
};
$scope.previous = function() {
$scope.data.selectedIndex = Math.max($scope.data.selectedIndex - 1, 0);
};
////////////////////////////////////////////////
//table 2 template start
//angular material alert box start
$scope.status = ' ';
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,//DialogController
templateUrl: 'dialog1.tmpl.html',
//scope:$scope,
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
//angular material alert box ends
$scope.isDeviceSelected =false;
//table 2 template ends
/////////////////////////////////////////////////////
var mainList =[{id:0,name:'Yesterday'},{id:1,name:'Today'},{id:2,name:'Current Month'},{id:3,name:'Last Month'},{id:4,name:'Overall'}];
$scope.filterOption = mainList[4].id;
$scope.mainListItems = mainList;
//setting main views on and off start
$scope.costOfOneKWh = parseFloat(2.50);
$scope.basic = true;
$scope.analytics =true;
$scope.analytics_name='Analytics';
$scope.todayGraph=true;
$scope.yesterdayGraph = true;
$scope.lastMonthGraph = true;
$scope.setAnalyticView = function(){
$scope.setStreamLineChartData();
if($scope.analytics==false){
$scope.analytics=true;
$scope.basic=false;
$scope.analytics_name='Basic';
console.log($scope.attrs);
console.log($scope.categories);
console.log($scope.dataset)
}else{
$scope.analytics=false;
$scope.basic=true;
$scope.analytics_name='Analytics';
}
};
$scope.getMonthGraph = function(){
//$scope.setThisMonthGraphData();
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerDayGraph(dateString);
if($scope.analytics==true){
$scope.analytics=false;
$scope.lastMonthGraph=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}else{
$scope.analytics=true;
$scope.lastMonthGraph=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}
};
$scope.getLastMonthGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerDayGraph(dateString);
if($scope.lastMonthGraph==true){
$scope.lastMonthGraph=false;
$scope.analytics=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}else{
$scope.lastMonthGraph=true;
$scope.analytics=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}
};
$scope.getTodayGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerHourGraph(dateString);
if($scope.todayGraph==true){
$scope.todayGraph=false;
$scope.yesterdayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}else{
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}
};
$scope.getYesterdayGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// date = date.toLocaleDateString();
// var dateString = date
//var dateString = yy+"-"+mm+"-"+dd;
// dateString = '2015-11-05'
// $scope.getPowerPerHourGraph(dateString);
if($scope.yesterdayGraph==true){
$scope.yesterdayGraph=false;
$scope.todayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}else{
$scope.yesterdayGraph=true;
$scope.todayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}
};
$scope.setGraphViews = function(){
// $scope.getMonthGraph();
// $scope.getLastMonthGraph();
// $scope.getTodayGraph();
// $scope.getYesterdayGraph();
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
date = date.toLocaleDateString();
var dateString = date
//var dateString = yy+"-"+mm+"-"+dd;
// dateString = '2015-11-05'
$scope.getPowerPerHourGraph(dateString);
$scope.getPowerPerDayGraph(dateString);
};
//setting main views on and off end
//set graph data holding variables start
//this month power
$scope.categories2=[];
$scope.attrs2={};
$scope.dataset2=[];
//this month cost
$scope.categories3=[];
$scope.attrs3={};
$scope.dataset3=[];
//last month power
$scope.categories4=[];
$scope.attrs4={};
$scope.dataset4=[];
//last month cost
$scope.categories5=[];
$scope.attrs5={};
$scope.dataset5=[];
//today power
$scope.categories6=[];
$scope.attrs6={};
$scope.dataset6=[];
//yesterday power
$scope.categories7=[];
$scope.attrs7={};
$scope.dataset7=[];
//today cost
$scope.categories8=[];
$scope.attrs8={};
$scope.dataset8=[];
//yesterday cost
$scope.categories9=[];
$scope.attrs9={};
$scope.dataset9=[];
//set graph data holding variables end
$scope.setGraphAttributes = function(){
//for this month graph
$scope.attrs2 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories2 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//for cost section
$scope.attrs3 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories3 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//last month cost and power section
$scope.attrs4 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories4 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//for cost section
$scope.attrs5 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories5 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//today and yesterday
$scope.attrs6 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories6 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
$scope.attrs8 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories8 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
//for yesterday
$scope.attrs7 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories7 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
$scope.attrs9 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories9 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
};
$scope.setGraphAttributes();
//calculation constants for power consumption cost end
$scope.init = function(){
$scope.getPatternForHourAll();
$scope.getDataOfCostofPastYears();
$scope.predictionOfCostNextYear();
$scope.setGraphViews();
};
// Create a new controller method for creating new Dashboards
$scope.create = function() {
// Use the form fields to create a new Dashboard $resource object
var Dashboard = new Dashboards({
pid: this.pid,
name: this.name,
consumption: this.consumption,
devices: this.devices,
smartplugs: this.smartplugs
});
// Use the Dashboard '$save' method to send an appropriate POST request
Dashboard.$save(function(response) {
// If an Dashboard was created successfully, redirect the user to the Dashboard's page
$location.path('dashboards/' + response._id);
console.log("Saved Dashboard");
console.log(response);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for retrieving a list of Dashboards
$scope.find = function() {
// Use the Dashboard 'query' method to send an appropriate GET request
var dashboards=[];
$scope.dashboards = Dashboards.query({}, function() {
var count=0;
angular.forEach($scope.dashboards, function(dashboard, key) {
var idevice = Devices.get({deviceId:dashboard.devices},function(){
dashboard.devices=idevice.name;
});
var ismartplug = SmartPlugs.get({smartplugId:dashboard.smartplugs},function(){
dashboard.smartplugs=ismartplug.name;
});
count++;
});//end of loop
dashboards = $scope.dashboards;
});//end of query
return dashboards;
};
// Create a new controller method for retrieving a single Dashboard
$scope.findOne = function() {
// Use the Dashboard 'get' method to send an appropriate GET request
$scope.dashboard = Dashboards.get({dashboardId: $routeParams.dashboardId});
};
///////////////////////////////////////////////
//get the prediction results
$scope.identify = function() {
// Use the Dashboard 'get' method to send an appropriate GET request
$scope.dashboard = Dashboards.get({identity: $routeParams.identity});
console.log('identify');
};
//////////////////////////////////
// Create a new controller method for updating a single Dashboard
$scope.update = function() {
// Use the device '$update' method to send an appropriate PUT request
$scope.dashboard.$update(function() {
// If an device was updated successfully, redirect the user to the device's page
$location.path('dashboards/' + $scope.dashboard._id);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for deleting a single Dashboard
$scope.delete = function(dashboard) {
// If an Dashboard was sent to the method, delete it
if (dashboard) {
// Use the Dashboard '$remove' method to delete the Dashboard
Dashboard.$remove(function() {
// Remove the Dashboard from the Dashboards list
for (var i in $scope.dashboards) {
if ($scope.dashboards[i] === dashboard) {
$scope.dashboards.splice(i, 1);
}
}
});
} else {
// Otherwise, use the Dashboard '$remove' method to delete the Dashboard
$scope.dashboard.$remove(function() {
$location.path('dashboards');
});
}
};
//retrieving all the Smart Plugs currently created
$scope.findDevices = function() {
// Use the Dashboard 'query' method to send an appropriate GET request
$scope.deviceList = Devices.query();
$scope.devices = $scope.deviceList[1];
};
$scope.findDevices();
$scope.findSmartPlugs = function() {
// Use the device 'query' method to send an appropriate GET request
$scope.smartplugList = SmartPlugs.query();
$scope.smartplugs = $scope.smartplugList[1];
};
$scope.findSmartPlugs();
//ngDialog Controlling Section Start
$scope.jsonData = '{"foo": "bar"}';
$scope.theme = 'ngdialog-theme-default';
$scope.clickToOpen = function () {
ngDialog.open(
{ template: 'templateId' ,
className: 'ngdialog-theme-flat',
plain: false,
showClose: true,
closeByDocument: true,
closeByEscape: true
});
};
//power calculation functions start
$scope.power_per_device =0;
$scope.getTotalPowerConsumedPerDevice = function(deviceId){
var powersPerDevice=[];
var totalPower=0;
var deviceList = Powers.query({devices:deviceId},function(){
angular.forEach(deviceList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPower+=(consN*10/3600/1000);
//console.log(deviceId);
});//end of foreach
totalPower = parseFloat(totalPower).toFixed(2);
$scope.power_per_device=totalPower;
$scope.power_per_device = parseFloat($scope.power_per_device);
console.log("Total Power Per Device: "+totalPower+" KWh");
$scope.setDataForNgDialog1();
console.log("Power of Device :"+ $scope.power_per_device)
$scope.setGaugeMeterForDevice();
});//end of query
return totalPower;
};
// power per smartplug start
$scope.power_per_smartplug =0;
$scope.getTotalPowerConsumedPerSmartPlug = function(smartplugId){
console.log("smartplug Id: "+smartplugId);
var powersPerSmartPlug=[];
var totalPowerSmartPlug=0;
var smartplugList = Powers.query({smartplugs:smartplugId},function(){
angular.forEach(smartplugList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPowerSmartPlug+=(consN*10/3600/1000);
console.log(smartplugId);
});//end of foreach
totalPowerSmartPlug = parseFloat(totalPowerSmartPlug).toFixed(2);
$scope.power_per_smartplug=totalPowerSmartPlug;
$scope.power_per_smartplug = parseFloat($scope.power_per_smartplug);
console.log("Total Power Per Smartplug: "+totalPowerSmartPlug+" KWh");
$scope.setDataForNgDialog2();
console.log("Power of SmartPlug :"+ $scope.power_per_smartplug)
$scope.setGaugeMeterForSmartPlug();
});//end of query
return totalPowerSmartPlug;
};
//power per smart plug end
$scope.total_power_consumption=0;
$scope.no_of_days_for_total_power=0;
//get power consumption for all devices
$scope.getTotalPowerConsumptionFromEachDevice =function(){
var power=0;
var powers=[];
Devices.query({},function(data){
var totalPower=0;
angular.forEach(data, function(device,key){
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPower+=(consN*10/3600/1000);
// console.log(device._id);
});//end of foreach powerList
console.log("Power :"+totalPower);
$scope.total_power_consumption=parseFloat(totalPower).toFixed(2);
$scope.setGuageMeterForOverall();
$scope.setGaugeMeterForDevice();
$scope.setGaugeMeterForSmartPlug();
});//end of query powerList
//retrieve power for each device start
console.log("Power All: "+power);
}); //end of angular foreach
});//end of query
};
$scope.getTotalPowerConsumptionFromEachDevice();
//power calculation functions end
//get results
$scope.getPowerByDevice = function(){
$scope.getTotalPowerConsumedPerDevice($scope.devices);
};
$scope.getPowerBySmartPlug = function(){
$scope.getTotalPowerConsumedPerSmartPlug($scope.smartplugs);
};
//date range power calculation
$scope.total_power_consumption_per_date_range=0;
$scope.date_range_device_wise_power_list=[];
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice =[];
$scope.dateRangemaxPowerUserInfo=[];
$scope.dateRangeminPowerUserInfo=[];
$scope.dateRangeDateInfo=[];
$scope.getTotalPowerConsumptionFromEachDeviceByDayRange =function(start_date,end_date){
var powerData=[];
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice=[];
$scope.date_range_device_wise_power_list=[];
$scope.dateRangemaxPowerUserInfo=[];
$scope.dateRangeminPowerUserInfo=[];
$scope.dateRangeDateInfo=[];
var mm1 = start_date.split('-')[1];
var dd1 = start_date.split('-')[2];
var yy1 = start_date.split('-')[0];
$scope.dateRangeDateInfo.push({start_date:start_date,end_date:end_date});
var mm2 = end_date.split('-')[1];
var dd2 = end_date.split('-')[2];
var yy2 = end_date.split('-')[0];
Devices.query({},function(data){
var max=0;
var maxDevice='';
var min=10000000000000;
var minDevice='';
angular.forEach(data, function(device,key){
//retrieve power for each device start
var totalPower=0;
var powerList = Powers.query({devices:device._id},function(){
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
var milli = date.getTime();
// console.log("Time: "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());
// console.log("Day : "+date.getDay()+"/ Year: "+date.getFullYear()+" / Month : "+date.getMonth()+"");
var condition1 = (date.getFullYear()>=yy1 && date.getFullYear()<=yy2 );
var condition2 = ((date.getMonth()+1>=mm1) && (date.getMonth()+1<=mm2)) ;
var condition3 = (date.getMonth()>=dd1 && date.getMonth()<=dd2) ;
// console.log(condition1+" "+condition2+" "+condition3);
if( condition1==true && condition2==true && condition3==true ){
totalPower+=(consN*10/3600/1000);
}
// console.log(device._id);
});//end of foreach powerList
//console.log("Total Power Per Device: "+totalPower+" KWh Based On: Day Range: "+yy1+"/"+mm1+"/"+dd1+" - "+yy2+"/"+mm2+"/"+dd2);
totalPower = parseFloat(totalPower);
powerData.push(totalPower);
console.log("device : "+device.name);
console.log("total power: "+totalPower);
//calculate max and min power summary starts
if(max<totalPower){
$scope.dateRangemaxPowerUserInfo.splice(0,1);
max=totalPower.toFixed(2);
maxDevice=device.name;
$scope.dateRangemaxPowerUserInfo.push({maxDevice:maxDevice,max:max});
console.log(max+" <max> "+totalPower)
}
//min power using device
if(min>totalPower){
$scope.dateRangeminPowerUserInfo.splice(0,1);
min=totalPower.toFixed(2);
minDevice=device.name;
$scope.dateRangeminPowerUserInfo.push({minDevice:minDevice,min:min});
console.log(min+" <min> "+totalPower)
}
//calculate the cost for power consumption start
var start= new Date($scope.start_date);
var end= new Date($scope.end_date);
var diff = Math.round((end-start)/(1000*60*60*24));
// console.log('no of days : '+diff);
var cost=[];
cost= $scope.calculateCostPerMonth(totalPower.toFixed(2),diff,0);
//console.log('Cost Array')
//console.log(cost);
//calculate the cost for power consumption end
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice.push({device:device.name, power:totalPower.toFixed(2),cost:cost[0].energy_cost});
//calculate max and min power summary ends
$scope.date_range_device_wise_power_list.push({device:device.name,power:totalPower});
console.log(powerData.length+"/"+data.length);
if(powerData.length==data.length){
var power1=0;
angular.forEach(powerData,function(value,key){
power1+=parseFloat(value);
});
power1= parseFloat(power1).toFixed(2)
$scope.total_power_consumption_per_date_range=power1;
$scope.search_date_range=start_date+"-"+end_date;
console.log("Power Of All Devices: "+ $scope.total_power_consumption_per_date_range);
$scope.dialogModel1 = {
message : power1
};
$scope.setDataForNgDialog();
}
});//end of query powerList
//retrieve power for each device start
// console.log("total power c: "+power);
}); //end of angular foreach
});//end of query
};
$scope.getTotalPowerConsumptionByDateRange = function(start_date,end_date){
var mm1 = start_date.split('-')[1];
var dd1 = start_date.split('-')[2];
var yy1 = start_date.split('-')[0];
var mm2 = end_date.split('-')[1];
var dd2 = end_date.split('-')[2];
var yy2 = end_date.split('-')[0];
start_date = new Date(start_date);
end_date = new Date(end_date);
var totalPower=0;
var powers = Powers.query({},function(data){
angular.forEach(data,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
var milli = date.getTime();
if(date>=start_date && date <= end_date){
totalPower+=(consN*10/3600/1000);
}
});
$scope.totalPowerByDateRange = totalPower.toFixed(2);
});
};
//ngDialog code
$scope.dialogModel = {
message : 'message from passed scope'
};
$scope.openSecond = function () {
ngDialog.open({
template: '<h3><a href="" ng-click="closeSecond()">Close all by click here!</a></h3>',
plain: true,
closeByEscape: false,
controller: 'SecondModalCtrl',
data: $scope.total_power_consumption_per_date_range,
scope:$scope
});
};
$scope.openFirst = function () {
console.log("Power : "+$scope.total_power_consumption_per_date_range);
$scope.jsonData1 = {foo: $scope.total_power_consumption_per_date_range};
console.log('Form Json data: ')
console.log( $scope.jsonData1.foo);
ngDialog.open({
template: '<h2>Value: <code>{{total_power_consumption_per_date_range}}</code></h2>',
plain: true,
closeByEscape: false,
controller: 'DashboardsController',
data: $scope.jsonData1,
scope:$scope
});
};
$scope.setDataForNgDialog = function(){
var start= new Date($scope.start_date);
var end= new Date($scope.end_date);
//console.log('start: '+start);
// console.log('end: '+end);
var diff = Math.round((end-start)/(1000*60*60*24));
// console.log('no of days : '+diff);
$scope.calculateCostPerMonth($scope.total_power_consumption_per_date_range,diff,0);
var cost = $scope.costOfConsumptionPerDateRange;
$scope.jsonData1 = {power: $scope.total_power_consumption_per_date_range,daterange: $scope.search_date_range, moreinfo:$scope.date_range_device_wise_power_list,summary:$scope.dateRangesummaryOnMaximumPowerUsagePerDevice,maxInfo: $scope.dateRangemaxPowerUserInfo,minInfo:$scope.dateRangeminPowerUserInfo,dateRange:$scope.dateRangeDateInfo,totalCost:cost};
};
$scope.setDataForNgDialog1 = function(){
$scope.jsonData2 = {power: $scope.power_per_device,totalpower: $scope.total_power_consumption};
console.log("jsondata2.power : "+$scope.jsonData2.power)
$scope.setGaugeMeterForDevice();
};
$scope.setDataForNgDialog2 = function(){
$scope.jsonData3 = {power: $scope.power_per_smartplug,totalpower: $scope.total_power_consumption};
console.log("jsondata2.power : "+$scope.jsonData3.power)
$scope.setGaugeMeterForSmartPlug();
};
$scope.setDataForNgDialogActivationTime = function(){
var active_time= $scope.processAcivationDeviceTime($scope.deviceActivateTime);
var deviceInfo = $scope.deviceProfile_SelectedDevice;
$scope.jsonData4 = {list: $scope.deviceActivateTime,len: $scope.deviceActivateTime.length,active:active_time,deviceInfo:deviceInfo};
};
$scope.setDataForNgDialogGraphDetails = function(){
$scope.setAnalyticChartInfo();
console.log('My Data Source');
console.log($scope.myDataSource);
$scope.jsonData8 = {dataSource:$scope.myDataSource};
};
//get the time ranges and make prediction start
$scope.processAcivationDeviceTime = function(list){
//data
var on_off_set=[];
var block=[];
console.log('===========Activation Time Process==========');
for(var i=list.length-1;i>0;i--){
var t1 = list[i].time;
var t2 = list[i-1].time;
var t = t2-t1;
if(t<=180000 ){
console.log(i+"->"+t1);
block.push({index:i,date:t1});
//this condition detects if the last data set contains a block or not
if(block.length>0 && i==1){
//console.log("block:");
//console.log(block);
on_off_set.push(block);
block=[];
}
}
else{
if(block.length>0){
//console.log("block:");
// console.log(block);
on_off_set.push(block);
block=[];
}
}
// console.log("diff :"+t+" ==>"+t1+"---"+t2);
}
console.log("array length blcok: "+on_off_set.length)
for(var k=0;k<on_off_set.length;k++){
console.log(on_off_set[k]);
}
return on_off_set;
};
//get the time ranges and make prediction end
//gauge meter per device start
$scope.setGaugeMeterForDevice = function(){
//ng Guage Meter Start - For Device Overall Consumption
var meter_reading_device = parseFloat($scope.power_per_device);
console.log("meter reading devices: "+meter_reading_device);
$scope.value1 = meter_reading_device ;
$scope.upperLimit1 = Math.ceil($scope.total_power_consumption);
$scope.lowerLimit1 = 0;
$scope.unit1= "kWh";
$scope.precision1 = 2;
$scope.ranges1 = [
{
min: 0,
max: $scope.upperLimit1/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit1/5,
max: 2*$scope.upperLimit1/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit1/5,
max: 3*$scope.upperLimit1/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit1/5,
max: 4*$scope.upperLimit1/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit1/5,
max: $scope.upperLimit1,
color: '#C50200'
}
];
//ng Gauge Meter For Overall Device Consumption End
console.log("setGaugeMeterForDevice");
};
//gauge meter per smartplug start
$scope.setGaugeMeterForSmartPlug = function(){
//ng Guage Meter Start - For Device Overall Consumption
var meter_reading_smartplug = parseFloat($scope.power_per_smartplug);
console.log("meter reading devices: "+meter_reading_smartplug);
$scope.value2 = meter_reading_smartplug ;
$scope.upperLimit2 = Math.ceil($scope.total_power_consumption);
$scope.lowerLimit2 = 0;
$scope.unit2= "kWh";
$scope.precision2 = 2;
$scope.ranges2 = [
{
min: 0,
max: $scope.upperLimit2/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit2/5,
max: 2*$scope.upperLimit2/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit2/5,
max: 3*$scope.upperLimit2/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit2/5,
max: 4*$scope.upperLimit2/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit2/5,
max: $scope.upperLimit2,
color: '#C50200'
}
];
//ng Gauge Meter For Overall Device Consumption End
console.log("setGaugeMeterForSmartPlug");
};
//for device update gauge start
function update1() {
$timeout(function() {
if($scope.power_per_device!=0){
$scope.value1= $scope.power_per_device;
$scope.upperLimit1= $scope.power_per_device + 10;
console.log("Upper limit: "+$scope.upperLimit1);
console.log($scope.value1+"**"+$scope.upperLimit1+"##"+$scope.power_per_device);
if ($scope.value1 > $scope.upperLimit1) {
$scope.value1=$scope.lowerLimit1;
}
}
update1();
}, 1000);
}
update1();
//device update gauge ends
//smartplug update gauge start
function update2() {
$timeout(function() {
if($scope.power_per_smartplug!=0){
$scope.value2= $scope.power_per_smartplug;
$scope.upperLimit2= $scope.power_per_smartplug + 10;
console.log("Upper limit: "+$scope.upperLimit1);
console.log($scope.value2+"**"+$scope.upperLimit2+"##"+$scope.power_per_smartplug);
if ($scope.value2 > $scope.upperLimit2) {
$scope.value2=$scope.lowerLimit2;
}
}
update2();
}, 1000);
}
update2();
//smartplug update gauge ends
///////////////////////////////////////////////////////////////////////////////
$scope.current = 27;
$scope.max = 50;
$scope.timerCurrent = 0;
$scope.uploadCurrent = 0;
$scope.stroke = 15;
$scope.radius = 60;
$scope.isSemi = false;
$scope.rounded = false;
$scope.responsive = false;
$scope.clockwise = true;
$scope.currentColor = '#45ccce';
$scope.bgColor = '#eaeaea';
$scope.duration = 800;
$scope.currentAnimation = 'easeOutCubic';
$scope.increment = function(amount){
$scope.current+=(amount || 1);
};
$scope.decrement = function(amount){
$scope.current-=(amount || 1);
};
$scope.animations = [];
angular.forEach(roundProgressService.animations, function(value, key){
$scope.animations.push(key);
});
$scope.getStyle = function(){
var transform = ($scope.isSemi ? '' : 'translateY(-50%) ') + 'translateX(-50%)';
return {
'top': $scope.isSemi ? 'auto' : '50%',
'bottom': $scope.isSemi ? '5%' : 'auto',
'left': '50%',
'transform': transform,
'-moz-transform': transform,
'-webkit-transform': transform,
'font-size': $scope.radius/3.5 + 'px'
};
};
$scope.getColor = function(){
return $scope.gradient ? 'url(#gradient)' : $scope.currentColor;
};
var getPadded = function(val){
return val < 10 ? ('0' + val) : val;
};
$interval(function(){
var date = new Date();
var secs = date.getSeconds();
$scope.timerCurrent = secs;
$scope.time = getPadded(date.getHours()) + ':' + getPadded(date.getMinutes()) + ':' + getPadded(secs);
}, 1000);
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//angular gauge meter panels
$scope.openGauages = function () {
ngDialog.open({
template: 'views/popupTmpl.html',
plain: true,
closeByEscape: false,
controller: 'DashboardsController',
scope:$scope
});
};
//angular gauge meter code start
//ng Guage Meter Start - For Overall Consumption
$scope.setGuageMeterForOverall = function(){
var meter_reading = parseFloat($scope.total_power_consumption);
console.log("meter reading: "+meter_reading)
var meter_reading1 = 3;
$scope.value = meter_reading;
$scope.upperLimit = meter_reading + 20.00;
$scope.lowerLimit = 0;
$scope.unit = "kWh";
$scope.precision = 2;
$scope.ranges = [
{
min: 0,
max: $scope.upperLimit/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit/5,
max: 2*$scope.upperLimit/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit/5,
max: 3*$scope.upperLimit/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit/5,
max: 4*$scope.upperLimit/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit/5,
max: $scope.upperLimit,
color: '#C50200'
}
];
};
function update() {
$timeout(function() {
$scope.value= $scope.value;
//console.log($scope.value+" "+$scope.upperLimit);
if ($scope.value > $scope.upperLimit) {
$scope.value=$scope.lowerLimit;
}
update();
}, 1000);
}
update();
//////////////////////////////////////////////////////////////
//calculate the on of times of a device start
$scope.deviceActivateTime =[];
$scope.deviceProfile_SelectedDevice='';
$scope.getActivationDetails = function(device){
if($scope.isDeviceSelected==false){
$scope.isDeviceSelected=true;
}
$scope.getActivatedTimeOfDevice(device);
};
$scope.getActivatedTimeOfDevice = function(device){
var i=0;
$scope.deviceActivateTime =[];
$scope.deviceProfile_SelectedDevice=device;
var powerlist = Powers.query({devices:device._id},function(){//start of power loop
angular.forEach(powerlist,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
$scope.deviceActivateTime.push({id:i,time:date});
i++;
});
if($scope.deviceActivateTime.length>0){
console.log("Length of activate time : "+$scope.deviceActivateTime.length)
$scope.dialogModelActivationTime = {
message : $scope.deviceActivateTime.length
};
$scope.setDataForNgDialogActivationTime();
}
});//end of power loop
};
//calculate the on of times of device end
/////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the summary starts
$scope.summaryOnMaximumPowerUsagePerDevice =[];
$scope.maxPowerUserInfo=[];
$scope.minPowerUserInfo=[];
$scope.getSummaryOnMaximumPowerUsagePerDevice = function(){//function start
var infoList=[];
var deviceList = Devices.query({},function(){//start device list
var powerPerDevice=0;
var max=0;
var maxDevice='';
var min=10000000000000;
var minDevice='';
angular.forEach(deviceList,function(device,key){//devicelist for loop start
var powerList = Powers.query({devices:device._id},function(){//powerlist for loop start
powerPerDevice=0;
angular.forEach(powerList,function(power,key){//power for loop start
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
powerPerDevice+=(consN*10/3600/1000);
}); //power for loop end
console.log("Device: "+device.name+" , Power Consumption : "+powerPerDevice.toFixed(2));
//max power using device
if(max<powerPerDevice){
$scope.maxPowerUserInfo.splice(0,1);
max=powerPerDevice.toFixed(2);
maxDevice=device.name;
$scope.maxPowerUserInfo.push({maxDevice:maxDevice,max:max});
console.log(max+" <max> "+powerPerDevice)
}
//min power using device
if(min>powerPerDevice){
$scope.minPowerUserInfo.splice(0,1);
min=powerPerDevice.toFixed(2);
minDevice=device.name;
$scope.minPowerUserInfo.push({minDevice:minDevice,min:min});
console.log(min+" <min> "+powerPerDevice)
}
$scope.summaryOnMaximumPowerUsagePerDevice.push({device:device.name, power:powerPerDevice.toFixed(2)});
});//powerlist for loop end
//get max power usage device
});//devicelist for loop ends
});//end device list
};//function ends
$scope.getSummaryOnMaximumPowerUsagePerDevice();
//summary ends
//cost calculation algorithm start
//calculation constants for power consumption cost start
//information url:
//http://leco.lk/?page_id=549
$scope.price_per_kwh=parseFloat(5.00);
var domesticCalculationBelow60={};
domesticCalculationBelow60.level=60;
domesticCalculationBelow60.range1_low=0;
domesticCalculationBelow60.range1_high=30;
domesticCalculationBelow60.range2_low=31;
domesticCalculationBelow60.range2_high=60;
domesticCalculationBelow60.range1_energy_charge=parseFloat(2.50);
domesticCalculationBelow60.range1_fixed_charge=parseFloat(30.00);
domesticCalculationBelow60.range2_energy_charge=parseFloat(4.85);
domesticCalculationBelow60.range2_fixed_charge=parseFloat(60.00);
domesticCalculationBelow60.ranges_energy_charge=[2.50,4.85,0,0,0];
domesticCalculationBelow60.ranges_fixed_charge=[30,60,0,0,0];
// 61-90 10.00 90
// 91-120 27.75 480
// 121-180 32.00 480
// >180 45.00 540
var domesticCalculationOver60={};
domesticCalculationOver60.level=60;
domesticCalculationOver60.range1_low=61;
domesticCalculationOver60.range1_high=90;
domesticCalculationOver60.range2_low=91;
domesticCalculationOver60.range2_high=120;
domesticCalculationOver60.range3_low=121;
domesticCalculationOver60.range3_high=180;
domesticCalculationOver60.range4_low=181;
domesticCalculationOver60.range4_high=100000;
domesticCalculationOver60.range1_energy_charge=parseFloat(10.00);
domesticCalculationOver60.range1_fixed_charge=parseFloat(90.00);
domesticCalculationOver60.range2_energy_charge=parseFloat(27.75);
domesticCalculationOver60.range2_fixed_charge=parseFloat(480.00);
domesticCalculationOver60.range3_energy_charge=parseFloat(32);
domesticCalculationOver60.range3_fixed_charge=parseFloat(480.00);
domesticCalculationOver60.range4_energy_charge=parseFloat(45.00);
domesticCalculationOver60.range4_fixed_charge=parseFloat(540.00);
domesticCalculationOver60.ranges_energy_charge=[7.85,10.00,27.75,32.00,45.00];
domesticCalculationOver60.ranges_fixed_charge=[0,90,480,480,540];
domesticCalculationOver60.ranges_fixed_charge_cut_off=[60,90,120,180,181];
$scope.costOfConsumptionPerDateRange = 0;
//calculating cost per month start
$scope.calculateCostPerMonth = function(units,days,type){
console.log('Bill Calculating');
console.log('=========================================');
var cost=0;
var costs=[];
//domestic type =0;
if(type==0){
console.log('This is domestic billing...');
if(units<=domesticCalculationBelow60.level){
var blocksize = days *2;
var currentUnit=units;
var block=[];
if(days<units){//block check if start
var no_of_blocks = Math.floor(units/days) ;
for(var i=0;i<5;i++){
if(currentUnit>=0 && i<4){
if(i==0 && currentUnit-blocksize>0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(i==3 && currentUnit-blocksize>=0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(currentUnit-days<=0){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}else{
block.push({id:i,val:days});
currentUnit-=days;
}
}
}
}else if(currentUnit>=0 && i==4){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}
}
console.log('no of blocks :'+no_of_blocks);
var cost=0;
for(var i=0;i<5;i++){
console.log(block[i].id+' - '+block[i].val);
cost+= block[i].val * domesticCalculationBelow60.ranges_energy_charge[i];
}
costs.push({id:'energy_cost',energy_cost:cost});
if(units>domesticCalculationBelow60.ranges_fixed_charge[0] ){
cost+=domesticCalculationBelow60.ranges_fixed_charge[1];
}else{
cost+=domesticCalculationBelow60.ranges_fixed_charge[0];
}
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',fixed_cost:cost});
}else{
costs.push({id:'energy_cost',energy_cost:(units*parseFloat(2.50)).toFixed(2)});
cost=((units*parseFloat(2.50) +parseFloat(30.00)).toFixed(2));
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',fixed_cost:cost});
}
}
if(units>domesticCalculationOver60.level){
var blocksize = days *2;
var currentUnit=units;
var block=[];
if(days<units){//block check if start
var no_of_blocks = Math.floor(units/days) ;
for(var i=0;i<5;i++){
if(currentUnit>=0 && i<4){
if(i==0 && currentUnit-blocksize>0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(i==3 && currentUnit-blocksize>=0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(currentUnit-days<=0){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}else{
block.push({id:i,val:days});
currentUnit-=days;
}
}
}
}else if(currentUnit>=0 && i==4){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}
}
console.log('no of blocks :'+no_of_blocks);
for(var i=0;i<5;i++){
console.log(block[i].id+' - '+block[i].val);
cost+= block[i].val * domesticCalculationOver60.ranges_energy_charge[i];
}
console.log('Cost : '+cost);
costs.push({id:'energy_cost',energy_cost:cost});
if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[0] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[0];
}else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[1] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[1];
}
else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[2] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[2];
}
else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[3] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[3];
}
else if(units>domesticCalculationOver60.ranges_fixed_charge_cut_off[4] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[4];
}
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',energy_cost:cost});
}
}
}//type 0 ends domestic
if(type='religious'){
}
if(type='hotel'){
}
if(type='industrial'){
}
console.log('=========================================');
$scope.costOfConsumptionPerDateRange=cost;
return costs;
};
//calculating cost per month end
//calculating cost per month start
$scope.calculateCostPerDay = function(units,days){
};
//calculating cost per month end
//calculating cost per month start
$scope.calculateCostPerYear = function(units,days){
};
//calculating cost per month end
//cost calculation algorithm ends
//get main list selected item and process data start
$scope.mainTodayOverallPower=[];
$scope.mainTodayTotalPower=0;
$scope.mainTodayTotalPowerCost=0;
$scope.mainTodayCostOfKWH= parseFloat(2.50);
$scope.isToday=false;
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
$scope.isYesterday=false;
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
$scope.isThisMonth=false;
$scope.mainLastMonthOverallPower=[];
$scope.mainLastMonthTotalPower=0;
$scope.mainLastMonthTotalPowerCost=0;
$scope.mainLastMonthCostOfKWH= parseFloat(2.50);
$scope.isLastMonth=false;
$scope.getMainListSearch = function(item){
if($scope.mainListItems[item].id==0){
//yesterday
$scope.isYesterday=true;
$scope.isToday=false;
$scope.isThisMonth=false;
$scope.isLastMonth=false;
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
//var tempDateString ="2015-11-25";
dateString = date.toLocaleDateString();
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==1){
//today
$scope.isToday=true;
$scope.isYesterday=false;
$scope.isThisMonth=false;
$scope.isLastMonth=false;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
// $window.alert($scope.mainListItems[item].name+"**"+'today :'+date);
// var tempDateString ="2015-09-16";
dateString = date.toLocaleDateString();
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==2){
//current month
$scope.isThisMonth=true;
$scope.isLastMonth=false;
$scope.isToday=false;
$scope.isYesterday=false;
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==3){
//last month
$scope.isThisMonth=false;
$scope.isLastMonth=true;
$scope.isToday=false;
$scope.isYesterday=false;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==4){
//overall
$scope.isToday=true;
$scope.isYesterday=true;
$scope.isThisMonth=true;
$scope.isLastMonth=true;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
}
//get main list selected item and process data end
//
//get total power consumption per device per day
$scope.getTotalPowerConsumptionFromEachDeviceByDay =function(start_date){
$scope.mainTodayOverallPower=[];
$scope.mainTodayTotalPower=0;
$scope.mainTodayTotalPowerCost=0;
$scope.mainTodayCostOfKWH= parseFloat(2.50);
$scope.mainTodayOverallPowerCost=[];
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
$scope.mainYesterdayOverallPowerCost=[];
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
$scope.mainThisMonthOverallPowerCost=[];
$scope.mainLastMonthOverallPower=[];
$scope.mainLastMonthTotalPower=0;
$scope.mainLastMonthTotalPowerCost=0;
$scope.mainLastMonthCostOfKWH= parseFloat(2.50);
$scope.mainLastMonthOverallPowerCost=[];
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
var powerOfAllDevices=0;
console.log(yy+"-"+mm+"-"+dd);
Devices.query({},function(data){
angular.forEach(data, function(device,key){
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
var totalPower=0;
var totalPowerYesterday=0;
var totalPowerThisMonth=0;
var totalPowerLastMonth=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
// console.log(device.name+'-'+date);
// console.log("Time: "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());
console.log("Day : "+date.getDate()+"/ Year: "+date.getFullYear()+" / Month : "+(date.getMonth()+1)+"");
//get today power
if(mm==(date.getMonth()+1) && (dd)==date.getDate() && yy==date.getFullYear()){
totalPower+=(consN*10/3600/1000);
}
//get yesterday power
if(mm==(date.getMonth()+1) && (dd-1)==(date.getDate()) && yy==date.getFullYear()){
totalPowerYesterday+=(consN*10/3600/1000);
}
//get this month power
if((mm-1)==(date.getMonth()) && yy==date.getFullYear()){
totalPowerThisMonth+=(consN*10/3600/1000);
}
//get last month power
if((mm-2)==(date.getMonth()) && yy==date.getFullYear()){
totalPowerLastMonth+=(consN*10/3600/1000);
}
// console.log(device._id);
});//end of foreach powerList
console.log(device.name+" : "+totalPower+" KWh Based On: "+mm+"/"+dd+"/"+yy);
powerOfAllDevices+=totalPower;
$scope.mainTodayOverallPower.push({device:device.name,power:totalPower});
$scope.mainTodayTotalPower +=totalPower;
var costOfTodayPower = $scope.mainTodayCostOfKWH * totalPower;
$scope.mainTodayOverallPowerCost.push({device:device.name,cost:costOfTodayPower});
console.log($scope.mainTodayOverallPowerCost);
$scope.mainYesterdayOverallPower.push({device:device.name,power:totalPowerYesterday});
$scope.mainYesterdayTotalPower +=totalPowerYesterday;
var costOfYesterdayPower = $scope.mainYesterdayCostOfKWH * totalPowerYesterday;
$scope.mainYesterdayOverallPowerCost.push({device:device.name,cost:costOfYesterdayPower});
$scope.mainThisMonthOverallPower.push({device:device.name,power:totalPowerThisMonth});
$scope.mainThisMonthTotalPower +=totalPowerThisMonth;
var costsThisMonth= $scope.calculateCostPerMonth(totalPowerThisMonth,30,0);
$scope.mainThisMonthOverallPowerCost.push({device:device.name,cost:costsThisMonth});
$scope.mainLastMonthOverallPower.push({device:device.name,power:totalPowerLastMonth});
$scope.mainLastMonthTotalPower +=totalPowerLastMonth;
var costsLastMonth= $scope.calculateCostPerMonth(totalPowerLastMonth,30,0);
$scope.mainLastMonthOverallPowerCost.push({device:device.name,cost:costsLastMonth});
if(data.length==$scope.mainTodayOverallPower.length){
var val = ($scope.mainTodayTotalPower * $scope.mainTodayCostOfKWH);
//val = parseFloat(val).toFixed(2);
$scope.mainTodayTotalPowerCost=val;
}
if(data.length==$scope.mainYesterdayOverallPower.length){
var val = ($scope.mainYesterdayTotalPower * $scope.mainYesterdayCostOfKWH);
//val = parseFloat(val).toFixed(2);
$scope.mainYesterdayTotalPowerCost=val;
}
if(data.length==$scope.mainThisMonthOverallPower.length){
var val = ($scope.mainThisMonthTotalPower);
var pow=0;
angular.forEach($scope.mainThisMonthOverallPower,function(value,key){
pow+=value.power;
});
$scope.mainThisMonthTotalPower=pow;
var costs= $scope.calculateCostPerMonth($scope.mainThisMonthTotalPower,30,0);
var energy_cost = costs[0].energy_cost;
var fixed_cost = costs[1].fixed_cost;
console.log('this month fixed cost: '+fixed_cost);
console.log('this month energy cost: '+energy_cost);
$scope.mainThisMonthTotalPowerCost=energy_cost;
console.log($scope.mainThisMonthTotalPowerCost);
}
if(data.length==$scope.mainLastMonthOverallPower.length){
if(totalPowerLastMonth==0){
$scope.mainLastMonthTotalPower=parseFloat(0.00);
}
var pow=0;
angular.forEach($scope.mainLastMonthOverallPower,function(value,key){
pow+=value.power;
});
$scope.mainLastMonthTotalPower=pow;
var costs= $scope.calculateCostPerMonth($scope.mainLastMonthTotalPower,30,0);
var energy_cost = costs[0].energy_cost;
var fixed_cost = costs[1].fixed_cost;
console.log('last month fixed cost: '+fixed_cost);
console.log('last month energy cost: '+energy_cost);
$scope.mainLastMonthTotalPowerCost=energy_cost;
console.log($scope.mainLastMonthTotalPowerCost);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//draw chart
$scope.myDataSource={};
$scope.setAnalyticChartInfo = function(){
};
$scope.myDataSource = {
chart: {
caption: "Harry's SuperMart",
subCaption: "Top 5 stores in last month by revenue",
numberPrefix: "$",
theme: "fint"
},
data: [{
label: "Bakersfield Central",
value: "880000"
}, {
label: "Garden Groove harbour",
value: "730000"
}, {
label: "Los Angeles Topanga",
value: "590000"
}, {
label: "Compton-Rancho Dom",
value: "520000"
}, {
label: "Daly City Serramonte",
value: "330000"
}]
};
$scope.myDataSourcePie = {
chart: {
caption: "Age profile of website visitors",
subcaption: "Last Year",
startingangle: "120",
showlabels: "0",
showlegend: "1",
enablemultislicing: "0",
slicingdistance: "15",
showpercentvalues: "1",
showpercentintooltip: "0",
plottooltext: "Age group : $label Total visit : $datavalue",
theme: "fint"
},
data: [
{
label: "Teenage",
value: "1250400"
},
{
label: "Adult",
value: "1463300"
},
{
label: "Mid-age",
value: "1050700"
},
{
label: "Senior",
value: "491000"
}
]
};
/* $scope.attrs={};
$scope.categories=[];
$scope.dataset=[];*/
//stream line char data
$scope.setStreamLineChartData = function(){
$scope.attrs = {
"caption": "Sales Comparison: 2013 versus 2014",
"subCaption": "Harry's SuperMart",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.dataset = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "21800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "27600"
}, {
"value": "26800"
}, {
"value": "27700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
//this month Graph Data Set
$scope.setThisMonthGraphData = function(){
$scope.attrsThisMonth = {
"caption": "This Month",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesThisMonth = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetThisMonth = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
//set last month graph data
$scope.setLastMonthGraphData =function(){
$scope.attrsLastMonth = {
"caption": "Last Month",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesLastMonth = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetLastMonth = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setTodayGraphData = function(){
$scope.attrsToday = {
"caption": "Today",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesToday = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetToday = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setYesterdayGraphData = function(){
$scope.attrsYesterday = {
"caption": "Yesterday",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesYesterday = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetYesterday = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setStreamLineChartData();
$scope.setThisMonthGraphData();
$scope.setLastMonthGraphData();
$scope.setTodayGraphData();
$scope.setYesterdayGraphData();
//generate data dynamically for graphs
$scope.getPowerPerDayGraph = function(start_date){
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
var selectedMonth ;
$scope.dataset2=[];
$scope.dataset3=[];
$scope.dataset4=[];
$scope.dataset5=[];
var maxPar =0;
var maxParLastMonth=0;
var days = [];
for (var i=1; i<=31; i++) {
days.push({day:i});
}
var data=[];
var dataLastMonth=[];
var monthlist = [{key:'1',month:'1',days:31},{key:'2',month:'2',days:31},{key:'3',month:'3',days:31},{key:'4',month:'4',days:31},{key:'5',month:'5',days:31},{key:'6',month:'6',days:31},{key:'7',month:'7',days:31},{key:'8',month:'8',days:31},{key:'9',month:'9',days:31},{key:'10',month:'10',days:31},{key:'11',month:'11',days:31},{key:'12',month:'12',days:31}];
var powerOfAllDevices=0;
Devices.query({},function(devicesData){
angular.forEach(devicesData, function(device,key){
var plotData = [];
var plotDataLastMonth=[];
var plotObject=[];
var plotObjectLastMonth=[];
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
// console.log(device._id)
// console.log(device._id+" "+(key+1))
angular.forEach(days,function(val1,key){//days loop start
var totalPower=0;
var totalPowerLastMonth=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
// console.log(date);
// console.log(date+"===>"+date.getFullYear()+"-"+((date.getMonth())+1)+"-"+date.getDate())
//calculation for this month
if( mm==((date.getMonth())+1) && yy==date.getFullYear() && (val1.day)==date.getDate() ){
totalPower+=(consN*10/3600/1000);
powerOfAllDevices+=(consN*10/3600/1000);
selectedMonth=date;
}
//calculation for last month
if( (mm-2)==((date.getMonth())) && yy==date.getFullYear() && (val1.day)==date.getDate() ){
totalPowerLastMonth+=(consN*10/3600/1000);
selectedMonth=date;
}
});//end of foreach powerList
plotData.push({value:totalPower});
plotDataLastMonth.push({value:totalPowerLastMonth});
if(maxPar==0){
maxPar=totalPower;
}else if(totalPower>maxPar){
maxPar=totalPower;
}else{
maxPar=maxPar;
}
if(maxParLastMonth==0){
maxParLastMonth=totalPowerLastMonth;
}else if(totalPowerLastMonth>maxParLastMonth){
maxParLastMonth=totalPowerLastMonth;
}else{
maxParLastMonth=maxParLastMonth;
}
});//days loop end
// var month = selectedMonth.toString().split(' ')[1];
plotObject.push({seriesname:device.name,data:plotData});
plotObjectLastMonth.push({seriesname:device.name,data:plotDataLastMonth});
data.push(plotObject);
dataLastMonth.push(plotObjectLastMonth);
/* $scope.dataset2.push({seriesname:device.name,data:plotData});
$scope.attrs2.caption='Power Consumption of Month - '+mm;
// console.log("maxPar: "+maxPar)
$scope.attrs2.yaxismaxvalue = Math.ceil(maxPar);*/
if(data.length==devicesData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var monthdata=[];
var monthdataCost=[];
for(var j=0;j<data[data.length-1][0].data.length;j++){
var val=0;
var cost=0;
for(var i=0;i<data.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
val+=data[i][0].data[j].value;
}
cost = val * $scope.costOfOneKWh;
monthdataCost.push({value:cost});
monthdata.push({value:val});
}
$scope.dataset2.push({seriesname:'Current Month ',data:monthdata});
$scope.dataset3.push({seriesname:'Current Month ',data:monthdataCost});
$scope.attrs2.caption='Power Consumption of Month - '+mm;
$scope.attrs3.caption='Cost of Consumption on Month - '+mm;
// console.log("maxPar: "+maxPar)
$scope.attrs2.yaxismaxvalue = Math.ceil(maxPar);
$scope.attrs3.yaxismaxvalue = Math.ceil(maxPar*$scope.costOfOneKWh);
}
if(dataLastMonth.length==devicesData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var monthdataLastMonth=[];
var monthdataCostLastMonth=[];
for(var j=0;j<dataLastMonth[dataLastMonth.length-1][0].data.length;j++){
var valLastMonth=0;
var costLastMonth=0;
for(var i=0;i<dataLastMonth.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
valLastMonth+=dataLastMonth[i][0].data[j].value;
}
costLastMonth = valLastMonth * $scope.costOfOneKWh;
monthdataCostLastMonth.push({value:costLastMonth});
monthdataLastMonth.push({value:valLastMonth});
}
$scope.dataset4.push({seriesname:'Last Month ',data:monthdataLastMonth});
$scope.dataset5.push({seriesname:'Last Month ',data:monthdataCostLastMonth});
$scope.attrs4.caption='Power Consumption of Month - '+(parseInt(mm)-1);
$scope.attrs5.caption='Cost of Consumption on Month - '+(parseInt(mm)-1);
// console.log("maxPar: "+maxPar)
$scope.attrs4.yaxismaxvalue = Math.ceil(maxParLastMonth);
$scope.attrs5.yaxismaxvalue = Math.ceil(maxParLastMonth*$scope.costOfOneKWh);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
//////////////////////////////////////////////////////////////////////////////////
// generating graphs for today and yesterday
$scope.getPowerPerHourGraph = function(start_date){
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
// var str = start_time.toString().split(' ')[4];
// var time = str.split(':');
// var hour = time[0];
// var minute = time[1];
// var second = time[2];
var selectedMonth ;
$scope.dataset6=[];//today
$scope.dataset7=[];//tommorrow
$scope.dataset8=[];//today
$scope.dataset9=[];//tommorrow
var maxPar =0;
var maxParYesterday=0;
var hours =[];
for(var j=0; j<=23 ; j++){
hours.push({hour:j});
}
var data=[];
var dataYesterday=[];
var monthlist = [{key:'1',month:'1',days:31},{key:'2',month:'2',days:31},{key:'3',month:'3',days:31},{key:'4',month:'4',days:31},{key:'5',month:'5',days:31},{key:'6',month:'6',days:31},{key:'7',month:'7',days:31},{key:'8',month:'8',days:31},{key:'9',month:'9',days:31},{key:'10',month:'10',days:31},{key:'11',month:'11',days:31},{key:'12',month:'12',days:31}];
Devices.query({},function(deviceData){
angular.forEach(deviceData, function(device,key){
var plotData = [];
var plotObject=[];
var plotDataYesterday = [];
var plotObjectYesterday=[];
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
// console.log(device._id)
angular.forEach(hours,function(val1,key){//days loop start
var totalPower=0;
var totalPowerYesterday=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
var str1 = date.toString().split(' ')[4];
str1= date.toTimeString().split(' ')[0]
var time1 = str1.split(':');
var hour1 = time1[0];
var minute1 = time1[1];
var second1 = time1[2];
// console.log(str);
// console.log(hour1+" "+minute1+" "+second1);
var condition1 =(mm==((date.getMonth())+1) && yy==date.getFullYear() && dd==date.getDate());
var condition2 = (hour1==val1.hour);
var condition3 = (mm==((date.getMonth())+1) && yy==date.getFullYear() && ((dd-1)==(date.getDate())));
// console.log(hour1+"--"+val1.hour)
// console.log(date+"===>"+date.getFullYear()+"-"+((date.getMonth())+1)+"-"+date.getDate())
if( condition1==true && condition2==true){
totalPower+=(consN*10/3600/1000);
selectedMonth=date;
}
if( condition3==true && condition2==true){
totalPowerYesterday+=(consN*10/3600/1000);
selectedMonth=date;
}
});//end of foreach powerList
plotData.push({value:totalPower});
if(maxPar==0){
maxPar=totalPower;
}else if(totalPower>maxPar){
maxPar=totalPower;
}else{
maxPar=maxPar;
}
plotDataYesterday.push({value:totalPowerYesterday});
if(maxParYesterday==0){
maxParYesterday=totalPowerYesterday;
}else if(totalPowerYesterday>maxParYesterday){
maxParYesterday=totalPowerYesterday;
}else{
maxParYesterday=maxParYesterday;
}
});//days loop end
// var month = selectedMonth.toString().split(' ')[1];
plotObject.push({seriesname:device.name,data:plotData});
plotObjectYesterday.push({seriesname:device.name,data:plotDataYesterday});
data.push(plotObject);
dataYesterday.push(plotObjectYesterday);
/* $scope.dataset6.push({seriesname:device.name,data:plotData});
$scope.attrs6.caption='Power Consumption of Day - '+start_date;
// console.log("maxPar: "+maxPar)
$scope.attrs6.yaxismaxvalue = Math.ceil(maxPar);
$scope.dataset7.push({seriesname:device.name,data:plotDataYesterday});
$scope.attrs7.caption='Power Consumption of Day - '+start_date;
// console.log("maxPar: "+maxPar)
$scope.attrs7.yaxismaxvalue = Math.ceil(maxParYesterday);*/
if(data.length==deviceData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var todaydata=[];
var todaydataCost=[];
var tempTodayPower=0;
var tempTodayPowerCost=0;
for(var j=0;j<data[data.length-1][0].data.length;j++){
var val=0;
var cost=0;
for(var i=0;i<data.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
val+=data[i][0].data[j].value;
}
cost = val * $scope.costOfOneKWh;
todaydataCost.push({value:cost});
todaydata.push({value:val});
tempTodayPower+=val;
tempTodayPowerCost+=cost;
}
$scope.tempTodayTotalPower = tempTodayPower;
$scope.tempTodayTotalPowerCost = tempTodayPowerCost;
$scope.dataset6.push({seriesname:'Today ',data:todaydata});
$scope.dataset8.push({seriesname:'Today ',data:todaydataCost});
$scope.attrs6.caption='Power Consumption of Today - '+dd;
$scope.attrs8.caption='Cost of Consumption on Today - '+dd;
// console.log("maxPar: "+maxPar)
$scope.attrs6.yaxismaxvalue = Math.ceil(maxPar);
$scope.attrs8.yaxismaxvalue = Math.ceil(maxPar*$scope.costOfOneKWh);
}
if(dataYesterday.length==deviceData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var yesterdaydata=[];
var yesterdaydatacost=[];
var tempYesterdayPower=0;
var tempYesterdayPowerCost=0;
for(var j=0;j<dataYesterday[dataYesterday.length-1][0].data.length;j++){
var valYesterday=0;
var costYesterday=0;
for(var i=0;i<dataYesterday.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
valYesterday+=dataYesterday[i][0].data[j].value;
}
costYesterday = valYesterday * $scope.costOfOneKWh;
tempYesterdayPower+=valYesterday;
tempYesterdayPowerCost+=costYesterday;
yesterdaydatacost.push({value:costYesterday});
yesterdaydata.push({value:valYesterday});
}
$scope.tempYesterdayTotalPower = tempYesterdayPower;
$scope.tempYesterdayTotalPowerCost = tempYesterdayPowerCost;
$scope.dataset7.push({seriesname:'Yesterday ',data:yesterdaydata});
$scope.dataset9.push({seriesname:'Yesterday ',data:yesterdaydatacost});
$scope.attrs7.caption='Power Consumption of Yesterday - '+(parseInt(dd)-1);
$scope.attrs9.caption='Cost of Consumption on Yesterday - '+(parseInt(dd)-1);
// console.log("maxPar: "+maxPar)
$scope.attrs7.yaxismaxvalue = Math.ceil(maxParYesterday);
$scope.attrs9.yaxismaxvalue = Math.ceil(maxParYesterday*$scope.costOfOneKWh);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
//call daily, monthly past and current data and load data to scope
var currentDate = new Date();
currentDate = currentDate.toLocaleDateString();
var demodata="2015-11-04";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(currentDate)
//$scope.setAnalyticChartInfo();
////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//predictions START
//reading from file START
$scope.showContent = function($fileContent){
$scope.content = $fileContent;
var data_string = $scope.content;
var data = data_string.split(',')
console.log('Plotting Pattern')
console.log(data);
};
//reading from file END
$scope.hour_data=[];
$scope.getPatternForHourAll = function(){
console.log('Hour Pattern Plotting');
var devices = Devices.query({},function(data){
angular.forEach(data,function(device,key){
console.log(device.name);
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+device.name+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.hour_data.push({seriesname:device.name,data:responses});
}).error(function(error){
$scope.hour_data.push({});
});
});
});
};
$scope.hour_data_per_device=[];
$scope.showHourDevicePatternGraph=false;
$scope.getPatternForHourPerDevice= function(deviceName){
$scope.showHourDevicePatternGraph=true;
$scope.hour_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+deviceName+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.hour_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.hour_data_per_device = [];
});
};
//month data extraction starts
$scope.month_data_per_device=[];
$scope.showMonthDevicePatternGraph=false;
$scope.getPatternForMonthPerDevice= function(deviceName){
$scope.showMonthDevicePatternGraph=true;
$scope.month_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/month/'+deviceName+'MonthX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.month_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.month_data_per_device = [];
});
};
//month data extraction ends
//week data extraction starts
$scope.week_data_per_device=[];
$scope.showWeekDevicePatternGraph=false;
$scope.getPatternForWeekPerDevice= function(deviceName){
$scope.showWeekDevicePatternGraph=true;
$scope.week_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/week/'+deviceName+'WeekX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.week_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.week_data_per_device = [];
});
};
//week data extraction ends
//get all pattern data start
$scope.getAllPatternData = function(deviceName){
$scope.getPatternForHourPerDevice(deviceName);
$scope.getPatternForMonthPerDevice(deviceName);
$scope.getPatternForWeekPerDevice(deviceName);
};
// get all pattern data end
$scope.predictionGraphPerHourDevices = function(){
$scope.attrsPredictionHour = {
"caption": "Hour Based",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.attrsPredictionHour1 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionHour = [
{
"category": [
{
"label": "0"
},
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},
{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
}
]
}
];
$scope.dataset = [];
};
//per week analysis
$scope.predictionGraphPerWeekDevices = function(){
$scope.attrsPredictionWeek1 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#69f0ae",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionWeek = [
{
"category": [
{
"label": "Monday"
},
{
"label": "Tuesday"
},
{
"label": "Wednesday"
},
{
"label": "Thursday"
},
{
"label": "Friday"
},
{
"label": "Saturday"
},
{
"label": "Sunday"
}
]
}
];
$scope.dataset = [];
};
//per week analysis ends
//per month analysis starts
$scope.predictionGraphPerMonthDevices = function(){
$scope.attrsPredictionMonth = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionMonth = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},
{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},
{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
$scope.dataset = [];
};
//per month analysis ends
$scope.predictionGraphPerHourDevices();
$scope.predictionGraphPerWeekDevices();
$scope.predictionGraphPerMonthDevices();
//visible prediction and patterns start
$scope.prediction = true;
$scope.pattern = false;
$scope.cost_prediction=false;
// visible prediction and patterns end
$scope.showPredictionTab = function(){
$scope.prediction = true;
$scope.pattern = false;
$scope.cost_prediction=false;
};
$scope.showPatternTab = function(){
$scope.pattern = true;
$scope.prediction = false;
$scope.cost_prediction=false;
};
$scope.showCostPredictionTab =function(){
$scope.pattern = false;
$scope.prediction = false;
$scope.cost_prediction=true;
};
//prediction of usage start
$scope.peak_usage_cost_per_unit = 60.0;
$scope.off_peak_usage_cost_per_unit = 45.0;
$scope.predictionOfUsagePerDevice = function(deviceName){
console.log('Device Name :'+deviceName);
$scope.usage_data=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+deviceName+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push(val);
});
$scope.usage_data.push(responses);
var usage_in_peak=0;
var usage_in_off_peak=0;
var capacity_peak=0;
var capacity_off_peak=0;
//process data start
var off_peak_lower1=18;
var off_peak_upper1=23;
var off_peak_lower2=0;
var off_peak_upper2=6;
var peak_lower=7;
var peak_upper=17;
console.log('Prediction of Usage Per Device');
console.log('==================================');
var length_of_data = responses.length;
console.log('length :'+length_of_data);
for(var i=0;i<length_of_data;i++){
var check_peak = (i>=peak_lower && i<=peak_upper) ;
var check_off_peak1 =(i>=off_peak_lower1 && i<=off_peak_upper1);
var check_off_peak2 =(i>=off_peak_lower2 && i<=off_peak_upper2);
if(check_peak){
if(responses[i]==1){
usage_in_peak= usage_in_peak +1;
capacity_peak= capacity_peak +1;
}
}
if(check_off_peak1){
if(responses[i]==1){
usage_in_off_peak= usage_in_off_peak +1;
capacity_off_peak= capacity_off_peak +1;
}
}
if(check_off_peak2){
if(responses[i]==1){
usage_in_off_peak= usage_in_off_peak +1;
capacity_off_peak= capacity_off_peak +1;
}
}
}
console.log('Peak Hour Usage : '+usage_in_peak);
console.log('Off-Peak Hour Usage : '+usage_in_off_peak);
$scope.usage_in_peak = usage_in_peak;
$scope.usage_in_off_peak = usage_in_off_peak;
//////////////////////////////
var cost_peak = $scope.usage_in_peak * $scope.peak_usage_cost_per_unit;
var cost_off_peak = $scope.usage_in_off_peak * $scope.off_peak_usage_cost_per_unit;
$scope.cost_peak=cost_peak;
$scope.cost_off_peak = cost_off_peak;
$scope.costOptimization($scope.usage_in_peak,$scope.usage_in_off_peak);
$scope.capacityShiftingCapability($scope.usage_in_peak,$scope.usage_in_off_peak);
//process data end
}).error(function(error){
$scope.usage_data = [];
});
};
$scope.cost_saving = 0.0;
$scope.costOptimization = function(usage_peak, usage_off_peak){
var total_cost = usage_peak*$scope.peak_usage_cost_per_unit + usage_off_peak*$scope.off_peak_usage_cost_per_unit;
var new_saving = $scope.off_peak_usage_cost_per_unit*(usage_peak+usage_off_peak);
var cost_saving = total_cost - new_saving;
$scope.cost_saving = cost_saving;
};
$scope.shifting_possible=false;
$scope.capacityShiftingCapability = function(capacity_peak, capacity_off_peak){
var off_peak_lower1=18;
var off_peak_upper1=24;
var off_peak_lower2=0;
var off_peak_upper2=6;
var peak_lower=6;
var peak_upper=18;
var status=false;
var total_off_peak_capacity = (off_peak_upper1 - off_peak_lower1) + (off_peak_upper2-off_peak_lower2);
var total_peak_capacity = (peak_upper-peak_lower);
var capacity_ratio = capacity_peak/capacity_off_peak;
var off_peak_capacity_remainder = total_off_peak_capacity - capacity_off_peak;
var peak_capacity_remainder = total_peak_capacity - capacity_peak;
$scope.peak_capacity_remainder = peak_capacity_remainder;
$scope.off_peak_capacity_remainder = off_peak_capacity_remainder;
console.log('remainder : '+off_peak_capacity_remainder);
console.log('peak capacity : '+capacity_peak);
if(off_peak_capacity_remainder>capacity_peak && capacity_peak>0){
status=true; //resembles cost can be minimized
}else{
status=false; //resembles cost cannot be minimized
}
$scope.shifting_possible=status;
console.log(status);
};
//prediction of usage ends
//prediction of cost STARTS
$scope.getDataOfCostofPastYears = function(){
var units_2014=[65,60,66,103,89,70,68,65,43,44,55,111];
var cost_2014=[521,220,531,1131,761,571,551,521,138,142,196,1353];
var units_2013=[118,88,68,90,71,78,58,58,65,56,74,80];
var cost_2013=[1548,751,551,771,581,651,210,210,521,201,611,671];
var units_2012=[119,108,96,127,113,127,131,145,119,123,100,90];
var cost_2012=[1575,1270,937,1827,1409,1827,1955,2403,1575,1699,1048,771];
var units_2011=[99,96,90,98,126,120,122,141,129,120,121,116];
var cost_2011=[1020,937,771,993,1795,1603,1667,2275,1891,1603,1635,1492];
var units_2010=[134,87,67,124,97,99,81,116,103,90,104,108];
var cost_2010=[2051,741,541,1731,965,1020,681,1492,1131,771,1159,1270];
$scope.attrsPredictionCostOfYear = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.attrsPredictionCostOfYear1 = {
"caption": "Electricty Bills",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesPredictionCostOfYear = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
}
]
}
];
$scope.dataset_cost_past_years = [
{
"seriesname": "2014",
"data": [
{
"value": "521"
},
{
"value": "220"
},
{
"value": "531"
},
{
"value": "1131"
},
{
"value": "761"
},
{
"value": "571"
},
{
"value": "551"
},
{
"value": "521"
},
{
"value": "138"
},
{
"value": "142"
},
{
"value": "196"
},
{
"value": "1353"
}
]
},
{
"seriesname": "2013",
"data": [
{
"value": "1548"
},
{
"value": "751"
},
{
"value": "551"
},
{
"value": "771"
},
{
"value": "581"
},
{
"value": "651"
},
{
"value": "210"
},
{
"value": "210"
},
{
"value": "521"
},
{
"value": "201"
},
{
"value": "611"
},
{
"value": "671"
}
]
},
{
"seriesname": "2012",
"data": [
{
"value": "1575"
},
{
"value": "1270"
},
{
"value": "937"
},
{
"value": "1827"
},
{
"value": "1409"
},
{
"value": "1827"
},
{
"value": "1955"
},
{
"value": "2403"
},
{
"value": "1575"
},
{
"value": "1699"
},
{
"value": "1048"
},
{
"value": "771"
}
]
},
{
"seriesname": "2011",
"data": [
{
"value": "1020"
},
{
"value": "937"
},
{
"value": "771"
},
{
"value": "993"
},
{
"value": "1795"
},
{
"value": "1603"
},
{
"value": "1667"
},
{
"value": "2275"
},
{
"value": "1891"
},
{
"value": "1603"
},
{
"value": "1635"
},
{
"value": "1492"
}
]
},
{
"seriesname": "2010",
"data": [
{
"value": "2051"
},
{
"value": "741"
},
{
"value": "541"
},
{
"value": "1731"
},
{
"value": "965"
},
{
"value": "1020"
},
{
"value": "681"
},
{
"value": "1492"
},
{
"value": "1131"
},
{
"value": "771"
},
{
"value": "1159"
},
{
"value": "1270"
}
]
}
];
};
$scope.predictionOfCostNextYear = function(){
$scope.attrsPredictionCostOfYear2014 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
/* "bgImage": "img/background/elec1.jpg",
"baseFontColor": "red",*/
"captionFontSize": "18",
"subcaptionFontSize": "16",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.attrsPredictionCostOfYear12014 = {
"caption": "Electricty Bills",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesPredictionCostOfYear2014 = [
{
"category": [
{
"label": "July"
},
{
"label": "August"
},
{
"label": "Sepetember"
},
{
"label": "October"
},
{
"label": "November"
},
{
"label": "December"
}
]
}
];
$scope.dataset_cost_past_years2014 = [
{
"seriesname": "2015 Prediction Bill",
"data": [
{
"value": "70"
},
{
"value": "65"
},
{
"value": "66"
},
{
"value": "103"
},
{
"value": "65"
},
{
"value": "65"
}
]
},
{
"seriesname": "2015 Real Bill",
"data": [
{
"value": "68"
},
{
"value": "65"
},
{
"value": "43"
},
{
"value": "44"
},
{
"value": "55"
},
{
"value": "111"
}
]
}
];
};
//prediction of cost ENDS
//predictions END
//
$scope.init();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
]).config( function($mdThemingProvider){
// Configure a dark theme with primary foreground yellow
$mdThemingProvider.theme('docs-dark', 'default')
.primaryPalette('yellow')
.dark();
});
angular.module('dashboards').controller('InsideCtrl', function ($scope, ngDialog) {
$scope.dialogModel = {
message : 'message from passed scope'
};
$scope.openSecond = function () {
ngDialog.open({
template: '<h3><a href="" ng-click="closeSecond()">Close all by click here!</a></h3>',
plain: true,
closeByEscape: false,
controller: 'SecondModalCtrl'
});
};
});
angular.module('dashboards').controller('InsideCtrlAs', function () {
this.value = 'value from controller';
});
angular.module('dashboards').controller('SecondModalCtrl', function ($scope, ngDialog) {
$scope.closeSecond = function () {
ngDialog.close();
};
});
//ngDialog Controlling Section End
////////////////////////////////////////////
//angular tables
app.directive('mdTable', function () {
return {
restrict: 'E',
scope: {
headers: '=',
content: '=',
sortable: '=',
filters: '=',
customClass: '=customClass',
thumbs:'=',
count: '='
},
controller: function ($scope,$filter,$window) {
var orderBy = $filter('orderBy');
$scope.tablePage = 0;
$scope.nbOfPages = function () {
return Math.ceil($scope.content.length / $scope.count);
},
$scope.handleSort = function (field) {
if ($scope.sortable.indexOf(field) > -1) { return true; } else { return false; }
};
$scope.order = function(predicate, reverse) {
$scope.content = orderBy($scope.content, predicate, reverse);
$scope.predicate = predicate;
};
$scope.order($scope.sortable[0],false);
$scope.getNumber = function (num) {
return new Array(num);
};
$scope.goToPage = function (page) {
$scope.tablePage = page;
};
},
template: angular.element(document.querySelector('#md-table-template')).html()
}
});
app.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
/*app.directive('mdColresize', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$evalAsync(function () {
$timeout(function(){ $(element).colResizable({
liveDrag: true,
fixed: true
});},100);
});
}
}
});*/
app.filter('startFrom', function() {
return function(input, start) {
if (!input || !input.length) { return; }
start = +start; //parse to int
return input.slice(start);
}
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
$scope.devicename="Name of the device";
$scope.deviceDetails= $scope.deviceProfile_SelectedDevice;
}
|
vibhatha/digitalocean_7
|
public/dashboards/controllers/dashboards.client.controller.js
|
JavaScript
|
mit
| 177,333
|
#--
# Copyright (c) 2010-2011 Engine Yard, Inc.
# Copyright (c) 2007-2009 Sun Microsystems, Inc.
# This source code is available under the MIT license.
# See the file LICENSE.txt for details.
#++
# This is a fake Rails config/environment file to be used during testing.
RAILS_ROOT = ENV['RAILS_ROOT']
RAILS_ENV = ENV['RAILS_ENV']
# Simulate the Rails 2.0 boot process here, to test our boot hook
module Rails
class << self
def boot!
unless booted?
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
Boot.new
end
end
class Boot
def run
require 'initializer'
Rails::Initializer.run(:set_load_path)
end
end
end
Rails.boot!
Rails::Initializer.run
|
atambo/jruby-rack
|
src/spec/ruby/rails/config/environment.rb
|
Ruby
|
mit
| 764
|
var process = function (json) {
var x = 0,
r = Raphael("chart", 2350, 550),
labels = {},
textattr = {"font": '9px "Arial"', stroke: "none", fill: "#fff"},
pathes = {},
nmhldr = $("#name")[0],
nmhldr2 = $("#name2")[0],
lgnd = $("#legend")[0],
usrnm = $("#username")[0],
lgnd2 = $("#legend2")[0],
usrnm2 = $("#username2")[0],
plchldr = $("#placeholder")[0];
function finishes() {
for (var i in json.authors) {
var start, end;
for (var j = json.buckets.length - 1; j >= 0; j--) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
}
if (isin) {
end = j;
break;
}
}
for (var j = 0, jj = json.buckets.length; j < jj; j++) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
};
if (isin) {
start = j;
break;
}
}
for (var j = start, jj = end; j < jj; j++) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
}
if (!isin) {
json.buckets[j].i.push([i, 0]);
}
}
}
}
function block() {
var p, h;
finishes();
for (var j = 0, jj = json.buckets.length; j < jj; j++) {
var users = json.buckets[j].i;
h = 0;
for (var i = 0, ii = users.length; i < ii; i++) {
p = pathes[users[i][0]];
if (!p) {
p = pathes[users[i][0]] = {f:[], b:[]};
}
p.f.push([x, h, users[i][1]]);
p.b.unshift([x, h += Math.max(Math.round(Math.log(users[i][1]) / Math.log(1.2) * 2.5), 1)]);
h += 2;
}
var dt = new Date(json.buckets[j].d * 1000);
var dtext = dt.getDate() + "." + (dt.getMonth()+1) + "." + dt.getFullYear();
r.text(x + 25, h + 10, dtext).attr({"font": '9px "Arial"', stroke: "none", fill: "#aaa"});
x += 100;
}
var c = 0;
for (var i in pathes) {
labels[i] = r.set();
var clr = Raphael.getColor();
pathes[i].p = r.path().attr({fill: clr, stroke: clr});
var path = "M".concat(pathes[i].f[0][0], ",", pathes[i].f[0][1], "L", pathes[i].f[0][0] + 50, ",", pathes[i].f[0][1]);
var th = Math.round(pathes[i].f[0][1] + (pathes[i].b[pathes[i].b.length - 1][1] - pathes[i].f[0][1]) / 2 + 3);
labels[i].push(r.text(pathes[i].f[0][0] + 25, th, pathes[i].f[0][2]).attr(textattr));
var X = pathes[i].f[0][0] + 50,
Y = pathes[i].f[0][1];
for (var j = 1, jj = pathes[i].f.length; j < jj; j++) {
path = path.concat("C", X + 20, ",", Y, ",");
X = pathes[i].f[j][0];
Y = pathes[i].f[j][1];
path = path.concat(X - 20, ",", Y, ",", X, ",", Y, "L", X += 50, ",", Y);
th = Math.round(Y + (pathes[i].b[pathes[i].b.length - 1 - j][1] - Y) / 2 + 3);
if (th - 9 > Y) {
labels[i].push(r.text(X - 25, th, pathes[i].f[j][2]).attr(textattr));
}
}
path = path.concat("L", pathes[i].b[0][0] + 50, ",", pathes[i].b[0][1], ",", pathes[i].b[0][0], ",", pathes[i].b[0][1]);
for (var j = 1, jj = pathes[i].b.length; j < jj; j++) {
path = path.concat("C", pathes[i].b[j][0] + 70, ",", pathes[i].b[j - 1][1], ",", pathes[i].b[j][0] + 70, ",", pathes[i].b[j][1], ",", pathes[i].b[j][0] + 50, ",", pathes[i].b[j][1], "L", pathes[i].b[j][0], ",", pathes[i].b[j][1]);
}
pathes[i].p.attr({path: path + "z"});
labels[i].hide();
var current = null;
(function (i) {
pathes[i].p.mouseover(function () {
if (current != null) {
labels[current].hide();
}
current = i;
labels[i].show();
pathes[i].p.toFront();
labels[i].toFront();
usrnm2.innerHTML = json.authors[i].n + " <em>(" + json.authors[i].c + " votes, " + json.authors[i].a + " for, " + json.authors[i].d + " against)</em>";
lgnd2.style.backgroundColor = pathes[i].p.attr("fill");
nmhldr2.className = "";
plchldr.className = "hidden";
});
})(i);
}
}
if (json.error) {
alert("Project not found. Try again.");
} else {
block();
}
};
$(function () {
process(json);
});
|
avoinministerio/avoinministerio
|
app/assets/javascripts/vote-flow/impact-code.js
|
JavaScript
|
mit
| 5,200
|
"""
The following tests that db connections works properly.
Make sure the default configurations match your connection to the database
"""
import pymysql
import warnings
warnings.filterwarnings("ignore")
from StreamingSQL.db import create_connection, execute_command
from StreamingSQL.fonts import Colors, Formats
"""Default configuration to connect to the DB"""
host = 'localhost'
port = 3306
usr = 'root'
paswd = ''
db = 'test'
def test_default_create_connection():
"""
Test the connection to database
Assert:
Connection occurs
"""
cur = create_connection(host=host, port=port, user=usr, password=paswd, db=db)
assert type(cur) == pymysql.cursors.Cursor
def test_wrong_host_fail_create_connection():
"""
Test that error is properly returned when there is an incorrect host
Assert:
Proper error is returned/formatted
"""
error = "2003: Cant connect to MySQL server on '%s' [Errno 61] Connection refused"
error = (Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) % host[:-3]
cur = create_connection(host=host[:-3], port=port, user=usr, password=paswd, db=db)
try:
assert cur == error
except AssertionError:
pass
def test_wrong_port_fail_create_connection():
"""
Test that error is properly returned when there is an incorrect port number
Assert:
Proper error is returned/formatted
"""
error = "2003: Cant connect to MySQL server on '%s' [Errno 61] Connection refused"
error = (Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) % host
cur = create_connection(host=host, port=port + 13, user=usr, password=paswd, db=db)
try:
assert cur == error
except AssertionError:
pass
def test_wrong_user_fail_create_connection():
"""
Test that error is properly returned when there is an incorrect user
Assert:
Proper error is returned/formatted
"""
error = "2003: Cant connect to MySQL server on '%s' [Errno 61] Connection refused"
error = (Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) % host
cur = create_connection(host=host, port=port, user='', password=paswd, db=db)
try:
assert cur == error
except AssertionError:
pass
def test_wrong_passwd_fail_create_connection():
"""
Test that error is properly returned when there is an incorrect password
Assert:
Proper error is returned/formatted
"""
error = "2003: Cant connect to MySQL server on '%s' [Errno 61] Connection refused"
error = (Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) % host
cur = create_connection(host=host, port=port, user=usr, password=usr, db=db)
try:
assert cur == error
except AssertionError:
pass
def test_execute_command():
"""
Execute "SELECT 1;"
Assert:
A result of 1 is returned
"""
cur = create_connection(host=host, port=port, user=usr, password=paswd, db=db)
assert type(cur) == pymysql.cursors.Cursor
stmt = "SELECT 1"
result = execute_command(cur, stmt)
assert result[0][0] == 1
def test_syntax_fail_execute_command():
"""
Execute "SLCT 1;"
Assert:
An error message is returned
"""
stmt = "SLCT 1"
error = ("1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server "+
"version for the right syntax to use near '%s' at line 1")
error = Formats.BOLD + Colors.RED + "Connection Error - " + error % stmt + Formats.END + Colors.END
cur = create_connection(host=host, port=port, user=usr, password=paswd, db=db)
assert type(cur) == pymysql.cursors.Cursor
result = execute_command(cur, stmt)
try:
assert result == error
except AssertionError:
pass
def test_new_db_create_connection():
"""
Create a connection to a new database
Assert:
New database is created/removed
"""
db="db2"
cur = create_connection(host=host, port=port, user=usr, password=paswd, db=db)
assert type(cur) == pymysql.cursors.Cursor
stmt = "SELECT `SCHEMA_NAME` from `INFORMATION_SCHEMA`.`SCHEMATA` WHERE `SCHEMA_NAME` LIKE '%s';" % db
result = execute_command(cur, stmt)
assert result[0][0] == db
stmt = "FLUSH TABLES; DROP DATABASE IF EXISTS %s;" % db
result = execute_command(cur, stmt)
assert result == ()
|
oshadmon/StreamingSQL
|
tests/test_db.py
|
Python
|
mit
| 4,584
|
<?php
namespace Likeme\SystemBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Likeme\SystemBundle\Extension\GetLinksForImagine;
use Likeme\SystemBundle\Entity\Pictures;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Gaufrette\Filesystem;
class AfterLoginController extends Controller
{
/**
* @Route("/afterlogin", name="after_login", options={"expose"=true})
*/
public function afterloginAction()
{
$em = $this->get('doctrine')->getEntityManager();
$user = $this->container->get('security.context')->getToken()->getUser();
// Check if user has already an image
$savedpictures = array();
foreach($user->getPictures() as $pic) {
$savedpictures[] = $pic->getSrc();
}
// If not, likeme takes one profile picture form facebook
if (!$savedpictures) {
// Get Facebook Service
$fosfbservice = $this->container->get('my.facebook.user');
$facebook = $fosfbservice->getFacebookObj();
$user = $fosfbservice->loadUserByUsername($user->getUsername());
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (\Exception $e) {
}
}
//Get AccessToken
$token = $facebook->getAccessToken();
//Receive a list with all albums from user
$extAlbumUrl = "https://graph.facebook.com/".$user_profile['id']."/albums?fields=id,name,type&access_token=".$token."&limit=0";
// Get Content also if there is a HTTP error code (ex. 400)
//Set stream options
$opts = array(
'http' => array('ignore_errors' => true)
);
$context = stream_context_create($opts);
$content = file_get_contents($extAlbumUrl, false, $context);
$response = json_decode($content, true);
// Check for errors
if (isset($response['error'])) {
//if ($response['error']['type'] == "OAuthException") {
throw new \OAuthException;
//}
} else {
// Loop trough albums and receive photos
$albums = $response['data'];
$foundonephoto = false;
foreach ($albums as $row)
{
// Only if Album is ProfilePictures
if ($row['type'] == 'profile')
{
// Print out the pictures from album
$contents = file_get_contents("https://graph.facebook.com/" . $row['id'] . "/photos?access_token=".$token."&limit=1");
$photos = json_decode($contents,true);
// Saving profile photo
$photo = $photos['data'];
if ($photo) {
// Min. 1 profile picture was found
$foundonephoto = true;
// Amazone Filesystem erstellen
define("AWS_CERTIFICATE_AUTHORITY", true);
$filesystem = $this->container->get('gaufrette.filesystem.media_cache');
// Get Facebook ID
$userfcbkid = $user_profile['id'];
// Bilderordner in Amazon S3 erstellen falls er noch nicht existiert
if ( ! $filesystem->has($userfcbkid."/images/profile/")) {
$filesystem->write($userfcbkid."/images/profile/","");
}
// Get Filename with and without filetype
$link = $photo[0]['source'];
$filenamewithtype = substr(strrchr($link, "/"),1);
$filename = strstr($filenamewithtype, '.', true);
// Save image if not already on amazon
if ( ! $filesystem->has($userfcbkid."/images/profile/".$filenamewithtype)) {
$content = file_get_contents($link);
$filesystem->write($userfcbkid."/images/profile/".$filenamewithtype, $content);
}
// Make a new picture object
$picture = new Pictures();
$picture->setSrc("http://likeme.s3.amazonaws.com/" . $userfcbkid."/images/profile/".$filenamewithtype);
$picture->setTimestamp(new \DateTime());
$picture->setType('original');
$picture->setUser($user);
$picture->setPosition(1);
$em->persist($picture);
$em->flush();
// Get updated pictures ($user obj isn't up to date)
$query = $em->createQueryBuilder()
->from('Likeme\SystemBundle\Entity\Pictures', 'p')
->select("p.src")
->where("p.user = :userid AND p.type = :type")
->setParameter('userid', $user->getId())
->setParameter('type', 'original');
$allpictures = $query->getQuery()->getResult();
// Edit picture links for LiipImagineBundle
$imagineservice = $this->container->get('likeme.liipimaginebundle.getlinks');
$imaginelinks = $imagineservice->editLinksForGeneration($allpictures);
// Generate thumbnails on amazon s3 for each picture
foreach($imaginelinks as $link) {
$this->container
->get('liip_imagine.controller')
->filterAction($this->getRequest(), $link['thumb'], 'thumbnails');
}
}
}
}
//No profile photo has been found => deactivate User
if ($foundonephoto == false) {
$user->setActive(0);
$em->persist($user);
$em->flush();
}
}
}
/**
* Save daily stranger array in session
*/
// UserService abrufen
$UserService = $this->container->get('likeme.user.userservice');
$strangers = $UserService->getStranger();
//update session
if($UserService->checkStrangerSessionEmpty($strangers) == false){
$UserService->setStrangers($strangers);
}
return new RedirectResponse($this->container->get('router')->generate('home'));
}
}
|
backender/likeme
|
src/Likeme/SystemBundle/Controller/AfterLoginController.php
|
PHP
|
mit
| 6,441
|
<?php
namespace Bolt\Extension\Leskis\BoltSimpleCommentSystem;
use Bolt\Asset\File\JavaScript;
use Bolt\Asset\File\Stylesheet;
use Bolt\Events\StorageEvent;
use Bolt\Events\StorageEvents;
use Bolt\Extension\Leskis\BoltSimpleCommentSystem\Controller\CommentController;
use Bolt\Extension\Leskis\BoltSimpleCommentSystem\Entity\Comment;
use Bolt\Extension\Leskis\BoltSimpleCommentSystem\Form\CommentForm;
use Bolt\Extension\SimpleExtension;
use \Bolt\Storage\Entity\Content;
use Silex\Application;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
/**
* BoltSimpleCommentSystem extension class.
*
* @author Nicolas Béhier-Dévigne
*/
class BoltSimpleCommentSystemExtension extends SimpleExtension
{
/**
* The callback function when {{ bscs_list_comments() }} is used in a template.
*
* @return string
*/
public function listCommentsFunction($context)
{
$config = $this->getConfig();
$html = $this->renderTemplate($config['templates']['list'], $context);
return new \Twig_Markup($html, 'UTF-8');
}
/**
* The callback function when {{ bscs_count_comments() }} is used in a template.
*
* @return string
*/
public function countCommentsFunction($context)
{
$app = $this->getContainer();
$guid = $context['guid'];
$repo = $app['storage']->getRepository('comments');
$aComments = $repo->findBy([
'guid' => $guid,
'status' => 'published'
],[],9999);
return count($aComments);
}
/**
* The callback function when {{ bscs_add_comment() }} is used in a template.
*
* @return string
*/
public function addCommentFunction($context)
{
$app = $this->getContainer();
$config = $this->getConfig();
$comment = new Comment();
$comment->setGuid($context['guid']);
// @see https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-symfony2/creer-des-formulaires-avec-symfony2
$formBuilder = $app['form.factory']->createBuilder(new CommentForm(), $comment)
->setAction($app['url_generator']->generate('bscs-comment-save') )//'/bscs-comment/save')
->setMethod('POST');
if ( $config['features']['questions']['enabled'] ) {
$aQuestion = $formBuilder->chooseARandomQuestion($config);
if ( $aQuestion !== false ) {
$uniqID = $formBuilder->uniqID($aQuestion['question']);
$formBuilder->add( 'question',
'text',
[
'label' => $aQuestion['question'],
'required' => true,
'mapped' => false
]
)
->add('questionuniq',
'hidden',
[
'data' => $uniqID,
'mapped' => false
]
);
}
}
$form = $formBuilder->getForm();
// Render the Twig
$html = $app['render']->render(
$config['templates']['form'], [
'form' => $form->createView()
]
);
return new \Twig_Markup($html, 'UTF-8');
}
public function gravatarTwigFilter($input)
{
return $this->uniqID($input);
}
private function uniqID($input)
{
return md5(trim(strtolower($input ) ) );
}
/**
* {@inheritdoc}
*/
protected function subscribe(EventDispatcherInterface $dispatcher)
{
// Pre-save hook
$dispatcher->addListener(StorageEvents::PRE_SAVE, [$this, 'hookPreSave']);
}
/**
* Pre-save hook
* @param \Bolt\Events\StorageEvent $event
*/
public function hookPreSave(StorageEvent $event)
{
$app = $this->getContainer();
$config = $this->getConfig();
$contenttype = $event->getContentType();
if ( empty($contenttype)
|| ! $config['features']['notify']['enabled']
|| $contenttype != 'comments' ) {
return;
}
// Get the record : Bolt\Storage\Entity\Content
// @todo : in fact, it returns a Bolt\Legacy\Content… why ?
// So I can't use $record->getStatus() but $record->values['status']…
// dump($record); die();
$record = $event->getContent();
$recordStatus = $record->values['status'];
$recordId = $record->values['id'];
$recordGuid = $record->values['guid'];
$recordAuthorEmail = $record->values['author_email'];
// Test if newly published
$contentNewlyPublished = false;
if ( $event->isCreate()
&& $recordStatus == 'published') {
$contentNewlyPublished = true;
}
else if ($recordStatus == 'published') {
// @todo : check if notification already sent
// use a temporary file or a db table ?
$repo = $app['storage']->getRepository($contenttype);
$oldRecord = $repo->find($recordId );
if ( !empty($oldRecord)
&& $oldRecord->getStatus() != 'published') {
$contentNewlyPublished = true;
}
}
if ($contentNewlyPublished) {
// Launch the notification
$notify = new Notifications($app, $config, $record);
// Search subscribers
try {
$aSubscribers = $this->getSubscribers($recordGuid, $recordAuthorEmail );
// Send email foreach subscriber
$notify->doNotification($aSubscribers);
} catch (\Exception $e) {
$app['logger.system']->error(sprintf("BoltSimpleCommentSystemExtension notifications can't be sent - %s", $e->getMessage() ), ['event' => 'extensions']);
return;
}
}
return;
}
/**
* Get Subscribers for notifications
* @return array email
*/
private function getSubscribers($guid, $sExcludeEmail)
{
$app = $this->getContainer();
$config = $this->getConfig();
$aSubscribers = false;
$repo = $app['storage']->getRepository('comments');
$aComments = $repo->findBy([
'guid' => $guid,
'status' => 'published',
'notify' => true
]);
if ($aComments) {
// @todo Do not sent email to owner
$aSubscribers = [];
$guidExcludeEmail = $this->uniqID($sExcludeEmail);
foreach ($aComments as $aComment) {
$emailUniq = $this->uniqID($aComment['author_email']);
if ( $guidExcludeEmail != $emailUniq ) {
$aSubscribers[$emailUniq] = [
'author_name' => $aComment['author_display_name'],
'author_email' => $aComment['author_email']
];
}
}
}
return $aSubscribers;
}
/**
* {@inheritdoc}
*
* Mount the ExampleController class to all routes that match '/example/url/*'
*
* To see specific bindings between route and controller method see 'connect()'
* function in the ExampleController class.
*/
protected function registerFrontendControllers()
{
$config = $this->getConfig();
return [
'/bscs-comment' => new CommentController($config),
];
}
/**
* {@inheritdoc}
*/
protected function registerAssets()
{
$assets = [];
$config = $this->getConfig();
if ( $config['assets']['frontend']['load_css'] ) {
$main_css = new Stylesheet();
$main_css->setFileName('simplecommentsystem.css');
$assets[] = $main_css;
}
if ( $config['assets']['frontend']['load_js'] ) {
$main_js = new JavaScript();
$main_js->setFileName('simplecommentsystem.js')
->setLate(true)
->setPriority(99);
$assets[] = $main_js;
}
if ( $config['assets']['frontend']['load_js']
&& $config['features']['gravatar']['enabled'] ) {
$gravatar_js = new JavaScript();
$gravatar_js->setFileName('blueimp-md5/js/md5.min.js')
->setLate(true)
->setPriority(98);
$assets[] = $gravatar_js;
}
if ( $config['assets']['frontend']['load_js']
&& $config['features']['mention']['enabled'] ) {
$mention_js = new JavaScript();
$mention_js->setFileName('tribute/dist/tribute.min.js')
->setLate(true)
->setPriority(98);
$mention_css = new Stylesheet();
$mention_css->setFileName('tribute/dist/tribute.css');
$assets[] = $mention_js;
$assets[] = $mention_css;
}
if ( $config['assets']['frontend']['load_js']
&& $config['features']['emoticons']['enabled'] ) {
$emoticons_js = new JavaScript();
$emoticons_js->setFileName('jQuery-CSSEmoticons/javascripts/jquery.cssemoticons.min.js')
->setLate(true)
->setPriority(97);
$emoticons_css = new Stylesheet();
$emoticons_css->setFileName('jQuery-CSSEmoticons/stylesheets/jquery.cssemoticons.css');
$assets[] = $emoticons_css;
$assets[] = $emoticons_js;
}
return $assets;
}
protected function registerServices(Application $app)
{
$app['bolt-simple-comment.config'] = $app->share(
function ($app) {
return new ParameterBag($this->getConfig() );
}
);
}
/**
* {@inheritdoc}
*/
protected function registerTwigPaths()
{
return ['templates'];
}
/**
* {@inheritdoc}
*/
protected function registerTwigFunctions()
{
return [
'bscs_list_comments' => 'listCommentsFunction',
'bscs_add_comment' => 'addCommentFunction',
'bscs_count_comments' => 'countCommentsFunction'
];
}
/**
* {@inheritdoc}
*/
protected function registerTwigFilters()
{
return [
'bscs_gravatar' => 'gravatarTwigFilter'
];
}
/**
* {@inheritdoc}
*/
protected function getDefaultConfig()
{
return [
'features' => [
'comments' => [
'order' => 'asc',
'default_approve' => true
],
'questions' => [
'enabled' => false
],
'gravatar' => [
'enabled' => true,
'url' => 'https://www.gravatar.com/avatar/XXX?s=40&d=mm'
],
'emoticons' => [
'enabled' => true,
'animate' => false
],
'notify' => [
'enabled' => true,
'debug' => [
'enabled' => true,
'address' => 'noreply@example.com'
],
'email' => [
'from_name' => 'Your website',
'from_email' => 'your-email@your-website.com',
'replyto_name' => '',
'replyto_email' => ''
]
]
],
'templates' => [
'form' => 'bscs_form_comment.twig',
'list' => 'bscs_list_comments.twig',
'emailbody' => 'bscs_email_body.twig',
'emailsubject' => 'bscs_email_subject.twig'
],
'assets' => [
'frontend' => [
'load_js' => true,
'load_css' => true
]
]
];
}
/**
* {@inheritdoc}
*/
public function getDisplayName()
{
return 'Simple comment system';
}
}
|
nbehier/bolt-simple-comment-system
|
src/BoltSimpleCommentSystemExtension.php
|
PHP
|
mit
| 12,695
|
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import mutations from './mutations';
import state from './state';
Vue.use(Vuex);
export default () =>
new Vuex.Store({
actions,
mutations,
state,
});
|
stoplightio/gitlabhq
|
app/assets/javascripts/releases/detail/store/index.js
|
JavaScript
|
mit
| 254
|
# Contributing to Electron Forge
Electron Forge is a community-driven project. As such, we welcome and encourage all sorts of
contributions. They include, but are not limited to:
- Constructive feedback
- [Questions about usage](#questions-about-usage)
- [Bug reports / technical issues](#before-opening-bug-reportstechnical-issues)
- [Documentation changes](#documentation-changes)
- Feature requests
- [Pull requests](#filing-pull-requests)
We strongly suggest that before filing an issue, you search through the existing issues to see
if it has already been filed by someone else.
This project is a part of the Electron ecosystem. As such, all contributions to this project follow
[Electron's code of conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md)
where appropriate.
## Questions about usage
If you have questions about usage, we encourage you to visit one of the several [community-driven
sites](https://github.com/electron/electron#community).
## Before opening bug reports/technical issues
### Debugging
Troubleshooting suggestions can be found in the [support
documentation](https://github.com/electron-userland/electron-forge/blob/master/SUPPORT.md#troubleshooting).
## Contribution suggestions
We use the label [`help wanted`](https://github.com/electron-userland/electron-forge/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)
in the issue tracker to denote fairly-well-scoped-out bugs or feature requests that the community
can pick up and work on. If any of those labeled issues do not have enough information, please feel
free to ask constructive questions. (This applies to any open issue.)
## Documentation changes
When changing the API documentation, here are some rules to keep in mind.
- The first line:
- should end with a period
- should be in imperative mood (e.g., "Create" instead of "Creates")
- First line should not be the function's "signature"
- The first word of the first line:
- should be properly capitalized
- should not be "This"
For changes to the website ([electronforge.io](https://www.electronforge.io)), please file
issues/pull requests at [its separate repository](https://github.com/electron-forge/electron-forge-docs).
## Changing the Code
Getting the code base running locally requires the `bolt` command installed globally. An example is given below.
```bash
npm i -g bolt
git clone https://github.com/electron-userland/electron-forge
cd electron-forge
# Installs all dependencies, don't run "yarn" or "npm install" yourself
bolt
# Builds all the TS code
bolt build
```
### Making Commits
Please ensure that all changes are committed using [semantic commit messages](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md).
We expose a helper (`bolt commit`) to make this easier.
### Running the Tests
The Electron Forge repository has a lot of tests, some of which take a decent
amount of time to run.
```bash
bolt test
```
## Filing Pull Requests
Here are some things to keep in mind as you file pull requests to fix bugs, add new features, etc.:
- GitHub Actions are used to make sure that the project builds packages as expected on the
supported platforms, using supported Node.js versions, and that the project conforms to the
configured coding standards.
- Unless it's impractical, please write tests for your changes. This will help us so that we can
spot regressions much easier.
- If your PR changes the behavior of an existing feature, or adds a new feature, please add/edit
the package's documentation.
- Commit messages and pull request titles should adhere to the [Conventional Commits
format](https://www.conventionalcommits.org/en/v1.0.0/).
- One of the philosophies of the project is to keep the code base as small as possible. If you are
adding a new feature, think about whether it is appropriate to go into a separate Node module,
and then be integrated into this project.
- Please **do not** bump the version number in your pull requests, the maintainers will do that.
Feel free to indicate whether the changes are a breaking change in behavior.
- If you are continuing the work of another person's PR and need to rebase/squash, please retain the
attribution of the original author(s) and continue the work in subsequent commits.
### Release process
- if you aren't sure if a release should happen, open an issue
- make sure the tests pass
- `./tools/bump.ts $NEW_VERSION`
- `node tools/publish.js`
|
electron-userland/electron-forge
|
CONTRIBUTING.md
|
Markdown
|
mit
| 4,483
|
from app import app
import argparse
import os
import routes
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Run the MightySpring backend server.')
parser.add_argument('--debug',
'-d',
default=True)
parser.add_argument('--port',
'-p',
nargs='?',
default=int(os.environ.get('PORT', 5000)),
type=int)
parser.add_argument('--bind-address',
'-b',
nargs='?',
default=u'0.0.0.0',
type=unicode)
args = parser.parse_args()
debug = args.debug
port = args.port
bind_address = args.bind_address
app.run(host=bind_address, port=port, debug=debug)
|
texuf/myantname
|
main.py
|
Python
|
mit
| 869
|
+++
Categories = ["开发工具", "Linux"]
Description = ""
Tags = ["程序员", "开发工具"]
date = "2017-06-15T16:01:02+08:00"
title = "优雅的使用 Linux"
+++
# 起头
*Linux 是我最喜欢的操作系统之一,平时用的最多的是 CentOS,Linux 的强悍不是我只言片语能描述清楚的,这篇博文将以事件记录的形式随时收集记录我平时所遇到的一些工具、命令、故障等。*
# 网络工具包
## host、nslookup、dig 等
*平时经常用的几个命令 `host`,`nslookup`,`dig` 等,新装的 CentOS 虚拟机运行 `host` 命令既然报 “找不到这个命令”*
`sudo yum install host`,并没有这个包的安装,谷歌后发现 `host` 命令属于网络工具包中的一个。
下面列出各个发行版对应的包安装方式:
```bash
Ubuntu:# sudo apt-get install dnsutils
Debian: # apt-get install dnsutils
Fedora / Centos: # yum install bind-utils
```
## tcpdump
*抓包分析 Vanilla 单次请求 sudo tcpdump -i any port 9110 -X -s 0 -S*
* -X表明当分析和打印时, tcpdump 会打印每个包的头部数据, 同时会以16进制和ASCII码形式打印出每个包的数据(但不包括连接层的头部)。
* -S表明打印TCP 数据包的顺序号时, 使用绝对的顺序号, 而不是相对的顺序号.比如我第一次用tcpdump查看tcp的三次握手时发现第三次握手的ack=1,这个ack就是相对的,因为tcpdump只在SYN包中显示绝对顺序号,而非SYN包则显示相对的,为了便于观察,在抓包时都采用来绝对的顺序号。
http://www2.meps.tp.edu.tw/documents/memo/TCP%EF%BC%8FIP%E6%A6%82%E8%AB%96/index.htm
http://xstarcd.github.io/wiki/shell/tcpdump_TCP_three-way_handshake.html
http://linuxwiki.github.io/NetTools/tcpdump.html

# json 命令行解析工具 `jq`
来自 IBM 的[文档](https://www.ibm.com/developerworks/cn/linux/1612_chengg_jq/index.html)
项目 [官方文档](https://stedolan.github.io/jq/manual/)
```bash
curl -s 'http://register.kailash.weibo.com:80/naming/service?action=lookup&service=yf-api-core&cluster=com.weibo.api.grpc.service.Statuses/service' |jq -r .body|jq ".nodes|.working[]"echo '{"name":"tom"}' |jq .
echo '{"name":"tom"}' |jq -r .
echo '{"name":"tom"}' |jq -c .
echo '{"name":"tom"}' |jq -R .
echo '{"name":"tom"}' '{"name":"tom"}' |jq -s .
jq -n '([1,2]|.[])+([4,6]|.[])'
jq -n 'a={"a":{"b":1}}, b={"a":{"c":2}}'
echo '[1,2,3,4]'| jq -r 'map(.+1)'
jq -nr '[1,2,3]|length as $arraylen|$arraylen+1'
jq -nr '{"firstname":"tom","lastname":"clancy"}|. as {firstname:$fn, lastname:$ln}|"author is "+$fn+"*"+$ln'
jq -nr '{"firstname":"tom","lastname":"clancy"}|def fname:. as {firstname:$fn, lastname:$ln}|$fn; fname|$fn'
jq -nr '{"firstname":"tom","lastname":"clancy"}|def fname:. as {firstname:$fn, lastname:$ln}|$fn; fname'
jq -nr '{"firstname":"tom","lastname":"clancy"}|def fname:. as {firstname:$fn, lastname:$ln}|$fn + "----" + $ln; fname'
jq -nr 'reduce ([1,2,3]|.[]) as $item (0; .+$item)'
jq -nr '[1,2,3]|.[]'
jq -cnr 'reduce ([1,2,3]|.[]) as $item (0; .+$item)'
jq -nr '0 | (3 as $item|.+$item)|(2 as $item | . + $item)|(1 as $item | . + $item)'
jq -cnr 'reduce (["x1","x2","x3"]|.[]) as $item ("xx"; .+$item)'
jq -nr 'foreach ([1,2,3]|.[]) as $item (0; .+$item;.)'
jq -nr 'first([1,2,3]|.[])'
```
## cmake
```bash
❯ cmake --version z@z
CMake Error: Could not find CMAKE_ROOT !!!
CMake has most likely not been installed correctly.
Modules directory not found in
/usr/local/bin
[1] 19038 segmentation fault cmake --version
```
export CMAKE_ROOT=/usr/local/share/cmake-3.10
## pstack
# 待消化的工具 http://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/pstack.html
|
idevz/idevz.org
|
content/tools/linux-tools.md
|
Markdown
|
mit
| 3,840
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class MPlayerPanel extends JPanel {
private JButton playButton, stopButton, exitButton, loadMp3Button, saveButton, openButton;
private JTable table = null;
Library library = new Library();
boolean buttonClicked = false;
MPlayerPanel() {
this.setLayout(new BorderLayout());
// buttonPanelTop contains the top row of buttons:
// load mp3 files, save and open
JPanel buttonPanelTop = new JPanel();
buttonPanelTop.setLayout(new GridLayout(1,3));
loadMp3Button = new JButton("Load mp3");
saveButton = new JButton("Save Library");
openButton = new JButton("Load Library");
loadMp3Button.addActionListener(new MyButtonListener());
saveButton.addActionListener(new MyButtonListener());
openButton.addActionListener(new MyButtonListener());
buttonPanelTop.add(loadMp3Button);
buttonPanelTop.add(saveButton);
buttonPanelTop.add(openButton);
this.add(buttonPanelTop, BorderLayout.NORTH);
// Bottom panel with panels: Play, Stop, Exit buttons
JPanel buttonPanelBottom = new JPanel();
buttonPanelBottom.setLayout(new GridLayout(1,3));
playButton = new JButton("Play");
stopButton = new JButton("Stop");
exitButton = new JButton("Exit");
playButton.addActionListener(new MyButtonListener());
stopButton.addActionListener(new MyButtonListener());
exitButton.addActionListener(new MyButtonListener());
buttonPanelBottom.add(playButton);
buttonPanelBottom.add(stopButton);
buttonPanelBottom.add(exitButton);
this.add(buttonPanelBottom, BorderLayout.SOUTH);
}
class MyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// The function that does something whenever each
// button is pressed
if (e.getSource() == loadMp3Button)
{
//debugging.
System.out.println("Load mp3 button");
library.loadLibrary(new File("/Users/Tim/Documents/cs112/Project4/mp3"));
library.sortSongs();
updateUI();
// FILL IN CODE - make the calls to other methods/classes, do NOT place all the code here
// 1) read all the mp3 files from mp3 directory
// 2) extract tags and load songs into the array of songs
// 3) Create a JTable from the songs and add it to the panel
// Replace the code below with the actual song data:
// right now it is hard coded and just demonstrates how to use JTable
String[][] tableElems = new String[10][2];
String[] columnNames = {"Title", "Artist"};
tableElems[0][0] = library.getSongs().get(0).getTitle();
tableElems[0][1] = library.getSongs().get(0).getArtist();
tableElems[1][0] = library.getSongs().get(1).getTitle();
tableElems[1][1] = library.getSongs().get(1).getArtist();
tableElems[2][0] = library.getSongs().get(2).getTitle();
tableElems[2][1] = library.getSongs().get(2).getArtist();
tableElems[3][0] = library.getSongs().get(3).getTitle();
tableElems[3][1] = library.getSongs().get(3).getArtist();
tableElems[4][0] = library.getSongs().get(4).getTitle();
tableElems[4][1] = library.getSongs().get(4).getArtist();
tableElems[5][0] = library.getSongs().get(5).getTitle();
tableElems[5][1] = library.getSongs().get(5).getArtist();
tableElems[6][0] = library.getSongs().get(6).getTitle();
tableElems[6][1] = library.getSongs().get(6).getArtist();
tableElems[7][0] = library.getSongs().get(7).getTitle();
tableElems[7][1] = library.getSongs().get(7).getArtist();
tableElems[8][0] = library.getSongs().get(8).getTitle();
tableElems[8][1] = library.getSongs().get(8).getArtist();
tableElems[9][0] = library.getSongs().get(9).getTitle();
tableElems[9][1] = library.getSongs().get(9).getArtist();
// you do not need to change the code below
table = new JTable(tableElems, columnNames );
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane, BorderLayout.CENTER );
updateUI();
}
else if (e.getSource() == saveButton) {
// FILL IN CODE : make the calls to other methods/classes, do NOT place all the code here
// save the song catalog into a file called "songCatalog".
// The format is described in the handout.
updateUI();
//Library object to call saving method.
//saves the songs from the ArrayList songs.
library.saving();
}
else if (e.getSource() == openButton) {
// FILL IN CODE: make the calls to other methods/classes, do NOT place all the code here
// open the file songCatalog and load songs
// into the arraylist of songs
try {
library.loadLibrary();
library.sortSongs();
updateUI();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (e.getSource() == playButton) {
int selectedSong = table.getSelectedRow();
library.playSongs( selectedSong );
// FILL IN CODE: make the calls to other methods/classes, do NOT place all the code here
// find the selected song in the arraylist of songs
// create a thread to play it as described in the handout.
}
else if (e.getSource() == stopButton) {
// FILL IN CODE: make the calls to other methods/classes, do NOT place all the code here
// stop the current running thread
boolean buttonClicked = true;
library.stopSong( buttonClicked );
}
else if (e.getSource() == exitButton) {
// Exit the program
System.exit(0);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame ("Mp3 player");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
MPlayerPanel panel = new MPlayerPanel();
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
|
tcsiwula/java_code
|
classes/cs112/Projects/project4/src/MPlayerPanel.java
|
Java
|
mit
| 6,176
|
def clean_dict_repr(mw):
"""Produce a repr()-like output of dict mw with ordered keys"""
return '{' + \
', '.join('{k!r}: {v!r}'.format(k=k, v=v) for k, v in
sorted(mw.items())) +\
'}'
|
npilon/planterbox
|
planterbox/util.py
|
Python
|
mit
| 236
|
/*
* Copyright (c) 2020 Pedro Falcato
* This file is part of Onyx, and is released under the terms of the MIT License
* check LICENSE at the root directory for more information
*/
#ifndef _ONYX_CRED_H
#define _ONYX_CRED_H
#include <string.h>
#include <sys/types.h>
#include <onyx/groups.h>
#include <onyx/rwlock.h>
struct creds
{
struct rwlock lock;
uid_t ruid;
uid_t euid;
gid_t rgid;
gid_t egid;
uid_t suid;
uid_t sgid;
// Type erasure because of C... Pain, all my homies know is pain.
void *groups;
};
struct process;
struct creds *creds_get(void);
struct creds *__creds_get(struct process *p);
struct creds *creds_get_write(void);
struct creds *__creds_get_write(struct process *p);
void creds_put(struct creds *c);
void creds_put_write(struct creds *c);
static inline bool is_root_user(void)
{
struct creds *c = creds_get();
bool is = c->euid == 0;
creds_put(c);
return is;
}
int process_inherit_creds(struct process *new_child, struct process *parent);
static inline void creds_init(struct creds *c)
{
/* Hacky, but works for both C and C++ */
memset(&c->ruid, 0, sizeof(*c) - offsetof(struct creds, ruid));
rwlock_init(&c->lock);
}
bool cred_is_in_group(struct creds *c, gid_t gid);
#ifdef __cplusplus
#include <onyx/utility.hpp>
enum class CGType
{
Write = 0,
Read
};
template <CGType type = CGType::Read>
class creds_guard
{
constexpr bool IsWrite() const
{
return type == CGType::Write;
}
creds *c;
public:
constexpr creds_guard(creds *c) : c{c}
{
}
creds_guard()
{
if (IsWrite())
c = creds_get_write();
else
c = creds_get();
}
creds_guard(creds_guard &&g) : c{g.c}
{
g.c = nullptr;
}
creds_guard &operator=(creds_guard &&g)
{
c = g.c;
g.c = nullptr;
return *this;
}
CLASS_DISALLOW_COPY(creds_guard);
~creds_guard()
{
if (c)
{
if (IsWrite())
creds_put_write(c);
else
creds_put(c);
}
}
creds *get() const
{
return c;
}
};
#endif
#endif
|
heatd/Onyx
|
kernel/include/onyx/cred.h
|
C
|
mit
| 2,207
|
<?php
namespace Laranix\Auth\Listeners;
use Laranix\Auth\Events\Settings;
use Laranix\Support\Listeners\Listener;
use Illuminate\Auth\Events\Registered as RegisteredEvent;
class Registered extends Listener
{
/**
* @var string
*/
protected $type = 'registration';
/**
* Handle event
*
* @param \Illuminate\Auth\Events\Registered $event
*/
public function handle(RegisteredEvent $event)
{
$this->track(Settings::TYPEID_REGISTERED, $event->user->id, 10);
}
}
|
samanix/laranix
|
src/Laranix/Auth/Listeners/Registered.php
|
PHP
|
mit
| 521
|
package com.simple.database.crud.base;
import com.simple.database.dao.async.AsyncDAO;
import java.util.HashMap;
import java.util.Map;
/**
* 构建查询条件的基础类.
* Created by mrsimple on 6/8/16.
*/
public abstract class BaseSQLBuilder<T> implements Executable {
protected AsyncDAO<T> mAsyncDao;
// 缓存异步的DAO类,避免重复创建与销毁
private static final Map<String, AsyncDAO> DAO_CACHE = new HashMap<>();
/**
* @param daoClass 同步的dao类,用于构建异步的dao类
*/
public BaseSQLBuilder(Class daoClass) {
String syncDaoClzName = daoClass.getName();
// 先检测缓存
mAsyncDao = DAO_CACHE.get(syncDaoClzName);
if (mAsyncDao == null) {
mAsyncDao = AsyncDAO.createDAO(daoClass);
}
if (mAsyncDao == null) {
throw new NullPointerException("Async DAO is null !!!");
} else {
// 缓存dao类型
DAO_CACHE.put(syncDaoClzName, mAsyncDao);
}
}
}
|
hehonghui/simpledb
|
database/src/main/java/com/simple/database/crud/base/BaseSQLBuilder.java
|
Java
|
mit
| 1,025
|
Chansig/Router
--------------
PHP Router for PHP5.4+ Built-in Server
See http://php.net/manual/en/features.commandline.webserver.php
Works on:
- Wordpress
- Symfony 2,
- Laravel,
- phpMyAdmin,
- bolt,
- etc.
## Features
- Serve multiple domains with vhosts configuration
- Allow different directory index (app_dev.php for example)
- Allowed Hosts only
- Header Cache control
- Header Access-Control-Allow-Origin
- Handles 404 error page
- Access logs
## Requirement
PHP 5.4+
## Warning
The built-in PHP web server is NOT meant to be a replacement for any production web server. It should used for development purposes only!
## Installation
The recommended way to install Chansig/Router is through
[Composer](http://getcomposer.org).
# Install Composer
curl -sS https://getcomposer.org/installer | php
Next, run the Composer command to install the latest stable version of Chansig/Router:
composer.phar require chansig/router dev-master
You can then later update Chansig/Router using composer:
composer.phar update
## Run PHP Built-in Server
php -S <addr>:<port> -t <docroot> vendor/chansig/router/src/router.php
e.g.
php -S localhost:80 vendor/chansig/router/src/router.php
e.g. on Symfony:
php -S 127.0.0.1:8080 -t web vendor/chansig/src/router/router_symfony_dev.php
e.g. on Wordpress:
php -S localhost:81 -t wordpress vendor/chansig/src/router/router.php
## Using Symfony console
app/console server:run 127.0.0.1:80 --router=vendor/chansig/src/router/router_symfony_dev.php --docroot=web
## php.ini
override ini values
php -S localhost:81 -t wordpress -c my.ini router.php
## Configuration
- copy vendor/chansig/src/router/router.php in your main directory
- require Composer's autoloader in router.php:
#router.php
require 'vendor/autoload.php';
### Override configuration
- copy vendor/chansig/src/router/router.json.example in your main directory
- copy router.json.example to router.json
Set configuration values in router.json:
- "hosts-name"
@var string[] ***[]***
List of allowed hosts if not empty.
- "port"
@var null|int ***null***
Which tcp/ip port does the server run on.
Default null for all ports
- "docroot"
@var null|string ***null***
Override Server DOCUMENT_ROOT if not null
- "directory-index"
@var null|array ***["index.php", "index.html"]***
Directory index filenames.
- "rewrite-index"
@var null|array ***null***
Rewrite filenames in docroot.
e.g.
"rewrite-index": ["app_dev.php"]
- "allow-origin"
@var null|array ***null***
Send Header Access-Control-Allow-Origin for defined hosts.
Useful for fonts files required on local CDN or Ajax requests.
e.g.
"allow-origin": ["*"]
- "handle-404"
@var bool ***false***
Router handles 404 error page.
- "cache-control"
@var null|int ***null***
Send http cache headers if > 0. Ex: Cache-Control: public, max-age=300
e.g.
"cache-control": 86400
- "render-ssi"
@var bool false
Render SSI include virtual & file.
e.g.
"render-ssi": true
- "ext-ssi"
@var null|array ***["shtml", "html", "htm"]***
File extensions that contains an SSI directive.
e.g.
"ext-ssi": ["shtml"]
- "log"
@var bool ***true***
Send access logs to output if true
- "logs-dir"
@var null|string ***null***
Write access logs to logs-dir if not null
e.g.
"logs-dir": "/Users/Toto/Sites/mysite.fr/app/logs"
- "auto-index-file"
@var null|string ***null***
PHP index Directory for directory listing. @see Chansig/DirectoryIndex.
To add auto-index-file, composer install chansig/directoryindex.
Set "auto-index-file" to absolute path of file vendor/chansig/directoryindex/src/directory.php.
e.g.
"auto-index-file": "/var/www/myphotos/vendor/chansig/directoryindex/src/directory.php"
- "vhosts"
@var object ***null***
List of virtual hosts.
You must define server(s) name and document root for each vhost.
Configuration is the same as the global configuration.
Vhost configuration is merged into global configuration.
e.g.
#router.json
{
"hosts-name": [],
"port": null,
"docroot": null,
"directory-index": ["index.php"],
"rewrite-index": null,
"allow-origin": null,
"allow-origin": null,
"handle-404": false,
"cache-control": 0,
"log": true,
"logs-dir": null,
"auto-index-file": null,
"vhosts":{
"serverkey1": {
"hosts-name": ["dev.mysite.ltd", "dev.www.mysite.ltd"],
"docroot": "/var/www/www.mysite.tld",
"rewrite-index": ["app_dev.php"],
"logs-dir": "/var/log/php/mysite.ltd",
},
"serverkey1": {
"hosts-name": ["cdn.dev.mysite.ltd""],
"port": 8080,
"docroot": "/var/www/www.mysite.tld",
"directory-index": ["index.html", "mydirectoryindex.php"],
"allow-origin": null,
"cache-control": 43200,
"handle-404": true,
"log": false
}
}
}
In vhosts configuration, **hosts-name** can be a regex. Captured patterns are available in $1 to $n string.
e.g.
"hosts-name": ["dev.www.([a-z]+).([a-z]+)"],
They will be replaced in **docroot** and **logs-dir** values.
e.g.
"docroot": "/var/www/www.$1.$2/web",
"logs-dir": "/var/log/php/www.$1.$2",
- "include"
@var null|array ***[]***
Include external config files.
Don't override main config.
e.g.
"include": [
"/Users/Toto/Sites/mysite.fr/router.json"
]
You can skip default configuration:
For exemple, sf2 site on windows:
#router.json
{
"vhosts":{
"mysite": {
"hosts-name": ["dev.mysite.ltd", "dev.www.mysite.ltd"],
"docroot": "C:\\var\\www\\www.mysite.tld\\web",
"rewrite-index": ["app_dev.php"],
"logs-dir": "C:\\var\\www\\www.mysite.tld\\app\\logs",",
},
"mysite2": {
"hosts-name": ["dev.www.mysite2.ltd"],
"docroot": "C:\\var\\www\\www.mysite2.tld\\web",
"rewrite-rewrite": ["app_dev.php"],
"logs-dir": "C:\\var\\www\\www.mysite2.tld\\app\\logs",",
},
"directory": {
"hosts-name": ["dev.www.mysite3.ltd"],
"docroot": "C:\\var\\www\\www.mysite23.tld",
"auto-index-file": "C:\\var\\www\\vendor\\chansig\\directoryindex\\directory.php"
},
}
}
- load config into router
$config = json_decode(file_get_contents(__DIR__ . '/router.json'), true);
$router = new PhpRouter($config);
or
$router = new PhpRouter(__DIR__ . '/router.json');
- run server
php -S localhost:80 router.php
To find process:
ps -ef | grep router.php
## Warning
On OSX, run sudo php -S 127.0.0.1:{port} router.php for port < 1024
PHP Build In Server is single threaded. So you can not curl (or file_ge_content) to itself on same port. Run an other Server on a new Port to do it.
e.g. php -S 127.0.0.1:80 for front and php -S 127.0.0.1:8000 for api
## License
MIT License
## Author
[Chansig](https://github.com/Chansig).
|
Chansig/Router
|
README.md
|
Markdown
|
mit
| 8,239
|
/**HEADER********************************************************************
*
* Copyright (c) 2008, 2013 Freescale Semiconductor;
* All Rights Reserved
*
*
***************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************
*
* $FileName: usb_opt.h$
* $Version :
* $Date :
*
* Comments:
*
*
*
*END************************************************************************/
#ifndef __usb_opt_h__
#define __usb_opt_h__ 1
#ifndef ENDIANNESS
#error ENDIANNESS should be defined, and then rebulid the project.
#endif
#define SWAP2BYTE_CONST(n) ((((n) & 0x00FF) << 8) | (((n) & 0xFF00) >> 8))
#define SWAP4BYTE_CONST(n) ((((n) & 0x000000FF) << 24) | (((n) & 0x0000FF00) << 8) | (((n) & 0x00FF0000) >> 8) | (((n) & 0xFF000000) >> 24))
#if (ENDIANNESS == BIG_ENDIAN)
#define USB_HOST_TO_BE_SHORT(n) (n)
#define USB_HOST_TO_BE_SHORT_CONST(n) (n)
#define USB_HOST_TO_LE_SHORT(n) SWAP2BYTE_CONST(n)
#define USB_HOST_TO_LE_SHORT_CONST(n) SWAP2BYTE_CONST(n)
#define USB_SHORT_BE_TO_HOST(n) (n)
#define USB_SHORT_BE_TO_HOST_CONST(n) (n)
#define USB_SHORT_LE_TO_HOST(n) SWAP2BYTE_CONST(n)
#define USB_SHORT_LE_TO_HOST_CONST(n) SWAP2BYTE_CONST(n)
#define USB_SHORT_UNALIGNED_LE_TO_HOST(n) ((n[1]<<8)|n[0])
#define USB_HOST_TO_BE_LONG(n) (n)
#define USB_HOST_TO_BE_LONG_CONST(n) (n)
#define USB_HOST_TO_BE_UNALIGNED_LONG(n, m) \
{ \
m[0]=((n>>24) & 0xFF); \
m[1]=((n>>16) & 0xFF); \
m[2]=((n>>8) & 0xFF); \
m[3]=(n & 0xFF); \
}
#define USB_HOST_TO_LE_LONG(n) SWAP4BYTE_CONST(n)
#define USB_HOST_TO_LE_LONG_CONST(n) SWAP4BYTE_CONST(n)
#define USB_HOST_TO_LE_UNALIGNED_LONG(n, m) \
{ \
m[0]=(n & 0xFF); \
m[1]=((n>>8) & 0xFF); \
m[2]=((n>>16) & 0xFF); \
m[3]=((n>>24) & 0xFF); \
}
#define USB_LONG_BE_TO_HOST(n) (n)
#define USB_LONG_BE_TO_HOST_CONST(n) (n)
#define USB_LONG_LE_TO_HOST(n) SWAP4BYTE_CONST(n)
#define USB_LONG_LE_TO_HOST_CONST(n) SWAP4BYTE_CONST(n)
#define USB_LONG_UNALIGNED_LE_TO_HOST(n) ((n[3]<<24)|(n[2]<<16)|(n[1]<<8)|n[0])
#else /* (PSP_ENDIAN == MQX_BIG_ENDIAN) */
#define USB_HOST_TO_BE_SHORT(n) SWAP2BYTE_CONST(n)
#define USB_HOST_TO_BE_SHORT_CONST(n) SWAP2BYTE_CONST(n)
#define USB_HOST_TO_LE_SHORT(n) (n)
#define USB_HOST_TO_LE_SHORT_CONST(n) (n)
#define USB_SHORT_BE_TO_HOST(n) SWAP2BYTE_CONST(n)
#define USB_SHORT_BE_TO_HOST_CONST(n) SWAP2BYTE_CONST(n)
#define USB_SHORT_LE_TO_HOST(n) (n)
#define USB_SHORT_LE_TO_HOST_CONST(n) (n)
#define USB_SHORT_UNALIGNED_LE_TO_HOST(n) ((uint16_t)((uint16_t)n[1]<<8)|n[0])
#define USB_HOST_TO_BE_LONG(n) SWAP4BYTE_CONST(n)
#define USB_HOST_TO_BE_LONG_CONST(n) SWAP4BYTE_CONST(n)
#define USB_HOST_TO_BE_UNALIGNED_LONG(n, m) \
{ \
m[0]=((n>>24) & 0xFF); \
m[1]=((n>>16) & 0xFF); \
m[2]=((n>>8) & 0xFF); \
m[3]=(n & 0xFF); \
}
#define USB_HOST_TO_LE_LONG(n) (n)
#define USB_HOST_TO_LE_LONG_CONST(n) (n)
#define USB_HOST_TO_LE_UNALIGNED_LONG(n, m) \
{ \
m[0]=(n & 0xFF); \
m[1]=((n>>8) & 0xFF); \
m[2]=((n>>16) & 0xFF); \
m[3]=((n>>24) & 0xFF); \
}
#define USB_LONG_BE_TO_HOST(n) SWAP4BYTE_CONST(n)
#define USB_LONG_BE_TO_HOST_CONST(n) SWAP4BYTE_CONST(n)
#define USB_LONG_LE_TO_HOST(n) (n)
#define USB_LONG_LE_TO_HOST_CONST(n) (n)
#define USB_LONG_UNALIGNED_LE_TO_HOST(n) (((uint32_t)n[3]<<24) | ((uint32_t)n[2]<<16) | ((uint32_t)n[1]<<8) | (uint32_t)n[0])
#endif /* (PSP_ENDIAN == MQX_BIG_ENDIAN) */
#endif
|
wesleyhunter/centaurian
|
Examples/Eclipse/FRDM-K64F/K64F_USB_CDC/SDK/usb/usb_core/include/usb_opt.h
|
C
|
mit
| 4,532
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM nsISecretDecoderRing.idl
*/
#ifndef __gen_nsISecretDecoderRing_h__
#define __gen_nsISecretDecoderRing_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsISecretDecoderRing */
#define NS_ISECRETDECODERRING_IID_STR "0ec80360-075c-11d4-9fd4-00c04f1b83d8"
#define NS_ISECRETDECODERRING_IID \
{0x0ec80360, 0x075c, 0x11d4, \
{ 0x9f, 0xd4, 0x00, 0xc0, 0x4f, 0x1b, 0x83, 0xd8 }}
class NS_NO_VTABLE nsISecretDecoderRing : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISECRETDECODERRING_IID)
/* [noscript] long encrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHOD Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) = 0;
/* [noscript] long decrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHOD Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) = 0;
/* string encryptString (in string text); */
NS_IMETHOD EncryptString(const char *text, char **_retval) = 0;
/* string decryptString (in string crypt); */
NS_IMETHOD DecryptString(const char *crypt, char **_retval) = 0;
/* void changePassword (); */
NS_IMETHOD ChangePassword(void) = 0;
/* void logout (); */
NS_IMETHOD Logout(void) = 0;
/* void logoutAndTeardown (); */
NS_IMETHOD LogoutAndTeardown(void) = 0;
};
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISECRETDECODERRING \
NS_IMETHOD Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval); \
NS_IMETHOD Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval); \
NS_IMETHOD EncryptString(const char *text, char **_retval); \
NS_IMETHOD DecryptString(const char *crypt, char **_retval); \
NS_IMETHOD ChangePassword(void); \
NS_IMETHOD Logout(void); \
NS_IMETHOD LogoutAndTeardown(void);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISECRETDECODERRING(_to) \
NS_IMETHOD Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) { return _to Encrypt(data, dataLen, result, _retval); } \
NS_IMETHOD Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) { return _to Decrypt(data, dataLen, result, _retval); } \
NS_IMETHOD EncryptString(const char *text, char **_retval) { return _to EncryptString(text, _retval); } \
NS_IMETHOD DecryptString(const char *crypt, char **_retval) { return _to DecryptString(crypt, _retval); } \
NS_IMETHOD ChangePassword(void) { return _to ChangePassword(); } \
NS_IMETHOD Logout(void) { return _to Logout(); } \
NS_IMETHOD LogoutAndTeardown(void) { return _to LogoutAndTeardown(); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISECRETDECODERRING(_to) \
NS_IMETHOD Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->Encrypt(data, dataLen, result, _retval); } \
NS_IMETHOD Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->Decrypt(data, dataLen, result, _retval); } \
NS_IMETHOD EncryptString(const char *text, char **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->EncryptString(text, _retval); } \
NS_IMETHOD DecryptString(const char *crypt, char **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->DecryptString(crypt, _retval); } \
NS_IMETHOD ChangePassword(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ChangePassword(); } \
NS_IMETHOD Logout(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Logout(); } \
NS_IMETHOD LogoutAndTeardown(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->LogoutAndTeardown(); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsSecretDecoderRing : public nsISecretDecoderRing
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISECRETDECODERRING
nsSecretDecoderRing();
virtual ~nsSecretDecoderRing();
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsSecretDecoderRing, nsISecretDecoderRing)
nsSecretDecoderRing::nsSecretDecoderRing()
{
/* member initializers and constructor code */
}
nsSecretDecoderRing::~nsSecretDecoderRing()
{
/* destructor code */
}
/* [noscript] long encrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHODIMP nsSecretDecoderRing::Encrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript] long decrypt (in buffer data, in long dataLen, out buffer result); */
NS_IMETHODIMP nsSecretDecoderRing::Decrypt(unsigned char * data, PRInt32 dataLen, unsigned char * *result, PRInt32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* string encryptString (in string text); */
NS_IMETHODIMP nsSecretDecoderRing::EncryptString(const char *text, char **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* string decryptString (in string crypt); */
NS_IMETHODIMP nsSecretDecoderRing::DecryptString(const char *crypt, char **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void changePassword (); */
NS_IMETHODIMP nsSecretDecoderRing::ChangePassword()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void logout (); */
NS_IMETHODIMP nsSecretDecoderRing::Logout()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void logoutAndTeardown (); */
NS_IMETHODIMP nsSecretDecoderRing::LogoutAndTeardown()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
/* starting interface: nsISecretDecoderRingConfig */
#define NS_ISECRETDECODERRINGCONFIG_IID_STR "01d8c0f0-0ccc-11d4-9fdd-000064657374"
#define NS_ISECRETDECODERRINGCONFIG_IID \
{0x01d8c0f0, 0x0ccc, 0x11d4, \
{ 0x9f, 0xdd, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74 }}
class NS_NO_VTABLE nsISecretDecoderRingConfig : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISECRETDECODERRINGCONFIG_IID)
/* void setWindow (in nsISupports w); */
NS_IMETHOD SetWindow(nsISupports *w) = 0;
};
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISECRETDECODERRINGCONFIG \
NS_IMETHOD SetWindow(nsISupports *w);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISECRETDECODERRINGCONFIG(_to) \
NS_IMETHOD SetWindow(nsISupports *w) { return _to SetWindow(w); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISECRETDECODERRINGCONFIG(_to) \
NS_IMETHOD SetWindow(nsISupports *w) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetWindow(w); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsSecretDecoderRingConfig : public nsISecretDecoderRingConfig
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISECRETDECODERRINGCONFIG
nsSecretDecoderRingConfig();
virtual ~nsSecretDecoderRingConfig();
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsSecretDecoderRingConfig, nsISecretDecoderRingConfig)
nsSecretDecoderRingConfig::nsSecretDecoderRingConfig()
{
/* member initializers and constructor code */
}
nsSecretDecoderRingConfig::~nsSecretDecoderRingConfig()
{
/* destructor code */
}
/* void setWindow (in nsISupports w); */
NS_IMETHODIMP nsSecretDecoderRingConfig::SetWindow(nsISupports *w)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsISecretDecoderRing_h__ */
|
SrivastavaConsultingGroup/DigitalSignature
|
Xmlsign/NetscapeUtil/allinclude/nsISecretDecoderRing.h
|
C
|
mit
| 8,045
|
package core
import (
"bytes"
"fmt"
"github.com/BurntSushi/toml"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
type Settings struct {
Current string
Files []File
}
type File struct {
Path string
Prefix string
Postfix string
IsNumber bool
}
type Versions struct {
Current string
Files []Version
}
type Version struct {
Path string
Lines []string
}
const SETTINGS_FILE_NAME = ".yangpao.toml"
const SEMANTIC_VERSION_PATTERN = `\d+\.\d+\.\d+`
const SEQUENTIAL_VERSION_PATTERN = `\d+`
const (
PATCH = iota
MINOR
MAJOR
)
func Exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func SearchSettingFile() error {
previous := ""
current, err := os.Getwd()
if err != nil {
return err
}
for previous != current {
if Exists(SETTINGS_FILE_NAME) {
return nil
}
previous = current
err = os.Chdir("..")
if err != nil {
return err
}
current, err = os.Getwd()
if err != nil {
return err
}
}
return fmt.Errorf("%s is not found. Run %s -g to generate", SETTINGS_FILE_NAME, os.Args[0])
}
func CurrentVersion() (string, error) {
var settings Settings
if err := ParseSettings(SETTINGS_FILE_NAME, &settings); err != nil {
return "", err
}
return settings.Current, nil
}
func GenerateSettingFile() {
var settings Settings
settings.Current = "0.0.0"
var file File
file.Path = "README.md"
file.Prefix = "AwesomeProject "
file.Postfix = " version"
file.IsNumber = false
settings.Files = append(settings.Files, file)
file.Path = "README.md"
file.Prefix = ""
file.Postfix = "th release"
file.IsNumber = true
settings.Files = append(settings.Files, file)
file.Path = "release_tag"
file.Prefix = "v"
file.Postfix = ""
file.IsNumber = false
settings.Files = append(settings.Files, file)
WriteBackSettings(settings)
}
func CheckVersions(versions *Versions) error {
var settings Settings
if err := ParseSettings(SETTINGS_FILE_NAME, &settings); err != nil {
return err
}
versions.Current = settings.Current
for _, file := range settings.Files {
if !Exists(file.Path) {
absolutePath, err := filepath.Abs(file.Path)
if err != nil {
return err
}
return fmt.Errorf("file is not exist: %s", absolutePath)
}
var version Version
version.Path = file.Path
var pattern string
if file.IsNumber {
pattern = fmt.Sprintf("%s%s%s", file.Prefix, SEQUENTIAL_VERSION_PATTERN, file.Postfix)
} else {
pattern = fmt.Sprintf("%s%s%s", file.Prefix, SEMANTIC_VERSION_PATTERN, file.Postfix)
}
matcher := regexp.MustCompile(pattern)
raw, err := ioutil.ReadFile(file.Path)
if err != nil {
return err
}
founds := matcher.FindAllString(string(raw), -1)
version.Lines = founds
versions.Files = append(versions.Files, version)
}
return nil
}
func Upgrade(which int) (string, error) {
var settings Settings
if err := ParseSettings(SETTINGS_FILE_NAME, &settings); err != nil {
return "", err
}
newVersion, err := UpgradeVersion(settings.Current, which)
if err != nil {
return "", err
}
settings.Current = newVersion
Replace(settings)
WriteBackSettings(settings)
return settings.Current, nil
}
func ParseSettings(settingsFileName string, settings *Settings) error {
if _, err := toml.DecodeFile(SETTINGS_FILE_NAME, &settings); err != nil {
return err
}
if settings.Current == "" {
return fmt.Errorf("current version is empty or undefined")
}
r := regexp.MustCompile(SEMANTIC_VERSION_PATTERN)
if !r.MatchString(settings.Current) {
return fmt.Errorf("version is not like semver")
}
for _, file := range settings.Files {
if file.Path == "" {
return fmt.Errorf("path for each file is requied")
}
}
return nil
}
func UpgradeVersion(current string, which int) (string, error) {
switch which {
case PATCH:
return IncrementSpecifiedVersion(current, 2)
case MINOR:
return IncrementSpecifiedVersion(current, 1)
case MAJOR:
return IncrementSpecifiedVersion(current, 0)
}
return "", fmt.Errorf("specify patch, minor, or major to upgrade")
}
func IncrementSpecifiedVersion(current string, index int) (string, error) {
split := strings.Split(current, ".")
version, err := strconv.Atoi(split[index])
if err != nil {
return "", err
}
split[index] = strconv.Itoa(version + 1)
for i := range split {
if index < i {
split[i] = "0"
}
}
return strings.Join(split, "."), nil
}
func WriteBackSettings(settings Settings) error {
file, err := os.OpenFile(SETTINGS_FILE_NAME, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return err
}
var buffer bytes.Buffer
encoder := toml.NewEncoder(&buffer)
if err := encoder.Encode(settings); err != nil {
return err
}
if _, err := file.Write(buffer.Bytes()); err != nil {
return err
}
return nil
}
func SemVerToInteger(semVer string) int {
split := strings.Split(semVer, ".")
major, _ := strconv.Atoi(split[0])
minor, _ := strconv.Atoi(split[1])
patch, _ := strconv.Atoi(split[2])
return major*10000 + minor*100 + patch
}
func Replace(settings Settings) error {
for _, file := range settings.Files {
if !Exists(file.Path) {
return fmt.Errorf("file is not exist: %s", file.Path)
}
raw, err := ioutil.ReadFile(file.Path)
if err != nil {
return err
}
var pattern string
var target string
if file.IsNumber {
pattern = fmt.Sprintf("%s(%s)%s", file.Prefix, SEQUENTIAL_VERSION_PATTERN, file.Postfix)
target = fmt.Sprintf("%s%d%s", file.Prefix, SemVerToInteger(settings.Current), file.Postfix)
} else {
pattern = fmt.Sprintf("%s(%s)%s", file.Prefix, SEMANTIC_VERSION_PATTERN, file.Postfix)
target = fmt.Sprintf("%s%s%s", file.Prefix, settings.Current, file.Postfix)
}
matcher := regexp.MustCompile(pattern)
replaced := matcher.ReplaceAllString(string(raw), target)
err = ioutil.WriteFile(file.Path, []byte(replaced), 0)
if err != nil {
return err
}
}
return nil
}
|
januswel/yangpao
|
core/core.go
|
GO
|
mit
| 5,900
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>stdpp: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+2 / stdpp - 1.3.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
stdpp
<small>
1.3.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-11-21 02:02:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-21 02:02:39 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 1 Virtual package relying on perl
coq 8.7.1+2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
name: "coq-stdpp"
maintainer: "Ralf Jung <jung@mpi-sws.org>"
authors: "Robbert Krebbers, Jacques-Henri Jourdan, Ralf Jung"
license: "BSD"
homepage: "https://gitlab.mpi-sws.org/iris/stdpp"
bug-reports: "https://gitlab.mpi-sws.org/iris/stdpp/issues"
dev-repo: "git+https://gitlab.mpi-sws.org/iris/stdpp.git"
tags: [
"date:2020-03-18"
"logpath:stdpp"
]
synopsis: "std++ is an extended \"Standard Library\" for Coq"
description: """
The key features of this library are as follows:
- It provides a great number of definitions and lemmas for common data
structures such as lists, finite maps, finite sets, and finite multisets.
- It uses type classes for common notations (like `∅`, `∪`, and Haskell-style
monad notations) so that these can be overloaded for different data structures.
- It uses type classes to keep track of common properties of types, like it
having decidable equality or being countable or finite.
- Most data structures are represented in canonical ways so that Leibniz
equality can be used as much as possible (for example, for maps we have
`m1 = m2` iff `∀ i, m1 !! i = m2 !! i`). On top of that, the library provides
setoid instances for most types and operations.
- It provides various tactics for common tasks, like an ssreflect inspired
`done` tactic for finishing trivial goals, a simple breadth-first solver
`naive_solver`, an equality simplifier `simplify_eq`, a solver `solve_proper`
for proving compatibility of functions with respect to relations, and a solver
`set_solver` for goals involving set operations.
- It is entirely dependency- and axiom-free.
"""
depends: [
"coq" { (= "8.7.2") | (= "8.8.2") | (>= "8.9.1" & < "8.12~") | (= "dev") }
]
build: [make "-j%{jobs}%"]
install: [make "install"]
url {
src:
"https://gitlab.mpi-sws.org/iris/stdpp/-/archive/coq-stdpp-1.3.0.tar.gz"
checksum:
"sha512=82247189f655c0ad60a81864b6f88a10933cacd79c35405dc812b7e6ca1938b3770c5d5339419f9e8252880acf028c767b2191061bbe1bfcdba3c05a960ed001"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-stdpp.1.3.0 coq.8.7.1+2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2).
The following dependencies couldn't be met:
- coq-stdpp -> coq (= 8.7.2 & = 8.8.2 & >= 8.9.1 & = dev)
no matching version
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-stdpp.1.3.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1+2/stdpp/1.3.0.html
|
HTML
|
mit
| 8,045
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-ssreflect: 1 m 54 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.2 / mathcomp-ssreflect - 1.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-ssreflect
<small>
1.10.0
<span class="label label-success">1 m 54 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-11-26 20:00:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-26 20:00:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Mathematical Components <mathcomp-dev@sympa.inria.fr>"
homepage: "https://math-comp.github.io/"
bug-reports: "https://github.com/math-comp/math-comp/issues"
dev-repo: "git+https://github.com/math-comp/math-comp.git"
license: "CeCILL-B"
build: [ make "-C" "mathcomp/ssreflect" "-j" "%{jobs}%" ]
install: [ make "-C" "mathcomp/ssreflect" "install" ]
depends: [ "coq" { (>= "8.7" & < "8.12~") } ]
tags: [ "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" "logpath:mathcomp.ssreflect" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "Small Scale Reflection"
description: """
This library includes the small scale reflection proof language
extension and the minimal set of libraries to take advantage of it.
This includes libraries on lists (seq), boolean and boolean
predicates, natural numbers and types with decidable equality,
finite types, finite sets, finite functions, finite graphs, basic arithmetics
and prime numbers, big operators
"""
url {
src: "http://github.com/math-comp/math-comp/archive/mathcomp-1.10.0.tar.gz"
checksum: "sha256=3f8a88417f3456da05e2755ea0510c1bd3fd13b13c41e62fbaa3de06be040166"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-ssreflect.1.10.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-ssreflect.1.10.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>11 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-ssreflect.1.10.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 54 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 21 M</p>
<ul>
<li>11 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnat.vo</code></li>
<li>924 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/seq.vo</code></li>
<li>759 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/seq.glob</code></li>
<li>656 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finset.glob</code></li>
<li>582 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/bigop.glob</code></li>
<li>573 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finset.vo</code></li>
<li>462 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnat.glob</code></li>
<li>446 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/prime.glob</code></li>
<li>439 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/bigop.vo</code></li>
<li>435 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fintype.glob</code></li>
<li>428 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/prime.vo</code></li>
<li>427 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/path.vo</code></li>
<li>407 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fintype.vo</code></li>
<li>341 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/path.glob</code></li>
<li>333 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/div.glob</code></li>
<li>264 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fingraph.vo</code></li>
<li>256 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/div.vo</code></li>
<li>254 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/binomial.vo</code></li>
<li>241 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fingraph.glob</code></li>
<li>222 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/binomial.glob</code></li>
<li>155 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/choice.vo</code></li>
<li>153 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/eqtype.glob</code></li>
<li>146 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finfun.vo</code></li>
<li>141 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/eqtype.vo</code></li>
<li>132 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/generic_quotient.vo</code></li>
<li>124 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/seq.v</code></li>
<li>117 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/tuple.vo</code></li>
<li>104 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/generic_quotient.glob</code></li>
<li>100 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/choice.glob</code></li>
<li>88 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finset.v</code></li>
<li>82 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finfun.glob</code></li>
<li>81 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/tuple.glob</code></li>
<li>81 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fintype.v</code></li>
<li>79 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/bigop.v</code></li>
<li>68 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnat.v</code></li>
<li>56 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/prime.v</code></li>
<li>49 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/path.v</code></li>
<li>38 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/div.v</code></li>
<li>37 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/eqtype.v</code></li>
<li>36 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/fingraph.v</code></li>
<li>29 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/all_ssreflect.vo</code></li>
<li>28 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/choice.v</code></li>
<li>27 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/generic_quotient.v</code></li>
<li>24 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/binomial.v</code></li>
<li>20 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/finfun.v</code></li>
<li>15 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/tuple.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssreflect.vo</code></li>
<li>9 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrbool.vo</code></li>
<li>8 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnotations.vo</code></li>
<li>7 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrbool.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnotations.v</code></li>
<li>6 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssreflect.glob</code></li>
<li>5 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrfun.vo</code></li>
<li>4 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssreflect.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrbool.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrfun.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrmatching.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrfun.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/all_ssreflect.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/all_ssreflect.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrmatching.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrnotations.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/mathcomp/ssreflect/ssrmatching.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-mathcomp-ssreflect.1.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.06.1-2.0.5/released/8.11.2/mathcomp-ssreflect/1.10.0.html
|
HTML
|
mit
| 15,178
|
<div class="col-lg-4 col-lg-offset-4 col-md-offset-1 col-md-10"><?php echo validation_errors(); ?></div>
<?php echo form_open('page/register'); ?>
<div class="fill col-lg-6 col-lg-offset-3 col-md-offset-1 col-md-10 col-xs-12">
<ol class="breadcrumb">
<li><?=anchor(site_url(),'Home')?></li>
<li class="active">Register</li>
</ol>
<div class="user-access bg-white col-lg-8 col-lg-offset-2">
<div id="name">
<label class="margin label label-default" for='name'>Imię:</label>
<input class="margin form-control input-sizer" type="text" name="name">
<br>
</div>
<div id="surname">
<label class="margin label label-default" for='surname'>Nazwisko:</label>
<input class="margin form-control input-sizer" type="text" name="surname">
<br>
</div>
<div id="email">
<label class="margin label label-default" for='email'>E-mail:</label>
<input class="margin form-control input-sizer" type="email" name="email">
<br>
</div>
<div id="password">
<label class="margin label label-default" for='password'>Hasło:</label>
<input class="margin form-control input-sizer" type="password" name="password">
<br>
</div>
<div id="password1">
<label class="margin label label-default" for='password1'>Powtórz hasło:</label>
<input class="margin form-control input-sizer" type="password" name="password1">
<br>
</div>
<div id="phoneNr">
<label class="margin label label-default" for='phoneNr'>Numer telefonu:</label>
<input class="margin form-control input-sizer" type="text" name="phoneNr">
<br>
</div>
<div id="city">
<label class="margin label label-default" for='city'>Miasto:</label>
<input class="margin form-control input-sizer" type="text" name="city">
<br>
</div>
<input class="margin btn btn-default" type="submit" name="submit" value="Zarejestruj się">
<?php echo anchor('page/login','Posiadasz już konto? Zaloguj się!',$arrayName = array('class' => 'advertAnchor' )); ?>
</form>
</div>
</div>
|
Danonovsky/Projekt2017
|
application/views/page/register.php
|
PHP
|
mit
| 2,099
|
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.0">
<defaueqkodec>UTF-8</defaueqkodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Equikoin</source>
<translation>در مورد بیتکویین</translation>
</message>
<message>
<location line="+39"/>
<source><b>Equikoin</b> version</source>
<translation><b>Equikoin</b> version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Equikoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>دفترچه آدرس</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>برای ویرایش آدرس/برچسب دوبار کلیک نمایید</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>یک آدرس جدید بسازید</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>آدرس انتخاب شده را در کلیپ بوردِ سیستم کپی کنید</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>و آدرس جدید</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Equikoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>و کپی آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>نشان و کد QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Equikoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Equikoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>و حذف</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Equikoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>کپی و برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>و ویرایش</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>انتقال اطلاعات دفترچه آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>سی.اس.وی. (فایل جداگانه دستوری)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>صدور پیام خطا</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی در فایل نیست %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>رمز/پَس فرِیز را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>رمز/پَس فرِیز جدید را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>رمز/پَس فرِیز را دوباره وارد کنید</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>wallet را رمزگذاری کنید</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>باز کردن قفل wallet </translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>کشف رمز wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>رمزگذاری wallet را تایید کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>تایید رمزگذاری</translation>
</message>
<message>
<location line="-56"/>
<source>Equikoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your equikoins from being stolen by malware infecting your computer.</source>
<translation>Equikoin برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>رمزگذاری تایید نشد</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>قفل wallet باز نشد</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>کشف رمز wallet انجام نشد</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>به روز رسانی با شبکه...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>و بازبینی</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>نمای کلی از wallet را نشان بده</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>و تراکنش</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تاریخچه تراکنش را باز کن</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>فهرست آدرسها و برچسبهای ذخیره شده را ویرایش کن</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>فهرست آدرسها را برای دریافت وجه نشان بده</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>از "درخواست نامه"/ application خارج شو</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Equikoin</source>
<translation>اطلاعات در مورد Equikoin را نشان بده</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>درباره و QT</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>و انتخابها</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>و رمزگذاری wallet</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>و گرفتن نسخه پیشتیبان از wallet</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Equikoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Equikoin</source>
<translation>اصلاح انتخابها برای پیکربندی Equikoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Equikoin</source>
<translation>equikoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Equikoin</source>
<translation>&در مورد بیتکویین</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش و</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Equikoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Equikoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>و فایل</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>و تنظیمات</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>و راهنما</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>نوار ابزار</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Equikoin client</source>
<translation>مشتری equikoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Equikoin network</source>
<translation><numerusform>%n ارتباط فعال به شبکه Equikoin
%n ارتباط فعال به شبکه Equikoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>روزآمد</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>در حال روزآمد سازی..</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>ارسال تراکنش</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>تراکنش دریافتی</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Equikoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Equikoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>هشدار شبکه</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>ویرایش آدرسها</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>برچسب مربوط به این دفترچه آدرس</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>و آدرس</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>برچسب مربوط به این دفترچه آدرس و تنها ب</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>آدرسِ دریافت کننده جدید</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>آدرس ارسال کننده جدید</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>ویرایش آدرسِ دریافت کننده</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>ویرایش آدرسِ ارسال کننده</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>آدرس وارد شده %1 قبلا به فهرست آدرسها اضافه شده بوده است.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Equikoin address.</source>
<translation>آدرس وارد شده "%1" یک آدرس صحیح برای equikoin نسشت</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>عدم توانیی برای قفل گشایی wallet</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>عدم توانیی در ایجاد کلید جدید</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Equikoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>انتخاب/آپشن</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Equikoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Equikoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Equikoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Equikoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Equikoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Equikoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>و نمایش آدرسها در فهرست تراکنش</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>و تایید</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>و رد</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>و به کار گرفتن</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>پیش فرض</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Equikoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Equikoin network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه equikoin به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>تایید نشده</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>تراکنشهای اخیر</translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>مانده حساب جاری</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>تعداد تراکنشهایی که نیاز به تایید دارند و هنوز در مانده حساب جاری شما به حساب نیامده اند</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>خارج از روزآمد سازی</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start equikoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>درخواست وجه</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>برچسب:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>پیام:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>و ذخیره با عنوانِ...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>تصاویر با فرمت PNG
(*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Equikoin-Qt help message to get a list with possible Equikoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Equikoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Equikoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Equikoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Equikoin RPC console.</source>
<translation>به کنسول آر.پی.سی. LITECOIN خوش آمدید</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>ارسال همزمان به گیرنده های متعدد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>تمامی فیلدهای تراکنش حذف شوند</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تایید عملیات ارسال </translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>و ارسال</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation>%1 به %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تایید ارسال سکه ها</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>شما مطمئن هستید که می خواهید %1 را ارسال کنید؟</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>و</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>میزان پرداخت باید بیشتر از 0 باشد</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>خطا: تراکنش تایید نشد. این خطا ممکن است به این دلیل اتفاق بیافتد که سکه های wallet شما خرج شده باشند مثلا اگر wallet.dat را مپی کرده باشید و سکه های شما در آن کپی استفاده شده باشند اما در اینجا نمایش داده نشده اند.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>و میزان وجه</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>پرداخت و به چه کسی</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</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>آدرس را بر کلیپ بورد کپی کنید</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>این گیرنده را حذف کن</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Equikoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس equikoin وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>و امضای پیام </translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس equikoin وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Equikoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس equikoin وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Equikoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Equikoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس equikoin وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Equikoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Equikoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1 غیرقابل تایید</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 تاییدها</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>تا به حال با موفقیت انتشار نیافته است</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ناشناس</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>جزئیات تراکنش</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>این بخش جزئیات تراکنش را نشان می دهد</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>میزان وجه</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>برون خطی (%1 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>تایید نشده (%1 از %2 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1 تاییدها)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>تولید شده اما قبول نشده است</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>قبول با </translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>دریافت شده از</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>وجه برای شما </translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>خالی</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>زمان و تاریخی که تراکنش دریافت شده است</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>آدرس مقصد در تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>میزان وجه کم شده یا اضافه شده به حساب</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>این سال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>حدود..</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>به شما</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>دیگر</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>آدرس یا برچسب را برای جستجو وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>حداقل میزان وجه</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>برچسب را ویرایش کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>داده های تراکنش را صادر کنید</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>تایید شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا در ارسال</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی به فایل نیست %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>دامنه:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Equikoin version</source>
<translation>نسخه equikoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or equikoind</source>
<translation>ارسال دستور به سرور یا equikoined</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>فهرست دستورها</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>درخواست کمک برای یک دستور</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>انتخابها:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: equikoin.conf)</source>
<translation>فایل پیکربندیِ را مشخص کنید (پیش فرض: equikoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: equikoind.pid)</source>
<translation>فایل pid را مشخص کنید (پیش فرض: equikoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>دایرکتوری داده را مشخص کن</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>ارتباطات را در <PORT> بشنوید (پیش فرض: 9333 or testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>نگهداری <N> ارتباطات برای قرینه سازی (پیش فرض:125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>ارتباطاتِ JSON-RPC را در <port> گوش کنید (پیش فرض:9332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>command line و JSON-RPC commands را قبول کنید</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>از تستِ شبکه استفاده نمایید</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=equikoinrpc
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 "Equikoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Equikoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Equikoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>برونداد اشکال زدایی با timestamp</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Equikoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>ارسال اطاعات خطایابی/پیگیری به سیستم خطایاب</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>رمز برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>دستورات را به گره اجرا شده در<ip> ارسال کنید (پیش فرض:127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین نسخه روزآمد کنید</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>حجم key pool را به اندازه <n> تنظیم کنید (پیش فرض:100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>فایل certificate سرور (پیش فرض server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>ciphers قابل قبول (پیش فرض: default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>این پیام راهنما</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>لود شدن آدرسها..</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Equikoin</source>
<translation>خطا در هنگام لود شدن wallet.dat. به نسخه جدید Bitocin برای wallet نیاز است.</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Equikoin to complete</source>
<translation>wallet نیاز به بازنویسی دارد. Equikoin را برای تکمیل عملیات دوباره اجرا کنید.</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>خطا در هنگام لود شدن wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان اشتباه است for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>میزان اشتباه است</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>وجوه ناکافی</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>لود شدن نمایه بلاکها..</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Equikoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>هزینه بر اساس کیلو بایت برای اضافه شدن به تراکنشی که ارسال کرده اید</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>wallet در حال لود شدن است...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>اسکنِ دوباره...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>اتمام لود شدن</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>برای استفاده از %s از اختیارات</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>شما باید یک رمز rpcpassword=<password> را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل "فقط متنی" ایجاد کنید.
</translation>
</message>
</context>
</TS>
|
KaSt/equikoin
|
src/qt/locale/bitcoin_fa_IR.ts
|
TypeScript
|
mit
| 107,441
|
/*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| CharType.cs |
| |
| hprose CharType enum for C#. |
| |
| LastModified: Jan 10, 2019 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
namespace Hprose.IO {
public enum CharType {
String, Char
}
}
|
hprose/hprose-dotnet
|
src/Hprose.IO/CharType.cs
|
C#
|
mit
| 936
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./css/bootstrap.min.css" />
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div class="form-wrapper" id="form-wrapper">
<form class="form-horizontal" onsubmit="return false">
<div class="control-group">
<label class="control-label" for="host">Host:</label>
<div class="controls">
<input type="text" id="host" name="host" value="" /><br />
</div>
</div>
<!-- <div class="control-group">
<label class="control-label" for="port">Port:</label>
<div class="controls">
<input type="text" id="port" name="port" value="" /><br />
</div>
</div>-->
<div class="control-group">
<label class="control-label" for="password">Password:</label>
<div class="controls">
<input type="password" id="password" name="password" value="" /><br />
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn" id="loginBtn">Log in</button>
</div>
</div>
</form>
</div>
<canvas id="screen">
</canvas>
<script src="http://10.0.0.185:8091/socket.io/socket.io.js"></script>
<script src="./js/jquery-2.1.3.min.js"></script>
<script src="./js/client.js"></script>
</body>
</html>
|
psd401/js-vnc-demo-project
|
static/index.html
|
HTML
|
mit
| 1,617
|
//
// PathController_Private.h
// DropboxLib
//
// Created by Jesse Grosjean on 3/7/11.
// Copyright 2011 Hog Bay Software. All rights reserved.
//
#import "PathController.h"
@interface PathController (Private)
- (NSString *)serverPathToLocal:(NSString *)serverPath;
- (NSString *)localPathToServer:(NSString *)localPath;
- (NSString *)localPathToNormalized:(NSString *)localPath;
- (BOOL)saveState;
- (void)setPathActivity:(PathActivity)aPathActivity forPath:(NSString *)aLocalPath;
- (PathMetadata *)pathMetadataForLocalPath:(NSString *)localPath createNewLocalIfNeeded:(BOOL)createIfNeeded;
- (void)deletePathMetadataForLocalPath:(NSString *)localPath;
- (void)initManagedObjectContext;
- (void)postQueuedPathChangedNotifications;
@end
|
jessegrosjean/DropboxSync
|
Source/PathController_Private.h
|
C
|
mit
| 749
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.client.soap;
import com.zimbra.cs.client.*;
public class LmcBrowseResponse extends LmcSoapResponse {
private LmcBrowseData mData[];
public void setData(LmcBrowseData d[]) { mData = d; }
public LmcBrowseData[] getData() { return mData; }
}
|
nico01f/z-pec
|
ZimbraServer/src/java/com/zimbra/cs/client/soap/LmcBrowseResponse.java
|
Java
|
mit
| 851
|
namespace GraphExec
{
public interface INode
{
INode Parent { get; set; }
NodeExecutionState ExecutionState { get; }
void Execute();
}
public interface INode<T> : INode
{
T Value { get; set; }
}
public interface INode<T, TNodeInfo> : INode<T>
where TNodeInfo : class, INodeInfo, new()
{
TNodeInfo Info { get; set; }
}
}
|
GraphExec/GraphExecNet
|
GraphExec/INode.cs
|
C#
|
mit
| 411
|
#include <core/reflection/dynamic/DynamicObject.h>
#include <core/reflection/dynamic/DynamicObjectImplementation.h>
#include <core/reflection/dynamic/DynamicReflectedObjectImplementation.h>
#include <core/reflection/dynamic/DynamicMappedObject.h>
#include <core.utility.h>
#include <core/reflection/type/Argument.implementation.template.h>
//#include <core.reflection.builder.h>
NS_USE(CORE_NAMESPACE);
//reflect_type_default_definition(NS(CORE_NAMESPACE)::DynamicObject)
DynamicObject::DynamicObject(std::shared_ptr<DynamicObjectImplementation> impl):_implementation(impl){}
IModifiableValue & DynamicObject::operator[](const std::string & name){
return *getProperty(name);
}
DynamicCallable DynamicObject::getMethod(const std::string & name){
Argument a = _implementation->getMember(name)->get();
return a;
}
bool DynamicObject::hasMember(const std::string & name)const{ return hasProperty(name)||hasMethod(name);}
bool DynamicObject::hasProperty(const std::string & name)const{
return _implementation->hasProperty(name);
}
bool DynamicObject::hasMethod(const std::string & name)const{
return _implementation->hasMethod(name);
}
DynamicObject::MemberList DynamicObject::getMemberNames()const{
return concat(getPropertyNames(),getMethodNames());
}
DynamicObject::MemberList DynamicObject::getMethodNames()const{
return _implementation->getMethodNames();
}
DynamicObject::MemberList DynamicObject::getPropertyNames()const{
return _implementation->getPropertyNames();
}
std::shared_ptr<IModifiableValue> DynamicObject::getProperty(const std::string & name){
return _implementation->getMember(name);
}
std::shared_ptr<const IModifiableValue> DynamicObject::getProperty(const std::string & name)const{
return _implementation->getMember(name);
}
Argument DynamicObject::operator*(){
return _implementation->asArgument();
}
NS_BEGIN(CORE_NAMESPACE)
DynamicObject make_dynamic_mapped(Argument arg){
return DynamicObject(std::make_shared<DynamicMappedObjectImplementation>());
}
DynamicObject make_dynamic(Argument argument){
DynamicObject result(std::make_shared<DynamicReflectedObjectImplementation>(argument));
return result;
}
bool copy(DynamicObject & destination, const DynamicObject & source){
auto names = concat(source.getPropertyNames(),destination.getPropertyNames());
std::sort(std::begin(names),std::end(names));
names.erase(std::unique(std::begin(names),std::end(names)),std::end(names));
for(auto it = std::begin(names); it != std::end(names); it++){
auto d = destination.getProperty(*it);
auto s = source.getProperty(*it);
auto value = s->get();
if(!value.isValid())continue;
d->set(value);
}
return true;
}
NS_END(CORE_NAMESPACE)
|
toeb/cpp.core
|
core/src/core/reflection/dynamic/DynamicObject.cpp
|
C++
|
mit
| 2,772
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'km', {
button: 'ពុម្ពគំរូ',
emptyListMsg: '(មិនមានពុម្ពគំរូត្រូវបានកំណត់)',
insertOption: 'ជំនួសក្នុងមាតិកាបច្ចុប្បន្ន',
options: 'ជម្រើសពុម្ពគំរូ',
selectPromptMsg: 'សូមរើសពុម្ពគំរូដើម្បីបើកក្នុងកម្មវិធីសរសេរអត្ថបទ',
title: 'ពុម្ពគំរូមាតិកា'
});
|
webmasterETSI/web
|
web/ckeditor/plugins/templates/lang/km.js
|
JavaScript
|
mit
| 806
|
/*
*
*
*/
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
void addOperatorsDFS(string num, int target, long long diff, long long curNum, string out, vector<string> &res) {
if (num.size() == 0 && curNum == target) {
res.push_back(out);
}
for (int i = 1; i <= num.size(); ++i) {
string cur = num.substr(0, i);
if (cur.size() > 1 && cur[0] == '0') return;
string next = num.substr(i);
if (out.size() > 0) {
addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, res);
addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, res);
addOperatorsDFS(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, res);
} else {
addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
}
}
}
};
// Conclusion:
//
|
xpharry/Leetcode
|
leetcode/cpp/282.cpp
|
C++
|
mit
| 1,128
|
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using NUnit.Framework;
using TimeAndDate.Services.Tests;
using TimeAndDate.Services.DataTypes.Places;
using TimeAndDate.Services.DataTypes.Time;
namespace TimeAndDate.Services.Tests.IntegrationTests
{
[TestFixture()]
public class ConvertTimeTestsAsync
{
public const string fromCountry = "Norway";
public const string fromCity = "Oslo";
public static LocationId fromCoords;
public string fromFormat = String.Format ("{0}/{1}", fromCountry, fromCity).ToLower ();
public static LocationId fromId;
public const string toUsState = "Alaska";
public const string toUsCountry = "USA";
public const string toUsCity = "Anchorage";
public string toUsFormat = String.Format ("{0}/{1}", toUsCountry, toUsCity).ToLower ();
public LocationId toUsId;
public const string toArticCountry = "Antarctica";
public const string toArticCity = "Troll";
public string toArticFormat = String.Format ("{0}/{1}", toArticCountry, toArticCity).ToLower ();
public LocationId toArticId;
[SetUp()]
public void Setup ()
{
fromCoords = new LocationId(new Coordinates (59.913m, 10.752m));
fromId = new LocationId (fromFormat);
toUsId = new LocationId (toUsFormat);
toArticId = new LocationId (toArticFormat);
}
[Test()]
public async Task Calling_ConvertTimeService_WithNoId_And_WithDateTime_Should_ReturnCorrectConvertedTime ()
{
// Arrange
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now);
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithOneToId_And_WithDateTime_Should_ReturnCorrectConvertedTime ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now, toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (oslo.Geography.Name, fromCity);
Assert.AreEqual (oslo.Geography.Country.Name, fromCountry);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithMultipleToIds_And_WithDateTime_Should_ReturnCorrectConvertedTime ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
toId.Add (toArticId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now, toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
var troll = result.Locations.FirstOrDefault (x => x.Id == "4365");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (troll.Geography.Country.Name, toArticCountry);
Assert.AreEqual (troll.Geography.Name, toArticCity + " Station");
Assert.AreEqual (oslo.Geography.Name, fromCity);
Assert.AreEqual (oslo.Geography.Country.Name, fromCountry);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithMultipleToIds_And_WithISO_Should_ReturnCorrectConvertedTime ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
toId.Add (toArticId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
var troll = result.Locations.FirstOrDefault (x => x.Id == "4365");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (toArticCountry, troll.Geography.Country.Name);
Assert.AreEqual (toArticCity + " Station", troll.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithNoId_And_WithISO_Should_ReturnCorrectConvertedTime ()
{
// Arrange
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture));
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithOneToId_And_WithISO_Should_ReturnCorrectConvertedTime ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
HasCorrectUtc (result.Utc.DateTime);
}
[Test()]
public async Task Calling_ConvertTimeService_WithoutTimeChanges_Should_NotReturnTimeChanges ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = false;
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
Assert.IsTrue (result.Locations.All (x => x.TimeChanges.Count == 0));
}
[Test()]
public async Task Calling_ConvertTimeService_WithTimeChanges_Should_ReturnTimeChanges ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
service.IncludeTimeChanges = true; // Default
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
Assert.IsTrue (result.Locations.All (x => x.TimeChanges != null));
}
[Test()]
public async Task Calling_ConvertTimeService_WithoutTimezone_Should_NotReturnTZInformation ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
service.IncludeTimezoneInformation = false;
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
Assert.IsTrue (result.Locations.All (x => x.Time.Timezone == null));
}
[Test()]
public async Task Calling_ConvertTimeService_WithTimezone_Should_ReturnTZInformation ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
service.IncludeTimezoneInformation = true; // Default
var result = await service.ConvertTimeAsync (fromId, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
Assert.IsTrue (result.Locations.All (x => x.Time.Timezone != null));
}
[Test()]
public async Task Calling_ConvertTimeService_WithRadius_Should_ReturnCorrectLocation ()
{
// Arrange
var toId = new List<LocationId> ();
toId.Add (toUsId);
// Act
var service = new ConvertTimeService (Config.AccessKey, Config.SecretKey);
service.Radius = 50;
var result = await service.ConvertTimeAsync (fromCoords, DateTime.Now.ToString ("s", CultureInfo.InvariantCulture), toId);
var anchorage = result.Locations.FirstOrDefault (x => x.Id == "18");
var oslo = result.Locations.FirstOrDefault (x => x.Id == "187");
// Assert
Assert.AreEqual (toUsState, anchorage.Geography.State);
Assert.AreEqual (toUsCity, anchorage.Geography.Name);
Assert.AreEqual (fromCity, oslo.Geography.Name);
Assert.AreEqual (fromCountry, oslo.Geography.Country.Name);
Assert.IsTrue (result.Locations.All (x => x.Time.Timezone != null));
}
public void HasCorrectLocation(TADDateTime date, Location location)
{
Assert.AreEqual (date.Year, location.Time.DateTime.Year);
Assert.AreEqual (date.Month, location.Time.DateTime.Month);
Assert.AreEqual (date.Day, location.Time.DateTime.Day);
Assert.AreEqual (date.Hour, location.Time.DateTime.Hour);
Assert.AreEqual (date.Minute, location.Time.DateTime.Minute);
}
public void HasCorrectUtc(TADDateTime date)
{
Assert.AreEqual (DateTime.UtcNow.Year, date.Year);
Assert.AreEqual (DateTime.UtcNow.Month, date.Month);
Assert.AreEqual (DateTime.UtcNow.Day, date.Day);
Assert.AreEqual (DateTime.UtcNow.Hour, date.Hour);
Assert.AreEqual (DateTime.UtcNow.Minute, date.Minute);
}
}
}
|
timeanddate/libtad-net
|
TimeAndDate.Services.Tests/IntegrationTests/async/ConvertTimeServiceTests.cs
|
C#
|
mit
| 11,708
|
---
layout: page
title: Mccall 15th Anniversary
date: 2016-05-24
author: Natalie Bryant
tags: weekly links, java
status: published
summary: Etiam dignissim rutrum nisi, et tristique.
banner: images/banner/meeting-01.jpg
booking:
startDate: 02/11/2018
endDate: 02/16/2018
ctyhocn: CLLTEHX
groupCode: M1A
published: true
---
Integer vel tempus massa, vitae tristique lacus. Maecenas vel luctus neque. Suspendisse at dignissim tellus. Proin a tellus tristique, consectetur ipsum sed, feugiat quam. Proin gravida est mauris. Nulla id efficitur nunc. Aliquam pulvinar faucibus urna id vulputate. Integer vel nulla lacinia, pellentesque ligula sit amet, consequat tortor. Nam tempus facilisis orci at rhoncus. Mauris cursus molestie quam vitae ultrices.
Donec velit neque, pretium a odio ac, sollicitudin mattis risus. Vestibulum vel nunc ligula. Aenean eu justo in tortor vestibulum tristique. Maecenas sit amet imperdiet velit. Vestibulum egestas sem ac posuere mattis. Aenean massa nulla, molestie nec eros vel, sollicitudin maximus dolor. Phasellus lorem justo, iaculis vel tellus eget, viverra convallis tellus.
* Suspendisse luctus ante id ipsum rhoncus egestas
* Mauris convallis lorem sed diam congue commodo
* Phasellus facilisis erat at euismod mollis
* Praesent hendrerit enim at mi mattis convallis
* Fusce commodo massa ut massa elementum ornare
* Sed vitae urna lacinia ipsum suscipit pulvinar.
Nunc et quam vitae arcu lacinia semper. Quisque placerat nisi vitae malesuada elementum. Donec sed rutrum mauris. Fusce ante felis, tincidunt at libero quis, efficitur dignissim odio. Pellentesque bibendum nibh ut ex finibus dignissim. Vestibulum feugiat, erat sit amet rhoncus malesuada, libero risus faucibus justo, scelerisque faucibus leo felis ac nisl. Mauris sed viverra ligula. Suspendisse potenti. Integer blandit libero justo, sit amet faucibus neque vestibulum vitae. Aliquam eros enim, viverra at felis a, viverra lobortis erat. Nullam elit diam, finibus in purus ut, consequat ullamcorper purus. Donec imperdiet enim nec pulvinar cursus. Ut sit amet tincidunt mauris. Ut bibendum rhoncus nisl, id pretium massa ullamcorper a.
Duis bibendum laoreet mollis. Donec ac venenatis risus. Cras dictum mauris mi, et elementum velit ultricies ac. Donec nunc urna, dapibus vel lorem nec, sagittis rhoncus odio. Sed pharetra ut dui quis bibendum. Fusce ultrices at tellus non blandit. Sed cursus dolor id nunc iaculis, ut consequat neque iaculis. In cursus accumsan dolor non ultrices. Aliquam quis volutpat purus. Nunc vel odio ut ante egestas elementum in ut eros. Vivamus sit amet iaculis mauris. Aliquam erat volutpat. Morbi consequat laoreet pellentesque. Nullam ut lacus eu quam gravida facilisis. Morbi vitae ante id nunc maximus viverra.
|
KlishGroup/prose-pogs
|
pogs/C/CLLTEHX/M1A/index.md
|
Markdown
|
mit
| 2,760
|
#http://pandas.pydata.org/pandas-docs/stable/tutorials.html
#file='pand.py'
#exec(compile(open(file).read(), file, 'exec'))
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import pandas as pd
#import sys
#import matplotlib
names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]
BabyDataSet = list(zip(names,births)) # zip pairs entries together and list combines the entries to a list
print(BabyDataSet)
#The DataFrame attribute of pandas reorganizes the list into a tabular panda object
#similar to an sql table or an excel spreadsheet.
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
print(df)
wait = input("PRESS ENTER TO CONTINUE.")
#We can now save the content as a standard tabular data format (csv)
df.to_csv('births1880.csv',index=False,header=False)
#We can also read back from the same file into a panda object
df = pd.read_csv(r'births1880.csv')
print(df)
print('Wrong header. read_cvs treated the first record as the header')
print('set the header to null')
wait = input("PRESS ENTER TO CONTINUE.")
df = pd.read_csv(r'births1880.csv',header=None)
print(df)
print('Now we have the right data but no header')
print('Label the headers')
wait = input("PRESS ENTER TO CONTINUE.")
df = pd.read_csv(r'births1880.csv', names=['Names','Births'])
print(df)
print('This looks like the table we need')
print('Numbers of 0,1,2,3,4 are row numbers similar to an Excel spreadsheet')
wait = input("PRESS ENTER TO CONTINUE.")
print('Lets do something with this tabulated data')
print('Sort the dataframe and select the top row')
Sorted1=df.sort_values(['Births'], ascending=False)
#Sorted2=df.sort_values(by='Births', ascending=False)
#Sorted.head(1)
print(Sorted1)
wait = input("PRESS ENTER TO CONTINUE.")
print('Use the max() attribute to find the maximum value')
MaxValue=df['Births'].max()
print('MaxValue is ',MaxValue)
wait = input("PRESS ENTER TO CONTINUE.")
print('Convert a column to an array')
print(df['Names'].values)
print('Reference the second entry')
print(df['Names'][1:2].values)
print('Apply a booleen mask on the Births column when compared to the MaxValue')
mask = df['Births']==MaxValue
print(mask)
print('Find the name associated with the maximum value')
MaxName = df['Names'][mask].values
print('Name at Max Value is ',MaxName)
wait = input("PRESS ENTER TO CONTINUE.")
#Create a graph object
print('Create a graph object')
df['Births'].plot()
# Text to display on graph
print('Construct a string to display on the graph')
Text = str(MaxValue) + " - " + MaxName
print(Text)
# Add text to graph
print('Annonate the graph')
plt.annotate(Text, xy=(1, MaxValue), xytext=(8, 0),
xycoords=('axes fraction', 'data'), textcoords='offset points')
print('Show the graph')
plt.show()
#Uncomment the following to save it as a png file
#plt.savefig('mygraph.png')
|
nuitrcs/python-researchers-toolkit
|
scripts/pand.py
|
Python
|
mit
| 2,880
|
<!DOCTYPE html>
<html>
<head>
<!-- -->
<title>comfyinvestor - get comfy and learn to build wealth</title>
<meta name="description" content="Use comfyinvestor's stock chart analysis tool and guides to build your understanding of price-volume charts and technical buy points."
<meta charset="utf-8">
<!-- Is this just for IE? -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap Styles -->
<link rel="stylesheet" href="stylesheets/bootstrap.css">
<!-- comfystyles -->
<link rel="stylesheet" href="stylesheets/style.css">
<!--<link rel="stylesheet" href="stylesheets/chart-analysis.css">
-->
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Work+Sans' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Gentium+Book+Basic:700' rel='stylesheet' type='text/css'>
<!-- Favicons -->
<link href="assets/favicon.jpg" rel="icon" type="image/x-icon" />
<!-- Plot.ly JS -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdn.rawgit.com/etpinard/plotlyjs-finance/master/plotlyjs-finance.js"></script>
<!-- Google Analytics Tracking -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-78033513-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<!-- Nav Bar -->
<div class='navbar navbar-fixed-top'>
<div class='container'>
<a href="http://comfyinvestor.com" class='navbar-brand'>
<img class="logo" src="images/ci-logo-2.png" alt="ComfyInvestor Logo">
</a>
<ul class="list-unstyled desktop-brow-nav">
<li>
<div class="nav-search-box">
<div>
<div class="nav-search-icon">
<i id="ticker-submit-button" class="glyphicon glyphicon-search button"></i>
</div>
<div>
<input class="form-control nav-search" type="text" id="ticker-textbox" placeholder="Example: FB"/>
</div>
</div>
</div>
<!--
<input type="text" class="form-control nav-search" id="stock" placeholder="TSLA"><i class="glyphicon glyphicon-search"></i>-->
</li>
<li><a href="http://comfyinvestor.com/about">about</a></li>
<li><a href="http://comfyinvestor.com/guides">guides</a></li>
<li><a href="http://comfyinvestor.com/chart-analysis">chart analysis</a></li>
</ul>
</div>
<!-- Border/Shadowsberg -->
<div class="banner"></div>
</div>
<!-- Guides Section -->
<div class='container'>
<div class='row'>
<h2>About comfyinvestor</h2>
<hr>
<div class='container'>
<p><b>comfyinvestor is a site created to educate and empower new investors.</b></p>
<p> we want to make learning to invest straight forward by providing informative guides and helpful research and analysis tools.</p>
<p>a key component of comfyinvestor's philosophy is a belief in numbers and statistics before speculation. the majority of information you will find on comfyinvestor is rooted in data, facts, and analysis.</p>
<img>
</div>
<h2>Team</h2>
<hr>
<div class='container'>
<p>The comfyinvestor team is a tight-knit unit comprised of 2 dudes named Mike. Both Mikes have over 10 years of investing experience and are passionate researchers of different strategies and concepts of the financial markets.</p>
<img class='hidden-sm hidden-xs' src="">
</div>
</div>
</div>
<!-- Footer Section -->
<div class='footer'>
<div class='container'>
<div class='row'>
<div class='col-sm-4 col-xs-12'>
<h4>Our Philosophy</h4>
<p>investing can change your life<br>
& learning to invest can be easy<br></p>
<p><a href='http://comfyinvestor.com/'>More About Us <i class='glyphicon glyphicon-arrow-right'></i></a></p>
</div>
<div class='col-sm-2 col-sm-offset-1 col-xs-6'>
<h4>Links</h4>
<ul class='list-unstyled'>
<li><a href='http://comfyinvestor.com'>Home</a></li>
<li><a href='http://comfyinvestor.com/chart-analysis'>Chart Analysis</a></li>
<li><a href='http://comfyinvestor.com/guides'>Guides</a></li>
<li><a href='http://comfyinvestor.com/about-us'>About</a></li>
</ul>
</div>
<div class='col-sm-4 col-sm-offset-1 col-xs-6'>
<h4>Contact Us</h4>
<ul class='list-unstyled'>
<li><i class='glyphicon glyphicon-globe'></i> Santa Barbara, CA</li>
<li><i class='glyphicon glyphicon-envelope'></i> <a href='mailto:mjlafirenza@gmail.com'>info@comfyinvestor.com</a></li>
</ul>
<br>
<p>comfyshorts, inc. © 2016</p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>-->
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/js/bootstrap.js"></script>
<script src="javascripts/chart-analysis.js"></script>
</body>
</html>
|
comfyinvestor/ci
|
about.html
|
HTML
|
mit
| 6,362
|
---
uid: SolidEdgePart.TubeFeatures.Item(System.Object)
summary:
remarks:
syntax:
parameters:
- id: Index
description: Variant (input) index.
---
|
SolidEdgeCommunity/docs
|
docfx_project/apidoc/SolidEdgePart.TubeFeatures.Item.md
|
Markdown
|
mit
| 165
|
var twimap;
twimap = require("twimap");
var Twit = require("twit");
var util = require("util");
var _current_index = -1;
var _followers_list ;
var thanks_temp;
thanks_temp = [
"Dear %s, thank you for following :)",
"%s = awesome. Me = grateful for following :)",
"Is there no limit to your awesomeness %s? Thank you for following!",
"You can’t see me %s! but I’m totally doing a happy dance! Big thanks for following me on twitter :)",
"hey %s!Do you practice being so wonderful? Thank you kindly for following."
];
// create twitter client
twit_cli = new Twit({
consumer_key: "---consumer-key---"
, consumer_secret: "---consumer-secret---"
, access_token: "---access-token---"
, access_token_secret: "---access-token-secret---"
});
//config TWIMAP imap account
twimap.configImap({
user : '---username---@gmail.com',
password : '---password---',
host : 'imap.gmail.com',
port : 993,
secure : true
});
// stores last imap try
var last_check = now();
//call this function periodically to get new followers
//callback is called when new information is available
function load_followers_priodically() {
try{
twimap.followersAsync(last_check, function(result) {
if(typeof result != "undefined" && result.length >=1){
//save it in our variable
_followers_list = result;
last_check = now();
msg_followers_thanks();
}
},function (err){
// I command you to stay silent
reset_values();
});
}catch(e){
//still...
reset_values();
console.log(e);
}
}
//this function iterates through followers listed in variable
//_followers_list
function msg_followers_thanks(){
//move cursor
_current_index++;
//if there is no followers OR finished messaging followers stop
if(_current_index >= _followers_list.length ){
_current_index = -1;
_followe_list = null;
return;
}
//otherwise get user name from twitter
twit_cli.get("users/show",{screen_name:_followers_list[_current_index]}, function (err,dt){
//clean up the name
var dude = filter_name(dt.name);
//message the user
twit_cli.post("direct_messages/new" , {screen_name:_followers_list[_current_index],text:random_msg(dude)}, function (err,dt){
if(!err) console.log("done...");
//go for another round
msg_followers_thanks();
});
});
}
//cut names bigger that 40 characters
function filter_name(name){
if ( typeof name == "undefined" || name=="" || name==null) name = "my friend";
if(name.length > 40 ) name = name.substr(0,40);
return name;
}
//generate a random message
function random_msg(name){
name = filter_name(name);
return util.format(thanks_temp[Math.floor(Math.random()*10)%(thanks_temp.length-1)] , name);
}
//return current day
function now() {
var d;
d = new Date();
return d.toUTCString();
}
//reset values on error
function reset_values(){
_current_index = -1;
_followers_list = null;
}
// run safe and sound :|
function run(){
_interval = setInterval(load_followers_priodically,1000*60*30);
//run now , I can't wait ;)
load_followers_priodically();
}
//cheers to a happy running ;)
run();
|
rasouli/twimap
|
examples/thanker.js
|
JavaScript
|
mit
| 3,226
|
using System;
namespace PCLExt.Network
{
/// <summary>
///
/// </summary>
public static class SocketClient
{
private static Exception NotImplementedInReferenceAssembly() =>
new NotImplementedException(@"This functionality is not implemented in the portable version of this assembly.
You should reference the PCLExt.Network NuGet package from your main application project in order to reference the platform-specific implementation.");
/// <summary>
///
/// </summary>
/// <returns></returns>
public static ITCPClient CreateTCP()
{
#if DESKTOP || ANDROID || __IOS__ || MAC || NETSTANDARD2_0
return new DesktopTCPClient();
#endif
throw NotImplementedInReferenceAssembly();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static ITCPClientEvent CreateTCPEvent()
{
#if DESKTOP || ANDROID || __IOS__ || MAC || NETSTANDARD2_0
return new DesktopTCPClientEvent();
#endif
throw NotImplementedInReferenceAssembly();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IUDPClient CreateUDP()
{
#if DESKTOP || ANDROID || __IOS__ || MAC || NETSTANDARD2_0
return new DesktopUDPClient();
#endif
throw NotImplementedInReferenceAssembly();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IUDPClientEvent CreateUPDEvent()
{
#if DESKTOP || ANDROID || __IOS__ || MAC || NETSTANDARD2_0
return new DesktopUDPClientEvent();
#endif
throw NotImplementedInReferenceAssembly();
}
}
}
|
Aragas/PCLExt.Network
|
src/PCLExt.Network/SocketClient.cs
|
C#
|
mit
| 1,802
|
import { expect } from 'chai';
import { validateRegister, validateLogin } from '../../src/universal/validation/authValidation';
describe('validation', () => {
describe('validateRegister', () => {
it('passes for acceptable details', () => {
const username = 'username';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors).to.be.empty;
});
it('fails with no username', () => {
const username = '';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Please provide a username');
});
it('fails for a username with non alpha numeric or hypen', () => {
const username = 'B4D4$$!!!!';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen');
});
it('fails for a username with spaces', () => {
const username = 'bad username';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen');
});
it('fails with no password', () => {
const username = 'username';
const password = '';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.password).to.equal('Please supply a password');
});
it('fails for a password under 6 characters', () => {
const username = 'username';
const password = 'passw';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.password).to.equal('Please supply a password over 6 characters');
});
it('fails with no email', () => {
const username = 'username';
const password = 'password';
const email = '';
const errors = validateRegister(username, password, email);
expect(errors.email).to.equal('Please provide an email');
});
it('fails with an invalid email', () => {
const username = 'username';
const password = 'password';
const email = '234567';
const errors = validateRegister(username, password, email);
expect(errors.email).to.equal('Please provide a valid email address');
});
});
describe('validateLogin', () => {
it('passes with both username and password', () => {
const username = 'username';
const password = 'password';
const errors = validateLogin(username, password);
expect(errors).to.be.empty;
});
it('fails with no username', () => {
const username = '';
const password = 'password';
const errors = validateLogin(username, password);
expect(errors.username).to.equal('Please provide a username');
});
it('fails with no password', () => {
const username = 'username';
const password = '';
const errors = validateLogin(username, password);
expect(errors.password).to.equal('Please supply a password');
});
});
});
|
YorkshireDigital/yorkshiredigital.com
|
test/validation/authValidation_spec.js
|
JavaScript
|
mit
| 3,536
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# Username Test
should validate_presence_of(:username)
should validate_length_of(:username).is_at_least(5).is_at_most(32)
should validate_uniqueness_of(:username).case_insensitive
# Email Test
should validate_presence_of(:email)
should validate_uniqueness_of(:email).case_insensitive
valid_emails = %w[valid@example.org t.e.s.t@example.com
test+tags@example.random.tld]
valid_emails.each do |valid|
should allow_value(valid).for(:email)
end
invalid_emails = %w[not_an_email @forgottheprefix.com fail_at_wrong_dot_com
foo@bar_baz.com foo@bar+baz.com]
invalid_emails << "#{ 'x' * 244 }@example.com"
invalid_emails.each do |invalid|
should_not allow_value(invalid).for(:email)
end
# Password Test
should have_secure_password
end
|
jeyavelnkl/jel_apps
|
todo-app-railsconf/test/models/user_test.rb
|
Ruby
|
mit
| 876
|
const NUM_HASHES = HASHES.length;
function verify(id, accessCode) {
var token = id.replace(/\s+/g, '').toLowerCase() + accessCode;
for (var i = 0; i < NUM_HASHES; ++i) {
var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1);
if (/^https?:\/\/[^\s]+$/.test(result)) {
window.location = result;
return true;
}
}
// Display denial
$("#lit-header").removeClass("power-on");
document.getElementById("go").className = "denied";
document.getElementById("go").value = "Access Denied";
return false;
}
$(document).ready(function() {
var state = false;
var numAttempts = 0;
$('#access-panel').on('submit', function(evt) {
evt.preventDefault();
if (!state && numAttempts < 10) {
state = true;
$("#lit-header").addClass("power-on");
document.getElementById("go").className = "";
document.getElementById("go").value = "Verifying...";
numAttempts += 1;
setTimeout(function() {
verify($('#name').val(), $('#password').val());
state = false;
}, 2000);
}
});
});
|
ohjay/ohjay.github.io
|
js/flickering.js
|
JavaScript
|
mit
| 1,236
|
const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');
const CMD = 'MODE';
describe(CMD, function () {
let sandbox;
const mockClient = {
reply: () => Promise.resolve()
};
const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);
beforeEach(() => {
sandbox = sinon.sandbox.create().usingPromise(Promise);
sandbox.spy(mockClient, 'reply');
});
afterEach(() => {
sandbox.restore();
});
it('S // successful', () => {
return cmdFn({command: {arg: 'S'}})
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(200);
});
});
it('Q // unsuccessful', () => {
return cmdFn({command: {arg: 'Q'}})
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(504);
});
});
});
|
trs/ftp-srv
|
test/commands/registration/mode.spec.js
|
JavaScript
|
mit
| 845
|
export { default } from './BottomNavigation';
export { default as BottomNavigationAction } from './BottomNavigationAction';
|
cherniavskii/material-ui
|
packages/material-ui/src/BottomNavigation/index.js
|
JavaScript
|
mit
| 124
|
package com.creatubbles.api.repository;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.creatubbles.api.ContentType;
import com.creatubbles.api.model.CreatubblesResponse;
import com.creatubbles.api.model.creation.Creation;
import com.creatubbles.api.model.creation.ToybooDetails;
import com.creatubbles.api.model.image_manipulation.ImageManipulation;
import com.creatubbles.api.model.upload.UploadState;
import com.creatubbles.api.response.ResponseCallback;
import com.creatubbles.api.response.UploadResponseCallback;
import java.io.File;
import java.util.List;
/**
* Interface defining methods operating on creations.
* To create an instance use {@link CreationRepositoryBuilder}.
*/
public interface CreationRepository {
/**
* @param page number of the page
* @param onlyPublic set true to get only approved Creations
*/
void getRecent(@Nullable Integer page, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
void getRecent(@Nullable Integer page, @Nullable Integer pageSize,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* @param page number of the page
* @param galleryId the ID of Gallery from which the Creations should be returned
* @param onlyPublic set true to get only approved Creations
*/
void getFromGallery(@Nullable Integer page, @NonNull String galleryId, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* @param page number of the page
* @param userId the ID of the User whom's Creations should be returned
* @param onlyPublic set true to get only approved Creations
*/
void getByUser(@Nullable Integer page, @NonNull String userId, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* @param page number of the page
* @param name keyword to filter Creations by name
* @param onlyPublic set true to get only approved Creations
*/
void getByName(@Nullable Integer page, @NonNull String name, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
void getById(@NonNull String creationId, @Nullable ResponseCallback<CreatubblesResponse<Creation>> callback);
/**
* Method used to obtain a list of recommended Creations by given Creation.
*
* @param page number of the page
* @param onlyPublic set true to get only approved Creations
*/
void getRecommendedByCreation(@Nullable Integer page, @NonNull String creationId, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* Method used to obtain a list of recommended creations added by given user.
*
* @param page number of the page
* @param onlyPublic set true to get only approved Creations
*/
void getRecommendedByUser(@Nullable Integer page, @NonNull String creationId, @Nullable Boolean onlyPublic,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* Method used to obtain a list of creations by Partner Application.
*/
void getByPartnerApplication(@Nullable Integer page, @NonNull String partnerApplicationId,
@Nullable ResponseCallback<CreatubblesResponse<List<Creation>>> callback);
/**
* Method used to update Creation with a given ID.
*
* @param creationId the ID of Creation to update
* @param creation Creation object with values to update. Only a few properties can be modified.
* To create this object use {@link com.creatubbles.api.model.creation.Creation.Builder}
* and set only the properties you want to update.
*/
void update(@NonNull String creationId, @NonNull Creation creation, @Nullable ResponseCallback<Void> callback);
/**
* Method used to create a new Creation.
*
* @param creation Creation instance created using {@link com.creatubbles.api.model.creation.Creation.Builder}.
*/
void create(@NonNull Creation creation, @Nullable ResponseCallback<CreatubblesResponse<Creation>> callback);
/**
* @param creationId the ID of Creation that should be removed
*/
void remove(@NonNull String creationId, @Nullable ResponseCallback<Void> callback);
/**
* Creates a creation, manages the upload of the file, and updates the server
* @param creation Creation instance created using {@link com.creatubbles.api.model.creation.Creation.Builder}.
* @param file File to be used for upload
* @param contentType Content type of the file
* @param galleryIds Galleries this creation should belong to
* @param callback Callback
*/
void uploadCreation(@NonNull Creation creation, @NonNull File file, @NonNull ContentType contentType, @Nullable List<String> galleryIds, @Nullable UploadResponseCallback<Creation> callback);
/**
* Resumes operations of creating, uploading, updating server.
*
* @param creation Creation instance created using {@link com.creatubbles.api.model.creation.Creation.Builder}.
* @param file File to be used for upload
* @param contentType Content type of the file
* @param galleryIds Galleries this creation should belong to
* @param uploadState The last upload state reported by the callback on your last try
* @param callback Callback
*/
void resumeUploadCreation(@NonNull Creation creation, @NonNull File file,
@NonNull ContentType contentType, @Nullable List<String> galleryIds,
@NonNull UploadState uploadState,
@Nullable UploadResponseCallback<Creation> callback);
/**
* Method used to modify image of a creation identified by {@code creationId}.
*
* @param imageManipulation object describing operations to perform on an image
*/
void updateImage(@NonNull String creationId, @NonNull ImageManipulation imageManipulation, @Nullable ResponseCallback<Void> callback);
/**
* Method used to obtain toyboo details for specific creation
*
* @param creationId the ID of Creation
*/
void getToybooDetails(@NonNull String creationId, @Nullable ResponseCallback<CreatubblesResponse<ToybooDetails>> callback);
/**
* Method used to update creation views count
*
* @param creationId the ID of Creation
*/
void updateViewsCount(@NonNull String creationId, @Nullable ResponseCallback<Void> callback);
}
|
creatubbles/ctb-api-android
|
api/src/main/java/com/creatubbles/api/repository/CreationRepository.java
|
Java
|
mit
| 6,961
|
class RoomCalendar
def initialize(room, url)
interval = 2.months
@calendar = RiCal.Calendar do |cal|
cal.add_x_property 'x_wr_calname', "#{room.name} - bookIT"
cal.add_x_property 'x_wr_caldesc', "Bokningar av #{room.name} ifrån bookIT"
cal.add_x_property 'url', url
cal.prodid = 'bookIT'
room.bookings.from_date(interval.ago).each do |b|
cal.event do |e|
e.summary = b.title
e.description = b.description
e.dtstart = b.begin_date
e.dtend = b.end_date
e.location = room.name
end
end
end
end
def to_s
@calendar.export
end
end
|
cthit/bookIT
|
app/calendars/room_calendar.rb
|
Ruby
|
mit
| 589
|
class Delivery
attr_accessor :day_of_week, :time_of_day, :selection_type
attr_accessor :number_of_boxes
def initialize(day_of_week=:Sat, time_of_day=:AM, selection_type=:RW, number_of_boxes=1)
@day_of_week = day_of_week
@time_of_day = time_of_day
@selection_type = selection_type
@number_of_boxes = number_of_boxes
end
def to_h
{
'dow' => @day_of_week.to_s,
'tod' => @time_of_day.to_s,
'selection_type' => @selection_type.to_s
}
end
end
|
mazen555/vin
|
lib/vin/model/delivery.rb
|
Ruby
|
mit
| 495
|
//
// TwitterDetailedViewController.h
// BBCSherlock
//
// Created by B.H.Liu appublisher on 11-12-20.
// Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "OHAttributedLabel.h"
#import "NSAttributedString+Attributes.h"
#import "AsyncImageView.h"
@interface TwitterDetailedViewController : UIViewController
@property (nonatomic, retain) OHAttributedLabel* textLabel;
@property (nonatomic, retain) AsyncImageView *avatarImage;
@property (nonatomic, retain) NSDictionary *tweetDict;
- (id)initWithDict:(NSDictionary *)dict;
@end
|
aceisScope/sherlockinfo
|
BBCSherlock_App Store_1.3/BBCSherlock/DetailControllers/TwitterDetailedViewController.h
|
C
|
mit
| 583
|
<h1>Actualizar Resguardo <?php echo $model->id; ?></h1>
<?php $this->renderPartial('_formUpdate', array('model'=>$model)); ?>
|
Nesdf/upp_nes
|
protected/views/resguardo/update.php
|
PHP
|
mit
| 128
|
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// 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 Sharpex2D.Audio;
namespace Sharpex2D.Common.Extensions
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public static class AudioEffectExtension
{
/// <summary>
/// Initializes the audio effect fluently.
/// </summary>
/// <param name="effect">The AudioEffect.</param>
/// <param name="audioSource">The AudioSource.</param>
/// <returns>AudioEffect.</returns>
public static AudioEffect FluentInitialize(this AudioEffect effect, AudioSource audioSource)
{
effect.AudioSource = audioSource;
effect.Initialize();
return effect;
}
}
}
|
ThuCommix/Sharpex2D
|
Sharpex2D/Common/Extensions/AudioEffectExtension.cs
|
C#
|
mit
| 1,846
|
package communication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import model.UserPOJO;
import util.HttpUtil;
import java.lang.reflect.Type;
import java.util.*;
/**
* @author Jack Meyer (jackcmeyer@gmail.com)
*
* A wrapper for communicating with the user service
*/
public class UserServiceCommunication {
private static final String USER_BASE_URL = "http://localhost:8000/users/";
/**
* Gets all users
*/
public List<UserPOJO> getAllUsers() {
try {
String json = HttpUtil.executeGetRequest(USER_BASE_URL);
Gson gson = new Gson();
Type typeList = new TypeToken<ArrayList<UserPOJO>>(){}.getType();
List<UserPOJO> userList = gson.fromJson(json, typeList);
return userList;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Get a user by their id
*
* @param id the id to find by
*/
public UserPOJO getUser(Long id) {
try {
String json = HttpUtil.executeGetRequest(USER_BASE_URL + id);
return jsonToUser(json);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Add a user to the database
*
* @param parameters a hashmap which holds the parameters
*/
public UserPOJO addUser(HashMap<String, String> parameters) {
// create request parameter string
Iterator iterator = parameters.entrySet().iterator();
StringBuilder builder = new StringBuilder();
builder.append("{");
while(iterator.hasNext()) {
Map.Entry pair = (Map.Entry) iterator.next();
builder.append("\"" + pair.getKey() + "\" : " + "\"" +pair.getValue() + "\", ");
}
String requestBody = builder.toString();
requestBody = requestBody.substring(0, requestBody.length()-2);
requestBody = requestBody + "}";
try {
String json = HttpUtil.executePostRequest(USER_BASE_URL, requestBody);
return jsonToUser(json);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Deletes a user by their id
*
* @param id the id to delete by
*/
public UserPOJO deleteUser(Long id) {
try {
String json = HttpUtil.executeDeleteRequest(USER_BASE_URL + id);
return jsonToUser(json);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Converts a json string to a UserPOJO object
* @param json the json string
* @return the user pojo object
*/
private UserPOJO jsonToUser(String json) {
Gson gson = new Gson();
UserPOJO user = gson.fromJson(json, UserPOJO.class);
return user;
}
}
|
jackcmeyer/SmartSync
|
smartsync-communication-util/src/communication/UserServiceCommunication.java
|
Java
|
mit
| 2,920
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coq bench</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../../..">Unstable</a></li>
<li><a href=".">dev / contrib:firing-squad 8.4.dev</a></li>
<li class="active"><a href="">2014-12-17 17:32:45</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="../../../../../about.html">About</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href=".">« Up</a>
<h1>
contrib:firing-squad
<small>
8.4.dev
<span class="label label-info">Not compatible with this Coq</span>
</small>
</h1>
<p><em><script>document.write(moment("2014-12-17 17:32:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2014-12-17 17:32:45 UTC)</em><p>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:firing-squad/coq:contrib:firing-squad.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>The package is valid.
</pre></dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --dry-run coq:contrib:firing-squad.8.4.dev coq.dev</code></dd>
<dt>Return code</dt>
<dd>768</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq:contrib:firing-squad -> coq <= 8.4.dev
Your request can't be satisfied:
- Conflicting version constraints for coq
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:firing-squad.8.4.dev</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>3 s</dd>
<dt>Output</dt>
<dd><pre>The following actions will be performed:
- remove coq.dev
=== 1 to remove ===
=-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Removing coq.dev.
[WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing
The following actions will be performed:
- install coq.8.4.dev [required by coq:contrib:firing-squad]
- install coq:contrib:firing-squad.8.4.dev
=== 2 to install ===
=-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
=-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Building coq.8.4.dev:
./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no
make -j4
make install
Installing coq.8.4.dev.
Building coq:contrib:firing-squad.8.4.dev:
coq_makefile -f Make -o Makefile
make -j4
make install
Installing coq:contrib:firing-squad.8.4.dev.
</pre></dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
coq-bench/coq-bench.github.io-old
|
clean/Linux-x86_64-4.02.1-1.2.0/unstable/dev/contrib:firing-squad/8.4.dev/2014-12-17_17-32-45.html
|
HTML
|
mit
| 6,907
|
<?php
namespace Grav\Common;
use Grav\Common\Config\Config;
use Grav\Common\File\CompiledYamlFile;
use Grav\Common\Data\Blueprints;
use Grav\Common\Data\Data;
use RocketTheme\Toolbox\Event\EventDispatcher;
use RocketTheme\Toolbox\Event\EventSubscriberInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* The Themes object holds an array of all the theme objects that Grav knows about.
*
* @author RocketTheme
* @license MIT
*/
class Themes extends Iterator
{
/** @var Grav */
protected $grav;
/** @var Config */
protected $config;
public function __construct(Grav $grav)
{
parent::__construct();
$this->grav = $grav;
$this->config = $grav['config'];
// Register instance as autoloader for theme inheritance
spl_autoload_register([$this, 'autoloadTheme']);
}
public function init()
{
/** @var Themes $themes */
$themes = $this->grav['themes'];
$themes->configure();
$this->initTheme();
}
public function initTheme()
{
/** @var Themes $themes */
$themes = $this->grav['themes'];
try {
$instance = $themes->load();
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($this->current(). ' theme could not be found');
}
if ($instance instanceof EventSubscriberInterface) {
/** @var EventDispatcher $events */
$events = $this->grav['events'];
$events->addSubscriber($instance);
}
$this->grav['theme'] = $instance;
$this->grav->fireEvent('onThemeInitialized');
}
/**
* Return list of all theme data with their blueprints.
*
* @return array
*/
public function all()
{
$list = array();
$locator = Grav::instance()['locator'];
$themes = (array) $locator->findResources('themes://', false);
foreach ($themes as $path) {
$iterator = new \DirectoryIterator($path);
/** @var \DirectoryIterator $directory */
foreach ($iterator as $directory) {
if (!$directory->isDir() || $directory->isDot()) {
continue;
}
$theme = $directory->getBasename();
$filePath = $locator->findResource('themes://' . $theme . DS . $theme . PLUGIN_EXT);
if (!is_file($filePath)) {
continue;
}
$list[$theme] = self::get($theme);
}
}
ksort($list);
return $list;
}
/**
* Get theme configuration or throw exception if it cannot be found.
*
* @param string $name
* @return Data
* @throws \RuntimeException
*/
public function get($name)
{
if (!$name) {
throw new \RuntimeException('Theme name not provided.');
}
$blueprints = new Blueprints('themes://');
$blueprint = $blueprints->get("{$name}/blueprints");
$blueprint->name = $name;
// Find thumbnail.
$thumb = "themes://{$name}/thumbnail.jpg";
if ($path = $this->grav['locator']->findResource($thumb, false)) {
$blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path);
}
// Load default configuration.
$file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT);
$obj = new Data($file->content(), $blueprint);
// Override with user configuration.
$obj->merge($this->grav['config']->get('themes.' . $name) ?: []);
// Save configuration always to user/config.
$file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT);
$obj->file($file);
return $obj;
}
/**
* Return name of the current theme.
*
* @return string
*/
public function current()
{
return (string) $this->config->get('system.pages.theme');
}
/**
* Load current theme.
*
* @return Theme|object
*/
public function load()
{
// NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
$grav = $this->grav;
$config = $this->config;
$name = $this->current();
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
$inflector = $grav['inflector'];
if ($file) {
// Local variables available in the file: $grav, $config, $name, $file
$class = include $file;
if (!is_object($class)) {
$themeClassFormat = [
'Grav\\Theme\\'.ucfirst($name),
'Grav\\Theme\\'.$inflector->camelize($name)
];
$themeClassName = false;
foreach ($themeClassFormat as $themeClass) {
if (class_exists($themeClass)) {
$themeClassName = $themeClass;
$class = new $themeClassName($grav, $config, $name);
break;
}
}
}
} elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
exit("Theme '$name' does not exist, unable to display page.");
}
$this->config->set('theme', $config->get('themes.' . $name));
if (empty($class)) {
$class = new Theme($grav, $config, $name);
}
return $class;
}
/**
* Configure and prepare streams for current template.
*
* @throws \InvalidArgumentException
*/
public function configure()
{
$name = $this->current();
$config = $this->config;
$this->loadConfiguration($name, $config);
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$registered = stream_get_wrappers();
$schemes = $config->get(
"themes.{$name}.streams.schemes",
['theme' => ['paths' => $locator->findResources("themes://{$name}", false)]]
);
foreach ($schemes as $scheme => $config) {
if (isset($config['paths'])) {
$locator->addPath($scheme, '', $config['paths']);
}
if (isset($config['prefixes'])) {
foreach ($config['prefixes'] as $prefix => $paths) {
$locator->addPath($scheme, $prefix, $paths);
}
}
if (in_array($scheme, $registered)) {
stream_wrapper_unregister($scheme);
}
$type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
if ($type[0] != '\\') {
$type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
}
if (!stream_wrapper_register($scheme, $type)) {
throw new \InvalidArgumentException("Stream '{$type}' could not be initialized.");
}
}
// Load languages after streams has been properly initialized
$this->loadLanguages($this->config);
}
/**
* Load theme configuration.
*
* @param string $name Theme name
* @param Config $config Configuration class
*/
protected function loadConfiguration($name, Config $config)
{
$themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
$config->joinDefaults("themes.{$name}", $themeConfig);
}
/**
* Load theme languages.
*
* @param Config $config Configuration class
*/
protected function loadLanguages(Config $config)
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
if ($config->get('system.languages.translations', true)) {
$languageFiles = array_reverse($locator->findResources("theme://languages" . YAML_EXT));
$languages = [];
foreach ($languageFiles as $language) {
$languages[] = CompiledYamlFile::instance($language)->content();
}
if ($languages) {
$languages = call_user_func_array('array_replace_recursive', $languages);
$config->getLanguages()->mergeRecursive($languages);
}
}
}
/**
* Autoload theme classes for inheritance
*
* @param string $class Class name
*
* @return mixed false FALSE if unable to load $class; Class name if
* $class is successfully loaded
*/
protected function autoloadTheme($class)
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$prefix = "Grav\\Theme";
if (false !== strpos($class, $prefix)) {
// Remove prefix from class
$class = substr($class, strlen($prefix));
// Replace namespace tokens to directory separators
$path = strtolower(ltrim(preg_replace('#\\\|_(?!.+\\\)#', '/', $class), '/'));
$file = $locator->findResource("themes://{$path}/{$path}.php");
// Load class
if (file_exists($file)) {
return include_once($file);
}
}
return false;
}
}
|
lennerd/grav
|
system/src/Grav/Common/Themes.php
|
PHP
|
mit
| 9,430
|
<?php
namespace Encore\Admin\Form\Field;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Str;
class Select extends Field
{
protected static $css = [
'/packages/admin/AdminLTE/plugins/select2/select2.min.css',
];
protected static $js = [
'/packages/admin/AdminLTE/plugins/select2/select2.full.min.js',
];
//xxl start select hidden
public function hidden(){
$this->isHidden = true;
}
//xxl end select hidden
public function render()
{
if (empty($this->script)) {
$this->script = <<<EOF
$("{$this->getElementClassSelector()}").select2({
allowClear: true,
placeholder: "{$this->label}"
});
EOF;
}
if ($this->options instanceof \Closure) {
if ($this->form) {
$this->options = $this->options->bindTo($this->form->model());
}
$this->options(call_user_func($this->options, $this->value));
}
$this->options = array_filter($this->options);
return parent::render()->with(['options' => $this->options]);
}
/**
* Set options.
*
* @param array|callable|string $options
*
* @return $this|mixed
*/
public function options($options = [])
{
// remote options
if (is_string($options)) {
return call_user_func_array([$this, 'loadOptionsFromRemote'], func_get_args());
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
if (is_callable($options)) {
$this->options = $options;
} else {
$this->options = (array) $options;
}
return $this;
}
/**
* Load options for other select on change.
*
* @param string $field
* @param string $sourceUrl
* @param string $idField
* @param string $textField
*
* @return $this
*/
public function load($field, $sourceUrl, $idField = 'id', $textField = 'text')
{
if (Str::contains($field, '.')) {
$field = $this->formatName($field);
$class = str_replace(['[', ']'], '_', $field);
} else {
$class = $field;
}
$script = <<<EOT
$(document).on('change', "{$this->getElementClassSelector()}", function () {
var target = $(this).closest('.fields-group').find(".$class");
$.get("$sourceUrl?q="+this.value, function (data) {
target.find("option").remove();
$(target).select2({
data: $.map(data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
})
}).trigger('change');
});
});
EOT;
Admin::script($script);
return $this;
}
/**
* Load options from remote.
*
* @param string $url
* @param array $parameters
* @param array $options
*
* @return $this
*/
protected function loadOptionsFromRemote($url, $parameters = [], $options = [])
{
$ajaxOptions = [
'url' => $url.'?'.http_build_query($parameters),
];
$ajaxOptions = json_encode(array_merge($ajaxOptions, $options));
$this->script = <<<EOT
$.ajax($ajaxOptions).done(function(data) {
$("{$this->getElementClassSelector()}").select2({data: data});
});
EOT;
return $this;
}
/**
* Load options from ajax results.
*
* @param string $url
* @param $idField
* @param $textField
*
* @return $this
*/
public function ajax($url, $idField = 'id', $textField = 'text')
{
$this->script = <<<EOT
$("{$this->getElementClassSelector()}").select2({
ajax: {
url: "$url",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data.data, function (d) {
d.id = d.$idField;
d.text = d.$textField;
return d;
}),
pagination: {
more: data.next_page_url
}
};
},
cache: true
},
minimumInputLength: 1,
escapeMarkup: function (markup) {
return markup;
}
});
EOT;
return $this;
}
}
|
elastosFans/larYbcy
|
src/Form/Field/Select.php
|
PHP
|
mit
| 4,489
|
module Sodascript
##
# Token is used by Lexer to keep track of all the tokens it finds in the file.
class Token
# Token associated rule (Rule)
attr_reader :rule
# Token's lexeme (String)
attr_reader :lexeme
##
# Creates a token given a _rule_ (Rule) and a _lexeme_ (String).
def initialize(rule, lexeme)
raise ArgumentError, 'rule must be a Rule' unless
rule.is_a?(Rule)
raise ArgumentError, 'lexeme must be a String' unless
lexeme.is_a?(String)
raise ArgumentError, 'rule must match lexeme' unless
rule.matches?(lexeme)
@rule = rule
@lexeme = lexeme
end
##
# String representation of a token
def to_s
"#{ @rule.name }: #{ @lexeme.inspect[1..-2] }"
end
end
end
|
miguelfrde/sodascript
|
lib/sodascript/token.rb
|
Ruby
|
mit
| 785
|
// @flow
import * as React from 'react'
import {StyleSheet, Image, Alert} from 'react-native'
import {Column, Row} from '../components/layout'
import {ListRow, Detail, Title} from '../components/list'
import type {StoryType} from './types'
type Props = {
onPress: string => any,
story: StoryType,
thumbnail: false | number,
}
export class NewsRow extends React.PureComponent<Props> {
_onPress = () => {
if (!this.props.story.link) {
Alert.alert('There is nowhere to go for this story')
return
}
this.props.onPress(this.props.story.link)
}
render() {
const {story} = this.props
const thumb =
this.props.thumbnail !== false
? story.featuredImage
? {uri: story.featuredImage}
: this.props.thumbnail
: null
return (
<ListRow arrowPosition="top" onPress={this._onPress}>
<Row alignItems="center">
{thumb !== null ? (
<Image source={thumb} style={styles.image} />
) : null}
<Column flex={1}>
<Title lines={2}>{story.title}</Title>
<Detail lines={3}>{story.excerpt}</Detail>
</Column>
</Row>
</ListRow>
)
}
}
const styles = StyleSheet.create({
image: {
borderRadius: 5,
marginRight: 15,
height: 70,
width: 70,
},
})
|
carls-app/carls
|
source/views/news/news-row.js
|
JavaScript
|
mit
| 1,225
|
{
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== "unknown") {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
}
|
stas-vilchik/bdd-ml
|
data/7759.js
|
JavaScript
|
mit
| 283
|
import numpy as np
import itertools
from scipy.misc import comb as bincoef
import random
#########################################################################
# GENERATORS
#########################################################################
def sign_permutations(length):
""" Memory efficient generator: generate all n^2 sign permutations. """
# return a generator which generates the product of "length" smaller
# generators of (-1 or +1) (i.e. the unrolled signs, evaulated as needed)
return itertools.product([-1, 1], repeat=length)
def random_product(*args, **kwds):
""" Random selection from itertools.product(*args, **kwds). """
pools = map(tuple, args) * kwds.get('repeat', 1)
limiter = 0
generate_limit = kwds.get('generate_limit', None)
while True if generate_limit == None else limiter < generate_limit:
limiter = limiter + 1
yield tuple(random.choice(pool) for pool in pools)
def random_sign_permutations(length, limit):
""" Random sign permutation generator. """
return random_product([-1, 1], repeat=length, generate_limit=limit)
def binary_combinations(length, sublength, comb_function=itertools.combinations, limit=None):
""" Memory efficient generator: generate all length choose sublength combinations. """
# get the combination indices, support both infinite and finite length generators
combination_indices = comb_function(range(length), sublength, limit) if limit else comb_function(range(length), sublength)
def indices_to_sign_vectors():
""" Generates sign vectors from indices. """
for index_tuple in combination_indices:
for i in xrange(length):
yield 1 if index_tuple.count(i) > 0 else 0
def grouper(n, iterable, fillvalue=None):
" For grouping a generated stream into tuples. "
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
# generate all combinations, grouped into tuples
return grouper(length, indices_to_sign_vectors())
def random_combination(iterable, r, limit=None):
""" Random selection from itertools.combinations(iterable, r). """
pool = tuple(iterable)
n = len(pool)
limiter = 0
comb = bincoef(len(iterable), r)
print comb
comb_indices = random.sample(xrange(comb), limit)
while True if limit == None else limiter < limit:
print comb_indices[limiter]
perm = get_nth_perm(pool, comb_indices[limiter])
subpool = sorted(perm[:r])
indices = sorted(random.sample(xrange(n), r))
print tuple(pool[i] for i in indices), subpool, perm
limiter = limiter + 1
yield tuple(pool[i] for i in indices)
def _progress_bar(self, max=100, label=""):
class Progress:
def __init__(self, max=100, label=""):
self.value = 1
self.label = label
self.max = max
def set(self, value):
self.value = value
p50 = int(50.0 * value / self.max)
if value >= self.max:
self.clear()
else:
sys.stdout.write("\r" + "|"*p50 + "\033[30m" + "·"*(50-p50) + "\033[0m %02d%% %s" % (p50*2, self.label))
sys.stdout.flush()
def advance(self):
self.set(self.value + 1)
def clear(self):
sys.stdout.write("\r"+" "*(80 + len(self.label))+"\r")
sys.stdout.flush()
return Progress(max, label)
def permutation_test(self, other, variables=None, ranked=False, two_samples=False, limit=1000):
"""Performs a permutation test on the given or the default dependent variables.
If two_samples is True, will conduct a two-sample test. Otherwise a one-sample test will be conducted.
If ranked is True, a Wilcoxon / Wilcoxon-Mann-Whitney test will be used for the one-sample /
two-sample case, respectively. Otherwise a Fisher / Pitman test will be conducted."""
variables = self._np1d(variables, fallback = self.dependent)
for var in variables:
A = self.get(var)
B = other.get(var)
if not two_samples:
D = [a - b for a, b in zip(A, B)]
if ranked:
D = self._signed_rank(D)
result = perm_test.one_sample(D, progress_bar = self._progress_bar(), limit=limit)
else:
if ranked:
D = self._rank(np.concatenate((A, B)))
A, B = D[:len(A)], D[len(A):]
result = perm_test.two_sample(A, B, progress_bar = self._progress_bar(), limit=limit)
return result
def _signed_rank(self, values):
"""Returns the signed rank of a list of values"""
lambda_signs = np.vectorize(lambda num: 1 if num >= 0 else -1)
signs = lambda_signs(values)
ranks = np.round(stats.rankdata(np.abs(values))).astype(int)
return signs*ranks
def signed_rank(self, attribute):
"""Returns the signed ranks of the data of the given attribute"""
values = self.get(attribute)
return self._signed_rank(values)
def _rank(self, values):
"""Returns the ranks of the data of a list of values"""
ranks = np.round(stats.rankdata(values)).astype(int)
return ranks
def rank(self, attribute):
"""Returns the ranks of the data of the given attribute"""
values = self.get(attribute)
return self._rank(values)
# def random_combination(iterable, r, limit=1000):
# """ Random selection from itertools.combinations(iterable, r). """
# pool = tuple(iterable)
# # number of
# comb = bincoef(len(iterable), r)
# comb_indices = random.sample(xrange(comb), limit)
# n = len(pool)
# limiter = 0
# for i in comb_indices:
# perm = get_nth_perm(pool, i)
# subpool = sorted(perm[:r])
# yield tuple(subpool)
def get_nth_perm(seq, index):
"Returns the <index>th permutation of <seq>"
seqc= list(seq[:])
seqn= [seqc.pop()]
divider= 2 # divider is meant to be len(seqn)+1, just a bit faster
while seqc:
index, new_index= index//divider, index%divider
seqn.insert(new_index, seqc.pop())
divider+= 1
return seqn
#########################################################################
# ACTUAL TESTS
#########################################################################
def one_sample(A, limit = 10000, progress_bar = None):
""" Conducts a permutation test on the input data"""
stat_ref = np.sum(A)
# count permutation test statistics <=, >=, or ||>=|| than reference stat
counts = np.array([0,0,0]) # (lesser, greater, more extreme)
total_perms = 2**len(A)
if total_perms < limit:
limit = total_perms
if progress_bar:
progress_bar.max = limit
progress_bar.label = "of %d permutations" % progress_bar.max
for sign_row in sign_permutations(len(A)):
stat_this = np.sum(np.array(A)*sign_row)
counts = counts + stat_compare(stat_ref,stat_this)
if progress_bar:
progress_bar.advance()
# return p-values for lower, upper, and two-tail tests (FP number)
return counts / 2.0**len(A)
def two_sample(A, B, limit = 10000, progress_bar = None):
""" Conducts a permutation test on the input data, transformed by fun. """
# apply transformation to input data (e.g. signed-rank for WMW)
data = np.concatenate((A, B))
stat_ref = np.sum(A)
# count permutation test statistics <=, >=, or ||>=|| than reference stat
counts = np.array([0,0,0]) # (lesser, greater)
total_perms = bincoef(len(data), len(A))
if not limit or total_perms < limit :
limit = None
comb_function = itertools.combinations
else:
comb_function = random_combination
if progress_bar:
progress_bar.max = limit or total_perms
progress_bar.label = "of %d permutations" % progress_bar.max
for binary_row in binary_combinations(len(data), len(A), comb_function=comb_function, limit=limit):
#print binary_row
stat_this = np.sum(np.array(data)*binary_row)
counts = counts + stat_compare(stat_ref,stat_this)
# if progress_bar:
# progress_bar.advance()
# return p-values for lower, upper, and two-tail tests (FP number)
n_comb = np.multiply.reduce(np.array(range(len(data)-len(A)+1,len(data)+1)))\
/ np.multiply.reduce(np.array(range(1,len(A)+1)))
n_comb = limit or total_perms
counts[2] = min(2*counts[0:2].min(),n_comb) # hack to define p.twotail as 2*smaller of 1 tail p's
return counts / float(n_comb)
def stat_compare(ref,test):
""" Tests for comparing permutation and observed test statistics"""
lesser = 1 * (test <= ref)
greater = 1 * (test >= ref)
more_extreme = 1 * (np.abs(test) >= np.abs(ref))
return np.array([lesser,greater,more_extreme])
|
maebert/knyfe
|
knyfe/perm_test.py
|
Python
|
mit
| 8,835
|
<?php
/**
* Sage includes
*
* The $sage_includes array determines the code library included in your theme.
* Add or remove files to the array as needed. Supports child theme overrides.
*
* Please note that missing files will produce a fatal error.
*
* @link https://github.com/roots/sage/pull/1042
*/
$sage_includes = [
'lib/assets.php', // Scripts and stylesheets
'lib/extras.php', // Custom functions
'lib/setup.php', // Theme setup
'lib/titles.php', // Page titles
'lib/wrapper.php', // Theme wrapper class
'lib/customizer.php', // Theme customizer
'lib/posts.php' // Add posts to hot sauces
];
foreach ($sage_includes as $file) {
if (!$filepath = locate_template($file)) {
trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR);
}
require_once $filepath;
}
unset($file, $filepath);
// add_action( 'init', 'setting_my_first_cookie' );
//
// function setting_my_first_cookie() {
// setcookie( '_wpnonce', wp_create_nonce('wp_json'), 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
//
// setcookie( 'nonce', wp_create_nonce('wp_json'), 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
// }
|
git-e-up/saucy-theme
|
functions.php
|
PHP
|
mit
| 1,197
|
ReddWall
================
ReddWall sets your wallpaper to a random image from one of the many Reddit wallpaper subreddits.
What it Does
------------
On the first run, ReddWall will find a random wallpaper from /r/wallpapers and minimize to the status bar. By default, it will select a new wallpaper every 1 hour. This behavior can be changed in the preferences window that can be opened by clicking the ReddWall icon in the status bar.
Downloads
---------
* Windows: [reddwall-v0.3.exe](https://github.com/matthewbauer/reddwall/releases/download/0.3/reddwall.exe)
* Mac OS X: [reddwall-v0.2.app](https://github.com/matthewbauer/reddwall/releases/download/0.2/reddwall.app.zip)
* Linux: [reddwall-v0.2.tar.gz](https://github.com/matthewbauer/reddwall/archive/0.2.tar.gz) (source code)
Running from Source
-------------------
To run from source, first make sure you have Git, Python 2.7, setuptools, and wxPython 2.7 installed. Then, clone the repo:
``git clone https://github.com/matthewbauer/reddwall.git``
and install it using the setup.py script:
``python2 setup.py install``
Reporting Issues
----------------
This program has not been tested on many different platforms. The cross platform toolkits used (wxWidgets, Python, and PRAW) mean that it should work without a problem. However, problems are bound to arise. If you have any issues with ReddWall, please [file an issue](https://github.com/matthewbauer/reddwall/issues/new) and I'll be sure to get back to you.
|
matthewbauer/reddwall
|
README.md
|
Markdown
|
mit
| 1,480
|
/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2015 Intel Corporation.
*
* Thanks to Adafruit for supplying a google translated version of the
* Chinese datasheet and some clues in their code.
*
* 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.
*/
#pragma once
#include <string>
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mraa.hpp"
#include "upm_utilities.h"
#define ZFM20_DEFAULT_UART 0
// protocol start codes
#define ZFM20_START1 0xef
#define ZFM20_START2 0x01
#define ZFM20_MAX_PKT_LEN 256
#define ZFM20_TIMEOUT 5000 // in ms
#define ZFM20_DEFAULT_PASSWORD 0x00000000
#define ZFM20_DEFAULT_ADDRESS 0xffffffff
namespace upm {
/**
* @brief ZFM-20 Fingerprint Sensor Module library
* @defgroup zfm20 libupm-zfm20
* @ingroup seeed uart touch
*/
/**
* @library zfm20
* @sensor zfm20
* @comname Fingerprint Sensor Module
* @altname Grove Fingerprint Sensor
* @type touch
* @man seeed
* @web http://wiki.seeed.cc/Grove-Fingerprint_Sensor/
* @con uart
*
* @brief API for the ZFM-20 Fingerprint Sensor Module
*
* This class was tested on the Grove Fingerprint Sensor
* Module. It can store up to 163 fingerprints.
*
* It is connected via a UART at 57,600 baud.
*
* @image html zfm20.jpg
* This example demonstrates how to register and store a new fingerprint
* @snippet zfm20-register.cxx Interesting
* This example demonstrates reading a fingerprint and locating it in the DB
* @snippet zfm20.cxx Interesting
*/
class ZFM20 {
public:
// commands
typedef enum {
CMD_GEN_IMAGE = 0x01,
CMD_IMG2TZ = 0x02,
CMD_MATCH = 0x03,
CMD_SEARCH = 0x04,
CMD_REGMODEL = 0x05,
CMD_STORE = 0x06,
CMD_LOAD_TMPL = 0x07,
CMD_UPLOAD_TMPL = 0x08,
CMD_DOWNLOAD_TMPL = 0x09,
CMD_UPLOAD_IMAGE = 0x0a,
CMD_DOWNLOAD_IMAGE = 0x0b,
CMD_DELETE_TMPL = 0x0c,
CMD_EMPTYDB = 0x0d,
CMD_SET_SYSPARAMS = 0x0e,
CMD_GET_SYSPARAMS = 0x0f,
CMD_SET_PASSWORD = 0x12,
CMD_VERIFY_PASSWORD = 0x13,
CMD_GET_RANDOM_NUMBER = 0x14,
CMD_SET_ADDRESS = 0x15,
CMD_GET_TMPL_COUNT = 0x1d,
CMD_GET_INDEX_TABLE = 0x1f
} ZFM20_COMMAND_T;
// Error response codes
typedef enum {
ERR_OK = 0x00,
ERR_PACKET_RX_ERROR = 0x01,
ERR_NO_FINGER = 0x02,
ERR_FP_IMAGE_FAILED = 0x03,
ERR_FP_TOO_MESSY = 0x06,
ERR_FP_IMAGE_FEW_FEATURES = 0x07,
ERR_FP_NOMATCH = 0x08,
ERR_FP_NOTFOUND = 0x09,
ERR_FP_ENROLLMISMATCH = 0x0a,
ERR_BAD_LOCATION = 0x0b,
ERR_DB_ERROR = 0x0c,
ERR_UPLOAD_FEAT_FAILED = 0x0d,
ERR_NO_MORE_PACKETS = 0x0e,
ERR_UPLOAD_IMG_FAILED = 0x0f,
ERR_RM_TMPL_FAILED = 0x10,
ERR_EMPTY_DB_FAILED = 0x11,
ERR_INVALID_PWD = 0x13,
ERR_INVALID_IMAGE = 0x15,
ERR_RW_FLASH_ERROR = 0x18,
ERR_INVALID_REG = 0x1a,
ERR_INVALID_ADDR = 0x20,
ERR_NEEDS_PWD = 0x21,
// end of module-specific errors
ERR_INTERNAL_ERR = 0xff // API internal error
} ZFM20_ERRORS_T;
typedef enum {
PKT_COMMAND = 0x01,
PKT_DATA = 0x02,
PKT_ACK = 0x07,
PKT_END_DATA = 0x08
} ZFM20_PKTCODES_T;
/**
* ZFM20 constructor
*
* @param uart Target mraa UART index to use (0 or 1)
* @param baud Desired baud rate
*/
ZFM20(int uart, int baud = 57600);
/**
* ZFM20 constructor
*
* @param uart File path (/dev/ttyXXX to uart
* @param baud Desired baud rate
*/
ZFM20(std::string uart_raw, int baud = 57600);
/**
* ZFM20 destructor
*/
virtual ~ZFM20() {}
/**
* Reads any available data in a user-supplied buffer. Note: the
* call blocks until data is available to be read. Use
* dataAvailable() to determine whether there is data available
* beforehand, to avoid blocking.
*
* @param buffer Buffer to hold the data read
* @param len Length of the buffer
* @return Number of bytes read
*/
int readData(char *buffer, int len);
/**
* Writes the data in the buffer to the device
*
* @param buffer Buffer to hold the data read
* @param len Length of the buffer
* @return Number of bytes written
*/
int writeData(char *buffer, int len);
/**
* Sets up proper tty I/O modes and the baud rate. For this device,
* the default baud rate is 57,600.
*
* @param baud Desired baud rate.
* @return True if successful
*/
bool setupTty(uint32_t baud = 57600);
/**
* Composes and writes a command packet
*
* @param pkt Packet
* @param len Length of packet
* @return Number of bytes written
*/
int writeCmdPacket(uint8_t *pkt, int len);
/**
* Verifies the packet header and indicates its validity
*
* @param pkt Packet to check
* @param len Length of packet
* @return True if the packet is valid, false otherwise
*/
bool verifyPacket(uint8_t *pkt, int len);
/**
* Returns the number of milliseconds elapsed since initClock()
* was last called
*
* @return Elapsed milliseconds
*/
uint32_t getMillis();
/**
* Resets the clock
*
*/
void initClock();
/**
* Sets the address that should be used to access the module
*
* @param addr Address to use
*/
void setAddress(uint32_t addr) { m_address = addr; };
/**
* Sets the password that should be used to access the module
*
* @param pw Password to use
*/
void setPassword(uint32_t pw) { m_password = pw; };
/**
* Gets the returned data from a request
*
* @param pkt Buffer to store the returned data
* @param len Expected response length; pkt should be at least this
* large
* @return True if successful
*/
bool getResponse(uint8_t *pkt, int len);
/**
* Verifies and authenticates to the module. The password used is
* the last one set by setPassword().
*
* @return True if successful
*/
bool verifyPassword();
/**
* Queries the module for the number of stored templates
* (fingerprints).
*
* @return Number of currently stored templates
*/
int getNumTemplates();
/**
* Sets a new password for the module. This passowrd is
* stored in the module, and is required to access
* the module in the future.
*
* @param pwd New password to set on the module
* @return True if successful
*/
bool setNewPassword(uint32_t pwd);
/**
* Sets a new address for the module. This address is
* stored in the module, and is required to access
* the module in the future.
*
* @param addr New address to set on the module
* @return True if successful
*/
bool setNewAddress(uint32_t addr);
/**
* Generates a new fingerprint image (scans a fingerprint)
*
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t generateImage();
/**
* Converts the image in the image buffer (generated by
* generateImage()) and stores it in one of the two characteristics
* buffers, 1 or 2
*
* @param slot Characteristics buffer to use; must be 1 or 2
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t image2Tz(int slot);
/**
* Based on the two characteristics buffers (1 & 2), creates a
* fingerprint model. Once a model is successfully created,
* it can be stored in the module with storeModel().
*
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t createModel();
/**
* Once a fingerprint model is created, this method can be
* used to store it (via one of the characteristics buffers) in a
* given location.
*
* @param slot Characteristics buffer to store the model, 1 or 2
* @param id Location to store the model
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t storeModel(int slot, uint16_t id);
/**
* Deletes a stored model
*
* @param id Location containing the model to delete
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t deleteModel(uint16_t id);
/**
* Deletes the model database (DB)
*
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t deleteDB();
/**
* Searches the fingerprint DB and returns an ID and score, if found
*
*
* @param slot Slot containing a converted image to search for
* @param id ID if found, 0 otherwise
* @param score Score if found, 0 otherwise
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t search(int slot, uint16_t &id, uint16_t &score);
/**
* Compares the features in characteristics buffers 1 and 2 and
* returns a score if they match
*
* @param score Score
* @return One of the ZFM20_ERRORS_T values
*/
uint8_t match(uint16_t &score);
private:
mraa::Uart m_uart;
uint32_t m_password;
uint32_t m_address;
upm_clock_t m_clock;
};
}
|
malikabhi05/upm
|
src/zfm20/zfm20.hpp
|
C++
|
mit
| 11,256
|
package org.jabref.gui.util.component;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import com.airhacks.afterburner.views.ViewLoader;
import org.fxmisc.easybind.EasyBind;
/**
* A tag item in a {@link TagBar}.
*/
public class Tag<T> extends HBox {
private ObjectProperty<T> value;
private Consumer<T> tagRemovedConsumer;
@FXML private Label text;
public Tag(Function<T, String> toString) {
Objects.requireNonNull(toString);
ViewLoader.view(this)
.root(this)
.load();
value = new SimpleObjectProperty<>();
text.textProperty().bind(EasyBind.map(value, toString));
}
public Tag(Function<T, String> toString, T value) {
this(toString);
setValue(value);
}
public T getValue() {
return value.get();
}
public void setValue(T value) {
this.value.set(value);
}
public ObjectProperty<T> valueProperty() {
return value;
}
@FXML
private void removeButtonClicked(ActionEvent event) {
if (tagRemovedConsumer != null) {
tagRemovedConsumer.accept(value.get());
}
}
public final void setOnTagRemoved(Consumer<T> tagRemovedConsumer) {
this.tagRemovedConsumer = tagRemovedConsumer;
}
}
|
zellerdev/jabref
|
src/main/java/org/jabref/gui/util/component/Tag.java
|
Java
|
mit
| 1,573
|
# confd
[](https://travis-ci.org/kelseyhightower/confd)
`confd` is a lightweight configuration management tool focused on:
* keeping local configuration files up-to-date using data stored in [etcd](https://github.com/coreos/etcd),
[consul](http://consul.io), [dynamodb](http://aws.amazon.com/dynamodb/), [redis](http://redis.io),
[vault](https://vaultproject.io), [zookeeper](https://zookeeper.apache.org), [aws ssm parameter store](https://aws.amazon.com/ec2/systems-manager/) or env vars and processing [template resources](docs/template-resources.md).
* reloading applications to pick up new config file changes
## Community
* IRC: `#confd` on Freenode
* Mailing list: [Google Groups](https://groups.google.com/forum/#!forum/confd-users)
* Website: [www.confd.io](http://www.confd.io)
## Building
Go 1.8 is required to build confd, which uses the new vendor directory.
```
$ mkdir -p $GOPATH/src/github.com/kelseyhightower
$ git clone https://github.com/blippar/confd.git $GOPATH/src/github.com/blippar/confd
$ cd $GOPATH/src/github.com/blippar/confd
$ ./build
```
You should now have confd in your `bin/` directory:
```
$ ls bin/
confd
```
## Getting Started
Before we begin be sure to [download and install confd](docs/installation.md).
* [quick start guide](docs/quick-start-guide.md)
## Next steps
Check out the [docs directory](docs) for more docs.
|
blippar/confd
|
README.md
|
Markdown
|
mit
| 1,454
|
require 'spec_helper'
describe ETL::Parser::FixedWidthParser do
it_should_behave_like 'ETL::Parser', 'fixed_width.ctl'
end
|
activewarehouse/etl
|
spec/etl/parser/fixed_width_parser_spec.rb
|
Ruby
|
mit
| 126
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.