answer
stringlengths 15
1.25M
|
|---|
#include <iostream>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <syslog.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include "<API key>.h"
static void termination_handler(int signum) {
<API key>();
}
static void sig_pipe_hanler(int signum) {
//printf("Sig Pipe\n");
}
<API key>( "TestSocket" , TestSocket ) {
switch (signal) {
case WEBSOCKET_CONNECT:
printf("Websocket API Connect TestSocket : %s \n", guid);
break;
case <API key>:
printf("Websocket API Disconnect TestSocket : %s \n", guid);
break;
case WEBSOCKET_MSG:
printf("Websocket API TestSocket Msg 1 %s\n", msg);
<API key>(guid, msg, strlen(msg));
break;
}
}
int main(int argc, char **argv) {
if (signal(SIGINT, termination_handler) == SIG_IGN ) signal(SIGINT, SIG_IGN);
if (signal(SIGHUP, termination_handler) == SIG_IGN ) signal(SIGHUP, SIG_IGN);
if (signal(SIGTERM, termination_handler) == SIG_IGN ) signal(SIGTERM, SIG_IGN);
if (signal(SIGPIPE, sig_pipe_hanler) == SIG_IGN ) signal(SIGPIPE, SIG_IGN);
if (0 == WebserverInit()) {
WebserverAddFileDir("", "www");
<API key>("port",8080);
<API key> ( TestSocket );
WebserverStart();
}
WebserverShutdown();
return 0;
}
|
/* A 32-bit implementation of the NIST P-256 elliptic curve. */
#include <string.h>
#include "prtypes.h"
#include "mpi.h"
#include "mpi-priv.h"
#include "ecp.h"
typedef PRUint8 u8;
typedef PRUint32 u32;
typedef PRUint64 u64;
/* Our field elements are represented as nine, unsigned 32-bit words. Freebl's
* MPI library calls them digits, but here they are called limbs, which is
* GMP's terminology.
*
* The value of an felem (field element) is:
* x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)
*
* That is, each limb is alternately 29 or 28-bits wide in little-endian
* order.
*
* This means that an felem hits 2**257, rather than 2**256 as we would like. A
* 28, 29, ... pattern would cause us to hit 2**256, but that causes problems
* when multiplying as terms end up one bit short of a limb which would require
* much bit-shifting to correct.
*
* Finally, the values stored in an felem are in Montgomery form. So the value
* |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.
*/
typedef u32 limb;
#define NLIMBS 9
typedef limb felem[NLIMBS];
static const limb kBottom28Bits = 0xfffffff;
static const limb kBottom29Bits = 0x1fffffff;
/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and
* 28-bit words.
*/
static const felem kOne = {
2, 0, 0, 0xffff800,
0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,
0
};
static const felem kZero = {0};
static const felem kP = {
0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,
0, 0, 0x200000, 0xf000000,
0xfffffff
};
static const felem k2P = {
0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,
0, 0, 0x400000, 0xe000000,
0x1fffffff
};
/* kPrecomputed contains precomputed values to aid the calculation of scalar
* multiples of the base point, G. It's actually two, equal length, tables
* concatenated.
*
* The first table contains (x,y) felem pairs for 16 multiples of the base
* point, G.
*
* Index | Index (binary) | Value
* 0 | 0000 | 0G (all zeros, omitted)
* 1 | 0001 | G
* 2 | 0010 | 2**64G
* 3 | 0011 | 2**64G + G
* 4 | 0100 | 2**128G
* 5 | 0101 | 2**128G + G
* 6 | 0110 | 2**128G + 2**64G
* 7 | 0111 | 2**128G + 2**64G + G
* 8 | 1000 | 2**192G
* 9 | 1001 | 2**192G + G
* 10 | 1010 | 2**192G + 2**64G
* 11 | 1011 | 2**192G + 2**64G + G
* 12 | 1100 | 2**192G + 2**128G
* 13 | 1101 | 2**192G + 2**128G + G
* 14 | 1110 | 2**192G + 2**128G + 2**64G
* 15 | 1111 | 2**192G + 2**128G + 2**64G + G
*
* The second table follows the same style, but the terms are 2**32G,
* 2**96G, 2**160G, 2**224G.
*
* This is ~2KB of data.
*/
static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {
0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,
0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,
0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,
0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,
0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,
0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,
0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,
0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,
0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,
0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,
0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,
0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,
0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,
0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,
0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,
0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,
0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,
0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,
0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,
0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,
0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,
0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,
0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,
0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,
0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,
0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,
0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,
0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,
0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,
0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,
0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,
0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,
0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,
0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,
0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,
0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,
0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,
0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,
0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,
0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,
0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,
0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,
0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,
0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,
0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,
0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,
0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,
0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,
0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,
0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,
0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,
0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,
0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,
0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,
0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,
0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,
0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,
0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,
0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,
0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,
};
/* Field element operations:
*/
/* <API key> returns:
* 0xffffffff for 0 < x <= 2**31
* 0 for x == 0 or x > 2**31.
*
* x must be a u32 or an equivalent type such as limb.
*/
#define <API key>(x) ((((u32)(x) - 1) >> 31) - 1)
/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,
* which is a term at 2**257.
*
* On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.
* On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29.
*/
static void felem_reduce_carry(felem inout, limb carry)
{
const u32 carry_mask = <API key>(carry);
inout[0] += carry << 1;
inout[3] += 0x10000000 & carry_mask;
/* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the
* previous line therefore this doesn't underflow.
*/
inout[3] -= carry << 11;
inout[4] += (0x20000000 - 1) & carry_mask;
inout[5] += (0x10000000 - 1) & carry_mask;
inout[6] += (0x20000000 - 1) & carry_mask;
inout[6] -= carry << 22;
/* This may underflow if carry is non-zero but, if so, we'll fix it in the
* next line.
*/
inout[7] -= 1 & carry_mask;
inout[7] += carry << 25;
}
/* felem_sum sets out = in+in2.
*
* On entry, in[i]+in2[i] must not overflow a 32-bit word.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29
*/
static void felem_sum(felem out, const felem in, const felem in2)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] = in[i] + in2[i];
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] = in[i] + in2[i];
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)
#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)
#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)
#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)
#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)
#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)
/* zero31 is 0 mod p.
*/
static const felem zero31 = {
two31m3, two30m2, two31m2, two30p13m2,
two31m2, two30m2, two31p24m2, two30m27m2,
two31m2
};
/* felem_diff sets out = in-in2.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
* in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_diff(felem out, const felem in, const felem in2)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] = in[i] - in2[i];
out[i] += zero31[i];
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] = in[i] - in2[i];
out[i] += zero31[i];
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words
* with the same 29,28,... bit positions as an felem.
*
* The values in felems are in Montgomery form: x*R mod p where R = 2**257.
* Since we just multiplied two Montgomery values together, the result is
* x*y*R*R mod p. We wish to divide by R in order for the result also to be
* in Montgomery form.
*
* On entry: tmp[i] < 2**64
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29
*/
static void felem_reduce_degree(felem out, u64 tmp[17])
{
/* The following table may be helpful when reading this code:
*
* Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...
* Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29
* Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285
* (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285
*/
limb tmp2[18], carry, x, xMask;
unsigned int i;
/* tmp contains 64-bit words with the same 29,28,29-bit positions as an
* felem. So the top of an element of tmp might overlap with another
* element two positions down. The following loop eliminates this
* overlap.
*/
tmp2[0] = tmp[0] & kBottom29Bits;
/* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try
* and hint to the compiler that it can do a single-word shift by selecting
* the right register rather than doing a double-word shift and truncating
* afterwards.
*/
tmp2[1] = ((limb) tmp[0]) >> 29;
tmp2[1] |= (((limb) (tmp[0] >> 32)) << 3) & kBottom28Bits;
tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;
carry = tmp2[1] >> 28;
tmp2[1] &= kBottom28Bits;
for (i = 2; i < 17; i++) {
tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25;
tmp2[i] += ((limb) (tmp[i - 1])) >> 28;
tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 4) & kBottom29Bits;
tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;
tmp2[i] += carry;
carry = tmp2[i] >> 29;
tmp2[i] &= kBottom29Bits;
i++;
if (i == 17)
break;
tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25;
tmp2[i] += ((limb) (tmp[i - 1])) >> 29;
tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 3) & kBottom28Bits;
tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;
tmp2[i] += carry;
carry = tmp2[i] >> 28;
tmp2[i] &= kBottom28Bits;
}
tmp2[17] = ((limb) (tmp[15] >> 32)) >> 25;
tmp2[17] += ((limb) (tmp[16])) >> 29;
tmp2[17] += (((limb) (tmp[16] >> 32)) << 3);
tmp2[17] += carry;
/* Montgomery elimination of terms:
*
* Since R is 2**257, we can divide by R with a bitwise shift if we can
* ensure that the right-most 257 bits are all zero. We can make that true
* by adding multiplies of p without affecting the value.
*
* So we eliminate limbs from right to left. Since the bottom 29 bits of p
* are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.
* We can do that for 8 further limbs and then right shift to eliminate the
* extra factor of R.
*/
for (i = 0;; i += 2) {
tmp2[i + 1] += tmp2[i] >> 29;
x = tmp2[i] & kBottom29Bits;
xMask = <API key>(x);
tmp2[i] = 0;
tmp2[i + 3] += (x << 10) & kBottom28Bits;
tmp2[i + 4] += (x >> 18);
tmp2[i + 6] += (x << 21) & kBottom29Bits;
tmp2[i + 7] += x >> 8;
/* At position 200, which is the starting bit position for word 7, we
* have a factor of 0xf000000 = 2**28 - 2**24.
*/
tmp2[i + 7] += 0x10000000 & xMask;
/* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */
tmp2[i + 8] += (x - 1) & xMask;
tmp2[i + 7] -= (x << 24) & kBottom28Bits;
tmp2[i + 8] -= x >> 4;
tmp2[i + 8] += 0x20000000 & xMask;
tmp2[i + 8] -= x;
tmp2[i + 8] += (x << 28) & kBottom29Bits;
tmp2[i + 9] += ((x >> 1) - 1) & xMask;
if (i+1 == NLIMBS)
break;
tmp2[i + 2] += tmp2[i + 1] >> 28;
x = tmp2[i + 1] & kBottom28Bits;
xMask = <API key>(x);
tmp2[i + 1] = 0;
tmp2[i + 4] += (x << 11) & kBottom29Bits;
tmp2[i + 5] += (x >> 18);
tmp2[i + 7] += (x << 21) & kBottom28Bits;
tmp2[i + 8] += x >> 7;
/* At position 199, which is the starting bit of the 8th word when
* dealing with a context starting on an odd word, we have a factor of
* 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th
* word from i+1 is i+8.
*/
tmp2[i + 8] += 0x20000000 & xMask;
tmp2[i + 9] += (x - 1) & xMask;
tmp2[i + 8] -= (x << 25) & kBottom29Bits;
tmp2[i + 9] -= x >> 4;
tmp2[i + 9] += 0x10000000 & xMask;
tmp2[i + 9] -= x;
tmp2[i + 10] += (x - 1) & xMask;
}
/* We merge the right shift with a carry chain. The words above 2**257 have
* widths of 28,29,... which we need to correct when copying them down.
*/
carry = 0;
for (i = 0; i < 8; i++) {
/* The maximum value of tmp2[i + 9] occurs on the first iteration and
* is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is
* therefore safe.
*/
out[i] = tmp2[i + 9];
out[i] += carry;
out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
out[i] = tmp2[i + 9] >> 1;
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
out[8] = tmp2[17];
out[8] += carry;
carry = out[8] >> 29;
out[8] &= kBottom29Bits;
felem_reduce_carry(out, carry);
}
/* felem_square sets out=in*in.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_square(felem out, const felem in)
{
u64 tmp[17];
tmp[0] = ((u64) in[0]) * in[0];
tmp[1] = ((u64) in[0]) * (in[1] << 1);
tmp[2] = ((u64) in[0]) * (in[2] << 1) +
((u64) in[1]) * (in[1] << 1);
tmp[3] = ((u64) in[0]) * (in[3] << 1) +
((u64) in[1]) * (in[2] << 1);
tmp[4] = ((u64) in[0]) * (in[4] << 1) +
((u64) in[1]) * (in[3] << 2) +
((u64) in[2]) * in[2];
tmp[5] = ((u64) in[0]) * (in[5] << 1) +
((u64) in[1]) * (in[4] << 1) +
((u64) in[2]) * (in[3] << 1);
tmp[6] = ((u64) in[0]) * (in[6] << 1) +
((u64) in[1]) * (in[5] << 2) +
((u64) in[2]) * (in[4] << 1) +
((u64) in[3]) * (in[3] << 1);
tmp[7] = ((u64) in[0]) * (in[7] << 1) +
((u64) in[1]) * (in[6] << 1) +
((u64) in[2]) * (in[5] << 1) +
((u64) in[3]) * (in[4] << 1);
/* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,
* which is < 2**64 as required.
*/
tmp[8] = ((u64) in[0]) * (in[8] << 1) +
((u64) in[1]) * (in[7] << 2) +
((u64) in[2]) * (in[6] << 1) +
((u64) in[3]) * (in[5] << 2) +
((u64) in[4]) * in[4];
tmp[9] = ((u64) in[1]) * (in[8] << 1) +
((u64) in[2]) * (in[7] << 1) +
((u64) in[3]) * (in[6] << 1) +
((u64) in[4]) * (in[5] << 1);
tmp[10] = ((u64) in[2]) * (in[8] << 1) +
((u64) in[3]) * (in[7] << 2) +
((u64) in[4]) * (in[6] << 1) +
((u64) in[5]) * (in[5] << 1);
tmp[11] = ((u64) in[3]) * (in[8] << 1) +
((u64) in[4]) * (in[7] << 1) +
((u64) in[5]) * (in[6] << 1);
tmp[12] = ((u64) in[4]) * (in[8] << 1) +
((u64) in[5]) * (in[7] << 2) +
((u64) in[6]) * in[6];
tmp[13] = ((u64) in[5]) * (in[8] << 1) +
((u64) in[6]) * (in[7] << 1);
tmp[14] = ((u64) in[6]) * (in[8] << 1) +
((u64) in[7]) * (in[7] << 1);
tmp[15] = ((u64) in[7]) * (in[8] << 1);
tmp[16] = ((u64) in[8]) * in[8];
felem_reduce_degree(out, tmp);
}
/* felem_mul sets out=in*in2.
*
* On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and
* in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_mul(felem out, const felem in, const felem in2)
{
u64 tmp[17];
tmp[0] = ((u64) in[0]) * in2[0];
tmp[1] = ((u64) in[0]) * (in2[1] << 0) +
((u64) in[1]) * (in2[0] << 0);
tmp[2] = ((u64) in[0]) * (in2[2] << 0) +
((u64) in[1]) * (in2[1] << 1) +
((u64) in[2]) * (in2[0] << 0);
tmp[3] = ((u64) in[0]) * (in2[3] << 0) +
((u64) in[1]) * (in2[2] << 0) +
((u64) in[2]) * (in2[1] << 0) +
((u64) in[3]) * (in2[0] << 0);
tmp[4] = ((u64) in[0]) * (in2[4] << 0) +
((u64) in[1]) * (in2[3] << 1) +
((u64) in[2]) * (in2[2] << 0) +
((u64) in[3]) * (in2[1] << 1) +
((u64) in[4]) * (in2[0] << 0);
tmp[5] = ((u64) in[0]) * (in2[5] << 0) +
((u64) in[1]) * (in2[4] << 0) +
((u64) in[2]) * (in2[3] << 0) +
((u64) in[3]) * (in2[2] << 0) +
((u64) in[4]) * (in2[1] << 0) +
((u64) in[5]) * (in2[0] << 0);
tmp[6] = ((u64) in[0]) * (in2[6] << 0) +
((u64) in[1]) * (in2[5] << 1) +
((u64) in[2]) * (in2[4] << 0) +
((u64) in[3]) * (in2[3] << 1) +
((u64) in[4]) * (in2[2] << 0) +
((u64) in[5]) * (in2[1] << 1) +
((u64) in[6]) * (in2[0] << 0);
tmp[7] = ((u64) in[0]) * (in2[7] << 0) +
((u64) in[1]) * (in2[6] << 0) +
((u64) in[2]) * (in2[5] << 0) +
((u64) in[3]) * (in2[4] << 0) +
((u64) in[4]) * (in2[3] << 0) +
((u64) in[5]) * (in2[2] << 0) +
((u64) in[6]) * (in2[1] << 0) +
((u64) in[7]) * (in2[0] << 0);
/* tmp[8] has the greatest value but doesn't overflow. See logic in
* felem_square.
*/
tmp[8] = ((u64) in[0]) * (in2[8] << 0) +
((u64) in[1]) * (in2[7] << 1) +
((u64) in[2]) * (in2[6] << 0) +
((u64) in[3]) * (in2[5] << 1) +
((u64) in[4]) * (in2[4] << 0) +
((u64) in[5]) * (in2[3] << 1) +
((u64) in[6]) * (in2[2] << 0) +
((u64) in[7]) * (in2[1] << 1) +
((u64) in[8]) * (in2[0] << 0);
tmp[9] = ((u64) in[1]) * (in2[8] << 0) +
((u64) in[2]) * (in2[7] << 0) +
((u64) in[3]) * (in2[6] << 0) +
((u64) in[4]) * (in2[5] << 0) +
((u64) in[5]) * (in2[4] << 0) +
((u64) in[6]) * (in2[3] << 0) +
((u64) in[7]) * (in2[2] << 0) +
((u64) in[8]) * (in2[1] << 0);
tmp[10] = ((u64) in[2]) * (in2[8] << 0) +
((u64) in[3]) * (in2[7] << 1) +
((u64) in[4]) * (in2[6] << 0) +
((u64) in[5]) * (in2[5] << 1) +
((u64) in[6]) * (in2[4] << 0) +
((u64) in[7]) * (in2[3] << 1) +
((u64) in[8]) * (in2[2] << 0);
tmp[11] = ((u64) in[3]) * (in2[8] << 0) +
((u64) in[4]) * (in2[7] << 0) +
((u64) in[5]) * (in2[6] << 0) +
((u64) in[6]) * (in2[5] << 0) +
((u64) in[7]) * (in2[4] << 0) +
((u64) in[8]) * (in2[3] << 0);
tmp[12] = ((u64) in[4]) * (in2[8] << 0) +
((u64) in[5]) * (in2[7] << 1) +
((u64) in[6]) * (in2[6] << 0) +
((u64) in[7]) * (in2[5] << 1) +
((u64) in[8]) * (in2[4] << 0);
tmp[13] = ((u64) in[5]) * (in2[8] << 0) +
((u64) in[6]) * (in2[7] << 0) +
((u64) in[7]) * (in2[6] << 0) +
((u64) in[8]) * (in2[5] << 0);
tmp[14] = ((u64) in[6]) * (in2[8] << 0) +
((u64) in[7]) * (in2[7] << 1) +
((u64) in[8]) * (in2[6] << 0);
tmp[15] = ((u64) in[7]) * (in2[8] << 0) +
((u64) in[8]) * (in2[7] << 0);
tmp[16] = ((u64) in[8]) * (in2[8] << 0);
felem_reduce_degree(out, tmp);
}
static void felem_assign(felem out, const felem in)
{
memcpy(out, in, sizeof(felem));
}
/* felem_inv calculates |out| = |in|^{-1}
*
* Based on Fermat's Little Theorem:
* a^p = a (mod p)
* a^{p-1} = 1 (mod p)
* a^{p-2} = a^{-1} (mod p)
*/
static void felem_inv(felem out, const felem in)
{
felem ftmp, ftmp2;
/* each e_I will hold |in|^{2^I - 1} */
felem e2, e4, e8, e16, e32, e64;
unsigned int i;
felem_square(ftmp, in);
felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */
felem_assign(e2, ftmp);
felem_square(ftmp, ftmp); /* 2^3 - 2^1 */
felem_square(ftmp, ftmp); /* 2^4 - 2^2 */
felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */
felem_assign(e4, ftmp);
felem_square(ftmp, ftmp); /* 2^5 - 2^1 */
felem_square(ftmp, ftmp); /* 2^6 - 2^2 */
felem_square(ftmp, ftmp); /* 2^7 - 2^3 */
felem_square(ftmp, ftmp); /* 2^8 - 2^4 */
felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */
felem_assign(e8, ftmp);
for (i = 0; i < 8; i++) {
felem_square(ftmp, ftmp);
} /* 2^16 - 2^8 */
felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */
felem_assign(e16, ftmp);
for (i = 0; i < 16; i++) {
felem_square(ftmp, ftmp);
} /* 2^32 - 2^16 */
felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */
felem_assign(e32, ftmp);
for (i = 0; i < 32; i++) {
felem_square(ftmp, ftmp);
} /* 2^64 - 2^32 */
felem_assign(e64, ftmp);
felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */
for (i = 0; i < 192; i++) {
felem_square(ftmp, ftmp);
} /* 2^256 - 2^224 + 2^192 */
felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */
for (i = 0; i < 16; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^80 - 2^16 */
felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */
for (i = 0; i < 8; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^88 - 2^8 */
felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */
for (i = 0; i < 4; i++) {
felem_square(ftmp2, ftmp2);
} /* 2^92 - 2^4 */
felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */
felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */
felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */
felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */
felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */
felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */
felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */
felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */
}
/* felem_scalar_3 sets out=3*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_3(felem out)
{
limb carry = 0;
unsigned int i;
for (i = 0;; i++) {
out[i] *= 3;
out[i] += carry;
carry = out[i] >> 29;
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
out[i] *= 3;
out[i] += carry;
carry = out[i] >> 28;
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_scalar_4 sets out=4*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_4(felem out)
{
limb carry = 0, next_carry;
unsigned int i;
for (i = 0;; i++) {
next_carry = out[i] >> 27;
out[i] <<= 2;
out[i] &= kBottom29Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 29);
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
next_carry = out[i] >> 26;
out[i] <<= 2;
out[i] &= kBottom28Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 28);
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* felem_scalar_8 sets out=8*out.
*
* On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
* On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29.
*/
static void felem_scalar_8(felem out)
{
limb carry = 0, next_carry;
unsigned int i;
for (i = 0;; i++) {
next_carry = out[i] >> 26;
out[i] <<= 3;
out[i] &= kBottom29Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 29);
out[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
next_carry = out[i] >> 25;
out[i] <<= 3;
out[i] &= kBottom28Bits;
out[i] += carry;
carry = next_carry + (out[i] >> 28);
out[i] &= kBottom28Bits;
}
felem_reduce_carry(out, carry);
}
/* <API key> returns 1 iff |in| == 0. It takes a variable amount of
* time depending on the value of |in|.
*/
static char <API key>(const felem in)
{
limb carry;
int i;
limb tmp[NLIMBS];
felem_assign(tmp, in);
/* First, reduce tmp to a minimal form.
*/
do {
carry = 0;
for (i = 0;; i++) {
tmp[i] += carry;
carry = tmp[i] >> 29;
tmp[i] &= kBottom29Bits;
i++;
if (i == NLIMBS)
break;
tmp[i] += carry;
carry = tmp[i] >> 28;
tmp[i] &= kBottom28Bits;
}
felem_reduce_carry(tmp, carry);
} while (carry);
/* tmp < 2**257, so the only possible zero values are 0, p and 2p.
*/
return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||
memcmp(tmp, kP, sizeof(tmp)) == 0 ||
memcmp(tmp, k2P, sizeof(tmp)) == 0;
}
/* Group operations:
*
* Elements of the elliptic curve group are represented in Jacobian
* coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in
* Jacobian form.
*/
static void point_double(felem x_out, felem y_out, felem z_out,
const felem x, const felem y, const felem z)
{
felem delta, gamma, alpha, beta, tmp, tmp2;
felem_square(delta, z);
felem_square(gamma, y);
felem_mul(beta, x, gamma);
felem_sum(tmp, x, delta);
felem_diff(tmp2, x, delta);
felem_mul(alpha, tmp, tmp2);
felem_scalar_3(alpha);
felem_sum(tmp, y, z);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, gamma);
felem_diff(z_out, tmp, delta);
felem_scalar_4(beta);
felem_square(x_out, alpha);
felem_diff(x_out, x_out, beta);
felem_diff(x_out, x_out, beta);
felem_diff(tmp, beta, x_out);
felem_mul(tmp, alpha, tmp);
felem_square(tmp2, gamma);
felem_scalar_8(tmp2);
felem_diff(y_out, tmp, tmp2);
}
static void point_add_mixed(felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2)
{
felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp;
felem_square(z1z1, z1);
felem_sum(tmp, z1, z1);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, x1);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, y1);
felem_sum(r, r, r);
felem_mul(v, x1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, y1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
static void point_add(felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2, const felem z2)
{
felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
felem_square(z1z1, z1);
felem_square(z2z2, z2);
felem_mul(u1, x1, z2z2);
felem_sum(tmp, z1, z2);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, z1z1);
felem_diff(tmp, tmp, z2z2);
felem_mul(z2z2z2, z2, z2z2);
felem_mul(s1, y1, z2z2z2);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, u1);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, s1);
felem_sum(r, r, r);
felem_mul(v, u1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, s1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
static void <API key>(
felem x_out, felem y_out, felem z_out,
const felem x1, const felem y1, const felem z1,
const felem x2, const felem y2, const felem z2)
{
felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;
char x_equal, y_equal;
felem_square(z1z1, z1);
felem_square(z2z2, z2);
felem_mul(u1, x1, z2z2);
felem_sum(tmp, z1, z2);
felem_square(tmp, tmp);
felem_diff(tmp, tmp, z1z1);
felem_diff(tmp, tmp, z2z2);
felem_mul(z2z2z2, z2, z2z2);
felem_mul(s1, y1, z2z2z2);
felem_mul(u2, x2, z1z1);
felem_mul(z1z1z1, z1, z1z1);
felem_mul(s2, y2, z1z1z1);
felem_diff(h, u2, u1);
x_equal = <API key>(h);
felem_sum(i, h, h);
felem_square(i, i);
felem_mul(j, h, i);
felem_diff(r, s2, s1);
y_equal = <API key>(r);
if (x_equal && y_equal) {
point_double(x_out, y_out, z_out, x1, y1, z1);
return;
}
felem_sum(r, r, r);
felem_mul(v, u1, i);
felem_mul(z_out, tmp, h);
felem_square(rr, r);
felem_diff(x_out, rr, j);
felem_diff(x_out, x_out, v);
felem_diff(x_out, x_out, v);
felem_diff(tmp, v, x_out);
felem_mul(y_out, tmp, r);
felem_mul(tmp, s1, j);
felem_diff(y_out, y_out, tmp);
felem_diff(y_out, y_out, tmp);
}
/* copy_conditional sets out=in if mask = 0xffffffff in constant time.
*
* On entry: mask is either 0 or 0xffffffff.
*/
static void copy_conditional(felem out, const felem in, limb mask)
{
int i;
for (i = 0; i < NLIMBS; i++) {
const limb tmp = mask & (in[i] ^ out[i]);
out[i] ^= tmp;
}
}
/* select_affine_point sets {out_x,out_y} to the index'th entry of table.
* On entry: index < 16, table[0] must be zero.
*/
static void select_affine_point(felem out_x, felem out_y,
const limb *table, limb index)
{
limb i, j;
memset(out_x, 0, sizeof(felem));
memset(out_y, 0, sizeof(felem));
for (i = 1; i < 16; i++) {
limb mask = i ^ index;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask
for (j = 0; j < NLIMBS; j++, table++) {
out_x[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_y[j] |= *table & mask;
}
}
}
/* <API key> sets {out_x,out_y,out_z} to the index'th entry of
* table. On entry: index < 16, table[0] must be zero.
*/
static void <API key>(felem out_x, felem out_y, felem out_z,
const limb *table, limb index)
{
limb i, j;
memset(out_x, 0, sizeof(felem));
memset(out_y, 0, sizeof(felem));
memset(out_z, 0, sizeof(felem));
/* The implicit value at index 0 is all zero. We don't need to perform that
* iteration of the loop because we already set out_* to zero.
*/
table += 3*NLIMBS;
for (i = 1; i < 16; i++) {
limb mask = i ^ index;
mask |= mask >> 2;
mask |= mask >> 1;
mask &= 1;
mask
for (j = 0; j < NLIMBS; j++, table++) {
out_x[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_y[j] |= *table & mask;
}
for (j = 0; j < NLIMBS; j++, table++) {
out_z[j] |= *table & mask;
}
}
}
/* get_bit returns the bit'th bit of scalar. */
static char get_bit(const u8 scalar[32], int bit)
{
return ((scalar[bit >> 3]) >> (bit & 7)) & 1;
}
/* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian
* number. Note that the value of scalar must be less than the order of the
* group.
*/
static void scalar_base_mult(felem nx, felem ny, felem nz, const u8 scalar[32])
{
int i, j;
limb n_is_infinity_mask = -1, <API key>, mask;
u32 table_offset;
felem px, py;
felem tx, ty, tz;
memset(nx, 0, sizeof(felem));
memset(ny, 0, sizeof(felem));
memset(nz, 0, sizeof(felem));
/* The loop adds bits at positions 0, 64, 128 and 192, followed by
* positions 32,96,160 and 224 and does this 32 times.
*/
for (i = 0; i < 32; i++) {
if (i) {
point_double(nx, ny, nz, nx, ny, nz);
}
table_offset = 0;
for (j = 0; j <= 32; j += 32) {
char bit0 = get_bit(scalar, 31 - i + j);
char bit1 = get_bit(scalar, 95 - i + j);
char bit2 = get_bit(scalar, 159 - i + j);
char bit3 = get_bit(scalar, 223 - i + j);
limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3);
select_affine_point(px, py, kPrecomputed + table_offset, index);
table_offset += 30 * NLIMBS;
/* Since scalar is less than the order of the group, we know that
* {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle
* below.
*/
point_add_mixed(tx, ty, tz, nx, ny, nz, px, py);
/* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero
* (a.k.a. the point at infinity). We handle that situation by
* copying the point from the table.
*/
copy_conditional(nx, px, n_is_infinity_mask);
copy_conditional(ny, py, n_is_infinity_mask);
copy_conditional(nz, kOne, n_is_infinity_mask);
/* Equally, the result is also wrong if the point from the table is
* zero, which happens when the index is zero. We handle that by
* only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0.
*/
<API key> = <API key>(index);
mask = <API key> & ~n_is_infinity_mask;
copy_conditional(nx, tx, mask);
copy_conditional(ny, ty, mask);
copy_conditional(nz, tz, mask);
/* If p was not zero, then n is now non-zero. */
n_is_infinity_mask &= ~<API key>;
}
}
}
/* point_to_affine converts a Jacobian point to an affine point. If the input
* is the point at infinity then it returns (0, 0) in constant time.
*/
static void point_to_affine(felem x_out, felem y_out,
const felem nx, const felem ny, const felem nz) {
felem z_inv, z_inv_sq;
felem_inv(z_inv, nz);
felem_square(z_inv_sq, z_inv);
felem_mul(x_out, nx, z_inv_sq);
felem_mul(z_inv, z_inv, z_inv_sq);
felem_mul(y_out, ny, z_inv);
}
/* scalar_mult sets {nx,ny,nz} = scalar*{x,y}. */
static void scalar_mult(felem nx, felem ny, felem nz,
const felem x, const felem y, const u8 scalar[32])
{
int i;
felem px, py, pz, tx, ty, tz;
felem precomp[16][3];
limb n_is_infinity_mask, index, <API key>, mask;
/* We precompute 0,1,2,... times {x,y}. */
memset(precomp, 0, sizeof(felem) * 3);
memcpy(&precomp[1][0], x, sizeof(felem));
memcpy(&precomp[1][1], y, sizeof(felem));
memcpy(&precomp[1][2], kOne, sizeof(felem));
for (i = 2; i < 16; i += 2) {
point_double(precomp[i][0], precomp[i][1], precomp[i][2],
precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]);
point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2],
precomp[i][0], precomp[i][1], precomp[i][2], x, y);
}
memset(nx, 0, sizeof(felem));
memset(ny, 0, sizeof(felem));
memset(nz, 0, sizeof(felem));
n_is_infinity_mask = -1;
/* We add in a window of four bits each iteration and do this 64 times. */
for (i = 0; i < 64; i++) {
if (i) {
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
point_double(nx, ny, nz, nx, ny, nz);
}
index = scalar[31 - i / 2];
if ((i & 1) == 1) {
index &= 15;
} else {
index >>= 4;
}
/* See the comments in scalar_base_mult about handling infinities. */
<API key>(px, py, pz, precomp[0][0], index);
point_add(tx, ty, tz, nx, ny, nz, px, py, pz);
copy_conditional(nx, px, n_is_infinity_mask);
copy_conditional(ny, py, n_is_infinity_mask);
copy_conditional(nz, pz, n_is_infinity_mask);
<API key> = <API key>(index);
mask = <API key> & ~n_is_infinity_mask;
copy_conditional(nx, tx, mask);
copy_conditional(ny, ty, mask);
copy_conditional(nz, tz, mask);
n_is_infinity_mask &= ~<API key>;
}
}
/* Interface with Freebl: */
/* <API key> swaps the bytes of a mp_digit to
* little-endian order.
*/
#ifdef IS_BIG_ENDIAN
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
#define BYTESWAP32(x) OSSwapInt32(x)
#define BYTESWAP64(x) OSSwapInt64(x)
#else
#define BYTESWAP32(x) \
(((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) & 0xff00) << 8) | ((x) << 24))
#define BYTESWAP64(x) \
(((x) >> 56) | (((x) >> 40) & 0xff00) | \
(((x) >> 24) & 0xff0000) | (((x) >> 8) & 0xff000000) | \
(((x) & 0xff000000) << 8) | (((x) & 0xff0000) << 24) | \
(((x) & 0xff00) << 40) | ((x) << 56))
#endif
#ifdef MP_USE_UINT_DIGIT
#define <API key>(x) BYTESWAP32(x)
#else
#define <API key>(x) BYTESWAP64(x)
#endif
#endif /* IS_BIG_ENDIAN */
#ifdef MP_USE_UINT_DIGIT
static const mp_digit kRInvDigits[8] = {
0x80000000, 1, 0xffffffff, 0,
0x80000001, 0xfffffffe, 1, 0x7fffffff
};
#else
static const mp_digit kRInvDigits[4] = {
PR_UINT64(0x180000000), 0xffffffff,
PR_UINT64(0xfffffffe80000001), PR_UINT64(0x7fffffff00000001)
};
#endif
#define <API key> (32/sizeof(mp_digit))
static const mp_int kRInv = {
MP_ZPOS,
<API key>,
<API key>,
(mp_digit*) kRInvDigits
};
static const limb kTwo28 = 0x10000000;
static const limb kTwo29 = 0x20000000;
/* to_montgomery sets out = R*in. */
static mp_err to_montgomery(felem out, const mp_int *in, const ECGroup *group)
{
/* There are no MPI functions for bitshift operations and we wish to shift
* in 257 bits left so we move the digits 256-bits left and then multiply
* by two.
*/
mp_int in_shifted;
int i;
mp_err res;
mp_init(&in_shifted);
s_mp_pad(&in_shifted, MP_USED(in) + <API key>);
memcpy(&MP_DIGIT(&in_shifted, <API key>),
MP_DIGITS(in),
MP_USED(in)*sizeof(mp_digit));
mp_mul_2(&in_shifted, &in_shifted);
MP_CHECKOK(group->meth->field_mod(&in_shifted, &in_shifted, group->meth));
for (i = 0;; i++) {
out[i] = MP_DIGIT(&in_shifted, 0) & kBottom29Bits;
mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL);
i++;
if (i == NLIMBS)
break;
out[i] = MP_DIGIT(&in_shifted, 0) & kBottom28Bits;
mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL);
}
CLEANUP:
mp_clear(&in_shifted);
return res;
}
/* from_montgomery sets out=in/R. */
static mp_err from_montgomery(mp_int *out, const felem in,
const ECGroup *group)
{
mp_int result, tmp;
mp_err res;
int i;
mp_init(&result);
mp_init(&tmp);
MP_CHECKOK(mp_add_d(&tmp, in[NLIMBS-1], &result));
for (i = NLIMBS-2; i >= 0; i
if ((i & 1) == 0) {
MP_CHECKOK(mp_mul_d(&result, kTwo29, &tmp));
} else {
MP_CHECKOK(mp_mul_d(&result, kTwo28, &tmp));
}
MP_CHECKOK(mp_add_d(&tmp, in[i], &result));
}
MP_CHECKOK(mp_mul(&result, &kRInv, out));
MP_CHECKOK(group->meth->field_mod(out, out, group->meth));
CLEANUP:
mp_clear(&result);
mp_clear(&tmp);
return res;
}
/* scalar_from_mp_int sets out_scalar=n, where n < the group order. */
static void scalar_from_mp_int(u8 out_scalar[32], const mp_int *n)
{
/* We require that |n| is less than the order of the group and therefore it
* will fit into |out_scalar|. However, these is a timing side-channel here
* that we cannot avoid: if |n| is sufficiently small it may be one or more
* words too short and we'll copy less data.
*/
memset(out_scalar, 0, 32);
#ifdef IS_LITTLE_ENDIAN
memcpy(out_scalar, MP_DIGITS(n), MP_USED(n) * sizeof(mp_digit));
#else
{
mp_size i;
mp_digit swapped[<API key>];
for (i = 0; i < MP_USED(n); i++) {
swapped[i] = <API key>(MP_DIGIT(n, i));
}
memcpy(out_scalar, swapped, MP_USED(n) * sizeof(mp_digit));
}
#endif
}
/* <API key> sets {out_x,out_y} = nG, where n is < the
* order of the group.
*/
static mp_err <API key>(const mp_int *n,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar[32];
felem x, y, z, x_affine, y_affine;
mp_err res;
/* FIXME(agl): test that n < order. */
scalar_from_mp_int(scalar, n);
scalar_base_mult(x, y, z, scalar);
point_to_affine(x_affine, y_affine, x, y, z);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* <API key> sets {out_x,out_y} = n*{in_x,in_y}, where n is <
* the order of the group.
*/
static mp_err <API key>(const mp_int *n,
const mp_int *in_x, const mp_int *in_y,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar[32];
felem x, y, z, x_affine, y_affine, px, py;
mp_err res;
scalar_from_mp_int(scalar, n);
MP_CHECKOK(to_montgomery(px, in_x, group));
MP_CHECKOK(to_montgomery(py, in_y, group));
scalar_mult(x, y, z, px, py, scalar);
point_to_affine(x_affine, y_affine, x, y, z);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* <API key> sets {out_x,out_y} = n1*G +
* n2*{in_x,in_y}, where n1 and n2 are < the order of the group.
*
* As indicated by the name, this function operates in variable time. This
* is safe because it's used for signature validation which doesn't deal
* with secrets.
*/
static mp_err <API key>(
const mp_int *n1, const mp_int *n2,
const mp_int *in_x, const mp_int *in_y,
mp_int *out_x, mp_int *out_y,
const ECGroup *group)
{
u8 scalar1[32], scalar2[32];
felem x1, y1, z1, x2, y2, z2, x_affine, y_affine, px, py;
mp_err res = MP_OKAY;
/* If n2 == NULL, this is just a base-point multiplication. */
if (n2 == NULL) {
return <API key>(n1, out_x, out_y, group);
}
/* If n1 == nULL, this is just an arbitary-point multiplication. */
if (n1 == NULL) {
return <API key>(n2, in_x, in_y, out_x, out_y, group);
}
/* If both scalars are zero, then the result is the point at infinity. */
if (mp_cmp_z(n1) == 0 && mp_cmp_z(n2) == 0) {
mp_zero(out_x);
mp_zero(out_y);
return res;
}
scalar_from_mp_int(scalar1, n1);
scalar_from_mp_int(scalar2, n2);
MP_CHECKOK(to_montgomery(px, in_x, group));
MP_CHECKOK(to_montgomery(py, in_y, group));
scalar_base_mult(x1, y1, z1, scalar1);
scalar_mult(x2, y2, z2, px, py, scalar2);
if (mp_cmp_z(n2) == 0) {
/* If n2 == 0, then {x2,y2,z2} is zero and the result is just
* {x1,y1,z1}. */
} else if (mp_cmp_z(n1) == 0) {
/* If n1 == 0, then {x1,y1,z1} is zero and the result is just
* {x2,y2,z2}. */
memcpy(x1, x2, sizeof(x2));
memcpy(y1, y2, sizeof(y2));
memcpy(z1, z2, sizeof(z2));
} else {
/* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */
<API key>(x1, y1, z1, x1, y1, z1, x2, y2, z2);
}
point_to_affine(x_affine, y_affine, x1, y1, z1);
MP_CHECKOK(from_montgomery(out_x, x_affine, group));
MP_CHECKOK(from_montgomery(out_y, y_affine, group));
CLEANUP:
return res;
}
/* Wire in fast point multiplication for named curves. */
mp_err <API key>(ECGroup *group, ECCurveName name)
{
if (name == ECCurve_NIST_P256) {
group->base_point_mul = &<API key>;
group->point_mul = &<API key>;
group->points_mul = &<API key>;
}
return MP_OKAY;
}
|
namespace Infrastructure.DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class <API key> : DbMigration
{
public override void Up()
{
AddColumn("dbo.ItSystemUsage", "UserSupervisionDate", c => c.DateTime(nullable: false, precision: 7, storeType: "datetime2"));
AddColumn("dbo.ItSystemUsage", "UserSupervision", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.ItSystemUsage", "UserSupervision");
DropColumn("dbo.ItSystemUsage", "UserSupervisionDate");
}
}
}
|
package org.seedstack.i18n.rest.internal.infrastructure.csv;
import com.google.common.collect.Sets;
import org.seedstack.i18n.rest.internal.locale.LocaleFinder;
import org.seedstack.i18n.rest.internal.locale.<API key>;
import org.seedstack.io.spi.Template;
import org.seedstack.io.spi.TemplateLoader;
import org.seedstack.io.supercsv.Column;
import org.seedstack.io.supercsv.SuperCsvTemplate;
import org.seedstack.jpa.JpaUnit;
import org.seedstack.seed.transaction.Transactional;
import org.supercsv.cellprocessor.Optional;
import javax.inject.Inject;
import java.util.List;
import java.util.Set;
/**
* @author pierre.thirouin@ext.mpsa.com
*/
public class <API key> implements TemplateLoader {
public static final String I18N_CSV_TEMPLATE = "i18nTranslations";
public static final String KEY = "key";
@Inject
private LocaleFinder localeFinder;
@JpaUnit("seed-i18n-domain")
@Transactional
@Override
public Template load(String name) {
List<<API key>> availableLocales = localeFinder.<API key>();
SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name);
superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional()));
for (<API key> availableLocale : availableLocales) {
superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional()));
}
return superCsvTemplate;
}
@Override
public Set<String> names() {
return Sets.newHashSet(I18N_CSV_TEMPLATE);
}
@Override
public boolean contains(String name) {
return names().contains(name);
}
@Override
public String templateRenderer() {
return I18nCSVRenderer.I18N_RENDERER;
}
@Override
public String templateParser() {
return CSVParser.I18N_PARSER;
}
}
|
<?php
declare(strict_types=1);
namespace ParkManager\Application\Command\User;
use Rollerworks\Component\SplitToken\SplitToken;
final class <API key>
{
/**
* @param string $password The password in hashed format
*/
public function __construct(public SplitToken $token, public string $password)
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour {
public float moveSpeed;
private float moveForce;
public float limit;
public bool vertical;
public bool movingPlus;
public Vector3 startPos;
Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
startPos = transform.position;
}
// Update is called once per frame
void Update () {
if (vertical == false) {
rb.velocity = new Vector2 (moveForce, rb.velocity.y);
} else {
rb.velocity = new Vector2 (rb.velocity.x, moveForce);
}
if (vertical == false) {
if (transform.localPosition.x >= startPos.x + limit) {
movingPlus = false;
}
if (transform.localPosition.x <= startPos.x - limit) {
movingPlus = true;
}
} else {
if (transform.localPosition.y >= startPos.y + limit) {
movingPlus = false;
}
if (transform.localPosition.y <= startPos.y - limit) {
movingPlus = true;
}
}
if (movingPlus == true)
{
moveForce = moveSpeed;
}
if (movingPlus == false)
{
moveForce = moveSpeed * -1;
}
}
}
|
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(env)]
#![feature(hash)]
#![feature(int_uint)]
#![feature(io)]
#![feature(<API key>)]
#![feature(path)]
#![feature(plugin)]
#![feature(rustc_private)]
#![feature(std_misc)]
#![feature(unicode)]
#![feature(unsafe_destructor)]
#![allow(<API key>)]
#[macro_use] extern crate log;
extern crate alloc;
#[macro_use] extern crate bitflags;
extern crate collections;
extern crate cssparser;
extern crate geom;
extern crate getopts;
extern crate layers;
extern crate libc;
#[no_link] #[macro_use] extern crate cssparser;
extern crate rand;
#[cfg(target_os="linux")]
extern crate regex;
extern crate "rustc-serialize" as rustc_serialize;
#[cfg(target_os="macos")]
extern crate task_info;
extern crate "time" as std_time;
extern crate text_writer;
extern crate selectors;
extern crate string_cache;
extern crate unicode;
extern crate url;
#[no_link] #[macro_use] #[plugin]
extern crate string_cache_macros;
extern crate lazy_static;
pub use selectors::smallvec;
use std::sync::Arc;
pub mod cache;
pub mod cursor;
pub mod debug_utils;
pub mod deque;
pub mod dlist;
pub mod fnv;
pub mod geometry;
pub mod logical_geometry;
pub mod memory;
pub mod namespace;
pub mod opts;
pub mod persistent_list;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod tid;
pub mod time;
pub mod taskpool;
pub mod task_state;
pub mod vec;
pub mod workqueue;
pub fn breakpoint() {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
|
import pytest
from umodbus.server.serial import <API key>
@pytest.fixture
def <API key>():
return <API key>()
def <API key>(<API key>):
""" Test if meta data is correctly extracted from request. """
assert <API key>.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def <API key>(<API key>):
assert <API key>._shutdown_request is False
<API key>.shutdown()
assert <API key>._shutdown_request is True
|
-- new sessions stored procedure
CREATE PROCEDURE `sessions_1` (
IN `uidArg` BINARY(16)
)
BEGIN
SELECT
tokenId,
uid,
createdAt,
uaBrowser,
uaBrowserVersion,
uaOS,
uaOSVersion,
uaDeviceType,
lastAccessTime
FROM sessionTokens
WHERE uid = uidArg;
END;
-- Schema patch-level increment.
UPDATE dbMetadata SET value = '17' WHERE name = 'schema-patch-level';
|
.frames ul .frames-group .group,
.frames ul .frames-group .group .location {
font-weight: 500;
cursor: default;
}
.frames ul .frames-group.expanded .group,
.frames ul .frames-group.expanded .group .location {
color: var(--<API key>);
}
.frames ul .frames-group.expanded .react path {
fill: var(--<API key>);
}
.frames ul .frames-group .frames-list li {
padding-left: 30px;
}
.frames ul .frames-group .frames-list {
border-top: 1px solid var(--<API key>);
border-bottom: 1px solid var(--<API key>);
}
.frames ul .frames-group.expanded .badge {
color: var(--<API key>);
}
|
if(!Attachments) var Attachments = {};
Attachments.List = new Class({
element : null,
initialize: function(options) {
this.element = document.id(options.container);
this.url = options.action;
this.token = options.token;
this.coordinates = '';
this.trueSize = '';
if(!this.element) {
return;
}
this.addCrop();
var that = this;
this.element.getElements('a[data-action]').each(function(a) {
if(a.get('data-action'))
{
a.addEvent('click', function(e) {
e.stop();
that.execute(this.get('data-action'), this.get('data-id'), this.get('data-row'));
});
}
});
},
addCrop: function()
{
var target = jQuery('#target');
var img = new Image(), self = this;
img.onload = function() {
self.trueSize = [this.width, this.height];
if (target.length) {
target.Jcrop({
boxWidth: 600,
boxHeight: 600,
trueSize: self.trueSize,
aspectRatio: 4 / 3,
minSize: [200, 150],
setSelect: [0, 0, 200, 150],
onSelect: self.setCoordinates.bind(self),
onChange: self.setCoordinates.bind(self)
});
}
};
var source = target.attr("src");
if (source) {
img.src = source;
}
},
setCoordinates: function(c)
{
this.coordinates = c;
},
execute: function(action, id, row)
{
var method = '_action' + action.capitalize();
if($type(this[method]) == 'function')
{
this.action = action;
var uri = new URI(this.url);
uri.setData('id', id);
this[method].call(this, uri);
}
},
_actionDelete: function(uri)
{
var form = new Kodekit.Form({
method: 'post',
url: uri.toString(),
params: {
_action: 'delete',
csrf_token: this.token
}
});
form.submit();
},
_actionCrop: function(uri)
{
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'post',
data: {
_action: 'edit',
csrf_token: this.token,
x1: this.coordinates.x,
y1: this.coordinates.y,
x2: this.coordinates.x2,
y2: this.coordinates.y2
}
}).then(function(data, textStatus, xhr) {
if (xhr.status === 204) {
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'get'
}).then(function(data, textStatus, xhr) {
if (xhr.status === 200 && typeof data.item === 'object') {
var thumbnail = data.item.thumbnail,
element = window.parent.jQuery('.thumbnail[data-id="'+data.item.id+'"] img'),
source = element.attr('src');
thumbnail = source.substring(0, source.lastIndexOf('/'))+'/'+thumbnail;
element.attr('src', thumbnail);
if (window.parent.SqueezeBox) {
window.parent.SqueezeBox.close();
}
}
});
} else {
alert('Unable to crop thumbnail');
}
});
}
});
|
this.joint = this.joint || {};
this.joint.shapes = this.joint.shapes || {};
(function (exports, basic_mjs, Element_mjs, Link_mjs) {
'use strict';
var State = basic_mjs.Circle.define('fsa.State', {
attrs: {
circle: { 'stroke-width': 3 },
text: { 'font-weight': '800' }
}
});
var StartState = Element_mjs.Element.define('fsa.StartState', {
size: { width: 20, height: 20 },
attrs: {
circle: {
transform: 'translate(10, 10)',
r: 10,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>',
});
var EndState = Element_mjs.Element.define('fsa.EndState', {
size: { width: 20, height: 20 },
attrs: {
'.outer': {
transform: 'translate(10, 10)',
r: 10,
fill: '#ffffff',
stroke: '#000000'
},
'.inner': {
transform: 'translate(10, 10)',
r: 6,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
});
var Arrow = Link_mjs.Link.define('fsa.Arrow', {
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }},
smooth: true
});
exports.Arrow = Arrow;
exports.EndState = EndState;
exports.StartState = StartState;
exports.State = State;
}(this.joint.shapes.fsa = this.joint.shapes.fsa || {}, joint.shapes.basic, joint.dia, joint.dia));
|
<!doctype html>
<script>
var searchParams = new URL(location).searchParams;
var test = searchParams.get("test");
window.onportalactivate = function(e) {
if (test == "adopt-once") {
var portal = e.adoptPredecessor();
document.body.appendChild(portal);
if (portal instanceof HTMLPortalElement) {
portal.postMessage("adopted", "*");
}
}
if (test == "adopt-twice") {
var portal = e.adoptPredecessor();
document.body.appendChild(portal);
try {
e.adoptPredecessor();
} catch(e) {
if (e.name == "InvalidStateError") {
portal.postMessage("passed", "*");
}
}
}
if (test == "adopt-after-event") {
setTimeout(function() {
try {
e.adoptPredecessor();
} catch(e) {
if (e.name == "InvalidStateError") {
var bc_test = new BroadcastChannel(`test-${test}`);
bc_test.postMessage("passed");
bc_test.close();
}
}
});
}
}
</script>
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>HYPERNOM</title>
<!
Nom all the cells of each 4d platonic solid, by mapping your head rotations to S^3.
By Henry Segerman, Vi Hart, and Andrea Hawksley, using Marc ten Bosch's 4D graphics shader, Mozilla's webVR stuff, and threejs.
http:
http://vihart.com
https://github.com/hawksley
http:
https://github.com/MozVR/vr-web-examples/tree/master/<API key>
http://threejs.org
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
background-color: #000;
color: #fff;
margin: 0px;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body style="cursor:pointer">
<audio id='music' src="media/monkeygif.mp3"/>
<audio id='nom1' src="media/nom1.ogg" >
<audio id='nom2' src="media/nom2.ogg" >
<audio id='nom3' src="media/nom3.ogg" >
<audio id='nom4' src="media/nom4.ogg" >
<audio id='nom5' src="media/nom5.ogg" >
<audio id='win' src="media/win.ogg" >
</body>
<!
three.js 3d library
<script src="js/lib/three.min.js"></script>
<script src="js/lib/threex.dynamictexture.js"></script>
<!
library for fast quaternion rotation
<script src="js/lib/gl-matrix.js"></script>
<script src="js/sphMath.js"></script>
<!
VRControls.js acquires positional information from connected VR devices and applies the transformations to a three.js camera object.
<script src="js/vr/PhoneVR.js"></script>
<script src="js/vr/VRControlsHyperNom.js"></script>
<!
VREffect.js handles stereo camera setup and rendering.
<script src="js/vr/VREffect.js"></script>
<!-- Quaternions for the centers of the cells -->
<script src="js/centers_600_cell.js"></script>
<script src="js/centers_5_cell.js"></script>
<script src="js/centers_8_cell.js"></script>
<script src="js/centers_16_cell.js"></script>
<script src="js/centers_24_cell.js"></script>
<script src="js/centers_120_cell.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="lib/helvetiker.js"></script>
<script type="x-shader/x-vertex" id="vertexShader">
// This shader moves vertices around
// Quaternion Multiplication
vec4 quatMult( in vec4 p, in vec4 q )
{
vec4 r;
r.w = + p.w*q.w - p.x*q.x - p.y*q.y - p.z*q.z;
r.x = + p.w*q.x + p.x*q.w + p.y*q.z - p.z*q.y;
r.y = + p.w*q.y - p.x*q.z + p.y*q.w + p.z*q.x;
r.z = + p.w*q.z + p.x*q.y - p.y*q.x + p.z*q.w;
return r;
}
vec4 quatInv( in vec4 p )
{
vec4 r;
r.x = -p.x;
r.y = -p.y;
r.z = -p.z;
r.w = p.w;
return r;
}
// Project the vector p to the 3-space perpendicular to q
vec4 projVecPerp( in vec4 p, in vec4 q )
{
vec4 r;
float pDotq = dot(p,q);
float qDotq = dot(q,q);
float foo = pDotq / qDotq;
r = p - foo*q;
return r;
}
// point on geod in S3 from p in direction of q going distance dist
vec4 pointOnS3Geod( in vec4 p, in vec4 q, in float dist)
{
vec4 Q = normalize( q - dot(p,q) * p );
return cos(dist)*p + sin(dist)*Q;
}
// input
uniform float time; // global time in seconds
uniform vec4 quatPerCell; // quaternion that moves this monkey into 4-space, set once per monkey
// uniform int fogType; // which type of fog to use
uniform vec2 mousePos;
uniform vec4 travelDir; //quaternion for which way we are rotating
uniform vec4 colourDir; //quaternion for which way we are colouring
uniform mat4 HopfColorMatrix; //rotates colourDir to lie along (0,0,z,w)
uniform vec4 moveQuat; //quaternion for head
uniform mat3 rotMatrix; //rotate tetrahedral cells into correct orientation
uniform float modelScale; //scale model by this
// Hopf fibration coloring
// returns a color based on the 4D normal
vec3 HopfColor( in vec4 nBase ) /// head foot are all same colour
{
//////first rotate the 4D normal to a space aligned with the polychoron
vec4 n = HopfColorMatrix * nBase;
// compute the color
float x = n.x;
float y = n.y;
float u = n.z;
float v = n.w;
float r = 2. * (u*x + v*y);
float g = 2. * (u*y - v*x);
float b = x*x + y*y - u*u - v*v;
first two coords are 2*z*conj(w), where z = x+iy, w = u+iv
rotate [0,0,-1] to [-1,-1,-1]/sqrt(3)
mat3 RotDownToDiag = mat3( vec3(0.707107, -0.707107, 0.), ///// input columns not rows?!?!?!
vec3(0.408248, 0.408248, -0.816497), //Because line n+3 is RotDownToDiag*newCol, not newCol*RotDownToDiag.
vec3(0.57735, 0.57735, 0.57735) ); //This basically lets the shader do matrix multiplication via dot products, which is relatively efficient.
vec3 newCol = vec3(r,g,b);
newCol = RotDownToDiag * newCol;
return vec3(newCol.x*0.5 + 0.5,newCol.y*0.5 + 0.5,newCol.z*0.5 + 0.5);
}
// output
varying vec3 vColor; // this shader computes the color of each vertex
// this gets called once per vertex of the monkey mesh (and numCells times since there are numCells monkeys)
void main()
{
// base position
// turn a 3D position of a model into a 4D position by adding a 1 as the w component then normalizing to get onto the unit 3-sphere
// vec4 p3sphere = normalize( vec4(position.zyx, 1.0) );
vec3 posn = position.zyx;
posn = rotMatrix * posn;
vec4 p3sphere = normalize( vec4(modelScale * posn, 1.0) );
// then rotate using this cell's quaternion to place in 4D
vec4 pt0 = quatMult( quatPerCell, p3sphere ); //position at time = 0
// this is the normal to the point
// same concept as for the position, but we add a 0 as the w component
vec4 n3sphere = vec4( normal.zyx, 0.0);
// above is normal on a cubical cell of the hypercube, below we get the corresponding
// normal on the 3-sphere
n3sphere = projVecPerp( n3sphere, p3sphere );
// rotate the normal using this monkey's quaternion
vec4 nt0 = quatMult(quatPerCell, n3sphere );
// // also rotate everything over time
// vec4 quatOverTime = pointOnS3Geod( vec4(0,0,0,1), travelDir, 0.5*time );
// vec4 quatOverTime = vec4(0,0,0,1);
vec4 quatOverTime = moveQuat;
vec4 p = quatMult( quatOverTime, pt0 );
vec4 n = quatMult( quatOverTime, nt0 );
// stereographic projection from 4D to 3D
vec3 pos3 = vec3( p.x / (1.0-p.w), p.y / (1.0-p.w), p.z / (1.0-p.w) );
// compute the color from the normal
/ using HopfColor again...
vec3 nColor = HopfColor(nt0);
/ or the transported back to 1 normal
// vec4 nTransported = quatMult(quatInv(pt0), nt0);
// vec3 nColor = vec3(0.5,0.5,0.5) + 0.5*normalize( vec3( nTransported.x, nTransported.y, nTransported.z) );
vec3 pColor = HopfColor(pt0);
vColor = -0.5*(nColor-vec3(0.5,0.5,0.5)) + 1.0*(pColor-vec3(0.5,0.5,0.5)) + vec3(0.5,0.5,0.5);
// vColor = pColor;
// vColor = nColor;
// take the final 3D position and project it onto the screen
// gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.6,-1.5), 1.0 );
// gl_Position = projectionMatrix * modelViewMatrix * vec4( pos3 + vec3(0.0,-0.7,-2.3), 1.0 );
gl_Position = modelViewMatrix * vec4( pos3 , 1.0 ); //truncate before the projectionMatrix transform (continued on line 253)
//Okay, now a slightly tricky thing:
//The camera's going to cull any vertices that are closer than 0.2, or further away than 25, from the camera.
//(in practice, this seems to be slightly different. I'm not sure why.)
//When this happens, it creates the black triangle of death, which pulls the viewer out of the virtual reality.
//To get around this, we're going to flatten out each vertex just before it reaches 0.2 or 25, moving it to where it would be.
//So, essentially, this is like replacing actual stars with a correctly painted planetarium.
//In case there's some weird z-layering going on, we're going to map -0.3,0 to -0.3, -0.2, preserving order.
float oldz=gl_Position.z;
if(oldz>-0.3 && oldz<0.0){
//map [-0.3, 0.0] to [-0.3,-0.2]
float newz=(oldz*0.3333333 - 0.2);
gl_Position.x=gl_Position.x*newz/(oldz);
gl_Position.y=gl_Position.y*newz/(oldz);
gl_Position.z=newz;
gl_Position.w=1.0;
}
gl_Position=projectionMatrix * gl_Position;
// do fog
// if ( fogType == 1 )
// ramp fog
// compute distance to camera from 0 to 1
float zz = gl_Position.z / gl_Position.w;
// go from 1 to 0 instead (0 is furthest and 1 is where the camera is )
// ( note that the computed distance is not linear )
float fogScale = 1. - zz;
// anything closer than 0.1 gets regular color
if ( fogScale > 0.1 )
fogScale = 1.0;
// everything else ramps from 0 to 1
else
fogScale = fogScale / 0.1;
// mutliply color by this value to make it go to black
vColor *= fogScale; //2015-02-17: fog re-enabled
// else if ( fogType == 2 )
// // near fog
// float zz = gl_Position.z / gl_Position.w;
// // go from 1 to 0, and make the curve less straight
// float fogScale = pow( 1. - zz, 0.7 );
// // everything closer than 0.2 gets regular color
// // but everything else stays the same, creating a discontinuity
// if ( fogScale > 0.2 ) fogScale = 1.0;
// // mutliply color by this value to make it go to black
// vColor *= fogScale;
// } else if (fogType == 3 ){
// vColor.r *= mousePos.x/1000.;
// vColor.g *= mousePos.y/1000.;
// vColor.b *= abs(1. - (mousePos.x + mousePos.y)/1000.);
}
</script>
<script type="x-shader/x-vertex" id="fragmentShader">
// this gets called once per pixel
varying vec3 vColor;
void main()
{
// just use the color we computed and assign it to this pixel
gl_FragColor = vec4( vColor, 1. );
}
</script>
<script type="text/javascript" id="mainCode" src="js/hypernom.js"></script>
</html>
|
.pinboard-open-btn {
margin-top: -1px;
background-color: #e6eef5 !important;
color: #252c33 !important;
}
#pinboard-panel {
background-color: #e6eef5;
color: #252c33;
flex: auto;
-webkit-flex: auto;
display: flex;
display: -webkit-flex;
flex-flow: row;
-webkit-flex-flow: row;
}
#pinboard-panel .header {
padding-left: 2px;
height: 18px;
}
/*
* Pinned jobs container
*/
#pinned-job-list {
position: relative;
flex: auto;
-webkit-flex: auto;
margin: 7px 7px 10px;
}
#pinned-job-list .content {
position: absolute;
width: 100%;
height: 100%;
padding: 2px;
overflow: auto;
background-color: #FFFFFF;
}
.pinned-job {
margin-bottom: 2px;
padding: 1px 2px;
width: 3.5em;
}
.<API key> {
padding: 1px 2px 1px 2px;
border-color: #fafafa #fafafa #fafafa transparent;
}
.<API key> {
color: #bfbfbf;
}
/*
* Related bugs container
*/
#<API key> {
position: relative;
width: 200px;
flex: none;
-webkit-flex: none;
margin: 7px 7px 10px;
}
#<API key> .content {
position: absolute;
height: 100%;
width: 200px;
padding: 2px;
overflow-x: hidden;
color: black;
background-color: #FFFFFF;
}
.<API key> {
margin-right: 2px;
font-size: 17px;
color: #98c3da;
}
.<API key> {
position: relative;
top: -18px;
left: 20px;
}
.<API key> {
width: 12em;
}
.<API key> {
vertical-align: top;
}
.<API key> {
margin-bottom: -1px;
}
.<API key>:hover > .related-bugs-link {
color: #2a6496;
text-decoration: underline;
}
/* Spin button suppression on chrome (bug 1045611) */
#<API key> form input[type=number]::-<API key> {
-webkit-appearance: none;
margin: 0;
}
/* Spin button suppression on firefox (bug 1045611) */
#<API key> form input[type=number] {
-moz-appearance: textfield;
}
/*
* Classification container
*/
#<API key> {
flex: none;
-webkit-flex: none;
width: 185px;
padding: 5px;
}
.pinboard-label {
color: #777;
}
#<API key> {
color: black;
}
#<API key> select {
width: 177px;
}
.<API key> {
width: 177px;
height: 20px;
padding: 0 0 0 3px;
border-radius: 0;
font-size: 12px;
}
/*
* Save container and dropdown menu controls
*/
#pinboard-controls {
flex: none;
-webkit-flex: none;
height: 43px;
margin: 20px;
}
#pinboard-controls .dropdown-menu {
z-index: 2000;
}
#pinboard-controls .save-btn-dropdown {
margin-left: -1px;
padding-top: 1px;
display: inline;
width: 24px;
float: right;
}
#pinboard-controls .save-btn {
float: left;
display: inline;
width: 70px;
}
.save-btn {
width: 81px;
}
.save-btn-dropdown {
width: 18px;
}
.btn-group + .btn + .save-btn-dropdown {
margin-left: -5px;
}
|
<form class="form-horizontal well" ng-submit="create(procedure)" >
<fieldset>
<legend>Create Procedure</legend>
<div class="form-group">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputMessage" placeholder="message" ng-model="procedure.message" >
</div>
</div>
<div class="form-group">
<label for="inputSource" class="col-lg-2 control-label">Source</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputSource" placeholder="source" ng-model="procedure.source" >
</div>
</div>
<div class="form-group">
<label for="inputType" class="col-lg-2 control-label">Type</label>
<div class="col-lg-10">
<select id="inputType" class="form-control" placeholder="type" ng-model="procedure.type">
<option>Crown Procedure</option>
<option>Surface Procedure</option>
<option>Ground Procedure</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputEnvironment" class="col-lg-2 control-label">Environment</label>
<div class="col-lg-10">
<select id="inputEnvironment" class="form-control" placeholder="environment" ng-model="procedure.environment">
<option>Production</option>
<option>Staging</option>
<option>Development</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputNetwork" class="col-lg-2 control-label">Network</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputNetwork" placeholder="network" ng-model="procedure.network" >
</div>
</div>
<div class="form-group">
<label for="inputDevice" class="col-lg-2 control-label">Device</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputDevice" placeholder="device" ng-model="procedure.device" >
</div>
</div>
<div class="form-group">
<label for="inputApplication" class="col-lg-2 control-label">Application</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputApplication" placeholder="application" ng-model="procedure.application" >
</div>
</div>
<div class="form-group">
<label for="inputStatus" class="col-lg-2 control-label">Status</label>
<div class="col-lg-10">
<select id="inputStatus" class="form-control" placeholder="status" ng-model="procedure.status">
<option>Draft</option>
<option>Active</option>
<option>Inactive</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputDescription" class="col-lg-2 control-label">Description</label>
<div class="col-lg-10">
<div text-angular ng-model="procedure.description" ></div>
</div>
</div>
<div class="form-group">
<label for="inputSteps" class="col-lg-2 control-label">Detailed Steps</label>
<div class="col-lg-10">
<div text-angular ng-model="procedure.steps" ></div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<a href="#/procedures" type="reset" class="btn btn-sm btn-default">Cancel</a>
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
</div>
</fieldset>
</form>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
panel_file = open('panels.txt','r')
name_file = open('testName.txt','r')
sample_type_file = open("sampleType.txt")
test_panel_results = open("output/testPanelResults.txt", 'w')
panel = []
type = []
test_names = []
def get_split_names( name ):
split_name_list = name.split("/")
for i in range(0, len(split_name_list)):
split_name_list[i] = split_name_list[i].strip()
return split_name_list
def esc_char(name):
if "'" in name:
return "$$" + name + "$$"
else:
return "'" + name + "'"
for line in panel_file:
panel.append(line.strip())
panel_file.close()
for line in sample_type_file:
type.append(line.strip())
sample_type_file.close()
for line in name_file:
test_names.append(line.strip())
name_file.close()
test_panel_results.write("Below should be pasted to TestPanel.csv\n\n")
for row in range(0, len(test_names)):
if len(panel[row]) > 1:
test_description = esc_char(test_names[row] + "(" + type[row] + ")")
test_panel_results.write("nextval( 'panel_item_seq' ) , (select id from panel where name = '" + panel[row] + "')")
test_panel_results.write(" , (select id from test where description = " + test_description + ") , null , now() \n")
test_panel_results.close()
print "Done look for results in testPanelResults.txt"
|
/* $RCSfile: eestrcon.c,v $
$Locker: $ $Name: $ $State: Exp $
char *EStrConcat(int argcnt, ...)
Concats up to argcnt strings together and malloc() a buffer that will
receive the result.
If one of the string == NULL, this string is ignored.
On failure, the program is terminated with the "out of memory" error.
Return:
the malloc'ed buffer
ob(ject): EStrConcat
su(bsystem): error
ty(pe): H
sh(ort description): Concat several strings together
lo(ng description): Concats several strings together, by using the
\tok{StrConcat()} function, and terminates the program on failure
with the error message: "Out of memory"
pr(erequistes):
re(lated to): StrConcat
se(condary subsystems): dynstr
in(itialized by):
wa(rning):
bu(gs):
va(lue): constructed dynamic string
fi(le): eestrcon.c
*/
#include "initsupl.loc"
#ifndef _MICROC_
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#endif
#include "dynstr.h"
#include "msgs.h"
#include "suppldbg.h"
#ifdef RCS_Version
static char const rcsid[] =
"$Id: eestrcon.c,v 1.1 2006/06/17 03:25:02 blairdude Exp $";
#endif
#ifdef _MICROC_
register char *EStrConcat(int argcnt)
{ unsigned cnt, *poi;
unsigned Xcnt, *Xpoi;
unsigned length;
char *h, *p;
DBG_ENTER1
cnt = nargs();
DBG_ENTER2("EStrConcat", "error")
DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, cnt) )
Xpoi = poi = cnt * 2 - 2 + &argcnt;
Xcnt = cnt = min(cnt, *poi);
for(length = 1; cnt
if(*--poi) length += strlen(*poi);
chkHeap
if((h = p = malloc(length)) == 0)
Esuppl_noMem();
chkHeap
while(Xcnt
if(*--Xpoi)
p = stpcpy(p, *Xpoi);
chkHeap
DBG_RETURN_S( h)
}
#else /* !_MICROC_ */
char *EStrConcat(int argcnt, ...)
{ va_list strings;
char *p, *s;
size_t length, l;
DBG_ENTER("EStrConcat", Suppl_error)
DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, argcnt) )
va_start(strings, argcnt);
chkHeap
p = Estrdup("");
chkHeap
length = 1;
while(argcnt
s = va_arg(strings, char *);
if(s && *s) {
l = length - 1;
Eresize(p, length += strlen(s));
strcpy(p + l, s);
}
}
va_end(strings);
chkHeap
DBG_RETURN_S( p)
}
#endif /* _MICROC_ */
|
import { createStore, applyMiddleware } from 'redux';
import threadDispatcher from '../../common/thread-middleware';
import handleMessages from '../../common/message-handler';
import messages from './messages-worker';
import reducers from './reducers';
import thunk from 'redux-thunk';
const store = createStore(
// Reducers:
reducers,
// Initial State:
{},
// Enhancers:
applyMiddleware(
[
thunk,
threadDispatcher(self, 'toContent'),
].filter(fn => fn)
)
);
handleMessages(self, store, messages);
|
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
var BUGNUMBER = 474935;
var summary = 'Do not assert: !ti->typeMap.matches(ti_other->typeMap)';
var actual = '';
var expect = '';
test();
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var a = ["", 0, 0, 0, 0, 0, "", "", 0, "", 0, ""];
var i = 0;
var g = 0;
for each (let e in a) {
"" + [e];
if (i == 3 || i == 7) {
for each (g in [1]) {
}
}
++i;
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
|
package command
import (
"strings"
"testing"
"time"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/mitchellh/cli"
)
func <API key>(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// Evals triggered by jobs log
state := &evalState{
status: structs.EvalStatusPending,
job: "job1",
}
mon.update(state)
out := ui.OutputWriter.String()
if !strings.Contains(out, "job1") {
t.Fatalf("missing job\n\n%s", out)
}
ui.OutputWriter.Reset()
// Evals trigerred by nodes log
state = &evalState{
status: structs.EvalStatusPending,
node: "<API key>",
}
mon.update(state)
out = ui.OutputWriter.String()
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing node\n\n%s", out)
}
// Transition to pending should not be logged
if strings.Contains(out, structs.EvalStatusPending) {
t.Fatalf("should skip status\n\n%s", out)
}
ui.OutputWriter.Reset()
// No logs sent if no update
mon.update(state)
if out := ui.OutputWriter.String(); out != "" {
t.Fatalf("expected no output\n\n%s", out)
}
// Status change sends more logs
state = &evalState{
status: structs.EvalStatusComplete,
node: "<API key>",
}
mon.update(state)
out = ui.OutputWriter.String()
if !strings.Contains(out, structs.EvalStatusComplete) {
t.Fatalf("missing status\n\n%s", out)
}
}
func <API key>(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// New allocations write new logs
state := &evalState{
allocs: map[string]*allocState{
"alloc1": &allocState{
id: "<API key>",
group: "group1",
node: "<API key>",
desired: structs.<API key>,
client: structs.<API key>,
index: 1,
},
},
}
mon.update(state)
// Logs were output
out := ui.OutputWriter.String()
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "group1") {
t.Fatalf("missing group\n\n%s", out)
}
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing node\n\n%s", out)
}
if !strings.Contains(out, "created") {
t.Fatalf("missing created\n\n%s", out)
}
ui.OutputWriter.Reset()
// No change yields no logs
mon.update(state)
if out := ui.OutputWriter.String(); out != "" {
t.Fatalf("expected no output\n\n%s", out)
}
ui.OutputWriter.Reset()
// Alloc updates cause more log lines
state = &evalState{
allocs: map[string]*allocState{
"alloc1": &allocState{
id: "<API key>",
group: "group1",
node: "<API key>",
desired: structs.<API key>,
client: structs.<API key>,
index: 2,
},
},
}
mon.update(state)
// Updates were logged
out = ui.OutputWriter.String()
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "pending") {
t.Fatalf("missing old status\n\n%s", out)
}
if !strings.Contains(out, "running") {
t.Fatalf("missing new status\n\n%s", out)
}
}
func <API key>(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
mon := newMonitor(ui, nil, fullId)
// New allocs with a create index lower than the
// eval create index are logged as modifications
state := &evalState{
index: 2,
allocs: map[string]*allocState{
"alloc3": &allocState{
id: "<API key>",
node: "<API key>",
group: "group2",
index: 1,
},
},
}
mon.update(state)
// Modification was logged
out := ui.OutputWriter.String()
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, "group2") {
t.Fatalf("missing group\n\n%s", out)
}
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing node\n\n%s", out)
}
if !strings.Contains(out, "modified") {
t.Fatalf("missing modification\n\n%s", out)
}
}
func TestMonitor_Monitor(t *testing.T) {
t.Parallel()
srv, client, _ := testServer(t, false, nil)
defer srv.Shutdown()
// Create the monitor
ui := new(cli.MockUi)
mon := newMonitor(ui, client, fullId)
// Submit a job - this creates a new evaluation we can monitor
job := testJob("job1")
resp, _, err := client.Jobs().Register(job, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
// Start monitoring the eval
var code int
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
code = mon.monitor(resp.EvalID, false)
}()
// Wait for completion
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatalf("eval monitor took too long")
}
// Check the return code. We should get exit code 2 as there
// would be a scheduling problem on the test server (no clients).
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, resp.EvalID) {
t.Fatalf("missing eval\n\n%s", out)
}
if !strings.Contains(out, "finished with status") {
t.Fatalf("missing final status\n\n%s", out)
}
}
func <API key>(t *testing.T) {
t.Parallel()
srv, client, _ := testServer(t, false, nil)
defer srv.Shutdown()
// Create the monitor
ui := new(cli.MockUi)
mon := newMonitor(ui, client, shortId)
// Submit a job - this creates a new evaluation we can monitor
job := testJob("job1")
resp, _, err := client.Jobs().Register(job, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
// Start monitoring the eval
var code int
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
code = mon.monitor(resp.EvalID[:8], true)
}()
// Wait for completion
select {
case <-doneCh:
case <-time.After(5 * time.Second):
t.Fatalf("eval monitor took too long")
}
// Check the return code. We should get exit code 2 as there
// would be a scheduling problem on the test server (no clients).
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, resp.EvalID[:8]) {
t.Fatalf("missing eval\n\n%s", out)
}
if strings.Contains(out, resp.EvalID) {
t.Fatalf("expected truncated eval id, got: %s", out)
}
if !strings.Contains(out, "finished with status") {
t.Fatalf("missing final status\n\n%s", out)
}
// Fail on identifier with too few characters
code = mon.monitor(resp.EvalID[:1], true)
if code != 1 {
t.Fatalf("expect exit 1, got: %d", code)
}
if out := ui.ErrorWriter.String(); !strings.Contains(out, "must contain at least two characters.") {
t.Fatalf("expected too few characters error, got: %s", out)
}
ui.ErrorWriter.Reset()
code = mon.monitor(resp.EvalID[:3], true)
if code != 2 {
t.Fatalf("expect exit 2, got: %d", code)
}
if out := ui.OutputWriter.String(); !strings.Contains(out, "Monitoring evaluation") {
t.Fatalf("expected evaluation monitoring output, got: %s", out)
}
}
func <API key>(t *testing.T) {
t.Parallel()
ui := new(cli.MockUi)
// Create an allocation and dump its status to the UI
alloc := &api.Allocation{
ID: "<API key>",
TaskGroup: "group1",
ClientStatus: structs.<API key>,
Metrics: &api.AllocationMetric{
NodesEvaluated: 10,
NodesFiltered: 5,
NodesExhausted: 1,
DimensionExhausted: map[string]int{
"cpu": 1,
},
ConstraintFiltered: map[string]int{
"$attr.kernel.name = linux": 1,
},
ClassExhausted: map[string]int{
"web-large": 1,
},
},
}
dumpAllocStatus(ui, alloc, fullId)
// Check the output
out := ui.OutputWriter.String()
if !strings.Contains(out, "<API key>") {
t.Fatalf("missing alloc\n\n%s", out)
}
if !strings.Contains(out, structs.<API key>) {
t.Fatalf("missing status\n\n%s", out)
}
if !strings.Contains(out, "5/10") {
t.Fatalf("missing filter stats\n\n%s", out)
}
if !strings.Contains(
out, `Constraint "$attr.kernel.name = linux" filtered 1 nodes`) {
t.Fatalf("missing constraint\n\n%s", out)
}
if !strings.Contains(out, "Resources exhausted on 1 nodes") {
t.Fatalf("missing resource exhaustion\n\n%s", out)
}
if !strings.Contains(out, `Class "web-large" exhausted on 1 nodes`) {
t.Fatalf("missing class exhaustion\n\n%s", out)
}
if !strings.Contains(out, `Dimension "cpu" exhausted on 1 nodes`) {
t.Fatalf("missing dimension exhaustion\n\n%s", out)
}
ui.OutputWriter.Reset()
// Dumping alloc status with no eligible nodes adds a warning
alloc.Metrics.NodesEvaluated = 0
dumpAllocStatus(ui, alloc, shortId)
// Check the output
out = ui.OutputWriter.String()
if !strings.Contains(out, "No nodes were eligible") {
t.Fatalf("missing eligibility warning\n\n%s", out)
}
if strings.Contains(out, "<API key>") {
t.Fatalf("expected truncated id, got %s", out)
}
if !strings.Contains(out, "87654321") {
t.Fatalf("expected alloc id, got %s", out)
}
}
|
#!/bin/bash
# This Source Code Form is subject to the terms of the Mozilla Public
set -ex
# required env vars: CLUSTER_NAME, CONFIG_BRANCH, CONFIG_REPO, NAMESPACE,
# DEPLOYMENT_YAML, <API key>, DEPLOYMENT_NAME, DEPLOYMENT_VERSION
|
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ResponseMode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ResponseMode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="D"/>
* <enumeration value="I"/>
* <enumeration value="Q"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ResponseMode")
@XmlEnum
public enum ResponseMode {
D,
I,
Q;
public String value() {
return name();
}
public static ResponseMode fromValue(String v) {
return valueOf(v);
}
}
|
#if BUILD_UNIT_TESTS
#include "augs/misc/enum/enum_map.h"
#include <Catch/single_include/catch2/catch.hpp>
TEST_CASE("EnumMap") {
enum class tenum {
_0,
_1,
_2,
_3,
_4,
COUNT
};
augs::enum_map<tenum, int> mm;
mm[tenum::_0] = 0;
mm[tenum::_1] = 1;
mm[tenum::_2] = 2;
int cnt = 0;
for (const auto&& m : mm) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);
}
REQUIRE(3 == cnt);
for (const auto&& m : reverse(mm)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
REQUIRE(0 == cnt);
{
augs::enum_map<tenum, int> emp;
for (const auto&& abc : emp) {
REQUIRE(false);
(void)abc;
}
for (const auto&& abc : reverse(emp)) {
REQUIRE(false);
(void)abc;
}
REQUIRE(emp.size() == 0);
emp[tenum::_0] = 48;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(48 == m.second);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_1] = 84;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(84 == m.second);
}
emp[tenum::_0] = 0;
emp[tenum::_1] = 1;
emp[tenum::_2] = 2;
REQUIRE(emp.size() == 3);
for (const auto&& m : emp) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);
}
REQUIRE(3 == cnt);
for (const auto&& m : reverse(emp)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_4] = 4;
emp[tenum::_3] = 3;
emp[tenum::_1] = 1;
emp[tenum::_0] = 0;
auto it = emp.rbegin();
REQUIRE((*it).second == 4);
REQUIRE((*++it).second == 3);
REQUIRE((*++it).second == 1);
REQUIRE((*++it).second == 0);
REQUIRE(++it == emp.rend());
}
}
#endif
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
package ims.core.clinical.domain.objects;
/**
*
* @author John MacEnri
* Generated.
*/
public class <API key> extends ims.domain.DomainObject implements ims.domain.<API key>, java.io.Serializable {
public static final int CLASSID = 1003100071;
private static final long serialVersionUID = 1003100071L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
private ims.domain.lookups.LookupInstance taxonomyName;
private String taxonomyCode;
private java.util.Date effectiveFrom;
private java.util.Date effectiveTo;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public <API key> (Integer id, int ver)
{
super(id, ver);
isComponentClass=true;
}
public <API key> ()
{
super();
isComponentClass=true;
}
public <API key> (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
isComponentClass=true;
}
public Class getRealDomainClass()
{
return ims.core.clinical.domain.objects.<API key>.class;
}
public ims.domain.lookups.LookupInstance getTaxonomyName() {
return taxonomyName;
}
public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) {
this.taxonomyName = taxonomyName;
}
public String getTaxonomyCode() {
return taxonomyCode;
}
public void setTaxonomyCode(String taxonomyCode) {
if ( null != taxonomyCode && taxonomyCode.length() > 30 ) {
throw new ims.domain.exceptions.<API key>("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+
taxonomyCode);
}
this.taxonomyCode = taxonomyCode;
}
public java.util.Date getEffectiveFrom() {
return effectiveFrom;
}
public void setEffectiveFrom(java.util.Date effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
public java.util.Date getEffectiveTo() {
return effectiveTo;
}
public void setEffectiveTo(java.util.Date effectiveTo) {
this.effectiveTo = effectiveTo;
}
public ims.domain.SystemInformation <API key>() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* <API key>
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean <API key>()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*taxonomyName* :");
if (taxonomyName != null)
auditStr.append(taxonomyName.getText());
auditStr.append("; ");
auditStr.append("\r\n*taxonomyCode* :");
auditStr.append(taxonomyCode);
auditStr.append("; ");
auditStr.append("\r\n*effectiveFrom* :");
auditStr.append(effectiveFrom);
auditStr.append("; ");
auditStr.append("\r\n*effectiveTo* :");
auditStr.append(effectiveTo);
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.<API key>() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getTaxonomyName() != null)
{
sb.append("<taxonomyName>");
sb.append(this.getTaxonomyName().toXMLString());
sb.append("</taxonomyName>");
}
if (this.getTaxonomyCode() != null)
{
sb.append("<taxonomyCode>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString()));
sb.append("</taxonomyCode>");
}
if (this.getEffectiveFrom() != null)
{
sb.append("<effectiveFrom>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveFrom>");
}
if (this.getEffectiveTo() != null)
{
sb.append("<effectiveTo>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveTo>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
<API key>(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
<API key>(set, el, factory, domMap);
return set;
}
private static void <API key>(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
<API key> domainObject = <API key>(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void <API key>(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
<API key> domainObject = <API key>(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static <API key> <API key>(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return <API key>(doc.getRootElement(), factory, domMap);
}
public static <API key> <API key>(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!<API key>.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!<API key>.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the <API key> class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (<API key>)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(<API key>.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
<API key> ret = null;
if (ret == null)
{
ret = new <API key>();
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, <API key> obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("taxonomyName");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("taxonomyCode");
if(fldEl != null)
{
obj.setTaxonomyCode(new String(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveFrom");
if(fldEl != null)
{
obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveTo");
if(fldEl != null)
{
obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
/**
equals
*/
public boolean equals(Object obj)
{
if (null == obj)
{
return false;
}
if(!(obj instanceof <API key>))
{
return false;
}
<API key> compareObj=(<API key>)obj;
if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&&
(taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&&
(effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&&
(effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo)))
return true;
return super.equals(obj);
}
/**
toString
*/
public String toString()
{
StringBuffer objStr = new StringBuffer();
if (taxonomyName != null)
objStr.append(taxonomyName.getText() + "-");
objStr.append(taxonomyCode);
return objStr.toString();
}
/**
hashcode
*/
public int hashCode()
{
int hash = 0;
if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011;
if (taxonomyCode!= null) hash += taxonomyCode.hashCode();
if (effectiveFrom!= null) hash += effectiveFrom.hashCode();
if (effectiveTo!= null) hash += effectiveTo.hashCode();
return hash;
}
public static class FieldNames
{
public static final String ID = "id";
public static final String TaxonomyName = "taxonomyName";
public static final String TaxonomyCode = "taxonomyCode";
public static final String EffectiveFrom = "effectiveFrom";
public static final String EffectiveTo = "effectiveTo";
}
}
|
package com.rapidminer.gui.plotter.mathplot;
import org.math.plot.Plot3DPanel;
import org.math.plot.PlotPanel;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.gui.plotter.<API key>;
/** The abstract super class for all 3D plotters using the JMathPlot library.
*
* @author Ingo Mierswa
*/
public abstract class JMathPlotter3D extends JMathPlotter {
private static final long serialVersionUID = -<API key>;
public JMathPlotter3D(<API key> settings) {
super(settings);
}
public JMathPlotter3D(<API key> settings, DataTable dataTable) {
super(settings, dataTable);
}
@Override
public PlotPanel createPlotPanel() { return new Plot3DPanel(); }
@Override
public int <API key>() {
return 5;
}
}
|
<?php
/**
* Smarty Internal Plugin Compile Make_Nocache
* Compiles the {make_nocache} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Make_Nocache Class
*
* @package Smarty
* @subpackage Compiler
*/
class <API key> extends <API key>
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see <API key>
*/
public $option_flags = [];
/**
* Array of names of required attribute required by tag
*
* @var array
*/
public $required_attributes = ['var'];
/**
* Shorttag attribute order defined by its names
*
* @var array
*/
public $shorttag_order = ['var'];
/**
* Compiles code for the {make_nocache} tag
*
* @param array $args array with attributes from parser
* @param \<API key> $compiler compiler object
* @param array $parameter array with compilation parameter
*
* @return string compiled code
* @throws \<API key>
*/
public function compile($args, <API key> $compiler, $parameter)
{
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
if ($compiler->template->caching) {
$output = "<?php \$_smarty_tpl->smarty->ext->_make_nocache->save(\$_smarty_tpl, {$_attr[ 'var' ]});\n?>\n";
$compiler->has_code = true;
$compiler-><API key> = true;
return $output;
} else {
return true;
}
}
}
|
<?php
$mess=array(
"Generic Conf Features" => "Configuraciones genéricas",
"Let user create repositories" => "Permitir al usuario crear repositorios",
"Remember guest preferences" => "Recordar preferencias de invitado",
"If the 'guest' user is enabled, remember her preferences accross sessions." => "Si el usuario 'Invitado' está habilitado, recordar sus preferencias a través de sesiones.",
"Configurations Management" => "Gestión de configuraciones",
"Sets how the application core data (users,roles,etc) is stored." => "Establece cómo se almacenan los datos básicos de aplicación (usuarios, roles, etc.)",
"Default start repository" => "Repositorio de inicio por defecto",
"Default repository" => "Repositorio por defecto",
"Maximum number of shared users per user" => "Número máximo de usuarios compartidos por usuario",
"Shared users limit" => "Límite de usuarios compartidos",
"Core SQL Connexion" => "Conexión SQL Principal",
"SQL Connexion" => "Conexión SQL",
"Simple SQL Connexion definition that can be used by other sql-based plugins" => "Definición de conexión SQL simple que puede ser utilizada por otros plugins basados en SQL",
"Preferences Saving" => "Preferencias de guardado",
"Skip user history" => "Omitir preferencias de interfaz",
"Use this option to avoid automatic reloading of the interface state (last folder, opened tabs, etc)" => "Utilice esta opción para evitar la carga automática del estado de la interfaz (última carpeta, pestañas abiertas, etc)",
"Internal / External Users" => "Usuarios internos / externos",
"Maximum number of users displayed in the users autocompleter" => "Número máximo de usuarios mostrados en la lista autocompletada de usuarios",
"Users completer limit" => "Límite del completador de usuarios",
"Minimum number of characters to trigger the auto completion feature" => "Número mínimo de caracteres para activar la función de autocompletado",
"Users completer min chars" => "Número mínimo de caracteres del completador de usuarios",
"Do not display real login in parenthesis" => "No mostrar el nombre de inicio de sesión real entre paréntesis",
"Hide real login" => "Ocultar nombre de inicio de sesión real",
"See existing users" => "Ver usuarios existentes",
"Allow the users to pick an existing user when sharing a folder" => "Permitir a los usuarios elegir un usuario existente al compartir una carpeta",
"Create external users" => "Crear usuarios externos",
"Allow the users to create a new user when sharing a folder" => "Permitir a los usuarios crear un nuevo usuario al compartir una carpeta",
"External users parameters" => "Parámetros de usuarios externos",
"List of parameters to be edited when creating a new shared user." => "Lista de parámetros a editar al crear un nuevo usuario compartido.",
"Configuration Store Instance" => "Instancia de almacenamiento de la configuración",
"Instance" => "Instancia",
"Choose the configuration plugin" => "Seleccionar el plugin de configuración",
"Name" => "Nombre",
"Full name displayed to others" => "Mostrar el nombre completo a los demás",
"Avatar" => "Avatar",
"Image displayed next to the user name" => "Imágen mostrada junto al nombre de usuario",
"Email" => "Correo electrónico",
"Address used for notifications" => "Dirección utilizada para las notificaciones",
"Country" => "País",
"Language" => "Idioma",
"User Language" => "Idioma del usuario",
"Role Label" => "Etiqueta de rol",
"Users Lock Action" => "Acción de bloqueo de usuarios",
"If set, this action will be triggered automatically at users login. Can be logout (to lock out the users), pass_change (to force password change), or anything else" => "Si se establece, esta acción se activará automáticamente en el inicio de sesión de los usuarios. Puede ser cerrar la sesión (para bloquear a los usuarios), cambiar contraseña (para forzar el cambio de contraseña), o cualquier otra cosa",
"Worskpace creation delegation" => "Delegación de la creación de repositorios",
"Let user create repositories from templates" => "Permitir al usuario crear repositorios usando plantillas",
"Whether users can create their own repositories, based on predefined templates." => "Si los usuarios pueden crear sus propios repositorios, hacerlo basándose en plantillas predefinidas.",
"Users Directory Listing" => "Listado del directorio de usuarios",
"Share with existing users from all groups" => "Compartir con los usuarios existentes de todos los grupos",
"Allow to search users from other groups through auto completer (can be handy if previous option is set to false) and share workspaces with them" => "Permitir de buscar usuarios de otros grupos a través de autocompletar (puede ser útil si la opción anterior se establece en False) y compartir repositorios con ellos",
"List existing from all groups" => "Listar existentes de todos los grupos",
"If previous option is set to True, directly display a full list of users from all groups" => "Si la opción anterior se establece en True, mostrar directamente una lista completa de los usuarios de todos los grupos",
"Roles / Groups Directory Listing" => "Listado de roles / directorio de grupos",
"Display roles and/or groups" => "Mostrar roles y/o grupos",
"Users only (do not list groups nor roles)" => "Sólo usuarios (no listar grupos ni roles)",
"Allow Group Listing" => "Permitir el listado de grupos",
"Allow Role Listing" => "Permitir el listado de roles",
"Role/Group Listing" => "Listado de roles/grupos",
"List Roles By" => "Listar roles por",
"All roles" => "Todos los roles",
"User roles only" => "Sólo roles de usuario",
"role prefix" => "Prefijo del rol",
"Excluded Roles" => "Roles excluidos",
"Included Roles" => "Roles incluidos",
"Some roles should be disappered in the list. list separated by ',' or start with 'preg:' for regex." => "Roles ocultos en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.",
"Some roles should be shown in the list. list separated by ',' or start with 'preg:' for regex." => "Roles que deben mostrarse en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.",
"External Users Creation" => "Creación de usuarios externos",
"Always override other roles, included group roles." => "Ignorar siempre otros roles, incluido los roles de grupo.",
"Always Override" => "Ignorar Siempre",
"Do not load groups and users list if no regexp is entered. Avoid sending large search on LDAP." => "No cargar la lista de grupos y usuarios si no se introduce una regexp. Evita enviar búsquedas largas a LDAP.",
"Make regexp mandatory" => "Regexp obligatorio",
);
|
<!-- title: crm -->
<div class="dev-header">
<a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;">
Version 6.7.7</a>
<a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/crm"
target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a>
</div>
<h3>Package Contents</h3>
{index}
<!-- autodoc -->
|
<?php
namespace Symfony\Component\HttpKernel\Profiler;
use Symfony\Component\HttpKernel\DataCollector\<API key>;
/**
* Profile.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Profile
{
private $token;
/**
* @var <API key>[]
*/
private $collectors = array();
private $ip;
private $method;
private $url;
private $time;
/**
* @var Profile
*/
private $parent;
/**
* @var Profile[]
*/
private $children = array();
/**
* Constructor.
*
* @param string $token The token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Returns the parent profile.
*
* @return Profile The parent profile
*/
public function getParent()
{
return $this->parent;
}
/**
* Sets the parent token
*
* @param Profile $parent The parent Profile
*/
public function setParent( Profile $parent )
{
$this->parent = $parent;
}
/**
* Returns the parent token.
*
* @return null|string The parent token
*/
public function getParentToken()
{
return $this->parent ? $this->parent->getToken() : null;
}
/**
* Gets the token.
*
* @return string The token
*/
public function getToken()
{
return $this->token;
}
/**
* Sets the token.
*
* @param string $token The token
*/
public function setToken( $token )
{
$this->token = $token;
}
/**
* Returns the IP.
*
* @return string The IP
*/
public function getIp()
{
return $this->ip;
}
/**
* Sets the IP.
*
* @param string $ip
*/
public function setIp($ip)
{
$this->ip = $ip;
}
/**
* Returns the request method.
*
* @return string The request method
*/
public function getMethod()
{
return $this->method;
}
public function setMethod($method)
{
$this->method = $method;
}
/**
* Returns the URL.
*
* @return string The URL
*/
public function getUrl()
{
return $this->url;
}
public function setUrl($url)
{
$this->url = $url;
}
/**
* Returns the time.
*
* @return string The time
*/
public function getTime()
{
if (null === $this->time) {
return 0;
}
return $this->time;
}
public function setTime($time)
{
$this->time = $time;
}
/**
* Finds children profilers.
*
* @return Profile[] An array of Profile
*/
public function getChildren()
{
return $this->children;
}
/**
* Sets children profiler.
*
* @param Profile[] $children An array of Profile
*/
public function setChildren(array $children)
{
$this->children = array();
foreach ($children as $child) {
$this->addChild($child);
}
}
/**
* Adds the child token
*
* @param Profile $child The child Profile
*/
public function addChild(Profile $child)
{
$this->children[] = $child;
$child->setParent($this);
}
/**
* Gets a Collector by name.
*
* @param string $name A collector name
*
* @return <API key> A <API key> instance
*
* @throws \<API key> if the collector does not exist
*/
public function getCollector($name)
{
if (!isset($this->collectors[$name])) {
throw new \<API key>(sprintf('Collector "%s" does not exist.', $name));
}
return $this->collectors[$name];
}
/**
* Gets the Collectors associated with this profile.
*
* @return <API key>[]
*/
public function getCollectors()
{
return $this->collectors;
}
/**
* Sets the Collectors associated with this profile.
*
* @param <API key>[] $collectors
*/
public function setCollectors(array $collectors)
{
$this->collectors = array();
foreach ($collectors as $collector) {
$this->addCollector($collector);
}
}
/**
* Adds a Collector.
*
* @param <API key> $collector A <API key> instance
*/
public function addCollector(<API key> $collector)
{
$this->collectors[$collector->getName()] = $collector;
}
/**
* Returns true if a Collector for the given name exists.
*
* @param string $name A collector name
*
* @return bool
*/
public function hasCollector($name)
{
return isset($this->collectors[$name]);
}
public function __sleep()
{
return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time');
}
}
|
# session module tests
require 'spec_helper'
require 'timecop'
require 'users/session'
module Users
describe Session do
after(:all) do
Timecop.return
end
describe "#initialize" do
it "sets attributes" do
id = Motel.gen_uuid
u = User.new :id => 'user1'
s = Session.new :id => id, :user => u, :endpoint_id => 'node1'
s.id.should == id
s.user.id.should == 'user1'
s.refreshed_time.should_not be_nil
s.endpoint_id.should == 'node1'
end
end
describe "#timed_out" do
before(:each) do
Timecop.freeze
@u = User.new :id => 'user1'
@s = Session.new :id => 'id', :user => @u
end
after(:each) do
Timecop.travel
end
context "timeout has passed" do
it "returns true" do
Timecop.freeze Session::SESSION_EXPIRATION + 1
@s.timed_out?.should be_true
end
end
context "timeout has not passed" do
it "returns false" do
@s.timed_out?.should be_false
@s.<API key>(:@refreshed_time).should == Time.now
end
end
context "user is permenant" do
it "always returns false" do
@u.permenant = true
Timecop.freeze Session::SESSION_EXPIRATION + 1
@s.timed_out?.should be_false
end
end
end
describe "#to_json" do
it "returns json representation of session" do
u = User.new :id => 'user1'
s = Session.new :id => '1234', :user => u, :endpoint_id => 'node1'
j = s.to_json
j.should include('"json_class":"Users::Session"')
j.should include('"id":"1234"')
j.should include('"json_class":"Users::User"')
j.should include('"id":"user1"')
j.should include('"refreshed_time":')
j.should include('"endpoint_id":"node1"')
end
end
describe "#json_create" do
it "returns session from json format" do
j = '{"json_class":"Users::Session","data":{"user":{"json_class":"Users::User","data":{"id":"user1","email":null,"roles":null,"permenant":false,"npc":false,"attributes":null,"password":null,"registration_code":null}},"id":"1234","refreshed_time":"2013-05-30 00:43:54 -0400"}}'
s = ::RJR::JSONParser.parse(j)
s.class.should == Users::Session
s.id.should == "1234"
s.user.id.should == 'user1'
s.refreshed_time.should_not be_nil
end
end
end # describe Session
end # module Users
|
import React from 'react';
import ImmutablePropTypes from '<API key>';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import <API key> from '<API key>';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
});
@injectIntl
export default class StatusActionBar extends <API key> {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onMuteConversation: PropTypes.func,
me: PropTypes.number.isRequired,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See <API key> for usage.
updateOnProps = [
'status',
'me',
'withDismiss',
]
handleReplyClick = () => {
this.props.onReply(this.props.status, this.context.router.history);
}
<API key> = () => {
this.props.onFavourite(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleOpen = () => {
this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
<API key> = () => {
this.props.onMuteConversation(this.props.status);
}
render () {
const { status, me, intl, withDismiss } = this.props;
const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct';
const mutingConversation = status.get('muted');
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
menu.push(null);
if (withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.<API key> });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = 'reply-all';
replyTitle = intl.formatMessage(messages.replyAll);
}
return (
<div className='status__action-bar'>
<IconButton className='<API key>' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} />
<IconButton className='<API key>' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='<API key> star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.<API key>} />
<div className='<API key>'>
<DropdownMenu items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel='More' />
</div>
</div>
);
}
}
|
# -*- coding: utf-8 -*-
# This file is part of Shoop.
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from shoop.admin.form_part import FormPart, TemplatedFormDef
from shoop.core.models import Shop
from shoop.discount_pricing.models import <API key>
class DiscountPricingForm(forms.Form):
def __init__(self, **kwargs):
self.product = kwargs.pop("product")
super(DiscountPricingForm, self).__init__(**kwargs)
self.shops = []
if self.product:
self._build_fields()
def _build_fields(self):
self.shops = list(Shop.objects.all())
<API key> = dict(
(shop_id, price)
for (shop_id, price)
in <API key>.objects.filter(product=self.product)
.values_list("shop_id", "price_value")
)
for shop in self.shops:
name = self._get_field_name(shop)
price = <API key>.get(shop.id)
price_field = forms.DecimalField(
min_value=0, initial=price,
label=_("Price (%s)") % shop, required=False
)
self.fields[name] = price_field
def _get_field_name(self, shop):
return "s_%d" % shop.id
def <API key>(self, shop):
name = self._get_field_name(shop)
value = self.cleaned_data.get(name)
clear = (value is None or value < 0)
if clear:
<API key>.objects.filter(product=self.product, shop=shop).delete()
else:
(spp, created) = <API key>.objects.get_or_create(
product=self.product, shop=shop,
defaults={'price_value': value})
if not created:
spp.price_value = value
spp.save()
def save(self):
if not self.has_changed(): # No changes, so no need to do anything.
return
for shop in self.shops:
self.<API key>(shop)
def get_shop_field(self, shop):
name = self._get_field_name(shop)
return self[name]
class <API key>(FormPart):
priority = 10
def get_form_defs(self):
yield TemplatedFormDef(
name="discount_pricing",
form_class=DiscountPricingForm,
template_name="shoop/admin/discount_pricing/form_part.jinja",
required=False,
kwargs={"product": self.object}
)
def form_valid(self, form):
form["discount_pricing"].save()
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.03 at 10:12:07 AM MEZ
package com.lp.server.schema.opentrans.cc.orderresponse;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.<API key>;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "<API key>", propOrder = {
"value"
})
public class <API key> {
@XmlValue
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(<API key>.class)
protected String type;
@XmlAttribute(name = "xsi_schemaLocation")
protected String xsiSchemaLocation;
@XmlAttribute(name = "xmlns_xsd")
protected String xmlnsXsd;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the xsiSchemaLocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String <API key>() {
if (xsiSchemaLocation == null) {
return "openbase_1_0.mxsd";
} else {
return xsiSchemaLocation;
}
}
/**
* Sets the value of the xsiSchemaLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void <API key>(String value) {
this.xsiSchemaLocation = value;
}
/**
* Gets the value of the xmlnsXsd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXsd() {
if (xmlnsXsd == null) {
return "http:
} else {
return xmlnsXsd;
}
}
/**
* Sets the value of the xmlnsXsd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXsd(String value) {
this.xmlnsXsd = value;
}
}
|
-- uncomment for testing
/*
DECLARE @id int = 1
*/
SELECT * FROM Products WHERE Id = @id
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>api Package — ally-py 1.0b1 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: '',
VERSION: '1.0b1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="ally-py 1.0b1 documentation" href="index.html" />
<link rel="up" title="person Package" href="superdesk.person.html" />
<link rel="next" title="impl Package" href="superdesk.person.impl.html" />
<link rel="prev" title="person Package" href="superdesk.person.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="superdesk.person.impl.html" title="impl Package"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="superdesk.person.html" title="person Package"
accesskey="P">previous</a> |</li>
<li><a href="index.html">ally-py 1.0b1 documentation</a> »</li>
<li><a href="superdesk.html" >superdesk Package</a> »</li>
<li><a href="superdesk.person.html" accesskey="U">person Package</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="api-package">
<h1>api Package<a class="headerlink" href="
<div class="section" id="person-module">
<h2><tt class="xref py py-mod docutils literal"><span class="pre">person</span></tt> Module<a class="headerlink" href="
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="<API key>">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">api Package</a><ul>
<li><a class="reference internal" href="#person-module"><tt class="docutils literal"><span class="pre">person</span></tt> Module</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="superdesk.person.html"
title="previous chapter">person Package</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="superdesk.person.impl.html"
title="next chapter">impl Package</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/superdesk.person.api.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="superdesk.person.impl.html" title="impl Package"
>next</a> |</li>
<li class="right" >
<a href="superdesk.person.html" title="person Package"
>previous</a> |</li>
<li><a href="index.html">ally-py 1.0b1 documentation</a> »</li>
<li><a href="superdesk.html" >superdesk Package</a> »</li>
<li><a href="superdesk.person.html" >person Package</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2012, Gabriel Nistor.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html>
|
import ITEM_QUALITIES from '../ITEM_QUALITIES';
export default {
// Shared legendaries
<API key>: {
id: 150936,
name: 'Soul of the Shadowblade',
icon: 'inv_jewelry_ring_56',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 144236,
name: 'Mantle of the Master Assassin',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 137049,
name: 'Insignia of Ravenholdt',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
WILL_OF_VALEERA: {
id: 137069,
name: 'Will of Valeera',
icon: 'inv_pants_cloth_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 137021,
name: 'The Dreadlord\'s Deceit',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Assassination legendaries
<API key>: {
id: 137030,
name: 'Duskwalker\'s Footpads',
icon: 'inv_boots_leather_8',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 137098,
name: 'Zoldyck Family Training Shackles',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_EMPTY_CROWN: {
id: 151815,
name: 'The Empty Crown',
icon: 'inv_crown_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Outlaw legendaries
<API key>: {
id: 137031,
name: 'Thraxi\'s Tricksy Treads',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 137099,
name: 'Greenskin\'s Waterlogged Wristcuffs',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
SHIVARRAN_SYMMETRY: {
id: 141321,
name: 'Shivarran Symmetry',
icon: 'inv_gauntlets_83',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 151817,
name: 'The Curse of Restlessness',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Subtlety legendaries
SHADOW_SATYRS_WALK: {
id: 137032,
name: 'Shadow Satyr\'s Walk',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 137100,
name: 'Denial of the Half-Giants',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
<API key>: {
id: 151818,
name: 'The First of the Dead',
icon: '<API key>',
quality: ITEM_QUALITIES.LEGENDARY,
},
};
|
module Merb::Maintainer::BillingHelper
def get_stats(metric, dom)
today = Date.today
date_this_month = Date.new(today.year, today.month, dom)
data = []
data_length = 30
data << get_stat(metric, date_this_month) if dom < today.mday
(1..(data_length-data.length)).each do |i|
date = date_this_month << i
data << get_stat(metric, date)
end
data
end
# to add a new metric to the billing section, add a case below
def get_stat(metric, date)
case metric
when "active_loans"
count = repository.adapter.query(%Q{
SELECT COUNT(date) FROM loan_history lh,
(SELECT max(date) AS mdt, loan_id FROM loan_history lh2 WHERE date <= '#{date.strftime}' GROUP BY loan_id) AS md
WHERE lh.date = md.mdt AND lh.loan_id = md.loan_id AND lh.status IN (2,4,5,6);
}).first
when "total_loans"
count = Loan.count(:applied_on.lte => date)
when "total_clients"
count = Client.count(:date_joined.lte => date)
end
{
:date => date.strftime(<API key>),
:count => count
}
end
end
|
#include <QMessageBox>
#include "longtextmessagebox.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include <QListWidget>
#include <QScrollBar>
#include <QAbstractItemView>
<API key>::<API key>(QWidget* parent): QDialog(parent)
{
setupUi(this);
<API key>->setReadOnly(true);
<API key>->setDefault(true);
<API key>->setSelectionMode(QAbstractItemView::SingleSelection);
connect(<API key>, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));
connect(<API key>, SIGNAL(clicked()), this, SLOT(addConstraint()));
connect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));
connect(<API key>, SIGNAL(clicked()), this, SLOT(removeConstraint()));
connect(<API key>, SIGNAL(clicked()), this, SLOT(modifyConstraint()));
connect(<API key>, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));
<API key>(this);
<API key>(this);
this->filterChanged();
}
<API key>::~<API key>()
{
<API key>(this);
}
bool <API key>::filterOk(TimeConstraint* ctr)
{
if(ctr->type==<API key>)
return true;
else
return false;
}
void <API key>::filterChanged()
{
this-><API key>.clear();
<API key>->clear();
for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){
TimeConstraint* ctr=gt.rules.timeConstraintsList[i];
if(filterOk(ctr)){
<API key>.append(ctr);
<API key>->addItem(ctr->getDescription(gt.rules));
}
}
if(<API key>->count()>0)
<API key>->setCurrentRow(0);
else
constraintChanged(-1);
}
void <API key>::constraintChanged(int index)
{
if(index<0){
<API key>->setPlainText("");
return;
}
assert(index<this-><API key>.size());
TimeConstraint* ctr=this-><API key>.at(index);
assert(ctr!=NULL);
<API key>->setPlainText(ctr-><API key>(gt.rules));
}
void <API key>::addConstraint()
{
<API key> form(this);
<API key>(&form, this);
form.exec();
filterChanged();
<API key>->setCurrentRow(<API key>->count()-1);
}
void <API key>::modifyConstraint()
{
int valv=<API key>->verticalScrollBar()->value();
int valh=<API key>->horizontalScrollBar()->value();
int i=<API key>->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this-><API key>.at(i);
<API key> form(this, (<API key>*)ctr);
<API key>(&form, this);
form.exec();
filterChanged();
<API key>->verticalScrollBar()->setValue(valv);
<API key>->horizontalScrollBar()->setValue(valh);
if(i>=<API key>->count())
i=<API key>->count()-1;
if(i>=0)
<API key>->setCurrentRow(i);
else
this->constraintChanged(-1);
}
void <API key>::removeConstraint()
{
int i=<API key>->currentRow();
if(i<0){
QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint"));
return;
}
TimeConstraint* ctr=this-><API key>.at(i);
QString s;
s=tr("Remove constraint?");
s+="\n\n";
s+=ctr-><API key>(gt.rules);
QListWidgetItem* item;
switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"),
s, tr("Yes"), tr("No"), 0, 0, 1 ) ){
case 0: // The user clicked the OK button or pressed Enter
gt.rules.<API key>(ctr);
<API key>.removeAt(i);
<API key>->setCurrentRow(-1);
item=<API key>->takeItem(i);
delete item;
break;
case 1: // The user clicked the Cancel button or pressed Escape
break;
}
if(i>=<API key>->count())
i=<API key>->count()-1;
if(i>=0)
<API key>->setCurrentRow(i);
else
this->constraintChanged(-1);
}
|
# -*- coding: utf-8 -*-
# OpenERP, Open Source Management Solution
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import base64
import netsvc
from osv import osv
from osv import fields
from tools.translate import _
import tools
def _reopen(self, wizard_id, res_model, res_id):
return {'type': 'ir.actions.act_window',
'view_mode': 'form',
'view_type': 'form',
'res_id': wizard_id,
'res_model': self._name,
'target': 'new',
# save original model in context, otherwise
# it will be lost on the action's context switch
'context': {'mail.compose.target.model': res_model,
'mail.compose.target.id': res_id,}
}
class <API key>(osv.osv_memory):
_inherit = 'mail.compose.message'
def _get_templates(self, cr, uid, context=None):
"""
Return Email Template of particular Model.
"""
if context is None:
context = {}
record_ids = []
email_template= self.pool.get('email.template')
model = False
if context.get('message_id'):
mail_message = self.pool.get('mail.message')
message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context)
model = message_data.model
elif context.get('mail.compose.target.model') or context.get('active_model'):
model = context.get('mail.compose.target.model', context.get('active_model'))
if model:
record_ids = email_template.search(cr, uid, [('model', '=', model)])
return email_template.name_get(cr, uid, record_ids, context) + [(False,'')]
return []
_columns = {
'use_template': fields.boolean('Use Template'),
'template_id': fields.selection(_get_templates, 'Template',
size=-1 # means we want an int db column
),
}
_defaults = {
'template_id' : lambda self, cr, uid, context={} : context.get('mail.compose.template_id', False)
}
def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None):
if context is None:
context = {}
values = {}
if template_id:
res_id = context.get('mail.compose.target.id') or context.get('active_id') or False
if context.get('mail.compose.message.mode') == 'mass_mail':
# use the original template values - to be rendered when actually sent
# by super.send_mail()
values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context)
report_xml_pool = self.pool.get('ir.actions.report.xml')
template = self.pool.get('email.template').get_email_template(cr, uid, template_id, res_id, context)
values['attachments'] = False
attachments = {}
if template.report_template:
report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
# Ensure report is rendered using template's language
ctx = context.copy()
if template.lang:
ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context)
service = netsvc.LocalService(report_service)
(result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx)
result = base64.b64encode(result)
if not report_name:
report_name = report_service
ext = "." + format
if not report_name.endswith(ext):
report_name += ext
attachments[report_name] = result
# Add document attachments
for attach in template.attachment_ids:
# keep the bytes as fetched from the db, base64 encoded
attachments[attach.datas_fname] = attach.datas
values['attachments'] = attachments
if values['attachments']:
attachment = values.pop('attachments')
attachment_obj = self.pool.get('ir.attachment')
att_ids = []
for fname, fcontent in attachment.iteritems():
data_attach = {
'name': fname,
'datas': fcontent,
'datas_fname': fname,
'description': fname,
'res_model' : self._name,
'res_id' : ids[0] if ids else False
}
att_ids.append(attachment_obj.create(cr, uid, data_attach))
values['attachment_ids'] = att_ids
else:
# render the mail as one-shot
values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context)
# retrofit generated attachments in the expected field format
if values['attachments']:
attachment = values.pop('attachments')
attachment_obj = self.pool.get('ir.attachment')
att_ids = []
for fname, fcontent in attachment.iteritems():
data_attach = {
'name': fname,
'datas': fcontent,
'datas_fname': fname,
'description': fname,
'res_model' : self._name,
'res_id' : ids[0] if ids else False
}
att_ids.append(attachment_obj.create(cr, uid, data_attach))
values['attachment_ids'] = att_ids
else:
# restore defaults
values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context)
values.update(use_template=use_template, template_id=template_id)
return {'value': values}
def template_toggle(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
had_template = record.use_template
record.write({'use_template': not(had_template)})
if had_template:
# equivalent to choosing an empty template
onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template),
False, email_from=record.email_from,
email_to=record.email_to, context=context)
record.write(onchange_defaults['value'])
return _reopen(self, record.id, record.model, record.res_id)
def save_as_template(self, cr, uid, ids, context=None):
if context is None:
context = {}
email_template = self.pool.get('email.template')
model_pool = self.pool.get('ir.model')
for record in self.browse(cr, uid, ids, context=context):
model = record.model or context.get('active_model')
model_ids = model_pool.search(cr, uid, [('model', '=', model)])
model_id = model_ids and model_ids[0] or False
model_name = ''
if model_id:
model_name = model_pool.browse(cr, uid, model_id, context=context).name
template_name = "%s: %s" % (model_name, tools.ustr(record.subject))
values = {
'name': template_name,
'email_from': record.email_from or False,
'subject': record.subject or False,
'body_text': record.body_text or False,
'email_to': record.email_to or False,
'email_cc': record.email_cc or False,
'email_bcc': record.email_bcc or False,
'reply_to': record.reply_to or False,
'model_id': model_id or False,
'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])]
}
template_id = email_template.create(cr, uid, values, context=context)
record.write({'template_id': template_id,
'use_template': True})
# _reopen same wizard screen with new template preselected
return _reopen(self, record.id, model, record.res_id)
# override the basic implementation
def render_template(self, cr, uid, template, model, res_id, context=None):
return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
package org.osforce.connect.service.system;
import org.osforce.connect.entity.system.ProjectFeature;
public interface <API key> {
ProjectFeature getProjectFeature(Long featureId);
ProjectFeature getProjectFeature(String code, Long projectId);
void <API key>(ProjectFeature feature);
void <API key>(ProjectFeature feature);
void <API key>(Long featureId);
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.<API key>
{
public enum IfcBooleanOperator
{
[Description("The operation of constructing the regularized set theoretic union of the volumes " +
"defined by two solids.")]
UNION = 1,
[Description("The operation of constructing the regularised set theoretic intersection of the v" +
"olumes defined by two solids.")]
INTERSECTION = 2,
[Description("The regularised set theoretic difference between the volumes defined by two solid" +
"s.")]
DIFFERENCE = 3,
}
}
|
// of patent rights can be found in the PATENTS file in the same directory.
#include "rocksdb/sst_file_writer.h"
#include <vector>
#include "db/dbformat.h"
#include "rocksdb/table.h"
#include "table/<API key>.h"
#include "table/<API key>.h"
#include "util/file_reader_writer.h"
#include "util/sync_point.h"
namespace rocksdb {
const std::string <API key>::kVersion =
"rocksdb.external_sst_file.version";
const std::string <API key>::kGlobalSeqno =
"rocksdb.external_sst_file.global_seqno";
#ifndef ROCKSDB_LITE
const size_t kFadviseTrigger = 1024 * 1024; // 1MB
struct SstFileWriter::Rep {
Rep(const EnvOptions& _env_options, const Options& options,
const Comparator* _user_comparator, ColumnFamilyHandle* _cfh,
bool <API key>)
: env_options(_env_options),
ioptions(options),
mutable_cf_options(options),
internal_comparator(_user_comparator),
cfh(_cfh),
<API key>(<API key>),
last_fadvise_size(0) {}
std::unique_ptr<WritableFileWriter> file_writer;
std::unique_ptr<TableBuilder> builder;
EnvOptions env_options;
ImmutableCFOptions ioptions;
MutableCFOptions mutable_cf_options;
<API key> internal_comparator;
ExternalSstFileInfo file_info;
InternalKey ikey;
std::string column_family_name;
ColumnFamilyHandle* cfh;
// If true, We will give the OS a hint that this file pages is not needed
// everytime we write 1MB to the file
bool <API key>;
// the size of the file during the last time we called Fadvise to remove
// cached pages from page cache.
uint64_t last_fadvise_size;
};
SstFileWriter::SstFileWriter(const EnvOptions& env_options,
const Options& options,
const Comparator* user_comparator,
ColumnFamilyHandle* column_family,
bool <API key>)
: rep_(new Rep(env_options, options, user_comparator, column_family,
<API key>)) {
rep_->file_info.file_size = 0;
}
SstFileWriter::~SstFileWriter() {
if (rep_->builder) {
// User did not call Finish() or Finish() failed, we need to
// abandon the builder.
rep_->builder->Abandon();
}
delete rep_;
}
Status SstFileWriter::Open(const std::string& file_path) {
Rep* r = rep_;
Status s;
std::unique_ptr<WritableFile> sst_file;
s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options);
if (!s.ok()) {
return s;
}
CompressionType compression_type;
if (r->ioptions.<API key> != <API key>) {
compression_type = r->ioptions.<API key>;
} else if (!r->ioptions.<API key>.empty()) {
// Use the compression of the last level if we have per level compression
compression_type = *(r->ioptions.<API key>.rbegin());
} else {
compression_type = r->mutable_cf_options.compression;
}
std::vector<std::unique_ptr<<API key>>>
<API key>;
// SstFileWriter properties collector to add SstFileWriter version.
<API key>.emplace_back(
new <API key>(2 /* version */,
0 /* global_seqno*/));
// User collector factories
auto <API key> =
r->ioptions.<API key>;
for (size_t i = 0; i < <API key>.size(); i++) {
<API key>.emplace_back(
new <API key>(
<API key>[i]));
}
int unknown_level = -1;
uint32_t cf_id;
if (r->cfh != nullptr) {
// user explicitly specified that this file will be ingested into cfh,
// we can persist this information in the file.
cf_id = r->cfh->GetID();
r->column_family_name = r->cfh->GetName();
} else {
r->column_family_name = "";
cf_id = <API key>::Context::<API key>;
}
TableBuilderOptions <API key>(
r->ioptions, r->internal_comparator, &<API key>,
compression_type, r->ioptions.compression_opts,
nullptr /* compression_dict */, false /* skip_filters */,
r->column_family_name, unknown_level);
r->file_writer.reset(
new WritableFileWriter(std::move(sst_file), r->env_options));
// TODO(tec) : If table_factory is using compressed block cache, we will
// be adding the external sst file blocks into it, which is wasteful.
r->builder.reset(r->ioptions.table_factory->NewTableBuilder(
<API key>, cf_id, r->file_writer.get()));
r->file_info.file_path = file_path;
r->file_info.file_size = 0;
r->file_info.num_entries = 0;
r->file_info.sequence_number = 0;
r->file_info.version = 2;
return s;
}
Status SstFileWriter::Add(const Slice& user_key, const Slice& value) {
Rep* r = rep_;
if (!r->builder) {
return Status::InvalidArgument("File is not opened");
}
if (r->file_info.num_entries == 0) {
r->file_info.smallest_key.assign(user_key.data(), user_key.size());
} else {
if (r->internal_comparator.user_comparator()->Compare(
user_key, r->file_info.largest_key) <= 0) {
// Make sure that keys are added in order
return Status::InvalidArgument("Keys must be added in order");
}
}
// TODO(tec) : For external SST files we could omit the seqno and type.
r->ikey.Set(user_key, 0 /* Sequence Number */,
ValueType::kTypeValue /* Put */);
r->builder->Add(r->ikey.Encode(), value);
// update file info
r->file_info.num_entries++;
r->file_info.largest_key.assign(user_key.data(), user_key.size());
r->file_info.file_size = r->builder->FileSize();
InvalidatePageCache(false /* closing */);
return Status::OK();
}
Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) {
Rep* r = rep_;
if (!r->builder) {
return Status::InvalidArgument("File is not opened");
}
if (r->file_info.num_entries == 0) {
return Status::InvalidArgument("Cannot create sst file with no entries");
}
Status s = r->builder->Finish();
r->file_info.file_size = r->builder->FileSize();
if (s.ok()) {
s = r->file_writer->Sync(r->ioptions.use_fsync);
InvalidatePageCache(true /* closing */);
if (s.ok()) {
s = r->file_writer->Close();
}
}
if (!s.ok()) {
r->ioptions.env->DeleteFile(r->file_info.file_path);
}
if (file_info != nullptr) {
*file_info = r->file_info;
}
r->builder.reset();
return s;
}
void SstFileWriter::InvalidatePageCache(bool closing) {
Rep* r = rep_;
if (r-><API key> == false) {
// Fadvise disabled
return;
}
uint64_t <API key> =
r->builder->FileSize() - r->last_fadvise_size;
if (<API key> > kFadviseTrigger || closing) {
<API key>("SstFileWriter::InvalidatePageCache",
&(<API key>));
// Tell the OS that we dont need this file in page cache
r->file_writer->InvalidateCache(0, 0);
r->last_fadvise_size = r->builder->FileSize();
}
}
uint64_t SstFileWriter::FileSize() {
return rep_->file_info.file_size;
}
#endif // !ROCKSDB_LITE
} // namespace rocksdb
|
const LdapStrategy = require('./LdapStrategy');
const MoodleStrategy = require('./MoodleStrategy');
const IservStrategy = require('./IservStrategy');
const TSPStrategy = require('./TSPStrategy');
const ApiKeyStrategy = require('./ApiKeyStrategy');
module.exports = {
LdapStrategy,
MoodleStrategy,
IservStrategy,
TSPStrategy,
ApiKeyStrategy,
};
|
#include "AccessOverview.hpp"
#include "core/auth/Door.hpp"
#include "core/auth/Door_odb.h"
#include "core/auth/User_odb.h"
#include "tools/JSONUtils.hpp"
#include "tools/db/DBService.hpp"
using namespace Leosac;
using namespace Leosac::Module;
using namespace Leosac::Module::WebSockAPI;
AccessOverview::AccessOverview(RequestContext ctx)
: MethodHandler(ctx)
{
}
MethodHandlerUPtr AccessOverview::create(RequestContext ctx)
{
return std::make_unique<AccessOverview>(ctx);
}
json AccessOverview::process_impl(const json &)
{
json rep;
DBPtr db = ctx_.dbsrv->db();
odb::transaction t(db->begin());
// todo: This probably doesn't scale very well...
auto doors = db->query<Auth::Door>();
// Since we'll be looping over users multiple time, we cannot use
// an odb::result object.
auto users_odb = db->query<Auth::User>();
// So we'll have to convert this to a vector of User, instead of
// odb::result::iterator.
std::vector<Auth::UserPtr> users;
for (auto itr_odb(users_odb.begin()); itr_odb != users_odb.end(); ++itr_odb)
users.push_back(itr_odb.load());
for (const auto &door : doors)
{
std::set<Auth::UserId> unique_user_ids;
json door_info = {{"door_id", door.id()}, {"user_ids", json::array()}};
for (const auto &lazy_mapping : door.lazy_mapping())
{
auto mapping = lazy_mapping.load();
for (const auto &user_ptr : users)
{
// Check the std::set in case the user is already authorized to
// access the door.
if (unique_user_ids.count(user_ptr->id()))
{
continue;
}
if (mapping->has_user_indirect(user_ptr))
{
unique_user_ids.insert(user_ptr->id());
}
}
}
for (const auto &id : unique_user_ids)
door_info["user_ids"].push_back(id);
rep.push_back(door_info);
}
return rep;
}
std::vector<ActionActionParam>
AccessOverview::required_permission(const json &) const
{
std::vector<ActionActionParam> perm_;
SecurityContext::ActionParam ap;
perm_.push_back({SecurityContext::Action::ACCESS_OVERVIEW, ap});
return perm_;
}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedules', '<API key>'),
]
operations = [
migrations.CreateModel(
name='ScheduleExperience',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('experience_type', models.<API key>(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])),
('schedule', models.OneToOneField(related_name='experience', to='schedules.Schedule', on_delete=models.CASCADE)),
],
),
]
|
# -*- coding: utf-8 -*-
# Hendrix Costa <hendrix.costa@kmee.com.br>
from openerp.addons.financial.tests.<API key> import \
FinancialTestCase
class <API key>(FinancialTestCase):
def setUp(self):
self.financial_model = self.env['financial.move']
super(<API key>, self).setUp()
def <API key>(self):
"""Check if view is correctly called for python code"""
# test for len(financial.move) == 1
financial_move_id = self.financial_model.search([], limit=1)
action = financial_move_id.<API key>('2receive')
self.assertEqual(
action.get('display_name'),
'financial.move.debt.2receive.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
action = financial_move_id.<API key>('2pay')
self.assertEqual(
action.get('display_name'),
'financial.move.debt.2pay.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
# test for len(financial.move) > 1
financial_move_id = self.financial_model.search([], limit=2)
action = financial_move_id.<API key>('2pay')
self.assertEqual(action.get('domain')[0][2], financial_move_id.ids)
# test for len(financial.move) < 1
action = self.financial_model.<API key>('2pay')
self.assertEqual(action.get('type'), 'ir.actions.act_window_close')
|
# -*- coding: utf-8 -*-
# This file is part of Shuup.
from django import forms
from django.utils.translation import ugettext_lazy as _
from shuup.core.models import Category
from shuup.xtheme import TemplatedPlugin
from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField
class <API key>(GenericPluginForm):
"""
A configuration form for the CategoryLinksPlugin
"""
def populate(self):
"""
A custom populate method to display category choices
"""
for field in self.plugin.fields:
if isinstance(field, tuple):
name, value = field
value.initial = self.plugin.config.get(name, value.initial)
self.fields[name] = value
self.fields["categories"] = forms.<API key>(
queryset=Category.objects.all_visible(customer=None),
required=False,
initial=self.plugin.config.get("categories", None),
)
def clean(self):
"""
A custom clean method to save category configuration information in a serializable form
"""
cleaned_data = super(<API key>, self).clean()
categories = cleaned_data.get("categories", [])
cleaned_data["categories"] = [category.pk for category in categories if hasattr(category, "pk")]
return cleaned_data
class CategoryLinksPlugin(TemplatedPlugin):
"""
A plugin for displaying links to visible categories on the shop front
"""
identifier = "category_links"
name = _("Category Links")
template_name = "shuup/xtheme/plugins/category_links.jinja"
editor_form_class = <API key>
fields = [
("title", TranslatableField(label=_("Title"), required=False, initial="")),
("show_all_categories", forms.BooleanField(
label=_("Show all categories"),
required=False,
initial=True,
help_text=_("All categories are shown, even if not selected"),
)),
"categories",
]
def get_context_data(self, context):
"""
A custom get_context_data method to return only visible categories
for request customer.
"""
selected_categories = self.config.get("categories", [])
show_all_categories = self.config.get("show_all_categories", True)
request = context.get("request")
categories = Category.objects.all_visible(
customer=getattr(request, "customer"),
shop=getattr(request, "shop")
)
if not show_all_categories:
categories = categories.filter(id__in=selected_categories)
return {
"title": self.<API key>("title"),
"categories": categories,
}
|
package functionaltests.job;
import java.io.Serializable;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import org.junit.Test;
import functionaltests.utils.<API key>;
import static org.junit.Assert.*;
/**
* Test provokes scenario when task gets 'NOT_RESTARTED' status:
* - task is submitted and starts execution
* - user requests to restart task with some delay
* - before task was restarted job is killed
*
*/
public class <API key> extends <API key> {
public static class TestJavaTask extends JavaExecutable {
@Override
public Serializable execute(TaskResult... results) throws Throwable {
Thread.sleep(Long.MAX_VALUE);
return "OK";
}
}
@Test
public void test() throws Exception {
Scheduler scheduler = schedulerHelper.<API key>();
JobId jobId = scheduler.submit(createJob());
JobState jobState;
schedulerHelper.<API key>(jobId, "task1");
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus());
scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus());
scheduler.killJob(jobId);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus());
}
private TaskFlowJob createJob() throws Exception {
TaskFlowJob job = new TaskFlowJob();
job.setName(this.getClass().getSimpleName());
JavaTask javaTask = new JavaTask();
javaTask.<API key>(TestJavaTask.class.getName());
javaTask.setName("task1");
javaTask.<API key>(10);
job.addTask(javaTask);
return job;
}
}
|
body {
padding: 50px;
}
.room-actions {
margin-right: -14px;
}
.room-actions .btn {
margin: -17px 0 1px;
padding: 5px 4px;
font-size:10px;
}
|
/* @group Base */
.chosen-container {
position: relative;
display: inline-block;
vertical-align: middle;
/*font-size: 13px;*/
zoom: 1;
*display: inline;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.chosen-container * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.chosen-container .chosen-drop {
position: absolute;
top: 100%;
left: -9999px;
z-index: 1010;
width: 100%;
border: 1px solid #aaa;
border-top: 0;
background: #fff;
box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15);
}
.chosen-container.chosen-with-drop .chosen-drop {
left: 0;
}
.chosen-container a {
cursor: pointer;
}
/* @end */
/* @group Single Chosen */
.<API key> .chosen-single {
position: relative;
display: block;
overflow: hidden;
padding: 0 0 0 8px;
height: 25px;
border: 1px solid #aaa;
border-radius: 5px;
background-color: #fff;
background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4));
background: -<API key>(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background-clip: padding-box;
box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
color: #444;
text-decoration: none;
white-space: nowrap;
line-height: 24px;
}
.<API key> .chosen-default {
color: #999;
}
.<API key> .chosen-single span {
display: block;
overflow: hidden;
margin-right: 26px;
text-overflow: ellipsis;
white-space: nowrap;
}
.<API key> .<API key> span {
margin-right: 38px;
}
.<API key> .chosen-single abbr {
position: absolute;
top: 6px;
right: 26px;
display: block;
width: 12px;
height: 12px;
background: url('chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.<API key> .chosen-single abbr:hover {
background-position: -42px -10px;
}
.<API key>.chosen-disabled .chosen-single abbr:hover {
background-position: -42px -10px;
}
.<API key> .chosen-single div {
position: absolute;
top: 0;
right: 0;
display: block;
width: 18px;
height: 100%;
}
.<API key> .chosen-single div b {
display: block;
width: 100%;
height: 100%;
background: url('chosen-sprite.png') no-repeat 0px 2px;
}
.<API key> .chosen-search {
position: relative;
z-index: 1010;
margin: 0;
padding: 3px 4px;
white-space: nowrap;
}
.<API key> .chosen-search input[type="text"] {
margin: 1px 0;
padding: 4px 20px 4px 5px;
width: 100%;
height: auto;
outline: 0;
border: 1px solid #aaa;
background: white url('chosen-sprite.png') no-repeat 100% -20px;
background: url('chosen-sprite.png') no-repeat 100% -20px;
font-size: 1em;
font-family: sans-serif;
line-height: normal;
border-radius: 0;
}
.<API key> .chosen-drop {
margin-top: -1px;
border-radius: 0 0 4px 4px;
background-clip: padding-box;
}
.<API key>.<API key> .chosen-search {
position: absolute;
left: -9999px;
}
/* @end */
/* @group Results */
.chosen-container .chosen-results {
color: #444;
position: relative;
overflow-x: hidden;
overflow-y: auto;
margin: 0 4px 4px 0;
padding: 0 0 0 4px;
max-height: 240px;
-<API key>: touch;
}
.chosen-container .chosen-results li {
display: none;
margin: 0;
padding: 5px 6px;
list-style: none;
line-height: 15px;
word-wrap: break-word;
-<API key>: none;
}
.chosen-container .chosen-results li.active-result {
display: list-item;
cursor: pointer;
}
.chosen-container .chosen-results li.disabled-result {
display: list-item;
color: #ccc;
cursor: default;
}
.chosen-container .chosen-results li.highlighted {
background-color: #3875d7;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc));
background-image: -<API key>(#3875d7 20%, #2a62bc 90%);
background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: linear-gradient(#3875d7 20%, #2a62bc 90%);
color: #fff;
}
.chosen-container .chosen-results li.no-results {
color: #777;
display: list-item;
background: #f4f4f4;
}
.chosen-container .chosen-results li.group-result {
display: list-item;
font-weight: bold;
cursor: default;
}
.chosen-container .chosen-results li.group-option {
padding-left: 15px;
}
.chosen-container .chosen-results li em {
font-style: normal;
text-decoration: underline;
}
/* @end */
/* @group Multi Chosen */
.<API key> .chosen-choices {
position: relative;
overflow: hidden;
margin: 0;
padding: 0 5px;
width: 100%;
height: auto !important;
height: 1%;
border: 1px solid #aaa;
background-color: #fff;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
background-image: -<API key>(#eeeeee 1%, #ffffff 15%);
background-image: -moz-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: -o-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: linear-gradient(#eeeeee 1%, #ffffff 15%);
cursor: text;
}
.<API key> .chosen-choices li {
float: left;
list-style: none;
}
.<API key> .chosen-choices li.search-field {
margin: 0;
padding: 0;
white-space: nowrap;
}
.<API key> .chosen-choices li.search-field input[type="text"] {
margin: 1px 0;
padding: 0;
height: 25px;
outline: 0;
border: 0 !important;
background: transparent !important;
box-shadow: none;
color: #999;
font-size: 100%;
font-family: sans-serif;
line-height: normal;
border-radius: 0;
}
.<API key> .chosen-choices li.search-choice {
position: relative;
margin: 3px 5px 3px 0;
padding: 3px 20px 3px 5px;
border: 1px solid #aaa;
max-width: 100%;
border-radius: 3px;
background-color: #eeeeee;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -<API key>(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-size: 100% 19px;
background-repeat: repeat-x;
background-clip: padding-box;
box-shadow: 0 0 2px white inset, 0 1px 0 rgba(0, 0, 0, 0.05);
color: #333;
line-height: 13px;
cursor: default;
}
.<API key> .chosen-choices li.search-choice span {
word-wrap: break-word;
}
.<API key> .chosen-choices li.search-choice .search-choice-close {
position: absolute;
top: 4px;
right: 3px;
display: block;
width: 12px;
height: 12px;
background: url('chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.<API key> .chosen-choices li.search-choice .search-choice-close:hover {
background-position: -42px -10px;
}
.<API key> .chosen-choices li.<API key> {
padding-right: 5px;
border: 1px solid #ccc;
background-color: #e4e4e4;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -<API key>(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
color: #666;
}
.<API key> .chosen-choices li.search-choice-focus {
background: #d4d4d4;
}
.<API key> .chosen-choices li.search-choice-focus .search-choice-close {
background-position: -42px -10px;
}
.<API key> .chosen-results {
margin: 0;
padding: 0;
}
.<API key> .chosen-drop .result-selected {
display: list-item;
color: #ccc;
cursor: default;
}
/* @end */
/* @group Active */
.<API key> .chosen-single {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.<API key>.chosen-with-drop .chosen-single {
border: 1px solid #aaa;
-<API key>: 0;
<API key>: 0;
-<API key>: 0;
<API key>: 0;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #eeeeee), color-stop(80%, #ffffff));
background-image: -<API key>(#eeeeee 20%, #ffffff 80%);
background-image: -moz-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: -o-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: linear-gradient(#eeeeee 20%, #ffffff 80%);
box-shadow: 0 1px 0 #fff inset;
}
.<API key>.chosen-with-drop .chosen-single div {
border-left: none;
background: transparent;
}
.<API key>.chosen-with-drop .chosen-single div b {
background-position: -18px 2px;
}
.<API key> .chosen-choices {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.<API key> .chosen-choices li.search-field input[type="text"] {
color: #222 !important;
}
/* @end */
/* @group Disabled Support */
.chosen-disabled {
opacity: 0.5 !important;
cursor: default;
}
.chosen-disabled .chosen-single {
cursor: default;
}
.chosen-disabled .chosen-choices .search-choice .search-choice-close {
cursor: default;
}
/* @end */
/* @group Right to Left */
.chosen-rtl {
text-align: right;
}
.chosen-rtl .chosen-single {
overflow: visible;
padding: 0 8px 0 0;
}
.chosen-rtl .chosen-single span {
margin-right: 0;
margin-left: 26px;
direction: rtl;
}
.chosen-rtl .<API key> span {
margin-left: 38px;
}
.chosen-rtl .chosen-single div {
right: auto;
left: 3px;
}
.chosen-rtl .chosen-single abbr {
right: auto;
left: 26px;
}
.chosen-rtl .chosen-choices li {
float: right;
}
.chosen-rtl .chosen-choices li.search-field input[type="text"] {
direction: rtl;
}
.chosen-rtl .chosen-choices li.search-choice {
margin: 3px 5px 3px 0;
padding: 3px 5px 3px 19px;
}
.chosen-rtl .chosen-choices li.search-choice .search-choice-close {
right: auto;
left: 4px;
}
.chosen-rtl.<API key> .chosen-search,
.chosen-rtl .chosen-drop {
left: 9999px;
}
.chosen-rtl.<API key> .chosen-results {
margin: 0 0 4px 4px;
padding: 0 4px 0 0;
}
.chosen-rtl .chosen-results li.group-option {
padding-right: 15px;
padding-left: 0;
}
.chosen-rtl.<API key>.chosen-with-drop .chosen-single div {
border-right: none;
}
.chosen-rtl .chosen-search input[type="text"] {
padding: 4px 5px 4px 20px;
background: white url('chosen-sprite.png') no-repeat -30px -20px;
background: url('chosen-sprite.png') no-repeat -30px -20px;
direction: rtl;
}
.chosen-rtl.<API key> .chosen-single div b {
background-position: 6px 2px;
}
.chosen-rtl.<API key>.chosen-with-drop .chosen-single div b {
background-position: -12px 2px;
}
/* @end */
/* @group Retina compatibility */
@media only screen and (-<API key>: 2), only screen and (min-resolution: 144dpi) {
.chosen-rtl .chosen-search input[type="text"],
.<API key> .chosen-single abbr,
.<API key> .chosen-single div b,
.<API key> .chosen-search input[type="text"],
.<API key> .chosen-choices .search-choice .search-choice-close,
.chosen-container .<API key> span,
.chosen-container .<API key> span {
background-image: url('chosen-sprite@2x.png') !important;
background-size: 52px 37px !important;
background-repeat: no-repeat !important;
}
}
select.form-control + .chosen-container.<API key> .chosen-single {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
-webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
background-image:none;
}
select.form-control + .chosen-container.<API key> .chosen-single div {
top:4px;
color:#000;
}
select.form-control + .chosen-container .chosen-drop {
background-color: #FFF;
border: 1px solid #CCC;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
margin: 2px 0 0;
}
select.form-control + .chosen-container .chosen-search input[type=text] {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .chosen-container .chosen-results {
margin: 2px 0 0;
padding: 5px 0;
font-size: 14px;
list-style: none;
background-color: #fff;
margin-bottom: 5px;
}
select.form-control + .chosen-container .chosen-results li ,
select.form-control + .chosen-container .chosen-results li.active-result {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.428571429;
color: #333;
white-space: nowrap;
background-image:none;
}
select.form-control + .chosen-container .chosen-results li:hover,
select.form-control + .chosen-container .chosen-results li.active-result:hover,
select.form-control + .chosen-container .chosen-results li.highlighted
{
color: #FFF;
text-decoration: none;
background-color: #428BCA;
background-image:none;
}
select.form-control + .<API key> .chosen-choices {
display: block;
width: 100%;
min-height: 34px;
padding: 6px;
font-size: 14px;
line-height: 1.428571429;
color: #555;
vertical-align: middle;
background-color: #FFF;
border: 1px solid #CCC;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
background-image:none;
}
select.form-control + .<API key> .chosen-choices li.search-field input[type="text"] {
height:auto;
padding:5px 0;
}
select.form-control + .<API key> .chosen-choices li.search-choice {
background-image: none;
padding: 3px 24px 3px 5px;
margin: 0 6px 0 0;
font-size: 14px;
font-weight: normal;
line-height: 1.428571429;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 4px;
color: #333;
background-color: #FFF;
border-color: #CCC;
}
select.form-control + .<API key> .chosen-choices li.search-choice .search-choice-close {
top:8px;
right:6px;
}
select.form-control + .<API key>.<API key> .chosen-choices,
select.form-control + .chosen-container.<API key>.<API key> .chosen-single,
select.form-control + .chosen-container .chosen-search input[type=text]:focus{
border-color: #66AFE9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
}
/* @end */
|
package org.voltdb;
import java.io.File;
/**
* This file isn't long for this world. It's just something I've been using
* to debug multi-process rejoin stuff.
*
*/
public class VLog {
static File m_logfile = new File("vlog.txt");
public synchronized static void setPortNo(int portNo) {
m_logfile = new File(String.format("vlog-%d.txt", portNo));
}
public synchronized static void log(String str) {
// turn off this stupid thing for now
/*try {
FileWriter log = new FileWriter(m_logfile, true);
log.write(str + "\n");
log.flush();
log.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public static void log(String format, Object... args) {
log(String.format(format, args));
}
}
|
<!-- title: Earning Type -->
<div class="dev-header">
<a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;">
Version 6.7.7</a>
<a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/erpnext/hr/doctype/earning_type"
target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a>
</div>
<p><b>Table Name:</b> <code>tabEarning Type</code></p>
<h3>Fields</h3>
<table class="table table-bordered" style="table-layout: fixed;">
<thead>
<tr>
<th style="width: 5%">Sr</th>
<th style="width: 25%">Fieldname</th>
<th style="width: 20%">Type</th>
<th style="width: 25%">Label</th>
<th style="width: 25%">Options</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td class="danger" title="Mandatory"><code>earning_name</code></td>
<td >
Data</td>
<td >
Name
</td>
<td></td>
</tr>
<tr >
<td>2</td>
<td ><code>description</code></td>
<td >
Small Text</td>
<td >
Description
</td>
<td></td>
</tr>
</tbody>
</table>
<hr>
<h3>Controller</h3>
<h4>erpnext.hr.doctype.earning_type.earning_type</h4>
<h3 style="font-weight: normal;">Class <b>EarningType</b></h3>
<p style="padding-left: 30px;"><i>Inherits from frappe.model.document.Document</i></h4>
<div class="docs-attr-desc"><p></p>
</div>
<div style="padding-left: 30px;">
</div>
<hr>
<h4>Linked In:</h4>
<ul>
<li>
<a href="https://frappe.github.io/erpnext/current/models/hr/salary_slip_earning">Salary Slip Earning</a>
</li>
<li>
<a href="https://frappe.github.io/erpnext/current/models/hr/<API key>">Salary Structure Earning</a>
</li>
</ul>
<!-- autodoc -->
<!-- jinja -->
<!-- static -->
|
// Generated by CoffeeScript 1.10.0
var api, baseOVHKonnector, connector, name, slug;
baseOVHKonnector = require('../lib/base_ovh_konnector');
name = 'Kimsufi EU';
slug = 'kimsufi_eu';
api = {
endpoint: 'kimsufi-eu',
appKey: '',
appSecret: ''
};
connector = module.exports = baseOVHKonnector.createNew(api, name, slug);
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client.enums;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
public enum BeaconIndexType implements EnumAsString {
LOG("Log"),
STATE("State");
private String value;
BeaconIndexType(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public static BeaconIndexType get(String value) {
if(value == null)
{
return null;
}
// goes over BeaconIndexType defined values and compare the inner value with the given one:
for(BeaconIndexType item: values()) {
if(item.getValue().equals(value)) {
return item;
}
}
// in case the requested value was not found in the enum values, we return the first item as default.
return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null;
}
}
|
package NonameTV::Importer::TV2;
use strict;
use warnings;
=pod
Import data from Viasat's press-site. The data is downloaded in
tab-separated text-files.
Features:
Proper episode and season fields. The episode-field contains a
number that is relative to the start of the series, not to the
start of this season.
program_type
=cut
use DateTime;
use Date::Parse;
use Encode;
use NonameTV qw/MyGet expand_entities AddCategory norm/;
use NonameTV::DataStore::Helper;
use NonameTV::Log qw/progress error/;
use NonameTV::Importer::BaseWeekly;
use base 'NonameTV::Importer::BaseWeekly';
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = $class->SUPER::new( @_ );
bless ($self, $class);
defined( $self->{UrlRoot} ) or die "You must specify UrlRoot";
my $dsh = NonameTV::DataStore::Helper->new( $self->{datastore},
"Europe/Oslo" );
$self->{datastorehelper} = $dsh;
return $self;
}
sub ImportContent
{
my $self = shift;
my( $batch_id, $cref, $chd ) = @_;
#my $ds = $self->{datastore};
my $dsh = $self->{datastorehelper};
# Decode the string into perl's internal format.
# see perldoc Encode
# my $str = decode( "utf-8", $$cref );
my $str = decode( "iso-8859-1", $$cref );
my @rows = split("\n", $str );
if( scalar( @rows < 2 ) )
{
error( "$batch_id: No data found" );
return 0;
}
my $columns = [ split( "\t", $rows[0] ) ];
my $date = "";
my $olddate = "";
#print ( $batch_id );
for ( my $i = 1; $i < scalar @rows; $i++ )
{
my $inrow = $self->row_to_hash($batch_id, $rows[$i], $columns );
$date = $inrow->{'SENDEDATO'};
if ($date ne $olddate) {
my $ymd = parseDate(fq( $date ));
#print "\n>>>STARTING NEW DATE $ymd <<<\n";
$dsh->StartDate( $ymd );
}
$olddate = $date;
#$date = substr( $date, 0, 10 );
#$date =~ s/\./-/;
#if ( exists($inrow->{'Date'}) )
# $dsh->StartDate( $inrow->{'Date'} );
my $start = $inrow->{'SENDETID'};
#my ($date, $time) = split(/ /, $start);
#$date =~ s/\./-/;
#$time =~ s/\./:/;
#$date = turnDate($date);
#$start = "$date $time";
#print norm($start);
$start = parseStart(fq($start));
#my $start = $inrow->{'Start time'};
#my $start = $starttime;
my $title = norm( $inrow->{'NORSKTITTEL'} );
$title = fq($title);
my $description = fq( norm( $inrow->{'EPISODESYNOPSIS'} ));
if ($description eq "") {
$description = fq( norm( $inrow->{'GENERELL_SYNOPSIS'} ));
}
my $subtitle = fq( norm ($inrow->{'EPISODETITTEL'}));
if ($subtitle eq "") {
$subtitle = fq( norm( $inrow->{'OVERSKRIFT'}))
}
#$description = norm( $description );
#$description = fq( $description );
# Episode info in xmltv-format
#my $ep_nr = norm(fq($inrow->{'EPISODENUMMER'})) || 0;
#my $ep_se = norm(fq($inrow->{'SESONGNUMMER'})) || 0;
#my $episode = undef;
#if( ($ep_nr > 0) and ($ep_se > 0) )
# $episode = sprintf( "%d . %d .", $ep_se-1, $ep_nr-1 );
#elsif( $ep_nr > 0 )
# $episode = sprintf( ". %d .", $ep_nr-1 );
my $ce = {
channel_id => $chd->{id},
title => $title,
description => $description,
subtitle => $subtitle,
start_time => $start,
#episode => $episode,
};
if( defined( $inrow->{'PRODUKSJONSAARKOPI'} ) and
$inrow->{'PRODUKSJONSAARKOPI'} =~ /(\d\d\d\d)/ )
{
$ce->{production_date} = "$1-01-01";
}
my $cast = norm( $inrow->{'ROLLEBESKRIVELSE'} );
$cast = fq( $cast );
if( $cast =~ /\S/ )
{
# Remove all variants of m.fl.
$cast =~ s/\s*m[\. ]*fl\.*\b
# Remove trailing '.'
$cast =~ s/\.$
my @actors = split( /\s*,\s*/, $cast );
foreach (@actors)
{
# The character name is sometimes given in parentheses. Remove it.
# The Cast-entry is sometimes cutoff, which means that the
# character name might be missing a trailing ).
s/\s*\(.*$
}
$ce->{actors} = join( ", ", grep( /\S/, @actors ) );
}
my $director = norm( $inrow->{'REGI'} );
$director = fq( $director );
if( $director =~ /\S/ )
{
# Remove all variants of m.fl.
$director =~ s/\s*m[\. ]*fl\.*\b
# Remove trailing '.'
$director =~ s/\.$
my @directors = split( /\s*,\s*/, $director );
$ce->{directors} = join( ", ", grep( /\S/, @directors ) );
}
#$self->extract_extra_info( $ce );
$dsh->AddProgramme( $ce );
}
# Success
return 1;
}
sub FetchDataFromSite
{
my $self = shift;
my( $batch_id, $data ) = @_;
my( $year, $week ) = ( $batch_id =~ /(\d+)-(\d+)$/ );
my $url = sprintf( "%s_%01d_%s_%02d.xls",
$self->{UrlRoot}, $week, $data->{grabber_info},
$year);
my( $content, $code ) = MyGet( $url );
return( $content, $code );
}
sub row_to_hash
{
my $self = shift;
my( $batch_id, $row, $columns ) = @_;
$row =~ s/\t.$
# if $(row)
my @coldata = split( "\t", $row );
my %res;
if( scalar( @coldata ) > scalar( @{$columns} ) )
{
error( "$batch_id: Too many data columns " .
scalar( @coldata ) . " > " .
scalar( @{$columns} ) );
}
for( my $i=0; $i<scalar(@coldata) and $i<scalar(@{$columns}); $i++ )
{
$res{$columns->[$i]} = norm($coldata[$i])
if $coldata[$i] =~ /\S/;
}
return \%res;
}
sub parseStart
{
my ($string) = @_;
#my $string = @$in[0];
#print "PARSESTART: $string\n";
my $day = substr( $string, 0, 2 );
my $mnt = substr( $string, 3, 2 );
my $yr = substr( $string, 6, 4 );
my $hr = substr( $string, 11, 2 );
my $min = substr( $string, 14, 2 );
return ( "$hr:$min:00");
}
sub parseDate
{
my ($string) = @_;
my $day = substr( $string, 0, 2 );
my $mnt = substr( $string, 3, 2 );
my $year = substr( $string, 6, 4 );
return ("$year-$mnt-$day");
}
sub fq
{
# Remove quotes from strings
my ($string) = @_;
$string =~ s/^"
$string =~ s/"$
return $string;
}
1;
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
package ims.admin.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class <API key>
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.admin.vo.<API key> copy(ims.admin.vo.<API key> valueObjectDest, ims.admin.vo.<API key> valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Location(valueObjectSrc.getID_Location());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Name
valueObjectDest.setName(valueObjectSrc.getName());
// Type
valueObjectDest.setType(valueObjectSrc.getType());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// Address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// IsVirtual
valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #<API key>(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.<API key> <API key>(java.util.Set domainObjectSet)
{
return <API key>(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.<API key> <API key>(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.admin.vo.<API key> voList = new ims.admin.vo.<API key>();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next();
ims.admin.vo.<API key> vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.<API key> <API key>(java.util.List domainObjectList)
{
return <API key>(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.<API key> <API key>(DomainObjectMap map, java.util.List domainObjectList)
{
ims.admin.vo.<API key> voList = new ims.admin.vo.<API key>();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i);
ims.admin.vo.<API key> vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.resource.place.domain.objects.Location set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractLocationSet(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> voCollection)
{
return extractLocationSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractLocationSet(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.admin.vo.<API key> vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = <API key>.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.resource.place.domain.objects.Location list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractLocationList(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> voCollection)
{
return extractLocationList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractLocationList(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.admin.vo.<API key> vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = <API key>.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.<API key> create(ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.admin.vo.<API key> create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.admin.vo.<API key> valueObject = (ims.admin.vo.<API key>) map.getValueObject(domainObject, ims.admin.vo.<API key>.class);
if ( null == valueObject )
{
valueObject = new ims.admin.vo.<API key>(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.<API key> insert(ims.admin.vo.<API key> valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.<API key> insert(DomainObjectMap map, ims.admin.vo.<API key> valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Location(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Name
valueObject.setName(domainObject.getName());
// Type
ims.domain.lookups.LookupInstance instance2 = domainObject.getType();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LocationType voLookup2 = new ims.core.vo.lookups.LocationType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.LocationType parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.LocationType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setType(voLookup2);
}
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// Address
valueObject.setAddress(ims.core.vo.domain.<API key>.create(map, domainObject.getAddress()) );
// IsVirtual
valueObject.setIsVirtual( domainObject.isIsVirtual() );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> valueObject)
{
return extractLocation(domainFactory, valueObject, new HashMap());
}
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.<API key> domainFactory, ims.admin.vo.<API key> valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Location();
ims.core.resource.place.domain.objects.Location domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject);
}
// ims.admin.vo.<API key> ID_Location field is unknown
domainObject = new ims.core.resource.place.domain.objects.Location();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location());
if (domMap.get(key) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(key);
}
domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Location());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getName() != null && valueObject.getName().equals(""))
{
valueObject.setName(null);
}
domainObject.setName(valueObject.getName());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getType() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getType().getID());
}
domainObject.setType(value2);
domainObject.setIsActive(valueObject.getIsActive());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.generic.domain.objects.Address value4 = null;
if ( null != valueObject.getAddress() )
{
if (valueObject.getAddress().getBoId() == null)
{
if (domMap.get(valueObject.getAddress()) != null)
{
value4 = (ims.core.generic.domain.objects.Address)domMap.get(valueObject.getAddress());
}
}
else
{
value4 = (ims.core.generic.domain.objects.Address)domainFactory.getDomainObject(ims.core.generic.domain.objects.Address.class, valueObject.getAddress().getBoId());
}
}
domainObject.setAddress(value4);
domainObject.setIsVirtual(valueObject.getIsVirtual());
return domainObject;
}
}
|
require 'test_helper'
class <API key> < ActionController::TestCase
setup do
@politizacao = politizacaos(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:politizacaos)
end
test "should get new" do
get :new
assert_response :success
end
test "should create politizacao" do
assert_difference('Politizacao.count') do
post :create, politizacao: { body: @politizacao.body, title: @politizacao.title }
end
<API key> politizacao_path(assigns(:politizacao))
end
test "should show politizacao" do
get :show, id: @politizacao
assert_response :success
end
test "should get edit" do
get :edit, id: @politizacao
assert_response :success
end
test "should update politizacao" do
patch :update, id: @politizacao, politizacao: { body: @politizacao.body, title: @politizacao.title }
<API key> politizacao_path(assigns(:politizacao))
end
test "should destroy politizacao" do
assert_difference('Politizacao.count', -1) do
delete :destroy, id: @politizacao
end
<API key> politizacaos_path
end
end
|
delete from <API key> where key = '<API key>';
INSERT INTO <API key> (key, name, groupname, description, value, valueType, displayOrder)
values ('<API key>', 'Configure Default vaccine product', 'Dashboard', '','2412', 'TEXT', 1);
delete from <API key> where key = '<API key>';
INSERT INTO <API key> (key, name, groupname, description, value, valueType, displayOrder)
values ('<API key>', 'Configure Default vaccine period trend', 'Dashboard', '','4', 'NUMBER', 1);
|
(function() {
'use strict';
module.exports = {
/* Forces an update when the underlying Backbone model instance has
* changed. Users will have to implement getBackboneModels().
* Also requires that React is loaded with addons.
*/
__syncedModels: [],
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a reconcile.
this.getBackboneModels().forEach(this.injectModel, this);
},
<API key>: function() {
// Ensure that we clean up any dangling references when the component is
// destroyed.
this.__syncedModels.forEach(function(model) {
model.off(null, model.__updater, this);
}, this);
},
injectModel: function(model){
if(!~this.__syncedModels.indexOf(model)){
var updater = function() {
try {
this.forceUpdate();
} catch(e) {
// This means the component is already being updated somewhere
// else, so we just silently go on with our business.
// This is most likely due to some AJAX callback that already
// updated the model at the same time or slightly earlier.
}
}.bind(this, null);
model.__updater = updater;
model.on('add change remove', updater, this);
}
},
bindTo: function(model, key){
/* Allows for two-way databinding for Backbone models.
* Use by passing it as a 'valueLink' property, e.g.:
* valueLink={this.bindTo(model, attribute)} */
return {
value: model.get(key),
requestChange: function(value){
model.set(key, value);
}.bind(this)
};
}
};
})();
|
<?php use_helper('Text') ?>
<?php if (QubitTerm::REFERENCE_ID == $usageType): ?>
<?php if (isset($link)): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('<API key>'))))), $link) ?>
<?php else: ?>
<?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?>
<?php endif; ?>
<?php else: ?>
<?php if ($iconOnly): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('<API key>'))))), $link) ?>
<?php else: ?>
<div style="width: 100px; text-align: center"/>
<?php if (isset($link)): ?>
<?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('<API key>'))))), $link) ?>
<?php else: ?>
<?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?>
<?php endif; ?>
<?php echo wrap_text($digitalObject->name, 15) ?>
</div>
<?php endif; ?>
<?php endif; ?>
|
<?php
class BAInitiativeParser extends RISParser
{
private static $MAX_OFFSET = 5500;
private static $MAX_OFFSET_UPDATE = 200;
public function parse($antrag_id)
{
$antrag_id = IntVal($antrag_id);
if (SITE_CALL_MODE != "cron") echo "- Initiative $antrag_id\n";
if ($antrag_id == 0) {
RISTools::<API key>("Fehler BAInitiativeParser", "Initiative-ID 0\n" . print_r(debug_backtrace(), true));
return;
}
$html_details = RISTools::load_file(RIS_BA_BASE_URL . "<API key>.jsp?Id=$antrag_id");
$html_dokumente = RISTools::load_file(RIS_BA_BASE_URL . "<API key>.jsp?Id=$antrag_id");
//$html_ergebnisse = load_file(RIS_BA_BASE_URL . "/RII/RII/<API key>.jsp?risid=" . $antrag_id);
$daten = new Antrag();
$daten->id = $antrag_id;
$daten-><API key> = new CDbExpression('NOW()');
$daten->typ = Antrag::$TYP_BA_INITIATIVE;
$dokumente = [];
//$ergebnisse = array();
preg_match("/<h3.*>.* +(.*)<\/h3/siU", $html_details, $matches);
if (count($matches) == 2) $daten->antrags_nr = Antrag::cleanAntragNr($matches[1]);;
$dat_details = explode("<h3 class=\"introheadline\"><API key>", $html_details);
$dat_details = explode("<div class=\"formularcontainer\">", $dat_details[1]);
preg_match_all("/class=\"detail_row\">.*detail_label\">(.*)<\/d.*detail_div\">(.*)<\/div/siU", $dat_details[0], $matches);
$betreff_gefunden = false;
for ($i = 0; $i < count($matches[1]); $i++) switch (trim($matches[1][$i])) {
case "Betreff:":
$betreff_gefunden = true;
$daten->betreff = html_entity_decode($this->text_simple_clean($matches[2][$i]), ENT_COMPAT, "UTF-8");
break;
case "Status:":
$daten->status = $this->text_simple_clean($matches[2][$i]);
break;
case "Bearbeitung:":
$daten->bearbeitung = trim(strip_tags($matches[2][$i]));
break;
}
if (!$betreff_gefunden) {
RISTools::<API key>("Fehler BAInitiativeParser", "Kein Betreff\n" . $html_details);
throw new Exception("Betreff nicht gefunden");
}
$dat_details = explode("<div class=\"detailborder\">", $html_details);
$dat_details = explode("<!-- seitenfuss -->", $dat_details[1]);
preg_match_all("/<span class=\"itext\">(.*)<\/span.*detail_div_(left|right|left_long)\">(.*)<\/div/siU", $dat_details[0], $matches);
for ($i = 0; $i < count($matches[1]); $i++) if ($matches[3][$i] != " ") switch ($matches[1][$i]) {
case "Zuständiges Referat:":
$daten->referat = $matches[3][$i];
break;
case "Gestellt am:":
$daten->gestellt_am = $this->date_de2mysql($matches[3][$i]);
break;
case "Wahlperiode:":
$daten->wahlperiode = $matches[3][$i];
break;
case "Bearbeitungsfrist:":
$daten->bearbeitungsfrist = $this->date_de2mysql($matches[3][$i]);
break;
case "Registriert am:":
$daten->registriert_am = $this->date_de2mysql($matches[3][$i]);
break;
case "Bezirksausschuss:":
$daten->ba_nr = IntVal($matches[3][$i]);
break;
case "Typ:":
$daten->antrag_typ = strip_tags($matches[3][$i]);
break;
case "TO aufgenommen am:":
$daten-><API key> = $this->date_de2mysql($matches[3][$i]);
break;
}
if ($daten->wahlperiode == "") $daten->wahlperiode = "?";
preg_match_all("/<li><span class=\"iconcontainer\">.*title=\"([^\"]+)\"[^>]+href=\"(.*)\".*>(.*)<\/a>/siU", $html_dokumente, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
$dokumente[] = [
"url" => $matches[2][$i],
"name" => $matches[3][$i],
"name_title" => $matches[1][$i],
];
}
/*
$dat_ergebnisse = explode("<!-- tabellenkopf -->", $html_ergebnisse);
$dat_ergebnisse = explode("<!-- tabellenfuss -->", $dat_ergebnisse[1]);
preg_match_all("<tr>.*bghell tdborder\"><a.*\">(.*)<\/a>.*
*/
if ($daten->ba_nr == 0) {
echo "BA-Initiative $antrag_id: " . "Keine BA-Angabe";
$GLOBALS["RIS_PARSE_ERROR_LOG"][] = "Keine BA-Angabe (Initiative): $antrag_id";
return;
}
$aenderungen = "";
/** @var Antrag $alter_eintrag */
$alter_eintrag = Antrag::model()->findByPk($antrag_id);
$changed = true;
if ($alter_eintrag) {
$changed = false;
if ($alter_eintrag->betreff != $daten->betreff) $aenderungen .= "Betreff: " . $alter_eintrag->betreff . " => " . $daten->betreff . "\n";
if ($alter_eintrag->bearbeitungsfrist != $daten->bearbeitungsfrist) $aenderungen .= "Bearbeitungsfrist: " . $alter_eintrag->bearbeitungsfrist . " => " . $daten->bearbeitungsfrist . "\n";
if ($alter_eintrag->status != $daten->status) $aenderungen .= "Status: " . $alter_eintrag->status . " => " . $daten->status . "\n";
if ($alter_eintrag->fristverlaengerung != $daten->fristverlaengerung) $aenderungen .= "Fristverlängerung: " . $alter_eintrag->fristverlaengerung . " => " . $daten->fristverlaengerung . "\n";
if ($alter_eintrag-><API key> != $daten-><API key>) $aenderungen .= "In TO Aufgenommen: " . $alter_eintrag-><API key> . " => " . $daten-><API key> . "\n";
if ($aenderungen != "") $changed = true;
if ($alter_eintrag->wahlperiode == "") $alter_eintrag->wahlperiode = "?";
}
if ($changed) {
if ($aenderungen == "") $aenderungen = "Neu angelegt\n";
echo "BA-Initiative $antrag_id: Verändert: " . $aenderungen . "\n";
if ($alter_eintrag) {
$alter_eintrag->copyToHistory();
$alter_eintrag->setAttributes($daten->getAttributes());
if (!$alter_eintrag->save()) {
var_dump($alter_eintrag->getErrors());
die("Fehler");
}
$daten = $alter_eintrag;
} else {
if (!$daten->save()) {
var_dump($daten->getErrors());
die("Fehler");
}
}
$daten->resetPersonen();
}
foreach ($dokumente as $dok) {
$aenderungen .= Dokument::create_if_necessary(Dokument::$TYP_BA_INITIATIVE, $daten, $dok);
}
if ($aenderungen != "") {
$aend = new RISAenderung();
$aend->ris_id = $daten->id;
$aend->ba_nr = $daten->ba_nr;
$aend->typ = RISAenderung::$TYP_BA_INITIATIVE;
$aend->datum = new CDbExpression("NOW()");
$aend->aenderungen = $aenderungen;
$aend->save();
/** @var Antrag $antrag */
$antrag = Antrag::model()->findByPk($antrag_id);
$antrag-><API key> = new CDbExpression('NOW()'); // Auch bei neuen Dokumenten
$antrag->save();
$antrag->rebuildVorgaenge();
}
}
public function parseSeite($seite, $first)
{
if (SITE_CALL_MODE != "cron") echo "BA-Initiativen Seite $seite\n";
$text = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen.jsp?Trf=n&Start=$seite");
$txt = explode("<!-- tabellenkopf -->", $text);
$txt = explode("<div class=\"ergebnisfuss\">", $txt[1]);
preg_match_all("/<API key>\.jsp\?Id=([0-9]+)[\"'& ]/siU", $txt[0], $matches);
if ($first && count($matches[1]) > 0) RISTools::<API key>("BA-Initiativen VOLL", "Erste Seite voll: $seite");
for ($i = count($matches[1]) - 1; $i >= 0; $i--) try {
$this->parse($matches[1][$i]);
} catch (Exception $e) {
echo " EXCEPTION! " . $e . "\n";
}
return $matches[1];
}
public function parseAlle()
{
$anz = static::$MAX_OFFSET;
$first = true;
for ($i = $anz; $i >= 0; $i -= 10) {
if (SITE_CALL_MODE != "cron") echo ($anz - $i) . " / $anz\n";
$this->parseSeite($i, $first);
$first = false;
}
}
public function parseUpdate()
{
echo "Updates: BA-Initiativen\n";
$loaded_ids = [];
$anz = static::$MAX_OFFSET_UPDATE;
for ($i = $anz; $i >= 0; $i -= 10) {
$ids = $this->parseSeite($i, false);
$loaded_ids = array_merge($loaded_ids, array_map("IntVal", $ids));
}
}
public function parseQuickUpdate()
{
}
}
|
# This file is part of Canvas.
# Canvas is free software: you can redistribute it and/or modify it under
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# details.
require "spec_helper"
describe Messages::AssignmentSubmitted::TwitterPresenter do
let(:course) { course_model(name: "MATH-101") }
let(:assignment) { course.assignments.create!(name: "Introductions", due_at: 1.day.ago) }
let(:teacher) { course_with_teacher(course: course, active_all: true).user }
let(:student) do
course_with_user("StudentEnrollment", course: course, name: "Adam Jones", active_all: true).user
end
let(:submission) do
@submission = assignment.submit_homework(student)
assignment.grade_student(student, grade: 5, grader: teacher)
@submission.reload
end
before :once do
PostPolicy.enable_feature!
end
describe "Presenter instance" do
let(:message) { Message.new(context: submission, user: teacher) }
let(:presenter) { Messages::AssignmentSubmitted::TwitterPresenter.new(message) }
context "when the assignment is not anonymously graded" do
it "#body includes the name of the student" do
expect(presenter.body).to include("Adam Jones")
end
it "#link is a url for the submission" do
expect(presenter.link).to eql(
message.<API key>(course, assignment, submission.user_id)
)
end
end
context "when the assignment is anonymously graded" do
before(:each) do
assignment.update!(anonymous_grading: true)
end
context "when grades have not been posted" do
it "#body excludes the name of the student" do
expect(presenter.body).not_to include("Adam Jones")
end
it "#link is a url to SpeedGrader" do
expect(presenter.link).to eq(
message.<API key>(course, assignment_id: assignment.id, anonymous_id: submission.anonymous_id)
)
end
end
context "when grades have been posted" do
before(:each) do
submission
assignment.unmute!
end
it "#body includes the name of the student" do
expect(presenter.body).to include("Adam Jones")
end
it "#link is a url for the submission" do
expect(presenter.link).to eql(
message.<API key>(course, assignment, submission.user_id)
)
end
end
end
end
describe "generated message" do
let(:message) { generate_message(:<API key>, :twitter, submission, {}) }
let(:presenter) do
msg = Message.new(context: submission, user: teacher)
Messages::AssignmentSubmitted::TwitterPresenter.new(msg)
end
context "when the assignment is not anonymously graded" do
it "#body includes the name of the student" do
expect(message.body).to include("Adam Jones")
end
it "#url is a url for the submission" do
expect(message.url).to include(presenter.link)
end
end
context "when the assignment is anonymously graded" do
before(:each) do
assignment.update!(anonymous_grading: true)
end
context "when grades have not been posted" do
it "#body excludes the name of the student" do
expect(message.body).not_to include("Adam Jones")
end
it "#url is a url to SpeedGrader" do
expect(message.url).to include(presenter.link)
end
end
context "when grades have been posted" do
before(:each) do
submission
assignment.unmute!
end
it "#body includes the name of the student" do
expect(message.body).to include("Adam Jones")
end
it "#url is a url for the submission" do
expect(message.url).to include(presenter.link)
end
end
end
end
end
|
# This file is part of Canvas.
# Canvas is free software: you can redistribute it and/or modify it under
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# details.
require 'spec_helper'
require_dependency "users/<API key>"
module Users
describe <API key> do
describe "#<API key>?" do
it "is true when forced" do
policy = <API key>.new(false, {<API key>: '1'})
expect(policy.<API key>?).to be(true)
end
it "is opposite the management ability provide" do
policy = <API key>.new(false, {})
expect(policy.<API key>?).to be(true)
policy = <API key>.new(true, {})
expect(policy.<API key>?).to be(false)
end
end
describe "#dispatch!" do
let(:user){ double() }
let(:pseudonym) { double() }
let(:channel){ double() }
context "for self_registration" do
let(:policy){ <API key>.new(true, {<API key>: true}) }
before{ allow(channel).to receive_messages(<API key>?: false) }
it "sends confirmation notification" do
allow(user).to receive_messages(pre_registered?: true)
expect(pseudonym).to receive(:send_confirmation!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
it "sends the registration notification if the user is pending or registered" do
allow(user).to receive_messages(pre_registered?: false, registered?: false)
expect(pseudonym).to receive(:<API key>!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
end
context "when the user isn't yet registered" do
before do
allow(user).to receive_messages(registered?: false)
allow(channel).to receive_messages(<API key>?: false)
end
it "sends the registration notification if should notify" do
policy = <API key>.new(true, {send_confirmation: '1'})
expect(pseudonym).to receive(:<API key>!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(true)
end
it "doesnt send the registration notification if shouldnt notify" do
policy = <API key>.new(true, {send_confirmation: '0'})
expect(pseudonym).to receive(:<API key>!).never
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
end
context "when the user is registered" do
before{ allow(user).to receive_messages(registered?: true) }
let(:policy){ <API key>.new(true, {}) }
it "sends the merge notification if there are merge candidates" do
allow(channel).to receive_messages(<API key>?: true)
expect(channel).to receive(:<API key>!)
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
it "does nothing without merge candidates" do
allow(channel).to receive_messages(<API key>?: false)
expect(channel).to receive(:<API key>!).never
result = policy.dispatch!(user, pseudonym, channel)
expect(result).to be(false)
end
end
end
end
end
|
<?
session_start();
// Modificado Junio 2009
foreach ($_GET as $key => $valor) ${$key} = $valor;
foreach ($_POST as $key => $valor) ${$key} = $valor;
define('ADODB_ASSOC_CASE', 1);
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
$codusuario = $_SESSION["codusuario"];
$tip3Nombre=$_SESSION["tip3Nombre"];
$tip3desc = $_SESSION["tip3desc"];
$tip3img =$_SESSION["tip3img"];
$verrad = "";
$ruta_raiz = "..";
/* Idea Original de la SUPERINTENDENCIA DE SERVICIOS PUBLICOS DOMICILIARIOS */
/* COLOMBIA TEL. (57) (1) 6913005 orfeogpl@gmail.com */
/* Este programa es software libre. usted puede redistribuirlo y/o modificarlo */
/* bajo los terminos de la licencia GNU General Public publicada por */
/* la "Free Software Foundation"; Licencia version 2. */
/* SSPS "Superintendencia de Servicios Publicos Domiciliarios" */
/* Jairo Hernan Losada jlosada@gmail.com Desarrollador */
/* C.R.A. "COMISION DE REGULACION DE AGUAS Y SANEAMIENTO AMBIENTAL" */
/* Liliana Gomez lgomezv@gmail.com Desarrolladora */
/* Lucia Ojeda lojedaster@gmail.com Desarrolladora */
/* D.N.P. "Departamento Nacional de Planeacin" */
/* Hollman Ladino hladino@gmail.com Desarrollador */
/* Colocar desde esta lInea las Modificaciones Realizadas Luego de la Version 3.5 */
/* Nombre Desarrollador Correo Fecha Modificacion */
$ruta_raiz = "..";
$verrad = "";
include_once "$ruta_raiz/include/db/ConnectionHandler.php";
$db = new ConnectionHandler($ruta_raiz);
if(!$tipo_archivo) $tipo_archivo = 0; //Para la consulta a archivados
// prestamo begin
// Inicializa, oculta o presenta los parmetros de bsqueda dependiendo de la opcin del men de prstamos seleccionada
// prestamo CustomIncludes begin
include ("common.php");
// Save Page and File Name available into variables
$sFileName = "prestamo.php";
// Variables de control
$opcionMenu=strip($_POST["opcionMenu"]); //opcin seleccionada del men
$pageAnt=strip($_POST["sFileName"]);
$ver=$_POST["s_sql"]; //consulta
// HTML Page layout
?>
<html>
<head>
<title>Prestamos ORFEO</title>
<link rel="stylesheet" href="<?=$ruta_raiz?>/estilos/orfeo.css" type="text/css">
<!--Necesario para hacer visible el calendario
<script src="<?=$ruta_raiz?>/js/popcalendar.js"></script>
<div id="spiffycalendar" class="text"></div>
<link rel="stylesheet" type="text/css" href="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.css">
</head>
<body class="PageBODY">
<div align="center">
<table>
<tr>
<td valign="top"><?php Search_Show(); ?></td>
</tr>
</table>
<table>
<tr>
<td valign="top"><?php if($ver=="") Pedidos_Show(); ?></td>
</tr>
</table>
</div>
</body>
</html>
<?php
// prestamo end
// Search_Show begin
function Search_Show(){
// De sesin
global $db;
global $ruta_raiz;
// Control de visualizacin
$sFileName = $_POST["sFileName"];
$opcionMenu = $_POST["opcionMenu"];
// Valores
$fechaFinal = $_POST["fechaFinal"];
$fechaInicial = $_POST["fechaInicial"];
foreach ($_GET as $key => $valor) ${$key} = $valor;
foreach ($_POST as $key => $valor) ${$key} = $valor;
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
// Inicializacin de la fecha a partir de la cual se cancelan las solicitudes
if ($fechaInicial=="") {
$hastaXDias=strtotime("-30 day");
$fechaInicial=date("Y-m-d",$hastaXDias);
}
if ($fechaFinal=="") {
if ($opcionMenu==3) {
$query="select PARAM_VALOR,PARAM_NOMB from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_DIAS_CANC'";
$rs = $db->conn->query($query);
if(!$rs->EOF) {
$x = $rs->fields("PARAM_VALOR"); // das por defecto
$haceXDias = strtotime("-".$x." day");
$fechaFinal=date("Y-m-d",$haceXDias);
}
if ($pageAnt!=$sFileName) { // inicializacin del tiempo
$v_hora_limite=date("h");
$v_minuto_limite=date("i");
$v_meridiano=date("A");
}
}
else{ $fechaFinal=date("Y-m-d"); }
}
// Set variables with search parameters
$flds_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]);
$flds_RADI_NUME_RADI=strip($_POST["s_RADI_NUME_RADI"]);
$flds_USUA_LOGIN =strip($_POST["s_USUA_LOGIN"]);
if ($opcionMenu==4) { $flds_USUA_LOGIN=$krd; } // Inicializa el usuario para el caso en que el ingresa por la opcin de SOLICITADOS
$flds_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]);
$flds_USUA_NOMB =strip($_POST["s_USUA_NOMB"]);
$<API key>=strip($_POST["<API key>"]);
if ($v_hora_limite=="") { $v_hora_limite =strip($_POST["s_hora_limite"]); }
if ($v_minuto_limite==""){ $v_minuto_limite=strip($_POST["s_minuto_limite"]); }
if ($v_meridiano=="") { $v_meridiano =strip($_POST["s_meridiano"]); }
// Inicializa el titulo y la visibilidad de los criterios de bsqueda
include_once "inicializarForm.inc";
// Form display
?>
<form method="post" action="prestamo.php" name="busqueda">
<!-- de sesin !-->
<input type="hidden" value=" " name="radicado">
<input type="hidden" value="" name="s_sql">
<!-- control de visualizacin !-->
<input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>">
<input type="hidden" name="sFileName" value="">
<!-- orden de presentacin del resultado !-->
<input type="hidden" name="FormPedidos_Sorting" value="1">
<input type="hidden" name="FormPedidos_Sorted" value="0">
<input type="hidden" name="s_Direction" value=" DESC ">
<!-- control de paginacin !-->
<input type="hidden" name="FormPedidos_Page" value="1">
<input type="hidden" name="FormStarPage" value="1">
<input type="hidden" name="FormSiguiente" value="0">
<script>
//Inicializa el formulario
function limpiar() {
document.busqueda.action="menu_prestamo.php";
document.busqueda.submit();
}
//Presenta los usuarios segun la dependencia seleccionada
var codUsuaSel="<?=$flds_USUA_NOMB?>";
</script>
<!--Calendario
<script language="JavaScript" src="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.js"></script>
<script language="javascript">
setRutaRaiz ('<?=$ruta_raiz?>');
</script>
<table border=0 cellpadding=0 cellspacing=2 class='borde_tab'>
<tr>
<td class="titulos4" colspan="2"><a name="Search"><?=$sFormTitle[$opcionMenu]; ?> </a></td>
</tr>
<tr id="b0" style="display:<?= $tipoBusqueda[$opcionMenu][0]; ?>">
<td class="titulos3"><p align="left">Radicado</p></td>
<td class="listado5"><input type="text" name="s_RADI_NUME_RADI" maxlength="15" value="<?= $flds_RADI_NUME_RADI; ?>" size="25" class="tex_area"></td>
</tr>
<tr id="b1" style="display:<?= $tipoBusqueda[$opcionMenu][1]; ?>">
<td class="titulos3"><p align="left">Login de Usuario</p></td>
<td class="listado5"><input type="text" name="s_USUA_LOGIN" maxlength="15" value="<?= $flds_USUA_LOGIN; ?>" size="25" class="tex_area"></td>
</tr>
<tr id="b2" style="display:<?= $tipoBusqueda[$opcionMenu][2]; ?>">
<td class="titulos3"><p align="left">Dependencia</p></td>
<td class="listado5"><select name="s_DEPE_NOMB" class="select" onChange=" document.busqueda.s_sql.value='no'; document.busqueda.submit(); ">
<option value="">- TODAS LAS DEPENDENCIAS -</option>
<?
$lookup_s = db_fill_array("select DEPE_CODI,DEPE_NOMB from DEPENDENCIA order by 2");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_DEPE_NOMB) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
} ?>
</select></td>
</tr>
<tr id="b3" style="display:<?= $tipoBusqueda[$opcionMenu][3]; ?>">
<td class="titulos3"><p align="left">Usuario</p></td>
<td class="listado5"><select name="s_USUA_NOMB" class=select>
<option value="">- TODOS LOS USUARIOS -</option>
<? $validUsuaActiv="";
// Modificado Infomtrika 14-Julio-2009
// Compatibilidad con PostgreSQL 8.3
// Cambi USUA_ESTA=1 por USUA_ESTA='1' para listar los usuarios activos.
if ($opcionMenu==1) { $validUsuaActiv=" USUA_ESTA='1' "; }ELSE { $validUsuaActiv=" USUA_LOGIN IS NOT NULL "; } //Verifica que el usuario se encuentre activo para hacer el prEstamo
if ($flds_DEPE_NOMB != "") $tmp = " AND DEPE_CODI= ".$flds_DEPE_NOMB; else $tmp = "";
$lookup_s = db_fill_array("select USUA_LOGIN,USUA_NOMB from USUARIO where ".$validUsuaActiv.$tmp);
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_USUA_NOMB) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
} ?>
</select></td>
</tr>
<tr id="b4" style="display:<?= $tipoBusqueda[$opcionMenu][4]; ?>">
<td class="titulos3"><p align="left">Requerimiento</p></td>
<td class="listado5"><select name="<API key>" class=select>
<option value="">- TODOS LOS TIPOS -</option>
<? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='<API key>' order by PARAM_VALOR desc");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $<API key>)
$option="<option SELECTED value=\"$key\">".strtoupper($value)."</option>";
else
$option="<option value=\"$key\">".strtoupper($value)."</option>";
echo $option;
}
} ?>
</select></td>
</tr>
<tr id="b5" style="display:<?= $tipoBusqueda[$opcionMenu][5]; ?>">
<td class="titulos3"><p align="left">Estado</p></td>
<td class="listado5"><select name="s_PRES_ESTADO" class=select>
<option value="">- TODOS LOS ESTADOS -</option>
<? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_ESTADO' order by PARAM_VALOR");
if(is_array($lookup_s)) {
reset($lookup_s);
while(list($key,$value)=each($lookup_s)) {
if($key == $flds_PRES_ESTADO) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"$key\">".strtoupper($value)."</option>";
}
}
if($flds_PRES_ESTADO == -1) { $option="SELECTED"; }
else { $option=""; }
echo "<option $option value=\"-1\">VENCIDO</option>"; ?>
</select></td>
</tr>
<tr id="b6" style="display:<?= $tipoBusqueda[$opcionMenu][6]; ?>">
<td class="titulos3"><p align="left">Fecha inicial<br> (aaaa-mm-dd)</p></td>
<td class="listado5"><script language="javascript">
var dateAvailable1 = new <API key>("dateAvailable1", "busqueda","fechaInicial","btnDate1","<?=$fechaInicial?>",<API key>);
dateAvailable1.writeControl();
dateAvailable1.dateFormat="yyyy-MM-dd";
</script></td>
</tr>
<tr id="b7" style="display:<?= $tipoBusqueda[$opcionMenu][7]; ?>">
<td class="titulos3"><p align="left">Fecha final<br> (aaaa-mm-dd)</p></td>
<td class="listado5"><script language="javascript">
var dateAvailable2 = new <API key>("dateAvailable2", "busqueda","fechaFinal","btnDate2","<?=$fechaFinal?>",<API key>);
dateAvailable2.writeControl();
dateAvailable2.dateFormat="yyyy-MM-dd";
</script>
</td>
</tr>
<tr id="b8" style="display:<?= $tipoBusqueda[$opcionMenu][8]; ?>">
<td class="titulos3"><p align="left">Hora límite<br> (hh:mm m)</p></td>
<td class="listado5"><select name="s_hora_limite" class=select>
<? for ($i=1; $i<=12; $i++) {
if ($i<=9) { $h="0".$i; }
else { $h="".$i; }
$seleccion="";
if ($h==$v_hora_limite) { $seleccion="SELECTED"; } ?>
<option <?= $seleccion; ?> value="<?= $h;?>"><?= $h;?></option>
<? } ?>
</select> :
<select name="s_minuto_limite" class=select>
<? for ($i=0; $i<=59; $i++) {
if ($i<=9) { $h="0".$i; }
else { $h="".$i; }
$seleccion="";
if ($h==$v_minuto_limite) { $seleccion="SELECTED"; } ?>
<option <?= $seleccion; ?> value="<?= $h;?>"> <?= $h;?></option>
<? } ?>
</select> :
<select name="s_meridiano" class=select>
<? if ($v_meridiano=="AM") {?>
<option value="AM" selected>am</option>
<option value="PM">pm</option>
<? }
else {?>
<option value="AM">am</option>
<option value="PM" selected>pm</option>
<? } ?>
</select>
</tr>
<tr>
<td class="titulos3" colspan="2">
<? if ($opcionMenu==0 || $opcionMenu==4) {?>
<input type="reset" class='botones' value="Limpiar" onClick="javascript: limpiar();">
<input type="submit" class='botones' value="Generar">
<? }
else {?>
<input type="submit" class='botones' value="Buscar">
<? }?>
</td>
</tr>
</table>
</form>
<?
} //end function
// Search_Show end
// Pedidos_Show begin
function Pedidos_Show(){
// De sesin
global $db;
global $ruta_raiz;
// Control de visualizacin
global $sFileName;
global $opcionMenu;
global $pageAnt; // Pagina de la cual viene
// Valores
$sFileName = $_POST["sFileName"];
$opcionMenu = $_POST["opcionMenu"];
// Valores
$fechaFinal = $_POST["fechaFinal"];
$fechaInicial = $_POST["fechaInicial"];
$krd = $_SESSION["krd"];
$dependencia = $_SESSION["dependencia"];
$usua_doc = $_SESSION["usua_doc"];
// Set variables with search parameters
$ps_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]);
$ps_RADI_NUME_RADI=strip(trim($_POST["s_RADI_NUME_RADI"]));
// Modificado Infomtrika 14-Julio-2009
// A la variable $ps_USUA_LOGIN se le asigna el valor de $_POST["s_USUA_LOGIN"] para
// realizar la consulta, por Login de Usuario, de los radicados solicitados para prstamo.
//$ps_USUA_LOGIN =$krd;
$ps_USUA_LOGIN = strip($_POST['s_USUA_LOGIN']); ;
$ps_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]);
$ps_USUA_NOMB =strip($_POST["s_USUA_NOMB"]);
$ps_hora_limite =strip($_POST["s_hora_limite"]);
$ps_minuto_limite =strip($_POST["s_minuto_limite"]);
$ps_meridiano =strip($_POST["s_meridiano"]);
$<API key>=strip($_POST["<API key>"]);
if (strlen($pageAnt)==0){
// Build SQL
include_once $ruta_raiz."/include/query/prestamo/builtSQL1.inc";
include_once $ruta_raiz."/include/query/prestamo/builtSQL2.inc";
include_once $ruta_raiz."/include/query/prestamo/builtSQL3.inc";
// Build ORDER statement
$iSort=strip(get_param("FormPedidos_Sorting"));
if(!$iSort) $iSort =20;
$iSorted=strip(get_param("FormPedidos_Sorted"));
$sDirection=strip(get_param("s_Direction"));
if ($iSorted!=$iSort){ $sDirection=" DESC ";}
else {
if(strcasecmp($sDirection," DESC ")==0){ $sDirection=" ASC "; }
else { $sDirection=" DESC "; }
}
$sOrder=" order by ".$iSort.$sDirection.",PRESTAMO_ID";
// Inicializa el titulo y la visibilidad de los resultados
include_once "inicializarRTA.inc";
// Execute SQL statement
$db->conn->SetFetchMode(ADODB_FETCH_ASSOC);
$rs=$db->query($sSQL.$sOrder);
$db->conn->SetFetchMode(ADODB_FETCH_NUM);
// Process empty recordset
if(!$rs || $rs->EOF) { ?>
<p align="center" class="titulosError2">NO HAY REGISTROS SELECCIONADOS</p>
<? return;
}
// Build parameters for order
$form_params_search = "s_RADI_NUME_RADI=".tourl($ps_RADI_NUME_RADI)."&s_USUA_LOGIN=".tourl($ps_USUA_LOGIN).
"&s_DEPE_NOMB=".tourl($ps_DEPE_NOMB)."&s_USUA_NOMB=".tourl($ps_USUA_NOMB)."&<API key>=".
tourl($<API key>)."&s_PRES_ESTADO=".tourl($ps_PRES_ESTADO)."&fechaInicial=".
tourl($fechaInicial)."&fechaFinal=".tourl($fechaFinal)."&s_hora_limite=".tourl($ps_hora_limite).
"&s_minuto_limite=".tourl($ps_minuto_limite)."&s_meridiano=".tourl($ps_meridiano);
$form_params_page = "&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0";
$form_params=$form_params_search.$form_params_page."&opcionMenu=".tourl($opcionMenu)."&krd=".tourl($krd).
"&FormPedidos_Sorted=".tourl($iSort)."&s_Direction=".tourl($sDirection)."&FormPedidos_Sorting=";
// HTML column prestamo headers
?>
<form method="post" action="prestamo.php" name="rta">
<input type="hidden" value='<?=$krd?>' name="krd">
<input type="hidden" value=" " name="radicado">
<input type="hidden" value="" name="prestado">
<input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>">
<!-- orden de presentacin del resultado en el formulario de envio !-->
<input type="hidden" name="FormPedidos_Sorting" value="<?=$iSort?>">
<input type="hidden" name="FormPedidos_Sorted" value="<?=$iSorted?>">
<input type="hidden" name="s_Direction" value="<?=$sDirection?>">
<table border=0 cellpadding=0 cellspacing=2 class='borde_tab' width="100%">
<tr>
<td class="titulos4" colspan="<?=$numCol?>"><a name="Search"><?= $tituloRespuesta[$opcionMenu]?></a></td>
</tr>
<?PHP // Titulos de las columnas
include_once "inicializarTabla.inc";
// Process page scroller
// Initialize records per page
$iRecordsPerPage = 15;
// Inicializa el valor de la pagina actual
$iPage=intval(get_param("FormPedidos_Page"));
// Inicializa los registros a presentar segn la pgina actual
$iCounter = 0;
$ant="";
if($iPage > 1) {
do{
$new=$rs->fields["PRESTAMO_ID"];
if ($new!=$ant) {
$iCounter++;
$ant=$new;
}
$rs->MoveNext();
}while ($iCounter < ($iPage - 1) * $iRecordsPerPage && !$rs->EOF);
}
$iCounterIni=$iCounter;
// Display grid based on recordset
$y=0; // Cantidad de registros presentados
include_once "getRtaSQLAntIn.inc"; //Une en un solo campo los expedientes
while($rs && !$rs->EOF && $y<$iRecordsPerPage) {
// Inicializa las variables con los resultados
include "getRtaSQL.inc";
if ($antfldPRESTAMO_ID!=$fldPRESTAMO_ID) { //Une en un solo campo los expedientes
if ($y!=0) { include "cuerpoTabla.inc"; } // Fila de la tabla con los resultados
include "getRtaSQLAnt.inc";
$y++;
}
else {
if ($antfldEXP!=""){
$antfldEXP.="<br>";
$antfldARCH.="<br>";
}
$antfldEXP.=$fldEXP;
if ($fldARCH=='SI') {
$encabARCH = session_name()."=".session_id()."&buscar_exp=".tourl($fldEXP)."&krd=$krd&tipo_archivo=&nomcarpeta=";
$antfldARCH.="<a href='".$ruta_raiz."/expediente/datos_expediente.php?".$encabARCH."&num_expediente=".tourl($fldEXP)."&nurad=".tourl($antfldRADICADO)."' class='vinculos'>".$fldARCH."</a>";
}
else { $antfldARCH.=$fldARCH; }
}
$rs->MoveNext();
}
if ($y!=0) {
include "cuerpoTabla.inc"; // Fila de la tabla con lso resultados
$y++;
}
$cantRegPorPagina=$y;
$iCounter=$iCounter+$y;
?>
<script>
// Inicializa el arreglo con los radicados a procesar
var cantRegPorPagina=<?=$cantRegPorPagina-1?>;
// Marca todas las casillas si la del titulo es marcada
function seleccionarRta() {
valor=document.rta.rta_.checked;
<? for ($j=0; $j<$cantRegPorPagina; $j++) { ?>
document.rta.rta_<?=$j?>.checked=valor;
<? } ?>
}
// Valida y envia el formulario
function enviar() {
var cant=0;
for (i=0; i<cantRegPorPagina; i++) {
if (eval('document.rta.rta_'+i+'.checked')==true){
cant=1;
break;
}
}
if (cant==0) { alert("Debe seleccionar al menos un radicado"); }
else {
document.rta.prestado.value=cantRegPorPagina;
document.rta.action="formEnvio.php";
document.rta.submit();
}
}
// Regresa al men de prstamos
function regresar() {
document.rta.opcionMenu.value="";
document.rta.action="menu_prestamo.php";
document.rta.submit();
}
</script>
<?
// Build parameters for page
if (strcasecmp($sDirection," DESC ")==0){ $sDirectionPages=" ASC "; }
else { $sDirectionPages=" DESC "; }
$form_params_page = $form_params_search."&opcionMenu=".tourl($opcionMenu)."&FormPedidos_Sorted=".tourl($iSort).
"&s_Direction=".tourl($sDirectionPages)."&krd=".tourl($krd)."&FormPedidos_Sorting=".tourl($iSort);
// Nmero total de registros
$ant=$antfldPRESTAMO_ID;
while($rs && !$rs->EOF) {
$new=$rs->fields["PRESTAMO_ID"]; //para el manejo de expedientes
if ($new!=$ant) {
$ant=$new;
$iCounter++;
}
$rs->MoveNext();
}
$iCounter
// Inicializa pginas visualizables
$iNumberOfPages=10;
// Inicializa cantidad de pginas
$iHasPages=intval($iCounter/$iRecordsPerPage);
if ($iCounter%$iRecordsPerPage!=0) { $iHasPages++; }
// Determina la pgina inicial del intervalo
$iStartPages=1;
$FormSiguiente=get_param("FormSiguiente"); //Indica si (1) el nmero de pginas es mayor al visualizable
if($FormSiguiente==0) { $iStartPages=get_param("FormStarPage"); }
elseif($FormSiguiente==-1){ $iStartPages=$iPage; }
else {
if($iPage>$iNumberOfPages) { $iStartPages=$iPage-$iNumberOfPages+1; }
}
// Genera las pginas visualizables
$sPages= "";
if($iHasPages>$iNumberOfPages) {
if($iStartPages==1){ $sPages.="|< << "; }
else{
$sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0&\">
<font class=\"ColumnFONT\" title=\"Ver la primera página\">|<</font></a> ";
$sPages.=" <a href=\"$sFileName?$form_params_page&FormPedidos_Page=".tourl($iStartPages-1)."&FormStarPage=".
tourl($iStartPages-1)."&FormSiguiente=-1&\"><font class=\"ColumnFONT\" title=\"Ver la página ".
($iStartPages-1)."\"><<</font></a> ";
}
}
for($iPageCount=$iStartPages; $iPageCount<($iStartPages+$iNumberOfPages); $iPageCount++) {
if ($iPageCount<=$iHasPages) {
$sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages)."&FormSiguiente=0&\">
<font class=\"ColumnFONT\" title=\"Ver la página ".$iPageCount."\">".$iPageCount."</font></a> ";
}
else { break; }
}
if($iHasPages>$iNumberOfPages) {
if($iPageCount-1<$iHasPages){
$sPages.="... <a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages).
"&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la página ".$iPageCount."\">>></font></a> ";
$sPages.=" <a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iHasPages&FormStarPage=tourl($iStartPages)
&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la última página\">>|</font></a>";
}
else { $sPages.=" >> >|"; }
}
?>
<tr class="titulos5" align="center">
<td class="leidos" colspan="<?=($numCol+1);?>"><center><br><?=$sPages?><br><br>Página <?=$iPage?>/<?=$iHasPages?><br>
Total de Registros: <?=$iCounter?><br> </center></td>
</tr>
<? // Botones para procesar
if ($tipoRespuesta[$opcionMenu][$numRtaMax]=="") {?>
<tr class="titulos4" align="center">
<td class="listado1" colspan="<?=($numCol+1);?>" align="center"><center>
<input type="button" class='botones' value="<?=$tituloSubmitRta[$opcionMenu]?>" onClick="javascript:enviar();">
<input type="button" class='botones' value="Cancelar" title="Regresa al menú de préstamo y control de documentos" onClick="javascript:regresar();"></center>
</td>
</tr>
<? }?>
</table>
</form>
<?
} //fin if
} //fin function
// Pedidos_Show end
?>
|
package org.ownprofile.boundary.owner.client;
public class Result<T> {
private boolean isSuccess;
private T successValue;
private Fail fail;
public static Result<Void> success() {
return success(null);
}
public static <S> Result<S> success(S successValue) {
return new Result<S>(successValue);
}
public static <S> Result<S> fail(String message) {
return fail((Throwable)null, "%s", message);
}
public static <S> Result<S> fail(Throwable cause, String message) {
return fail(cause, "%s", message);
}
public static <S> Result<S> fail(String format, Object... args) {
return fail(null, format, args);
}
public static <S> Result<S> fail(Throwable cause, String format, Object... args) {
final Fail f = new Fail(cause, format, args);
return new Result<S>(f);
}
private Result(T successValue) {
this.isSuccess = true;
this.successValue = successValue;
}
private Result(Fail fail) {
this.isSuccess = false;
this.fail = fail;
}
public boolean isSuccess() {
return isSuccess;
}
public boolean isFail() {
return !isSuccess;
}
public T getSuccessValue() {
if (isSuccess) {
return successValue;
} else {
throw new <API key>(String.format("Result is Fail: %s", fail));
}
}
public Fail getFail() {
if (isSuccess) {
throw new <API key>(String.format("Result is Success"));
} else {
return fail;
}
}
@Override
public String toString() {
return String.format("%s: %s",
isSuccess ? "SUCCESS" : "FAIL",
isSuccess ? successValue : fail);
}
public static class Fail {
private String message;
private Throwable cause;
private Fail(Throwable cause, String message) {
this.cause = cause;
this.message = message;
}
private Fail(Throwable cause, String format, Object... args) {
this(cause, String.format(format, args));
}
public String getMessage() {
return message;
}
public Throwable getCause() {
return cause;
}
@Override
public String toString() {
return String.format("%s - %s", message, cause);
}
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
class <API key> extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('businesses', function ($table) {
$table->integer('domain_id')->unsigned()->nullable()->after('category_id');
$table->foreign('domain_id')->references('id')->on('domains')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('businesses', function ($table) {
$table->dropForeign('<API key>');
$table->dropColumn('domain_id');
});
}
}
|
# -*- coding: utf-8 -*-
from .base import BaseHandler
class TestRoute(BaseHandler):
def get(self, file):
return self.render(str(file) + '.jade', show_h1=1)
|
# FlareDNS-client
Synchronize your App dynamic IP with your CloudFlare DNS A records.
Use this package if:
* You use [CloudFlare](https://cloudflare.com "CloudFlare").
* You run your Laravel App on a server with a Dynamic IP or your IP changes often.
## Installation
composer require thinkingcircles/flaredns-client
php
// config/app.php
'providers' => [
// Other service providers...
ThinkingCircles\FlareDNSClient\<API key>::class,
]
php artisan vendor:publish --provider="ThinkingCircles\FlareDNSClient\<API key>"
## Get CloudFlare api keys
## Configuration
php
// .env
cloudflare_zone_id=
cloudflare_global_<TwitterConsumerkey>=
:or
php
// config/flaredns-client.php
<?php return [
'<API key>' => [
'cloudflare_zone_id' => 'ZONE-ID',
'<API key>' => 'API-KEY',
'<API key>' => 'API-EMAIL',
'dns_records' => [
//will match id or name
['id'=>null, 'name'=>'domain.net'],
['id'=>'<API key>', 'name'=>null]
]
]
];
// Cron if you have not setup already
* * * * * php /<API key>/artisan schedule:run >> /dev/null 2>&1
## Usage
php
// App/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('flarednsclient:ipsync')->everyFiveMinutes();
}
## Todo
- [x] Debug
- [ ] Clean up code
- [ ] Improve logic
- [ ] Make UI [FlareDNS Management UI](https:
|
<?php
class <API key> extends GenericModel
{
/* dados da tabela */
protected $_banco = "SAC";
protected $_schema = "dbo";
protected $_name = "<API key>";
public function buscarDados($pronac = null, $conta_rejeitada = null, $periodo = null, $operacao = null ,$tamanho=-1, $inicio=-1, $count = null)
{
$select = $this->select();
$select->setIntegrityCheck(false);
if(isset($count)){
$select->from(
array("mi" => "<API key>"),
array("total" => "count(*)"));
} else {
$select->from(
array("mi" => "<API key>")
,array("m.nrBanco"
,"CONVERT(CHAR(10), m.dtInicioMovimento, 103) AS dtInicioMovimento"
,"CONVERT(CHAR(10), m.dtFimMovimento, 103) AS dtFimMovimento"
,"mi.<API key>"
,"mi.tpRegistro"
,"mi.nrAgencia"
,"mi.nrDigitoConta"
,"mi.nmTituloRazao"
,"mi.nmAbreviado"
,"CONVERT(CHAR(10), mi.dtAberturaConta, 103) AS dtAberturaConta"
,"mi.nrCNPJCPF"
,"n.Descricao AS Proponente"
,"mi.vlSaldoInicial"
,"mi.tpSaldoInicial"
,"mi.vlSaldoFinal"
,"mi.tpSaldoFinal"
,"CONVERT(CHAR(10), mi.dtMovimento, 103) AS dtMovimento"
,"mi.cdHistorico"
,"mi.dsHistorico"
,"mi.nrDocumento"
,"mi.vlMovimento"
,"mi.cdMovimento"
,"mi.<API key>"
,"ti.<API key>"
,"ti.<API key>"
,"(p.AnoProjeto+p.Sequencial) AS pronac"
,"p.NomeProjeto"
,"bc.Descricao AS nmBanco")
);
}
$select->joinInner(
array("m" => $this->_name)
,"m.<API key> = mi.<API key>"
,array()
);
if(!empty($conta_rejeitada) && $conta_rejeitada){
$select->joinInner(
array("mx" => "<API key>")
,"mi.<API key> = mx.<API key>"
,array()
);
$select->joinInner(
array("ti" => "<API key>")
,"ti.<API key> = mx.<API key>"
,array()
);
} else {
$select->joinLeft(
array("mx" => "<API key>")
,"mi.<API key> = mx.<API key>"
,array()
);
$select->joinLeft(
array("ti" => "<API key>")
,"ti.<API key> = mx.<API key>"
,array()
);
}
$select->joinLeft(
array("c" => "ContaBancaria")
,"mi.nrAgencia = c.Agencia AND (mi.nrDigitoConta = c.ContaBloqueada OR mi.nrDigitoConta = c.ContaLivre)"
,array()
);
$select->joinLeft(
array("p" => "Projetos")
,"c.AnoProjeto = p.AnoProjeto AND c.Sequencial = p.Sequencial"
,array()
);
$select->joinLeft(
array("bc" => "bancos")
,"m.nrBanco = bc.Codigo"
,array()
,"AGENTES.dbo"
);
$select->joinLeft(
array("a" => "Agentes")
,"mi.nrCNPJCPF = a.CNPJCPF"
,array()
,"AGENTES.dbo"
);
$select->joinLeft(
array("n" => "Nomes")
,"a.idAgente = n.idAgente"
,array()
,"AGENTES.dbo"
);
// $select->where("mi.vlSaldoInicial > 0.00");
//$select->where("mi.vlSaldoFinal > 0.00");
// busca pelo pronac
if (!empty($pronac))
{
$select->where("(c.AnoProjeto+c.Sequencial) = ?", $pronac);
}
// filtra por contas rejeitadas
if (!empty($conta_rejeitada) && $conta_rejeitada)
{
$select->where("mx.<API key> IS NOT NULL");
$select->where("mx.<API key> IS NOT NULL");
}
else
{
$select->where("mx.<API key> IS NULL");
$select->where("mx.<API key> IS NULL");
}
if (!empty($periodo))
{
if ($periodo[0] == "A") // Hoje
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) = CONVERT(DATE, GETDATE())
OR CONVERT(DATE, m.dtFimMovimento) = CONVERT(DATE, GETDATE())
OR CONVERT(DATE, mi.dtMovimento) = CONVERT(DATE, GETDATE())");
}
if ($periodo[0] == "B") // Ontem
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "C")
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "D") // Semana passada (seg-dom)
{
$select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
END)");
}
if ($periodo[0] == "E")
{
$select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)
OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE()))
END
AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE())
WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE()))
WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE()))
WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))
END)");
}
if ($periodo[0] == "F")
{
$select->where("DATEPART(MONTH, m.dtInicioMovimento) + DATEPART(YEAR, m.dtInicioMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())
OR DATEPART(MONTH, m.dtFimMovimento) + DATEPART(YEAR, m.dtFimMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())
OR DATEPART(MONTH, mi.dtMovimento) + DATEPART(YEAR, mi.dtMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())");
}
if ($periodo[0] == "G") // Ano passado
{
$select->where("DATEPART(YEAR, m.dtInicioMovimento) = (DATEPART(YEAR, GETDATE()) - 1)
OR DATEPART(YEAR, m.dtFimMovimento) = (DATEPART(YEAR, GETDATE()) - 1)
OR DATEPART(YEAR, mi.dtMovimento) = (DATEPART(YEAR, GETDATE()) - 1)");
}
if ($periodo[0] == "H")
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "I")
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "J")
{
$select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))
OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))");
}
if ($periodo[0] == "K") // filtra conforme uma data inicial e uma data final
{
if (!empty($periodo[1]) && !empty($periodo[2]))
{
$select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00");
$select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59");
}
else
{
if (!empty($periodo[1]))
{
$select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00");
}
if (!empty($periodo[2]))
{
$select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59");
}
}
}
} // fecha if periodo
if (!empty($operacao))
{
$select->where("mi.tpSaldoInicial = ? OR mi.tpSaldoInicial IS NULL", $operacao);
$select->where("mi.tpSaldoFinal = ? OR mi.tpSaldoFinal IS NULL", $operacao);
$select->where("mi.cdMovimento = ? OR mi.cdMovimento IS NULL", $operacao);
}
/*$select->order("mi.tpRegistro");
$select->order("(p.AnoProjeto+p.Sequencial)");
$select->order("m.dtInicioMovimento");
$select->order("m.dtFimMovimento");
$select->order("mi.dtMovimento");
$select->order(array(5,26,2,3,17));
}*/
//paginacao
if ($tamanho > -1) {
$tmpInicio = 0;
if ($inicio > -1) {
$tmpInicio = $inicio;
}
$select->limit($tamanho, $tmpInicio);
}
//x($select->assemble());
return $this->fetchAll($select);
}
public function cadastrarDados($dados)
{
return $this->insert($dados);
}
public function alterarDados($dados, $where)
{
$where = "<API key> = " . $where;
return $this->update($dados, $where);
}
public function excluirDados($where)
{
$where = "<API key> = " . $where;
return $this->delete($where);
}
} // fecha class
|
#ifndef STATSSOURCE_H_
#define STATSSOURCE_H_
#include "common/tabletuple.h"
#include "common/ids.h"
#include "boost/scoped_ptr.hpp"
#include <string>
#include <vector>
#include <map>
namespace voltdb {
class Table;
class TableFactory;
class TupleSchema;
class TableTuple;
/**
* Abstract superclass of all sources of statistical information inside the EE. Statistics are currently represented as a single
* row table that is updated every time it is retrieved.
*/
class StatsSource {
public:
/**
* Generates the list of column names that are present for every
* stats table. Derived classes should implement their own static
* methods to generate their column names and call this method
* within it to populate the column name vector before adding
* their stat-specific column names.
*/
static std::vector<std::string> <API key>();
/**
* Populates the other schema information which is present for
* every stats table. Usage by derived classes takes the same
* pattern as <API key>.
*/
static void populateBaseSchema(std::vector<voltdb::ValueType>& types,
std::vector<int32_t>& columnLengths,
std::vector<bool>& allowNull,
std::vector<bool>& inBytes);
/*
* Do nothing constructor that initializes statTable_ and schema_ to NULL.
*/
StatsSource();
/**
* Configure a StatsSource superclass for a set of statistics. Since this class is only used in the EE it can be assumed that
* it is part of an Execution Site and that there is a site Id.
* @parameter name Name of this set of statistics
* @parameter hostId id of the host this partition is on
* @parameter hostname name of the host this partition is on
* @parameter siteId this stat source is associated with
* @parameter partitionId this stat source is associated with
* @parameter databaseId Database this source is associated with
*/
void configure(
std::string name,
voltdb::CatalogId databaseId);
/*
* Destructor that frees tupleSchema_, and statsTable_
*/
virtual ~StatsSource();
/**
* Retrieve table containing the latest statistics available. An updated stat is requested from the derived class by calling
* StatsSource::updateStatsTuple
* @param interval Return counters since the beginning or since this method was last invoked
* @param now Timestamp to return with each row
* @return Pointer to a table containing the statistics.
*/
voltdb::Table* getStatsTable(bool interval, int64_t now);
/*
* Retrieve tuple containing the latest statistics available. An updated stat is requested from the derived class by calling
* StatsSource::updateStatsTuple
* @param interval Whether to return counters since the beginning or since the last time this was called
* @param Timestamp to embed in each row
* @return Pointer to a table tuple containing the latest version of the statistics.
*/
voltdb::TableTuple* getStatsTuple(bool interval, int64_t now);
/**
* Retrieve the name of this set of statistics
* @return Name of statistics
*/
std::string getName();
/**
* String representation of the statistics. Default implementation is to print the stats table.
* @return String representation
*/
virtual std::string toString();
protected:
/**
* Update the stats tuple with the latest statistics available to this StatsSource. Implemented by derived classes.
* @parameter tuple TableTuple pointing to a row in the stats table.
*/
virtual void updateStatsTuple(voltdb::TableTuple *tuple) = 0;
/**
* Generates the list of column names that will be in the statTable_. Derived classes must override this method and call
* the parent class's version to obtain the list of columns contributed by ancestors and then append the columns they will be
* contributing to the end of the list.
*/
virtual std::vector<std::string> <API key>();
/**
* Same pattern as <API key> except the return value is used as an offset into the tuple schema instead of appending to
* end of a list.
*/
virtual void populateSchema(std::vector<voltdb::ValueType> &types, std::vector<int32_t> &columnLengths,
std::vector<bool> &allowNull, std::vector<bool> &inBytes);
/**
* Map describing the mapping from column names to column indices in the stats tuple. Necessary because classes in the
* inheritance hierarchy can vary the number of columns they contribute. This removes the dependency between them.
*/
std::map<std::string, int> m_columnName2Index;
bool interval() { return m_interval; }
private:
/**
* Table containing the stat information. Shared pointer used as a substitute for scoped_ptr due to forward
* declaration.
*/
boost::scoped_ptr<voltdb::Table> m_statsTable;
/**
* Tuple used to modify the stat table.
*/
voltdb::TableTuple m_statsTuple;
/**
* Name of this set of statistics.
*/
std::string m_name;
/**
* CatalogId of the partition this StatsSource is associated with.
*/
voltdb::CatalogId m_partitionId;
int64_t m_siteId;
voltdb::CatalogId m_hostId;
voltdb::NValue m_hostname;
bool m_interval;
};
}
#endif /* STATSCONTAINER_H_ */
|
import sys
import time
import sys
num = 1000
print_granularity = 1000
count = 0
first = True
start = 0
gran_start = 0
min = 0
max = 0
avg = 0
sum = 0
total = 0
def <API key>(p):
global print_granularity
print_granularity = p
print("%s: print granularity = %s" % (sys.argv[0], print_granularity))
def loop_count():
global min, max, avg, total, gran_start, sum, start, first, count
now = round(time.time() * 1000)
if not first:
elapsed = now - start
if elapsed < min: min = elapsed
if elapsed > max: max = elapsed
sum = sum + elapsed
start = now
count = count + 1
total = total + 1
if count % print_granularity == 0 and not first:
gran_elapsed = now - gran_start
gran_start = now
avg = sum / print_granularity
print("%s: last %s run stats in msec \t\t elapsed = %s \t min = %s \t max = %s \t avg = %s \t\t total loops = %s" % (sys.argv[0], print_granularity, sum, min, max, avg, total))
# sys.stdout.write("-")
# sys.stdout.flush()
if first or count % print_granularity == 0:
gran_start = now
min = 10e10
max = -10e10
avg = 0
sum = 0
first = False
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.vitalsignstprbp;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void onFormOpen() throws ims.framework.exceptions.<API key>;
abstract protected void <API key>() throws ims.framework.exceptions.<API key>;
abstract protected void onBtnViewClick() throws ims.framework.exceptions.<API key>;
abstract protected void <API key>() throws ims.framework.exceptions.<API key>;
abstract protected void onBtnPrintClick() throws ims.framework.exceptions.<API key>;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.<API key>
{
onFormOpen();
}
});
this.form.chkLegend().<API key>(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.<API key>
{
<API key>();
}
});
this.form.btnView().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.<API key>
{
onBtnViewClick();
}
});
this.form.grpShowBy().<API key>(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.<API key>
{
<API key>();
}
});
this.form.btnPrint().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.<API key>
{
onBtnPrintClick();
}
});
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo.beans;
public class <API key> extends ims.vo.ValueObjectBean
{
public <API key>()
{
}
public <API key>(ims.RefMan.vo.<API key> vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.<API key> vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public ims.RefMan.vo.<API key> buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.RefMan.vo.<API key> buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.<API key> vo = null;
if(map != null)
vo = (ims.RefMan.vo.<API key>)map.getValueObject(this);
if(vo == null)
{
vo = new ims.RefMan.vo.<API key>();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getStatus()
{
return this.status;
}
public void setStatus(ims.vo.LookupInstanceBean value)
{
this.status = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean status;
}
|
<?php
// Database Restore
$locale['400'] = "Восстановление БД";
$locale['401'] = "Ошибка";
$locale['402'] = "Неверный формат файла резервной копии";
$locale['403'] = "Закрыть";
// Backup File Information
$locale['410'] = "Данные о файле резервной копии";
$locale['411'] = "Данные о файле для восстановления";
$locale['412'] = "Имя файла копии:";
$locale['413'] = "Дата создания:";
$locale['414'] = "Имя базы данных:";
$locale['415'] = "Префикс таблиц ядра:";
$locale['416'] = "Таблицы:";
$locale['417'] = "Посмотреть";
$locale['418'] = "отмена";
$locale['419'] = "таблиц";
// Database Restore
$locale['430'] = "Параметры восстановления";
$locale['431'] = "Имя файла:";
$locale['432'] = "Создан:";
$locale['433'] = "Создать таблицы:";
$locale['434'] = "Заполнить таблицы:";
$locale['435'] = "Выбрать:";
$locale['436'] = "все";
$locale['437'] = "ничего";
$locale['438'] = "Восстановить из резервной копии";
$locale['439'] = "Отмена";
$locale['440'] = "Поддерживаемые типы файлов:";
// Database Backup
$locale['450'] = "Резервирование БД";
$locale['451'] = "Информация о базе данных";
$locale['452'] = "Общий размер таблиц:";
$locale['453'] = "Размер таблиц ядра:";
$locale['454'] = "Параметры резервирования:";
$locale['455'] = "Тип резервной копии:";
$locale['456'] = "(сжатая)";
$locale['457'] = "Таблицы БД";
$locale['458'] = "ядро";
$locale['459'] = "Создать резервную копию";
$locale['460'] = "Админпароль:";
$locale['460b'] = "Пожалуйста, введите Ваш админпароль";
$locale['461'] = "Требуемая информация";
// Backup List
$locale['480'] = "Восстановить из резервной копии";
$locale['481'] = "Имя файла:";
$locale['481b'] = "Пожалуйста, укажите имя файла";
?>
|
// This file is part of C
// C#raft is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#endregion
using Chraft.Entity.Items;
using Chraft.Utilities.Blocks;
using Chraft.World.Blocks.Base;
namespace Chraft.World.Blocks
{
class BlockStone : BlockBase
{
public BlockStone()
{
Name = "Stone";
Type = BlockData.Blocks.Stone;
IsSolid = true;
var item = ItemHelper.GetInstance(BlockData.Blocks.Cobblestone);
item.Count = 1;
LootTable.Add(item);
}
}
}
|
# -*- coding: utf-8 -*-
# Odoo, Open Source Business Applications
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res = super(StockPicking, self).do_transfer()
if self.carrier_id and self.carrier_id.delivery_type != 'grid':
self.send_to_shipper()
return res
# Signature due to strange old api methods
@api.model
def <API key>(self, picking, invoice):
picking.ensure_one()
invoice.ensure_one()
carrier = picking.carrier_id
# No carrier
if not carrier:
return None
# Carrier already invoiced on the sale order
if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids):
return None
# Classic carrier
if carrier.delivery_type == 'grid':
return super(StockPicking, self).<API key>(picking, invoice)
# Shipping provider
price = picking.carrier_price
account_id = carrier.product_id.<API key>.id
if not account_id:
account_id = carrier.product_id.categ_id.<API key>.id
taxes = carrier.product_id.taxes_id
taxes_ids = taxes.ids
# Apply original SO fiscal position
if picking.sale_id.fiscal_position_id:
fpos = picking.sale_id.fiscal_position_id
account_id = fpos.map_account(account_id)
taxes_ids = fpos.map_tax(taxes).ids
res = {
'name': carrier.name,
'invoice_id': invoice.id,
'uos_id': carrier.product_id.uos_id.id,
'product_id': carrier.product_id.id,
'account_id': account_id,
'price_unit': price,
'quantity': 1,
'<API key>': [(6, 0, taxes_ids)],
}
return res
@api.one
def send_to_shipper(self):
res = self.carrier_id.send_shipping(self)[0]
self.carrier_price = res['exact_price']
self.<API key> = res['tracking_number']
msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.<API key>)
self.message_post(body=msg)
@api.multi
def open_website_url(self):
self.ensure_one()
client_action = {'type': 'ir.actions.act_url',
'name': "Shipment Tracking Page",
'target': 'new',
'url': self.carrier_id.get_tracking_link(self)[0]
}
return client_action
@api.one
def cancel_shipment(self):
self.carrier_id.cancel_shipment(self)
msg = "Shipment %s cancelled" % self.<API key>
self.message_post(body=msg)
self.<API key> = False
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search — Paver 1.2.1 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: './',
VERSION: '1.2.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/searchtools.js"></script>
<link rel="top" title="Paver 1.2.1 documentation" href="index.html" />
<script type="text/javascript">
jQuery(function() { Search.loadIndex("searchindex.js"); });
</script>
<script type="text/javascript" id="searchindexloader"></script>
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Paver 1.2.1 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<h1 id="<API key>">Search</h1>
<div id="fallback" class="admonition warning">
<script type="text/javascript">$('#fallback').hide();</script>
<p>
Please activate JavaScript to enable the search
functionality.
</p>
</div>
<p>
From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result list.
</p>
<form action="" method="get">
<input type="text" name="q" value="" />
<input type="submit" value="search" />
<span id="search-progress" style="padding-left: 10px"></span>
</form>
<div id="search-results">
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="<API key>">
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Paver 1.2.1 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2008, SitePen, Inc..
Last updated on Jun 02, 2013.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2b1.
</div>
</body>
</html>
|
<?php $this->applyTemplateHook('settings-nav','before'); ?>
<nav id="panel-settings-nav" class="sidebar-panel">
<?php $this->applyTemplateHook('settings-nav','begin'); ?>
<?php $this->applyTemplateHook('settings-nav','end'); ?>
</nav>
<?php $this->applyTemplateHook('settings-nav','after'); ?>
|
package com.funambol.ctp.server.notification;
/**
*
* @version $Id: <API key>.java,v 1.2 2007-11-28 11:26:16 nichele Exp $
*/
public class <API key> extends Exception {
/**
* Creates a new instance of <code><API key></code> without
* detail message.
*/
public <API key>() {
super();
}
/**
* Constructs an instance of <code><API key></code> with the
* specified detail message.
*
* @param message the detail message.
*/
public <API key>(String message) {
super(message);
}
/**
* Constructs an instance of <code><API key></code> with the
* specified detail message and the given cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public <API key>(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code><API key></code> with the
* specified cause.
*
* @param cause the cause.
*/
public <API key>(Throwable cause) {
super(cause);
}
}
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// WARNING: DO NOT MODIFY the content of this file
package ims.spinalinjuries.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class <API key> extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatesaveConcern(ims.core.vo.<API key> concern, ims.core.vo.PatientShort patient)
{
}
@SuppressWarnings("unused")
public void validatelistHcps(ims.core.vo.HcpFilter filter)
{
}
@SuppressWarnings("unused")
public void <API key>(ims.core.vo.CareContextShortVo <API key>)
{
}
@SuppressWarnings("unused")
public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId)
{
}
}
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//
//#EOH
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class <API key>
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// CurrentArea
valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea());
// isPrimaryCare
valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare());
// isDischarged
valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged());
// <API key>
valueObjectDest.<API key>(valueObjectSrc.<API key>());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #<API key>(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.<API key> <API key>(java.util.Set domainObjectSet)
{
return <API key>(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.<API key> <API key>(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.<API key> voList = new ims.emergency.vo.<API key>();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next();
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.<API key> <API key>(java.util.List domainObjectList)
{
return <API key>(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.<API key> <API key>(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.<API key> voList = new ims.emergency.vo.<API key>();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i);
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.Tracking set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractTrackingSet(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection)
{
return extractTrackingSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractTrackingSet(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = <API key>.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.Tracking list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractTrackingList(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection)
{
return extractTrackingList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractTrackingList(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = <API key>.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.TrackingLiteVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Tracking(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// CurrentArea
if (domainObject.getCurrentArea() != null)
{
if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea();
int id = Integer.parseInt(p.<API key>().getIdentifier().toString());
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1));
}
else
{
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion()));
}
}
// isPrimaryCare
valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() );
// isDischarged
valueObject.setIsDischarged( domainObject.isIsDischarged() );
// <API key>
java.util.Date <API key> = domainObject.<API key>();
if ( null != <API key> )
{
valueObject.<API key>(new ims.framework.utils.DateTime(<API key>) );
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.<API key> domainFactory, ims.emergency.vo.TrackingLiteVo valueObject)
{
return extractTracking(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.<API key> domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Tracking();
ims.emergency.domain.objects.Tracking domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject);
}
// ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown
domainObject = new ims.emergency.domain.objects.Tracking();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Tracking());
ims.emergency.configuration.domain.objects.TrackingArea value1 = null;
if ( null != valueObject.getCurrentArea() )
{
if (valueObject.getCurrentArea().getBoId() == null)
{
if (domMap.get(valueObject.getCurrentArea()) != null)
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value1 = domainObject.getCurrentArea();
}
else
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId());
}
}
domainObject.setCurrentArea(value1);
domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare());
domainObject.setIsDischarged(valueObject.getIsDischarged());
ims.framework.utils.DateTime dateTime4 = valueObject.<API key>();
java.util.Date value4 = null;
if ( dateTime4 != null )
{
value4 = dateTime4.getJavaDate();
}
domainObject.<API key>(value4);
return domainObject;
}
}
|
<?php
namespace Symfony\Component\HttpKernel\EventListener;
use Symfony\Component\EventDispatcher\<API key>;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\<API key>;
/**
* Initializes the locale based on the current request.
*
* This listener works in 2 modes:
*
* * 2.3 compatibility mode where you must call setRequest whenever the Request changes.
* * 2.4+ mode where you must pass a RequestStack instance in the constructor.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LocaleListener implements <API key>
{
private $router;
private $defaultLocale;
private $requestStack;
/**
* RequestStack will become required in 3.0.
*/
public function __construct($defaultLocale = 'en', <API key> $router = null, RequestStack $requestStack = null)
{
$this->defaultLocale = $defaultLocale;
$this->requestStack = $requestStack;
$this->router = $router;
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the Router to have access to the _locale
KernelEvents::REQUEST => array( array( 'onKernelRequest', 16 ) ),
KernelEvents::FINISH_REQUEST => array( array( '<API key>', 0 ) ),
);
}
/**
* Sets the current Request.
*
* This method was used to synchronize the Request, but as the HttpKernel
* is doing that automatically now, you should never call it directly.
* It is kept public for BC with the 2.3 version.
*
* @param Request|null $request A Request instance
*
* @deprecated Deprecated since version 2.4, to be removed in 3.0.
*/
public function setRequest(Request $request = null)
{
if (null === $request) {
return;
}
$this->setLocale($request);
$this->setRouterContext($request);
}
private function setLocale( Request $request )
{
if ($locale = $request->attributes->get( '_locale' )) {
$request->setLocale( $locale );
}
}
private function setRouterContext( Request $request )
{
if (null !== $this->router) {
$this->router->getContext()->setParameter( '_locale', $request->getLocale() );
}
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$request->setDefaultLocale($this->defaultLocale);
$this->setLocale($request);
$this->setRouterContext($request);
}
public function <API key>(FinishRequestEvent $event)
{
if (null === $this->requestStack) {
return; // removed when requestStack is required
}
if (null !== $parentRequest = $this->requestStack->getParentRequest()) {
$this->setRouterContext($parentRequest);
}
}
}
|
package com.sapienter.jbilling.client.jspc.payment;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool <API key>;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool <API key>;
private javax.el.ExpressionFactory <API key>;
private org.apache.AnnotationProcessor <API key>;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
<API key> = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
<API key> = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
<API key> = _jspxFactory.<API key>(getServletConfig().getServletContext()).<API key>();
<API key> = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
<API key>.release();
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release();
<API key>.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
if (<API key>(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
if (<API key>(_jspx_page_context))
return;
out.write("\r\n\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean <API key>(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag <API key> = (org.apache.taglibs.session.ExistsAttributeTag) <API key>.get(org.apache.taglibs.session.ExistsAttributeTag.class);
<API key>.setPageContext(_jspx_page_context);
<API key>.setParent(null);
// /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setName("jsp_is_refund");
// /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setValue(false);
int <API key> = <API key>.doStartTag();
if (<API key> != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (<API key>(<API key>, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = <API key>.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (<API key>.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
<API key>.reuse(<API key>);
return true;
}
<API key>.reuse(<API key>);
return false;
}
private boolean <API key>(javax.servlet.jsp.tagext.JspTag <API key>, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag <API key> = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
<API key>.setPageContext(_jspx_page_context);
<API key>.setParent((javax.servlet.jsp.tagext.Tag) <API key>);
// /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setDefinition("payment.review");
// /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setFlush(true);
int <API key> = <API key>.doStartTag();
if (<API key>.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(<API key>);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(<API key>);
return false;
}
private boolean <API key>(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag <API key> = (org.apache.taglibs.session.ExistsAttributeTag) <API key>.get(org.apache.taglibs.session.ExistsAttributeTag.class);
<API key>.setPageContext(_jspx_page_context);
<API key>.setParent(null);
// /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setName("jsp_is_refund");
int <API key> = <API key>.doStartTag();
if (<API key> != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (<API key>(<API key>, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = <API key>.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (<API key>.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
<API key>.reuse(<API key>);
return true;
}
<API key>.reuse(<API key>);
return false;
}
private boolean <API key>(javax.servlet.jsp.tagext.JspTag <API key>, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag <API key> = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
<API key>.setPageContext(_jspx_page_context);
<API key>.setParent((javax.servlet.jsp.tagext.Tag) <API key>);
// /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setDefinition("refund.review");
// /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
<API key>.setFlush(true);
int <API key> = <API key>.doStartTag();
if (<API key>.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(<API key>);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(<API key>);
return false;
}
}
|
/*@author Jvlaple
*Crystal of Roots
*/
var status = 0;
var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093);
importPackage(net.sf.odinms.client);
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (status >= 0 && mode == 0) {
cm.sendOk("Ok, keep preservering!");
cm.dispose();
return;
}
if (mode == 1)
status++;
else
status
if (status == 0 ) {
cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?");
} else if (status == 1) {
var eim = cm.getPlayer().getEventInstance();
cm.warp(100000000, 0);
if (eim != null) {
eim.unregisterPlayer(cm.getPlayer());
}cm.dispose();
}
}
}
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.notificationdialog;
public interface IFormUILogicCode
{
// No methods yet.
}
|
package v4
var (
BundleCharms = (*Handler).bundleCharms
ParseSearchParams = parseSearchParams
DefaultIcon = defaultIcon
<API key> = &<API key>
<API key> = &<API key>
ParamsLogLevels = paramsLogLevels
ParamsLogTypes = paramsLogTypes
ProcessIcon = processIcon
UsernameAttr = usernameAttr
GroupsAttr = groupsAttr
GetPromulgatedURL = (*Handler).getPromulgatedURL
)
|
# <API key>: true
require "test_helper"
module GobiertoAdmin
class UserFormTest < ActiveSupport::TestCase
def valid_user_form
@valid_user_form ||= UserForm.new(
id: user.id,
name: user.name,
bio: user.bio,
email: user.email
)
end
def invalid_user_form
@invalid_user_form ||= UserForm.new(
name: nil,
email: nil
)
end
def user
@user ||= users(:reed)
end
def <API key>
assert valid_user_form.save
end
def <API key>
refute invalid_user_form.save
end
def <API key>
invalid_user_form.save
assert_equal 1, invalid_user_form.errors.messages[:name].size
assert_equal 1, invalid_user_form.errors.messages[:email].size
end
def <API key>
email_changing_form = UserForm.new(
id: user.id,
email: "wadus@gobierto.dev",
name: "Wadus"
)
assert_difference "ActionMailer::Base.deliveries.size", 1 do
email_changing_form.save
end
end
def <API key>
<API key> "ActionMailer::Base.deliveries.size" do
valid_user_form.save
end
end
end
end
|
# This file is part of Shuup.
import decimal
import pytest
from django.conf import settings
from shuup.core.models import Shipment, ShippingStatus, StockBehavior
from shuup.testing.factories import (
<API key>, create_empty_order, create_product,
get_default_shop, <API key>
)
from shuup.utils.excs import Problem
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
shipment = order.create_shipment({line.product: 1}, supplier=supplier)
expected_key_start = "%s/%s" % (order.pk, i)
assert shipment.identifier.startswith(expected_key_start)
assert order.shipments.count() == int(line.quantity)
assert order.shipping_status == ShippingStatus.FULLY_SHIPPED # Check that order is now fully shipped
assert not order.can_edit()
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
unsaved_shipment = Shipment(order=order, supplier=supplier)
shipment = order.create_shipment({line.product: 1}, shipment=unsaved_shipment)
expected_key_start = "%s/%s" % (order.pk, i)
assert shipment.identifier.startswith(expected_key_start)
assert order.shipments.count() == int(line.quantity)
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
with pytest.raises(AssertionError):
order.create_shipment({line.product: 1})
assert order.shipments.count() == 0
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
second_order = create_empty_order(shop=shop)
second_order.full_clean()
second_order.save()
product_lines = order.lines.exclude(product_id=None)
for line in product_lines:
for i in range(0, int(line.quantity)):
with pytest.raises(AssertionError):
unsaved_shipment = Shipment(supplier=supplier, order=second_order)
order.create_shipment({line.product: 1}, shipment=unsaved_shipment)
assert order.shipments.count() == 0
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
assert order.can_edit()
first_product_line = order.lines.exclude(product_id=None).first()
assert first_product_line.quantity > 1
order.create_shipment({first_product_line.product: 1}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert not order.can_edit()
@pytest.mark.django_db
def <API key>():
shop = get_default_shop()
supplier = <API key>()
order = _get_order(shop, supplier)
assert order.can_edit()
first_product_line = order.lines.exclude(product_id=None).first()
assert first_product_line.quantity > 1
shipment = order.create_shipment({first_product_line.product: 1}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert order.shipments.all().count() == 1
# Test shipment delete
shipment.soft_delete()
assert order.shipments.all().count() == 1
assert order.shipments.all_except_deleted().count() == 0
# Check the shipping status update
assert order.shipping_status == ShippingStatus.NOT_SHIPPED
@pytest.mark.django_db
def <API key>():
if "shuup.simple_supplier" not in settings.INSTALLED_APPS:
pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS")
from shuup_tests.simple_supplier.utils import get_simple_supplier
shop = get_default_shop()
supplier = get_simple_supplier()
order = _get_order(shop, supplier, stocked=True)
product_line = order.lines.products().first()
product = product_line.product
assert product_line.quantity == 15
supplier.adjust_stock(product.pk, delta=10)
stock_status = supplier.get_stock_status(product.pk)
assert stock_status.physical_count == 10
order.create_shipment({product: 5}, supplier=supplier)
assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED
assert order.shipments.all().count() == 1
with pytest.raises(Problem):
order.create_shipment({product: 10}, supplier=supplier)
# Should be fine after adding more stock
supplier.adjust_stock(product.pk, delta=5)
order.create_shipment({product: 10}, supplier=supplier)
def _get_order(shop, supplier, stocked=False):
order = create_empty_order(shop=shop)
order.full_clean()
order.save()
for product_data in _get_product_data(stocked):
quantity = product_data.pop("quantity")
product = create_product(
sku=product_data.pop("sku"),
shop=shop,
supplier=supplier,
default_price=3.33,
**product_data)
<API key>(order, supplier, product, quantity=quantity, <API key>=1)
order.cache_prices()
order.check_all_verified()
order.save()
return order
def _get_product_data(stocked=False):
return [
{
"sku": "sku1234",
"net_weight": decimal.Decimal("1"),
"gross_weight": decimal.Decimal("43.34257"),
"quantity": decimal.Decimal("15"),
"stock_behavior": StockBehavior.STOCKED if stocked else StockBehavior.UNSTOCKED
}
]
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
// This code was generated by Silviu Checherita using IMS Development Environment (version 1.80 build 5567.19951)
package ims.scheduling.domain.impl;
import java.util.ArrayList;
import java.util.List;
import ims.domain.DomainFactory;
import ims.domain.lookups.LookupInstance;
import ims.scheduling.domain.base.impl.<API key>;
import ims.scheduling.vo.lookups.<API key>;
import ims.scheduling.vo.lookups.<API key>;
import ims.scheduling.vo.lookups.Status_Reason;
public class <API key> extends <API key>
{
private static final long serialVersionUID = 1L;
//WDEV-21736
public <API key> listReasons()
{
DomainFactory factory = getDomainFactory();
ArrayList markers = new ArrayList();
ArrayList values = new ArrayList();
String hql = "SELECT r FROM <API key> AS t LEFT JOIN t.cancellationReason as r WHERE t.cancellationType.id = :cancellationType AND r.active = 1";
markers.add("cancellationType");
values.add(Status_Reason.HOSPITALCANCELLED.getID());
List results = factory.find(hql.toString(), markers,values);
if (results == null)
return null;
<API key> col = new <API key>();
for (int i=0; i<results.size(); i++)
{
<API key> reason = new <API key>(((LookupInstance) results.get(i)).getId(), ((LookupInstance) results.get(i)).getText(), ((LookupInstance) results.get(i)).isActive());
col.add(reason);
}
return col;
}
//WDEV-21736 ends here
}
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class <API key> extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public <API key>()
{
super();
}
public <API key>(int id)
{
super(id, "", true);
}
public <API key>(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public <API key>(int id, String text, boolean active, <API key> parent, Image image)
{
super(id, text, active, parent, image);
}
public <API key>(int id, String text, boolean active, <API key> parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public <API key>(int id, String text, boolean active, <API key> parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static <API key> buildLookup(ims.vo.LookupInstanceBean bean)
{
return new <API key>(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (<API key>)super.getParentInstance();
}
public <API key> getParent()
{
return (<API key>)super.getParentInstance();
}
public void setParent(<API key> parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
<API key>[] typedChildren = new <API key>[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (<API key>)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof <API key>)
{
super.addChild((<API key>)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof <API key>)
{
super.removeChild((<API key>)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection <API key>()
{
<API key> result = new <API key>();
return result;
}
public static <API key>[] <API key>()
{
return new <API key>[] {};
}
public static String[] <API key>()
{
return new String[] {};
}
public static <API key> getNegativeInstance(String name)
{
if(name == null)
return null;
// No negative instances found
return null;
}
public static <API key> getNegativeInstance(Integer id)
{
if(id == null)
return null;
// No negative instances found
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1251032;
}
|
div.<API key> {
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
div.<API key> {
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
-<API key>: 10px;
-webkit-box-shadow: 3px 3px 4px #000;
-moz-border-radius: 10px;
-moz-box-shadow: 3px 3px 4px #000;
padding: 20px;
background-color: white;
z-index:1002;
overflow: auto;
text-align: center;
background-color: #EFF5FB;
}
span.<API key> {
font-size: 32px;
font-weight: bold;
color: #424242;
}
span.<API key> {
font-size: 20px;
color: #424242;
}
input.<API key> {
font-size: 20px;
text-align: center;
width: 300px;
color: #424242;
}
button.<API key> {
-<API key>: 10px;
-webkit-box-shadow: 3px 3px 4px #000;
-moz-border-radius: 10px;
-moz-box-shadow: 3px 3px 4px #000;
font-size: 20px;
background-color: #045FB4;
color: white;
width: 150px;
}
button.<API key>[disabled] {
background-color: #ddd;
}
|
<div data-role="header">
<h1>Prijave problema koje nisu poslate</h1>
</div>
<div data-role="content" role="main">
<div id="existing_report">
<% if ( title ) { %>
<h3><%= title %></h3>
<% } %>
<div class="meta">
<p>
<% if ( category && category != '-- Izaberite kategoriju --' ) { %>
Saved in the <%= category %> category
<% } %>
</p>
<p><% print( moment( created ).fromNow() ) %></p>
</div>
<% if ( file ) { %>
<div class="photo" style="background-image: url(<%= file %>)"></div>
<% } %>
<% if ( details ) { %>
<div class="details"><div><%= details %></div></div>
<% } %>
</div>
<div class="right">
<input id="use_report" type="button" value="Završite prijavu sada" data-role="button" data-theme="a" />
<input id="save_report" type="button" value="Sačuvaj za kasnije" data-role="button" data-theme="a" />
<input id="discard" type="button" value="Odbaci" data-role="button" data-theme="a" />
</div>
</div>
|
package com.rapid_i.deployment.update.client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.<API key>;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.rapid_i.deployment.update.client.listmodels.<API key>;
import com.rapidminer.deployment.client.wsimport.PackageDescriptor;
import com.rapidminer.deployment.client.wsimport.UpdateService;
import com.rapidminer.gui.RapidMinerGUI;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.gui.tools.ProgressThread;
import com.rapidminer.gui.tools.ResourceAction;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.gui.tools.dialogs.ButtonDialog;
import com.rapidminer.gui.tools.dialogs.ConfirmDialog;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.tools.FileSystemService;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.XMLException;
/**
* The Dialog is eventually shown at the start of RapidMiner, if the user purchased extensions online but haven't installed them yet.
*
* @author Dominik Halfkann
*/
public class <API key> extends ButtonDialog {
private static final long serialVersionUID = 1L;
private final <API key> <API key> = new <API key>();
private <API key> purchasedModel = new <API key>(<API key>);
JCheckBox neverAskAgain = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.<API key>.<API key>"));
private final List<String> packages;
private boolean isConfirmed;
private LinkedList<PackageDescriptor> <API key>;
private JButton remindNeverButton;
private JButton remindLaterButton;
private JButton okButton;
private class <API key> extends <API key> {
private static final long serialVersionUID = 1L;
public <API key>(<API key> cache) {
super(cache, "gui.dialog.update.tab.no_packages");
}
@Override
public List<String> <API key>() {
return packages;
}
}
public <API key>(List<String> packages) {
super("<API key>");
this.packages = packages;
remindNeverButton = remindNeverButton();
remindLaterButton = remindLaterButton();
okButton = makeOkButton("install_purchased");
layoutDefault(makeContentPanel(), NORMAL, okButton, remindNeverButton, remindLaterButton);
this.setPreferredSize(new Dimension(404, 430));
this.setMaximumSize(new Dimension(404, 430));
this.setMinimumSize(new Dimension(404, 300));
this.setSize(new Dimension(404, 430));
}
private JPanel makeContentPanel() {
BorderLayout layout = new BorderLayout(12, 12);
JPanel panel = new JPanel(layout);
panel.setBorder(new EmptyBorder(0, 12, 8, 12));
panel.add(<API key>(purchasedModel), BorderLayout.CENTER);
purchasedModel.update();
JPanel southPanel = new JPanel(new BorderLayout(0, 7));
JLabel question = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.<API key>.should_install"));
southPanel.add(question, BorderLayout.CENTER);
southPanel.add(neverAskAgain, BorderLayout.SOUTH);
panel.add(southPanel, BorderLayout.SOUTH);
return panel;
}
private JScrollPane <API key>(<API key> model) {
final JList updateList = new JList(model);
updateList.setCellRenderer(new <API key>(true));
JScrollPane <API key> = new ExtendedJScrollPane(updateList);
<API key>.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
return <API key>;
}
private JButton remindLaterButton() {
Action Action = new ResourceAction("ask_later") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
close();
}
};
getRootPane().getInputMap(JComponent.<API key>).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CLOSE");
getRootPane().getActionMap().put("CLOSE", Action);
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
private JButton remindNeverButton() {
Action Action = new ResourceAction("ask_never") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
neverRemindAgain();
close();
}
};
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
@Override
protected void ok() {
checkNeverAskAgain();
startUpdate(<API key>());
dispose();
}
public List<PackageDescriptor> <API key>() {
List<PackageDescriptor> packageList = new ArrayList<PackageDescriptor>();
for (int a = 0; a < purchasedModel.getSize(); a++) {
Object listItem = purchasedModel.getElementAt(a);
if (listItem instanceof PackageDescriptor) {
packageList.add((PackageDescriptor) listItem);
}
}
return packageList;
}
public void startUpdate(final List<PackageDescriptor> downloadList) {
final UpdateService service;
try {
service = UpdateManager.getService();
} catch (Exception e) {
SwingTools.<API key>("<API key>", e, UpdateManager.getBaseUrl());
return;
}
new ProgressThread("<API key>", true) {
@Override
public void run() {
try {
getProgressListener().setTotal(100);
remindLaterButton.setEnabled(false);
remindNeverButton.setEnabled(false);
final HashMap<PackageDescriptor, HashSet<PackageDescriptor>> dependency = UpdateDialog.resolveDependency(downloadList, <API key>);
getProgressListener().setCompleted(30);
<API key> = UpdateDialog.<API key>(dependency);
final HashMap<String, String> <API key> = UpdateDialog.collectLicenses(<API key>,getProgressListener(),100,30,100);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
isConfirmed = <API key>.confirm(dependency, <API key>);
new ProgressThread("installing_updates", true) {
@Override
public void run() {
try {
if (isConfirmed) {
getProgressListener().setTotal(100);
getProgressListener().setCompleted(20);
UpdateService service = UpdateManager.getService();
UpdateManager um = new UpdateManager(service);
List<PackageDescriptor> installedPackages = um.performUpdates(<API key>, getProgressListener());
getProgressListener().setCompleted(40);
if (installedPackages.size() > 0) {
int confirmation = SwingTools.showConfirmDialog((installedPackages.size() == 1 ? "update.complete_restart" : "update.complete_restart1"),
ConfirmDialog.YES_NO_OPTION, installedPackages.size());
if (confirmation == ConfirmDialog.YES_OPTION) {
RapidMinerGUI.getMainFrame().exit(true);
} else if (confirmation == ConfirmDialog.NO_OPTION) {
if (installedPackages.size() == <API key>.size()) {
dispose();
}
}
}
getProgressListener().complete();
}
} catch (Exception e) {
SwingTools.<API key>("<API key>", e, e.getMessage());
} finally {
getProgressListener().complete();
}
}
}.start();
}
});
remindLaterButton.setEnabled(true);
remindNeverButton.setEnabled(true);
getProgressListener().complete();
} catch (Exception e) {
SwingTools.<API key>("<API key>", e, e.getMessage());
}
}
}.start();
}
private void checkNeverAskAgain() {
if (neverAskAgain.isSelected()) {
ParameterService.setParameterValue(RapidMinerGUI.<API key>, "false");
ParameterService.saveParameters();
}
}
private void neverRemindAgain() {
LogService.getRoot().log(Level.CONFIG, "com.rapid_i.deployment.update.client.<API key>.<API key>");
Document doc;
try {
doc = <API key>.newInstance().newDocumentBuilder().newDocument();
} catch (<API key> e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.<API key>.<API key>",
e),
e);
return;
}
Element root = doc.createElement(UpdateManager.<API key>);
doc.appendChild(root);
for (String i : purchasedModel.fetchPackageNames()) {
Element entryElem = doc.createElement("extension_name");
entryElem.setTextContent(i);
root.appendChild(entryElem);
}
File file = FileSystemService.getUserConfigFile(UpdateManager.<API key>);
try {
XMLTools.stream(doc, file, null);
} catch (XMLException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.<API key>.<API key>",
e),
e);
}
}
}
|
def _checkInput(index):
if index < 0:
raise ValueError("Indice negativo non supportato [{}]".format(index))
elif type(index) != int:
raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__))
def fib_from_string(index):
_checkInput(index)
serie = "0 1 1 2 3 5 8".replace(" ", "")
return int(serie[index])
def fib_from_list(index):
_checkInput(index)
serie = [0,1,1,2,3,5,8]
return serie[index]
def fib_from_algo(index):
_checkInput(index)
current_number = current_index = 0
base = 1
while current_index < index:
old_base = current_number
current_number = current_number + base
base = old_base
current_index += 1
pass
return current_number
def recursion(index):
if index <= 1:
return index
return recursion(index - 1) + recursion(index - 2)
def <API key>(index):
_checkInput(index)
return recursion(index)
calculate = <API key>
|
package rpcclient
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
"github.com/tendermint/tmlibs/log"
types "github.com/tendermint/tendermint/rpc/lib/types"
)
type myHandler struct {
closeConnAfterRead bool
mtx sync.RWMutex
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
defer conn.Close()
for {
messageType, _, err := conn.ReadMessage()
if err != nil {
return
}
h.mtx.RLock()
if h.closeConnAfterRead {
conn.Close()
}
h.mtx.RUnlock()
res := json.RawMessage(`{}`)
emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: &res})
if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil {
return
}
}
}
func <API key>(t *testing.T) {
var wg sync.WaitGroup
// start server
h := &myHandler{}
s := httptest.NewServer(h)
defer s.Close()
c := startClient(t, s.Listener.Addr())
defer c.Stop()
wg.Add(1)
go callWgDoneOnResult(t, c, &wg)
h.mtx.Lock()
h.closeConnAfterRead = true
h.mtx.Unlock()
// results in WS read error, no send retry because write succeeded
call(t, "a", c)
// expect to reconnect almost immediately
time.Sleep(10 * time.Millisecond)
h.mtx.Lock()
h.closeConnAfterRead = false
h.mtx.Unlock()
// should succeed
call(t, "b", c)
wg.Wait()
}
func <API key>(t *testing.T) {
var wg sync.WaitGroup
// start server
h := &myHandler{}
s := httptest.NewServer(h)
c := startClient(t, s.Listener.Addr())
defer c.Stop()
wg.Add(2)
go callWgDoneOnResult(t, c, &wg)
// hacky way to abort the connection before write
c.conn.Close()
// results in WS write error, the client should resend on reconnect
call(t, "a", c)
// expect to reconnect almost immediately
time.Sleep(10 * time.Millisecond)
// should succeed
call(t, "b", c)
wg.Wait()
}
func <API key>(t *testing.T) {
// start server
h := &myHandler{}
s := httptest.NewServer(h)
c := startClient(t, s.Listener.Addr())
defer c.Stop()
go func() {
for {
select {
case <-c.ResponsesCh:
case <-c.Quit:
return
}
}
}()
// hacky way to abort the connection before write
c.conn.Close()
s.Close()
// results in WS write error
// provide timeout to avoid blocking
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
c.Call(ctx, "a", make(map[string]interface{}))
// expect to reconnect almost immediately
time.Sleep(10 * time.Millisecond)
done := make(chan struct{})
go func() {
// client should block on this
call(t, "b", c)
close(done)
}()
// test that client blocks on the second send
select {
case <-done:
t.Fatal("client should block on calling 'b' during reconnect")
case <-time.After(5 * time.Second):
t.Log("All good")
}
}
func <API key>(t *testing.T) {
timeout := 2 * time.Second
s := httptest.NewServer(&myHandler{})
c := startClient(t, s.Listener.Addr())
c.Call(context.Background(), "a", make(map[string]interface{}))
// Let the readRoutine get around to blocking
time.Sleep(time.Second)
passCh := make(chan struct{})
go func() {
// Unless we have a non-blocking write to ResponsesCh from readRoutine
// this blocks forever ont the waitgroup
c.Stop()
passCh <- struct{}{}
}()
select {
case <-passCh:
// Pass
case <-time.After(timeout):
t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?",
timeout.Seconds())
}
}
func startClient(t *testing.T, addr net.Addr) *WSClient {
c := NewWSClient(addr.String(), "/websocket")
_, err := c.Start()
require.Nil(t, err)
c.SetLogger(log.TestingLogger())
return c
}
func call(t *testing.T, method string, c *WSClient) {
err := c.Call(context.Background(), method, make(map[string]interface{}))
require.NoError(t, err)
}
func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) {
for {
select {
case resp := <-c.ResponsesCh:
if resp.Error != nil {
t.Fatalf("unexpected error: %v", resp.Error)
}
if *resp.Result != nil {
wg.Done()
}
case <-c.Quit:
return
}
}
}
|
// Generated by CoffeeScript 1.10.0
var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile;
ovhFetcher = require('../lib/ovh_fetcher');
filterExisting = require('../lib/filter_existing');
saveDataAndFile = require('../lib/save_data_and_file');
linkBankOperation = require('../lib/link_bank_operation');
baseKonnector = require('../lib/base_konnector');
Bill = require('../models/bill');
module.exports = {
createNew: function(ovhApi, name, slug) {
var connector, fetchBills, fileOptions, logger, ovhFetcherInstance;
fileOptions = {
vendor: slug,
dateFormat: 'YYYYMMDD'
};
logger = require('printit')({
prefix: name,
date: true
});
ovhFetcherInstance = ovhFetcher["new"](ovhApi, slug, logger);
fetchBills = function(requiredFields, entries, body, next) {
return ovhFetcherInstance.fetchBills(requiredFields, entries, body, next);
};
return connector = baseKonnector.createNew({
name: name,
fields: {
loginUrl: "link",
token: "hidden",
folderPath: "folder"
},
models: [Bill],
fetchOperations: [
fetchBills, filterExisting(logger, Bill), saveDataAndFile(logger, Bill, fileOptions, ['bill']), linkBankOperation({
log: logger,
model: Bill,
identifier: slug,
dateDelta: 4,
amountDelta: 0.1
})
]
});
}
};
|
class <API key> < <API key>
def create
@subscriber = Subscriber.new(params[:subscriber])
if @subscriber.save
flash[:notice] = "Success! You have been sent a subscription email. Please click the confirmation link in that email to confirm your subscription."\
else
flash[:error] = "We're having trouble with that email address. Either it's invalid or you have already signed up to watch this story."
end
redirect_to :back
end
def confirm
@subscriber = Subscriber.<API key>(params[:id])
@subscriber.subscribe if @subscriber
end
def cancel
@subscriber = Subscriber.<API key>(params[:id])
@subscriber.cancel if @subscriber
end
end
|
"""
Braitenberg Vehicle2b
The more light sensed on the left side the faster the right motor moves.
The more light sensed on the right side the faster the left motor moves.
This causes the robot to turn towards a light source.
"""
from pyrobot.brain import Brain, avg
class Vehicle(Brain):
def setup(self):
self.robot.light[0].units = "SCALED"
def step(self):
leftSpeed = max([s.value for s in self.robot.light[0]["right"]])
rightSpeed = max([s.value for s in self.robot.light[0]["left"]])
print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed
self.motors(leftSpeed, rightSpeed)
def INIT(engine):
if engine.robot.type not in ['K-Team', 'Pyrobot']:
raise "Robot should have light sensors!"
return Vehicle('Braitenberg2a', engine)
|
//
//
//
//
//# This program is free software: you can redistribute it and/or modify #
//
//# published by the Free Software Foundation, either version 3 of the #
//
//
//# This program is distributed in the hope that it will be useful, #
//
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//
//
//
//
//
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//
//
//#EOH
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Florin Blindu
*/
public class <API key>
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.<API key> copy(ims.emergency.vo.<API key> valueObjectDest, ims.emergency.vo.<API key> valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.<API key>(valueObjectSrc.<API key>());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// <API key>
valueObjectDest.<API key>(valueObjectSrc.<API key>());
// Specialty
valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty());
// AllocatedStatus
valueObjectDest.setAllocatedStatus(valueObjectSrc.getAllocatedStatus());
// AllocatedBedType
valueObjectDest.setAllocatedBedType(valueObjectSrc.getAllocatedBedType());
// AuthoringInfo
valueObjectDest.setAuthoringInfo(valueObjectSrc.getAuthoringInfo());
// AllocatedDateTime
valueObjectDest.<API key>(valueObjectSrc.<API key>());
// AdmittingConsultant
valueObjectDest.<API key>(valueObjectSrc.<API key>());
// <API key>
valueObjectDest.<API key>(valueObjectSrc.<API key>());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.<API key> createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.Set domainObjectSet)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.<API key> createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.<API key> voList = new ims.emergency.vo.<API key>();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) iterator.next();
ims.emergency.vo.<API key> vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.<API key> createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.List domainObjectList)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.<API key> createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.<API key> voList = new ims.emergency.vo.<API key>();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainObjectList.get(i);
ims.emergency.vo.<API key> vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection)
{
return <API key>(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.<API key> vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = <API key>.<API key>(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection)
{
return <API key>(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.<API key> vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = <API key>.<API key>(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.<API key> create(ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.<API key> create(DomainObjectMap map, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.<API key> valueObject = (ims.emergency.vo.<API key>) map.getValueObject(domainObject, ims.emergency.vo.<API key>.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.<API key>(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.<API key> insert(ims.emergency.vo.<API key> valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.<API key> insert(DomainObjectMap map, ims.emergency.vo.<API key> valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.<API key>(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// <API key>
java.util.Date <API key> = domainObject.<API key>();
if ( null != <API key> )
{
valueObject.<API key>(new ims.framework.utils.DateTime(<API key>) );
}
// Specialty
ims.domain.lookups.LookupInstance instance2 = domainObject.getSpecialty();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Specialty voLookup2 = new ims.core.vo.lookups.Specialty(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.Specialty parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.Specialty(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setSpecialty(voLookup2);
}
// AllocatedStatus
ims.domain.lookups.LookupInstance instance3 = domainObject.getAllocatedStatus();
if ( null != instance3 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath());
}
color = instance3.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocationStatus voLookup3 = new ims.emergency.vo.lookups.AllocationStatus(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocationStatus parentVoLookup3 = voLookup3;
ims.domain.lookups.LookupInstance parent3 = instance3.getParent();
while (parent3 != null)
{
if (parent3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent3.getColor();
if (color != null)
color.getValue();
parentVoLookup3.setParent(new ims.emergency.vo.lookups.AllocationStatus(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color));
parentVoLookup3 = parentVoLookup3.getParent();
parent3 = parent3.getParent();
}
valueObject.setAllocatedStatus(voLookup3);
}
// AllocatedBedType
ims.domain.lookups.LookupInstance instance4 = domainObject.getAllocatedBedType();
if ( null != instance4 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath());
}
color = instance4.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocatedBedType voLookup4 = new ims.emergency.vo.lookups.AllocatedBedType(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocatedBedType parentVoLookup4 = voLookup4;
ims.domain.lookups.LookupInstance parent4 = instance4.getParent();
while (parent4 != null)
{
if (parent4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent4.getColor();
if (color != null)
color.getValue();
parentVoLookup4.setParent(new ims.emergency.vo.lookups.AllocatedBedType(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color));
parentVoLookup4 = parentVoLookup4.getParent();
parent4 = parent4.getParent();
}
valueObject.setAllocatedBedType(voLookup4);
}
// AuthoringInfo
valueObject.setAuthoringInfo(ims.core.vo.domain.<API key>.create(map, domainObject.getAuthoringInfo()) );
// AllocatedDateTime
java.util.Date AllocatedDateTime = domainObject.<API key>();
if ( null != AllocatedDateTime )
{
valueObject.<API key>(new ims.framework.utils.DateTime(AllocatedDateTime) );
}
// AdmittingConsultant
valueObject.<API key>(ims.core.vo.domain.HcpMinVoAssembler.create(map, domainObject.<API key>()) );
// <API key>
ims.domain.lookups.LookupInstance instance8 = domainObject.<API key>();
if ( null != instance8 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath());
}
color = instance8.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.<API key> voLookup8 = new ims.core.vo.lookups.<API key>(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color);
ims.core.vo.lookups.<API key> parentVoLookup8 = voLookup8;
ims.domain.lookups.LookupInstance parent8 = instance8.getParent();
while (parent8 != null)
{
if (parent8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent8.getColor();
if (color != null)
color.getValue();
parentVoLookup8.setParent(new ims.core.vo.lookups.<API key>(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color));
parentVoLookup8 = parentVoLookup8.getParent();
parent8 = parent8.getParent();
}
valueObject.<API key>(voLookup8);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.EDPartialAdmission <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> valueObject)
{
return <API key>(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.EDPartialAdmission <API key>(ims.domain.<API key> domainFactory, ims.emergency.vo.<API key> valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.<API key>();
ims.emergency.domain.objects.EDPartialAdmission domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(valueObject);
}
// ims.emergency.vo.<API key> <API key> field is unknown
domainObject = new ims.emergency.domain.objects.EDPartialAdmission();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.<API key>());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainFactory.getDomainObject(ims.emergency.domain.objects.EDPartialAdmission.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.<API key>());
ims.framework.utils.DateTime dateTime1 = valueObject.<API key>();
java.util.Date value1 = null;
if ( dateTime1 != null )
{
value1 = dateTime1.getJavaDate();
}
domainObject.<API key>(value1);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getSpecialty() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getSpecialty().getID());
}
domainObject.setSpecialty(value2);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value3 = null;
if ( null != valueObject.getAllocatedStatus() )
{
value3 =
domainFactory.getLookupInstance(valueObject.getAllocatedStatus().getID());
}
domainObject.setAllocatedStatus(value3);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value4 = null;
if ( null != valueObject.getAllocatedBedType() )
{
value4 =
domainFactory.getLookupInstance(valueObject.getAllocatedBedType().getID());
}
domainObject.setAllocatedBedType(value4);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.clinical.domain.objects.<API key> value5 = null;
if ( null != valueObject.getAuthoringInfo() )
{
if (valueObject.getAuthoringInfo().getBoId() == null)
{
if (domMap.get(valueObject.getAuthoringInfo()) != null)
{
value5 = (ims.core.clinical.domain.objects.<API key>)domMap.get(valueObject.getAuthoringInfo());
}
}
else
{
value5 = (ims.core.clinical.domain.objects.<API key>)domainFactory.getDomainObject(ims.core.clinical.domain.objects.<API key>.class, valueObject.getAuthoringInfo().getBoId());
}
}
domainObject.setAuthoringInfo(value5);
ims.framework.utils.DateTime dateTime6 = valueObject.<API key>();
java.util.Date value6 = null;
if ( dateTime6 != null )
{
value6 = dateTime6.getJavaDate();
}
domainObject.<API key>(value6);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.resource.people.domain.objects.Hcp value7 = null;
if ( null != valueObject.<API key>() )
{
if (valueObject.<API key>().getBoId() == null)
{
if (domMap.get(valueObject.<API key>()) != null)
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domMap.get(valueObject.<API key>());
}
}
else
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Hcp.class, valueObject.<API key>().getBoId());
}
}
domainObject.<API key>(value7);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value8 = null;
if ( null != valueObject.<API key>() )
{
value8 =
domainFactory.getLookupInstance(valueObject.<API key>().getID());
}
domainObject.<API key>(value8);
return domainObject;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.