text stringlengths 2 1.04M | meta dict |
|---|---|
/**
* @file
* @brief libpq Queue Storage Definitions
*/
#include <gear_config.h>
#include <libgearman-server/common.h>
#include <libgearman-server/byte.h>
#include <libgearman-server/plugins/queue/postgres/queue.h>
#include <libgearman-server/plugins/queue/base.h>
#if defined(HAVE_LIBPQ) and HAVE_LIBPQ
#pragma GCC diagnostic ignored "-Wundef"
#include <libpq-fe.h>
#endif
#include <cerrno>
/**
* @addtogroup plugins::queue::Postgresatic Static libpq Queue Storage Definitions
* @ingroup gearman_queue_libpq
* @{
*/
/**
* Default values.
*/
#define GEARMAN_QUEUE_LIBPQ_DEFAULT_TABLE "queue"
#define GEARMAN_QUEUE_QUERY_BUFFER 256
namespace gearmand { namespace plugins { namespace queue { class Postgres; }}}
static gearmand_error_t _initialize(gearman_server_st& server, gearmand::plugins::queue::Postgres *queue);
namespace gearmand {
namespace plugins {
namespace queue {
class Postgres : public gearmand::plugins::Queue {
public:
Postgres();
~Postgres();
gearmand_error_t initialize();
const std::string &insert()
{
return _insert_query;
}
const std::string &select()
{
return _select_query;
}
const std::string &create()
{
return _create_query;
}
PGconn *con;
std::string postgres_connect_string;
std::string table;
std::vector<char> query_buffer;
public:
std::string _insert_query;
std::string _select_query;
std::string _create_query;
};
Postgres::Postgres() :
Queue("Postgres"),
con(NULL),
postgres_connect_string(""),
table(""),
query_buffer()
{
command_line_options().add_options()
("libpq-conninfo", boost::program_options::value(&postgres_connect_string)->default_value(""), "PostgreSQL connection information string.")
("libpq-table", boost::program_options::value(&table)->default_value(GEARMAN_QUEUE_LIBPQ_DEFAULT_TABLE), "Table to use.");
}
Postgres::~Postgres ()
{
if (con)
PQfinish(con);
}
gearmand_error_t Postgres::initialize()
{
_create_query+= "CREATE TABLE " +table +" (unique_key VARCHAR" +"(" + TOSTRING(GEARMAN_UNIQUE_SIZE) +"), ";
_create_query+= "function_name VARCHAR(255), priority INTEGER, data BYTEA, when_to_run INTEGER, UNIQUE (unique_key, function_name))";
gearmand_error_t ret= _initialize(Gearmand()->server, this);
_insert_query+= "INSERT INTO " +table +" (priority, unique_key, function_name, data, when_to_run) VALUES($1,$2,$3,$4::BYTEA,$5)";
_select_query+= "SELECT unique_key,function_name,priority,data,when_to_run FROM " +table;
return ret;
}
void initialize_postgres()
{
static Postgres local_instance;
}
} // namespace queue
} // namespace plugins
} // namespace gearmand
/**
* PostgreSQL notification callback.
*/
static void _libpq_notice_processor(void *arg, const char *message);
/* Queue callback functions. */
static gearmand_error_t _libpq_add(gearman_server_st *server, void *context,
const char *unique, size_t unique_size,
const char *function_name,
size_t function_name_size,
const void *data, size_t data_size,
gearman_job_priority_t priority,
int64_t when);
static gearmand_error_t _libpq_flush(gearman_server_st *server, void *context);
static gearmand_error_t _libpq_done(gearman_server_st *server, void *context,
const char *unique,
size_t unique_size,
const char *function_name,
size_t function_name_size);
static gearmand_error_t _libpq_replay(gearman_server_st *server, void *context,
gearman_queue_add_fn *add_fn,
void *add_context);
/** @} */
/*
* Public definitions
*/
#pragma GCC diagnostic ignored "-Wold-style-cast"
gearmand_error_t _initialize(gearman_server_st& server,
gearmand::plugins::queue::Postgres *queue)
{
gearmand_info("Initializing libpq module");
gearman_server_set_queue(server, queue, _libpq_add, _libpq_flush, _libpq_done, _libpq_replay);
queue->con= PQconnectdb(queue->postgres_connect_string.c_str());
if (queue->con == NULL || PQstatus(queue->con) != CONNECTION_OK)
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "PQconnectdb: %s", PQerrorMessage(queue->con));
gearman_server_set_queue(server, NULL, NULL, NULL, NULL, NULL);
return GEARMAN_QUEUE_ERROR;
}
(void)PQsetNoticeProcessor(queue->con, _libpq_notice_processor, &server);
std::string query("SELECT tablename FROM pg_tables WHERE tablename='" +queue->table + "'");
PGresult* result= PQexec(queue->con, query.c_str());
if (result == NULL || PQresultStatus(result) != PGRES_TUPLES_OK)
{
std::string error_string= "PQexec:";
error_string+= PQerrorMessage(queue->con);
gearmand_gerror(error_string.c_str(), GEARMAN_QUEUE_ERROR);
PQclear(result);
return GEARMAN_QUEUE_ERROR;
}
if (PQntuples(result) == 0)
{
PQclear(result);
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "libpq module creating table '%s'", queue->table.c_str());
result= PQexec(queue->con, queue->create().c_str());
if (result == NULL || PQresultStatus(result) != PGRES_COMMAND_OK)
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM,
"PQexec:%s", PQerrorMessage(queue->con));
PQclear(result);
gearman_server_set_queue(server, NULL, NULL, NULL, NULL, NULL);
return GEARMAN_QUEUE_ERROR;
}
PQclear(result);
}
else
{
PQclear(result);
}
return GEARMAN_SUCCESS;
}
/*
* Static definitions
*/
static void _libpq_notice_processor(void *arg, const char *message)
{
(void)arg;
gearmand_log_info(GEARMAN_DEFAULT_LOG_PARAM, "PostgreSQL %s", message);
}
static gearmand_error_t _libpq_add(gearman_server_st*, void *context,
const char *unique, size_t unique_size,
const char *function_name,
size_t function_name_size,
const void *data, size_t data_size,
gearman_job_priority_t priority,
int64_t when)
{
(void)when;
gearmand::plugins::queue::Postgres *queue= (gearmand::plugins::queue::Postgres *)context;
char buffer[22];
snprintf(buffer, sizeof(buffer), "%u", static_cast<uint32_t>(priority));
const char *param_values[]= {
(char *)buffer,
(char *)unique,
(char *)function_name,
(char *)data,
(char *)when };
int param_lengths[]= {
(int)strlen(buffer),
(int)unique_size,
(int)function_name_size,
(int)data_size,
(int)when };
int param_formats[] = { 0, 0, 0, 1, 0 };
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libpq add: %.*s", (uint32_t)unique_size, (char *)unique);
PGresult *result= PQexecParams(queue->con, queue->insert().c_str(),
gearmand_array_size(param_lengths),
NULL, param_values, param_lengths, param_formats, 0);
if (result == NULL || PQresultStatus(result) != PGRES_COMMAND_OK)
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "PQexec:%s", PQerrorMessage(queue->con));
PQclear(result);
return GEARMAN_QUEUE_ERROR;
}
PQclear(result);
return GEARMAN_SUCCESS;
}
static gearmand_error_t _libpq_flush(gearman_server_st *, void *)
{
gearmand_debug("libpq flush");
return GEARMAN_SUCCESS;
}
static gearmand_error_t _libpq_done(gearman_server_st*, void *context,
const char *unique,
size_t unique_size,
const char *function_name,
size_t function_name_size)
{
(void)function_name_size;
gearmand::plugins::queue::Postgres *queue= (gearmand::plugins::queue::Postgres *)context;
PGresult *result;
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libpq done: %.*s", (uint32_t)unique_size, (char *)unique);
std::string query;
query+= "DELETE FROM ";
query+= queue->table;
query+= " WHERE unique_key='";
query+= (const char *)unique;
query+= "' AND function_name='";
query+= (const char *)function_name;
query+= "'";
result= PQexec(queue->con, query.c_str());
if (result == NULL || PQresultStatus(result) != PGRES_COMMAND_OK)
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "PQexec:%s", PQerrorMessage(queue->con));
PQclear(result);
return GEARMAN_QUEUE_ERROR;
}
PQclear(result);
return GEARMAN_SUCCESS;
}
static gearmand_error_t _libpq_replay(gearman_server_st *server, void *context,
gearman_queue_add_fn *add_fn,
void *add_context)
{
gearmand::plugins::queue::Postgres *queue= (gearmand::plugins::queue::Postgres *)context;
gearmand_info("libpq replay start");
std::string query("SELECT unique_key,function_name,priority,data,when_to_run FROM " + queue->table);
PGresult *result= PQexecParams(queue->con, query.c_str(), 0, NULL, NULL, NULL, NULL, 1);
if (result == NULL || PQresultStatus(result) != PGRES_TUPLES_OK)
{
gearmand_log_error(GEARMAN_DEFAULT_LOG_PARAM, "PQexecParams:%s", PQerrorMessage(queue->con));
PQclear(result);
return GEARMAN_QUEUE_ERROR;
}
for (int row= 0; row < PQntuples(result); row++)
{
gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM,
"libpq replay: %.*s",
PQgetlength(result, row, 0),
PQgetvalue(result, row, 0));
size_t data_length;
char *data;
if (PQgetlength(result, row, 3) == 0)
{
data= NULL;
data_length= 0;
}
else
{
data_length= size_t(PQgetlength(result, row, 3));
data= (char *)malloc(data_length);
if (data == NULL)
{
PQclear(result);
return gearmand_perror(errno, "malloc");
}
memcpy(data, PQgetvalue(result, row, 3), data_length);
}
gearmand_error_t ret;
ret= (*add_fn)(server, add_context, PQgetvalue(result, row, 0),
(size_t)PQgetlength(result, row, 0),
PQgetvalue(result, row, 1),
(size_t)PQgetlength(result, row, 1),
data, data_length,
(gearman_job_priority_t)atoi(PQgetvalue(result, row, 2)),
atoll(PQgetvalue(result, row, 4)));
if (gearmand_failed(ret))
{
PQclear(result);
return ret;
}
}
PQclear(result);
return GEARMAN_SUCCESS;
}
| {
"content_hash": "c125761c624d06cf42d1d498e8e85b91",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 143,
"avg_line_length": 29.190217391304348,
"alnum_prop": 0.6055669335319307,
"repo_name": "ssm/pkg-gearmand",
"id": "14ee4e422e2be2aec5af1679ca8e148deed9695c",
"size": "12484",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libgearman-server/plugins/queue/postgres/queue.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "334963"
},
{
"name": "C++",
"bytes": "2114456"
},
{
"name": "Objective-C",
"bytes": "121306"
},
{
"name": "Perl",
"bytes": "848"
},
{
"name": "Shell",
"bytes": "328492"
}
],
"symlink_target": ""
} |
. ./config.sh
xmlpkg=`echo .build/checkouts/SwiftLibXML.git-*/Package.swift`
[ -e $xmlpkg ] || ./generate-wrapper.sh
if [ -z "$@" ]; then
JAZZY_ARGS="--theme fullwidth --author René Hexel --author_url https://www.ict.griffith.edu.au/~rhexel/ --github_url https://github.com/rhx/$Mod --github-file-prefix https://github.com/rhx/$Mod/tree/main --root-url http://rhx.github.io/$Mod/ --output docs"
fi
rm -rf .docs.old
mv docs .docs.old 2>/dev/null
sourcekitten doc --spm-module $Mod -- $CCFLAGS $LINKFLAGS | \
sed -e 's/^}\]/},/' > .build/$Mod-doc.json
sourcekitten doc --spm-module lib$Mod -- $CCFLAGS $LINKFLAGS | \
sed -e 's/^\[//' >> .build/$Mod-doc.json
jazzy --sourcekitten-sourcefile .build/$Mod-doc.json --clean \
--module-version $JAZZY_VER --module $Mod $JAZZY_ARGS "$@"
| {
"content_hash": "006cabec95be1d24b170c486d7f1cc3d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 272,
"avg_line_length": 57.5,
"alnum_prop": 0.6608695652173913,
"repo_name": "rhx/gir2swift",
"id": "6f97d433fd4c7dc5292b82bb6654c4df6c68a799",
"size": "925",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "generate-documentation.sh",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Shell",
"bytes": "13801"
},
{
"name": "Swift",
"bytes": "400924"
},
{
"name": "XSLT",
"bytes": "7355"
}
],
"symlink_target": ""
} |
ALboolean LoadOAL10Library(char *szOALFullPathName, LPOPENALFNTABLE lpOALFnTable)
{
// TODO: Implement this.
if (!lpOALFnTable)
return AL_FALSE;
memset(lpOALFnTable, 0, sizeof(OPENALFNTABLE));
lpOALFnTable->alEnable = (LPALENABLE)alEnable;
if (lpOALFnTable->alEnable == NULL)
{
warn("Failed to retrieve 'alEnable' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDisable = (LPALDISABLE)alDisable;
if (lpOALFnTable->alDisable == NULL)
{
warn("Failed to retrieve 'alDisable' function address\n");
return AL_FALSE;
}
lpOALFnTable->alIsEnabled = (LPALISENABLED)alIsEnabled;
if (lpOALFnTable->alIsEnabled == NULL)
{
warn("Failed to retrieve 'alIsEnabled' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetBoolean = (LPALGETBOOLEAN)alGetBoolean;
if (lpOALFnTable->alGetBoolean == NULL)
{
warn("Failed to retrieve 'alGetBoolean' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetInteger = (LPALGETINTEGER)alGetInteger;
if (lpOALFnTable->alGetInteger == NULL)
{
warn("Failed to retrieve 'alGetInteger' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetFloat = (LPALGETFLOAT)alGetFloat;
if (lpOALFnTable->alGetFloat == NULL)
{
warn("Failed to retrieve 'alGetFloat' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetDouble = (LPALGETDOUBLE)alGetDouble;
if (lpOALFnTable->alGetDouble == NULL)
{
warn("Failed to retrieve 'alGetDouble' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetBooleanv = (LPALGETBOOLEANV)alGetBooleanv;
if (lpOALFnTable->alGetBooleanv == NULL)
{
warn("Failed to retrieve 'alGetBooleanv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetIntegerv = (LPALGETINTEGERV)alGetIntegerv;
if (lpOALFnTable->alGetIntegerv == NULL)
{
warn("Failed to retrieve 'alGetIntegerv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetFloatv = (LPALGETFLOATV)alGetFloatv;
if (lpOALFnTable->alGetFloatv == NULL)
{
warn("Failed to retrieve 'alGetFloatv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetDoublev = (LPALGETDOUBLEV)alGetDoublev;
if (lpOALFnTable->alGetDoublev == NULL)
{
warn("Failed to retrieve 'alGetDoublev' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetString = (LPALGETSTRING)alGetString;
if (lpOALFnTable->alGetString == NULL)
{
warn("Failed to retrieve 'alGetString' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetError = (LPALGETERROR)alGetError;
if (lpOALFnTable->alGetError == NULL)
{
warn("Failed to retrieve 'alGetError' function address\n");
return AL_FALSE;
}
lpOALFnTable->alIsExtensionPresent = (LPALISEXTENSIONPRESENT)alIsExtensionPresent;
if (lpOALFnTable->alIsExtensionPresent == NULL)
{
warn("Failed to retrieve 'alIsExtensionPresent' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetProcAddress = (LPALGETPROCADDRESS)alGetProcAddress;
if (lpOALFnTable->alGetProcAddress == NULL)
{
warn("Failed to retrieve 'alGetProcAddress' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetEnumValue = (LPALGETENUMVALUE)alGetEnumValue;
if (lpOALFnTable->alGetEnumValue == NULL)
{
warn("Failed to retrieve 'alGetEnumValue' function address\n");
return AL_FALSE;
}
lpOALFnTable->alListeneri = (LPALLISTENERI)alListeneri;
if (lpOALFnTable->alListeneri == NULL)
{
warn("Failed to retrieve 'alListeneri' function address\n");
return AL_FALSE;
}
lpOALFnTable->alListenerf = (LPALLISTENERF)alListenerf;
if (lpOALFnTable->alListenerf == NULL)
{
warn("Failed to retrieve 'alListenerf' function address\n");
return AL_FALSE;
}
lpOALFnTable->alListener3f = (LPALLISTENER3F)alListener3f;
if (lpOALFnTable->alListener3f == NULL)
{
warn("Failed to retrieve 'alListener3f' function address\n");
return AL_FALSE;
}
lpOALFnTable->alListenerfv = (LPALLISTENERFV)alListenerfv;
if (lpOALFnTable->alListenerfv == NULL)
{
warn("Failed to retrieve 'alListenerfv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetListeneri = (LPALGETLISTENERI)alGetListeneri;
if (lpOALFnTable->alGetListeneri == NULL)
{
warn("Failed to retrieve 'alGetListeneri' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetListenerf =(LPALGETLISTENERF)alGetListenerf;
if (lpOALFnTable->alGetListenerf == NULL)
{
warn("Failed to retrieve 'alGetListenerf' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetListener3f = (LPALGETLISTENER3F)alGetListener3f;
if (lpOALFnTable->alGetListener3f == NULL)
{
warn("Failed to retrieve 'alGetListener3f' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetListenerfv = (LPALGETLISTENERFV)alGetListenerfv;
if (lpOALFnTable->alGetListenerfv == NULL)
{
warn("Failed to retrieve 'alGetListenerfv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGenSources = (LPALGENSOURCES)alGenSources;
if (lpOALFnTable->alGenSources == NULL)
{
warn("Failed to retrieve 'alGenSources' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDeleteSources = (LPALDELETESOURCES)alDeleteSources;
if (lpOALFnTable->alDeleteSources == NULL)
{
warn("Failed to retrieve 'alDeleteSources' function address\n");
return AL_FALSE;
}
lpOALFnTable->alIsSource = (LPALISSOURCE)alIsSource;
if (lpOALFnTable->alIsSource == NULL)
{
warn("Failed to retrieve 'alIsSource' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcei = (LPALSOURCEI)alSourcei;
if (lpOALFnTable->alSourcei == NULL)
{
warn("Failed to retrieve 'alSourcei' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcef = (LPALSOURCEF)alSourcef;
if (lpOALFnTable->alSourcef == NULL)
{
warn("Failed to retrieve 'alSourcef' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSource3f = (LPALSOURCE3F)alSource3f;
if (lpOALFnTable->alSource3f == NULL)
{
warn("Failed to retrieve 'alSource3f' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcefv = (LPALSOURCEFV)alSourcefv;
if (lpOALFnTable->alSourcefv == NULL)
{
warn("Failed to retrieve 'alSourcefv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetSourcei = (LPALGETSOURCEI)alGetSourcei;
if (lpOALFnTable->alGetSourcei == NULL)
{
warn("Failed to retrieve 'alGetSourcei' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetSourcef = (LPALGETSOURCEF)alGetSourcef;
if (lpOALFnTable->alGetSourcef == NULL)
{
warn("Failed to retrieve 'alGetSourcef' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetSourcefv = (LPALGETSOURCEFV)alGetSourcefv;
if (lpOALFnTable->alGetSourcefv == NULL)
{
warn("Failed to retrieve 'alGetSourcefv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcePlayv = (LPALSOURCEPLAYV)alSourcePlayv;
if (lpOALFnTable->alSourcePlayv == NULL)
{
warn("Failed to retrieve 'alSourcePlayv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourceStopv = (LPALSOURCESTOPV)alSourceStopv;
if (lpOALFnTable->alSourceStopv == NULL)
{
warn("Failed to retrieve 'alSourceStopv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcePlay = (LPALSOURCEPLAY)alSourcePlay;
if (lpOALFnTable->alSourcePlay == NULL)
{
warn("Failed to retrieve 'alSourcePlay' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourcePause = (LPALSOURCEPAUSE)alSourcePause;
if (lpOALFnTable->alSourcePause == NULL)
{
warn("Failed to retrieve 'alSourcePause' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourceStop = (LPALSOURCESTOP)alSourceStop;
if (lpOALFnTable->alSourceStop == NULL)
{
warn("Failed to retrieve 'alSourceStop' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourceRewind = (LPALSOURCEREWIND)alSourceRewind;
if (lpOALFnTable->alSourceRewind == NULL)
{
warn("Failed to retrieve 'alSourceRewind' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGenBuffers = (LPALGENBUFFERS)alGenBuffers;
if (lpOALFnTable->alGenBuffers == NULL)
{
warn("Failed to retrieve 'alGenBuffers' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDeleteBuffers = (LPALDELETEBUFFERS)alDeleteBuffers;
if (lpOALFnTable->alDeleteBuffers == NULL)
{
warn("Failed to retrieve 'alDeleteBuffers' function address\n");
return AL_FALSE;
}
lpOALFnTable->alIsBuffer = (LPALISBUFFER)alIsBuffer;
if (lpOALFnTable->alIsBuffer == NULL)
{
warn("Failed to retrieve 'alIsBuffer' function address\n");
return AL_FALSE;
}
lpOALFnTable->alBufferData = (LPALBUFFERDATA)alBufferData;
if (lpOALFnTable->alBufferData == NULL)
{
warn("Failed to retrieve 'alBufferData' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetBufferi = (LPALGETBUFFERI)alGetBufferi;
if (lpOALFnTable->alGetBufferi == NULL)
{
warn("Failed to retrieve 'alGetBufferi' function address\n");
return AL_FALSE;
}
lpOALFnTable->alGetBufferf = (LPALGETBUFFERF)alGetBufferf;
if (lpOALFnTable->alGetBufferf == NULL)
{
warn("Failed to retrieve 'alGetBufferf' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourceQueueBuffers = (LPALSOURCEQUEUEBUFFERS)alSourceQueueBuffers;
if (lpOALFnTable->alSourceQueueBuffers == NULL)
{
warn("Failed to retrieve 'alSourceQueueBuffers' function address\n");
return AL_FALSE;
}
lpOALFnTable->alSourceUnqueueBuffers = (LPALSOURCEUNQUEUEBUFFERS)alSourceUnqueueBuffers;
if (lpOALFnTable->alSourceUnqueueBuffers == NULL)
{
warn("Failed to retrieve 'alSourceUnqueueBuffers' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDistanceModel = (LPALDISTANCEMODEL)alDistanceModel;
if (lpOALFnTable->alDistanceModel == NULL)
{
warn("Failed to retrieve 'alDistanceModel' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDopplerFactor = (LPALDOPPLERFACTOR)alDopplerFactor;
if (lpOALFnTable->alDopplerFactor == NULL)
{
warn("Failed to retrieve 'alDopplerFactor' function address\n");
return AL_FALSE;
}
lpOALFnTable->alDopplerVelocity = (LPALDOPPLERVELOCITY)alDopplerVelocity;
if (lpOALFnTable->alDopplerVelocity == NULL)
{
warn("Failed to retrieve 'alDopplerVelocity' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetString = (LPALCGETSTRING)alcGetString;
if (lpOALFnTable->alcGetString == NULL)
{
warn("Failed to retrieve 'alcGetString' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetIntegerv = (LPALCGETINTEGERV)alcGetIntegerv;
if (lpOALFnTable->alcGetIntegerv == NULL)
{
warn("Failed to retrieve 'alcGetIntegerv' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcOpenDevice = (LPALCOPENDEVICE)alcOpenDevice;
if (lpOALFnTable->alcOpenDevice == NULL)
{
warn("Failed to retrieve 'alcOpenDevice' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcCloseDevice = (LPALCCLOSEDEVICE)alcCloseDevice;
if (lpOALFnTable->alcCloseDevice == NULL)
{
warn("Failed to retrieve 'alcCloseDevice' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcCreateContext = (LPALCCREATECONTEXT)alcCreateContext;
if (lpOALFnTable->alcCreateContext == NULL)
{
warn("Failed to retrieve 'alcCreateContext' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcMakeContextCurrent = (LPALCMAKECONTEXTCURRENT)alcMakeContextCurrent;
if (lpOALFnTable->alcMakeContextCurrent == NULL)
{
warn("Failed to retrieve 'alcMakeContextCurrent' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcProcessContext = (LPALCPROCESSCONTEXT)alcProcessContext;
if (lpOALFnTable->alcProcessContext == NULL)
{
warn("Failed to retrieve 'alcProcessContext' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetCurrentContext = (LPALCGETCURRENTCONTEXT)alcGetCurrentContext;
if (lpOALFnTable->alcGetCurrentContext == NULL)
{
warn("Failed to retrieve 'alcGetCurrentContext' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetContextsDevice = (LPALCGETCONTEXTSDEVICE)alcGetContextsDevice;
if (lpOALFnTable->alcGetContextsDevice == NULL)
{
warn("Failed to retrieve 'alcGetContextsDevice' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcSuspendContext = (LPALCSUSPENDCONTEXT)alcSuspendContext;
if (lpOALFnTable->alcSuspendContext == NULL)
{
warn("Failed to retrieve 'alcSuspendContext' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcDestroyContext = (LPALCDESTROYCONTEXT)alcDestroyContext;
if (lpOALFnTable->alcDestroyContext == NULL)
{
warn("Failed to retrieve 'alcDestroyContext' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetError = (LPALCGETERROR)alcGetError;
if (lpOALFnTable->alcGetError == NULL)
{
warn("Failed to retrieve 'alcGetError' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcIsExtensionPresent = (LPALCISEXTENSIONPRESENT)alcIsExtensionPresent;
if (lpOALFnTable->alcIsExtensionPresent == NULL)
{
warn("Failed to retrieve 'alcIsExtensionPresent' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetProcAddress = (LPALCGETPROCADDRESS)alcGetProcAddress;
if (lpOALFnTable->alcGetProcAddress == NULL)
{
warn("Failed to retrieve 'alcGetProcAddress' function address\n");
return AL_FALSE;
}
lpOALFnTable->alcGetEnumValue = (LPALCGETENUMVALUE)alcGetEnumValue;
if (lpOALFnTable->alcGetEnumValue == NULL)
{
warn("Failed to retrieve 'alcGetEnumValue' function address\n");
return AL_FALSE;
}
return AL_TRUE;
}
ALvoid UnloadOAL10Library()
{
// TODO: Implement this.
}
| {
"content_hash": "82202363589fd6edd87097050554d550",
"timestamp": "",
"source": "github",
"line_count": 414,
"max_line_length": 92,
"avg_line_length": 36.06038647342995,
"alnum_prop": 0.6711099202893697,
"repo_name": "astrellon/Rouge",
"id": "ab8899a31b2ba33538c8f561f7f1280af80c8068",
"size": "16346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sfx/openal/nix/LoadOAL.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "40457"
},
{
"name": "C",
"bytes": "2674932"
},
{
"name": "C++",
"bytes": "1605811"
},
{
"name": "CSS",
"bytes": "1314"
},
{
"name": "GLSL",
"bytes": "982"
},
{
"name": "Lua",
"bytes": "44082"
},
{
"name": "Makefile",
"bytes": "14762"
},
{
"name": "Python",
"bytes": "23613"
}
],
"symlink_target": ""
} |
var assert = require( 'assert' );
before( function () {
describe.account = process.env.ACCOUNT;
describe.url = process.env.URL;
describe.ok = function ( output ) {
assert.ok( output.ok );
};
describe.not = function ( done ) {
return function () {
done( new Error( 'Should not be OK' ) );
};
};
describe.fail = function ( done ) {
throw new Error( 'Should fail' );
};
} );
| {
"content_hash": "58bc9461ebe57e940dade152c6b54dde",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 46,
"avg_line_length": 18.90909090909091,
"alnum_prop": 0.5793269230769231,
"repo_name": "mobilcom-debitel/edge-cli",
"id": "47eb9c89d2c9fceea0114ebcaad8f65e21696ef7",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/suite.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "61824"
}
],
"symlink_target": ""
} |
"""
Unit tests for volume views.
"""
import boto.ec2.volume
import mox
from django.core.urlresolvers import reverse
from django_nova import forms
from django_nova.tests.view_tests.base import (BaseProjectViewTests,
TEST_PROJECT)
TEST_VOLUME = 'vol-0000001'
class VolumeTests(BaseProjectViewTests):
def test_index(self):
instance_id = 'i-abcdefgh'
volume = boto.ec2.volume.Volume()
volume.id = TEST_VOLUME
volume.displayName = TEST_VOLUME
volume.size = 1
self.mox.StubOutWithMock(self.project, 'get_volumes')
self.mox.StubOutWithMock(forms, 'get_available_volume_choices')
self.mox.StubOutWithMock(forms, 'get_instance_choices')
self.project.get_volumes().AndReturn([])
forms.get_available_volume_choices(mox.IgnoreArg()).AndReturn(
self.create_available_volume_choices([volume]))
forms.get_instance_choices(mox.IgnoreArg()).AndReturn(
self.create_instance_choices([instance_id]))
self.mox.ReplayAll()
response = self.client.get(reverse('nova_volumes',
args=[TEST_PROJECT]))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'django_nova/volumes/index.html')
self.assertEqual(len(response.context['volumes']), 0)
self.mox.VerifyAll()
def test_add_get(self):
self.mox.ReplayAll()
res = self.client.get(reverse('nova_volumes_add', args=[TEST_PROJECT]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_add_post(self):
vol = boto.ec2.volume.Volume()
vol.name = TEST_VOLUME
vol.displayName = TEST_VOLUME
vol.size = 1
self.mox.StubOutWithMock(self.project, 'create_volume')
self.project.create_volume(vol.size, vol.name, vol.name).AndReturn(vol)
self.mox.ReplayAll()
url = reverse('nova_volumes_add', args=[TEST_PROJECT])
data = {'size': '1',
'nickname': TEST_VOLUME,
'description': TEST_VOLUME}
res = self.client.post(url, data)
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_delete_get(self):
self.mox.ReplayAll()
res = self.client.get(reverse('nova_volumes_delete',
args=[TEST_PROJECT, TEST_VOLUME]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_delete_post(self):
self.mox.StubOutWithMock(self.project, 'delete_volume')
self.project.delete_volume(TEST_VOLUME).AndReturn(True)
self.mox.ReplayAll()
res = self.client.post(reverse('nova_volumes_delete',
args=[TEST_PROJECT, TEST_VOLUME]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_attach_get(self):
self.mox.ReplayAll()
res = self.client.get(reverse('nova_volumes_attach',
args=[TEST_PROJECT]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_attach_post(self):
volume = boto.ec2.volume.Volume()
volume.id = TEST_VOLUME
volume.displayName = TEST_VOLUME
volume.size = 1
instance_id = 'i-abcdefgh'
device = '/dev/vdb'
self.mox.StubOutWithMock(self.project, 'attach_volume')
self.mox.StubOutWithMock(forms, 'get_available_volume_choices')
self.mox.StubOutWithMock(forms, 'get_instance_choices')
self.project.attach_volume(TEST_VOLUME, instance_id, device) \
.AndReturn(True)
forms.get_available_volume_choices(mox.IgnoreArg()).AndReturn(
self.create_available_volume_choices([volume]))
forms.get_instance_choices(mox.IgnoreArg()).AndReturn(
self.create_instance_choices([instance_id]))
self.mox.ReplayAll()
url = reverse('nova_volumes_attach', args=[TEST_PROJECT])
data = {'volume': TEST_VOLUME,
'instance': instance_id,
'device': device}
res = self.client.post(url, data)
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_detach_get(self):
self.mox.ReplayAll()
res = self.client.get(reverse('nova_volumes_detach',
args=[TEST_PROJECT, TEST_VOLUME]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
def test_detach_post(self):
self.mox.StubOutWithMock(self.project, 'detach_volume')
self.project.detach_volume(TEST_VOLUME).AndReturn(True)
self.mox.ReplayAll()
res = self.client.post(reverse('nova_volumes_detach',
args=[TEST_PROJECT, TEST_VOLUME]))
self.assertRedirectsNoFollow(res, reverse('nova_volumes',
args=[TEST_PROJECT]))
self.mox.VerifyAll()
| {
"content_hash": "8dbfc8ac8483d9fa0158f9b8717fdff0",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 79,
"avg_line_length": 37.83552631578947,
"alnum_prop": 0.5677273517649104,
"repo_name": "sleepsonthefloor/openstack-dashboard",
"id": "cd917406063aa397d89e56965d15bd0e7468a3bf",
"size": "6528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "django-nova/src/django_nova/tests/view_tests/volume_tests.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "42576"
},
{
"name": "Python",
"bytes": "197049"
},
{
"name": "Shell",
"bytes": "325"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='../../../../../../../../../test.xsl'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE Test SYSTEM '../../../../../../../../../test.dtd'>
<Test ID="Xrun" date-of-creation="2005-09-23" timeout="1">
<APITestDescription>
<Description>
</Description>
</APITestDescription>
<Keyword name="cmdline testing"/>
<Source name="Xrun.xml"/>
<Modification date="2005-09-23" />
<Runner ID="Execute">
<Param name="toRun" value="$TestedRuntime">
<Option name="-Xruntestlib"/>
<Option name="-cp" value="$CP"/>
<Option name="CommonTest"/>
</Param>
</Runner>
</Test>
| {
"content_hash": "34c5381a44a79b83704a578d7fc1edc3",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 77,
"avg_line_length": 42.421052631578945,
"alnum_prop": 0.6054590570719603,
"repo_name": "freeVM/freeVM",
"id": "4225441b53b9e3e64c1791b5939779fb84aa7470",
"size": "1612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/vm/cli/Xrun/Xrun.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "116828"
},
{
"name": "C",
"bytes": "17860389"
},
{
"name": "C++",
"bytes": "19007206"
},
{
"name": "CSS",
"bytes": "217777"
},
{
"name": "Java",
"bytes": "152108632"
},
{
"name": "Objective-C",
"bytes": "106412"
},
{
"name": "Objective-J",
"bytes": "11029421"
},
{
"name": "Perl",
"bytes": "305690"
},
{
"name": "Scilab",
"bytes": "34"
},
{
"name": "Shell",
"bytes": "153821"
},
{
"name": "XSLT",
"bytes": "152859"
}
],
"symlink_target": ""
} |
"""Watchmaker module."""
from __future__ import (absolute_import, division, print_function,
unicode_literals, with_statement)
import collections
import datetime
import logging
import os
import platform
import re
import subprocess
import oschmod
import pkg_resources
import setuptools
import yaml
from compatibleversion import check_version
import watchmaker.utils
from watchmaker import static
from watchmaker.exceptions import InvalidValueError, WatchmakerError
from watchmaker.logger import log_system_details
from watchmaker.managers.worker_manager import (LinuxWorkersManager,
WindowsWorkersManager)
from watchmaker.utils import urllib
def _extract_version(package_name):
try:
return pkg_resources.get_distribution(package_name).version
except pkg_resources.DistributionNotFound:
_conf = setuptools.config.read_configuration(
os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
'setup.cfg'
)
)
return _conf['metadata']['version']
def _version_info(app_name, version):
return '{0}/{1} Python/{2} {3}/{4}'.format(
app_name,
version,
platform.python_version(),
platform.system(),
platform.release())
__version__ = _extract_version('watchmaker')
VERSION_INFO = _version_info('Watchmaker', __version__)
class Arguments(dict):
"""
Create an arguments object for the :class:`watchmaker.Client`.
Args:
config_path: (:obj:`str`)
Path or URL to the Watchmaker configuration
file. If ``None``, the default config.yaml file is used.
(*Default*: ``None``)
log_dir: (:obj:`str`)
Path to a directory. If set, Watchmaker logs to a file named
``watchmaker.log`` in the specified directory. Both the directory
and the file will be created if necessary. If the file already
exists, Watchmaker appends to it rather than overwriting it. If
this argument evaluates to ``False``, then logging to a file is
disabled. Watchmaker will always output to stdout/stderr.
Additionaly, Watchmaker workers may use this directory to keep
other log files.
(*Default*: ``None``)
no_reboot: (:obj:`bool`)
Switch to control whether to reboot the system upon a successful
execution of :func:`watchmaker.Client.install`. When this parameter
is set, Watchmaker will suppress the reboot. Watchmaker
automatically suppresses the reboot if it encounters an error.
(*Default*: ``False``)
log_level: (:obj:`str`)
Level to log at. Case-insensitive. Valid options include,
from least to most verbose:
- ``critical``
- ``error``
- ``warning``
- ``info``
- ``debug``
.. important::
For all **Keyword Arguments**, below, the default value of ``None``
means Watchmaker will get the value from the configuration file. Be
aware that ``None`` and ``'None'`` are two different values, with
different meanings and effects.
Keyword Arguments:
admin_groups: (:obj:`str`)
Set a salt grain that specifies the domain
_groups_ that should have root privileges on Linux or admin
privileges on Windows. Value must be a colon-separated string. On
Linux, use the ``^`` to denote spaces in the group name.
(*Default*: ``None``)
.. code-block:: python
admin_groups = "group1:group2"
# (Linux only) The group names must be lowercased. Also, if
# there are spaces in a group name, replace the spaces with a
# '^'.
admin_groups = "space^out"
# (Windows only) No special capitalization nor syntax
# requirements.
admin_groups = "Space Out"
admin_users: (:obj:`str`)
Set a salt grain that specifies the domain
_users_ that should have root privileges on Linux or admin
privileges on Windows. Value must be a colon-separated string.
(*Default*: ``None``)
.. code-block:: python
admin_users = "user1:user2"
computer_name: (:obj:`str`)
Set a salt grain that specifies the computername to apply to the
system.
(*Default*: ``None``)
environment: (:obj:`str`)
Set a salt grain that specifies the environment in which the system
is being built. For example: ``dev``, ``test``, or ``prod``.
(*Default*: ``None``)
salt_states: (:obj:`str`)
Comma-separated string of salt states to apply. A value of
``None`` will not apply any salt states. A value of ``'Highstate'``
will apply the salt highstate.
(*Default*: ``None``)
ou_path: (:obj:`str`)
Set a salt grain that specifies the full DN of the OU where the
computer account will be created when joining a domain.
(*Default*: ``None``)
.. code-block:: python
ou_path="OU=Super Cool App,DC=example,DC=com"
extra_arguments: (:obj:`list`)
A list of extra arguments to be merged into the worker
configurations. The list must be formed as pairs of named arguments
and values. Any leading hypens in the argument name are stripped.
(*Default*: ``[]``)
.. code-block:: python
extra_arguments=['--arg1', 'value1', '--arg2', 'value2']
# This list would be converted to the following dict and merged
# into the parameters passed to the worker configurations:
{'arg1': 'value1', 'arg2': 'value2'}
"""
DEFAULT_VALUE = 'WAM_NONE'
def __init__(
self,
config_path=None,
log_dir=None,
no_reboot=False,
log_level=None,
*args,
**kwargs
):
super(Arguments, self).__init__(*args, **kwargs)
self.config_path = config_path
self.log_dir = log_dir
self.no_reboot = no_reboot
self.log_level = log_level
self.admin_groups = watchmaker.utils.clean_none(
kwargs.pop('admin_groups', None) or Arguments.DEFAULT_VALUE)
self.admin_users = watchmaker.utils.clean_none(
kwargs.pop('admin_users', None) or Arguments.DEFAULT_VALUE)
self.computer_name = watchmaker.utils.clean_none(
kwargs.pop('computer_name', None) or Arguments.DEFAULT_VALUE)
self.environment = watchmaker.utils.clean_none(
kwargs.pop('environment', None) or Arguments.DEFAULT_VALUE)
self.salt_states = watchmaker.utils.clean_none(
kwargs.pop('salt_states', None) or Arguments.DEFAULT_VALUE)
self.ou_path = watchmaker.utils.clean_none(
kwargs.pop('ou_path', None) or Arguments.DEFAULT_VALUE)
# Parse extra_arguments passed as `--argument=value` into separate
# tokens, ['--argument', 'value']. This way the `=` as the separator is
# treated the same as the ` ` as the separator, e.g. `--argument value`
extra_arguments = []
for item in kwargs.pop('extra_arguments', None) or []:
match = re.match('^(?P<arg>-+.*?)=(?P<val>.*)', item)
if match:
# item is using '=' to separate argument name and value
extra_arguments.extend([
match.group('arg'),
watchmaker.utils.clean_none(
match.group('val') or Arguments.DEFAULT_VALUE
)
])
elif item.startswith('-'):
# item is the argument name
extra_arguments.extend([item])
else:
# item is the argument value
extra_arguments.extend([
watchmaker.utils.clean_none(
item or Arguments.DEFAULT_VALUE
)
])
self.extra_arguments = extra_arguments
def __getattr__(self, attr):
"""Support attr-notation for getting dict contents."""
return super(Arguments, self).__getitem__(attr)
def __setattr__(self, attr, value):
"""Support attr-notation for setting dict contents."""
super(Arguments, self).__setitem__(attr, value)
class Client(object):
"""
Prepare a system for setup and installation.
Keyword Arguments:
arguments: (:obj:`Arguments`)
A dictionary of arguments. See :class:`watchmaker.Arguments`.
"""
def __init__(self, arguments):
self.log = logging.getLogger(
'{0}.{1}'.format(__name__, self.__class__.__name__)
)
# Pop extra_arguments now so we can log it separately
extra_arguments = arguments.pop('extra_arguments', [])
header = ' WATCHMAKER RUN '
header = header.rjust((40 + len(header) // 2), '#').ljust(80, '#')
self.log.info(header)
self.log.debug('Watchmaker Version: %s', __version__)
self.log.debug('Parameters: %s', arguments)
self.log.debug('Extra Parameters: %s', extra_arguments)
# Pop remaining arguments used by watchmaker.Client itself
self.default_config = os.path.join(static.__path__[0], 'config.yaml')
self.no_reboot = arguments.pop('no_reboot', False)
self.config_path = arguments.pop('config_path')
self.log_dir = arguments.pop('log_dir')
self.log_level = arguments.pop('log_level')
log_system_details(self.log)
# Get the system params
self.system = platform.system().lower()
self._set_system_params()
self.log.debug('System Parameters: %s', self.system_params)
# All remaining arguments are worker_args
worker_args = arguments
# Convert extra_arguments to a dict and merge it with worker_args.
# Leading hypens are removed, and other hyphens are converted to
# underscores
worker_args.update(dict(
(k.lstrip('-').replace('-', '_'), v) for k, v in zip(
*[iter(extra_arguments)] * 2)
))
try:
# Set self.worker_args, removing `None` values from worker_args
self.worker_args = dict(
(k, yaml.safe_load('null' if v is None else v))
for k, v in worker_args.items()
if v != Arguments.DEFAULT_VALUE
)
except yaml.YAMLError as exc:
if hasattr(exc, "problem_mark"):
msg = (
"Failed to parse argument value as YAML. Check the format "
"and/or properly quote the value when using the CLI to "
"account for shell interpolation. YAML error: {0}"
).format(str(exc))
self.log.critical(msg)
raise InvalidValueError(msg)
raise
self.config = self._get_config()
def _get_config(self):
"""
Read and validate configuration data for installation.
Returns:
:obj:`collections.OrderedDict`: Returns the data from the the YAML
configuration file, scoped to the value of ``self.system`` and
merged with the value of the ``"All"`` key.
"""
if not self.config_path:
self.log.warning(
'User did not supply a config. Using the default config.'
)
self.config_path = self.default_config
else:
self.log.info('User supplied config being used.')
# Convert a local config path to a URI
self.config_path = watchmaker.utils.uri_from_filepath(self.config_path)
# Get the raw config data
data = ''
try:
data = watchmaker.utils.urlopen_retry(self.config_path).read()
except (ValueError, urllib.error.URLError):
msg = (
'Could not read config file from the provided value "{0}"! '
'Check that the config is available.'.format(self.config_path)
)
self.log.critical(msg)
raise
config_full = yaml.safe_load(data)
try:
config_all = config_full.get('all', [])
config_system = config_full.get(self.system, [])
config_version_specifier = config_full.get(
'watchmaker_version', None)
except AttributeError:
msg = 'Malformed config file. Must be a dictionary.'
self.log.critical(msg)
raise
# If both config and config_system are empty, raise
if not config_system and not config_all:
msg = 'Malformed config file. No workers for this system.'
self.log.critical(msg)
raise WatchmakerError(msg)
if config_version_specifier and not check_version(
watchmaker.__version__, config_version_specifier):
msg = (
'Watchmaker version {} is not compatible with the config '
'file (watchmaker_version = {})').format(
watchmaker.__version__, config_version_specifier)
self.log.critical(msg)
raise WatchmakerError(msg)
# Merge the config data, preserving the listed order of workers.
# The worker order from config_system has precedence over config_all.
# This is managed by adding config_system to the config first, using
# the loop order, e.g. config_system + config_all. In the loop, if the
# worker is already in the config, it is always the worker from
# config_system.
# To also preserve precedence of worker options from config_system, the
# worker_config from config_all is updated with the config from
# config_system, then the config is replaced with the worker_config.
config = collections.OrderedDict()
for worker in config_system + config_all:
try:
# worker is a single-key dict, where the key is the name of the
# worker and the value is the worker parameters. we need to
# test if the worker is already in the config, but a dict is
# is not hashable so cannot be tested directly with
# `if worker not in config`. this bit of ugliness extracts the
# key and its value so we can use them directly.
worker_name, worker_config = list(worker.items())[0]
if worker_name not in config:
# Add worker to config
config[worker_name] = {'config': worker_config}
self.log.debug('%s config: %s', worker_name, worker_config)
else:
# Worker is present in both config_system and config_all,
# config[worker_name]['config'] is from config_system,
# worker_config is from config_all
worker_config.update(config[worker_name]['config'])
config[worker_name]['config'] = worker_config
self.log.debug(
'%s extra config: %s',
worker_name, worker_config
)
# Need to (re)merge cli worker args so they override
config[worker_name]['__merged'] = False
if not config[worker_name].get('__merged'):
# Merge worker_args into config params
config[worker_name]['config'].update(self.worker_args)
config[worker_name]['__merged'] = True
except Exception:
msg = (
'Failed to merge worker config; worker={0}'
.format(worker)
)
self.log.critical(msg)
raise
self.log.debug(
'Command-line arguments merged into worker configs: %s',
self.worker_args
)
return config
def _get_linux_system_params(self):
"""Set ``self.system_params`` attribute for Linux systems."""
params = {}
params['prepdir'] = os.path.join(
'{0}'.format(self.system_drive), 'usr', 'tmp', 'watchmaker')
params['readyfile'] = os.path.join(
'{0}'.format(self.system_drive), 'var', 'run', 'system-is-ready')
params['logdir'] = os.path.join(
'{0}'.format(self.system_drive), 'var', 'log')
params['workingdir'] = os.path.join(
'{0}'.format(params['prepdir']), 'workingfiles')
params['restart'] = 'shutdown -r +1 &'
return params
def _get_windows_system_params(self):
"""Set ``self.system_params`` attribute for Windows systems."""
params = {}
# os.path.join does not produce path as expected when first string
# ends in colon; so using a join on the sep character.
params['prepdir'] = os.path.sep.join([self.system_drive, 'Watchmaker'])
params['readyfile'] = os.path.join(
'{0}'.format(params['prepdir']), 'system-is-ready')
params['logdir'] = os.path.join(
'{0}'.format(params['prepdir']), 'Logs')
params['workingdir'] = os.path.join(
'{0}'.format(params['prepdir']), 'WorkingFiles')
params['shutdown_path'] = os.path.join(
'{0}'.format(os.environ['SYSTEMROOT']), 'system32', 'shutdown.exe')
params['restart'] = params["shutdown_path"] + \
' /r /t 30 /d p:2:4 /c ' + \
'"Watchmaker complete. Rebooting computer."'
return params
def _set_system_params(self):
"""Set OS-specific attributes."""
if 'linux' in self.system:
self.system_drive = '/'
self.workers_manager = LinuxWorkersManager
self.system_params = self._get_linux_system_params()
os.umask(0o077)
elif 'windows' in self.system:
self.system_drive = os.environ['SYSTEMDRIVE']
self.workers_manager = WindowsWorkersManager
self.system_params = self._get_windows_system_params()
else:
msg = 'System, {0}, is not recognized?'.format(self.system)
self.log.critical(msg)
raise WatchmakerError(msg)
if self.log_dir:
self.system_params['logdir'] = self.log_dir
def install(self):
"""
Execute the watchmaker workers against the system.
Upon successful execution, the system will be properly provisioned,
according to the defined configuration and workers.
"""
self.log.info('Start time: %s', datetime.datetime.now())
self.log.info('Workers to execute: %s', self.config.keys())
# Create watchmaker directories
try:
os.makedirs(self.system_params['workingdir'])
oschmod.set_mode(self.system_params['prepdir'], 0o700)
except OSError:
if not os.path.exists(self.system_params['workingdir']):
msg = (
'Unable to create directory - {0}'
.format(self.system_params['workingdir'])
)
self.log.critical(msg)
raise
workers_manager = self.workers_manager(
system_params=self.system_params,
workers=self.config
)
try:
workers_manager.worker_cadence()
except Exception:
msg = 'Execution of the workers cadence has failed.'
self.log.critical(msg)
raise
if self.no_reboot:
self.log.info(
'Detected `no-reboot` switch. System will not be '
'rebooted.'
)
else:
self.log.info(
'Reboot scheduled. System will reboot after the script '
'exits.'
)
subprocess.call(self.system_params['restart'], shell=True)
self.log.info('Stop time: %s', datetime.datetime.now())
| {
"content_hash": "849d817eb65d3f7ccd82b407d2bfa68e",
"timestamp": "",
"source": "github",
"line_count": 516,
"max_line_length": 79,
"avg_line_length": 39.55813953488372,
"alnum_prop": 0.5641289437585734,
"repo_name": "plus3it/watchmaker",
"id": "daefc44b373787b02f7df7a07fdb73839d457198",
"size": "20436",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/watchmaker/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1853"
},
{
"name": "Dockerfile",
"bytes": "965"
},
{
"name": "Python",
"bytes": "148949"
},
{
"name": "Shell",
"bytes": "3946"
}
],
"symlink_target": ""
} |
var gulp = require('gulp');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var onBabelError = require('./babel-error.js');
var rename = require('gulp-rename');
var webpackStream = require('webpack-stream');
var webpack2 = require('webpack');
var named = require('vinyl-named');
var CONFIG = require('../config.js');
// Compiles JavaScript into a single file
gulp.task('javascript', ['javascript:foundation', 'javascript:deps', 'javascript:docs']);
// NOTE: This sets up all imports from within Foundation as externals, for the purpose
// of replicating the "drop in dist file" approach of prior versions.
// THIS IS NOT RECOMMENDED FOR MOST USERS. Chances are you either want everything
// (just throw in foundation.js or foundation.min.js) or you should be using a build
// system.
var pluginsAsExternals = {
'jquery': 'jQuery',
'./foundation.core': '{Foundation: window.Foundation}',
'./foundation.util.core' : '{rtl: window.Foundation.rtl, GetYoDigits: window.Foundation.GetYoDigits, transitionend: window.Foundation.transitionend, RegExpEscape: window.Foundation.RegExpEscape}',
'./foundation.util.imageLoader' : '{onImagesLoaded: window.Foundation.onImagesLoaded}',
'./foundation.util.keyboard' : '{Keyboard: window.Foundation.Keyboard}',
'./foundation.util.mediaQuery' : '{MediaQuery: window.Foundation.MediaQuery}',
'./foundation.util.motion' : '{Motion: window.Foundation.Motion, Move: window.Foundation.Move}',
'./foundation.util.nest' : '{Nest: window.Foundation.Nest}',
'./foundation.util.timer' : '{Timer: window.Foundation.Timer}',
'./foundation.util.touch' : '{Touch: window.Foundation.Touch}',
'./foundation.util.box' : '{Box: window.Foundation.Box}',
'./foundation.plugin' : '{Plugin: window.Foundation.Plugin}',
'./foundation.dropdownMenu' : '{DropdownMenu: window.Foundation.DropdownMenu}',
'./foundation.drilldown' : '{Drilldown: window.Foundation.Drilldown}',
'./foundation.accordionMenu' : '{AccordionMenu: window.Foundation.AccordionMenu}',
'./foundation.accordion' : '{Accordion: window.Foundation.Accordion}',
'./foundation.tabs' : '{Tabs: window.Foundation.Tabs}',
'./foundation.smoothScroll' : '{SmoothScroll: window.Foundation.SmoothScroll}',
};
var webpackConfig = {
externals: {
'jquery': 'jQuery'
},
module: {
rules: [
{
test: /.js$/,
use: [
{
loader: 'babel-loader'
}
]
}
]
},
output: {
// ---
// FIXME: to resolve before the next release
// Temporary disable UMD bundling, waiting for a way to import plugins are externals
// See https://github.com/zurb/foundation-sites/pull/10903
// ---
// libraryTarget: 'umd',
}
}
// Core has to be dealt with slightly differently due to bootstrapping externals
// and the dependency on foundation.util.core
//
gulp.task('javascript:plugin-core', function() {
return gulp.src('js/entries/plugins/foundation.core.js')
.pipe(named())
.pipe(webpackStream(webpackConfig, webpack2))
.pipe(gulp.dest('_build/assets/js/plugins'));
});
gulp.task('javascript:plugins', ['javascript:plugin-core'], function () {
return gulp.src(['js/entries/plugins/*.js', '!js/entries/plugins/foundation.core.js'])
.pipe(named())
.pipe(webpackStream(Object.assign({}, webpackConfig, { externals: pluginsAsExternals }), webpack2))
.pipe(gulp.dest('_build/assets/js/plugins'));
});
gulp.task('javascript:foundation', ['javascript:plugins'], function() {
return gulp.src('js/entries/foundation.js')
.pipe(named())
.pipe(webpackStream(webpackConfig, webpack2))
.pipe(gulp.dest('_build/assets/js'));
});
//gulp.task('javascript:foundation', function() {
// return gulp.src(CONFIG.JS_FILES)
// .pipe(babel()
// .on('error', onBabelError))
// .pipe(gulp.dest('_build/assets/js/plugins'))
// .pipe(concat('foundation.js'))
// .pipe(gulp.dest('_build/assets/js'));
//});
gulp.task('javascript:deps', function() {
return gulp.src(CONFIG.JS_DEPS)
.pipe(concat('vendor.js'))
.pipe(gulp.dest('_build/assets/js'));
});
gulp.task('javascript:docs', function() {
return gulp.src(CONFIG.JS_DOCS)
.pipe(concat('docs.js'))
.pipe(gulp.dest('_build/assets/js'));
});
| {
"content_hash": "fd15a53f5fe29f0f40a44d24a37abc96",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 198,
"avg_line_length": 39.388888888888886,
"alnum_prop": 0.6793606017865539,
"repo_name": "dragthor/foundation-sites",
"id": "da41933cef7df0deac08fa02b7a0a411aeca616a",
"size": "4254",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "gulp/tasks/javascript.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "356662"
},
{
"name": "HTML",
"bytes": "689544"
},
{
"name": "JavaScript",
"bytes": "820166"
},
{
"name": "Shell",
"bytes": "139"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>MoneyTracker</title>
<base href="/">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body class="hold-transition skin-money-tracker sidebar-mini">
<div class="wrapper">
<mt-root>Loading...</mt-root>
</div>
</body>
</html>
| {
"content_hash": "577b9295307c7feb633386c3b5fa7349",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 105,
"avg_line_length": 34.57692307692308,
"alnum_prop": 0.6618464961067854,
"repo_name": "dirty-mustard/money-tracker-ui",
"id": "e26814dbd30c8a3729a1523626d27c031405622a",
"size": "899",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "100986"
},
{
"name": "HTML",
"bytes": "33102"
},
{
"name": "JavaScript",
"bytes": "3565"
},
{
"name": "TypeScript",
"bytes": "46238"
}
],
"symlink_target": ""
} |
package jstreamserver.ftp;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.unitils.UnitilsJUnit4;
import org.unitils.inject.annotation.TestedObject;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link CustomFileSystemView}
*
* @author Sergey Prilukin
*/
public class CustomFileSystemViewTest extends UnitilsJUnit4 {
@TestedObject
private CustomFileSystemView customFileSystemView;
private Map<String, String> rootDirs;
@Before
public void before() {
rootDirs = new HashMap<String, String>();
rootDirs.put("c", "c:\\");
rootDirs.put("d", "d:\\");
}
@Test
public void testCannotCDUPFromRootDir() throws Exception {
customFileSystemView.setRootDirs(rootDirs);
boolean changed = customFileSystemView.changeWorkingDirectory("..");
assertFalse(changed);
assertEquals(RootFtpDir.ROOT_PATH, customFileSystemView.getWorkingDirectory().getAbsolutePath());
}
@Ignore
public void testChangeToNonASCIIDir() throws Exception {
customFileSystemView.setRootDirs(rootDirs);
boolean changed = customFileSystemView.changeWorkingDirectory("d/test test/папка 1");
assertTrue(changed);
assertEquals("/d/test test/папка 1", customFileSystemView.getWorkingDirectory().getAbsolutePath());
}
@Test
public void testChangeDirRelatively() throws Exception {
customFileSystemView.setRootDirs(rootDirs);
boolean changed = customFileSystemView.changeWorkingDirectory("d/test");
assertTrue(changed);
assertEquals("/d/test", customFileSystemView.getWorkingDirectory().getAbsolutePath());
changed = customFileSystemView.changeWorkingDirectory("./../../d/test/../..");
assertTrue(changed);
assertEquals("/", customFileSystemView.getWorkingDirectory().getAbsolutePath());
}
}
| {
"content_hash": "a23d3b529f7aca024acb1782b99754dd",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 108,
"avg_line_length": 31.65671641791045,
"alnum_prop": 0.6916548797736917,
"repo_name": "sprilukin/jstreamserver",
"id": "cbe3835511bdd984b3a9c7c100b8d341cb692535",
"size": "3270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jstreamserver-war/src/test/java/jstreamserver/ftp/CustomFileSystemViewTest.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "178163"
},
{
"name": "JavaScript",
"bytes": "235873"
}
],
"symlink_target": ""
} |
/* We can use the normal code but we also know the __curbrk is not exported
from ld.so. */
extern void *__curbrk attribute_hidden;
#include <sbrk.c>
| {
"content_hash": "ad50d9bd17e30dd4bc9dfd633ac3582a",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 75,
"avg_line_length": 30.8,
"alnum_prop": 0.6948051948051948,
"repo_name": "endplay/omniplay",
"id": "4713a92694e37183cb4b31d9b943d95b193c059e",
"size": "154",
"binary": false,
"copies": "94",
"ref": "refs/heads/master",
"path": "eglibc-2.15/elf/dl-sbrk.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "4528"
},
{
"name": "Assembly",
"bytes": "17491433"
},
{
"name": "Awk",
"bytes": "79791"
},
{
"name": "Batchfile",
"bytes": "903"
},
{
"name": "C",
"bytes": "444772157"
},
{
"name": "C++",
"bytes": "10631343"
},
{
"name": "GDB",
"bytes": "17950"
},
{
"name": "HTML",
"bytes": "47935"
},
{
"name": "Java",
"bytes": "2193"
},
{
"name": "Lex",
"bytes": "44513"
},
{
"name": "M4",
"bytes": "9029"
},
{
"name": "Makefile",
"bytes": "1758605"
},
{
"name": "Objective-C",
"bytes": "5278898"
},
{
"name": "Perl",
"bytes": "649746"
},
{
"name": "Perl 6",
"bytes": "1101"
},
{
"name": "Python",
"bytes": "585875"
},
{
"name": "RPC",
"bytes": "97869"
},
{
"name": "Roff",
"bytes": "2522798"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "426172"
},
{
"name": "TeX",
"bytes": "283872"
},
{
"name": "UnrealScript",
"bytes": "6143"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "Yacc",
"bytes": "93190"
},
{
"name": "sed",
"bytes": "9202"
}
],
"symlink_target": ""
} |
package com.sumologic.shellbase
import java.io.File
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class ScriptRendererSpec extends CommonWordSpec {
"ScriptRenderer" should {
"convert the arguments to a map" in {
val command = new ScriptRenderer(null, Array("key=value", "key1=value1"))
val props = command.argsToMap
props("key") should be("value")
props("key1") should be("value1")
}
"get the lines of non velocity script" in {
val parser = new ScriptRenderer(new File("src/test/resources/scripts/novelocity"), Array[String]())
val lines: Seq[String] = parser.getLines
lines should contain("do something")
lines should contain("exit")
}
"get the lines of velocity script with keys replaced with values" in {
val parser = new ScriptRenderer(new File("src/test/resources/scripts/velocity"), Array("key1=value1", "key2=value2"))
val lines: Seq[String] = parser.getLines
lines should contain("do something value1")
lines should contain("do something value2")
lines should contain("exit")
}
}
}
| {
"content_hash": "163287ce8a018fc627ff4706ca02f83e",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 123,
"avg_line_length": 36.125,
"alnum_prop": 0.6929065743944637,
"repo_name": "SumoLogic/shellbase",
"id": "6dd13356618202223abf849f19ba0cb9ad87fa08",
"size": "1962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shellbase-core/src/test/scala/com/sumologic/shellbase/ScriptRendererSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "239393"
}
],
"symlink_target": ""
} |
package com.grarak.kerneladiutor.tasker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.grarak.kerneladiutor.BaseActivity;
import com.grarak.kerneladiutor.R;
import com.grarak.kerneladiutor.fragments.tools.ProfileFragment;
import java.util.List;
/**
* Created by willi on 28.07.15.
*/
public class AddProfileActivity extends BaseActivity {
public static final String EXTRA_BUNDLE = "com.twofortyfouram.locale.intent.extra.BUNDLE";
private static final String EXTRA_STRING_BLURB = "com.twofortyfouram.locale.intent.extra.BLURB";
public static final String DIVIDER = "wkefnewnfewp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BundleScrubber.scrub(getIntent());
Bundle localeBundle = getIntent().getBundleExtra(EXTRA_BUNDLE);
BundleScrubber.scrub(localeBundle);
ActionBar actionBar;
if ((actionBar = getSupportActionBar()) != null) {
actionBar.setTitle(getString(R.string.profile));
if (PluginBundleManager.isBundleValid(localeBundle)) {
String message;
if ((message = localeBundle.getString(PluginBundleManager.BUNDLE_EXTRA_STRING_MESSAGE)) != null)
actionBar.setSubtitle(message.split(DIVIDER)[0]);
}
}
setFragment(R.id.content_frame, ProfileFragment.newInstance());
}
@Override
public View getParentView() {
return null;
}
@Override
public int getParentViewId() {
return R.layout.activity_fragment;
}
@Override
public Toolbar getToolbar() {
return (Toolbar) findViewById(R.id.toolbar);
}
public void finish(String name, List < String > commands) {
StringBuilder command = new StringBuilder();
command.append(name).append(DIVIDER);
boolean first = true;
for (String c: commands) {
if (first) first = false;
else command.append(DIVIDER);
command.append(c);
}
Intent resultIntent = new Intent();
Bundle resultBundle = PluginBundleManager.generateBundle(command.toString());
resultIntent.putExtra(EXTRA_BUNDLE, resultBundle);
resultIntent.putExtra(EXTRA_STRING_BLURB, generateBlurb(name));
setResult(RESULT_OK, resultIntent);
finish();
}
private String generateBlurb(String message) {
final int maxBlurbLength = getResources().getInteger(R.integer.twofortyfouram_locale_maximum_blurb_length);
if (message.length() > maxBlurbLength) return message.substring(0, maxBlurbLength);
return message;
}
} | {
"content_hash": "8502df4b24d677fb24bc1fa1eb6e469f",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 115,
"avg_line_length": 31.818181818181817,
"alnum_prop": 0.6767857142857143,
"repo_name": "bhb27/KA27",
"id": "9362e3db7c5353f297290105a885b38ff90da374",
"size": "3470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/grarak/kerneladiutor/tasker/AddProfileActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1279252"
},
{
"name": "Shell",
"bytes": "4459"
}
],
"symlink_target": ""
} |
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* logerr: errx with logging
* Copyright (c) 2006-2021 Roy Marples <roy@marples.name>
* All rights reserved
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/time.h>
#include <errno.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include "logerr.h"
#ifndef LOGERR_SYSLOG_FACILITY
#define LOGERR_SYSLOG_FACILITY LOG_DAEMON
#endif
#ifdef SMALL
#undef LOGERR_TAG
#endif
/* syslog protocol is 1k message max, RFC 3164 section 4.1 */
#define LOGERR_SYSLOGBUF 1024 + sizeof(int) + sizeof(pid_t)
#define UNUSED(a) (void)(a)
struct logctx {
char log_buf[BUFSIZ];
unsigned int log_opts;
int log_fd;
pid_t log_pid;
#ifndef SMALL
FILE *log_file;
#ifdef LOGERR_TAG
const char *log_tag;
#endif
#endif
};
static struct logctx _logctx = {
/* syslog style, but without the hostname or tag. */
.log_opts = LOGERR_LOG | LOGERR_LOG_DATE | LOGERR_LOG_PID,
.log_fd = -1,
.log_pid = 0,
};
#if defined(__linux__)
/* Poor man's getprogname(3). */
static char *_logprog;
static const char *
getprogname(void)
{
const char *p;
/* Use PATH_MAX + 1 to avoid truncation. */
if (_logprog == NULL) {
/* readlink(2) does not append a NULL byte,
* so zero the buffer. */
if ((_logprog = calloc(1, PATH_MAX + 1)) == NULL)
return NULL;
if (readlink("/proc/self/exe", _logprog, PATH_MAX + 1) == -1) {
free(_logprog);
_logprog = NULL;
return NULL;
}
}
if (_logprog[0] == '[')
return NULL;
p = strrchr(_logprog, '/');
if (p == NULL)
return _logprog;
return p + 1;
}
#endif
#ifndef SMALL
/* Write the time, syslog style. month day time - */
static int
logprintdate(FILE *stream)
{
struct timeval tv;
time_t now;
struct tm tmnow;
char buf[32];
if (gettimeofday(&tv, NULL) == -1)
return -1;
now = tv.tv_sec;
if (localtime_r(&now, &tmnow) == NULL)
return -1;
if (strftime(buf, sizeof(buf), "%b %d %T ", &tmnow) == 0)
return -1;
return fprintf(stream, "%s", buf);
}
#endif
__printflike(3, 0) static int
vlogprintf_r(struct logctx *ctx, FILE *stream, const char *fmt, va_list args)
{
int len = 0, e;
va_list a;
#ifndef SMALL
bool log_pid;
#ifdef LOGERR_TAG
bool log_tag;
#endif
if ((stream == stderr && ctx->log_opts & LOGERR_ERR_DATE) ||
(stream != stderr && ctx->log_opts & LOGERR_LOG_DATE))
{
if ((e = logprintdate(stream)) == -1)
return -1;
len += e;
}
#ifdef LOGERR_TAG
log_tag = ((stream == stderr && ctx->log_opts & LOGERR_ERR_TAG) ||
(stream != stderr && ctx->log_opts & LOGERR_LOG_TAG));
if (log_tag) {
if (ctx->log_tag == NULL)
ctx->log_tag = getprogname();
if ((e = fprintf(stream, "%s", ctx->log_tag)) == -1)
return -1;
len += e;
}
#endif
log_pid = ((stream == stderr && ctx->log_opts & LOGERR_ERR_PID) ||
(stream != stderr && ctx->log_opts & LOGERR_LOG_PID));
if (log_pid) {
pid_t pid;
if (ctx->log_pid == 0)
pid = getpid();
else
pid = ctx->log_pid;
if ((e = fprintf(stream, "[%d]", pid)) == -1)
return -1;
len += e;
}
#ifdef LOGERR_TAG
if (log_tag || log_pid)
#else
if (log_pid)
#endif
{
if ((e = fprintf(stream, ": ")) == -1)
return -1;
len += e;
}
#else
UNUSED(ctx);
#endif
va_copy(a, args);
e = vfprintf(stream, fmt, a);
if (fputc('\n', stream) == EOF)
e = -1;
else if (e != -1)
e++;
va_end(a);
return e == -1 ? -1 : len + e;
}
/*
* NetBSD's gcc has been modified to check for the non standard %m in printf
* like functions and warn noisily about it that they should be marked as
* syslog like instead.
* This is all well and good, but our logger also goes via vfprintf and
* when marked as a sysloglike funcion, gcc will then warn us that the
* function should be printflike instead!
* This creates an infinte loop of gcc warnings.
* Until NetBSD solves this issue, we have to disable a gcc diagnostic
* for our fully standards compliant code in the logger function.
*/
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-format-attribute"
#endif
__printflike(2, 0) static int
vlogmessage(int pri, const char *fmt, va_list args)
{
struct logctx *ctx = &_logctx;
int len = 0;
if (ctx->log_fd != -1) {
char buf[LOGERR_SYSLOGBUF];
pid_t pid;
memcpy(buf, &pri, sizeof(pri));
pid = getpid();
memcpy(buf + sizeof(pri), &pid, sizeof(pid));
len = vsnprintf(buf + sizeof(pri) + sizeof(pid),
sizeof(buf) - sizeof(pri) - sizeof(pid),
fmt, args);
if (len != -1)
len = (int)write(ctx->log_fd, buf,
((size_t)++len) + sizeof(pri) + sizeof(pid));
return len;
}
if (ctx->log_opts & LOGERR_ERR &&
(pri <= LOG_ERR ||
(!(ctx->log_opts & LOGERR_QUIET) && pri <= LOG_INFO) ||
(ctx->log_opts & LOGERR_DEBUG && pri <= LOG_DEBUG)))
len = vlogprintf_r(ctx, stderr, fmt, args);
#ifndef SMALL
if (ctx->log_file != NULL &&
(pri != LOG_DEBUG || (ctx->log_opts & LOGERR_DEBUG)))
len = vlogprintf_r(ctx, ctx->log_file, fmt, args);
#endif
if (ctx->log_opts & LOGERR_LOG)
vsyslog(pri, fmt, args);
return len;
}
#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 5))
#pragma GCC diagnostic pop
#endif
__printflike(2, 3) void
logmessage(int pri, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogmessage(pri, fmt, args);
va_end(args);
}
__printflike(2, 0) static void
vlogerrmessage(int pri, const char *fmt, va_list args)
{
int _errno = errno;
char buf[1024];
vsnprintf(buf, sizeof(buf), fmt, args);
logmessage(pri, "%s: %s", buf, strerror(_errno));
errno = _errno;
}
__printflike(2, 3) void
logerrmessage(int pri, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogerrmessage(pri, fmt, args);
va_end(args);
}
void
log_debug(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogerrmessage(LOG_DEBUG, fmt, args);
va_end(args);
}
void
log_debugx(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogmessage(LOG_DEBUG, fmt, args);
va_end(args);
}
void
log_info(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogerrmessage(LOG_INFO, fmt, args);
va_end(args);
}
void
log_infox(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogmessage(LOG_INFO, fmt, args);
va_end(args);
}
void
log_warn(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogerrmessage(LOG_WARNING, fmt, args);
va_end(args);
}
void
log_warnx(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogmessage(LOG_WARNING, fmt, args);
va_end(args);
}
void
log_err(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogerrmessage(LOG_ERR, fmt, args);
va_end(args);
}
void
log_errx(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vlogmessage(LOG_ERR, fmt, args);
va_end(args);
}
int
loggetfd(void)
{
struct logctx *ctx = &_logctx;
return ctx->log_fd;
}
void
logsetfd(int fd)
{
struct logctx *ctx = &_logctx;
ctx->log_fd = fd;
#ifndef SMALL
if (fd != -1 && ctx->log_file != NULL) {
fclose(ctx->log_file);
ctx->log_file = NULL;
}
#endif
}
int
logreadfd(int fd)
{
struct logctx *ctx = &_logctx;
char buf[LOGERR_SYSLOGBUF];
int len, pri;
len = (int)read(fd, buf, sizeof(buf));
if (len == -1)
return -1;
/* Ensure we have pri, pid and a terminator */
if (len < (int)(sizeof(pri) + sizeof(pid_t) + 1) ||
buf[len - 1] != '\0')
{
errno = EINVAL;
return -1;
}
memcpy(&pri, buf, sizeof(pri));
memcpy(&ctx->log_pid, buf + sizeof(pri), sizeof(ctx->log_pid));
logmessage(pri, "%s", buf + sizeof(pri) + sizeof(ctx->log_pid));
ctx->log_pid = 0;
return len;
}
unsigned int
loggetopts(void)
{
struct logctx *ctx = &_logctx;
return ctx->log_opts;
}
void
logsetopts(unsigned int opts)
{
struct logctx *ctx = &_logctx;
ctx->log_opts = opts;
setlogmask(LOG_UPTO(opts & LOGERR_DEBUG ? LOG_DEBUG : LOG_INFO));
}
#ifdef LOGERR_TAG
void
logsettag(const char *tag)
{
#if !defined(SMALL)
struct logctx *ctx = &_logctx;
ctx->log_tag = tag;
#else
UNUSED(tag);
#endif
}
#endif
int
logopen(const char *path)
{
struct logctx *ctx = &_logctx;
int opts = 0;
/* Cache timezone */
tzset();
(void)setvbuf(stderr, ctx->log_buf, _IOLBF, sizeof(ctx->log_buf));
#ifndef SMALL
if (ctx->log_file != NULL) {
fclose(ctx->log_file);
ctx->log_file = NULL;
}
#endif
if (ctx->log_opts & LOGERR_LOG_PID)
opts |= LOG_PID;
openlog(getprogname(), opts, LOGERR_SYSLOG_FACILITY);
if (path == NULL)
return 1;
#ifndef SMALL
if ((ctx->log_file = fopen(path, "ae")) == NULL)
return -1;
setlinebuf(ctx->log_file);
return fileno(ctx->log_file);
#else
errno = ENOTSUP;
return -1;
#endif
}
void
logclose(void)
{
#ifndef SMALL
struct logctx *ctx = &_logctx;
#endif
closelog();
#if defined(__linux__)
free(_logprog);
_logprog = NULL;
#endif
#ifndef SMALL
if (ctx->log_file == NULL)
return;
fclose(ctx->log_file);
ctx->log_file = NULL;
#endif
}
| {
"content_hash": "4dab781e7ff842005bfcdf62aecd706f",
"timestamp": "",
"source": "github",
"line_count": 497,
"max_line_length": 80,
"avg_line_length": 20.6317907444668,
"alnum_prop": 0.6412131850984981,
"repo_name": "rsmarples/dhcpcd",
"id": "7a650e87f2c70b7eabea7f61db7b2cebb208b5db",
"size": "10254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/logerr.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1119882"
},
{
"name": "C++",
"bytes": "11531"
},
{
"name": "Makefile",
"bytes": "14761"
},
{
"name": "Roff",
"bytes": "61698"
},
{
"name": "Shell",
"bytes": "9559"
}
],
"symlink_target": ""
} |
using EasyNetQ.Topology;
namespace EasyNetQ.Consumer
{
public class HandlerCollectionFactory : IHandlerCollectionFactory
{
/// <inheritdoc />
public IHandlerCollection CreateHandlerCollection(IQueue queue)
{
return new HandlerCollection();
}
}
}
| {
"content_hash": "73825ad0e770cd1c201898897bdceae7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 71,
"avg_line_length": 23.384615384615383,
"alnum_prop": 0.6578947368421053,
"repo_name": "zidad/EasyNetQ",
"id": "89b602421dfa9168045ec5c18ce2f65ab9b70953",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/EasyNetQ/Consumer/HandlerCollectionFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "947"
},
{
"name": "C#",
"bytes": "1592649"
},
{
"name": "JavaScript",
"bytes": "1022"
},
{
"name": "PLpgSQL",
"bytes": "2807"
},
{
"name": "TSQL",
"bytes": "5424"
}
],
"symlink_target": ""
} |
<?php
namespace Craft;
class CurrencyPriceFieldType extends BaseFieldType
{
/**
* Returns the name of the fieldtype.
*
* @return mixed
*/
public function getName ()
{
return Craft::t('Currency Price');
}
/**
* Returns the content attribute config.
*
* @return mixed
*/
public function defineContentAttribute ()
{
return [ AttributeType::Mixed, 'model' => 'CurrencyPriceModel' ];
}
/**
* Returns the field's input HTML.
*
* @param string $name
* @param mixed $value
*
* @return string
*/
public function getInputHtml ($name, $value)
{
if ( !$value )
$value = new CurrencyPriceModel();
$id = craft()->templates->formatInputId($name);
$namespacedId = craft()->templates->namespaceInputId($id);
// Include our Javascript & CSS
//craft()->templates->includeCssResource('currencyprice/css/fields/CurrencyPriceFieldType.css');
/* -- Variables to pass down to our rendered template */
$variables = array(
'id' => $id,
'name' => $name,
'namespaceId' => $namespacedId,
'values' => $value,
'enabledCurrencies' => $this->getSettings()->enabledCurrencies,
);
return craft()->templates->render('currencyprice/fields/CurrencyPriceFieldType.twig', $variables);
}
public function getSettingsHtml ()
{
//$enabledCurrencies = $this->getSettings()->enabledCurrencies;
$currencies = $this->getCurrencies();
return craft()->templates->render('currencyprice/CurrencyPrice_Settings', array(
'settings' => $this->getSettings(),
'currencies' => $currencies,
));
}
protected function defineSettings ()
{
return array(
'enabledCurrencies' => [ AttributeType::Mixed, 'default' => [ ] ],
);
}
public function prepSettings ($settings)
{
if ( isset($settings['enabledCurrencies']) ) {
foreach ($settings['enabledCurrencies'] as $currency => $value) {
if ( $value !== '1' ) {
unset($settings['enabledCurrencies'][ $currency ]);
}
}
}
return $settings;
}
/**
* Returns the input value as it should be saved to the database.
*
* @param mixed $value
*
* @return mixed
*/
public function prepValueFromPost ($value)
{
return $value;
}
/**
* Prepares the field's value for use.
*
* @param mixed $value
*
* @return mixed
*/
public function prepValue ($value)
{
return $value;
}
protected function getCurrencies ()
{
// Currency files courtesy of https://github.com/Commercie/currency
$folder = IOHelper::getFolder(CRAFT_PLUGINS_PATH . 'currencyprice/lib/currencies/');
$currencies = [ ];
if ( $folder ) {
$files = $folder->getContents($recursive = false, $filter = '.json');
// Loop through and read
foreach ($files as $file) {
$content = IOHelper::getFileContents($file);
$currencies[] = json_decode($content, true);
}
}
return $currencies;
}
} | {
"content_hash": "51bd38e26e351aef132719f24184e337",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 106,
"avg_line_length": 25.708955223880597,
"alnum_prop": 0.5323657474600871,
"repo_name": "sjelfull/Craft-CurrencyPrice",
"id": "2384dec22c3fdefdbe3dc7c67c2a771175ce20db",
"size": "3975",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "currencyprice/fieldtypes/CurrencyPriceFieldType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "516"
},
{
"name": "HTML",
"bytes": "2591"
},
{
"name": "JavaScript",
"bytes": "5627"
},
{
"name": "PHP",
"bytes": "11621"
}
],
"symlink_target": ""
} |
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>tall background-size: contain; for percent-width-omitted-height.svg</title>
<link rel="author" title="Jeff Walden" href="http://whereswalden.com/" />
<link rel="help" href="http://www.w3.org/TR/css3-background/#the-background-size" />
<link rel="help" href="http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing" />
<link rel="help" href="http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute" />
<meta name="flags" content="svg" />
<style type="text/css">
div
{
width: 256px; height: 768px;
}
#outer
{
border: 1px solid black;
}
#inner
{
background-image: url(percent-width-omitted-height.svg);
background-repeat: no-repeat;
background-size: contain;
}
</style>
</head>
<body>
<div id="outer"><div id="inner"></div></div>
</body>
</html>
| {
"content_hash": "24b2a248772c5acdc37c8da0ca3b9945",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 94,
"avg_line_length": 27.38235294117647,
"alnum_prop": 0.6799140708915145,
"repo_name": "wilebeast/FireFox-OS",
"id": "e454f28fc4138091b62c93dc25f5315935094e88",
"size": "931",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "B2G/gecko/layout/reftests/backgrounds/vector/tall--contain--percent-width-omitted-height.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package cn.sherlock.javax.sound.sampled;
/**
* The <code>Line</code> interface represents a mono or multi-channel
* audio feed. A line is an element of the digital audio
* "pipeline," such as a mixer, an input or output port,
* or a data path into or out of a mixer.
* <p>
* A line can have controls, such as gain, pan, and reverb.
* The controls themselves are instances of classes that extend the
* base <code>{@link Control}</code> class.
* The <code>Line</code> interface provides two accessor methods for
* obtaining the line's controls: <code>{@link #getControls getControls}</code> returns the
* entire set, and <code>{@link #getControl getControl}</code> returns a single control of
* specified type.
* <p>
* Lines exist in various states at different times. When a line opens, it reserves system
* resources for itself, and when it closes, these resources are freed for
* other objects or applications. The <code>{@link #isOpen()}</code> method lets
* you discover whether a line is open or closed.
* An open line need not be processing data, however. Such processing is
* typically initiated by subinterface methods such as
* <code>{@link SourceDataLine#write SourceDataLine.write}</code> and
* <code>{@link TargetDataLine#read TargetDataLine.read}</code>.
*<p>
* You can register an object to receive notifications whenever the line's
* state changes. The object must implement the <code>{@link LineListener}</code>
* interface, which consists of the single method
* <code>{@link LineListener#update update}</code>.
* This method will be invoked when a line opens and closes (and, if it's a
* {@link DataLine}, when it starts and stops).
*<p>
* An object can be registered to listen to multiple lines. The event it
* receives in its <code>update</code> method will specify which line created
* the event, what type of event it was
* (<code>OPEN</code>, <code>CLOSE</code>, <code>START</code>, or <code>STOP</code>),
* and how many sample frames the line had processed at the time the event occurred.
* <p>
* Certain line operations, such as open and close, can generate security
* exceptions if invoked by unprivileged code when the line is a shared audio
* resource.
*
* @author Kara Kytle
*
* @see LineEvent
* @since 1.3
*/
public interface Line extends cn.sherlock.javax.sound.sampled.AutoCloseable {
/**
* Obtains the <code>Line.Info</code> object describing this
* line.
* @return description of the line
*/
public Info getLineInfo();
/**
* Opens the line, indicating that it should acquire any required
* system resources and become operational.
* If this operation
* succeeds, the line is marked as open, and an <code>OPEN</code> event is dispatched
* to the line's listeners.
* <p>
* Note that some lines, once closed, cannot be reopened. Attempts
* to reopen such a line will always result in an <code>LineUnavailableException</code>.
* <p>
* Some types of lines have configurable properties that may affect
* resource allocation. For example, a <code>DataLine</code> must
* be opened with a particular format and buffer size. Such lines
* should provide a mechanism for configuring these properties, such
* as an additional <code>open</code> method or methods which allow
* an application to specify the desired settings.
* <p>
* This method takes no arguments, and opens the line with the current
* settings. For <code>{@link SourceDataLine}</code> and
* <code>{@link TargetDataLine}</code> objects, this means that the line is
* opened with default settings. For a <code>{@link Clip}</code>, however,
* the buffer size is determined when data is loaded. Since this method does not
* allow the application to specify any data to load, an IllegalArgumentException
* is thrown. Therefore, you should instead use one of the <code>open</code> methods
* provided in the <code>Clip</code> interface to load data into the <code>Clip</code>.
* <p>
* For <code>DataLine</code>'s, if the <code>DataLine.Info</code>
* object which was used to retrieve the line, specifies at least
* one fully qualified audio format, the last one will be used
* as the default format.
*
* @throws IllegalArgumentException if this method is called on a Clip instance.
* @throws LineUnavailableException if the line cannot be
* opened due to resource restrictions.
* @throws SecurityException if the line cannot be
* opened due to security restrictions.
*
* @see #close
* @see #isOpen
* @see LineEvent
* @see DataLine
* @see Clip#open(AudioFormat, byte[], int, int)
* @see Clip#open(AudioInputStream)
*/
public void open() throws LineUnavailableException;
/**
* Closes the line, indicating that any system resources
* in use by the line can be released. If this operation
* succeeds, the line is marked closed and a <code>CLOSE</code> event is dispatched
* to the line's listeners.
* @throws SecurityException if the line cannot be
* closed due to security restrictions.
*
* @see #open
* @see #isOpen
* @see LineEvent
*/
public void close();
/**
* Indicates whether the line is open, meaning that it has reserved
* system resources and is operational, although it might not currently be
* playing or capturing sound.
* @return <code>true</code> if the line is open, otherwise <code>false</code>
*
* @see #open()
* @see #close()
*/
public boolean isOpen();
/**
* A <code>Line.Info</code> object contains information about a line.
* The only information provided by <code>Line.Info</code> itself
* is the Java class of the line.
* A subclass of <code>Line.Info</code> adds other kinds of information
* about the line. This additional information depends on which <code>Line</code>
* subinterface is implemented by the kind of line that the <code>Line.Info</code>
* subclass describes.
* <p>
* A <code>Line.Info</code> can be retrieved using various methods of
* the <code>Line</code>, <code>Mixer</code>, and <code>AudioSystem</code>
* interfaces. Other such methods let you pass a <code>Line.Info</code> as
* an argument, to learn whether lines matching the specified configuration
* are available and to obtain them.
*
* @author Kara Kytle
*
* @see Line#getLineInfo
* @see Mixer#getSourceLineInfo
* @see Mixer#getTargetLineInfo
* @see Mixer#getLine <code>Mixer.getLine(Line.Info)</code>
* @see Mixer#getSourceLineInfo(Info) <code>Mixer.getSourceLineInfo(Line.Info)</code>
* @see Mixer#getSourceLineInfo(Info) <code>Mixer.getTargetLineInfo(Line.Info)</code>
* @see Mixer#isLineSupported <code>Mixer.isLineSupported(Line.Info)</code>
* @see AudioSystem#getLine <code>AudioSystem.getLine(Line.Info)</code>
* @see AudioSystem#getSourceLineInfo <code>AudioSystem.getSourceLineInfo(Line.Info)</code>
* @see AudioSystem#getTargetLineInfo <code>AudioSystem.getTargetLineInfo(Line.Info)</code>
* @see AudioSystem#isLineSupported <code>AudioSystem.isLineSupported(Line.Info)</code>
* @since 1.3
*/
public static class Info {
/**
* The class of the line described by the info object.
*/
private final Class lineClass;
/**
* Constructs an info object that describes a line of the specified class.
* This constructor is typically used by an application to
* describe a desired line.
* @param lineClass the class of the line that the new Line.Info object describes
*/
public Info(Class<?> lineClass) {
if (lineClass == null) {
this.lineClass = Line.class;
} else {
this.lineClass = lineClass;
}
}
/**
* Obtains the class of the line that this Line.Info object describes.
* @return the described line's class
*/
public Class<?> getLineClass() {
return lineClass;
}
/**
* Indicates whether the specified info object matches this one.
* To match, the specified object must be identical to or
* a special case of this one. The specified info object
* must be either an instance of the same class as this one,
* or an instance of a sub-type of this one. In addition, the
* attributes of the specified object must be compatible with the
* capabilities of this one. Specifically, the routing configuration
* for the specified info object must be compatible with that of this
* one.
* Subclasses may add other criteria to determine whether the two objects
* match.
*
* @param info the info object which is being compared to this one
* @return <code>true</code> if the specified object matches this one,
* <code>false</code> otherwise
*/
public boolean matches(Info info) {
// $$kk: 08.30.99: is this backwards?
// dataLine.matches(targetDataLine) == true: targetDataLine is always dataLine
// targetDataLine.matches(dataLine) == false
// so if i want to make sure i get a targetDataLine, i need:
// targetDataLine.matches(prospective_match) == true
// => prospective_match may be other things as well, but it is at least a targetDataLine
// targetDataLine defines the requirements which prospective_match must meet.
// "if this Class object represents a declared class, this method returns
// true if the specified Object argument is an instance of the represented
// class (or of any of its subclasses)"
// GainControlClass.isInstance(MyGainObj) => true
// GainControlClass.isInstance(MySpecialGainInterfaceObj) => true
// this_class.isInstance(that_object) => that object can by cast to this class
// => that_object's class may be a subtype of this_class
// => that may be more specific (subtype) of this
// "If this Class object represents an interface, this method returns true
// if the class or any superclass of the specified Object argument implements
// this interface"
// GainControlClass.isInstance(MyGainObj) => true
// GainControlClass.isInstance(GenericControlObj) => may be false
// => that may be more specific
if (! (this.getClass().isInstance(info)) ) {
return false;
}
// this.isAssignableFrom(that) => this is same or super to that
// => this is at least as general as that
// => that may be subtype of this
if (! (getLineClass().isAssignableFrom(info.getLineClass())) ) {
return false;
}
return true;
}
/**
* Obtains a textual description of the line info.
* @return a string description
*/
public String toString() {
String fullPackagePath = "javax.sound.sampled.";
String initialString = new String(getLineClass().toString());
String finalString;
int index = initialString.indexOf(fullPackagePath);
if (index != -1) {
finalString = initialString.substring(0, index) + initialString.substring( (index + fullPackagePath.length()), initialString.length() );
} else {
finalString = initialString;
}
return finalString;
}
} // class Info
} // interface Line
| {
"content_hash": "a63bdc2693fc41c957bb94a7ac36ec48",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 152,
"avg_line_length": 43.12367491166078,
"alnum_prop": 0.6356112749918059,
"repo_name": "KyoSherlock/SherlockMidi",
"id": "99b870f7e9697d1fe176cb01554cebbbc94c5472",
"size": "12359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sherlockmidi/src/main/java/cn/sherlock/javax/sound/sampled/Line.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "950519"
}
],
"symlink_target": ""
} |
Given an integer array, find three numbers whose product is maximum and output the maximum product.
### Example 1:
```
Input: [1,2,3]
Output: 6
```
### Example 2:
```
Input: [1,2,3,4]
Output: 24
```
### Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
#Symantec #BBG #AMZN #RFIN #GS
#Array #Math
#Similar question [#152](../p152m/README.md) [#628](../p628e/README.md)
| {
"content_hash": "be3f1df5523c19d9cf704a5c514f4723",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 105,
"avg_line_length": 23.347826086956523,
"alnum_prop": 0.6815642458100558,
"repo_name": "l33tdaima/l33tdaima",
"id": "9548adc5c5c3afbbbdc91004bf3756f309c42f2f",
"size": "585",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "p628e/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "214858"
},
{
"name": "CMake",
"bytes": "185"
},
{
"name": "Go",
"bytes": "3918"
},
{
"name": "JavaScript",
"bytes": "357357"
},
{
"name": "Kotlin",
"bytes": "893"
},
{
"name": "OCaml",
"bytes": "11241"
},
{
"name": "Python",
"bytes": "534124"
}
],
"symlink_target": ""
} |
import frappe
from frappe.model.document import Document
class OAuthAuthorizationCode(Document):
pass
| {
"content_hash": "7522f809d47db24b8c0b46be16e30ec5",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 42,
"avg_line_length": 17.5,
"alnum_prop": 0.8380952380952381,
"repo_name": "frappe/frappe",
"id": "431d27bc04f1a18503a8a245b1be00bcda431f86",
"size": "193",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "frappe/integrations/doctype/oauth_authorization_code/oauth_authorization_code.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "65093"
},
{
"name": "HTML",
"bytes": "250850"
},
{
"name": "JavaScript",
"bytes": "2523337"
},
{
"name": "Less",
"bytes": "10921"
},
{
"name": "Python",
"bytes": "3618097"
},
{
"name": "SCSS",
"bytes": "261690"
},
{
"name": "Vue",
"bytes": "98456"
}
],
"symlink_target": ""
} |
package laika.rewrite.nav
import cats.instances.map
import laika.ast.Path
import laika.config.Config.ConfigResult
import laika.config.{Config, ConfigDecoder, ConfigEncoder, Key, LaikaKeys}
/** Configuration for a cover image for e-books (EPUB or PDF).
*
* The optional classifier can be used if the `@:select` directive
* is used to produce multiple e-books with slightly different content.
* The classifier would refer to the name of the configured choice,
* or in case of multiple choices, to the combination of their names concatenated with `-`.
*
* @author Jens Halm
*/
case class CoverImage (path: Path, classifier: Option[String] = None)
object CoverImage {
def apply (path: Path, classifier: String): CoverImage = CoverImage(path, Some(classifier))
implicit val decoder: ConfigDecoder[CoverImage] = ConfigDecoder.config.flatMap { config =>
for {
path <- config.get[Path]("path")
classifier <- config.getOpt[String]("classifier")
} yield {
CoverImage(path, classifier)
}
}
implicit val encoder: ConfigEncoder[CoverImage] = ConfigEncoder[CoverImage] { coverImage =>
ConfigEncoder.ObjectBuilder.empty
.withValue("path", coverImage.path)
.withValue("classifier", coverImage.classifier)
.build
}
}
case class CoverImages (default: Option[Path], classified: Map[String, Path]) {
def getImageFor (classifier: String): Option[Path] = classified.get(classifier).orElse(default)
def withFallback (fallback: CoverImages): CoverImages = {
CoverImages(default.orElse(fallback.default), fallback.classified ++ classified)
}
}
object CoverImages {
def forPDF (config: Config): ConfigResult[CoverImages] = extract(config, LaikaKeys.root.child("pdf"), LaikaKeys.root)
def forEPUB (config: Config): ConfigResult[CoverImages] = extract(config, LaikaKeys.root.child("epub"), LaikaKeys.root)
private def extract (config: Config, mainKey: Key, fallbackKey: Key): ConfigResult[CoverImages] = {
def extract (key: Key): ConfigResult[CoverImages] = for {
classified <- config.get[Seq[CoverImage]](key.child(LaikaKeys.coverImages.local), Nil)
default <- config
.getOpt[Path](key.child(LaikaKeys.coverImage.local))
.map(_.orElse(classified.find(_.classifier.isEmpty).map(_.path)))
} yield {
val classifiedMap = classified
.collect { case CoverImage(path, Some(classifier)) => (classifier, path) }
.toMap
CoverImages(default, classifiedMap)
}
for {
mainConf <- extract(mainKey)
fallback <- extract(fallbackKey)
} yield mainConf.withFallback(fallback)
}
}
| {
"content_hash": "efe9d4c9c25e6fea983e8f462ec3a58c",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 121,
"avg_line_length": 34.22784810126582,
"alnum_prop": 0.6900887573964497,
"repo_name": "planet42/Laika",
"id": "c18f3cfc060c6e90756f0a34ec674c198dfbafc4",
"size": "3324",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "core/shared/src/main/scala/laika/rewrite/nav/CoverImage.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "30283"
},
{
"name": "HTML",
"bytes": "369038"
},
{
"name": "JavaScript",
"bytes": "6401"
},
{
"name": "Scala",
"bytes": "2885495"
}
],
"symlink_target": ""
} |
você está em gastos comuns - index | {
"content_hash": "067c5792300800dee64794e08ee3bf31",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 34,
"avg_line_length": 34,
"alnum_prop": 0.7941176470588235,
"repo_name": "IltonS/ContaRestaurante",
"id": "474d2ec7ef7b32c428b7fdb9e954bc0d9ce06408",
"size": "36",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "www/views/GastosComuns/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "15347"
},
{
"name": "C#",
"bytes": "70149"
},
{
"name": "C++",
"bytes": "12306"
},
{
"name": "CSS",
"bytes": "12905"
},
{
"name": "HTML",
"bytes": "64935"
},
{
"name": "Java",
"bytes": "558940"
},
{
"name": "JavaScript",
"bytes": "96715"
},
{
"name": "Objective-C",
"bytes": "334852"
},
{
"name": "QML",
"bytes": "2765"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Get Shit Done Kit Template by Creative Tim</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<link href="bootstrap3/css/bootstrap.css" rel="stylesheet" />
<link href="assets/css/gsdk.css" rel="stylesheet" />
<link href="assets/css/demo.css" rel="stylesheet" />
<!-- Font Awesome -->
<link href="bootstrap3/css/font-awesome.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Grand+Hotel' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="main">
<div class="container">
<!--
<br>
<button type="button" class="btn btn-info">This is a button</button>
-->
</div>
</div>
</body>
<script src="jquery/jquery-1.10.2.js" type="text/javascript"></script>
<script src="assets/js/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>
<script src="bootstrap3/js/bootstrap.js" type="text/javascript"></script>
<script src="assets/js/gsdk-checkbox.js"></script>
<script src="assets/js/gsdk-radio.js"></script>
<script src="assets/js/gsdk-bootstrapswitch.js"></script>
<script src="assets/js/get-shit-done.js"></script>
<script src="assets/js/custom.js"></script>
</html> | {
"content_hash": "b0e8be85405249933d8df98edba726d9",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 109,
"avg_line_length": 35.48936170212766,
"alnum_prop": 0.6354916067146283,
"repo_name": "mishapivo/mishapivo.github.io",
"id": "a1b591f18a85baf99541ee9b3990a63bb91ffb84",
"size": "1668",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aqua-ui-kits/creative_get-shit-done/template.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6083155"
},
{
"name": "HTML",
"bytes": "14081180"
},
{
"name": "JavaScript",
"bytes": "8361872"
},
{
"name": "Python",
"bytes": "32324"
},
{
"name": "Vue",
"bytes": "201514"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "6f71b248800f26f09dec205ea83a1063",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "b9a54355eb2bdafbb27713c253c70fb8735b8ec9",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Cunoniaceae/Weinmannia/Weinmannia baccariniana/Weinmannia baccariniana baccariniana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
if [[ -n "$1" ]]; then
cp -i resources/Artestead.json Artestead.json
else
cp -i resources/Artestead.yaml Artestead.yaml
fi
cp -i resources/after.sh after.sh
cp -i resources/aliases.sh aliases.sh
echo "Artestead initialized!"
| {
"content_hash": "a70e59f89885648854b90f6e5025d553",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 49,
"avg_line_length": 23.5,
"alnum_prop": 0.723404255319149,
"repo_name": "gdmgent/artestead",
"id": "282b46620636eb3f4f20b888255271975186a264",
"size": "256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "init.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "271"
},
{
"name": "PHP",
"bytes": "43926"
},
{
"name": "Ruby",
"bytes": "13429"
},
{
"name": "Shell",
"bytes": "35287"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for aeroflow\source\generators\index.js</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../../../prettify.css" />
<link rel="stylesheet" href="../../../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../../../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../../../index.html">all files</a> / <a href="index.html">aeroflow/source/generators/</a> index.js
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Statements</span>
<span class='fraction'>22/22</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Branches</span>
<span class='fraction'>4/4</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Functions</span>
<span class='fraction'>1/1</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">100% </span>
<span class="quiet">Lines</span>
<span class='fraction'>7/7</span>
</div>
</div>
</div>
<div class='status-line high'></div>
<pre><table class="coverage">
<tr><td class="line-count quiet">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16</td><td class="line-coverage quiet"><span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-yes">1×</span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span>
<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">import customGenerator from './custom';
import emptyGenerator from './empty';
import expandGenerator from './expand';
import randomGenerator from './random';
import rangeGenerator from './range';
import repeatGenerator from './repeat';
export {
customGenerator,
emptyGenerator,
expandGenerator,
randomGenerator,
rangeGenerator,
repeatGenerator
};
</pre></td></tr>
</table></pre>
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Sat Mar 19 2016 18:27:07 GMT+0300 (Belarus Standard Time)
</div>
</div>
<script src="../../../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../../../sorter.js"></script>
</body>
</html>
| {
"content_hash": "f234d26210eec6fa4c63c49b6d2e8e01",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 145,
"avg_line_length": 31.118181818181817,
"alnum_prop": 0.6295647093193105,
"repo_name": "vladen/aeroflow",
"id": "b55616f3caa18aaaf6ce0d5d7935dfb32db433cc",
"size": "3429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coverage/lcov-report/aeroflow/source/generators/index.js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5058"
},
{
"name": "HTML",
"bytes": "466328"
},
{
"name": "JavaScript",
"bytes": "912135"
}
],
"symlink_target": ""
} |
description: This template provides a easy way to deploy a Sonarqube docker image (alpine tag) on a Linux Web App with Azure database for MySQL
page_type: sample
products:
- azure
- azure-resource-manager
urlFragment: webapp-linux-sonarqube-mysql
languages:
- json
---
# Sonarqube Docker Web App on Linux with MySQL






[](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.web%2Fwebapp-linux-sonarqube-mysql%2Fazuredeploy.json)
[](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.web%2Fwebapp-linux-sonarqube-mysql%2Fazuredeploy.json)
This template provides a easy way to deploy a Sonarqube docker image on a Linux Web App with Azure database for MySQL.
Notice once deployed Sonar can take a while to start due the creation of the initial empty database, it can even fail if you try to access it directly, allow to start it before accessing it or even adjust the tier for the webapp or MySQL accordingly.
`Tags: Microsoft.Web/sites, config, Microsoft.Web/serverfarms, Microsoft.DBforMySQL/servers, firewallrules, databases`
| {
"content_hash": "98e34071d5e6b9a9055fa089f69ca504",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 378,
"avg_line_length": 90.32142857142857,
"alnum_prop": 0.8252273625939106,
"repo_name": "bmoore-msft/azure-quickstart-templates",
"id": "e084823c2ca7240d97c413afd6c77b4f1f740013",
"size": "2533",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "quickstarts/microsoft.web/webapp-linux-sonarqube-mysql/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "852"
},
{
"name": "Bicep",
"bytes": "1307140"
},
{
"name": "C#",
"bytes": "13071"
},
{
"name": "CSS",
"bytes": "8505"
},
{
"name": "Dockerfile",
"bytes": "186"
},
{
"name": "Groovy",
"bytes": "1715"
},
{
"name": "HCL",
"bytes": "7632"
},
{
"name": "HTML",
"bytes": "5143"
},
{
"name": "HiveQL",
"bytes": "613"
},
{
"name": "Java",
"bytes": "6880"
},
{
"name": "JavaScript",
"bytes": "1067401"
},
{
"name": "PowerShell",
"bytes": "1205333"
},
{
"name": "Python",
"bytes": "27862"
},
{
"name": "Shell",
"bytes": "1232774"
},
{
"name": "Solidity",
"bytes": "247"
},
{
"name": "TSQL",
"bytes": "66"
},
{
"name": "XSLT",
"bytes": "4429"
}
],
"symlink_target": ""
} |
using System;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Framework;
namespace NakedFramework.Metamodel.Facet;
[Serializable]
public abstract class DisableForSessionFacetAbstract : FacetAbstract, IDisableForSessionFacet {
public override Type FacetType => typeof(IDisableForSessionFacet);
#region IDisableForSessionFacet Members
public abstract string DisabledReason(INakedObjectAdapter target, INakedFramework framework);
#endregion
}
// Copyright (c) Naked Objects Group Ltd. | {
"content_hash": "935d014444b6b3f8636447eaf661e7d6",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 97,
"avg_line_length": 30.157894736842106,
"alnum_prop": 0.8254799301919721,
"repo_name": "NakedObjectsGroup/NakedObjectsFramework",
"id": "aa732e92dba9db696f37bd244b7594f7cc61ecc8",
"size": "1193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NakedFramework/NakedFramework.Metamodel/Facet/DisableForSessionFacetAbstract.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3010"
},
{
"name": "C#",
"bytes": "17252161"
},
{
"name": "CSS",
"bytes": "87105"
},
{
"name": "F#",
"bytes": "2080309"
},
{
"name": "HTML",
"bytes": "77491"
},
{
"name": "JavaScript",
"bytes": "7967"
},
{
"name": "TSQL",
"bytes": "5089"
},
{
"name": "TypeScript",
"bytes": "683807"
},
{
"name": "Vim Snippet",
"bytes": "41860"
},
{
"name": "Visual Basic .NET",
"bytes": "288499"
}
],
"symlink_target": ""
} |
from construct import Struct, ULInt16, ULInt32, String
from construct.macros import ULInt64, Padding, If
from crypto.aes import AESencryptCBC, AESdecryptCBC
from hfs import HFSVolume, HFSFile
from keystore.keybag import Keybag
from structs import HFSPlusVolumeHeader, kHFSPlusFileRecord, getString, \
kHFSRootParentID
from util import search_plist
from util.bruteforce import loadKeybagFromVolume
import hashlib
import os
import plistlib
import struct
"""
iOS >= 4 raw images
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/hfs/hfs_cprotect.c
http://opensource.apple.com/source/xnu/xnu-1699.22.73/bsd/sys/cprotect.h
"""
cp_root_xattr = Struct("cp_root_xattr",
ULInt16("major_version"),
ULInt16("minor_version"),
ULInt64("flags"),
ULInt32("reserved1"),
ULInt32("reserved2"),
ULInt32("reserved3"),
ULInt32("reserved4")
)
cprotect_xattr = Struct("cprotect_xattr",
ULInt16("xattr_major_version"),
ULInt16("xattr_minor_version"),
ULInt32("flags"),
ULInt32("persistent_class"),
ULInt32("key_size"),
If(lambda ctx: ctx["xattr_major_version"] >= 4, Padding(20)),
String("persistent_key", length=lambda ctx: ctx["key_size"])
)
NSProtectionNone = 4
PROTECTION_CLASSES={
1:"NSFileProtectionComplete",
2:"NSFileProtectionCompleteUnlessOpen",
3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
4:"NSFileProtectionNone",
5:"NSFileProtectionRecovery?"
}
#HAX: flags set in finderInfo[3] to tell if the image was already decrypted
FLAG_DECRYPTING = 0x454d4664 #EMFd big endian
FLAG_DECRYPTED = 0x454d4644 #EMFD big endian
class EMFFile(HFSFile):
def __init__(self, volume, hfsplusfork, fileID, filekey, deleted=False):
super(EMFFile,self).__init__(volume, hfsplusfork, fileID, deleted)
self.filekey = filekey
self.ivkey = None
self.decrypt_offset = 0
if volume.cp_major_version == 4:
self.ivkey = hashlib.sha1(filekey).digest()[:16]
def processBlock(self, block, lba):
iv = self.volume.ivForLBA(lba)
ciphertext = AESencryptCBC(block, self.volume.emfkey, iv)
if not self.ivkey:
clear = AESdecryptCBC(ciphertext, self.filekey, iv)
else:
clear = ""
for i in xrange(len(block)/0x1000):
iv = self.volume.ivForLBA(self.decrypt_offset, False)
iv = AESencryptCBC(iv, self.ivkey)
clear += AESdecryptCBC(ciphertext[i*0x1000:(i+1)*0x1000], self.filekey,iv)
self.decrypt_offset += 0x1000
return clear
def decryptFile(self):
self.decrypt_offset = 0
bs = self.volume.blockSize
for extent in self.extents:
for i in xrange(extent.blockCount):
lba = extent.startBlock+i
data = self.volume.readBlock(lba)
if len(data) == bs:
clear = self.processBlock(data, lba)
self.volume.writeBlock(lba, clear)
class EMFVolume(HFSVolume):
def __init__(self, bdev, device_infos, **kwargs):
super(EMFVolume,self).__init__(bdev, **kwargs)
volumeid = self.volumeID().encode("hex")
if not device_infos:
dirname = os.path.dirname(bdev.filename)
device_infos = search_plist(dirname, {"dataVolumeUUID":volumeid})
if not device_infos:
raise Exception("Missing keyfile")
try:
self.emfkey = None
if device_infos.has_key("EMF"):
self.emfkey = device_infos["EMF"].decode("hex")
self.lbaoffset = device_infos["dataVolumeOffset"]
self.keybag = Keybag.createWithPlist(device_infos)
except:
raise #Exception("Invalid keyfile")
rootxattr = self.getXattr(kHFSRootParentID, "com.apple.system.cprotect")
self.decrypted = (self.header.finderInfo[3] == FLAG_DECRYPTED)
self.cp_major_version = None
self.cp_root = None
if rootxattr == None:
print "(No root com.apple.system.cprotect xattr)"
else:
self.cp_root = cp_root_xattr.parse(rootxattr)
ver = self.cp_root.major_version
print "cprotect version : %d (iOS %d)" % (ver, 4 + int(ver != 2))
assert self.cp_root.major_version == 2 or self.cp_root.major_version == 4
self.cp_major_version = self.cp_root.major_version
self.keybag = loadKeybagFromVolume(self, device_infos)
def ivForLBA(self, lba, add=True):
iv = ""
if add:
lba = lba + self.lbaoffset
lba &= 0xffffffff
for _ in xrange(4):
if (lba & 1):
lba = 0x80000061 ^ (lba >> 1);
else:
lba = lba >> 1;
iv += struct.pack("<L", lba)
return iv
def getFileKeyForCprotect(self, cp):
if self.cp_major_version == None:
self.cp_major_version = struct.unpack("<H", cp[:2])[0]
cprotect = cprotect_xattr.parse(cp)
return self.keybag.unwrapKeyForClass(cprotect.persistent_class, cprotect.persistent_key)
def getFileKeyForFileId(self, fileid):
cprotect = self.getXattr(fileid, "com.apple.system.cprotect")
if cprotect == None:
return None
return self.getFileKeyForCprotect(cprotect)
def readFile(self, path, outFolder="./", returnString=False):
k,v = self.catalogTree.getRecordFromPath(path)
if not v:
print "File %s not found" % path
return
assert v.recordType == kHFSPlusFileRecord
cprotect = self.getXattr(v.data.fileID, "com.apple.system.cprotect")
if cprotect == None or not self.cp_root or self.decrypted:
#print "cprotect attr not found, reading normally"
return super(EMFVolume, self).readFile(path, returnString=returnString)
filekey = self.getFileKeyForCprotect(cprotect)
if not filekey:
print "Cannot unwrap file key for file %s protection_class=%d" % (path, cprotect_xattr.parse(cprotect).persistent_class)
return
f = EMFFile(self, v.data.dataFork, v.data.fileID, filekey)
if returnString:
return f.readAllBuffer()
f.readAll(outFolder + os.path.basename(path))
return True
def flagVolume(self, flag):
self.header.finderInfo[3] = flag
h = HFSPlusVolumeHeader.build(self.header)
return self.bdev.write(0x400, h)
def decryptAllFiles(self):
if self.header.finderInfo[3] == FLAG_DECRYPTING:
print "Volume is half-decrypted, aborting (finderInfo[3] == FLAG_DECRYPTING)"
return
elif self.header.finderInfo[3] == FLAG_DECRYPTED:
print "Volume already decrypted (finderInfo[3] == FLAG_DECRYPTED)"
return
self.failedToGetKey = []
self.notEncrypted = []
self.decryptedCount = 0
self.flagVolume(FLAG_DECRYPTING)
self.catalogTree.traverseLeafNodes(callback=self.decryptFile)
self.flagVolume(FLAG_DECRYPTED)
print "Decrypted %d files" % self.decryptedCount
print "Failed to unwrap keys for : ", self.failedToGetKey
print "Not encrypted files : %d" % len(self.notEncrypted)
def decryptFile(self, k,v):
if v.recordType == kHFSPlusFileRecord:
filename = getString(k).encode("utf-8")
cprotect = self.getXattr(v.data.fileID, "com.apple.system.cprotect")
if not cprotect:
self.notEncrypted.append(filename)
return
fk = self.getFileKeyForCprotect(cprotect)
if not fk:
self.failedToGetKey.append(filename)
return
print "Decrypting", filename
f = EMFFile(self, v.data.dataFork, v.data.fileID, fk)
f.decryptFile()
self.decryptedCount += 1
def list_protected_files(self):
self.protected_dict = {}
self.xattrTree.traverseLeafNodes(callback=self.inspectXattr)
for k in self.protected_dict.keys():
print k
for v in self.protected_dict[k]: print "\t",v
print ""
def inspectXattr(self, k, v):
if getString(k) == "com.apple.system.cprotect" and k.fileID != kHFSRootParentID:
c = cprotect_xattr.parse(v.data)
if c.persistent_class != NSProtectionNone:
#desc = "%d %s" % (k.fileID, self.getFullPath(k.fileID))
desc = "%s" % self.getFullPath(k.fileID)
self.protected_dict.setdefault(PROTECTION_CLASSES.get(c.persistent_class),[]).append(desc)
#print k.fileID, self.getFullPath(k.fileID), PROTECTION_CLASSES.get(c.persistent_class)
| {
"content_hash": "c2c06c06ab851c9e41421cbec10193de",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 132,
"avg_line_length": 41.10909090909091,
"alnum_prop": 0.6010614772224679,
"repo_name": "trailofbits/iverify-oss",
"id": "5eb65612ef5e2a77a30b669bae382d77fba11115",
"size": "9044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/iphone-dataprotection/python_scripts/hfs/emf.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Shell",
"bytes": "19086"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2014-2016 CyberVision, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources>
<item type="id" name="ctx_menu_refresh_device" />
<item type="id" name="ctx_menu_change_mode" />
<item type="id" name="ctx_menu_rename_device" />
<item type="id" name="ctx_menu_detach_device" />
</resources>
| {
"content_hash": "cb7853dcaa58aa61d04ce5d478c6a7f6",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 77,
"avg_line_length": 36.36,
"alnum_prop": 0.682068206820682,
"repo_name": "maxml/sample-apps",
"id": "ae9ec1413060dd5888b4dbfd3f38467f300f66c0",
"size": "909",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "iotworld/source/smarthome/android/res/values/ids.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23868"
},
{
"name": "C",
"bytes": "5016986"
},
{
"name": "C++",
"bytes": "420951"
},
{
"name": "CMake",
"bytes": "52788"
},
{
"name": "HTML",
"bytes": "1482"
},
{
"name": "Java",
"bytes": "2114878"
},
{
"name": "JavaScript",
"bytes": "4701"
},
{
"name": "Makefile",
"bytes": "9995"
},
{
"name": "Objective-C",
"bytes": "382359"
},
{
"name": "Shell",
"bytes": "73744"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b5a6f97748df3ee52e12629fcb188655",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "9bad5cfdfdd658c126e88f1a0ef4f2850c7b766e",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Pagamea/Pagamea guianensis/Pagamea guianensis macrocarpa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
SET(CMAKE_SYSTEM_NAME Windows)
# The name of the target architecture
SET(CMAKE_SYSTEM_PROCESSOR "i586")
# Choose an appropriate compiler prefix
SET(MINGW_TOOLCHAIN "i586-mingw32msvc")
# Which compilers to use for C and C++
FIND_PROGRAM(CMAKE_RC_COMPILER NAMES ${MINGW_TOOLCHAIN}-windres)
FIND_PROGRAM(CMAKE_C_COMPILER NAMES ${MINGW_TOOLCHAIN}-gcc)
FIND_PROGRAM(CMAKE_CXX_COMPILER NAMES ${MINGW_TOOLCHAIN}-g++)
# Here is the target environment located
SET(CMAKE_FIND_ROOT_PATH /usr/${MINGW_TOOLCHAIN})
# Adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
| {
"content_hash": "d2794f19e34d8db5241d8c201b38822d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 64,
"avg_line_length": 37.95238095238095,
"alnum_prop": 0.7804265997490589,
"repo_name": "cpp4ever/libuv-cmake",
"id": "7365c274603e3e45f5ea947df31779240ba31a2d",
"size": "839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "i586-mingw32msvc.cmake",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CMake",
"bytes": "13107"
}
],
"symlink_target": ""
} |
{% extends 'posts/base.html' %}
{% load blog_tags %}
{% block title %} {{ blog_name.title }} {% endblock %}
{% block blog_content %}
<div class="row col-sm-12 col-md-9 blog-container-left">
<div class="blogs">
<ul class="blog-list">
<table align="center" class="table table-bordered">
<thead>
<th>
Title: {{ blog_name.title }}
</th>
</thead>
<tbody>
<tr>
<td><strong>Author</strong>: {{ blog_name.user }}</td>
</tr>
<tr>
<td><strong>Content</strong>: {{ blog_name.content|safe }}</td>
</tr>
<tr>
<td class="widget tags"><strong>Tags</strong>:
{% for tag in blog_name.tags.all %}
<a href="{% url 'selected_tag' tag_slug=tag.slug %}" ><i class="fa fa-tags"></i> {{ tag }}</a>
{% endfor %}
</td>
</tr>
<tr>
<td><strong>Keywords</strong>: {{ blog_name.keywords|safe }}</td>
</tr>
</tbody>
</table>
</ul>
</div>
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
*/
var disqus_config = function () {
this.page.identifier = '{{ blog_name.slug }}';
this.page.title = '{{ blog_name.title }}';
};
var disqus_shortname = '{{ disqus_shortname }}';
(function() { // REQUIRED CONFIGURATION VARIABLE: EDIT THE SHORTNAME BELOW
var d = document, s = d.createElement('script');
s.src = '//' + disqus_shortname + '.disqus.com/embed.js';
// IMPORTANT: Replace EXAMPLE with your forum shortname!
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</div>
{% endblock %}
{% block js_script %}
<script type="text/javascript"></script>
{% endblock %} | {
"content_hash": "248f6f11361a878938832ed7ec0845dd",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 147,
"avg_line_length": 36.540983606557376,
"alnum_prop": 0.5545087483176312,
"repo_name": "nikhila05/micro-blog",
"id": "9ea0a0b0e9b29218ddd8701b50b45a7be6128fbf",
"size": "2229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "micro_blog/microblog/templates/posts/blog_view.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11045"
},
{
"name": "HTML",
"bytes": "105822"
},
{
"name": "JavaScript",
"bytes": "24672"
},
{
"name": "Makefile",
"bytes": "6783"
},
{
"name": "Python",
"bytes": "81628"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>XLabs: F:/Projects/Xamarin-Forms-Labs/src/Serialization/ServiceStack/Common/ITypeSerializer.cs File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="XLabs_logo.psd"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">XLabs
</div>
<div id="projectbrief">Cross-platform reusable C# libraries</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('_i_type_serializer_8cs.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">ITypeSerializer.cs File Reference</div> </div>
</div><!--header-->
<div class="contents">
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_96aec6d1100a5554d6f7fb69df2c511a.html">Xamarin-Forms-Labs</a></li><li class="navelem"><a class="el" href="dir_88bafe9029e18a0be9e6e2b4e8ed9f17.html">src</a></li><li class="navelem"><a class="el" href="dir_22cc748290613e84c02d8ba9d46e740e.html">Serialization</a></li><li class="navelem"><a class="el" href="dir_54e619d53058ba4ad7cc5434af7a6df6.html">ServiceStack</a></li><li class="navelem"><a class="el" href="dir_4cede4b35917a731d596d4c188753cbb.html">Common</a></li><li class="navelem"><a class="el" href="_i_type_serializer_8cs.html">ITypeSerializer.cs</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "3f24151a663cfd7d40f124402a18e164",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 612,
"avg_line_length": 43.58064516129032,
"alnum_prop": 0.6572908956328646,
"repo_name": "XLabs/xlabs.github.io",
"id": "411df40de38eb2b487faa66f93e200747df4300a",
"size": "5404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/_i_type_serializer_8cs.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33201"
},
{
"name": "HTML",
"bytes": "25233456"
},
{
"name": "JavaScript",
"bytes": "1159419"
}
],
"symlink_target": ""
} |
package org.voovan.tools.tuple;
import org.voovan.tools.reflect.TReflect;
import java.util.*;
import java.util.stream.Collectors;
/**
* 带命名的元组类型
*
* @author helyho
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class Tuple {
private Integer nullValueId = 0;
private Map<Object, TupleItem> items;
public Tuple() {
items = new LinkedHashMap<Object, TupleItem>();
}
/**
* 为元组增加属性定义
* @param name 属性名称
* @param clazz 属性类型
* @return 元组对象
*/
public Tuple addField(String name, Class clazz) {
items.put(name, new TupleItem(name, clazz));
return this;
}
public boolean containName(String name) {
return items.containsKey(name);
}
public int contain(Object value) {
return (int)items.values().stream().filter(tupleItem -> tupleItem.equals(value)).count();
}
public Map<Object, TupleItem> getItems() {
return items;
}
/**
* 设置元素属性
* @param name 属性名称
* @param value 属性类型
* @return 元组对象
*/
public Tuple set(Object name, Object value) {
boolean noneName = name == null;
name = noneName ? nullValueId++ : name;
TupleItem tupleItem = items.get(name);
if(noneName && tupleItem!=null) {
throw new TupleException("Tuple none name id duplicate: " + tupleItem);
}
if(tupleItem!=null) {
if (TReflect.isSuper(value.getClass(), tupleItem.getClazz())) {
tupleItem.setValue(value);
} else {
throw new TupleException("Tuple field [" + name + "] need obj " + tupleItem.getClazz() + ", actual " + value.getClass());
}
} else {
Class clazz = value == null ? Object.class : value.getClass();
items.put(name, new TupleItem(name, clazz, value));
}
return this;
}
/**
* 设置元素属性
* @param value 属性类型
* @return 元组对象
*/
public Tuple set(Object value) {
return set(null, value);
}
/**
* 获取元组元素
* @param name 属性名称
* @return 元组元素
*/
public TupleItem getItem(Object name) {
return items.get(name);
}
/**
* 获取元组数据
* @param name 属性名称
* @param <T> 响应范型
* @return 元组数据
*/
public <T> T get(Object name) {
return (T)getItem(name).getValue();
}
/**
* 转换为 List
* list 中的元素为 TupleItem.value
* @return List
*/
public List toList() {
return items.values().stream().map(tupleItem -> tupleItem.getValue()).collect(Collectors.toList());
}
/**
* 转换为 Map
* Map 中的元素为 [TupleItem.name, TupleItem.valu]
* @return 元组对应的 Map
*/
public Map<String, ?> toMap() {
Map ret = new LinkedHashMap();
items.values().stream().forEach(tupleItem -> ret.put(tupleItem.getName(), tupleItem.getValue()));
return ret;
}
@Override
public String toString() {
return "Tuple{" +
"items=" + items +
'}';
}
/**
* 参数构造
* @param items 参数
* @return 元组对象
*/
public static Tuple with(Object ... items) {
Tuple tuple = new Tuple();
for(Object item : items) {
tuple.set(item);
}
return tuple;
}
/**
* 名称, 参数构造
* @param items 命名参数, 类似:[name_1, val_1, name_2, val_2...name_n, val_n]
* @return 元组对象
*/
public static Tuple withName(Object ... items) {
Tuple tuple = new Tuple();
for(int i=0;i<items.length;i++) {
String name = items[i].toString();
Object value = i < items.length ? items[++i] : null;
tuple.set(name, value);
}
return tuple;
}
}
| {
"content_hash": "2dbda259a8d3ff41074fd2278ccf9df3",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 137,
"avg_line_length": 23.95,
"alnum_prop": 0.5394050104384134,
"repo_name": "helyho/Voovan",
"id": "be0a24799262c6c226acd34feff365cc6992d779",
"size": "4112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Common/src/main/java/org/voovan/tools/tuple/Tuple.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "8971"
},
{
"name": "Java",
"bytes": "1930566"
},
{
"name": "PLpgSQL",
"bytes": "1626"
},
{
"name": "Shell",
"bytes": "453"
}
],
"symlink_target": ""
} |
"""
Contains definition for a plugin protocol and other utiltities.
"""
from hyde.exceptions import HydeException
from hyde.util import first_match, discover_executable
from hyde.model import Expando
import abc
from functools import partial
import fnmatch
import os
import re
import subprocess
import sys
import traceback
from commando.util import getLoggerWithNullHandler, load_python_object
from fswrap import File
logger = getLoggerWithNullHandler('hyde.engine')
# Plugins have been reorganized. Map old plugin paths to new.
PLUGINS_OLD_AND_NEW = {
"hyde.ext.plugins.less.LessCSSPlugin" : "hyde.ext.plugins.css.LessCSSPlugin",
"hyde.ext.plugins.stylus.StylusPlugin" : "hyde.ext.plugins.css.StylusPlugin",
"hyde.ext.plugins.jpegoptim.JPEGOptimPlugin" : "hyde.ext.plugins.images.JPEGOptimPlugin",
"hyde.ext.plugins.optipng.OptiPNGPlugin" : "hyde.ext.plugins.images.OptiPNGPlugin",
"hyde.ext.plugins.jpegtran.JPEGTranPlugin" : "hyde.ext.plugins.images.JPEGTranPlugin",
"hyde.ext.plugins.uglify.UglifyPlugin": "hyde.ext.plugins.js.UglifyPlugin",
"hyde.ext.plugins.requirejs.RequireJSPlugin": "hyde.ext.plugins.js.RequireJSPlugin",
"hyde.ext.plugins.coffee.CoffeePlugin": "hyde.ext.plugins.js.CoffeePlugin",
"hyde.ext.plugins.sorter.SorterPlugin": "hyde.ext.plugins.meta.SorterPlugin",
"hyde.ext.plugins.grouper.GrouperPlugin": "hyde.ext.plugins.meta.GrouperPlugin",
"hyde.ext.plugins.tagger.TaggerPlugin": "hyde.ext.plugins.meta.TaggerPlugin",
"hyde.ext.plugins.auto_extend.AutoExtendPlugin": "hyde.ext.plugins.meta.AutoExtendPlugin",
"hyde.ext.plugins.folders.FlattenerPlugin": "hyde.ext.plugins.structure.FlattenerPlugin",
"hyde.ext.plugins.combine.CombinePlugin": "hyde.ext.plugins.structure.CombinePlugin",
"hyde.ext.plugins.paginator.PaginatorPlugin": "hyde.ext.plugins.structure.PaginatorPlugin",
"hyde.ext.plugins.blockdown.BlockdownPlugin": "hyde.ext.plugins.text.BlockdownPlugin",
"hyde.ext.plugins.markings.MarkingsPlugin": "hyde.ext.plugins.text.MarkingsPlugin",
"hyde.ext.plugins.markings.ReferencePlugin": "hyde.ext.plugins.text.ReferencePlugin",
"hyde.ext.plugins.syntext.SyntextPlugin": "hyde.ext.plugins.text.SyntextPlugin",
"hyde.ext.plugins.textlinks.TextlinksPlugin": "hyde.ext.plugins.text.TextlinksPlugin",
"hyde.ext.plugins.git.GitDatesPlugin": "hyde.ext.plugins.vcs.GitDatesPlugin"
}
class PluginProxy(object):
"""
A proxy class to raise events in registered plugins
"""
def __init__(self, site):
super(PluginProxy, self).__init__()
self.site = site
def __getattr__(self, method_name):
if hasattr(Plugin, method_name):
def __call_plugins__(*args):
res = None
if self.site.plugins:
for plugin in self.site.plugins:
if hasattr(plugin, method_name):
checker = getattr(plugin, 'should_call__' + method_name)
if checker(*args):
function = getattr(plugin, method_name)
try:
res = function(*args)
except:
HydeException.reraise(
'Error occured when calling %s' %
plugin.plugin_name, sys.exc_info())
targs = list(args)
if len(targs):
last = targs.pop()
res = res if res else last
targs.append(res)
args = tuple(targs)
return res
return __call_plugins__
raise HydeException(
"Unknown plugin method [%s] called." % method_name)
class Plugin(object):
"""
The plugin protocol
"""
__metaclass__ = abc.ABCMeta
def __init__(self, site):
super(Plugin, self).__init__()
self.site = site
self.logger = getLoggerWithNullHandler(
'hyde.engine.%s' % self.__class__.__name__)
self.template = None
def template_loaded(self, template):
"""
Called when the template for the site has been identified.
Handles the template loaded event to keep
a reference to the template object.
"""
self.template = template
def __getattribute__(self, name):
"""
Syntactic sugar for template methods
"""
result = None
if name.startswith('t_') and self.template:
attr = name[2:]
if hasattr(self.template, attr):
result = self.template[attr]
elif attr.endswith('_close_tag'):
tag = attr.replace('_close_tag', '')
result = partial(self.template.get_close_tag, tag)
elif attr.endswith('_open_tag'):
tag = attr.replace('_open_tag', '')
result = partial(self.template.get_open_tag, tag)
elif name.startswith('should_call__'):
(_, _, method) = name.rpartition('__')
if (method in ('begin_text_resource', 'text_resource_complete',
'begin_binary_resource', 'binary_resource_complete')):
result = self._file_filter
elif (method in ('begin_node', 'node_complete')):
result = self._dir_filter
else:
def always_true(*args, **kwargs):
return True
result = always_true
return result if result else super(Plugin, self).__getattribute__(name)
@property
def settings(self):
"""
The settings for this plugin the site config.
"""
opts = Expando({})
try:
opts = getattr(self.site.config, self.plugin_name)
except AttributeError:
pass
return opts
@property
def plugin_name(self):
"""
The name of the plugin. Makes an intelligent guess.
This is used to lookup the settings for the plugin.
"""
return self.__class__.__name__.replace('Plugin', '').lower()
def begin_generation(self):
"""
Called when generation is about to take place.
"""
pass
def begin_site(self):
"""
Called when the site is loaded completely. This implies that all the
nodes and resources have been identified and are accessible in the
site variable.
"""
pass
def begin_node(self, node):
"""
Called when a node is about to be processed for generation.
This method is called only when the entire node is generated.
"""
pass
def _file_filter(self, resource, *args, **kwargs):
"""
Returns True if the resource path matches the filter property in
plugin settings.
"""
if not self._dir_filter(resource.node, *args, **kwargs):
return False
try:
filters = self.settings.include_file_pattern
if not isinstance(filters, list):
filters = [filters]
except AttributeError:
filters = None
result = any(fnmatch.fnmatch(resource.path, f)
for f in filters) if filters else True
return result
def _dir_filter(self, node, *args, **kwargs):
"""
Returns True if the node path is a descendant of the include_paths property in
plugin settings.
"""
try:
node_filters = self.settings.include_paths
if not isinstance(node_filters, list):
node_filters = [node_filters]
node_filters = [self.site.content.node_from_relative_path(f)
for f in node_filters]
except AttributeError:
node_filters = None
result = any(node.source == f.source or
node.source.is_descendant_of(f.source)
for f in node_filters if f) \
if node_filters else True
return result
def begin_text_resource(self, resource, text):
"""
Called when a text resource is about to be processed for generation.
The `text` parameter contains the resource text at this point
in its lifecycle. It is the text that has been loaded and any
plugins that are higher in the order may have tampered with it.
But the text has not been processed by the template yet. Note that
the source file associated with the text resource may not be modifed
by any plugins.
If this function returns a value, it is used as the text for further
processing.
"""
return text
def begin_binary_resource(self, resource):
"""
Called when a binary resource is about to be processed for generation.
Plugins are free to modify the contents of the file.
"""
pass
def text_resource_complete(self, resource, text):
"""
Called when a resource has been processed by the template.
The `text` parameter contains the resource text at this point
in its lifecycle. It is the text that has been processed by the
template and any plugins that are higher in the order may have
tampered with it. Note that the source file associated with the
text resource may not be modifed by any plugins.
If this function returns a value, it is used as the text for further
processing.
"""
return text
def binary_resource_complete(self, resource):
"""
Called when a binary resource has already been processed.
Plugins are free to modify the contents of the file.
"""
pass
def node_complete(self, node):
"""
Called when all the resources in the node have been processed.
This method is called only when the entire node is generated.
"""
pass
def site_complete(self):
"""
Called when the entire site has been processed. This method is called
only when the entire site is generated.
"""
pass
def generation_complete(self):
"""
Called when generation is completed.
"""
pass
@staticmethod
def load_all(site):
"""
Loads plugins based on the configuration. Assigns the plugins to
'site.plugins'
"""
def load_plugin(name):
plugin_name = PLUGINS_OLD_AND_NEW.get(name, name)
return load_python_object(plugin_name)(site)
site.plugins = [load_plugin(name)
for name in site.config.plugins]
@staticmethod
def get_proxy(site):
"""
Returns a new instance of the Plugin proxy.
"""
return PluginProxy(site)
class CLTransformer(Plugin):
"""
Handy class for plugins that simply call a command line app to
transform resources.
"""
@property
def defaults(self):
"""
Default command line options. Can be overridden
by specifying them in config.
"""
return {}
@property
def executable_name(self):
"""
The executable name for the plugin. This can be overridden in the
config. If a configuration option is not provided, this is used
to guess the complete path of the executable.
"""
return self.plugin_name
@property
def executable_not_found_message(self):
"""
Message to be displayed if the command line application
is not found.
"""
return ("%(name)s executable path not configured properly. "
"This plugin expects `%(name)s.app` to point "
"to the full path of the `%(exec)s` executable." %
{
"name":self.plugin_name, "exec": self.executable_name
})
@property
def app(self):
"""
Gets the application path from the site configuration.
If the path is not configured, attempts to guess the path
from the sytem path environment variable.
"""
try:
app_path = getattr(self.settings, 'app')
except AttributeError:
app_path = self.executable_name
# Honour the PATH environment variable.
if app_path is not None and not os.path.isabs(app_path):
app_path = discover_executable(app_path, self.site.sitepath)
if app_path is None:
raise HydeException(self.executable_not_found_message)
app = File(app_path)
if not app.exists:
raise HydeException(self.executable_not_found_message)
return app
def option_prefix(self, option):
"""
Return the prefix for the given option.
Defaults to --.
"""
return "--"
def process_args(self, supported):
"""
Given a list of supported arguments, consutructs an argument
list that could be passed on to the call_app function.
"""
args = {}
args.update(self.defaults)
try:
args.update(self.settings.args.to_dict())
except AttributeError:
pass
params = []
for option in supported:
if isinstance(option, tuple):
(descriptive, short) = option
else:
descriptive = short = option
options = [descriptive.rstrip("="), short.rstrip("=")]
match = first_match(lambda arg: arg in options, args)
if match:
val = args[match]
param = "%s%s" % (self.option_prefix(descriptive),
descriptive)
if descriptive.endswith("="):
param += val
val = None
params.append(param)
if val:
params.append(val)
return params
def call_app(self, args):
"""
Calls the application with the given command line parameters.
"""
try:
self.logger.debug(
"Calling executable [%s] with arguments %s" %
(args[0], unicode(args[1:])))
return subprocess.check_output(args)
except subprocess.CalledProcessError, error:
self.logger.error(error.output)
raise
class TextyPlugin(Plugin):
"""
Base class for text preprocessing plugins.
Plugins that desire to provide syntactic sugar for
commonly used hyde functions for various templates
can inherit from this class.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, site):
super(TextyPlugin, self).__init__(site)
self.open_pattern = self.default_open_pattern
self.close_pattern = self.default_close_pattern
self.template = None
config = getattr(site.config, self.plugin_name, None)
if config and hasattr(config, 'open_pattern'):
self.open_pattern = config.open_pattern
if self.close_pattern and config and hasattr(config, 'close_pattern'):
self.close_pattern = config.close_pattern
@property
def plugin_name(self):
"""
The name of the plugin. Makes an intelligent guess.
"""
return self.__class__.__name__.replace('Plugin', '').lower()
@abc.abstractproperty
def tag_name(self):
"""
The tag that this plugin tries add syntactic sugar for.
"""
return self.plugin_name
@abc.abstractproperty
def default_open_pattern(self):
"""
The default pattern for opening the tag.
"""
return None
@abc.abstractproperty
def default_close_pattern(self):
"""
The default pattern for closing the tag.
"""
return None
def get_params(self, match, start=True):
"""
Default implementation for getting template args.
"""
return match.groups(1)[0] if match.lastindex else ''
@abc.abstractmethod
def text_to_tag(self, match, start=True):
"""
Replaces the matched text with tag statement
given by the template.
"""
params = self.get_params(match, start)
return (self.template.get_open_tag(self.tag_name, params)
if start
else self.template.get_close_tag(self.tag_name, params))
def begin_text_resource(self, resource, text):
"""
Replace a text base pattern with a template statement.
"""
text_open = re.compile(self.open_pattern, re.UNICODE|re.MULTILINE)
text = text_open.sub(self.text_to_tag, text)
if self.close_pattern:
text_close = re.compile(self.close_pattern, re.UNICODE|re.MULTILINE)
text = text_close.sub(
partial(self.text_to_tag, start=False), text)
return text
| {
"content_hash": "046d784ab84a22e07dc30aeb5e74dd58",
"timestamp": "",
"source": "github",
"line_count": 501,
"max_line_length": 95,
"avg_line_length": 34.49101796407186,
"alnum_prop": 0.5794560185185185,
"repo_name": "0111001101111010/hyde",
"id": "d0839cbaa51c31d168e2a4c5b0de8e54d62b6d75",
"size": "17304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hyde/plugin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16853"
},
{
"name": "JavaScript",
"bytes": "370"
},
{
"name": "Python",
"bytes": "387576"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Steve Myles > Lognormality > Archive > 12 July 2015</title>
<meta name="viewport" content="width=device-width">
<meta name="description" content="Steve Myles, some guy from Texas">
<meta name="author" content="Steve Myles">
<link rel="canonical" href="https://stevemyles.site/blog/2015/07/12/">
<link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
<link rel="icon" type="image/png" href="https://stevemyles.site/img/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="https://stevemyles.site/img/favicon-16x16.png" sizes="16x16" />
<!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
<link rel="stylesheet" href="/style.css">
<!-- Google verification -->
<meta name="google-site-verification" content="v249ifvo2RPEG6ai3LJgSAG7PRDntewxOW37aBgrhZY">
<!-- Bing Verification -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-15892472-10"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-15892472-10');
</script>
<!-- Custom Fonts -->
<link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
<link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" class="index">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="https://stevemyles.site/#page-top">Steve Myles</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a href="https://stevemyles.site/#page-top"></a>
</li>
<li class="page-scroll">
<a href="https://stevemyles.site/#about">About</a>
</li>
<li class="page-scroll">
<a href="https://stevemyles.site/#experience">Experience</a>
</li>
<li class="page-scroll">
<a href="https://stevemyles.site/#projects">Projects</a>
</li>
<li class="page-scroll">
<a href="https://stevemyles.site/#talks">Talks</a>
</li>
<li class="page-scroll">
<a href="/blog/" style="background-color:#57565e;">Blog</a>
</li>
<li class="page-scroll">
<a href="https://steve.mylesandmyles.info/">Tumblr</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<section id="archive">
<div class="container">
<br /><br /><br />
<div class="row">
<div class="col-lg-12">
<h3><a style="color:#39383d;" href="https://stevemyles.site/blog/">Lognormality</a> > <a style="color:#39383d;" href="https://stevemyles.site/blog/archive/">Archive</a> > <a style="color:#39383d;" href="https://stevemyles.site/blog/2015/07/12/">12 July 2015</a></h3>
<hr class="star-primary">
</div>
</div>
<div class="row">
<ul class="posts">
<li>
2015/07/12: <a class="post-link" href="/blog/2015/07/12/phonenumber/">phonenumber</a>
</li>
</ul>
</div>
<ul class="pager">
<li>
<a href="https://stevemyles.site/blog/">Main</a>
</li>
<li>
<a href="https://stevemyles.site/blog/archive/">Archive</a>
</li>
</ul>
</div>
</section>
<!-- Footer -->
<footer class="text-center">
<div class="footer-above">
<div class="container">
<div class="row">
<div class="footer-col col-md-4">
<h4>Links</h4>
<p>
<ul>
<li><p><a href="https://stevemyles.site/blog/">Lognormality</a> (blog)</p></li>
<li><p><a href="https://steve.mylesandmyles.info/">MEMORYLESSNESS</a> (tumblr)</p></li>
<li><p><a href="https://photos.scumdogentertainment.com/">Stochasticity</a> (my photos)</p></li>
<li><p><a href="https://about.me/stevemyles">about.me</a></p></li>
<li><p><a href="https://www.researchgate.net/profile/Steven_Myles2">ResearchGate</a></p></li>
</ul>
</p>
</div>
<div class="footer-col col-md-4">
<h4>Me Elsewhere</h4>
<ul class="list-inline">
<li>
<a href="https://www.linkedin.com/in/stevenmyles" class="btn-social btn-outline"><i class="fa fa-fw fa-linkedin"></i></a>
</li>
<li>
<a href="https://github.com/scumdogsteev" class="btn-social btn-outline"><i class="fa fa-fw fa-github"></i></a>
</li>
<li>
<a href="https://www.flickr.com/photos/scumdogsteev/" class="btn-social btn-outline"><i class="fa fa-fw fa-flickr"></i></a>
</li>
<li>
<a href="https://www.instagram.com/scumdogsteev/" class="btn-social btn-outline"><i class="fa fa-fw fa-instagram"></i></a>
</li>
<li>
<a href="https://www.youtube.com/user/scumdogsteev" class="btn-social btn-outline"><i class="fa fa-fw fa-youtube"></i></a>
</li>
<li>
<a href="https://soundcloud.com/scumdogsteev" class="btn-social btn-outline"><i class="fa fa-fw fa-soundcloud"></i></a>
</li>
<li>
<a href="https://steve.mylesandmyles.info/" class="btn-social btn-outline"><i class="fa fa-fw fa-tumblr"></i></a>
</li>
<li>
<a href="https://www.last.fm/user/scumdogsteev" class="btn-social btn-outline"><i class="fa fa-fw fa-lastfm"></i></a>
</li>
</ul>
</div>
<div class="footer-col col-md-4">
<h4>Credits</h4>
<p>Theme = <a href="http://jekyllthemes.org/themes/freelancer/">Freelancer</a> by <a href="https://startbootstrap.com">Start Bootstrap</a>. Hosting by <a href="https://pages.github.com/">GitHub Pages</a>.</p>
</div>
</div>
</div>
</div>
<div class="footer-below">
<div class="container">
<div class="row">
<div class="col-lg-12">
Copyright © 1994-2021 <a href="mailto:steve@mylesandmyles.info">Steve Myles</a>. <a href="/license/">Some rights reserved</a>.<br />
</div>
</div>
</div>
</div>
</footer>
<!-- Scroll to Top Button (Only visible on small and extra-small screen sizes) -->
<div class="scroll-top page-scroll visible-xs visible-sm">
<a class="btn btn-primary" href="#page-top">
<i class="fa fa-chevron-up"></i>
</a>
</div>
<!-- jQuery Version 1.11.0 -->
<script src="/js/jquery-1.11.0.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="/js/jquery.easing.min.js"></script>
<script src="/js/classie.js"></script>
<script src="/js/cbpAnimatedHeader.js"></script>
<!-- Custom Theme JavaScript -->
<script src="/js/freelancer.js"></script>
<!-- ToggleDiv JavaScript -->
<script src="/js/toggleDiv.js"></script>
</body>
</html>
| {
"content_hash": "0f052123b2c09f46eff87e0f26758c44",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 287,
"avg_line_length": 43.20704845814978,
"alnum_prop": 0.4957177814029364,
"repo_name": "scumdogsteev/scumdogsteev.github.io",
"id": "1a7bb54d3df7f9b0757b3d05ac506135d78c36f1",
"size": "9808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blog/2015/07/12/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "147"
},
{
"name": "CSS",
"bytes": "14054"
},
{
"name": "HTML",
"bytes": "1837827"
},
{
"name": "JavaScript",
"bytes": "80972"
},
{
"name": "R",
"bytes": "1271"
},
{
"name": "Ruby",
"bytes": "1709"
}
],
"symlink_target": ""
} |
"""Utility to dump events to screen.
This is a simple program that dumps events to the console
as they happen. Think of it like a `tcpdump` for Celery events.
"""
from __future__ import absolute_import, print_function, unicode_literals
import sys
from datetime import datetime
from celery.app import app_or_default
from celery.utils.functional import LRUCache
from celery.utils.time import humanize_seconds
__all__ = ('Dumper', 'evdump')
TASK_NAMES = LRUCache(limit=0xFFF)
HUMAN_TYPES = {
'worker-offline': 'shutdown',
'worker-online': 'started',
'worker-heartbeat': 'heartbeat',
}
CONNECTION_ERROR = """\
-> Cannot connect to %s: %s.
Trying again %s
"""
def humanize_type(type):
try:
return HUMAN_TYPES[type.lower()]
except KeyError:
return type.lower().replace('-', ' ')
class Dumper(object):
"""Monitor events."""
def __init__(self, out=sys.stdout):
self.out = out
def say(self, msg):
print(msg, file=self.out)
# need to flush so that output can be piped.
try:
self.out.flush()
except AttributeError: # pragma: no cover
pass
def on_event(self, ev):
timestamp = datetime.utcfromtimestamp(ev.pop('timestamp'))
type = ev.pop('type').lower()
hostname = ev.pop('hostname')
if type.startswith('task-'):
uuid = ev.pop('uuid')
if type in ('task-received', 'task-sent'):
task = TASK_NAMES[uuid] = '{0}({1}) args={2} kwargs={3}' \
.format(ev.pop('name'), uuid,
ev.pop('args'),
ev.pop('kwargs'))
else:
task = TASK_NAMES.get(uuid, '')
return self.format_task_event(hostname, timestamp,
type, task, ev)
fields = ', '.join(
'{0}={1}'.format(key, ev[key]) for key in sorted(ev)
)
sep = fields and ':' or ''
self.say('{0} [{1}] {2}{3} {4}'.format(
hostname, timestamp, humanize_type(type), sep, fields),)
def format_task_event(self, hostname, timestamp, type, task, event):
fields = ', '.join(
'{0}={1}'.format(key, event[key]) for key in sorted(event)
)
sep = fields and ':' or ''
self.say('{0} [{1}] {2}{3} {4} {5}'.format(
hostname, timestamp, humanize_type(type), sep, task, fields),)
def evdump(app=None, out=sys.stdout):
"""Start event dump."""
app = app_or_default(app)
dumper = Dumper(out=out)
dumper.say('-> evdump: starting capture...')
conn = app.connection_for_read().clone()
def _error_handler(exc, interval):
dumper.say(CONNECTION_ERROR % (
conn.as_uri(), exc, humanize_seconds(interval, 'in', ' ')
))
while 1:
try:
conn.ensure_connection(_error_handler)
recv = app.events.Receiver(conn, handlers={'*': dumper.on_event})
recv.capture()
except (KeyboardInterrupt, SystemExit):
return conn and conn.close()
except conn.connection_errors + conn.channel_errors:
dumper.say('-> Connection lost, attempting reconnect')
if __name__ == '__main__': # pragma: no cover
evdump()
| {
"content_hash": "c7d30ceee9f02b86762e1225f9663b7e",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 77,
"avg_line_length": 30.83177570093458,
"alnum_prop": 0.5586541376174599,
"repo_name": "mdworks2016/work_development",
"id": "0c3865d5a033f8e3c6c478369250e65e3ccca5a4",
"size": "3323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/20_Third_Certification/venv/lib/python3.7/site-packages/celery/events/dumper.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "142"
},
{
"name": "Kotlin",
"bytes": "68744"
},
{
"name": "Python",
"bytes": "1080"
}
],
"symlink_target": ""
} |
import getopt
import sys
from Bio import SeqIO
from Bio.SeqUtils import GC
import time# import time, gmtime, strftime
import os
import shutil
import pandas
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
import csv
#from datetime import datetime
import numpy as np
from scipy import stats
__author__ = "Andriy Sheremet"
#Helper functions definitions
def genome_shredder(input_dct, shear_val):
shredded = {}
for key, value in input_dct.items():
#print input_dct[i].seq
#print i
dic_name = key
rec_name = value.name
for j in range(0, len(str(value.seq)), int(shear_val)):
# print j
record = str(value.seq)[0+j:int(shear_val)+j]
shredded[dic_name+"_"+str(j)] = SeqRecord(Seq(record),rec_name+"_"+str(j),'','')
#record = SeqRecord(input_ref_records[i].seq[0+i:int(shear_val)+i],input_ref_records[i].name+"_%i"%i,"","")
return shredded
def parse_contigs_ind(f_name):
"""
Returns sequences index from the input files(s)
remember to close index object after use
"""
handle = open(f_name, "rU")
record_dict = SeqIO.index(f_name,"fasta")
handle.close()
return record_dict
#returning specific sequences and overal list
def retrive_sequence(contig_lst, rec_dic):
"""
Returns list of sequence elements from dictionary/index of SeqIO objects specific to the contig_lst parameter
"""
contig_seqs = list()
#record_dict = rec_dic
#handle.close()
for contig in contig_lst:
contig_seqs.append(str(rec_dic[contig].seq))#fixing BiopythonDeprecationWarning
return contig_seqs
def filter_seq_dict(key_lst, rec_dic):
"""
Returns filtered dictionary element from rec_dic according to sequence names passed in key_lst
"""
return { key: rec_dic[key] for key in key_lst }
def unique_scaffold_topEval(dataframe):
#returns pandas series object
variables = list(dataframe.columns.values)
scaffolds=dict()
rows=list()
for row in dataframe.itertuples():
#if row[1]=='Ga0073928_10002560':
if row[1] not in scaffolds:
scaffolds[row[1]]=row
else:
if row[11]<scaffolds[row[1]][11]:
scaffolds[row[1]]=row
rows=scaffolds.values()
#variables=['quid', 'suid', 'iden', 'alen', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits']
df = pandas.DataFrame([[getattr(i,j) for j in variables] for i in rows], columns = variables)
return df
def unique_scaffold_topBits(dataframe):
#returns pandas series object
variables = list(dataframe.columns.values)
scaffolds=dict()
rows=list()
for row in dataframe.itertuples():
#if row[1]=='Ga0073928_10002560':
if row[1] not in scaffolds:
scaffolds[row[1]]=row
else:
if row[12]>scaffolds[row[1]][12]:
scaffolds[row[1]]=row
rows=scaffolds.values()
#variables=['quid', 'suid', 'iden', 'alen', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits']
df = pandas.DataFrame([[getattr(i,j) for j in variables] for i in rows], columns = variables)
return df
def close_ind_lst(ind_lst):
"""
Closes index objects supplied in input parameter list
"""
for index in ind_lst:
index.close()
def usage():
print "\nThis is the usage function\n"
# print 'Usage: '+sys.argv[0]+' -i <input_file> [-o <output>] [-l <minimum length>]'
# print 'Example: '+sys.argv[0]+' -i input.fasta -o output.fasta -l 100'
def main(argv):
#default parameters
mg_lst = []
ref_lst = []
e_val = 1e-5
alen = 50.0
alen_percent = True
alen_bp = False
iden = 95.0
name= "output"
fmt_lst = ["fasta"]
supported_formats =["fasta", "csv"]
iterations = 1
alen_increment = 5.0
iden_increment = 0.0
blast_db_Dir = ""
results_Dir = ""
input_files_Dir = ""
ref_out_0 = ""
blasted_lst = []
continue_from_previous = False #poorly supported, just keeping the directories
skip_blasting = False
debugging = False
sheared = False
shear_val = None
logfile = ""
try:
opts, args = getopt.getopt(argv, "r:m:n:e:a:i:s:f:h", ["reference=", "metagenome=", "name=", "e_value=", "alignment_length=", "identity=","shear=","format=", "iterations=", "alen_increment=", "iden_increment=","continue_from_previous","skip_blasting","debugging", "help"])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
# elif opt in ("--recover_after_failure"):
# recover_after_failure = True
# print "Recover after failure:", recover_after_failure
elif opt in ("--continue_from_previous"):
continue_from_previous = True
if debugging:
print "Continue after failure:", continue_from_previous
elif opt in ("--debugging"):
debugging = True
if debugging:
print "Debugging messages:", debugging
elif opt in ("-r", "--reference"):
if arg:
ref_lst=arg.split(',')
#infiles = arg
if debugging:
print "Reference file(s)", ref_lst
elif opt in ("-m", "--metagenome"):
if arg:
mg_lst=arg.split(',')
#infiles = arg
if debugging:
print "Metagenome file(s)", mg_lst
elif opt in ("-f", "--format"):
if arg:
fmt_lst=arg.split(',')
#infiles = arg
if debugging:
print "Output format(s)", fmt_lst
elif opt in ("-n", "--name"):
if arg.strip():
name = arg
if debugging:
print "Project name", name
elif opt in ("-e", "--e_value"):
try:
e_val = float(arg)
except:
print "\nERROR: Please enter numerical value as -e parameter (default: 1e-5)"
usage()
sys.exit(1)
if debugging:
print "E value", e_val
elif opt in ("-a", "--alignment_length"):
if arg.strip()[-1]=="%":
alen_bp = False
alen_percent = True
else:
alen_bp = True
alen_percent = False
try:
alen = float(arg.split("%")[0])
except:
print "\nERROR: Please enter a numerical value as -a parameter (default: 50.0)"
usage()
sys.exit(1)
if debugging:
print "Alignment length", alen
elif opt in ("-i", "--identity"):
try:
iden = float(arg)
except:
print "\nERROR: Please enter a numerical value as -i parameter (default: 95.0)"
usage()
sys.exit(1)
if debugging:
print "Alignment length", iden
elif opt in ("-s", "--shear"):
sheared = True
try:
shear_val = int(arg)
except:
print "\nERROR: Please enter an integer value as -s parameter"
usage()
sys.exit(1)
if debugging:
print "Alignment length", iden
elif opt in ("--iterations"):
try:
iterations = int(arg)
except:
print "\nWARNING: Please enter integer value as --iterations parameter (using default: 1)"
if debugging:
print "Iterations: ", iterations
elif opt in ("--alen_increment"):
try:
alen_increment = float(arg)
except:
print "\nWARNING: Please enter numerical value as --alen_increment parameter (using default: )", alen_increment
if debugging:
print "Alignment length increment: ", alen_increment
elif opt in ("--iden_increment"):
try:
iden_increment = float(arg)
except:
print "\nWARNING: Please enter numerical value as --iden_increment parameter (using default: )", iden_increment
if debugging:
print "Alignment length increment: ", iden_increment
elif opt in ("--skip_blasting"):
skip_blasting = True
if debugging:
print "Blasting step omitted; Using previous blast output."
for ref_file in [x for x in ref_lst if x]:
try:
#
with open(ref_file, "rU") as hand_ref:
pass
except:
print "\nERROR: Reference File(s) ["+ref_file+"] doesn't exist"
usage()
sys.exit(1)
for mg_file in [x for x in mg_lst if x]:
try:
#
with open(mg_file, "rU") as hand_mg:
pass
except:
print "\nERROR: Metagenome File(s) ["+mg_file+"] doesn't exist"
usage()
sys.exit(1)
for fmt in [x for x in fmt_lst if x]:
if fmt not in supported_formats:
print "\nWARNING: Output format [",fmt,"] is not supported"
print "\tUse -h(--help) option for the list of supported formats"
fmt_lst=["fasta"]
print "\tUsing default output format: ", fmt_lst[0]
project_dir = name
if not continue_from_previous:
if os.path.exists(project_dir):
shutil.rmtree(project_dir)
try:
os.mkdir(project_dir)
except OSError:
print "ERROR: Cannot create project directory: " + name
raise
print "\n\t Initial Parameters:"
print "\nProject Name: ", name,'\n'
print "Project Directory: ", os.path.abspath(name),'\n'
print "Reference File(s): ", ref_lst,'\n'
if sheared:
print "Shear Reference File(s):", str(shear_val)+"bp",'\n'
print "Metagenome File(s): ", mg_lst,'\n'
print "E Value: ", e_val, "\n"
if alen_percent:
print "Alignment Length: "+str(alen)+'%\n'
if alen_bp:
print "Alignment Length: "+str(alen)+'bp\n'
print "Sequence Identity: "+str(iden)+'%\n'
print "Output Format(s):", fmt_lst,'\n'
if iterations > 1:
print "Iterations: ", iterations, '\n'
print "Alignment Length Increment: ", alen_increment, '\n'
print "Sequence identity Increment: ", iden_increment, '\n'
#Initializing directories
blast_db_Dir = name+"/blast_db"
if not continue_from_previous:
if os.path.exists(blast_db_Dir):
shutil.rmtree(blast_db_Dir)
try:
os.mkdir(blast_db_Dir)
except OSError:
print "ERROR: Cannot create project directory: " + blast_db_Dir
raise
results_Dir = name+"/results"
if not continue_from_previous:
if os.path.exists(results_Dir):
shutil.rmtree(results_Dir)
try:
os.mkdir(results_Dir)
except OSError:
print "ERROR: Cannot create project directory: " + results_Dir
raise
input_files_Dir = name+"/input_files"
if not continue_from_previous:
if os.path.exists(input_files_Dir):
shutil.rmtree(input_files_Dir)
try:
os.mkdir(input_files_Dir)
except OSError:
print "ERROR: Cannot create project directory: " + input_files_Dir
raise
# Writing raw reference files into a specific input filename
input_ref_records = {}
for reference in ref_lst:
ref_records_ind = parse_contigs_ind(reference)
#ref_records = dict(ref_records_ind)
input_ref_records.update(ref_records_ind)
ref_records_ind.close()
#input_ref_records.update(ref_records)
ref_out_0 = input_files_Dir+"/reference0.fna"
if (sheared & bool(shear_val)):
with open(ref_out_0, "w") as handle:
SeqIO.write(genome_shredder(input_ref_records, shear_val).values(), handle, "fasta")
#NO NEED TO CLOSE with statement will automatically close the file
else:
with open(ref_out_0, "w") as handle:
SeqIO.write(input_ref_records.values(), handle, "fasta")
# Making BLAST databases
#output fname from before used as input for blast database creation
input_ref_0 = ref_out_0
title_db = name+"_db"#add iteration functionality
outfile_db = blast_db_Dir+"/iteration"+str(iterations)+"/"+name+"_db"#change into for loop
os.system("makeblastdb -in "+input_ref_0+" -dbtype nucl -title "+title_db+" -out "+outfile_db+" -parse_seqids")
# BLASTing query contigs
if not skip_blasting:
print "\nBLASTing query file(s):"
for i in range(len(mg_lst)):
database = outfile_db # adjust for iterations
blasted_lst.append(results_Dir+"/recruited_mg_"+str(i)+".tab")
start = time.time()
os_string = 'blastn -db '+database+' -query \"'+mg_lst[i]+'\" -out '+blasted_lst[i]+" -evalue "+str(e_val)+" -outfmt 6 -num_threads 8"
#print os_string
os.system(os_string)
print "\t"+mg_lst[i]+"; Time elapsed: "+str(time.time()-start)+" seconds."
else:
for i in range(len(mg_lst)):
blasted_lst.append(results_Dir+"/recruited_mg_"+str(i)+".tab")
# Parsing BLAST outputs
blast_cols = ['quid', 'suid', 'iden', 'alen', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits']
recruited_mg=[]
for i in range(len(mg_lst)):
try:
df = pandas.read_csv(blasted_lst[i] ,sep="\t", header=None)
except:
df = pandas.DataFrame(columns=blast_cols)
df.columns=blast_cols
recruited_mg.append(df)
# print len(recruited_mg[0])
# print len(recruited_mg[1])
#creating all_records entry
#! Remember to close index objects after they are no longer needed
#! Use helper function close_ind_lst()
all_records = []
all_input_recs = parse_contigs_ind(ref_out_0)
##calculating GC of the reference
if (len(all_input_recs)>1):
ref_gc_lst = np.array([GC(x.seq) for x in all_input_recs.values()])
ref_cnt = ref_gc_lst.size
ref_gc_avg = np.mean(ref_gc_lst)
ref_gc_avg_std = np.std(ref_gc_lst)
if(len(ref_gc_lst) > 0):
ref_gc_avg_sem = stats.sem(ref_gc_lst, axis=0)
else:
ref_gc_avg_sem=0
else:
if (debugging):
print "Only one reference"
ref_gc_lst = np.array([GC(x.seq) for x in all_input_recs.values()])
ref_cnt = ref_gc_lst.size
ref_gc_avg = np.mean(ref_gc_lst)
ref_gc_avg_std=0
ref_gc_avg_sem=0
#ref_gc_avg_sem = stats.sem(ref_gc_lst, axis=0)
# _ = 0
# for key, value in all_input_recs.items():
# _ +=1
# if _ < 20:
# print key, len(value)
print "\nIndexing metagenome file(s):"
for i in range(len(mg_lst)):
start = time.time()
all_records.append(parse_contigs_ind(mg_lst[i]))
print "\t"+mg_lst[i]+" Indexed in : "+str(time.time()-start)+" seconds."
# Transforming data
print "\nParsing recruited contigs:"
for i in range(len(mg_lst)):
start = time.time()
#cutoff_contigs[dataframe]=evalue_filter(cutoff_contigs[dataframe])
recruited_mg[i]=unique_scaffold_topBits(recruited_mg[i])
contig_list = recruited_mg[i]['quid'].tolist()
recruited_mg[i]['Contig_nt']=retrive_sequence(contig_list, all_records[i])
recruited_mg[i]['Contig_size']=recruited_mg[i]['Contig_nt'].apply(lambda x: len(x))
#recruited_mg[i]['Ref_nt']=recruited_mg[i]['suid'].apply(lambda x: all_input_recs[str(x)].seq)
recruited_mg[i]['Ref_size']=recruited_mg[i]['suid'].apply(lambda x: len(all_input_recs[str(x)]))
recruited_mg[i]['Ref_GC']=recruited_mg[i]['suid'].apply(lambda x: GC(all_input_recs[str(x)].seq))
#recruited_mg[i]['Coverage']=recruited_mg[i]['alen'].apply(lambda x: 100.0*float(x))/min(recruited_mg[i]['Contig_size'].apply(lambda y: y),recruited_mg[i]['Ref_size'].apply(lambda z: z))
#df.loc[:, ['B0', 'B1', 'B2']].min(axis=1)
recruited_mg[i]['Coverage']=recruited_mg[i]['alen'].apply(lambda x: 100.0*float(x))/recruited_mg[i].loc[:,["Contig_size", "Ref_size"]].min(axis=1)
recruited_mg[i]['Metric']=recruited_mg[i]['Coverage']*recruited_mg[i]['iden']/100.0
try:
recruited_mg[i]['Contig_GC']=recruited_mg[i]['Contig_nt'].apply(lambda x: GC(x))
except:
recruited_mg[i]['Contig_GC']=recruited_mg[i]['Contig_nt'].apply(lambda x: None)
try:
recruited_mg[i]['Read_RPKM']=1.0/((recruited_mg[i]['Ref_size']/1000.0)*(len(all_records[i])/1000000.0))
except:
recruited_mg[i]['Read_RPKM']=np.nan
#recruited_mg[i] = recruited_mg[i][['quid', 'suid', 'iden', 'alen','Coverage','Metric', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits','Ref_size','Ref_GC','Ref_nt','Contig_size','Contig_GC','Contig_nt']]
recruited_mg[i] = recruited_mg[i][['quid', 'suid', 'iden', 'alen','Coverage','Metric', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits','Ref_size','Ref_GC','Contig_size','Contig_GC','Read_RPKM','Contig_nt']]
print "\tContigs from "+mg_lst[i]+" parsed in : "+str(time.time()-start)+" seconds."
# Here would go statistics functions and producing plots
#
#
#
#
#
# Quality filtering before outputting
if alen_percent:
for i in range(len(recruited_mg)):
recruited_mg[i]=recruited_mg[i][(recruited_mg[i]['iden']>=iden)&(recruited_mg[i]['Coverage']>=alen)&(recruited_mg[i]['eval']<=e_val)]
if alen_bp:
for i in range(len(recruited_mg)):
recruited_mg[i]=recruited_mg[i][(recruited_mg[i]['iden']>=iden)&(recruited_mg[i]['alen']>=alen)&(recruited_mg[i]['eval']<=e_val)]
# print len(recruited_mg[0])
# print len(recruited_mg[1])
# Batch export to outfmt (csv and/or multiple FASTA)
alen_str = ""
iden_str = "_iden_"+str(iden)+"%"
if alen_percent:
alen_str = "_alen_"+str(alen)+"%"
if alen_bp:
alen_str = "_alen_"+str(alen)+"bp"
if iterations > 1:
prefix=name+"/results/"+name.split("/")[0]+"_iter_e_"+str(e_val)+iden_str+alen_str
else:
prefix=name+"/results/"+name.split("/")[0]+"_e_"+str(e_val)+iden_str+alen_str
if sheared:
prefix = prefix+'_sheared_'+str(shear_val)+"bp"
prefix = prefix + "_recruited_mg_"
#initializing log file data
logfile=name.split("/")[0]+"/results_log.csv"
try:
run = int(name.split("/")[-1].split("_")[-1])# using "_" less depends on the wrapper script
except:
if name.split("/")[-1].split("_")[-1]==name:
run = 0
else:
print "Warning: Run identifier could not be written in: "+logfile
#sys.exit(1)
run = None
alen_header = "Min alen"
if alen_bp:
alen_header = alen_header+" (bp)"
if alen_percent:
alen_header = alen_header+" (%)"
shear_header = "Reference Shear (bp)"
shear_log_value = 0
if sheared:
shear_log_value = str(shear_val)
print "\nWriting files:"
for i in range(len(mg_lst)):
records= []
if "csv" in fmt_lst:
outfile1 = prefix+str(i)+".csv"
recruited_mg[i].to_csv(outfile1, sep='\t')
print str(len(recruited_mg[i]))+" sequences written to "+outfile1
if "fasta" in fmt_lst:
ids = recruited_mg[i]['quid'].tolist()
#if len(ids)==len(sequences):
for j in range(len(ids)):
records.append(all_records[i][ids[j]])
outfile2 = prefix+str(i)+".fasta"
with open(outfile2, "w") as output_handle:
SeqIO.write(records, output_handle, "fasta")
print str(len(ids))+" sequences written to "+outfile2
#Writing logfile
try:
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
except:
print "Warning: Time identifier could not be written in: "+logfile
metagenome = mg_lst[i]
#contig info
rpkm_lst = np.array(recruited_mg[i]['Read_RPKM'].tolist())
if(len(rpkm_lst) > 0):
rpkm = np.sum(rpkm_lst)
rpkm_std= np.std(rpkm_lst)
rpkm_sem = np.std(rpkm_lst)*np.sqrt(len(rpkm_lst))
else:
rpkm = 0
rpkm_std= 0
rpkm_sem=0
sizes_lst = np.array(recruited_mg[i]['Contig_size'].tolist())
if(len(sizes_lst) > 0):
sizes_avg = np.mean(sizes_lst)
sizes_avg_std= np.std(sizes_lst)
if(len(sizes_lst) > 1):
sizes_avg_sem = stats.sem(sizes_lst, axis=0)
else:
sizes_avg_sem = 0
else:
sizes_avg = 0
sizes_avg_std= 0
sizes_avg_sem=0
#sizes_avg_sem = stats.sem(sizes_lst, axis=0)
alen_lst = np.array(recruited_mg[i]['alen'].tolist())
if(len(alen_lst) > 0):
alen_avg = np.mean(alen_lst)
alen_avg_std = np.std(alen_lst)
if(len(alen_lst) > 1):
alen_avg_sem = stats.sem(alen_lst, axis=0)
else:
alen_avg_sem = 0
else:
alen_avg = 0
alen_avg_std = 0
alen_avg_sem=0
#alen_avg_sem = stats.sem(alen_lst, axis=0)
iden_lst = np.array(recruited_mg[i]['iden'].tolist())
if(len(iden_lst) > 0):
iden_avg = np.mean(iden_lst)
iden_avg_std = np.std(iden_lst)
if(len(iden_lst) > 1):
iden_avg_sem = stats.sem(iden_lst, axis=0)
else:
iden_avg_sem = 0
else:
iden_avg = 0
iden_avg_std = 0
iden_avg_sem=0
#iden_avg_sem = stats.sem(iden_lst, axis=0)
gc_lst = np.array(recruited_mg[i]['Contig_GC'].tolist())
if(len(gc_lst) > 0):
gc_avg = np.mean(gc_lst)
gc_avg_std = np.std(gc_lst)
if(len(gc_lst) > 1):
gc_avg_sem = stats.sem(gc_lst, axis=0)
else:
gc_avg_sem = 0
else:
gc_avg = 0
gc_avg_std = 0
gc_avg_sem=0
if ref_cnt > 0:
recr_percent = float(len(ids))/float(len(all_records[i]))*100
else:
recr_percent = 0.0
#log_header = ['Run','Project Name','Created', 'Reference(s)','Metagenome', 'No. Contigs','No. References', alen_header, "Min iden (%)", shear_header, "Mean Contig Size (bp)","STD Contig Size", "SEM Contig Size", "Mean Contig alen (bp)","STD Contig alen", "SEM Contig alen", "Mean Contig iden (bp)","STD Contig iden", "SEM Contig iden", "Mean Contig GC (%)","STD Contig GC","SEM Contig GC","Mean Reference GC (%)","STD Reference GC","SEM Reference GC"]
log_header = ['Run','Project Name','Created', 'Reference(s)', shear_header,'No. Ref. Sequences','Metagenome','No. Metagenome Contigs' , alen_header, "Min iden (%)",'No. Recruited Contigs','% Recruited Contigs', 'Total RPKM', 'RPKM STD', 'RPKM SEM', "Mean Rec. Contig Size (bp)","STD Rec. Contig Size", "SEM Rec. Contig Size", "Mean alen (bp)","STD alen", "SEM alen", "Mean Rec. Contig iden (bp)","STD Rec. Contig iden", "SEM Rec. Contig iden", "Mean Rec. Contigs GC (%)","STD Rec. Contig GC","SEM Rec. Contig GC","Mean Total Reference(s) GC (%)","STD Total Reference(s) GC","SEM Total Reference(s) GC"]
#log_row = [run,name.split("/")[0],time_str, ";".join(ref_lst), metagenome, len(ids),ref_cnt, alen, iden, shear_log_value, sizes_avg,sizes_avg_std, sizes_avg_sem, alen_avg,alen_avg_std, alen_avg_sem, iden_avg,iden_avg_std, iden_avg_sem, gc_avg,gc_avg_std, gc_avg_sem,ref_gc_avg,ref_gc_avg_std, ref_gc_avg_sem]
log_row = [run,name.split("/")[0],time_str, ";".join(ref_lst), shear_log_value,ref_cnt, metagenome,len(all_records[i]) , alen, iden,len(ids),recr_percent,rpkm, rpkm_std, rpkm_sem, sizes_avg,sizes_avg_std, sizes_avg_sem, alen_avg,alen_avg_std, alen_avg_sem, iden_avg,iden_avg_std, iden_avg_sem, gc_avg,gc_avg_std, gc_avg_sem,ref_gc_avg,ref_gc_avg_std, ref_gc_avg_sem]
if os.path.isfile(logfile):#file exists - appending
with open(logfile, "a") as log_handle:
log_writer = csv.writer(log_handle, delimiter='\t')
log_writer.writerow(log_row)
else:#no file exists - writing
with open(logfile,"w") as log_handle:
log_writer = csv.writer(log_handle, delimiter='\t')
log_writer.writerow(log_header)
log_writer.writerow(log_row)
close_ind_lst(all_records)
close_ind_lst([all_input_recs])
#run = 0
#all_records[i].close()# keep open if multiple iterations
#recruited_mg_1 = pandas.read_csv(out_name1 ,sep="\t", header=None)
#recruited_mg_1.columns=['quid', 'suid', 'iden', 'alen', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits']
#recruited_mg_2 = pandas.read_csv(out_name2 ,sep="\t", header=None)
#recruited_mg_2.columns=['quid', 'suid', 'iden', 'alen', 'mism', 'gapo', 'qsta', 'qend', 'ssta', 'send', 'eval', 'bits']
#recruited_mg = [recruited_mg_1, recruited_mg_2]
# blast_db_Dir = ""
# results_Dir = ""
# input_files_Dir = ""
# parsed = SeqIO.parse(handle, "fasta")
#
# records = list()
#
#
# total = 0
# processed = 0
# for record in parsed:
# total += 1
# #print(record.id), len(record.seq)
# if len(record.seq) >= length:
# processed += 1
# records.append(record)
# handle.close()
#
# print "%d sequences found"%(total)
#
# try:
# output_handle = open(outfile, "w")
# SeqIO.write(records, output_handle, "fasta")
# output_handle.close()
# print "%d sequences written"%(processed)
# except:
# print "ERROR: Illegal output filename"
# sys.exit(1)
if __name__ == "__main__":
main(sys.argv[1:])
| {
"content_hash": "bd2788898bf98644c36473870cc4c4a0",
"timestamp": "",
"source": "github",
"line_count": 723,
"max_line_length": 610,
"avg_line_length": 37.26002766251729,
"alnum_prop": 0.544155313857233,
"repo_name": "dunfieldlab/mg_wrapser",
"id": "438b60a12d416abbb8f67f25cf730337216f89d3",
"size": "26958",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mg_wrapser_latest.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "53916"
},
{
"name": "Shell",
"bytes": "9334"
}
],
"symlink_target": ""
} |
<?php
namespace DNDCampaignManagerAPI\Server;
use DNDCampaignManagerAPI\Configuration\Configuration;
use DNDCampaignManagerAPI\ManagerRegistry\ConfigurationManagerRegistry;
use DNDCampaignManagerAPI\Server\Endpoints\CreaturesEndpoint;
use DNDCampaignManagerAPI\Server\ResourceAPIResponseDataFactories\CreatureAPIResponseDataFactory;
use DNDCampaignManagerAPI\Server\ResourceParameterFactories\CreaturesParametersFactory;
use LunixREST\Server\Router\EndpointFactory\RegisteredEndpointFactory;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
class EndpointFactory extends RegisteredEndpointFactory
{
use LoggerAwareTrait;
protected $registeredEndpointFactory;
protected $managerRepository;
/**
* EndpointFactory constructor.
* @param Configuration $configuration
* @param LoggerInterface $logger
*/
public function __construct(Configuration $configuration, LoggerInterface $logger)
{
$this->managerRepository = new ConfigurationManagerRegistry($configuration);
$this->logger = $logger;
$this->register('creatures', 1, $this->getCreaturesEndpoint());
}
private function getCreaturesEndpoint(): CreaturesEndpoint {
return new CreaturesEndpoint(
new CreaturesParametersFactory(),
new CreatureAPIResponseDataFactory(),
$this->logger,
$this->managerRepository
);
}
}
| {
"content_hash": "2aa2e8f04298411aed848938f820377f",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 97,
"avg_line_length": 35.5,
"alnum_prop": 0.7612676056338028,
"repo_name": "johnvandeweghe/DND-CampaignManager-API",
"id": "756c44ac965cc23311ba7ba1d530568de25121f9",
"size": "1420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Server/EndpointFactory.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "122418"
}
],
"symlink_target": ""
} |
package messages
import (
"github.com/stretchr/testify/require"
"testing"
"time"
)
func TestTimeConversion(t *testing.T) {
t.Run("converts to and from milliseconds since epoch (wall time)", func(t *testing.T) {
now := time.Unix(1, 234)
timestamp := GoTimeToTimestamp(now)
nowAgain := TimestampToGoTime(timestamp)
require.Equal(t, now, nowAgain)
})
t.Run("converts to and from duration (monotonic time)", func(t *testing.T) {
durationInNanoseconds, err := time.ParseDuration("1234ms")
require.NoError(t, err)
duration := GoDurationToDuration(durationInNanoseconds)
durationInNanosecondsAgain := DurationToGoDuration(duration)
require.Equal(t, durationInNanoseconds, durationInNanosecondsAgain)
})
t.Run("converts to and from duration (with nanoseconds)", func(t *testing.T) {
durationInNanoseconds, err := time.ParseDuration("3s890ns")
require.NoError(t, err)
duration := GoDurationToDuration(durationInNanoseconds)
durationInNanosecondsAgain := DurationToGoDuration(duration)
require.Equal(t, duration.Seconds, int64(3))
require.Equal(t, duration.Nanos, int64(890))
require.Equal(t, durationInNanoseconds, durationInNanosecondsAgain)
})
}
| {
"content_hash": "039b1e979bac0e205bb052a2e00ac070",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 88,
"avg_line_length": 31.263157894736842,
"alnum_prop": 0.7550505050505051,
"repo_name": "cucumber/cucumber",
"id": "dee626f3463d2b870ddea34d597fbaa5d28304ec",
"size": "1188",
"binary": false,
"copies": "1",
"ref": "refs/heads/retain-step-keyword",
"path": "messages/go/time_conversion_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "127"
},
{
"name": "C",
"bytes": "480225"
},
{
"name": "C#",
"bytes": "289774"
},
{
"name": "C++",
"bytes": "14849"
},
{
"name": "CMake",
"bytes": "3944"
},
{
"name": "CSS",
"bytes": "3355"
},
{
"name": "Dockerfile",
"bytes": "3553"
},
{
"name": "Gherkin",
"bytes": "8970"
},
{
"name": "Go",
"bytes": "425168"
},
{
"name": "HTML",
"bytes": "71036"
},
{
"name": "JSONiq",
"bytes": "2997"
},
{
"name": "Java",
"bytes": "695608"
},
{
"name": "JavaScript",
"bytes": "2853"
},
{
"name": "Makefile",
"bytes": "168761"
},
{
"name": "Objective-C",
"bytes": "242920"
},
{
"name": "Perl",
"bytes": "140453"
},
{
"name": "Python",
"bytes": "269889"
},
{
"name": "Ruby",
"bytes": "310834"
},
{
"name": "Shell",
"bytes": "47340"
},
{
"name": "TypeScript",
"bytes": "405056"
}
],
"symlink_target": ""
} |
#include "test.h"
__FBSDID("$FreeBSD: head/lib/libarchive/test/test_compat_solaris_tar_acl.c 201247 2009-12-30 05:59:21Z kientzle $");
/*
* Exercise support for reading Solaris-style ACL data
* from tar archives.
*
* This should work on all systems, regardless of whether local
* filesystems support ACLs or not.
*/
DEFINE_TEST(test_compat_solaris_tar_acl)
{
struct archive *a;
struct archive_entry *ae;
const char *reference1 = "test_compat_solaris_tar_acl.tar";
int type, permset, tag, qual;
const char *name;
/* Sample file generated on Solaris 10 */
extract_reference_file(reference1);
assert(NULL != (a = archive_read_new()));
assertA(0 == archive_read_support_format_all(a));
assertA(0 == archive_read_support_compression_all(a));
assertA(0 == archive_read_open_filename(a, reference1, 512));
/* Archive has 1 entry with some ACLs set on it. */
assertA(0 == archive_read_next_header(a, &ae));
failure("Basic ACLs should set mode to 0644, not %04o",
archive_entry_mode(ae)&0777);
assertEqualInt((archive_entry_mode(ae) & 0777), 0644);
assertEqualInt(7, archive_entry_acl_reset(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS));
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(006, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_USER_OBJ, tag);
assertEqualInt(-1, qual);
assert(name == NULL);
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(004, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_GROUP_OBJ, tag);
assertEqualInt(-1, qual);
assert(name == NULL);
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(004, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_OTHER, tag);
assertEqualInt(-1, qual);
assert(name == NULL);
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(001, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_USER, tag);
assertEqualInt(71, qual);
assertEqualString(name, "lp");
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(004, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_USER, tag);
assertEqualInt(666, qual);
assertEqualString(name, "666");
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(007, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_USER, tag);
assertEqualInt(1000, qual);
assertEqualString(name, "trasz");
assertEqualInt(ARCHIVE_OK, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
assertEqualInt(ARCHIVE_ENTRY_ACL_TYPE_ACCESS, type);
assertEqualInt(004, permset);
assertEqualInt(ARCHIVE_ENTRY_ACL_MASK, tag);
assertEqualInt(-1, qual);
assertEqualString(name, NULL);
assertEqualInt(ARCHIVE_EOF, archive_entry_acl_next(ae,
ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
&type, &permset, &tag, &qual, &name));
/* Close the archive. */
assertEqualIntA(a, ARCHIVE_OK, archive_read_close(a));
assertEqualInt(ARCHIVE_OK, archive_read_finish(a));
}
| {
"content_hash": "9ed7d702116db3cde9cfe1b013019672",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 116,
"avg_line_length": 34.77142857142857,
"alnum_prop": 0.7271980279375514,
"repo_name": "ayyucedemirbas/Minix-Source-Code",
"id": "ca1506a355ed721b05358f193218b3a88f4a8178",
"size": "4978",
"binary": false,
"copies": "30",
"ref": "refs/heads/master",
"path": "minix-master/external/bsd/libarchive/dist/libarchive/test/test_compat_solaris_tar_acl.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arc",
"bytes": "2839"
},
{
"name": "Assembly",
"bytes": "2637160"
},
{
"name": "Awk",
"bytes": "39398"
},
{
"name": "Brainfuck",
"bytes": "5114"
},
{
"name": "C",
"bytes": "45099473"
},
{
"name": "C++",
"bytes": "622042"
},
{
"name": "CSS",
"bytes": "254"
},
{
"name": "Emacs Lisp",
"bytes": "4528"
},
{
"name": "Groff",
"bytes": "6259659"
},
{
"name": "HTML",
"bytes": "57800"
},
{
"name": "IGOR Pro",
"bytes": "2975"
},
{
"name": "JavaScript",
"bytes": "20307"
},
{
"name": "Lex",
"bytes": "26563"
},
{
"name": "Limbo",
"bytes": "4037"
},
{
"name": "Logos",
"bytes": "14672"
},
{
"name": "Lua",
"bytes": "4385"
},
{
"name": "M4",
"bytes": "48559"
},
{
"name": "Makefile",
"bytes": "893777"
},
{
"name": "Max",
"bytes": "3667"
},
{
"name": "Objective-C",
"bytes": "26287"
},
{
"name": "Perl",
"bytes": "93049"
},
{
"name": "Perl6",
"bytes": "143"
},
{
"name": "Prolog",
"bytes": "97"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Shell",
"bytes": "2194049"
},
{
"name": "Terra",
"bytes": "89"
},
{
"name": "Yacc",
"bytes": "137952"
}
],
"symlink_target": ""
} |
/*
* File: UnixSocketServer.h
* Author: tiepologian <tiepolo.gian@gmail.com>
*
* Created on 14 giugno 2014, 19.36
*/
#ifndef UNIXSOCKETSERVER_H
#define UNIXSOCKETSERVER_H
#include <thread>
#include <utility>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include "TrisDb.h"
#include "message.pb.h"
#include "GenericServer.h"
#include "PackedMessage.h"
#include <cstdlib>
#include <atomic>
#include <memory>
#include <sys/stat.h>
class UnixSocketServer : public GenericServer {
public:
UnixSocketServer(TrisDb* db, std::string path);
UnixSocketServer(const UnixSocketServer& orig);
virtual ~UnixSocketServer();
virtual void run();
virtual void stop();
virtual int getOpenConnections();
std::atomic<int> cnx = ATOMIC_VAR_INIT(0);
private:
TrisDb* _db;
std::string _path;
boost::asio::io_service io_service;
void server();
};
class AsyncUnixSocketServer {
public:
AsyncUnixSocketServer(boost::asio::io_service& io_service, std::string filename, TrisDb* tris, UnixSocketServer* srv);
private:
void do_accept();
boost::asio::local::stream_protocol::acceptor acceptor_;
boost::asio::local::stream_protocol::socket socket_;
TrisDb* _db;
UnixSocketServer* _srv;
};
class AsyncUnixSocketSession : public std::enable_shared_from_this<AsyncUnixSocketSession> {
public:
AsyncUnixSocketSession(boost::asio::local::stream_protocol::socket socket, TrisDb* tris, UnixSocketServer* srv);
virtual ~AsyncUnixSocketSession();
void start();
typedef boost::shared_ptr<QueryRequest> RequestPointer;
typedef boost::shared_ptr<QueryResponse> ResponsePointer;
private:
TrisDb* _db;
UnixSocketServer* _srv;
void do_read();
void parseMessage(unsigned size);
void handle_read_header(const boost::system::error_code& error);
void handle_read_body(const boost::system::error_code& error);
boost::asio::local::stream_protocol::socket socket_;
std::vector<uint8_t> m_readbuf;
std::vector<google::protobuf::uint8> m_writebuf;
PackedMessage<QueryRequest> m_packed_request;
};
#endif /* UNIXSOCKETSERVER_H */
| {
"content_hash": "c926c7c27d7de5921049c64000e81d29",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 122,
"avg_line_length": 30.054794520547944,
"alnum_prop": 0.7128532360984503,
"repo_name": "tiepologian/trisdb",
"id": "d8622e366103450ce0b866682a3630f69d13ac99",
"size": "2194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/UnixSocketServer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "527011"
},
{
"name": "CMake",
"bytes": "5615"
},
{
"name": "Makefile",
"bytes": "583"
}
],
"symlink_target": ""
} |
package net.sansa_stack.rdf.spark.kge.convertor
/**
* Convertor Abstract Class
* ------------------------
*
* Trait for the Convertor
*
* Created by Hamed Shariat Yazdi
*/
import net.sansa_stack.rdf.spark.kge.triples._
import org.apache.spark.sql._
trait Convertor {
val (e, r) = (getEntities(), getRelations())
def getEntities(): Array[Row]
def getRelations(): Array[Row]
def numeric(): Dataset[IntegerTriples]
}
| {
"content_hash": "61eab9db0930b44542758f3ee85750a9",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 47,
"avg_line_length": 17.48,
"alnum_prop": 0.6544622425629291,
"repo_name": "SANSA-Stack/SANSA-RDF",
"id": "dd2f419bf13d0798a722a179becf637495f060b5",
"size": "437",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "sansa-rdf/sansa-rdf-spark/src/main/scala/net/sansa_stack/rdf/spark/kge/convertor/Convertor.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "78227"
},
{
"name": "Makefile",
"bytes": "22"
},
{
"name": "Scala",
"bytes": "542195"
},
{
"name": "Shell",
"bytes": "363"
}
],
"symlink_target": ""
} |
package mvnfind;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.regex.Pattern;
public class Arguments {
private static final Pattern INTEGER_PATTERN = Pattern.compile("^0|[1-9][0-9]*$");
public static Arguments parse(String... args) {
final Arguments arguments = new Arguments();
for (int i=0; i<args.length; i++) {
final String token = args[i];
if (token.equals("-h") || token.equals("--help")) {
arguments.help = true;
} else if (token.equals("-g") || token.equals("--groupId")) {
arguments.groupId = requiredParameter("groupId", args, ++i);
} else if (token.equals("-a") || token.equals("--artifactId")) {
arguments.artifactId = requiredParameter("artifactId", args, ++i);
} else if (token.equals("-v") || token.equals("--version")) {
arguments.version = requiredParameter("version", args, ++i);
} else if (token.equals("-p") || token.equals("--packaging")) {
arguments.packaging = requiredParameter("packaging", args, ++i);
} else if (token.equals("-l") || token.equals("--classifier")) {
arguments.classifier = requiredParameter("classifier", args, ++i);
} else if (token.equals("-c") || token.equals("--className")) {
arguments.className = requiredParameter("className", args, ++i);
} else if (token.equals("-f") || token.equals("--fullClassName")) {
arguments.fullClassName = requiredParameter("fullClassName", args, ++i);
} else if (token.equals("-1") || token.equals("--sha1")) {
arguments.sha1 = requiredParameter("sha1", args, ++i);
} else if (token.equals("-s") || token.equals("--start")) {
final int start = requiredIntParameter("start", args, ++i);
if (start < 0) {
throw new IllegalCommandLineArgsException("start must be greater than equal 0.");
}
arguments.start = start;
} else if (token.equals("-r") || token.equals("--rows")) {
final int rows = requiredIntParameter("rows", args, ++i);
if (rows < 0) {
throw new IllegalCommandLineArgsException("rows must be greater than 0.");
}
arguments.rows = rows;
} else if (token.equals("--httpProxy")) {
final String httpProxy = requiredParameter("httpProxy", args, ++i);
final String[] hostAndPort = httpProxy.split(":");
if (hostAndPort.length != 2) {
throw new IllegalCommandLineArgsException("httpProxy must be \"host:port\".");
}
if (!INTEGER_PATTERN.matcher(hostAndPort[1]).matches()) {
throw new IllegalCommandLineArgsException("httpProxy port must be integer.");
}
arguments.httpProxy = httpProxy;
arguments.proxyHost = hostAndPort[0];
arguments.proxyPort = Integer.valueOf(hostAndPort[1]);
} else if (token.equals("--proxyUser")) {
arguments.proxyUser = requiredParameter("proxyUser", args, ++i);
} else if (token.equals("--proxyPass")) {
arguments.proxyPass = requiredParameter("proxyPass", args, ++i);
} else if (token.equals("--debug")) {
arguments.debug = true;
} else if (token.equals("--all")) {
arguments.allVersions = true;
} else {
arguments.query = token;
}
}
return arguments;
}
private static String requiredParameter(String name, String[] args, int index) {
if (args.length <= index) {
throw new IllegalCommandLineArgsException(name + " must have a parameter.");
}
return args[index];
}
private static int requiredIntParameter(String name, String[] args, int index) {
if (args.length <= index) {
throw new IllegalCommandLineArgsException(name + " must have a parameter.");
}
final String text = args[index];
if (INTEGER_PATTERN.matcher(text).matches()) {
return Integer.parseInt(text);
} else {
throw new IllegalCommandLineArgsException(name + " must be integer.");
}
}
private boolean help;
private String groupId;
private String artifactId;
private String version;
private String packaging;
private String classifier;
private String className;
private String fullClassName;
private String sha1;
private Integer rows;
private Integer start;
private boolean allVersions;
private String httpProxy;
private String proxyHost;
private Integer proxyPort;
private String proxyUser;
private String proxyPass;
private String query;
private boolean debug;
private Arguments() {}
public boolean hasHelp() {
return help;
}
public Optional<String> getGroupId() {
return Optional.ofNullable(groupId);
}
public Optional<String> getArtifactId() {
return Optional.ofNullable(artifactId);
}
public Optional<String> getVersion() {
return Optional.ofNullable(version);
}
public Optional<String> getPackaging() {
return Optional.ofNullable(packaging);
}
public Optional<String> getClassifier() {
return Optional.ofNullable(classifier);
}
public Optional<String> getClassName() {
return Optional.ofNullable(className);
}
public Optional<String> getFullClassName() {
return Optional.ofNullable(fullClassName);
}
public Optional<String> getSha1() {
return Optional.ofNullable(sha1);
}
public OptionalInt getRows() {
return rows != null ? OptionalInt.of(rows) : OptionalInt.empty();
}
public Optional<String> getHttpProxy() {
return Optional.ofNullable(httpProxy);
}
public Optional<String> getProxyHost() {
return Optional.ofNullable(proxyHost);
}
public OptionalInt getProxyPort() {
return proxyPort != null ? OptionalInt.of(proxyPort) : OptionalInt.empty();
}
public Optional<String> getProxyUser() {
return Optional.ofNullable(proxyUser);
}
public Optional<String> getProxyPass() {
return Optional.ofNullable(proxyPass);
}
public Optional<String> getQuery() {
return Optional.ofNullable(query);
}
public boolean hasAdvancedOptions() {
return this.getGroupId().isPresent()
|| this.getArtifactId().isPresent()
|| this.getVersion().isPresent()
|| this.getPackaging().isPresent()
|| this.getClassifier().isPresent()
|| this.getClassName().isPresent()
|| this.getFullClassName().isPresent()
|| this.getSha1().isPresent();
}
public boolean isDebug() {
return debug;
}
public OptionalInt getStart() {
return start != null ? OptionalInt.of(start) : OptionalInt.empty();
}
public boolean isAllVersions() {
return allVersions;
}
}
| {
"content_hash": "2aa1ee81e40d1261e813a824ba39c2f3",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 101,
"avg_line_length": 36.467980295566505,
"alnum_prop": 0.5773335134404971,
"repo_name": "opengl-8080/MavenFind",
"id": "311854215d36dee2f3a5727cebdc8b2af3f74691",
"size": "7403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/mvnfind/Arguments.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "5781"
},
{
"name": "Java",
"bytes": "130"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a855820dfe0c275e888844d6751d9359",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e30adcab54a8fc6d5b11634c36cce92b45db3179",
"size": "166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Gypsophytum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
set -e # halt script on error
# Could you build a config file on the fly each time with a base url matching
# the name of the branch?
bundle exec jekyll build --config _config.yml
| {
"content_hash": "bb05e2b5beb04156d32ceed24dd35f47",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 77,
"avg_line_length": 36.2,
"alnum_prop": 0.7458563535911602,
"repo_name": "justwriteclick/versions-jekyll",
"id": "3cb2db431a6b8301321db2b6013e433953729fdd",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "script/build-travis.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "225"
},
{
"name": "JavaScript",
"bytes": "638"
},
{
"name": "Ruby",
"bytes": "4580"
},
{
"name": "Shell",
"bytes": "5941"
}
],
"symlink_target": ""
} |
<?php
class HomeController extends CloggyAppController {
public $uses = array('Cloggy.CloggyUser', 'Cloggy.CloggyValidation', 'Cloggy.CloggyUserLogin');
public $helpers = array('Form');
private $_userCount;
private $_userId;
public function beforeFilter() {
parent::beforeFilter();
//allow all
$this->Auth->allow();
/*
* check if has users
*/
$this->_userCount = $this->CloggyUser->find('count', array('contain' => false));
$this->_userId = $this->Auth->user('id');
}
public function index() {
/*
* check if user has logged in
*/
if ($this->Auth->loggedIn()) {
$this->redirect($this->Auth->loginRedirect);
}
$this->_redirectIfNoUsers();
$this->redirect(array('action' => 'login'));
}
public function login() {
//redirect if user empty
$this->_redirectIfNoUsers();
/*
* form submitted
*/
if ($this->request->is('post')) {
if ($this->Auth->login()) {//if user loggedIn
/*
* > set user id
* > set user last login time
* > set user login
* > redirect to dashboard
*/
$this->_userId = $this->Auth->user('id');
$this->CloggyUser->setUserLastLogin($this->_userId);
$this->CloggyUserLogin->setLogin($this->_userId);
$this->redirect($this->Auth->loginRedirect);
} else {
$this->Auth->flash(__d('cloggy','Wrong username or password'));
$this->redirect($this->Auth->loginAction);
}
}
$this->set('title_for_layout', __d('cloggy','Cloggy - Administrator Login'));
}
public function logout() {
/*
* > set user last login
* > remove user login
* > redirect to home controller
*/
$this->CloggyUser->setUserLastLogin($this->_userId);
$this->CloggyUserLogin->removeLogin($this->_userId);
$this->redirect($this->Auth->logout());
}
private function _redirectIfNoUsers() {
/*
* if there are no users
* then install (setup first users)
*/
if ($this->_userCount < 1) {
$this->redirect($this->_base . '/install');
}
}
} | {
"content_hash": "97e0fc6b41e75474d4ff51d6debcf59f",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 99,
"avg_line_length": 26.76086956521739,
"alnum_prop": 0.4930950446791227,
"repo_name": "hiraq/Cloggy",
"id": "c769c56d8a8f6a76e9850599855eee2914ffaafa",
"size": "2462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Controller/HomeController.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "624065"
},
{
"name": "Shell",
"bytes": "59"
}
],
"symlink_target": ""
} |
@implementation Workout
@dynamic workoutHeadbandCount;
@dynamic workoutShortColor;
@dynamic isBouncyHousePresent;
@end
| {
"content_hash": "052e88882efaf20cdd0d83fa1c63a974",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 30,
"avg_line_length": 17.285714285714285,
"alnum_prop": 0.8429752066115702,
"repo_name": "seltzered/CoreDataMagicalRecordTempObjectsDemo",
"id": "c912a5be39d4994fb91b53bee458dd3e96b760d7",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CoreDataMagicalRecordTempObjectsDemo/Workout.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6004"
},
{
"name": "C++",
"bytes": "6300"
},
{
"name": "Objective-C",
"bytes": "161932"
},
{
"name": "Ruby",
"bytes": "268"
},
{
"name": "Shell",
"bytes": "7104"
}
],
"symlink_target": ""
} |
class GameHelpers {
itemsOfTheArrayAreSame(cellArray) {
let allSame = true;
for (let i = 1; allSame && i < cellArray.length; i++) {
allSame = cellArray[0] && cellArray[i] === cellArray[0];
}
return !!allSame;
}
boardToColArray(board, colIndex) {
return board.map(boardRow => {
return boardRow[colIndex];
});
}
boardToDiagonalArray(board) {
return board.map((boardRow, rowIndex) => {
return boardRow[rowIndex];
});
}
isBoardFull(board){
let isBoardFull = true;
board.map(boardRow => {
boardRow.map(boardCell => {
isBoardFull = isBoardFull && !!boardCell;
});
});
return isBoardFull;
}
createWinnerCell(rowIndex, colIndex) {
return {rowIndex, colIndex};
}
createWinnerCellsFromRow(row, rowIndex) {
return row.map((cell, colIndex) => this.createWinnerCell(rowIndex, colIndex));
}
createWinnerCellsFromCol(cols, colIndex) {
return cols.map((cell, rowIndex) => this.createWinnerCell(rowIndex, colIndex));
}
createWinnerCellsFromDiagonal(newBoard) {
return newBoard.map((row, rowIndex) => this.createWinnerCell(rowIndex, rowIndex));
}
computeWinnerCells(newBoard, boardSize) {
let winnerCells = [];
const diagonal = this.boardToDiagonalArray(newBoard);
if (this.itemsOfTheArrayAreSame(diagonal)) {
winnerCells = this.createWinnerCellsFromDiagonal(newBoard);
} else {
for (let i = 0; winnerCells.length === 0 && i < boardSize; i++) {
const row = newBoard[i];
const col = this.boardToColArray(newBoard, i);
if (this.itemsOfTheArrayAreSame(row)) {
winnerCells = this.createWinnerCellsFromRow(row, i);
}
else if (this.itemsOfTheArrayAreSame(col)) {
winnerCells = this.createWinnerCellsFromCol(col, i);
}
}
}
return winnerCells;
}
isWinnerCell(winnerCells = [], rowIndex, colIndex) {
return winnerCells.filter(winnerCell => winnerCell.rowIndex === rowIndex && winnerCell.colIndex === colIndex).length > 0;
}
}
export default new GameHelpers(); | {
"content_hash": "821f61ed98d1cac446d9fd95b62d54ca",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 125,
"avg_line_length": 28.364864864864863,
"alnum_prop": 0.6479275845640782,
"repo_name": "cubbuk/tic-tac-toe",
"id": "5d9bf0d4c366d2cb432fe101baae73ed2a2f54f9",
"size": "2099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/reducers/game_reducers/game_helper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "712"
},
{
"name": "HTML",
"bytes": "209"
},
{
"name": "JavaScript",
"bytes": "29082"
}
],
"symlink_target": ""
} |
#import "TiModule.h"
#ifdef USE_TI_API
@interface APIModule : TiModule {
}
@end
#endif | {
"content_hash": "b0a256efe1267cf7eecb37241e4e7ea2",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 33,
"avg_line_length": 7.666666666666667,
"alnum_prop": 0.6739130434782609,
"repo_name": "arnaudsj/titanium_mobile",
"id": "3763b70bb62ebf978d5b2a874fdc32e24527ec77",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iphone/Classes/APIModule.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "252069"
},
{
"name": "C++",
"bytes": "47528"
},
{
"name": "Java",
"bytes": "2789001"
},
{
"name": "JavaScript",
"bytes": "1502307"
},
{
"name": "Objective-C",
"bytes": "2936179"
},
{
"name": "Python",
"bytes": "1534280"
},
{
"name": "Shell",
"bytes": "1642"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_13) on Mon Dec 14 15:24:35 MSK 2009 -->
<TITLE>
MissingRecordAwareHSSFListener (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2009-12-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MissingRecordAwareHSSFListener (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/MissingRecordAwareHSSFListener.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFUserException.html" title="class in org.apache.poi.hssf.eventusermodel"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="MissingRecordAwareHSSFListener.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.poi.hssf.eventusermodel</FONT>
<BR>
Class MissingRecordAwareHSSFListener</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html" title="interface in org.apache.poi.hssf.eventusermodel">HSSFListener</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public final class <B>MissingRecordAwareHSSFListener</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html" title="interface in org.apache.poi.hssf.eventusermodel">HSSFListener</A></DL>
</PRE>
<P>
<p>A HSSFListener which tracks rows and columns, and will
trigger your HSSFListener for all rows and cells,
even the ones that aren't actually stored in the file.</p>
<p>This allows your code to have a more "Excel" like
view of the data in the file, and not have to worry
(as much) about if a particular row/cell is in the
file, or was skipped from being written as it was
blank.
<P>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.html#MissingRecordAwareHSSFListener(org.apache.poi.hssf.eventusermodel.HSSFListener)">MissingRecordAwareHSSFListener</A></B>(<A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html" title="interface in org.apache.poi.hssf.eventusermodel">HSSFListener</A> listener)</CODE>
<BR>
Constructs a new MissingRecordAwareHSSFListener, which
will fire processRecord on the supplied child
HSSFListener for all Records, and missing records.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.html#processRecord(org.apache.poi.hssf.record.Record)">processRecord</A></B>(<A HREF="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</A> record)</CODE>
<BR>
process an HSSF Record.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="MissingRecordAwareHSSFListener(org.apache.poi.hssf.eventusermodel.HSSFListener)"><!-- --></A><H3>
MissingRecordAwareHSSFListener</H3>
<PRE>
public <B>MissingRecordAwareHSSFListener</B>(<A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html" title="interface in org.apache.poi.hssf.eventusermodel">HSSFListener</A> listener)</PRE>
<DL>
<DD>Constructs a new MissingRecordAwareHSSFListener, which
will fire processRecord on the supplied child
HSSFListener for all Records, and missing records.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>listener</CODE> - The HSSFListener to pass records on to</DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="processRecord(org.apache.poi.hssf.record.Record)"><!-- --></A><H3>
processRecord</H3>
<PRE>
public void <B>processRecord</B>(<A HREF="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</A> record)</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html#processRecord(org.apache.poi.hssf.record.Record)">HSSFListener</A></CODE></B></DD>
<DD>process an HSSF Record. Called when a record occurs in an HSSF file.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html#processRecord(org.apache.poi.hssf.record.Record)">processRecord</A></CODE> in interface <CODE><A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFListener.html" title="interface in org.apache.poi.hssf.eventusermodel">HSSFListener</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/MissingRecordAwareHSSFListener.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hssf/eventusermodel/HSSFUserException.html" title="class in org.apache.poi.hssf.eventusermodel"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="MissingRecordAwareHSSFListener.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2009 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| {
"content_hash": "b32d7e9131f599e19fc0251ea7500b8d",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 400,
"avg_line_length": 46.197879858657245,
"alnum_prop": 0.6392075875783999,
"repo_name": "tobyclemson/msci-project",
"id": "ddb54c0900dd2728b40f6ca0e6772ffb1c0a735d",
"size": "13074",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/poi-3.6/doc/apidocs/org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "89867"
},
{
"name": "Ruby",
"bytes": "137019"
}
],
"symlink_target": ""
} |
package com.atlassian.maven.plugins.refapp;
import com.atlassian.maven.plugins.amps.osgi.GenerateObrArtifactMojo;
/**
*
*/
public class RefappGenerateObrArtifactMojo extends GenerateObrArtifactMojo
{
}
| {
"content_hash": "3e57782b8acc8060e6c19f68963fcc5f",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 74,
"avg_line_length": 20.6,
"alnum_prop": 0.8155339805825242,
"repo_name": "mrdon/AMPS",
"id": "036b6790c0634a94f91972e85a74eda842620947",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "amps-product-plugins/maven-refapp-plugin/src/main/java/com/atlassian/maven/plugins/refapp/RefappGenerateObrArtifactMojo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "19002"
},
{
"name": "Java",
"bytes": "1466537"
},
{
"name": "JavaScript",
"bytes": "0"
},
{
"name": "Shell",
"bytes": "6977"
}
],
"symlink_target": ""
} |
package trace.mobile;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.StreamHandler;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.text.format.Formatter;
import android.widget.TextView;
import android.net.http.*;
/**
*
* @author petert
* 353230000000000;2011-03-24T17:17:00Z;109;01;80;00;0;0;0;0;13410;0;2;1;1300990620;62316018;17362360;0;0;198;4;000000000000;0;\\n
17:52 [johanl(johanl@kartena)] dr
17:52 [johanl(johanl@kartena)] {IMEI};{create
time};109;01;80;00;0;0;0;0;13410;0;2;1;{position unix
time};{lat};{long};0;0;198;4;000000000000;0;\\n
17:57 [johanl(johanl@kartena)] jag har rknat ut ngra wgs84 vrden som borde
motsvara ungefr 10m i respektive ledd
17:57 [johanl(johanl@kartena)] lat: 0,000093
17:57 [johanl(johanl@kartena)] long: 0,000160
17:58 [johanl(johanl@kartena)] borde vara giltigt hr i gbg ungefr
*/
public class LocationService {
private static Main activity = null;
public LocationService(Main activity) {
LocationService.activity = activity;
LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
TextView textView = (TextView)LocationService.activity.findViewById(R.id.textview);
try {
makeUseOfNewLocation(location);
} catch (NumberFormatException e) {
e.printStackTrace();
textView.setText(e.getMessage());
} catch (UnknownHostException e) {
e.printStackTrace();
textView.setText(e.getMessage());
} catch (IOException e) {
String host = LocationService.activity.getString(R.string.traceHost);
String appRoot = LocationService.activity.getString(R.string.appRoot);
String s = "http://"+host+"/"+appRoot+"/Login.aspx";
e.printStackTrace();
textView.setText(e.getMessage());
DefaultHttpClient dhc = new DefaultHttpClient();
try {
HttpResponse response = dhc.execute(new HttpHost(host), new HttpGet(s));
e.printStackTrace();
if (response.getStatusLine().getStatusCode() == 200) {
textView.setText("Started up PPF.");
onLocationChanged(location);
} else {
textView.setText("PPF is not running, failed to start.");
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
textView.setText("Failed to start PPF. " + e1.getMessage());
} catch (IOException e1) {
e1.printStackTrace();
textView.setText("Failed to start PPF. " + e1.getMessage());
}
}
}
private void makeUseOfNewLocation(Location location) throws NumberFormatException, UnknownHostException, IOException {
((TextView)LocationService.activity.findViewById(R.id.textview)).setText("Updating location...");
String dstName = LocationService.activity.getString(R.string.traceHost);
int dstPort = Integer.parseInt(LocationService.activity.getString(R.string.tracePort));
Socket socket = new Socket(dstName, dstPort);
//ObjectOutputStream out = (ObjectOutputStream) socket.getOutputStream();
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
TelephonyManager telMgr = (TelephonyManager) LocationService.activity.getSystemService(Context.TELEPHONY_SERVICE);
// {IMEI};{create time};109;01;80;00;0;0;0;0;13410;0;2;1;{position Unix time};{latitude};{longitude};0;0;{bearing/direction};4;000000000000;0;\\n
CharSequence createTime = DateFormat.format("yyyy-MM-ddTkk:mm:ssZ", location.getTime()); // TODO set to UTC (currently local time)...
StringBuilder a1maxMsg = new StringBuilder();
a1maxMsg.append(telMgr.getDeviceId() + ";");
a1maxMsg.append(createTime + ";");
a1maxMsg.append("109;01;80;00;0;0;0;0;13410;0;2;1;");
a1maxMsg.append((location.getTime() / 1000) + ";");
a1maxMsg.append(((long)(location.getLatitude() * 1000000)) + ";");
a1maxMsg.append(((long)(location.getLongitude() * 1000000))+ ";");
//a1maxMsg.append("0;0;");
a1maxMsg.append((int)location.getSpeed() + ";" + (int)location.getAltitude() + ";");
a1maxMsg.append((int)location.getBearing() + ";");
a1maxMsg.append("4;000000000000;0;");
((TextView)LocationService.activity.findViewById(R.id.textview)).setText("Sending location to server...");
try {
out.println(a1maxMsg.toString());
} catch (Exception e) {
((TextView)LocationService.activity.findViewById(R.id.textview)).setText(e.getMessage());
}
((TextView)LocationService.activity.findViewById(R.id.textview)).setText(a1maxMsg.toString());
out.flush();
out.close();
socket.close();
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 15000, 0, locationListener);
}
}
| {
"content_hash": "a42a1f4d6f401a37877b9d83597491a1",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 149,
"avg_line_length": 41.772413793103446,
"alnum_prop": 0.711738484398217,
"repo_name": "pthorin/trace-mobile",
"id": "72bfcde2894d71c3b33b5d4a2d2d0674c1a48a84",
"size": "6057",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/trace/mobile/LocationService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "7814"
}
],
"symlink_target": ""
} |
#include <QStringList>
#include <QString>
#include <QDebug>
#include <QList>
#include <QtXml>
#include <QDir>
#include "qlcfixturemode.h"
#include "qlcfixturedef.h"
#include "qlcfile.h"
#include "channelsgroup.h"
#include "collection.h"
#include "function.h"
#include "universe.h"
#include "fixture.h"
#include "chaser.h"
#include "scene.h"
#include "show.h"
#include "efx.h"
#include "doc.h"
#include "bus.h"
#include "rgbscriptscache.h"
#include "monitorproperties.h"
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#if defined(__APPLE__) || defined(Q_OS_MAC)
#include "audiocapture_portaudio.h"
#elif defined(WIN32) || defined (Q_OS_WIN)
#include "audiocapture_wavein.h"
#else
#include "audiocapture_alsa.h"
#endif
#else
#include "audiocapture_qt.h"
#endif
Doc::Doc(QObject* parent, int universes)
: QObject(parent)
, m_wsPath("")
, m_fixtureDefCache(new QLCFixtureDefCache)
, m_modifiersCache(new QLCModifiersCache)
, m_rgbScriptsCache(new RGBScriptsCache(this))
, m_ioPluginCache(new IOPluginCache(this))
, m_ioMap(new InputOutputMap(this, universes))
, m_masterTimer(new MasterTimer(this))
, m_inputCapture(NULL)
, m_monitorProps(NULL)
, m_mode(Design)
, m_kiosk(false)
, m_clipboard(new QLCClipboard(this))
, m_latestFixtureId(0)
, m_latestFixtureGroupId(0)
, m_latestChannelsGroupId(0)
, m_latestFunctionId(0)
, m_startupFunctionId(Function::invalidId())
{
Bus::init(this);
resetModified();
qsrand(QTime::currentTime().msec());
}
Doc::~Doc()
{
delete m_masterTimer;
m_masterTimer = NULL;
clearContents();
if (isKiosk() == false)
{
// TODO: is this still needed ??
//m_ioMap->saveDefaults();
}
delete m_ioMap;
m_ioMap = NULL;
delete m_ioPluginCache;
m_ioPluginCache = NULL;
delete m_modifiersCache;
m_modifiersCache = NULL;
delete m_fixtureDefCache;
m_fixtureDefCache = NULL;
}
void Doc::clearContents()
{
emit clearing();
m_clipboard->resetContents();
if (m_monitorProps != NULL)
m_monitorProps->reset();
destroyAudioCapture();
// Delete all function instances
QListIterator <quint32> funcit(m_functions.keys());
while (funcit.hasNext() == true)
{
Function* func = m_functions.take(funcit.next());
if (func == NULL)
continue;
emit functionRemoved(func->id());
delete func;
}
// Delete all fixture groups
QListIterator <quint32> grpit(m_fixtureGroups.keys());
while (grpit.hasNext() == true)
{
FixtureGroup* grp = m_fixtureGroups.take(grpit.next());
quint32 grpID = grp->id();
delete grp;
emit fixtureGroupRemoved(grpID);
}
// Delete all fixture instances
QListIterator <quint32> fxit(m_fixtures.keys());
while (fxit.hasNext() == true)
{
Fixture* fxi = m_fixtures.take(fxit.next());
quint32 fxID = fxi->id();
delete fxi;
emit fixtureRemoved(fxID);
}
// Delete all channels groups
QListIterator <quint32> grpchans(m_channelsGroups.keys());
while (grpchans.hasNext() == true)
{
ChannelsGroup* grp = m_channelsGroups.take(grpchans.next());
emit channelsGroupRemoved(grp->id());
delete grp;
}
m_orderedGroups.clear();
m_latestFunctionId = 0;
m_latestFixtureId = 0;
m_latestFixtureGroupId = 0;
m_latestChannelsGroupId = 0;
m_addresses.clear();
emit cleared();
}
void Doc::setWorkspacePath(QString path)
{
m_wsPath = path;
}
QString Doc::getWorkspacePath() const
{
return m_wsPath;
}
QString Doc::normalizeComponentPath(const QString& filePath) const
{
if (filePath.isEmpty())
return filePath;
QFileInfo f(filePath);
if (f.absolutePath().startsWith(getWorkspacePath()))
{
return QDir(getWorkspacePath()).relativeFilePath(f.absoluteFilePath());
}
else
{
return f.absoluteFilePath();
}
}
QString Doc::denormalizeComponentPath(const QString& filePath) const
{
if (filePath.isEmpty())
return filePath;
return QFileInfo(QDir(getWorkspacePath()), filePath).absoluteFilePath();
}
/*****************************************************************************
* Engine components
*****************************************************************************/
QLCFixtureDefCache* Doc::fixtureDefCache() const
{
return m_fixtureDefCache;
}
QLCModifiersCache* Doc::modifiersCache() const
{
return m_modifiersCache;
}
RGBScriptsCache* Doc::rgbScriptsCache() const
{
return m_rgbScriptsCache;
}
IOPluginCache* Doc::ioPluginCache() const
{
return m_ioPluginCache;
}
InputOutputMap* Doc::inputOutputMap() const
{
return m_ioMap;
}
MasterTimer* Doc::masterTimer() const
{
return m_masterTimer;
}
AudioCapture *Doc::audioInputCapture()
{
if (m_inputCapture == NULL)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#if defined(__APPLE__) || defined(Q_OS_MAC)
m_inputCapture = new AudioCapturePortAudio();
#elif defined(WIN32) || defined (Q_OS_WIN)
m_inputCapture = new AudioCaptureWaveIn();
#else
m_inputCapture = new AudioCaptureAlsa();
#endif
#else
m_inputCapture = new AudioCaptureQt();
#endif
}
return m_inputCapture;
}
void Doc::destroyAudioCapture()
{
qDebug() << "Destroying audio capture";
if (m_inputCapture != NULL)
{
if (m_inputCapture->isRunning())
m_inputCapture->stop();
delete m_inputCapture;
}
m_inputCapture = NULL;
}
/*****************************************************************************
* Modified status
*****************************************************************************/
bool Doc::isModified() const
{
return m_modified;
}
void Doc::setModified()
{
m_modified = true;
emit modified(true);
}
void Doc::resetModified()
{
m_modified = false;
emit modified(false);
}
/*****************************************************************************
* Main operating mode
*****************************************************************************/
void Doc::setMode(Doc::Mode mode)
{
/* Don't do mode switching twice */
if (m_mode == mode)
return;
m_mode = mode;
emit modeChanged(m_mode);
}
Doc::Mode Doc::mode() const
{
return m_mode;
}
void Doc::setKiosk(bool state)
{
m_kiosk = state;
}
bool Doc::isKiosk() const
{
return m_kiosk;
}
/*********************************************************************
* Clipboard
*********************************************************************/
QLCClipboard *Doc::clipboard()
{
return m_clipboard;
}
/*****************************************************************************
* Fixtures
*****************************************************************************/
quint32 Doc::createFixtureId()
{
/* This results in an endless loop if there are UINT_MAX-1 fixtures. That,
however, seems a bit unlikely. Are there even 4294967295-1 fixtures in
total in the whole world? */
while (m_fixtures.contains(m_latestFixtureId) == true ||
m_latestFixtureId == Fixture::invalidId())
{
m_latestFixtureId++;
}
return m_latestFixtureId;
}
bool Doc::addFixture(Fixture* fixture, quint32 id)
{
Q_ASSERT(fixture != NULL);
// No ID given, this method can assign one
if (id == Fixture::invalidId())
id = createFixtureId();
if (m_fixtures.contains(id) == true || id == Fixture::invalidId())
{
qWarning() << Q_FUNC_INFO << "a fixture with ID" << id << "already exists!";
return false;
}
else
{
fixture->setID(id);
m_fixtures.insert(id, fixture);
/* Patch fixture change signals thru Doc */
connect(fixture, SIGNAL(changed(quint32)),
this, SLOT(slotFixtureChanged(quint32)));
/* Keep track of fixture addresses */
for (uint i = fixture->universeAddress();
i < fixture->universeAddress() + fixture->channels(); i++)
{
m_addresses[i] = id;
}
// Add the fixture channels capabilities to the universe they belong
QList<Universe *> universes = inputOutputMap()->claimUniverses();
int uni = fixture->universe();
// TODO !!! if a universe for this fixture doesn't exist, add it !!!
QList<int> forcedHTP = fixture->forcedHTPChannels();
QList<int> forcedLTP = fixture->forcedLTPChannels();
for (quint32 i = 0 ; i < fixture->channels(); i++)
{
const QLCChannel* channel(fixture->channel(i));
if (forcedHTP.contains(i))
universes.at(uni)->setChannelCapability(fixture->address() + i,
channel->group(), Universe::HTP);
else if (forcedLTP.contains(i))
universes.at(uni)->setChannelCapability(fixture->address() + i,
channel->group(), Universe::LTP);
else
universes.at(uni)->setChannelCapability(fixture->address() + i,
channel->group());
ChannelModifier *mod = fixture->channelModifier(i);
universes.at(uni)->setChannelModifier(fixture->address() + i, mod);
}
inputOutputMap()->releaseUniverses(true);
emit fixtureAdded(id);
setModified();
return true;
}
}
bool Doc::deleteFixture(quint32 id)
{
if (m_fixtures.contains(id) == true)
{
Fixture* fxi = m_fixtures.take(id);
Q_ASSERT(fxi != NULL);
/* Keep track of fixture addresses */
QMutableHashIterator <uint,uint> it(m_addresses);
while (it.hasNext() == true)
{
it.next();
if (it.value() == id)
it.remove();
}
if (m_monitorProps != NULL)
m_monitorProps->removeFixture(id);
emit fixtureRemoved(id);
setModified();
delete fxi;
if (m_fixtures.count() == 0)
m_latestFixtureId = 0;
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "No fixture with id" << id;
return false;
}
}
bool Doc::replaceFixtures(QList<Fixture*> newFixturesList)
{
// Delete all fixture instances
QListIterator <quint32> fxit(m_fixtures.keys());
while (fxit.hasNext() == true)
{
Fixture* fxi = m_fixtures.take(fxit.next());
delete fxi;
}
m_latestFixtureId = 0;
m_addresses.clear();
foreach(Fixture *fixture, newFixturesList)
{
quint32 id = fixture->id();
// create a copy of the original cause remapping will
// destroy it later
Fixture *newFixture = new Fixture(this);
newFixture->setID(id);
newFixture->setName(fixture->name());
newFixture->setAddress(fixture->address());
newFixture->setUniverse(fixture->universe());
if (fixture->fixtureDef() != NULL && fixture->fixtureMode() != NULL)
{
QLCFixtureDef *def = fixtureDefCache()->fixtureDef(fixture->fixtureDef()->manufacturer(),
fixture->fixtureDef()->model());
QLCFixtureMode *mode = NULL;
if (def != NULL)
mode = def->mode(fixture->fixtureMode()->name());
newFixture->setFixtureDefinition(def, mode);
}
else
newFixture->setChannels(fixture->channels());
newFixture->setExcludeFadeChannels(fixture->excludeFadeChannels());
m_fixtures.insert(id, newFixture);
/* Patch fixture change signals thru Doc */
connect(newFixture, SIGNAL(changed(quint32)),
this, SLOT(slotFixtureChanged(quint32)));
/* Keep track of fixture addresses */
for (uint i = newFixture->universeAddress();
i < newFixture->universeAddress() + newFixture->channels(); i++)
{
m_addresses[i] = id;
}
m_latestFixtureId = id;
}
return true;
}
bool Doc::updateFixtureChannelCapabilities(quint32 id, QList<int> forcedHTP, QList<int> forcedLTP)
{
if (m_fixtures.contains(id) == true)
{
Fixture* fixture = m_fixtures[id];
// get exclusive access to the universes list
QList<Universe *> universes = inputOutputMap()->claimUniverses();
int uni = fixture->universe();
// Set forced HTP channels
if (!forcedHTP.isEmpty())
{
fixture->setForcedHTPChannels(forcedHTP);
for(int i = 0; i < forcedHTP.count(); i++)
{
int chIdx = forcedHTP.at(i);
const QLCChannel* channel(fixture->channel(chIdx));
if (channel->group() == QLCChannel::Intensity)
universes.at(uni)->setChannelCapability(fixture->address() + chIdx,
channel->group(),
Universe::ChannelType(Universe::HTP | Universe::Intensity));
else
universes.at(uni)->setChannelCapability(fixture->address() + chIdx,
channel->group(),
Universe::HTP);
}
}
// Set forced LTP channels
if (!forcedLTP.isEmpty())
{
fixture->setForcedLTPChannels(forcedLTP);
for(int i = 0; i < forcedLTP.count(); i++)
{
int chIdx = forcedLTP.at(i);
const QLCChannel* channel(fixture->channel(chIdx));
universes.at(uni)->setChannelCapability(fixture->address() + chIdx, channel->group(), Universe::LTP);
}
}
// set channels modifiers
for (quint32 i = 0; i < fixture->channels(); i++)
{
ChannelModifier *mod = fixture->channelModifier(i);
universes.at(uni)->setChannelModifier(fixture->address() + i, mod);
}
inputOutputMap()->releaseUniverses(true);
return true;
}
return false;
}
QList <Fixture*> Doc::fixtures() const
{
QMap <quint32, Fixture*> fixturesMap;
QHashIterator <quint32, Fixture*> hashIt(m_fixtures);
while (hashIt.hasNext())
{
hashIt.next();
fixturesMap.insert(hashIt.key(), hashIt.value());
}
return fixturesMap.values();
}
Fixture* Doc::fixture(quint32 id) const
{
return m_fixtures.value(id, NULL);
}
quint32 Doc::fixtureForAddress(quint32 universeAddress) const
{
return m_addresses.value(universeAddress, Fixture::invalidId());
}
int Doc::totalPowerConsumption(int& fuzzy) const
{
int totalPowerConsumption = 0;
// Make sure fuzzy starts from zero
fuzzy = 0;
QListIterator <Fixture*> fxit(fixtures());
while (fxit.hasNext() == true)
{
Fixture* fxi(fxit.next());
Q_ASSERT(fxi != NULL);
// Generic dimmer has no mode and physical
if (fxi->isDimmer() == false && fxi->fixtureMode() != NULL)
{
QLCPhysical phys = fxi->fixtureMode()->physical();
if (phys.powerConsumption() > 0)
totalPowerConsumption += phys.powerConsumption();
else
fuzzy++;
}
else
{
fuzzy++;
}
}
return totalPowerConsumption;
}
void Doc::slotFixtureChanged(quint32 id)
{
/* Keep track of fixture addresses */
Fixture* fxi = fixture(id);
// remove it
QMutableHashIterator <uint,uint> it(m_addresses);
while (it.hasNext() == true)
{
it.next();
if (it.value() == id)
{
qDebug() << Q_FUNC_INFO << " remove: " << it.key() << " val: " << it.value();
it.remove();
}
}
for (uint i = fxi->universeAddress(); i < fxi->universeAddress() + fxi->channels(); i++)
{
/*
* setting new universe and address calls this twice,
* with an tmp wrong address after the first call (old address() + new universe()).
* we only add if the channel is free, to prevent messing up things
*/
Q_ASSERT(!m_addresses.contains(i));
m_addresses[i] = id;
}
setModified();
emit fixtureChanged(id);
}
/*****************************************************************************
* Fixture groups
*****************************************************************************/
bool Doc::addFixtureGroup(FixtureGroup* grp, quint32 id)
{
Q_ASSERT(grp != NULL);
// No ID given, this method can assign one
if (id == FixtureGroup::invalidId())
id = createFixtureGroupId();
if (m_fixtureGroups.contains(id) == true || id == FixtureGroup::invalidId())
{
qWarning() << Q_FUNC_INFO << "a fixture group with ID" << id << "already exists!";
return false;
}
else
{
grp->setId(id);
m_fixtureGroups[id] = grp;
/* Patch fixture group change signals thru Doc */
connect(grp, SIGNAL(changed(quint32)),
this, SLOT(slotFixtureGroupChanged(quint32)));
emit fixtureGroupAdded(id);
setModified();
return true;
}
}
bool Doc::deleteFixtureGroup(quint32 id)
{
if (m_fixtureGroups.contains(id) == true)
{
FixtureGroup* grp = m_fixtureGroups.take(id);
Q_ASSERT(grp != NULL);
emit fixtureGroupRemoved(id);
setModified();
delete grp;
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "No fixture group with id" << id;
return false;
}
}
FixtureGroup* Doc::fixtureGroup(quint32 id) const
{
if (m_fixtureGroups.contains(id) == true)
return m_fixtureGroups[id];
else
return NULL;
}
QList <FixtureGroup*> Doc::fixtureGroups() const
{
return m_fixtureGroups.values();
}
quint32 Doc::createFixtureGroupId()
{
/* This results in an endless loop if there are UINT_MAX-1 fixture groups. That,
however, seems a bit unlikely. Are there even 4294967295-1 fixtures in
total in the whole world? */
while (m_fixtureGroups.contains(m_latestFixtureGroupId) == true ||
m_latestFixtureGroupId == FixtureGroup::invalidId())
{
m_latestFixtureGroupId++;
}
return m_latestFixtureGroupId;
}
void Doc::slotFixtureGroupChanged(quint32 id)
{
setModified();
emit fixtureGroupChanged(id);
}
/*********************************************************************
* Channels groups
*********************************************************************/
bool Doc::addChannelsGroup(ChannelsGroup *grp, quint32 id)
{
Q_ASSERT(grp != NULL);
// No ID given, this method can assign one
if (id == ChannelsGroup::invalidId())
id = createChannelsGroupId();
grp->setId(id);
m_channelsGroups[id] = grp;
if (m_orderedGroups.contains(id) == false)
m_orderedGroups.append(id);
emit channelsGroupAdded(id);
setModified();
return true;
}
bool Doc::deleteChannelsGroup(quint32 id)
{
if (m_channelsGroups.contains(id) == true)
{
ChannelsGroup* grp = m_channelsGroups.take(id);
Q_ASSERT(grp != NULL);
emit channelsGroupRemoved(id);
setModified();
delete grp;
int idx = m_orderedGroups.indexOf(id);
if (idx != -1)
m_orderedGroups.takeAt(idx);
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "No channels group with id" << id;
return false;
}
}
bool Doc::moveChannelGroup(quint32 id, int direction)
{
if (direction == 0 || m_orderedGroups.contains(id) == false)
return false;
int idx = m_orderedGroups.indexOf(id);
if (idx + direction < 0 || idx + direction >= m_orderedGroups.count())
return false;
qDebug() << Q_FUNC_INFO << m_orderedGroups;
m_orderedGroups.takeAt(idx);
m_orderedGroups.insert(idx + direction, id);
qDebug() << Q_FUNC_INFO << m_orderedGroups;
setModified();
return true;
}
ChannelsGroup* Doc::channelsGroup(quint32 id) const
{
if (m_channelsGroups.contains(id) == true)
return m_channelsGroups[id];
else
return NULL;
}
QList <ChannelsGroup*> Doc::channelsGroups() const
{
QList <ChannelsGroup*> orderedList;
for (int i = 0; i < m_orderedGroups.count(); i++)
{
orderedList.append(m_channelsGroups[m_orderedGroups.at(i)]);
}
return orderedList;
}
quint32 Doc::createChannelsGroupId()
{
while (m_channelsGroups.contains(m_latestChannelsGroupId) == true ||
m_latestChannelsGroupId == ChannelsGroup::invalidId())
{
m_latestChannelsGroupId++;
}
return m_latestChannelsGroupId;
}
/*****************************************************************************
* Functions
*****************************************************************************/
quint32 Doc::createFunctionId()
{
/* This results in an endless loop if there are UINT_MAX-1 functions. That,
however, seems a bit unlikely. Are there even 4294967295-1 functions in
total in the whole world? */
while (m_functions.contains(m_latestFunctionId) == true ||
m_latestFunctionId == Fixture::invalidId())
{
m_latestFunctionId++;
}
return m_latestFunctionId;
}
bool Doc::addFunction(Function* func, quint32 id)
{
Q_ASSERT(func != NULL);
if (id == Function::invalidId())
id = createFunctionId();
if (m_functions.contains(id) == true || id == Fixture::invalidId())
{
qWarning() << Q_FUNC_INFO << "a function with ID" << id << "already exists!";
return false;
}
else
{
// Listen to function changes
connect(func, SIGNAL(changed(quint32)),
this, SLOT(slotFunctionChanged(quint32)));
// Listen to function name changes
connect(func, SIGNAL(nameChanged(quint32)),
this, SLOT(slotFunctionNameChanged(quint32)));
// Make the function listen to fixture removals
connect(this, SIGNAL(fixtureRemoved(quint32)),
func, SLOT(slotFixtureRemoved(quint32)));
// Place the function in the map and assign it the new ID
m_functions[id] = func;
func->setID(id);
emit functionAdded(id);
setModified();
return true;
}
}
QList <Function*> Doc::functions() const
{
return m_functions.values();
}
QList<Function *> Doc::functionsByType(Function::Type type) const
{
QList <Function*> list;
foreach(Function *f, m_functions)
{
if (f != NULL && f->type() == type)
list.append(f);
}
return list;
}
bool Doc::deleteFunction(quint32 id)
{
if (m_functions.contains(id) == true)
{
Function* func = m_functions.take(id);
Q_ASSERT(func != NULL);
emit functionRemoved(id);
setModified();
delete func;
return true;
}
else
{
qWarning() << Q_FUNC_INFO << "No function with id" << id;
return false;
}
}
Function* Doc::function(quint32 id) const
{
if (m_functions.contains(id) == true)
return m_functions[id];
else
return NULL;
}
quint32 Doc::nextFunctionID()
{
quint32 tmpFID = m_latestFunctionId;
while (m_functions.contains(tmpFID) == true ||
tmpFID == Fixture::invalidId())
{
tmpFID++;
}
return tmpFID;
}
void Doc::setStartupFunction(quint32 fid)
{
m_startupFunctionId = fid;
}
quint32 Doc::startupFunction()
{
return m_startupFunctionId;
}
bool Doc::checkStartupFunction()
{
if (m_mode == Operate && m_startupFunctionId != Function::invalidId())
{
Function *func = function(m_startupFunctionId);
if (func != NULL)
{
func->start(masterTimer());
return true;
}
}
return false;
}
void Doc::slotFunctionChanged(quint32 fid)
{
setModified();
emit functionChanged(fid);
}
void Doc::slotFunctionNameChanged(quint32 fid)
{
setModified();
emit functionNameChanged(fid);
}
/*********************************************************************
* Monitor Properties
*********************************************************************/
MonitorProperties *Doc::monitorProperties()
{
if (m_monitorProps == NULL)
m_monitorProps = new MonitorProperties();
return m_monitorProps;
}
/*****************************************************************************
* Load & Save
*****************************************************************************/
bool Doc::loadXML(const QDomElement& root)
{
clearErrorLog();
if (root.tagName() != KXMLQLCEngine)
{
qWarning() << Q_FUNC_INFO << "Engine node not found";
return false;
}
emit loading();
if (root.hasAttribute(KXMLQLCStartupFunction))
{
quint32 sID = root.attribute(KXMLQLCStartupFunction).toUInt();
if (sID != Function::invalidId())
setStartupFunction(sID);
}
QDomNode node = root.firstChild();
while (node.isNull() == false)
{
QDomElement tag = node.toElement();
if (tag.tagName() == KXMLFixture)
{
Fixture::loader(tag, this);
}
else if (tag.tagName() == KXMLQLCFixtureGroup)
{
FixtureGroup::loader(tag, this);
}
else if (tag.tagName() == KXMLQLCChannelsGroup)
{
ChannelsGroup::loader(tag, this);
}
else if (tag.tagName() == KXMLQLCFunction)
{
Function::loader(tag, this);
}
else if (tag.tagName() == KXMLQLCBus)
{
/* LEGACY */
Bus::instance()->loadXML(tag);
}
else if (tag.tagName() == KXMLIOMap)
{
m_ioMap->loadXML(tag);
}
else if (tag.tagName() == KXMLQLCMonitorProperties)
{
monitorProperties()->loadXML(tag, this);
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown engine tag:" << tag.tagName();
}
node = node.nextSibling();
}
postLoad();
emit loaded();
return true;
}
bool Doc::saveXML(QDomDocument* doc, QDomElement* wksp_root)
{
QDomElement root;
Q_ASSERT(doc != NULL);
Q_ASSERT(wksp_root != NULL);
/* Create the master Engine node */
root = doc->createElement(KXMLQLCEngine);
if (startupFunction() != Function::invalidId())
{
root.setAttribute(KXMLQLCStartupFunction, QString::number(startupFunction()));
}
wksp_root->appendChild(root);
m_ioMap->saveXML(doc, &root);
/* Write fixtures into an XML document */
QListIterator <Fixture*> fxit(fixtures());
while (fxit.hasNext() == true)
{
Fixture* fxi(fxit.next());
Q_ASSERT(fxi != NULL);
fxi->saveXML(doc, &root);
}
/* Write fixture groups into an XML document */
QListIterator <FixtureGroup*> grpit(fixtureGroups());
while (grpit.hasNext() == true)
{
FixtureGroup* grp(grpit.next());
Q_ASSERT(grp != NULL);
grp->saveXML(doc, &root);
}
/* Write channel groups into an XML document */
QListIterator <ChannelsGroup*> chanGroups(channelsGroups());
while (chanGroups.hasNext() == true)
{
ChannelsGroup* grp(chanGroups.next());
Q_ASSERT(grp != NULL);
grp->saveXML(doc, &root);
}
/* Write functions into an XML document */
QListIterator <Function*> funcit(functions());
while (funcit.hasNext() == true)
{
Function* func(funcit.next());
Q_ASSERT(func != NULL);
func->saveXML(doc, &root);
}
if (m_monitorProps != NULL)
m_monitorProps->saveXML(doc, &root, this);
return true;
}
void Doc::appendToErrorLog(QString error)
{
if (m_errorLog.contains(error))
return;
m_errorLog.append(error);
m_errorLog.append("\n");
}
void Doc::clearErrorLog()
{
m_errorLog = "";
}
QString Doc::errorLog()
{
return m_errorLog;
}
void Doc::postLoad()
{
QListIterator <Function*> functionit(functions());
while (functionit.hasNext() == true)
{
Function* function(functionit.next());
Q_ASSERT(function != NULL);
function->postLoad();
}
}
| {
"content_hash": "a674f91e2099786c2a0b8aaffb519aad",
"timestamp": "",
"source": "github",
"line_count": 1114,
"max_line_length": 120,
"avg_line_length": 25.638240574506284,
"alnum_prop": 0.554742481005567,
"repo_name": "peternewman/qlcplus",
"id": "6d3b9e08153f65e1566aeaaa3f51c92f243650c8",
"size": "29176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/src/doc.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "3195"
},
{
"name": "Batchfile",
"bytes": "1428"
},
{
"name": "C",
"bytes": "222020"
},
{
"name": "C++",
"bytes": "5247693"
},
{
"name": "CSS",
"bytes": "10931"
},
{
"name": "HTML",
"bytes": "394014"
},
{
"name": "JavaScript",
"bytes": "106696"
},
{
"name": "NSIS",
"bytes": "9260"
},
{
"name": "Objective-C",
"bytes": "17578"
},
{
"name": "Prolog",
"bytes": "3407"
},
{
"name": "QML",
"bytes": "185718"
},
{
"name": "QMake",
"bytes": "146511"
},
{
"name": "Ruby",
"bytes": "15461"
},
{
"name": "Shell",
"bytes": "25664"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("7.PointInACircle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("7.PointInACircle")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e05f2b03-0e43-4957-b07c-2dedaf388f5a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "43fab663e135a60b7d0d7e5d1ffb8ae3",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.02777777777778,
"alnum_prop": 0.7451957295373666,
"repo_name": "kossov/Telerik-Academy",
"id": "8bbb34a0e93bd00759981b497f4f66cb1bfcbf24",
"size": "1408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C#/C#1/MyHomeworks/OperatorsAndExpressions/7.PointInACircle/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "907639"
},
{
"name": "CSS",
"bytes": "85660"
},
{
"name": "CoffeeScript",
"bytes": "3700"
},
{
"name": "HTML",
"bytes": "265090"
},
{
"name": "JavaScript",
"bytes": "1475083"
},
{
"name": "Smalltalk",
"bytes": "635"
}
],
"symlink_target": ""
} |
#include <aws/redshift/model/ModifyClusterRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::Redshift::Model;
using namespace Aws::Utils;
ModifyClusterRequest::ModifyClusterRequest() :
m_clusterIdentifierHasBeenSet(false),
m_clusterTypeHasBeenSet(false),
m_nodeTypeHasBeenSet(false),
m_numberOfNodes(0),
m_numberOfNodesHasBeenSet(false),
m_clusterSecurityGroupsHasBeenSet(false),
m_vpcSecurityGroupIdsHasBeenSet(false),
m_masterUserPasswordHasBeenSet(false),
m_clusterParameterGroupNameHasBeenSet(false),
m_automatedSnapshotRetentionPeriod(0),
m_automatedSnapshotRetentionPeriodHasBeenSet(false),
m_preferredMaintenanceWindowHasBeenSet(false),
m_clusterVersionHasBeenSet(false),
m_allowVersionUpgrade(false),
m_allowVersionUpgradeHasBeenSet(false),
m_hsmClientCertificateIdentifierHasBeenSet(false),
m_hsmConfigurationIdentifierHasBeenSet(false),
m_newClusterIdentifierHasBeenSet(false),
m_publiclyAccessible(false),
m_publiclyAccessibleHasBeenSet(false),
m_elasticIpHasBeenSet(false),
m_enhancedVpcRouting(false),
m_enhancedVpcRoutingHasBeenSet(false)
{
}
Aws::String ModifyClusterRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=ModifyCluster&";
if(m_clusterIdentifierHasBeenSet)
{
ss << "ClusterIdentifier=" << StringUtils::URLEncode(m_clusterIdentifier.c_str()) << "&";
}
if(m_clusterTypeHasBeenSet)
{
ss << "ClusterType=" << StringUtils::URLEncode(m_clusterType.c_str()) << "&";
}
if(m_nodeTypeHasBeenSet)
{
ss << "NodeType=" << StringUtils::URLEncode(m_nodeType.c_str()) << "&";
}
if(m_numberOfNodesHasBeenSet)
{
ss << "NumberOfNodes=" << m_numberOfNodes << "&";
}
if(m_clusterSecurityGroupsHasBeenSet)
{
unsigned clusterSecurityGroupsCount = 1;
for(auto& item : m_clusterSecurityGroups)
{
ss << "ClusterSecurityGroups.member." << clusterSecurityGroupsCount << "="
<< StringUtils::URLEncode(item.c_str()) << "&";
clusterSecurityGroupsCount++;
}
}
if(m_vpcSecurityGroupIdsHasBeenSet)
{
unsigned vpcSecurityGroupIdsCount = 1;
for(auto& item : m_vpcSecurityGroupIds)
{
ss << "VpcSecurityGroupIds.member." << vpcSecurityGroupIdsCount << "="
<< StringUtils::URLEncode(item.c_str()) << "&";
vpcSecurityGroupIdsCount++;
}
}
if(m_masterUserPasswordHasBeenSet)
{
ss << "MasterUserPassword=" << StringUtils::URLEncode(m_masterUserPassword.c_str()) << "&";
}
if(m_clusterParameterGroupNameHasBeenSet)
{
ss << "ClusterParameterGroupName=" << StringUtils::URLEncode(m_clusterParameterGroupName.c_str()) << "&";
}
if(m_automatedSnapshotRetentionPeriodHasBeenSet)
{
ss << "AutomatedSnapshotRetentionPeriod=" << m_automatedSnapshotRetentionPeriod << "&";
}
if(m_preferredMaintenanceWindowHasBeenSet)
{
ss << "PreferredMaintenanceWindow=" << StringUtils::URLEncode(m_preferredMaintenanceWindow.c_str()) << "&";
}
if(m_clusterVersionHasBeenSet)
{
ss << "ClusterVersion=" << StringUtils::URLEncode(m_clusterVersion.c_str()) << "&";
}
if(m_allowVersionUpgradeHasBeenSet)
{
ss << "AllowVersionUpgrade=" << std::boolalpha << m_allowVersionUpgrade << "&";
}
if(m_hsmClientCertificateIdentifierHasBeenSet)
{
ss << "HsmClientCertificateIdentifier=" << StringUtils::URLEncode(m_hsmClientCertificateIdentifier.c_str()) << "&";
}
if(m_hsmConfigurationIdentifierHasBeenSet)
{
ss << "HsmConfigurationIdentifier=" << StringUtils::URLEncode(m_hsmConfigurationIdentifier.c_str()) << "&";
}
if(m_newClusterIdentifierHasBeenSet)
{
ss << "NewClusterIdentifier=" << StringUtils::URLEncode(m_newClusterIdentifier.c_str()) << "&";
}
if(m_publiclyAccessibleHasBeenSet)
{
ss << "PubliclyAccessible=" << std::boolalpha << m_publiclyAccessible << "&";
}
if(m_elasticIpHasBeenSet)
{
ss << "ElasticIp=" << StringUtils::URLEncode(m_elasticIp.c_str()) << "&";
}
if(m_enhancedVpcRoutingHasBeenSet)
{
ss << "EnhancedVpcRouting=" << std::boolalpha << m_enhancedVpcRouting << "&";
}
ss << "Version=2012-12-01";
return ss.str();
}
void ModifyClusterRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| {
"content_hash": "f9c4fbe60de0587eaeb081e35541c7d3",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 119,
"avg_line_length": 28.973509933774835,
"alnum_prop": 0.6964571428571429,
"repo_name": "svagionitis/aws-sdk-cpp",
"id": "d442345ea6d1283c71f4a9aed370c8b64de9bc3e",
"size": "4948",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-redshift/source/model/ModifyClusterRequest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2313"
},
{
"name": "C++",
"bytes": "104799778"
},
{
"name": "CMake",
"bytes": "455533"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "243075"
},
{
"name": "Python",
"bytes": "72896"
},
{
"name": "Shell",
"bytes": "2803"
}
],
"symlink_target": ""
} |
from CIM14.CPSM.Equipment.Core.Curve import Curve
class ImpedanceVariationCurve(Curve):
"""An Impedance Variation Curve describes the change in Transformer Winding impedance values in relationship to tap step changes. The tap step is represented using the xValue, resistance using y1value, reactance using y2value, and magnetizing susceptance using y3value. The resistance (r), reactance (x), and magnetizing susceptance (b) of the associated TransformerWinding define the impedance when the tap is at neutral step. The curve values represent the change to the impedance from the neutral step values. The impedance at a non-neutral step is calculated by adding the neutral step impedance (from the TransformerWinding) to the delta value from the curve.
"""
def __init__(self, TapChanger=None, *args, **kw_args):
"""Initialises a new 'ImpedanceVariationCurve' instance.
@param TapChanger: An ImpedanceVariationCurve is defines impedance changes for a TapChanger.
"""
self._TapChanger = None
self.TapChanger = TapChanger
super(ImpedanceVariationCurve, self).__init__(*args, **kw_args)
_attrs = []
_attr_types = {}
_defaults = {}
_enums = {}
_refs = ["TapChanger"]
_many_refs = []
def getTapChanger(self):
"""An ImpedanceVariationCurve is defines impedance changes for a TapChanger.
"""
return self._TapChanger
def setTapChanger(self, value):
if self._TapChanger is not None:
self._TapChanger._ImpedanceVariationCurve = None
self._TapChanger = value
if self._TapChanger is not None:
self._TapChanger.ImpedanceVariationCurve = None
self._TapChanger._ImpedanceVariationCurve = self
TapChanger = property(getTapChanger, setTapChanger)
| {
"content_hash": "dcc794398b3eaa228eecbb94334a7b5f",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 672,
"avg_line_length": 46.743589743589745,
"alnum_prop": 0.7032364234777839,
"repo_name": "rwl/PyCIM",
"id": "b6e32b457ed8e818ef35f9e73af507d6295303c8",
"size": "2923",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CIM14/CPSM/Equipment/Wires/ImpedanceVariationCurve.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7420564"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" ?>
<Entity name="CPK">
<EntityLocation id="dataobject">
<FileLocation project="TobascoTest" folder="GeneratedEntity"></FileLocation>
<Namespaces>
<Namespace value="System.Dynamic"></Namespace>
</Namespaces>
<BaseClass value="DifferentBase"></BaseClass>
</EntityLocation>
<Properties>
<Property name="Training" required="true">
<DataType name="String" size="100"></DataType>
</Property>
<Property name="aaa" required="true">
<DataType name="ReadonlyChild" type="CPK1"></DataType>
</Property>
<Property name="Duur" required="true">
<DataType name="String" size="100"></DataType>
</Property>
<Property name="Kosten" required="true">
<DataType name="String" size="100"></DataType>
</Property>
</Properties>
</Entity> | {
"content_hash": "262e95e93d7d55d34fa3bb8accd13a9b",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 84,
"avg_line_length": 38.75,
"alnum_prop": 0.5881720430107527,
"repo_name": "VictordeBaare/Tobasco",
"id": "605a94909d58b87dd6d79a95b11d033237110df7",
"size": "932",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TobascoV2Test/Entities/TobascoTest1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "518397"
},
{
"name": "CSS",
"bytes": "1868"
},
{
"name": "HTML",
"bytes": "3517"
},
{
"name": "PLSQL",
"bytes": "712688"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers');
//JHtml::_('formbehavior.chosen', 'select');
JHtml::_('behavior.caption');
?>
<div class="archive<?php echo $this->pageclass_sfx;?>">
<?php if ($this->params->get('show_page_heading', 1)) : ?>
<div class="page-header">
<h1>
<?php echo $this->escape($this->params->get('page_heading')); ?>
</h1>
</div>
<?php endif; ?>
<form id="adminForm" action="<?php echo JRoute::_('index.php')?>" method="post" class="form-inline">
<fieldset class="filters">
<div class="filter-search">
<?php if ($this->params->get('filter_field') != 'hide') : ?>
<label class="filter-search-lbl element-invisible" for="filter-search"><?php echo JText::_('COM_CONTENT_TITLE_FILTER_LABEL').' '; ?></label>
<input type="text" name="filter-search" id="filter-search" value="<?php echo $this->escape($this->filter); ?>" class="inputbox span2" onchange="document.getElementById('adminForm').submit();" placeholder="<?php echo JText::_('COM_CONTENT_TITLE_FILTER_LABEL'); ?>" />
<?php endif; ?>
<?php echo $this->form->monthField; ?>
<?php echo $this->form->yearField; ?>
<?php echo $this->form->limitField; ?>
<button type="submit" class="btn btn-primary" style="vertical-align: top;"><?php echo JText::_('JGLOBAL_FILTER_BUTTON'); ?></button>
<input type="hidden" name="view" value="archive" />
<input type="hidden" name="option" value="com_content" />
<input type="hidden" name="limitstart" value="0" />
</div>
<br />
</fieldset>
<?php echo $this->loadTemplate('items'); ?>
</form>
</div>
| {
"content_hash": "33c248d4766193c2ee84f6336f1eaf24",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 268,
"avg_line_length": 39.5,
"alnum_prop": 0.6430379746835443,
"repo_name": "yaelduckwen/libriastore",
"id": "b081cc537c7e550d763a76938e96e4c3b33d910d",
"size": "1814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "joomla/templates/horme_3/html/com_content/archive/default.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "44"
},
{
"name": "CSS",
"bytes": "2779463"
},
{
"name": "HTML",
"bytes": "26380"
},
{
"name": "JavaScript",
"bytes": "2813038"
},
{
"name": "PHP",
"bytes": "24821947"
},
{
"name": "PLpgSQL",
"bytes": "2393"
},
{
"name": "SQLPL",
"bytes": "17688"
}
],
"symlink_target": ""
} |
package com.i_walletlive.paylive;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ProcessPaymentJSONResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"processPaymentJSONResult"
})
@XmlRootElement(name = "ProcessPaymentJSONResponse")
public class ProcessPaymentJSONResponse {
@XmlElement(name = "ProcessPaymentJSONResult")
protected String processPaymentJSONResult;
/**
* Gets the value of the processPaymentJSONResult property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProcessPaymentJSONResult() {
return processPaymentJSONResult;
}
/**
* Sets the value of the processPaymentJSONResult property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProcessPaymentJSONResult(String value) {
this.processPaymentJSONResult = value;
}
}
| {
"content_hash": "0c69669b211b15a3e51bb43c579189d0",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 118,
"avg_line_length": 26.171875,
"alnum_prop": 0.6662686567164179,
"repo_name": "DreamOval/iwallet-java-connector",
"id": "e7a06b7df46f77d4285d2eecc3058b87d1c70508",
"size": "1675",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/generated/iwallet/com/i_walletlive/paylive/ProcessPaymentJSONResponse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "125537"
}
],
"symlink_target": ""
} |
package org.mycontroller.standalone.db.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.mycontroller.standalone.MYCMessages.MESSAGE_TYPE_SET_REQ;
import org.mycontroller.standalone.db.DbException;
import org.mycontroller.standalone.db.tables.SensorVariable;
import org.mycontroller.standalone.metrics.MetricsUtils;
import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.support.ConnectionSource;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 0.0.2
*/
public class SensorVariableDaoImpl extends BaseAbstractDaoImpl<SensorVariable, Integer> implements SensorVariableDao {
private static final Logger _logger = LoggerFactory.getLogger(SensorVariableDaoImpl.class);
public SensorVariableDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, SensorVariable.class);
}
@Override
public void create(SensorVariable sensorVariable) {
try {
this.nodeIdSensorIdnullCheck(sensorVariable);
Integer count = this.getDao().create(sensorVariable);
_logger.debug("Created SensorVariable:[{}], Create count:{}", sensorVariable, count);
} catch (SQLException ex) {
_logger.error("unable to add SensorVariable:[{}]", sensorVariable, ex);
} catch (DbException dbEx) {
_logger.error("unable to create, sensorValue:{}", sensorVariable, dbEx);
}
}
@Override
public void createOrUpdate(SensorVariable sensorVariable) {
try {
this.nodeIdSensorIdnullCheck(sensorVariable);
CreateOrUpdateStatus status = this.getDao().createOrUpdate(sensorVariable);
_logger.debug("CreateOrUpdate SensorVariable:[{}],Create:{},Update:{},Lines Changed:{}",
sensorVariable, status.isCreated(), status.isUpdated(),
status.getNumLinesChanged());
} catch (SQLException ex) {
_logger.error("CreateOrUpdate failed, SensorVariable:[{}]", sensorVariable, ex);
} catch (DbException dbEx) {
_logger.error("unable to createOrUpdate, sensorValue:{}", sensorVariable, dbEx);
}
}
@Override
public void delete(SensorVariable sensorVariable) {
try {
int deleteCount = this.getDao().delete(sensorVariable);
_logger.debug("Deleted senosor:[{}], delete count:{}", sensorVariable, deleteCount);
} catch (SQLException ex) {
_logger.error("unable to delete, sensorValue:{}", sensorVariable, ex);
}
}
@Override
public void update(SensorVariable sensorVariable) {
try {
this.nodeIdSensorIdnullCheck(sensorVariable);
UpdateBuilder<SensorVariable, Integer> updateBuilder = this.getDao().updateBuilder();
updateBuilder.updateColumnValue(SensorVariable.KEY_UNIT, sensorVariable.getUnit());
if (sensorVariable.getValue() != null) {
updateBuilder.updateColumnValue(SensorVariable.KEY_VALUE, sensorVariable.getValue());
}
if (sensorVariable.getPreviousValue() != null) {
updateBuilder.updateColumnValue(SensorVariable.KEY_PREVIOUS_VALUE, sensorVariable.getPreviousValue());
}
if (sensorVariable.getTimestamp() != null) {
updateBuilder.updateColumnValue(SensorVariable.KEY_TIMESTAMP, sensorVariable.getTimestamp());
}
if (sensorVariable.getMetricType() != null) {
updateBuilder.updateColumnValue(SensorVariable.KEY_METRIC, sensorVariable.getMetricType());
}
if (sensorVariable.getVariableType() != null) {
updateBuilder.updateColumnValue(SensorVariable.KEY_VARIABLE_TYPE, sensorVariable.getVariableType());
}
if (sensorVariable.getId() != null) {
updateBuilder.where().eq(SensorVariable.KEY_ID, sensorVariable.getId());
} else {
updateBuilder.where().eq(SensorVariable.KEY_SENSOR_DB_ID, sensorVariable.getSensor().getId()).and()
.eq(SensorVariable.KEY_VARIABLE_TYPE, sensorVariable.getVariableType());
}
int updateCount = updateBuilder.update();
_logger.debug("Updated senosorValue:[{}], update count:{}", sensorVariable, updateCount);
} catch (SQLException ex) {
_logger.error("unable to get", ex);
} catch (DbException dbEx) {
_logger.error("unable to update, sensorValue:{}", sensorVariable, dbEx);
}
}
@Override
public List<SensorVariable> getAllBySensorId(Integer sensorRefId) {
try {
if (sensorRefId == null) {
return new ArrayList<SensorVariable>();
}
return this.getDao().queryForEq(SensorVariable.KEY_SENSOR_DB_ID, sensorRefId);
} catch (SQLException ex) {
_logger.error("unable to get all list with sensorRefId:{}", sensorRefId, ex);
return null;
}
}
@Override
public List<SensorVariable> getAllBySensorIds(List<Integer> sensorRefIds) {
try {
if (sensorRefIds == null) {
return new ArrayList<SensorVariable>();
}
return this.getDao().queryBuilder().selectColumns(SensorVariable.KEY_ID, SensorVariable.KEY_SENSOR_DB_ID)
.where().in(SensorVariable.KEY_SENSOR_DB_ID, sensorRefIds).query();
} catch (SQLException ex) {
_logger.error("unable to get all list with sensorRefIds:{}", sensorRefIds, ex);
return null;
}
}
@Override
public List<SensorVariable> getByVariableType(MESSAGE_TYPE_SET_REQ variableType) {
try {
if (variableType == null) {
return null;
}
return this.getDao().queryForEq(SensorVariable.KEY_VARIABLE_TYPE, variableType);
} catch (SQLException ex) {
_logger.error("unable to get all list with variableType: {}", variableType, ex);
return null;
}
}
@Override
public List<SensorVariable> getAllDoubleMetric(Integer sensorRefId) {
try {
if (sensorRefId == null) {
return null;
}
QueryBuilder<SensorVariable, Integer> queryBuilder = this.getDao().queryBuilder();
queryBuilder.where().eq(SensorVariable.KEY_SENSOR_DB_ID, sensorRefId).and()
.eq(SensorVariable.KEY_METRIC, MetricsUtils.METRIC_TYPE.DOUBLE);
return queryBuilder.query();
} catch (SQLException ex) {
_logger.error("unable to get all list with sensorRefId:{}, MetricType:{}", sensorRefId,
MetricsUtils.METRIC_TYPE.DOUBLE, ex);
return null;
}
}
@Override
public List<SensorVariable> getAll() {
try {
return this.getDao().queryForAll();
} catch (SQLException ex) {
_logger.error("unable to get all list", ex);
return null;
}
}
@Override
public SensorVariable get(Integer sensorRefId, MESSAGE_TYPE_SET_REQ messageVariableType) {
try {
nodeIdSensorIdnullCheck(sensorRefId, messageVariableType);
return this.getDao().queryForFirst(
this.getDao().queryBuilder()
.where().eq(SensorVariable.KEY_SENSOR_DB_ID, sensorRefId)
.and().eq(SensorVariable.KEY_VARIABLE_TYPE, messageVariableType).prepare());
} catch (SQLException ex) {
_logger.error("unable to get", ex);
} catch (DbException dbEx) {
_logger.error("unable to get, nodeId:{},sensorId:{}", sensorRefId, messageVariableType, dbEx);
}
return null;
}
@Override
public SensorVariable get(SensorVariable sensorVariable) {
try {
if (sensorVariable.getId() != null) {
return this.getDao().queryForId(sensorVariable.getId());
} else {
return this.get(sensorVariable.getSensor().getId(), sensorVariable.getVariableType());
}
} catch (SQLException ex) {
_logger.error("unable to get", ex);
return null;
}
}
@Override
public SensorVariable get(int id) {
try {
return this.getDao().queryForId(id);
} catch (SQLException ex) {
_logger.error("unable to get", ex);
return null;
}
}
private void nodeIdSensorIdnullCheck(Integer sensorRefId, MESSAGE_TYPE_SET_REQ messageVariableType)
throws DbException {
if (sensorRefId != null && messageVariableType != null) {
return;
} else {
throw new DbException("SensorId or NodeId should not be a NULL, sensorRefId:" + sensorRefId
+ ",messageVariableTypeId:" + messageVariableType);
}
}
private void nodeIdSensorIdnullCheck(SensorVariable sensorVariable) throws DbException {
if (sensorVariable != null && sensorVariable.getSensor() != null && sensorVariable.getVariableType() != null) {
return;
} else {
throw new DbException("SensorVariable or Sensor or VariableType should not be a NULL, SensorVariable:"
+ sensorVariable);
}
}
@Override
public List<Integer> getSensorVariableIds(Integer sensorRefId) {
List<SensorVariable> variables = this.getAllBySensorId(sensorRefId);
List<Integer> ids = new ArrayList<Integer>();
//TODO: should modify by query (RAW query)
for (SensorVariable sensorVariable : variables) {
ids.add(sensorVariable.getId());
}
return ids;
}
@Override
public List<SensorVariable> getAll(List<Integer> ids) {
return super.getAll(SensorVariable.KEY_ID, ids);
}
} | {
"content_hash": "86a1ea29a38dea422b23025698f235a5",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 119,
"avg_line_length": 40.524,
"alnum_prop": 0.6208666469252788,
"repo_name": "Dietmar-Franken/mycontroller",
"id": "6d4a450ae52796ec1d570bb1c5b049459c9da445",
"size": "10764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/mycontroller/standalone/db/dao/SensorVariableDaoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1062"
},
{
"name": "CSS",
"bytes": "177768"
},
{
"name": "HTML",
"bytes": "168573"
},
{
"name": "Java",
"bytes": "697633"
},
{
"name": "JavaScript",
"bytes": "272580"
},
{
"name": "Shell",
"bytes": "2909"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Parameter JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ParameterJsonUnmarshaller implements Unmarshaller<Parameter, JsonUnmarshallerContext> {
public Parameter unmarshall(JsonUnmarshallerContext context) throws Exception {
Parameter parameter = new Parameter();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
parameter.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Type", targetDepth)) {
context.nextToken();
parameter.setType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Value", targetDepth)) {
context.nextToken();
parameter.setValue(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Version", targetDepth)) {
context.nextToken();
parameter.setVersion(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("Selector", targetDepth)) {
context.nextToken();
parameter.setSelector(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SourceResult", targetDepth)) {
context.nextToken();
parameter.setSourceResult(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("LastModifiedDate", targetDepth)) {
context.nextToken();
parameter.setLastModifiedDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("ARN", targetDepth)) {
context.nextToken();
parameter.setARN(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return parameter;
}
private static ParameterJsonUnmarshaller instance;
public static ParameterJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ParameterJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "826b33388fb9021a90973901332f2d21",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 136,
"avg_line_length": 41.175824175824175,
"alnum_prop": 0.6015479049906592,
"repo_name": "jentfoo/aws-sdk-java",
"id": "400f59f4fa119338e5cf343dd5fbd7bf6a1ddfd1",
"size": "4327",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/ParameterJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SharedCoreModule } from 'moh-common-lib';
import { FormsModule } from '@angular/forms';
import { LocalStorageModule } from 'angular-2-local-storage';
import { RemoveChildComponent } from './remove-child.component';
import { AccountPersonalInformationComponent } from '../../../components/personal-information/personal-information.component';
import { MspAccountMaintenanceDataService } from '../../../services/msp-account-data.service';
import { MspPerson } from '../../../../../components/msp/model/msp-person.model';
import { Relationship } from '../../../../../models/relationship.enum';
describe('RemoveChildComponent', () => {
let component: RemoveChildComponent;
let fixture: ComponentFixture<RemoveChildComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AccountPersonalInformationComponent,
RemoveChildComponent
],
imports: [
FormsModule,
SharedCoreModule,
LocalStorageModule.withConfig({
prefix: 'ca.bc.gov.msp',
storageType: 'sessionStorage'
})
],
providers: [
MspAccountMaintenanceDataService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RemoveChildComponent);
component = fixture.componentInstance;
component.child = new MspPerson(Relationship.Child19To24);
component.phns = [''];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"content_hash": "24a311ad84266910bbcb7acb0e076fda",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 126,
"avg_line_length": 34.361702127659576,
"alnum_prop": 0.6712074303405573,
"repo_name": "bcgov/MyGovBC-MSP",
"id": "8b32e16967a4404cea0886ebc5ce1852396c73be",
"size": "1615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/modules/account/pages/child-info/remove-child/remove-child.component.spec.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2344"
},
{
"name": "HTML",
"bytes": "271916"
},
{
"name": "JavaScript",
"bytes": "34731"
},
{
"name": "SCSS",
"bytes": "38078"
},
{
"name": "Shell",
"bytes": "1487"
},
{
"name": "TypeScript",
"bytes": "1205347"
}
],
"symlink_target": ""
} |
LIB= LLVMSparcTargetInfo
.include <bsd.init.mk>
SPARC_OBJDIR!= cd ${.CURDIR}/../libLLVMSparcCodeGen && ${PRINTOBJDIR}
CPPFLAGS+= -I${SPARC_OBJDIR} -I${LLVM_SRCDIR}/lib/Target/Sparc
.PATH: ${LLVM_SRCDIR}/lib/Target/Sparc/TargetInfo
SRCS+= SparcTargetInfo.cpp
.if defined(HOSTLIB)
.include <bsd.hostlib.mk>
.else
.include <bsd.lib.mk>
.endif
| {
"content_hash": "d2c4c8b41ddaa0baac780c94708e645a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 21.5625,
"alnum_prop": 0.7275362318840579,
"repo_name": "veritas-shine/minix3-rpi",
"id": "99bd1c539d8a75b67f2f900121b75d5a1b0750de",
"size": "404",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "external/bsd/llvm/lib/libLLVMSparcTargetInfo/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89060"
},
{
"name": "Arc",
"bytes": "2839"
},
{
"name": "Assembly",
"bytes": "2791293"
},
{
"name": "Awk",
"bytes": "39398"
},
{
"name": "Bison",
"bytes": "137952"
},
{
"name": "C",
"bytes": "45473316"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "577647"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "254"
},
{
"name": "Emacs Lisp",
"bytes": "4528"
},
{
"name": "IGOR Pro",
"bytes": "2975"
},
{
"name": "JavaScript",
"bytes": "25168"
},
{
"name": "Logos",
"bytes": "14672"
},
{
"name": "Lua",
"bytes": "4385"
},
{
"name": "Makefile",
"bytes": "669790"
},
{
"name": "Max",
"bytes": "3667"
},
{
"name": "Objective-C",
"bytes": "62068"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Perl",
"bytes": "100129"
},
{
"name": "Perl6",
"bytes": "243"
},
{
"name": "Prolog",
"bytes": "97"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "SAS",
"bytes": "1711"
},
{
"name": "Shell",
"bytes": "2207644"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Dynamic CA Server</display-name>
<listener>
<listener-class>org.consec.dynamicca.utils.WebAppInitializer</listener-class>
</listener>
<context-param>
<param-name>conf-file</param-name>
<param-value>/etc/contrail/dynamic-ca-server/dynamic-ca-server.properties</param-value>
</context-param>
<servlet>
<servlet-name>Jersey REST Services</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.consec.dynamicca.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Services</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
| {
"content_hash": "5b2030c39f902aec0ed23ea2f2a0e985",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 118,
"avg_line_length": 42.92857142857143,
"alnum_prop": 0.6638935108153078,
"repo_name": "consec/ConSec",
"id": "0afbe0dc0fae41defe104af5798fc93d87db0a48",
"size": "1202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dynamic-ca-server/src/main/webapp/WEB-INF/web.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "5112"
},
{
"name": "CSS",
"bytes": "262571"
},
{
"name": "Cucumber",
"bytes": "15685"
},
{
"name": "HTML",
"bytes": "76686"
},
{
"name": "Java",
"bytes": "1268727"
},
{
"name": "JavaScript",
"bytes": "1158778"
},
{
"name": "Makefile",
"bytes": "6919"
},
{
"name": "PHP",
"bytes": "2878790"
},
{
"name": "Perl",
"bytes": "48337"
},
{
"name": "Python",
"bytes": "298646"
},
{
"name": "Ruby",
"bytes": "7994"
},
{
"name": "Shell",
"bytes": "22042"
}
],
"symlink_target": ""
} |
'use strict'
var test = require('tape')
test('test directives/partial.js', function (t) {
t.plan(4)
var directive = require('../../../lib/directives/partial')
var methods = new Map()
var methods2 = new Map()
t.equal('', directive({
context: {args: ['test']},
template: {methods: methods},
nested: function () {},
variable: 'content'
}))
methods2.set('test', `test(content) {
var output = []
// compiled
return output
}`)
t.equal('', directive({
context: {args: ['test'], parened: 'parened'},
template: {methods: methods},
nested: function () {},
variable: 'content'
}))
methods2.set('test', `test(content, parened) {
var output = []
// compiled
return output
}`)
t.looseEqual(methods, methods2)
t.throws(function () { directive({context: {args: []}}) }, /Exactly one arg required/)
})
| {
"content_hash": "598dcc0be6dfd97973cc96bd8e16fe34",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 88,
"avg_line_length": 20.928571428571427,
"alnum_prop": 0.5870307167235495,
"repo_name": "erickmerchant/atlatl",
"id": "c88d97e90dedd2f84beccdd5f96461110d64e176",
"size": "879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/lib/directives/partial.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "30981"
}
],
"symlink_target": ""
} |
"""Common utilities used in testing"""
import os
import fixtures
import testtools
_TRUE = ('True', '1')
class BaseTestCase(testtools.TestCase):
def setUp(self):
super(BaseTestCase, self).setUp()
if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE:
stdout = self.useFixture(fixtures.StringStream('stdout')).stream
self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
if os.environ.get('OS_STDERR_CAPTURE') in _TRUE:
stderr = self.useFixture(fixtures.StringStream('stderr')).stream
self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
self.log_fixture = self.useFixture(
fixtures.FakeLogger('oslo.packaging'))
self.useFixture(fixtures.NestedTempfile())
self.useFixture(fixtures.FakeLogger())
self.useFixture(fixtures.Timeout(30, True))
| {
"content_hash": "bba9c4b616573cebe8b6c670067bd57e",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 76,
"avg_line_length": 33.5,
"alnum_prop": 0.6636050516647531,
"repo_name": "markmc/oslo.packaging",
"id": "977d45f99277e440120c819004f55e946189819e",
"size": "1507",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oslo/packaging/tests/utils.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "7404"
},
{
"name": "Python",
"bytes": "30172"
}
],
"symlink_target": ""
} |
package com.uber.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class SupportLibraryFragmentWithoutOnCreateView extends Fragment {
private Object mOnCreateInitialisedField;
// BUG: Diagnostic contains: @NonNull field mOnCreateViewInitialisedField not initialized
private Object mOnCreateViewInitialisedField;
private Object mOnAttachInitialisedField;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mOnCreateInitialisedField = new Object();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mOnAttachInitialisedField = new Object();
}
}
| {
"content_hash": "81757f0a1ba161191f21668448d644b8",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 91,
"avg_line_length": 29.04,
"alnum_prop": 0.7961432506887053,
"repo_name": "uber/nullaway",
"id": "5879eab933e31eb1984c620536cc44b4b1ec3a8a",
"size": "726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nullaway/src/test/resources/com/uber/nullaway/testdata/android-error/SupportLibraryFragmentWithoutOnCreateView.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1313113"
},
{
"name": "Python",
"bytes": "2657"
},
{
"name": "Shell",
"bytes": "909"
}
],
"symlink_target": ""
} |
var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaults');
var Connection = require('./connection');
var Client = function(config) {
EventEmitter.call(this);
this.connectionParameters = new ConnectionParameters(config);
this.user = this.connectionParameters.user;
this.database = this.connectionParameters.database;
this.port = this.connectionParameters.port;
this.host = this.connectionParameters.host;
this.password = this.connectionParameters.password;
var c = config || {};
this._types = new TypeOverrides(c.types);
this.connection = c.connection || new Connection({
stream: c.stream,
ssl: this.connectionParameters.ssl,
keepAlive: c.keepAlive || false
});
this.queryQueue = [];
this.binary = c.binary || defaults.binary;
this.encoding = 'utf8';
this.processID = null;
this.secretKey = null;
this.ssl = this.connectionParameters.ssl || false;
};
util.inherits(Client, EventEmitter);
Client.prototype.connect = function(callback) {
var self = this;
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send startup message
con.on('connect', function() {
if(self.ssl) {
con.requestSsl();
} else {
con.startup(self.getStartupConf());
}
});
con.on('sslconnect', function() {
con.startup(self.getStartupConf());
});
function checkPgPass(cb) {
return function(msg) {
if (null !== self.password) {
cb(msg);
} else {
pgPass(self.connectionParameters, function(pass){
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass;
}
cb(msg);
});
}
};
}
//password request handling
con.on('authenticationCleartextPassword', checkPgPass(function() {
con.password(self.password);
}));
//password request handling
con.on('authenticationMD5Password', checkPgPass(function(msg) {
var inner = Client.md5(self.password + self.user);
var outer = Client.md5(Buffer.concat([new Buffer(inner), msg.salt]));
var md5password = "md5" + outer;
con.password(md5password);
}));
con.once('backendKeyData', function(msg) {
self.processID = msg.processID;
self.secretKey = msg.secretKey;
});
//hook up query handling events to connection
//after the connection initially becomes ready for queries
con.once('readyForQuery', function() {
//delegate rowDescription to active query
con.on('rowDescription', function(msg) {
self.activeQuery.handleRowDescription(msg);
});
//delegate dataRow to active query
con.on('dataRow', function(msg) {
self.activeQuery.handleDataRow(msg);
});
//delegate portalSuspended to active query
con.on('portalSuspended', function(msg) {
self.activeQuery.handlePortalSuspended(con);
});
//deletagate emptyQuery to active query
con.on('emptyQuery', function(msg) {
self.activeQuery.handleEmptyQuery(con);
});
//delegate commandComplete to active query
con.on('commandComplete', function(msg) {
self.activeQuery.handleCommandComplete(msg, con);
});
//if a prepared statement has a name and properly parses
//we track that its already been executed so we don't parse
//it again on the same client
con.on('parseComplete', function(msg) {
if(self.activeQuery.name) {
con.parsedStatements[self.activeQuery.name] = true;
}
});
con.on('copyInResponse', function(msg) {
self.activeQuery.handleCopyInResponse(self.connection);
});
con.on('copyData', function (msg) {
self.activeQuery.handleCopyData(msg, self.connection);
});
con.on('notification', function(msg) {
self.emit('notification', msg);
});
//process possible callback argument to Client#connect
if (callback) {
callback(null, self);
//remove callback for proper error handling
//after the connect event
callback = null;
}
self.emit('connect');
});
con.on('readyForQuery', function() {
var activeQuery = self.activeQuery;
self.activeQuery = null;
self.readyForQuery = true;
self._pulseQueryQueue();
if(activeQuery) {
activeQuery.handleReadyForQuery(con);
}
});
con.on('error', function(error) {
if(self.activeQuery) {
var activeQuery = self.activeQuery;
self.activeQuery = null;
return activeQuery.handleError(error, con);
}
if(!callback) {
return self.emit('error', error);
}
callback(error);
callback = null;
});
con.once('end', function() {
if ( callback ) {
// haven't received a connection message yet !
var err = new Error('Connection terminated');
callback(err);
callback = null;
return;
}
if(self.activeQuery) {
var disconnectError = new Error('Connection terminated');
self.activeQuery.handleError(disconnectError, con);
self.activeQuery = null;
}
self.emit('end');
});
con.on('notice', function(msg) {
self.emit('notice', msg);
});
};
Client.prototype.getStartupConf = function() {
var params = this.connectionParameters;
var data = {
user: params.user,
database: params.database
};
var appName = params.application_name || params.fallback_application_name;
if (appName) {
data.application_name = appName;
}
return data;
};
Client.prototype.cancel = function(client, query) {
if(client.activeQuery == query) {
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send cancel message
con.on('connect', function() {
con.cancel(client.processID, client.secretKey);
});
} else if(client.queryQueue.indexOf(query) != -1) {
client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
}
};
Client.prototype.setTypeParser = function(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn);
};
Client.prototype.getTypeParser = function(oid, format) {
return this._types.getTypeParser(oid, format);
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeIdentifier = function(str) {
var escaped = '"';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '"') {
escaped += c + c;
} else {
escaped += c;
}
}
escaped += '"';
return escaped;
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeLiteral = function(str) {
var hasBackslash = false;
var escaped = '\'';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '\'') {
escaped += c + c;
} else if (c === '\\') {
escaped += c + c;
hasBackslash = true;
} else {
escaped += c;
}
}
escaped += '\'';
if(hasBackslash === true) {
escaped = ' E' + escaped;
}
return escaped;
};
Client.prototype._pulseQueryQueue = function() {
if(this.readyForQuery===true) {
this.activeQuery = this.queryQueue.shift();
if(this.activeQuery) {
this.readyForQuery = false;
this.hasExecuted = true;
this.activeQuery.submit(this.connection);
} else if(this.hasExecuted) {
this.activeQuery = null;
this.emit('drain');
}
}
};
Client.prototype.copyFrom = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.copyTo = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.query = function(config, values, callback) {
//can take in strings, config object or query object
var query = (typeof config.submit == 'function') ? config :
new Query(config, values, callback);
if(this.binary && !query.binary) {
query.binary = true;
}
if(query._result) {
query._result._getTypeParser = this._types.getTypeParser.bind(this._types);
}
this.queryQueue.push(query);
this._pulseQueryQueue();
return query;
};
Client.prototype.end = function(cb) {
this.connection.end();
if (cb) {
this.connection.once('end', cb);
}
};
Client.md5 = function(string) {
return crypto.createHash('md5').update(string, 'utf-8').digest('hex');
};
// expose a Query constructor
Client.Query = Query;
module.exports = Client;
| {
"content_hash": "5feba65b596b427f60b9b6346b8859bc",
"timestamp": "",
"source": "github",
"line_count": 347,
"max_line_length": 90,
"avg_line_length": 25.703170028818445,
"alnum_prop": 0.6442426280973204,
"repo_name": "kingoffighter97/ReactNote",
"id": "a77e5d4805bce221c4e6dc1865845304dfd2dcda",
"size": "9150",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "node_modules/pg/lib/client.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1249"
},
{
"name": "JavaScript",
"bytes": "29985"
}
],
"symlink_target": ""
} |
package com.google.cloud.dialogflow.cx.v3beta1.stub;
import static com.google.cloud.dialogflow.cx.v3beta1.WebhooksClient.ListLocationsPagedResponse;
import static com.google.cloud.dialogflow.cx.v3beta1.WebhooksClient.ListWebhooksPagedResponse;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dialogflow.cx.v3beta1.CreateWebhookRequest;
import com.google.cloud.dialogflow.cx.v3beta1.DeleteWebhookRequest;
import com.google.cloud.dialogflow.cx.v3beta1.GetWebhookRequest;
import com.google.cloud.dialogflow.cx.v3beta1.ListWebhooksRequest;
import com.google.cloud.dialogflow.cx.v3beta1.ListWebhooksResponse;
import com.google.cloud.dialogflow.cx.v3beta1.UpdateWebhookRequest;
import com.google.cloud.dialogflow.cx.v3beta1.Webhook;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.protobuf.Empty;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Base stub class for the Webhooks service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@BetaApi
@Generated("by gapic-generator-java")
public abstract class WebhooksStub implements BackgroundResource {
public UnaryCallable<ListWebhooksRequest, ListWebhooksPagedResponse> listWebhooksPagedCallable() {
throw new UnsupportedOperationException("Not implemented: listWebhooksPagedCallable()");
}
public UnaryCallable<ListWebhooksRequest, ListWebhooksResponse> listWebhooksCallable() {
throw new UnsupportedOperationException("Not implemented: listWebhooksCallable()");
}
public UnaryCallable<GetWebhookRequest, Webhook> getWebhookCallable() {
throw new UnsupportedOperationException("Not implemented: getWebhookCallable()");
}
public UnaryCallable<CreateWebhookRequest, Webhook> createWebhookCallable() {
throw new UnsupportedOperationException("Not implemented: createWebhookCallable()");
}
public UnaryCallable<UpdateWebhookRequest, Webhook> updateWebhookCallable() {
throw new UnsupportedOperationException("Not implemented: updateWebhookCallable()");
}
public UnaryCallable<DeleteWebhookRequest, Empty> deleteWebhookCallable() {
throw new UnsupportedOperationException("Not implemented: deleteWebhookCallable()");
}
public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
listLocationsPagedCallable() {
throw new UnsupportedOperationException("Not implemented: listLocationsPagedCallable()");
}
public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
throw new UnsupportedOperationException("Not implemented: listLocationsCallable()");
}
public UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
throw new UnsupportedOperationException("Not implemented: getLocationCallable()");
}
@Override
public abstract void close();
}
| {
"content_hash": "43f283481023b53136df28ebb332b277",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 100,
"avg_line_length": 41.82432432432432,
"alnum_prop": 0.8168012924071082,
"repo_name": "googleapis/java-dialogflow-cx",
"id": "69892856bd6672d8bc94a3424d512cad53bd5b3e",
"size": "3690",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "google-cloud-dialogflow-cx/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/stub/WebhooksStub.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "31858414"
},
{
"name": "Python",
"bytes": "1229"
},
{
"name": "Shell",
"bytes": "20462"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<?dlps id="NurDep2"?>
<?dlps page-images="none" figure-images="no"?>
<?dlps transcription="other"?>
<!DOCTYPE TEI.2 SYSTEM "http://text.lib.virginia.edu/dtd/tei/tei-p4/tei2.dtd" [
<!ENTITY % POSTKB "INCLUDE">
<!ENTITY % TEI.extensions.ent SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.ent">
<!ENTITY % TEI.extensions.dtd SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.dtd">
<!ENTITY % ISOnum SYSTEM "http://text.lib.virginia.edu/charent/iso-num.ent"> %ISOnum;
]>
<TEI.2 id="NurDep2">
<teiHeader type="migrated" creator="Etext">
<fileDesc>
<titleStmt>
<title type="main">Rebecca Nurse Collection:
Ann Putnam, Sr. Vs. Rebecca Nurse</title>
<title type="sort">rebecca nurse collection ann putnam, sr vs rebecca nurse</title>
<author>Nurse, Rebecca</author>
<respStmt>
<resp>Creation of machine-readable version:</resp>
<name>Carolyn Fay, Electronic Text Center</name>
<resp>Creation of digital images:</resp>
<name/>
<resp>Conversion to TEI.2-conformant markup:</resp>
<name>University of Virginia Library Electronic Text Center.</name>
</respStmt>
</titleStmt>
<extent>ca. <num type="kilobytes">6</num> kilobytes</extent>
<publicationStmt>
<publisher>University of Virginia Library</publisher>
<pubPlace>Charlottesville, Virginia</pubPlace>
<idno type="ETC">NurDep2</idno>
<date value="1998">1998</date>
<availability status="public">
<p n="copyright">Copyright © 1998 by the Rector and Visitors of the University of Virginia</p>
<p n="access">Publicly accessible</p>
</availability>
<idno type="uva-pid">uva-lib:476591</idno>
</publicationStmt>
<seriesStmt>
<title>University of Virginia Library, Text collection</title>
<idno type="uva-set">UVA-LIB-Text</idno>
</seriesStmt>
<notesStmt>
<note>
<p>This document is part of a collection of documents pertaining to the Rebecca Nurse witchcraft trial of 1692 in Salem Village, Massachusetts, collected and edited by Richard B. Trask in "The Devil hath been raised." This electronic collection is a pilot project that is part of a larger digital enterprise which will collect together all of the documents pertaining to the Salem witchcraft trials. This enterprise is a project undertaken by the Electronic Text Center. Benjamin C. Ray, professor of Religious Studies, is the project supervisor.</p>
</note>
</notesStmt>
<sourceDesc>
<biblFull>
<titleStmt>
<title type="main">Rebecca Nurse Collection:
Ann Putnam, Sr. Vs. Rebecca Nurse</title>
<title level="m">"The Devil hath been raised:" A Documentary History of the Salem Village Witchcraft Outbreak of March 1692</title>
<title type="sort">rebecca nurse collection ann putnam, sr vs rebecca nurse</title>
<author>Rebecca Nurse</author>
<respStmt>
<resp>Editor</resp>
<name>Richard B. Trask</name>
</respStmt>
</titleStmt>
<editionStmt>
<p>Revised Edition</p>
</editionStmt>
<extent>p. 48</extent>
<publicationStmt>
<publisher>Yeoman Press</publisher>
<pubPlace>Danvers, Mass.</pubPlace>
<date value="1997">1997</date>
<idno type="callNo">Print copy consulted: personal copy</idno>
</publicationStmt>
</biblFull>
</sourceDesc>
</fileDesc>
<encodingDesc>
<projectDesc>
<p>Prepared for the University of Virginia Library Electronic Text Center.</p>
</projectDesc>
<editorialDecl>
<p>The images exist as archived TIFF images, one or more JPEG versions for general use, and thumbnail GIFs.</p>
<p>Some keywords in the header are a local Electronic Text Center scheme to aid in establishing analytical groupings.</p>
</editorialDecl>
</encodingDesc>
<profileDesc>
<creation>
<date value="1692-03-21">1692-03-21</date>;
<date value="1692-03-22">1692-03-22</date>;
<date value="1692-03-23">1692-03-23</date>
</creation>
<langUsage>
<language id="eng" usage="main">English</language>
</langUsage>
<textClass>
<keywords>
<term>nonfiction</term>
<term>prose</term>
<term>feminine</term>
</keywords>
</textClass>
</profileDesc>
<revisionDesc>
<change>
<date value="1998-07">July 1998</date>
<respStmt>
<resp>corrector</resp>
<name>Carolyn Fay, Electronic Text Center</name>
</respStmt>
<item>Added TEI header and tags.</item>
</change>
<change>
<date value="2005-07">July 2005</date>
<respStmt>
<resp>Corrector</resp>
<name>John Ivor Carlson</name>
</respStmt>
<item>Converted to XML and/or checked tags.</item>
</change>
<change>
<date value="2007-09">September 2007</date>
<respStmt>
<resp>Migration</resp>
<name>Ethan Gruber, University of Virginia Library</name>
</respStmt>
<item>Converted XML markup from TEI Lite to uva-dl-tei (TEI P4 with local customizations).</item>
</change>
<change>
<date value="2008-01">January 2008</date>
<respStmt>
<resp>Migration</resp>
<name>Greg Murray, University of Virginia Library</name>
</respStmt>
<item>Programmatically updated TEI header markup (but not header content) for minimal compliance with current QA requirements.</item>
</change>
</revisionDesc>
</teiHeader>
<text id="d1">
<body id="d2">
<div1 type="statement" n="1692-05-31" id="d3">
<head>
<hi rend="bold">MONDAY -WEDNESDAY, MARCH 21-23, 1692</hi><lb/>
<hi rend="bold">Ann Putnam, Sr. Vs. Rebecca Nurse</hi>
</head>
<p>
<hi rend="italic">This continuation of a deposition by Ann Putnam, Sr., relates to the
torments suffered by her during the several days prior to Rebecca
Nurse's witchcraft examination. The deposition was sworn to before
magistrates John Hathorne and Jonathan Corwin on May 31,1692.</hi>
</p><p>
21:th march being the day of the Examinati of martha Cory: I had not
many fitts tho I was very weak my strenth. being as I thought almost
gon: but on the:22 march 1691/92 the Apperishtion of Rebekah nurs
did againe sett upon in a most dreadfull maner very early in the morning
as soon as it was well light and now she appeared to me only in her
shift #[and night cap] and brought a litle Red book in hir hand urging
me vehemently to writ in hir book and because I would not yeald to hir
hellish temtations she threatened to tare my soule out of my body:
blasphemously denying the blessed God and the power of the Lord Jesus
Christ to save my soule and denying severall places of scripture which I
tould hir of to Repell hir hellish temtations and for near Two hours
together at this time the Apperishtions of Rebekah Nurs did temp and
tortor me before she left me as if indeed she would have kiled me: and
allso the grates part of this day with but very little respitt: 23
march: I am againe affleted by the Apperishtions of Rebekah nurs: and
martha Cory: but Cheafly by Rebekah nurs: </p>
</div1>
</body>
</text>
</TEI.2>
| {
"content_hash": "2476338cb3cdf32d02c32e0eb5683aa0",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 550,
"avg_line_length": 36.22222222222222,
"alnum_prop": 0.7510736196319019,
"repo_name": "JohannGillium/modern_english_ed",
"id": "e87ceb9fab7bfe61cf63d17763e5bdc7a6420682",
"size": "6520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XML/NurDep2.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19931"
},
{
"name": "HTML",
"bytes": "8251"
},
{
"name": "JavaScript",
"bytes": "1711"
},
{
"name": "Python",
"bytes": "3438"
},
{
"name": "Ruby",
"bytes": "75"
},
{
"name": "XSLT",
"bytes": "6581"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Device Management | Tarento Mobility</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<meta name="description" content="Tarento Device Management">
<!-- bootstrap 3.0.2 -->
<link href="./public/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- font Awesome -->
<link href="./public/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<!-- Ionicons -->
<link href="./public/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<!-- Theme style -->
<link href="./public/css/style.css" rel="stylesheet" type="text/css" />
<link href="./public/css/bootstrap-dialog.min.css" rel="stylesheet" type="text/css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<style type="text/css">
</style>
</head>
<body class="skin-black">
<!-- header logo: style can be found in header.less -->
<header class="header">
<a href="#" class="logo">
Tarento
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="navbar-right">
<ul class="nav navbar-nav">
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user"></i>
<input type="hidden" id="useridhidden" name="useridhidden" value="<?php print_r($user); ?>">
<input type="hidden" id="userhidden" name="userhidden" value="<?php print_r($user_id); ?>">
<span><?php
print_r($user);
?> <i class="caret"></i></span>
</a>
<ul class="dropdown-menu dropdown-custom dropdown-menu-right">
<!-- <li class="dropdown-header text-center">Account</li>
<li>
<a href="#">
<i class="fa fa-clock-o fa-fw pull-right"></i>
<span class="badge badge-success pull-right">10</span> Updates</a>
<a href="#">
<i class="fa fa-envelope-o fa-fw pull-right"></i>
<span class="badge badge-danger pull-right">5</span> Messages</a>
<a href="#"><i class="fa fa-magnet fa-fw pull-right"></i>
<span class="badge badge-info pull-right">3</span> Subscriptions</a>
<a href="#"><i class="fa fa-question fa-fw pull-right"></i> <span class=
"badge pull-right">11</span> FAQ</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<i class="fa fa-user fa-fw pull-right"></i>
Profile
</a>
<a data-toggle="modal" href="#modal-user-settings">
<i class="fa fa-cog fa-fw pull-right"></i>
Settings
</a>
</li>
<li class="divider"></li>
-->
<li>
<a href="/devices"><i class="fa fa-ban fa-fw pull-right"></i> Logout</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<div class="wrapper row-offcanvas row-offcanvas-left">
<!-- Left side column. contains the logo and sidebar -->
<aside class="left-side sidebar-offcanvas">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<!-- search form -->
<!-- <form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..."/>
<span class="input-group-btn">
<button type='submit' name='seach' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form> -->
<ul class="sidebar-menu">
<!-- <li>
<a href="dash">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li> -->
<li>
<a href="devices-user">
<i class="fa fa-gavel"></i> <span>Devices</span>
</a>
</li>
<!-- <li>
<a href="newdevice">
<i class="fa fa-globe"></i> <span>New Device </span>
</a>
</li> -->
<!-- <li>
<a href="resetpin">
<i class="glyphicon glyphicon-lock"></i> <span>Reset PIN </span>
</a>
</li> -->
<li>
<a href="changepwd" target="_blank">
<i class="glyphicon glyphicon-lock"></i> <span>Change Password </span>
</a>
</li>
<li>
<a href="resetpin">
<i class="glyphicon glyphicon-lock"></i> <span>Reset Pin </span>
</a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<aside class="right-side">
<section class="content">
<?php echo $content; ?>
</section><!-- /.content -->
</aside><!-- /.right-side -->
</div><!-- ./wrapper -->
<div class="footer footer-main">
Copyright © Tarento, 2015
</div>
<!-- jQuery 2.0.2 -->
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> -->
<script src="./public/js/jquery.min.js"></script>
<script src="./public/js/ChartNew.js"></script>
<script src="./public/js/d3.v3.min.js"></script>
<script src="./public/js/d3.tip.v0.6.3.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="./public/js/jquery.min.js" type="text/javascript"></script>
<!-- jQuery UI 1.10.3 -->
<script src="./public/js/jquery-ui-1.10.3.min.js" type="text/javascript"></script>
<!-- Bootstrap -->
<script src="./public/js/bootstrap.min.js" type="text/javascript"></script>
<!-- daterangepicker -->
<script src="./public/js/plugins/daterangepicker/daterangepicker.js" type="text/javascript"></script>
<!-- Director App -->
<script src="./public/js/Director/app.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var stuff = new Object();
var usertext=document.getElementById("useridhidden").value;
//alert(usertext);
stuff = {
"appId":1,
"apiToken":"111111",
"user_id":""+usertext+""
};
$.ajax({
url: 'device-management/list-device-details-user',
type: 'POST',
data: JSON.stringify(stuff),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(result) {
//console.log(usertext);
var getres=result["responseData"];
getres=getres[1];
//console.log(getres);
$.each(getres, function(i, item) {
var date = getres[i].created_at;
document.getElementById("userspan").innerHTML=getres[i].first_name;
document.getElementById("userspan").innerHTML+="<i class=caret></i>";
})
}
});
});
</script>
</body>
</html> | {
"content_hash": "66a4f9cf4f4def7065b457a3d8e23116",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 149,
"avg_line_length": 42.673151750972764,
"alnum_prop": 0.39089997264520837,
"repo_name": "TarentoIndia/TarentoDeviceManagement",
"id": "e0d64ef80948f597d5fa9b57f7b94f53a03d99ad",
"size": "10967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views-code-php/views/TDM/TDM/layout-user.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "128"
},
{
"name": "C",
"bytes": "6893"
},
{
"name": "CSS",
"bytes": "364002"
},
{
"name": "HTML",
"bytes": "21111"
},
{
"name": "JavaScript",
"bytes": "1622674"
},
{
"name": "Objective-C",
"bytes": "633740"
},
{
"name": "PHP",
"bytes": "327216"
},
{
"name": "Ruby",
"bytes": "215"
},
{
"name": "SQLPL",
"bytes": "26969"
},
{
"name": "Shell",
"bytes": "3942"
}
],
"symlink_target": ""
} |
<?php
include_once 'phing/filters/BaseParamFilterReader.php';
include_once 'phing/filters/ChainableReader.php';
/**
* Reads the first <code>n</code> lines of a stream.
* (Default is first 10 lines.)
* <p>
* Example:
* <pre><headfilter lines="3"/></pre>
* Or:
* <pre><filterreader classname="phing.filters.HeadFilter">
* <param name="lines" value="3"/>
* </filterreader></pre>
*
* @author <a href="mailto:yl@seasonfive.com">Yannick Lecaillez</a>
* @author hans lellelid, hans@velum.net
* @version $Revision: 1.6 $ $Date: 2007-12-20 16:44:58 +0100 (jeu., 20 déc. 2007) $
* @access public
* @see FilterReader
* @package phing.filters
*/
class HeadFilter extends BaseParamFilterReader implements ChainableReader {
/**
* Parameter name for the number of lines to be returned.
*/
const LINES_KEY = "lines";
/**
* Number of lines currently read in.
* @var integer
*/
private $_linesRead = 0;
/**
* Number of lines to be returned in the filtered stream.
* @var integer
*/
private $_lines = 10;
/**
* Returns first n lines of stream.
* @return the resulting stream, or -1
* if the end of the resulting stream has been reached
*
* @exception IOException if the underlying stream throws an IOException
* during reading
*/
function read($len = null) {
if ( !$this->getInitialized() ) {
$this->_initialize();
$this->setInitialized(true);
}
// note, if buffer contains fewer lines than
// $this->_lines this code will not work.
if($this->_linesRead < $this->_lines) {
$buffer = $this->in->read($len);
if($buffer === -1) {
return -1;
}
// now grab first X lines from buffer
$lines = explode("\n", $buffer);
$linesCount = count($lines);
// must account for possibility that the num lines requested could
// involve more than one buffer read.
$len = ($linesCount > $this->_lines ? $this->_lines - $this->_linesRead : $linesCount);
$filtered_buffer = implode("\n", array_slice($lines, 0, $len) );
$this->_linesRead += $len;
return $filtered_buffer;
}
return -1; // EOF, since the file is "finished" as far as subsequent filters are concerned.
}
/**
* Sets the number of lines to be returned in the filtered stream.
*
* @param integer $lines the number of lines to be returned in the filtered stream.
*/
function setLines($lines) {
$this->_lines = (int) $lines;
}
/**
* Returns the number of lines to be returned in the filtered stream.
*
* @return integer The number of lines to be returned in the filtered stream.
*/
function getLines() {
return $this->_lines;
}
/**
* Creates a new HeadFilter using the passed in
* Reader for instantiation.
*
* @param object A Reader object providing the underlying stream.
* Must not be <code>null</code>.
*
* @return object A new filter based on this configuration, but filtering
* the specified reader.
*/
function chain(Reader $reader) {
$newFilter = new HeadFilter($reader);
$newFilter->setLines($this->getLines());
$newFilter->setInitialized(true);
$newFilter->setProject($this->getProject());
return $newFilter;
}
/**
* Scans the parameters list for the "lines" parameter and uses
* it to set the number of lines to be returned in the filtered stream.
*/
private function _initialize() {
$params = $this->getParameters();
if ( $params !== null ) {
for($i = 0, $_i=count($params) ; $i < $_i; $i++) {
if ( self::LINES_KEY == $params[$i]->getName() ) {
$this->_lines = (int) $params[$i]->getValue();
break;
}
}
}
}
}
| {
"content_hash": "f3065ba497e0ea54dfe57562cbc5b756",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 99,
"avg_line_length": 29.818181818181817,
"alnum_prop": 0.5412757973733584,
"repo_name": "studiodev/archives",
"id": "8269f0f9ae49d5c08a2cdcad62a131a6f7ffdb7a",
"size": "5292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2012 - Portfolio V5/lib/vendor/symfony/lib/plugins/sfPropelPlugin/lib/vendor/phing/filters/HeadFilter.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "278127"
},
{
"name": "ApacheConf",
"bytes": "17574"
},
{
"name": "CSS",
"bytes": "947736"
},
{
"name": "ColdFusion",
"bytes": "42028"
},
{
"name": "HTML",
"bytes": "9820794"
},
{
"name": "Java",
"bytes": "30831"
},
{
"name": "JavaScript",
"bytes": "7757772"
},
{
"name": "Lasso",
"bytes": "24527"
},
{
"name": "PHP",
"bytes": "21467673"
},
{
"name": "Perl",
"bytes": "39266"
},
{
"name": "Python",
"bytes": "26247"
},
{
"name": "Smarty",
"bytes": "196757"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1fd76b314992d8fe5185663ef2734d9d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e557295fe472d3acf62f50d784d52dc0e0f2efbd",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lupinus/Lupinus sinaloensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.jsimpledb.kv.fdb;
import com.foundationdb.FDBException;
import com.foundationdb.KeyValue;
import com.foundationdb.MutationType;
import com.foundationdb.Range;
import com.foundationdb.ReadTransaction;
import com.foundationdb.Transaction;
import com.foundationdb.async.AsyncIterator;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.primitives.Bytes;
import java.util.Iterator;
import java.util.concurrent.Future;
import org.jsimpledb.kv.CloseableKVStore;
import org.jsimpledb.kv.KVPair;
import org.jsimpledb.kv.KVTransaction;
import org.jsimpledb.kv.KVTransactionException;
import org.jsimpledb.kv.RetryTransactionException;
import org.jsimpledb.kv.StaleTransactionException;
import org.jsimpledb.kv.TransactionTimeoutException;
import org.jsimpledb.util.ByteReader;
import org.jsimpledb.util.ByteUtil;
import org.jsimpledb.util.ByteWriter;
/**
* FoundationDB transaction.
*/
public class FoundationKVTransaction implements KVTransaction {
private static final byte[] MIN_KEY = ByteUtil.EMPTY; // minimum possible key (inclusive)
private static final byte[] MAX_KEY = new byte[] { (byte)0xff }; // maximum possible key (exclusive)
private final FoundationKVDatabase store;
private final Transaction tx;
private final byte[] keyPrefix;
private volatile boolean stale;
private volatile boolean canceled;
/**
* Constructor.
*/
FoundationKVTransaction(FoundationKVDatabase store, byte[] keyPrefix) {
Preconditions.checkArgument(store != null, "null store");
this.store = store;
this.tx = this.store.getDatabase().createTransaction();
this.keyPrefix = keyPrefix;
}
// KVTransaction
@Override
public FoundationKVDatabase getKVDatabase() {
return this.store;
}
/**
* Get the underlying {@link Transaction} associated with this instance.
*
* @return the associated transaction
*/
public Transaction getTransaction() {
return this.tx;
}
@Override
public void setTimeout(long timeout) {
Preconditions.checkArgument(timeout >= 0, "timeout < 0");
this.tx.options().setTimeout(timeout);
}
@Override
public Future<Void> watchKey(byte[] key) {
Preconditions.checkArgument(key != null, "null key");
if (this.stale)
throw new StaleTransactionException(this);
try {
return new FutureWrapper<Void>(this.tx.watch(this.addPrefix(key)));
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public byte[] get(byte[] key) {
if (this.stale)
throw new StaleTransactionException(this);
Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
try {
return this.tx.get(this.addPrefix(key)).get();
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public KVPair getAtLeast(byte[] minKey) {
if (this.stale)
throw new StaleTransactionException(this);
if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
return null;
return this.getFirstInRange(minKey, null, false);
}
@Override
public KVPair getAtMost(byte[] maxKey) {
if (this.stale)
throw new StaleTransactionException(this);
if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
maxKey = null;
return this.getFirstInRange(null, maxKey, true);
}
@Override
public Iterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) {
if (this.stale)
throw new StaleTransactionException(this);
if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
minKey = MAX_KEY;
if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
maxKey = null;
Preconditions.checkArgument(minKey == null || maxKey == null || ByteUtil.compare(minKey, maxKey) <= 0, "minKey > maxKey");
try {
return Iterators.transform(this.tx.getRange(this.addPrefix(minKey, maxKey),
ReadTransaction.ROW_LIMIT_UNLIMITED, reverse).iterator(), new Function<KeyValue, KVPair>() {
@Override
public KVPair apply(KeyValue kv) {
return new KVPair(FoundationKVTransaction.this.removePrefix(kv.getKey()), kv.getValue());
}
});
} catch (FDBException e) {
throw this.wrapException(e);
}
}
private KVPair getFirstInRange(byte[] minKey, byte[] maxKey, boolean reverse) {
try {
final AsyncIterator<KeyValue> i = this.tx.getRange(this.addPrefix(minKey, maxKey),
ReadTransaction.ROW_LIMIT_UNLIMITED, reverse).iterator();
if (!i.hasNext())
return null;
final KeyValue kv = i.next();
return new KVPair(this.removePrefix(kv.getKey()), kv.getValue());
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public void put(byte[] key, byte[] value) {
if (this.stale)
throw new StaleTransactionException(this);
Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
try {
this.tx.set(this.addPrefix(key), value);
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public void remove(byte[] key) {
if (this.stale)
throw new StaleTransactionException(this);
Preconditions.checkArgument(key.length == 0 || key[0] != (byte)0xff, "key starts with 0xff");
try {
this.tx.clear(this.addPrefix(key));
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public void removeRange(byte[] minKey, byte[] maxKey) {
if (this.stale)
throw new StaleTransactionException(this);
if (minKey != null && minKey.length > 0 && minKey[0] == (byte)0xff)
return;
if (maxKey != null && maxKey.length > 0 && maxKey[0] == (byte)0xff)
maxKey = null;
Preconditions.checkArgument(minKey == null || maxKey == null || ByteUtil.compare(minKey, maxKey) <= 0, "minKey > maxKey");
try {
this.tx.clear(this.addPrefix(minKey, maxKey));
} catch (FDBException e) {
throw this.wrapException(e);
}
}
@Override
public void commit() {
if (this.stale)
throw new StaleTransactionException(this);
this.stale = true;
try {
this.tx.commit().get();
} catch (FDBException e) {
throw this.wrapException(e);
} finally {
this.cancel();
}
}
@Override
public void rollback() {
if (this.stale)
return;
this.stale = true;
this.cancel();
}
@Override
public CloseableKVStore mutableSnapshot() {
throw new UnsupportedOperationException();
}
private void cancel() {
if (this.canceled)
return;
this.canceled = true;
try {
this.tx.cancel();
} catch (FDBException e) {
// ignore
}
}
@Override
public byte[] encodeCounter(long value) {
final ByteWriter writer = new ByteWriter(8);
ByteUtil.writeLong(writer, value);
final byte[] bytes = writer.getBytes();
this.reverse(bytes);
return bytes;
}
@Override
public long decodeCounter(byte[] bytes) {
if (this.stale)
throw new StaleTransactionException(this);
Preconditions.checkArgument(bytes.length == 8, "invalid encoded counter value length != 8");
bytes = bytes.clone();
this.reverse(bytes);
return ByteUtil.readLong(new ByteReader(bytes));
}
@Override
public void adjustCounter(byte[] key, long amount) {
if (this.stale)
throw new StaleTransactionException(this);
this.tx.mutate(MutationType.ADD, this.addPrefix(key), this.encodeCounter(amount));
}
private void reverse(byte[] bytes) {
int i = 0;
int j = bytes.length - 1;
while (i < j) {
final byte temp = bytes[i];
bytes[i] = bytes[j];
bytes[j] = temp;
i++;
j--;
}
}
// Other methods
/**
* Wrap the given {@link FDBException} in the appropriate {@link KVTransactionException}.
*
* @param e FoundationDB exception
* @return appropriate {@link KVTransactionException} with chained exception {@code e}
* @throws NullPointerException if {@code e} is null
*/
public KVTransactionException wrapException(FDBException e) {
try {
this.cancel();
} catch (KVTransactionException e2) {
// ignore
}
switch (e.getCode()) {
case ErrorCodes.TRANSACTION_TIMED_OUT:
case ErrorCodes.PAST_VERSION:
return new TransactionTimeoutException(this, e);
case ErrorCodes.NOT_COMMITTED:
case ErrorCodes.COMMIT_UNKNOWN_RESULT:
return new RetryTransactionException(this, e);
default:
return new KVTransactionException(this, e);
}
}
// Key prefixing
private byte[] addPrefix(byte[] key) {
return this.keyPrefix != null ? Bytes.concat(this.keyPrefix, key) : key;
}
private Range addPrefix(byte[] minKey, byte[] maxKey) {
return new Range(this.addPrefix(minKey != null ? minKey : MIN_KEY), this.addPrefix(maxKey != null ? maxKey : MAX_KEY));
}
private byte[] removePrefix(byte[] key) {
if (this.keyPrefix == null)
return key;
if (!ByteUtil.isPrefixOf(this.keyPrefix, key)) {
throw new IllegalArgumentException("read key " + ByteUtil.toString(key) + " not having "
+ ByteUtil.toString(this.keyPrefix) + " as a prefix");
}
final byte[] stripped = new byte[key.length - this.keyPrefix.length];
System.arraycopy(key, this.keyPrefix.length, stripped, 0, stripped.length);
return stripped;
}
}
| {
"content_hash": "7935e562d70adb15ce9c82784b6c4ac5",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 130,
"avg_line_length": 32.679127725856695,
"alnum_prop": 0.6050524308865586,
"repo_name": "tempbottle/jsimpledb",
"id": "35e815a0187715e1cc778777b1f7d1dd32d5d309",
"size": "10556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/org/jsimpledb/kv/fdb/FoundationKVTransaction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11303"
},
{
"name": "HTML",
"bytes": "29770969"
},
{
"name": "Java",
"bytes": "3695737"
},
{
"name": "JavaScript",
"bytes": "25330"
},
{
"name": "XSLT",
"bytes": "26413"
}
],
"symlink_target": ""
} |
<?php
# Author Bermi Ferrer - MIT LICENSE
class Status extends ActiveRecord
{
}
| {
"content_hash": "f39b8b098cff99a299af7583840b64df",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 35,
"avg_line_length": 10.375,
"alnum_prop": 0.7228915662650602,
"repo_name": "akelos/editam",
"id": "4e7b9aebeb62a95ee5146d0454db96b3b13bc6e3",
"size": "83",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "installer/editam_files/app/models/status.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "128307"
},
{
"name": "PHP",
"bytes": "364768"
}
],
"symlink_target": ""
} |
require 'color_decomposition/quadtree/quadtree'
require 'color_decomposition/quadtree/node'
require 'test/unit'
class TestColorComparator < Test::Unit::TestCase
include ColorDecomposition
def test_quadtree_rect
quadtree = Quadtree.new(2, 2)
assert_equal({ left: 0, top: 0, right: 2, bottom: 2 }, quadtree.root.rect)
nodes = quadtree.base_nodes
assert_equal({ left: 0, top: 0, right: 1, bottom: 1 }, nodes[0].rect)
assert_equal({ left: 1, top: 0, right: 2, bottom: 1 }, nodes[1].rect)
assert_equal({ left: 0, top: 1, right: 1, bottom: 2 }, nodes[2].rect)
assert_equal({ left: 1, top: 1, right: 2, bottom: 2 }, nodes[3].rect)
end
def test_quadtree_base_nodes
quadtree = Quadtree.new(6, 6)
assert_equal(16, quadtree.base_nodes.size)
quadtree = Quadtree.new(15, 15)
assert_equal(64, quadtree.base_nodes.size)
quadtree = Quadtree.new(250, 150)
assert_equal(16_384, quadtree.base_nodes.size)
end
end
| {
"content_hash": "b0be454bfcdbc0c4c15c4a51c5ae9811",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 78,
"avg_line_length": 33.172413793103445,
"alnum_prop": 0.6735966735966736,
"repo_name": "jonasbleyl/color-decomposition",
"id": "23e0ff83de19efac8c19891c3bf261cd63549c13",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/quadtree_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "14186"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="ntnu.master.nofall.MainActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
| {
"content_hash": "f329dffa712fe265c87c632d4ef7ecf4",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 64,
"avg_line_length": 32.45454545454545,
"alnum_prop": 0.6722689075630253,
"repo_name": "finnjohansen/NoFall",
"id": "e037f5e1c08b9dc8b1f3730d14b668f76eb69cc1",
"size": "357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/menu/main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "261986"
}
],
"symlink_target": ""
} |
var columnDefsLeft = [
{ headerName: "Function", field: 'function', minWidth: 150 },
{ headerName: "Value", field: 'value' },
{ headerName: "Times 10", valueGetter: 'getValue("value") * 10' }
];
var rowDataLeft = [
{ function: 'Number Squared', value: '=ctx.theNumber * ctx.theNumber' },
{ function: 'Number x 2', value: '=ctx.theNumber * 2' },
{ function: 'Today\'s Date', value: '=new Date().toLocaleDateString()' },
{ function: 'Sum A', value: '=ctx.sum("a")' },
{ function: 'Sum B', value: '=ctx.sum("b")' }
];
var gridOptionsLeft = {
columnDefs: columnDefsLeft,
defaultColDef: {
flex: 1
},
enableCellExpressions: true,
rowData: rowDataLeft,
context: {
theNumber: 4
},
};
///// Right table
var columnDefsRight = [
{headerName: 'A', field: 'a', width: 150, editable: true, newValueHandler: numberNewValueHandler, onCellValueChanged: cellValueChanged},
{headerName: 'B', field: 'b', width: 150, editable: true, newValueHandler: numberNewValueHandler, onCellValueChanged: cellValueChanged}
];
var rowDataRight = [
{a: 1, b: 22},
{a: 2, b: 33},
{a: 3, b: 44},
{a: 4, b: 55},
{a: 5, b: 66},
{a: 6, b: 77},
{a: 7, b: 88}
];
var gridOptionsRight = {
columnDefs: columnDefsRight,
defaultColDef: {
flex: 1
},
rowData: rowDataRight,
};
gridOptionsLeft.context.sum = function(field) {
var result = 0;
rowDataRight.forEach( function(item) {
result += item[field];
});
return result;
};
// tell Left grid to refresh when number changes
function onNewNumber(value) {
gridOptionsLeft.context.theNumber = new Number(value);
gridOptionsLeft.api.redrawRows();
}
// we want to convert the strings to numbers
function numberNewValueHandler(params) {
var valueAsNumber = parseFloat(params.newValue);
var field = params.colDef.field;
var data = params.data;
data[field] = valueAsNumber;
}
// we want to tell the Left grid to refresh when the Right grid values change
function cellValueChanged() {
gridOptionsLeft.api.redrawRows();
}
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDivLeft = document.querySelector('#myGridLeft');
new agGrid.Grid(gridDivLeft, gridOptionsLeft);
var gridDivRight = document.querySelector('#myGridRight');
new agGrid.Grid(gridDivRight, gridOptionsRight);
});
| {
"content_hash": "2d9c6369596d616dccfc6681132c6c0f",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 140,
"avg_line_length": 29.261904761904763,
"alnum_prop": 0.6517493897477624,
"repo_name": "ceolter/ag-grid",
"id": "3ab61ad70326686ba4d5828917aafa445108bafc",
"size": "2475",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "grid-packages/ag-grid-docs/documentation/doc-pages/cell-expressions/examples/cell-expressions/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37765"
},
{
"name": "JavaScript",
"bytes": "22118"
},
{
"name": "TypeScript",
"bytes": "1267988"
}
],
"symlink_target": ""
} |
package de.philipphager.disclosure.util.time;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.threeten.bp.Duration;
import org.threeten.bp.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StopwatchShould {
@Mock protected Clock clock;
@InjectMocks protected Stopwatch stopwatch;
@Test(expected = IllegalStateException.class)
public void forbidCallingStopBeforeCallStart() {
stopwatch.stop();
}
@Test public void measureDurationTime() {
LocalDateTime mockStart = LocalDateTime.of(2016, 1, 1, 0, 0, 0);
LocalDateTime mockEnd = LocalDateTime.of(2016, 1, 1, 0, 1, 0);
when(clock.now()).thenReturn(mockStart);
stopwatch.start();
when(clock.now()).thenReturn(mockEnd);
stopwatch.stop();
assertThat(stopwatch.getDuration()).isEqualTo(Duration.between(mockStart, mockEnd));
}
@Test @SuppressWarnings("PMD.JUnitTestContainsTooManyAsserts")
public void resetAfterRestart() {
LocalDateTime firstMockStart = LocalDateTime.of(2016, 1, 1, 0, 0, 0);
LocalDateTime firstMockEnd = LocalDateTime.of(2016, 1, 1, 0, 1, 0);
when(clock.now()).thenReturn(firstMockStart);
stopwatch.start();
when(clock.now()).thenReturn(firstMockEnd);
stopwatch.stop();
Duration firstActualDuration = Duration.between(firstMockStart, firstMockEnd);
Duration firstMeasuredDuration = stopwatch.getDuration();
assertThat(firstMeasuredDuration).isEqualTo(firstActualDuration);
LocalDateTime secondMockStart = LocalDateTime.of(2016, 1, 1, 0, 5, 0);
LocalDateTime secondMockEnd = LocalDateTime.of(2016, 1, 1, 0, 10, 0);
when(clock.now()).thenReturn(secondMockStart);
stopwatch.start();
when(clock.now()).thenReturn(secondMockEnd);
stopwatch.stop();
Duration secondActualDuration = Duration.between(secondMockStart, secondMockEnd);
Duration secondMeasuredDuration = stopwatch.getDuration();
assertThat(secondMeasuredDuration).isEqualTo(secondActualDuration);
}
@Test(expected = IllegalStateException.class)
public void forbidCallingStopTwiceWithoutStart() {
stopwatch.start();
stopwatch.stop();
stopwatch.stop();
}
}
| {
"content_hash": "2e0e9f5a073447afe4f5bfecb1364ab9",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 88,
"avg_line_length": 33.74285714285714,
"alnum_prop": 0.7464013547840813,
"repo_name": "philipphager/disclosure-android-app",
"id": "096fcda625c12ac08b99ce25f5feec06a0a454bc",
"size": "2362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/test/java/de/philipphager/disclosure/util/time/StopwatchShould.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "IDL",
"bytes": "343"
},
{
"name": "Java",
"bytes": "360355"
},
{
"name": "Smali",
"bytes": "7494"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.crazyit.manager"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<activity android:name=".GroupSend"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 授予读联系人ContentProvider的权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<!-- 授予发送短信的权限 -->
<uses-permission android:name="android.permission.SEND_SMS"/>
</manifest> | {
"content_hash": "e8c039a28e2252a7402fcef0848c2302",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 84,
"avg_line_length": 34.166666666666664,
"alnum_prop": 0.7170731707317073,
"repo_name": "00wendi00/MyProject",
"id": "cb3e060b82aa472195f3a1b7a1515a944e94bc0f",
"size": "856",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "W_eclipse1_2/GroupSend/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "430521"
},
{
"name": "C",
"bytes": "17868156"
},
{
"name": "C++",
"bytes": "5054355"
},
{
"name": "CMake",
"bytes": "7325"
},
{
"name": "CSS",
"bytes": "3874611"
},
{
"name": "Groff",
"bytes": "409306"
},
{
"name": "HTML",
"bytes": "7833410"
},
{
"name": "Java",
"bytes": "13395187"
},
{
"name": "JavaScript",
"bytes": "2319278"
},
{
"name": "Logos",
"bytes": "6864"
},
{
"name": "M",
"bytes": "20108"
},
{
"name": "Makefile",
"bytes": "2540551"
},
{
"name": "Objective-C",
"bytes": "546363"
},
{
"name": "Perl",
"bytes": "11763"
},
{
"name": "Python",
"bytes": "3285"
},
{
"name": "R",
"bytes": "8138"
},
{
"name": "Rebol",
"bytes": "3080"
},
{
"name": "Shell",
"bytes": "1020448"
},
{
"name": "SuperCollider",
"bytes": "8013"
},
{
"name": "XSLT",
"bytes": "220483"
}
],
"symlink_target": ""
} |
import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
import ReactAccordion from '..';
import {
DATA,
OPTIONS
} from './const';
class App extends Component {
static propTypes = {
data: PropTypes.array.isRequired,
options: PropTypes.object.isRequired
};
render() {
const { data, options } = this.props;
return (
<ReactAccordion
data={data}
options={options}
headerAttName="headerName"
itemsAttName="items"
/>
);
}
}
const appRoot = document.createElement('div');
appRoot.id = 'app';
document.body.appendChild(appRoot);
render(<App data= {DATA} options={OPTIONS}/>, appRoot);
| {
"content_hash": "ddf8d239c7a4158362a6df57952e534a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 55,
"avg_line_length": 20.441176470588236,
"alnum_prop": 0.6330935251798561,
"repo_name": "cht8687/react-accordion",
"id": "f3087f62ab0876b5bbda588cded7cf42add0b70d",
"size": "695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/example/Example.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "924"
},
{
"name": "JavaScript",
"bytes": "8872"
}
],
"symlink_target": ""
} |
/**
* A client to Cloud Data Loss Prevention (DLP) API.
*
* <p>The interfaces provided are listed below, along with usage samples.
*
* <p>================ DlpServiceClient ================
*
* <p>Service Description: The Cloud Data Loss Prevention (DLP) API is a service that allows clients
* to detect the presence of Personally Identifiable Information (PII) and other privacy-sensitive
* data in user-supplied, unstructured data streams, like text blocks or images. The service also
* includes methods for sensitive data redaction and scheduling of data scans on Google Cloud
* Platform based data sets.
*
* <p>To learn more about concepts and find how-to guides see https://cloud.google.com/dlp/docs/.
*
* <p>Sample for DlpServiceClient:
*
* <pre>
* <code>
* try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
* ProjectName parent = ProjectName.of("[PROJECT]");
* InspectContentRequest request = InspectContentRequest.newBuilder()
* .setParent(parent.toString())
* .build();
* InspectContentResponse response = dlpServiceClient.inspectContent(request);
* }
* </code>
* </pre>
*/
package com.google.cloud.dlp.v2;
| {
"content_hash": "f9e4aaf004e5f300202f6fde07859ab3",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 100,
"avg_line_length": 36.84375,
"alnum_prop": 0.7056827820186599,
"repo_name": "vam-google/google-cloud-java",
"id": "62ac4638fd1cf3a750628ba07abc1132d69f4521",
"size": "1773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "google-cloud-clients/google-cloud-dlp/src/main/java/com/google/cloud/dlp/v2/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "128"
},
{
"name": "CSS",
"bytes": "23036"
},
{
"name": "Dockerfile",
"bytes": "127"
},
{
"name": "Go",
"bytes": "9641"
},
{
"name": "HTML",
"bytes": "16158"
},
{
"name": "Java",
"bytes": "47356483"
},
{
"name": "JavaScript",
"bytes": "989"
},
{
"name": "Python",
"bytes": "110799"
},
{
"name": "Shell",
"bytes": "9162"
}
],
"symlink_target": ""
} |
"""
django-guardian helper functions.
"""
import logging
from django.contrib.auth.models import User, AnonymousUser, Group
from guardian.exceptions import NotUserNorGroup
from guardian.conf.settings import ANONYMOUS_USER_ID
from itertools import chain
logger = logging.getLogger(__name__)
def get_anonymous_user():
"""
Returns ``User`` instance (not ``AnonymousUser``) depending on
``ANONYMOUS_USER_ID`` configuration.
"""
return User.objects.get(id=ANONYMOUS_USER_ID)
def get_identity(identity):
"""
Returns (user_obj, None) or (None, group_obj) tuple depending on what is
given. Also accepts AnonymousUser instance but would return ``User``
instead - it is convenient and needed for authorization backend to support
anonymous users.
:param identity: either ``User`` or ``Group`` instance
:raises ``NotUserNorGroup``: if cannot return proper identity instance
**Examples**::
>>> user = User.objects.create(username='joe')
>>> get_identity(user)
(<User: joe>, None)
>>> group = Group.objects.create(name='users')
>>> get_identity(group)
(None, <Group: users>)
>>> anon = AnonymousUser()
>>> get_identity(anon)
(<User: AnonymousUser>, None)
>>> get_identity("not instance")
...
NotUserNorGroup: User/AnonymousUser or Group instance is required (got )
"""
if isinstance(identity, AnonymousUser):
identity = get_anonymous_user()
if isinstance(identity, User):
return identity, None
elif isinstance(identity, Group):
return None, identity
raise NotUserNorGroup("User/AnonymousUser or Group instance is required "
"(got %s)" % identity)
def clean_orphan_obj_perms():
"""
Seeks and removes all object permissions entries pointing at non-existing
targets.
Returns number of removed objects.
"""
from guardian.models import UserObjectPermission
from guardian.models import GroupObjectPermission
deleted = 0
# TODO: optimise
for perm in chain(UserObjectPermission.objects.all(),
GroupObjectPermission.objects.all()):
if perm.content_object is None:
logger.debug("Removing %s (pk=%d)" % (perm, perm.pk))
perm.delete()
deleted += 1
logger.info("Total removed orphan object permissions instances: %d" %
deleted)
return deleted
| {
"content_hash": "a724f67e184613c3b5233d199108beb6",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 79,
"avg_line_length": 29.27710843373494,
"alnum_prop": 0.660082304526749,
"repo_name": "MediaSapiens/wavesf",
"id": "96d177a515bd845d6cdb8fade77d664f09260bb4",
"size": "2430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/externals/guardian/utils.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "120591"
},
{
"name": "Python",
"bytes": "4074314"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/11. JavaScript Objects and Assoc Arrays.iml" filepath="$PROJECT_DIR$/.idea/11. JavaScript Objects and Assoc Arrays.iml" />
</modules>
</component>
</project> | {
"content_hash": "14e476427699ddc55a54f3b7194682f4",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 172,
"avg_line_length": 41.25,
"alnum_prop": 0.6878787878787879,
"repo_name": "kalinmarkov/SoftUni",
"id": "353421f086eb8a91bee36d3a49f389d54d5d78a3",
"size": "330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JS Core/JS Fundamentals/11. JavaScript Objects and Assoc Arrays/.idea/modules.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "399"
},
{
"name": "Batchfile",
"bytes": "13483"
},
{
"name": "C#",
"bytes": "1616313"
},
{
"name": "CSS",
"bytes": "919718"
},
{
"name": "HTML",
"bytes": "119725"
},
{
"name": "Java",
"bytes": "59878"
},
{
"name": "JavaScript",
"bytes": "400825"
},
{
"name": "PHP",
"bytes": "9586"
},
{
"name": "PLSQL",
"bytes": "598162"
},
{
"name": "SQLPL",
"bytes": "3168"
},
{
"name": "Shell",
"bytes": "14116"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-42.tmpl.c
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: increment
* GoodSink: Ensure there will not be an overflow before incrementing data
* BadSink : Increment data, which can cause an overflow
* Flow Variant: 42 Data flow: data returned from one function to another in the same source file
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
static unsigned int badSource(unsigned int data)
{
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%u", &data);
return data;
}
void CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42_bad()
{
unsigned int data;
data = 0;
data = badSource(data);
{
/* POTENTIAL FLAW: Incrementing data could cause an overflow */
data++;
unsigned int result = data;
printUnsignedLine(result);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static unsigned int goodG2BSource(unsigned int data)
{
/* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
data = 2;
return data;
}
static void goodG2B()
{
unsigned int data;
data = 0;
data = goodG2BSource(data);
{
/* POTENTIAL FLAW: Incrementing data could cause an overflow */
data++;
unsigned int result = data;
printUnsignedLine(result);
}
}
/* goodB2G uses the BadSource with the GoodSink */
static unsigned int goodB2GSource(unsigned int data)
{
/* POTENTIAL FLAW: Use a value input from the console */
fscanf (stdin, "%u", &data);
return data;
}
static void goodB2G()
{
unsigned int data;
data = 0;
data = goodB2GSource(data);
/* FIX: Add a check to prevent an overflow from occurring */
if (data < UINT_MAX)
{
data++;
unsigned int result = data;
printUnsignedLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
void CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42_good()
{
goodB2G();
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "61ecf38d2cea72b0f99b6ac486d9a8aa",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 97,
"avg_line_length": 26.56,
"alnum_prop": 0.6424698795180723,
"repo_name": "JianpingZeng/xcc",
"id": "a627a4f3fc0950cd7db28f5ef6ecf6062bc6b26d",
"size": "3320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE190_Integer_Overflow/s06/CWE190_Integer_Overflow__unsigned_int_fscanf_postinc_42.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Sat Sep 26 18:07:50 CST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>XEnum.RadarChartType</title>
<meta name="date" content="2015-09-26">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="XEnum.RadarChartType";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/XEnum.RadarChartType.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/xclcharts/renderer/XEnum.PointerStyle.html" title="enum in org.xclcharts.renderer"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/xclcharts/renderer/XEnum.RectType.html" title="enum in org.xclcharts.renderer"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/xclcharts/renderer/XEnum.RadarChartType.html" target="_top">Frames</a></li>
<li><a href="XEnum.RadarChartType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.xclcharts.renderer</div>
<h2 title="Enum XEnum.RadarChartType" class="title">Enum XEnum.RadarChartType</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a>></li>
<li>
<ul class="inheritance">
<li>org.xclcharts.renderer.XEnum.RadarChartType</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a>></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../org/xclcharts/renderer/XEnum.html" title="class in org.xclcharts.renderer">XEnum</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">XEnum.RadarChartType</span>
extends java.lang.Enum<<a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a>></pre>
<div class="block">雷达图显示类型(蛛网或圆形)</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>XCL</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html#RADAR">RADAR</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html#ROUND">ROUND</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="RADAR">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RADAR</h4>
<pre>public static final <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a> RADAR</pre>
</li>
</ul>
<a name="ROUND">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ROUND</h4>
<pre>public static final <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a> ROUND</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (XEnum.RadarChartType c : XEnum.RadarChartType.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in
the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../org/xclcharts/renderer/XEnum.RadarChartType.html" title="enum in org.xclcharts.renderer">XEnum.RadarChartType</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant
with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/XEnum.RadarChartType.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/xclcharts/renderer/XEnum.PointerStyle.html" title="enum in org.xclcharts.renderer"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/xclcharts/renderer/XEnum.RectType.html" title="enum in org.xclcharts.renderer"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/xclcharts/renderer/XEnum.RadarChartType.html" target="_top">Frames</a></li>
<li><a href="XEnum.RadarChartType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "ef62860afc63e0615b380f38574e041d",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 202,
"avg_line_length": 37.6048632218845,
"alnum_prop": 0.6595538312318138,
"repo_name": "ylfonline/XCL_CHARTS",
"id": "551bf37dcf459fbe9832660e7538839335a75bb8",
"size": "12396",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc/org/xclcharts/renderer/XEnum.RadarChartType.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "Java",
"bytes": "1321147"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Mon Dec 14 16:16:13 CST 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer (Play! API)</title>
<meta name="date" content="2015-12-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer (Play! API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../play/classloading/enhancers/LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" title="class in play.classloading.enhancers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?play/classloading/enhancers/class-use/LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" target="_top">Frames</a></li>
<li><a href="LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer" class="title">Uses of Class<br>play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer</h2>
</div>
<div class="classUseContainer">No usage of play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../play/classloading/enhancers/LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" title="class in play.classloading.enhancers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?play/classloading/enhancers/class-use/LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" target="_top">Frames</a></li>
<li><a href="LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><a href=http://guillaume.bort.fr>Guillaume Bort</a> & <a href=http://www.zenexity.fr>zenexity</a> - Distributed under <a href=http://www.apache.org/licenses/LICENSE-2.0.html>Apache 2 licence</a>, without any warrantly</small></p>
</body>
</html>
| {
"content_hash": "45fbf7bd7567ec6fb9025a44849f3e36",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 261,
"avg_line_length": 40.92857142857143,
"alnum_prop": 0.65949195268567,
"repo_name": "play1-maven-plugin/play1-maven-plugin.github.io",
"id": "fb8f4e1cdd6492f82008e9d0d9dbc40b8f0bb78d",
"size": "5157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.4.1/play/classloading/enhancers/class-use/LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "245466"
},
{
"name": "HTML",
"bytes": "161333450"
},
{
"name": "JavaScript",
"bytes": "11578"
}
],
"symlink_target": ""
} |
namespace capnp {
namespace _ { // private
namespace {
TEST(Encoding, AllTypes) {
MallocMessageBuilder builder;
initTestMessage(builder.initRoot<TestAllTypes>());
checkTestMessage(builder.getRoot<TestAllTypes>());
checkTestMessage(builder.getRoot<TestAllTypes>().asReader());
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
checkTestMessage(reader.getRoot<TestAllTypes>());
ASSERT_EQ(1u, builder.getSegmentsForOutput().size());
checkTestMessage(readMessageUnchecked<TestAllTypes>(builder.getSegmentsForOutput()[0].begin()));
EXPECT_EQ(builder.getSegmentsForOutput()[0].size() - 1, // -1 for root pointer
reader.getRoot<TestAllTypes>().totalSize().wordCount);
}
TEST(Encoding, AllTypesMultiSegment) {
MallocMessageBuilder builder(0, AllocationStrategy::FIXED_SIZE);
initTestMessage(builder.initRoot<TestAllTypes>());
checkTestMessage(builder.getRoot<TestAllTypes>());
checkTestMessage(builder.getRoot<TestAllTypes>().asReader());
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
checkTestMessage(reader.getRoot<TestAllTypes>());
}
TEST(Encoding, Defaults) {
AlignedData<1> nullRoot = {{0, 0, 0, 0, 0, 0, 0, 0}};
kj::ArrayPtr<const word> segments[1] = {kj::arrayPtr(nullRoot.words, 1)};
SegmentArrayMessageReader reader(kj::arrayPtr(segments, 1));
checkTestMessage(reader.getRoot<TestDefaults>());
checkTestMessage(readMessageUnchecked<TestDefaults>(nullRoot.words));
checkTestMessage(TestDefaults::Reader());
}
TEST(Encoding, DefaultInitialization) {
MallocMessageBuilder builder;
checkTestMessage(builder.getRoot<TestDefaults>()); // first pass initializes to defaults
checkTestMessage(builder.getRoot<TestDefaults>().asReader());
checkTestMessage(builder.getRoot<TestDefaults>()); // second pass just reads the initialized structure
checkTestMessage(builder.getRoot<TestDefaults>().asReader());
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
checkTestMessage(reader.getRoot<TestDefaults>());
}
TEST(Encoding, DefaultInitializationMultiSegment) {
MallocMessageBuilder builder(0, AllocationStrategy::FIXED_SIZE);
// first pass initializes to defaults
checkTestMessage(builder.getRoot<TestDefaults>());
checkTestMessage(builder.getRoot<TestDefaults>().asReader());
// second pass just reads the initialized structure
checkTestMessage(builder.getRoot<TestDefaults>());
checkTestMessage(builder.getRoot<TestDefaults>().asReader());
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
checkTestMessage(reader.getRoot<TestDefaults>());
}
TEST(Encoding, DefaultsFromEmptyMessage) {
AlignedData<1> emptyMessage = {{0, 0, 0, 0, 0, 0, 0, 0}};
kj::ArrayPtr<const word> segments[1] = {kj::arrayPtr(emptyMessage.words, 1)};
SegmentArrayMessageReader reader(kj::arrayPtr(segments, 1));
checkTestMessage(reader.getRoot<TestDefaults>());
checkTestMessage(readMessageUnchecked<TestDefaults>(emptyMessage.words));
}
TEST(Encoding, Unions) {
MallocMessageBuilder builder;
TestUnion::Builder root = builder.getRoot<TestUnion>();
EXPECT_EQ(TestUnion::Union0::U0F0S0, root.getUnion0().which());
EXPECT_EQ(VOID, root.getUnion0().getU0f0s0());
EXPECT_DEBUG_ANY_THROW(root.getUnion0().getU0f0s1());
root.getUnion0().setU0f0s1(true);
EXPECT_EQ(TestUnion::Union0::U0F0S1, root.getUnion0().which());
EXPECT_TRUE(root.getUnion0().getU0f0s1());
EXPECT_DEBUG_ANY_THROW(root.getUnion0().getU0f0s0());
root.getUnion0().setU0f0s8(123);
EXPECT_EQ(TestUnion::Union0::U0F0S8, root.getUnion0().which());
EXPECT_EQ(123, root.getUnion0().getU0f0s8());
EXPECT_DEBUG_ANY_THROW(root.getUnion0().getU0f0s1());
}
struct UnionState {
uint discriminants[4];
int dataOffset;
UnionState(std::initializer_list<uint> discriminants, int dataOffset)
: dataOffset(dataOffset) {
memcpy(this->discriminants, discriminants.begin(), sizeof(this->discriminants));
}
bool operator==(const UnionState& other) const {
for (uint i = 0; i < 4; i++) {
if (discriminants[i] != other.discriminants[i]) {
return false;
}
}
return dataOffset == other.dataOffset;
}
};
kj::String KJ_STRINGIFY(const UnionState& us) {
return kj::str("UnionState({", kj::strArray(us.discriminants, ", "), "}, ", us.dataOffset, ")");
}
template <typename StructType, typename Func>
UnionState initUnion(Func&& initializer) {
// Use the given setter to initialize the given union field and then return a struct indicating
// the location of the data that was written as well as the values of the four union
// discriminants.
MallocMessageBuilder builder;
initializer(builder.getRoot<StructType>());
kj::ArrayPtr<const word> segment = builder.getSegmentsForOutput()[0];
KJ_ASSERT(segment.size() > 2, segment.size());
// Find the offset of the first set bit after the union discriminants.
int offset = 0;
for (const uint8_t* p = reinterpret_cast<const uint8_t*>(segment.begin() + 2);
p < reinterpret_cast<const uint8_t*>(segment.end()); p++) {
if (*p != 0) {
uint8_t bits = *p;
while ((bits & 1) == 0) {
++offset;
bits >>= 1;
}
goto found;
}
offset += 8;
}
offset = -1;
found:
const uint8_t* discriminants = reinterpret_cast<const uint8_t*>(segment.begin() + 1);
return UnionState({discriminants[0], discriminants[2], discriminants[4], discriminants[6]},
offset);
}
TEST(Encoding, UnionLayout) {
#define INIT_UNION(setter) \
initUnion<TestUnion>([](TestUnion::Builder b) {b.setter;})
EXPECT_EQ(UnionState({ 0,0,0,0}, -1), INIT_UNION(getUnion0().setU0f0s0(VOID)));
EXPECT_EQ(UnionState({ 1,0,0,0}, 0), INIT_UNION(getUnion0().setU0f0s1(1)));
EXPECT_EQ(UnionState({ 2,0,0,0}, 0), INIT_UNION(getUnion0().setU0f0s8(1)));
EXPECT_EQ(UnionState({ 3,0,0,0}, 0), INIT_UNION(getUnion0().setU0f0s16(1)));
EXPECT_EQ(UnionState({ 4,0,0,0}, 0), INIT_UNION(getUnion0().setU0f0s32(1)));
EXPECT_EQ(UnionState({ 5,0,0,0}, 0), INIT_UNION(getUnion0().setU0f0s64(1)));
EXPECT_EQ(UnionState({ 6,0,0,0}, 448), INIT_UNION(getUnion0().setU0f0sp("1")));
EXPECT_EQ(UnionState({ 7,0,0,0}, -1), INIT_UNION(getUnion0().setU0f1s0(VOID)));
EXPECT_EQ(UnionState({ 8,0,0,0}, 0), INIT_UNION(getUnion0().setU0f1s1(1)));
EXPECT_EQ(UnionState({ 9,0,0,0}, 0), INIT_UNION(getUnion0().setU0f1s8(1)));
EXPECT_EQ(UnionState({10,0,0,0}, 0), INIT_UNION(getUnion0().setU0f1s16(1)));
EXPECT_EQ(UnionState({11,0,0,0}, 0), INIT_UNION(getUnion0().setU0f1s32(1)));
EXPECT_EQ(UnionState({12,0,0,0}, 0), INIT_UNION(getUnion0().setU0f1s64(1)));
EXPECT_EQ(UnionState({13,0,0,0}, 448), INIT_UNION(getUnion0().setU0f1sp("1")));
EXPECT_EQ(UnionState({0, 0,0,0}, -1), INIT_UNION(getUnion1().setU1f0s0(VOID)));
EXPECT_EQ(UnionState({0, 1,0,0}, 65), INIT_UNION(getUnion1().setU1f0s1(1)));
EXPECT_EQ(UnionState({0, 2,0,0}, 65), INIT_UNION(getUnion1().setU1f1s1(1)));
EXPECT_EQ(UnionState({0, 3,0,0}, 72), INIT_UNION(getUnion1().setU1f0s8(1)));
EXPECT_EQ(UnionState({0, 4,0,0}, 72), INIT_UNION(getUnion1().setU1f1s8(1)));
EXPECT_EQ(UnionState({0, 5,0,0}, 80), INIT_UNION(getUnion1().setU1f0s16(1)));
EXPECT_EQ(UnionState({0, 6,0,0}, 80), INIT_UNION(getUnion1().setU1f1s16(1)));
EXPECT_EQ(UnionState({0, 7,0,0}, 96), INIT_UNION(getUnion1().setU1f0s32(1)));
EXPECT_EQ(UnionState({0, 8,0,0}, 96), INIT_UNION(getUnion1().setU1f1s32(1)));
EXPECT_EQ(UnionState({0, 9,0,0}, 128), INIT_UNION(getUnion1().setU1f0s64(1)));
EXPECT_EQ(UnionState({0,10,0,0}, 128), INIT_UNION(getUnion1().setU1f1s64(1)));
EXPECT_EQ(UnionState({0,11,0,0}, 512), INIT_UNION(getUnion1().setU1f0sp("1")));
EXPECT_EQ(UnionState({0,12,0,0}, 512), INIT_UNION(getUnion1().setU1f1sp("1")));
EXPECT_EQ(UnionState({0,13,0,0}, -1), INIT_UNION(getUnion1().setU1f2s0(VOID)));
EXPECT_EQ(UnionState({0,14,0,0}, 65), INIT_UNION(getUnion1().setU1f2s1(1)));
EXPECT_EQ(UnionState({0,15,0,0}, 72), INIT_UNION(getUnion1().setU1f2s8(1)));
EXPECT_EQ(UnionState({0,16,0,0}, 80), INIT_UNION(getUnion1().setU1f2s16(1)));
EXPECT_EQ(UnionState({0,17,0,0}, 96), INIT_UNION(getUnion1().setU1f2s32(1)));
EXPECT_EQ(UnionState({0,18,0,0}, 128), INIT_UNION(getUnion1().setU1f2s64(1)));
EXPECT_EQ(UnionState({0,19,0,0}, 512), INIT_UNION(getUnion1().setU1f2sp("1")));
EXPECT_EQ(UnionState({0,0,0,0}, 192), INIT_UNION(getUnion2().setU2f0s1(1)));
EXPECT_EQ(UnionState({0,0,0,0}, 193), INIT_UNION(getUnion3().setU3f0s1(1)));
EXPECT_EQ(UnionState({0,0,1,0}, 200), INIT_UNION(getUnion2().setU2f0s8(1)));
EXPECT_EQ(UnionState({0,0,0,1}, 208), INIT_UNION(getUnion3().setU3f0s8(1)));
EXPECT_EQ(UnionState({0,0,2,0}, 224), INIT_UNION(getUnion2().setU2f0s16(1)));
EXPECT_EQ(UnionState({0,0,0,2}, 240), INIT_UNION(getUnion3().setU3f0s16(1)));
EXPECT_EQ(UnionState({0,0,3,0}, 256), INIT_UNION(getUnion2().setU2f0s32(1)));
EXPECT_EQ(UnionState({0,0,0,3}, 288), INIT_UNION(getUnion3().setU3f0s32(1)));
EXPECT_EQ(UnionState({0,0,4,0}, 320), INIT_UNION(getUnion2().setU2f0s64(1)));
EXPECT_EQ(UnionState({0,0,0,4}, 384), INIT_UNION(getUnion3().setU3f0s64(1)));
#undef INIT_UNION
}
TEST(Encoding, UnnamedUnion) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestUnnamedUnion>();
EXPECT_EQ(test::TestUnnamedUnion::FOO, root.which());
root.setBar(321);
EXPECT_EQ(test::TestUnnamedUnion::BAR, root.which());
EXPECT_EQ(test::TestUnnamedUnion::BAR, root.asReader().which());
EXPECT_EQ(321u, root.getBar());
EXPECT_EQ(321u, root.asReader().getBar());
EXPECT_DEBUG_ANY_THROW(root.getFoo());
EXPECT_DEBUG_ANY_THROW(root.asReader().getFoo());
root.setFoo(123);
EXPECT_EQ(test::TestUnnamedUnion::FOO, root.which());
EXPECT_EQ(test::TestUnnamedUnion::FOO, root.asReader().which());
EXPECT_EQ(123u, root.getFoo());
EXPECT_EQ(123u, root.asReader().getFoo());
EXPECT_DEBUG_ANY_THROW(root.getBar());
EXPECT_DEBUG_ANY_THROW(root.asReader().getBar());
#if !CAPNP_LITE
StructSchema schema = Schema::from<test::TestUnnamedUnion>();
// The discriminant is allocated just before allocating "bar".
EXPECT_EQ(2u, schema.getProto().getStruct().getDiscriminantOffset());
EXPECT_EQ(0u, schema.getFieldByName("foo").getProto().getSlot().getOffset());
EXPECT_EQ(2u, schema.getFieldByName("bar").getProto().getSlot().getOffset());
#endif // !CAPNP_LITE
}
TEST(Encoding, Groups) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestGroups>();
{
auto foo = root.getGroups().initFoo();
foo.setCorge(12345678);
foo.setGrault(123456789012345ll);
foo.setGarply("foobar");
EXPECT_EQ(12345678, foo.getCorge());
EXPECT_EQ(123456789012345ll, foo.getGrault());
EXPECT_EQ("foobar", foo.getGarply());
}
{
auto bar = root.getGroups().initBar();
bar.setCorge(23456789);
bar.setGrault("barbaz");
bar.setGarply(234567890123456ll);
EXPECT_EQ(23456789, bar.getCorge());
EXPECT_EQ("barbaz", bar.getGrault());
EXPECT_EQ(234567890123456ll, bar.getGarply());
}
{
auto baz = root.getGroups().initBaz();
baz.setCorge(34567890);
baz.setGrault("bazqux");
baz.setGarply("quxquux");
EXPECT_EQ(34567890, baz.getCorge());
EXPECT_EQ("bazqux", baz.getGrault());
EXPECT_EQ("quxquux", baz.getGarply());
}
}
TEST(Encoding, InterleavedGroups) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestInterleavedGroups>();
// Init both groups to different values.
{
auto group = root.getGroup1();
group.setFoo(12345678u);
group.setBar(123456789012345llu);
auto corge = group.initCorge();
corge.setGrault(987654321098765llu);
corge.setGarply(12345u);
corge.setPlugh("plugh");
corge.setXyzzy("xyzzy");
group.setWaldo("waldo");
}
{
auto group = root.getGroup2();
group.setFoo(23456789u);
group.setBar(234567890123456llu);
auto corge = group.initCorge();
corge.setGrault(876543210987654llu);
corge.setGarply(23456u);
corge.setPlugh("hgulp");
corge.setXyzzy("yzzyx");
group.setWaldo("odlaw");
}
// Check group1 is still set correctly.
{
auto group = root.asReader().getGroup1();
EXPECT_EQ(12345678u, group.getFoo());
EXPECT_EQ(123456789012345llu, group.getBar());
auto corge = group.getCorge();
EXPECT_EQ(987654321098765llu, corge.getGrault());
EXPECT_EQ(12345u, corge.getGarply());
EXPECT_EQ("plugh", corge.getPlugh());
EXPECT_EQ("xyzzy", corge.getXyzzy());
EXPECT_EQ("waldo", group.getWaldo());
}
// Zero out group 1 and see if it is zero'd.
{
auto group = root.initGroup1().asReader();
EXPECT_EQ(0u, group.getFoo());
EXPECT_EQ(0u, group.getBar());
EXPECT_EQ(test::TestInterleavedGroups::Group1::QUX, group.which());
EXPECT_EQ(0u, group.getQux());
EXPECT_FALSE(group.hasWaldo());
}
// Group 2 should not have been touched.
{
auto group = root.asReader().getGroup2();
EXPECT_EQ(23456789u, group.getFoo());
EXPECT_EQ(234567890123456llu, group.getBar());
auto corge = group.getCorge();
EXPECT_EQ(876543210987654llu, corge.getGrault());
EXPECT_EQ(23456u, corge.getGarply());
EXPECT_EQ("hgulp", corge.getPlugh());
EXPECT_EQ("yzzyx", corge.getXyzzy());
EXPECT_EQ("odlaw", group.getWaldo());
}
}
TEST(Encoding, UnionDefault) {
MallocMessageBuilder builder;
TestUnionDefaults::Reader reader = builder.getRoot<TestUnionDefaults>().asReader();
{
auto field = reader.getS16s8s64s8Set();
EXPECT_EQ(TestUnion::Union0::U0F0S16, field.getUnion0().which());
EXPECT_EQ(TestUnion::Union1::U1F0S8 , field.getUnion1().which());
EXPECT_EQ(TestUnion::Union2::U2F0S64, field.getUnion2().which());
EXPECT_EQ(TestUnion::Union3::U3F0S8 , field.getUnion3().which());
EXPECT_EQ(321, field.getUnion0().getU0f0s16());
EXPECT_EQ(123, field.getUnion1().getU1f0s8());
EXPECT_EQ(12345678901234567ll, field.getUnion2().getU2f0s64());
EXPECT_EQ(55, field.getUnion3().getU3f0s8());
}
{
auto field = reader.getS0sps1s32Set();
EXPECT_EQ(TestUnion::Union0::U0F1S0 , field.getUnion0().which());
EXPECT_EQ(TestUnion::Union1::U1F0SP , field.getUnion1().which());
EXPECT_EQ(TestUnion::Union2::U2F0S1 , field.getUnion2().which());
EXPECT_EQ(TestUnion::Union3::U3F0S32, field.getUnion3().which());
EXPECT_EQ(VOID, field.getUnion0().getU0f1s0());
EXPECT_EQ("foo", field.getUnion1().getU1f0sp());
EXPECT_EQ(true, field.getUnion2().getU2f0s1());
EXPECT_EQ(12345678, field.getUnion3().getU3f0s32());
}
{
auto field = reader.getUnnamed1();
EXPECT_EQ(test::TestUnnamedUnion::FOO, field.which());
EXPECT_EQ(123u, field.getFoo());
EXPECT_FALSE(field.hasBefore());
EXPECT_FALSE(field.hasAfter());
}
{
auto field = reader.getUnnamed2();
EXPECT_EQ(test::TestUnnamedUnion::BAR, field.which());
EXPECT_EQ(321u, field.getBar());
EXPECT_EQ("foo", field.getBefore());
EXPECT_EQ("bar", field.getAfter());
}
}
// =======================================================================================
TEST(Encoding, ListDefaults) {
MallocMessageBuilder builder;
TestListDefaults::Builder root = builder.getRoot<TestListDefaults>();
checkTestMessage(root.asReader());
checkTestMessage(root);
checkTestMessage(root.asReader());
}
TEST(Encoding, BuildListDefaults) {
MallocMessageBuilder builder;
TestListDefaults::Builder root = builder.getRoot<TestListDefaults>();
initTestMessage(root);
checkTestMessage(root.asReader());
checkTestMessage(root);
checkTestMessage(root.asReader());
}
TEST(Encoding, SmallStructLists) {
// In this test, we will manually initialize TestListDefaults.lists to match the default
// value and verify that we end up with the same encoding that the compiler produces.
MallocMessageBuilder builder;
auto root = builder.getRoot<TestListDefaults>();
auto sl = root.initLists();
// Verify that all the lists are actually empty.
EXPECT_EQ(0u, sl.getList0 ().size());
EXPECT_EQ(0u, sl.getList1 ().size());
EXPECT_EQ(0u, sl.getList8 ().size());
EXPECT_EQ(0u, sl.getList16().size());
EXPECT_EQ(0u, sl.getList32().size());
EXPECT_EQ(0u, sl.getList64().size());
EXPECT_EQ(0u, sl.getListP ().size());
EXPECT_EQ(0u, sl.getInt32ListList().size());
EXPECT_EQ(0u, sl.getTextListList().size());
EXPECT_EQ(0u, sl.getStructListList().size());
{ auto l = sl.initList0 (2); l[0].setF(VOID); l[1].setF(VOID); }
{ auto l = sl.initList1 (4); l[0].setF(true); l[1].setF(false);
l[2].setF(true); l[3].setF(true); }
{ auto l = sl.initList8 (2); l[0].setF(123u); l[1].setF(45u); }
{ auto l = sl.initList16(2); l[0].setF(12345u); l[1].setF(6789u); }
{ auto l = sl.initList32(2); l[0].setF(123456789u); l[1].setF(234567890u); }
{ auto l = sl.initList64(2); l[0].setF(1234567890123456u); l[1].setF(2345678901234567u); }
{ auto l = sl.initListP (2); l[0].setF("foo"); l[1].setF("bar"); }
{
auto l = sl.initInt32ListList(3);
l.set(0, {1, 2, 3});
l.set(1, {4, 5});
l.set(2, {12341234});
}
{
auto l = sl.initTextListList(3);
l.set(0, {"foo", "bar"});
l.set(1, {"baz"});
l.set(2, {"qux", "corge"});
}
{
auto l = sl.initStructListList(2);
l.init(0, 2);
l.init(1, 1);
l[0][0].setInt32Field(123);
l[0][1].setInt32Field(456);
l[1][0].setInt32Field(789);
}
kj::ArrayPtr<const word> segment = builder.getSegmentsForOutput()[0];
// Initialize another message such that it copies the default value for that field.
MallocMessageBuilder defaultBuilder;
defaultBuilder.getRoot<TestListDefaults>().getLists();
kj::ArrayPtr<const word> defaultSegment = defaultBuilder.getSegmentsForOutput()[0];
// Should match...
EXPECT_EQ(defaultSegment.size(), segment.size());
for (size_t i = 0; i < kj::min(segment.size(), defaultSegment.size()); i++) {
EXPECT_EQ(reinterpret_cast<const uint64_t*>(defaultSegment.begin())[i],
reinterpret_cast<const uint64_t*>(segment.begin())[i]);
}
}
TEST(Encoding, SetListToEmpty) {
// Test initializing list fields from various ways of constructing zero-sized lists.
// At one point this would often fail because the lists would have ElementSize::VOID which is
// incompatible with other list sizes.
#define ALL_LIST_TYPES(MACRO) \
MACRO(Void, Void) \
MACRO(Bool, bool) \
MACRO(UInt8, uint8_t) \
MACRO(UInt16, uint16_t) \
MACRO(UInt32, uint32_t) \
MACRO(UInt64, uint64_t) \
MACRO(Int8, int8_t) \
MACRO(Int16, int16_t) \
MACRO(Int32, int32_t) \
MACRO(Int64, int64_t) \
MACRO(Float32, float) \
MACRO(Float64, double) \
MACRO(Text, Text) \
MACRO(Data, Data) \
MACRO(Struct, TestAllTypes)
#define SET_FROM_READER_ACCESSOR(name, type) \
root.set##name##List(reader.get##name##List());
#define SET_FROM_BUILDER_ACCESSOR(name, type) \
root.set##name##List(root.get##name##List());
#define SET_FROM_READER_CONSTRUCTOR(name, type) \
root.set##name##List(List<type>::Reader());
#define SET_FROM_BUILDER_CONSTRUCTOR(name, type) \
root.set##name##List(List<type>::Builder());
#define CHECK_EMPTY_NONNULL(name, type) \
EXPECT_TRUE(root.has##name##List()); \
EXPECT_EQ(0, root.get##name##List().size());
{
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAllTypes>();
auto reader = root.asReader();
ALL_LIST_TYPES(SET_FROM_READER_ACCESSOR)
ALL_LIST_TYPES(CHECK_EMPTY_NONNULL)
}
{
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAllTypes>();
ALL_LIST_TYPES(SET_FROM_BUILDER_ACCESSOR)
ALL_LIST_TYPES(CHECK_EMPTY_NONNULL)
}
{
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAllTypes>();
ALL_LIST_TYPES(SET_FROM_READER_CONSTRUCTOR)
ALL_LIST_TYPES(CHECK_EMPTY_NONNULL)
}
{
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAllTypes>();
ALL_LIST_TYPES(SET_FROM_BUILDER_CONSTRUCTOR)
ALL_LIST_TYPES(CHECK_EMPTY_NONNULL)
}
#undef SET_FROM_READER_ACCESSOR
#undef SET_FROM_BUILDER_ACCESSOR
#undef SET_FROM_READER_CONSTRUCTOR
#undef SET_FROM_BUILDER_CONSTRUCTOR
#undef CHECK_EMPTY_NONNULL
}
#if CAPNP_EXPENSIVE_TESTS
TEST(Encoding, LongList) {
// This test allocates 512MB of contiguous memory and takes several seconds, so we usually don't
// run it. It is run before release, though.
MallocMessageBuilder builder;
auto root = builder.initRoot<TestAllTypes>();
uint length = 1 << 27;
auto list = root.initUInt64List(length);
for (uint ii = 0; ii < length; ++ii) {
list.set(ii, ii);
}
for (uint ii = 0; ii < length; ++ii) {
ASSERT_EQ(list[ii], ii);
}
}
#endif
// =======================================================================================
TEST(Encoding, ListUpgrade) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
root.getAnyPointerField().setAs<List<uint16_t>>({12, 34, 56});
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {12, 34, 56});
{
auto l = root.getAnyPointerField().getAs<List<test::TestLists::Struct8>>();
ASSERT_EQ(3u, l.size());
EXPECT_EQ(12u, l[0].getF());
EXPECT_EQ(34u, l[1].getF());
EXPECT_EQ(56u, l[2].getF());
}
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {12, 34, 56});
auto reader = root.asReader();
checkList(reader.getAnyPointerField().getAs<List<uint8_t>>(), {12, 34, 56});
{
auto l = reader.getAnyPointerField().getAs<List<test::TestLists::Struct8>>();
ASSERT_EQ(3u, l.size());
EXPECT_EQ(12u, l[0].getF());
EXPECT_EQ(34u, l[1].getF());
EXPECT_EQ(56u, l[2].getF());
}
root.getAnyPointerField().setAs<List<uint16_t>>({12, 34, 56});
{
kj::Maybe<kj::Exception> e = kj::runCatchingExceptions([&]() {
reader.getAnyPointerField().getAs<List<uint32_t>>();
#if !KJ_NO_EXCEPTIONS
ADD_FAILURE() << "Should have thrown an exception.";
#endif
});
KJ_EXPECT(e != nullptr, "Should have thrown an exception.");
}
{
auto l = reader.getAnyPointerField().getAs<List<test::TestLists::Struct32>>();
ASSERT_EQ(3u, l.size());
// These should return default values because the structs aren't big enough.
EXPECT_EQ(0u, l[0].getF());
EXPECT_EQ(0u, l[1].getF());
EXPECT_EQ(0u, l[2].getF());
}
checkList(reader.getAnyPointerField().getAs<List<uint16_t>>(), {12, 34, 56});
}
TEST(Encoding, BitListDowngrade) {
// NO LONGER SUPPORTED -- We check for exceptions thrown.
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
root.getAnyPointerField().setAs<List<uint16_t>>({0x1201u, 0x3400u, 0x5601u, 0x7801u});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
{
auto l = root.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
ASSERT_EQ(4u, l.size());
EXPECT_TRUE(l[0].getF());
EXPECT_FALSE(l[1].getF());
EXPECT_TRUE(l[2].getF());
EXPECT_TRUE(l[3].getF());
}
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(),
{0x1201u, 0x3400u, 0x5601u, 0x7801u});
auto reader = root.asReader();
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
{
auto l = reader.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
ASSERT_EQ(4u, l.size());
EXPECT_TRUE(l[0].getF());
EXPECT_FALSE(l[1].getF());
EXPECT_TRUE(l[2].getF());
EXPECT_TRUE(l[3].getF());
}
checkList(reader.getAnyPointerField().getAs<List<uint16_t>>(),
{0x1201u, 0x3400u, 0x5601u, 0x7801u});
}
TEST(Encoding, BitListDowngradeFromStruct) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
{
auto list = root.getAnyPointerField().initAs<List<test::TestLists::Struct1c>>(4);
list[0].setF(true);
list[1].setF(false);
list[2].setF(true);
list[3].setF(true);
}
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
{
auto l = root.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
ASSERT_EQ(4u, l.size());
EXPECT_TRUE(l[0].getF());
EXPECT_FALSE(l[1].getF());
EXPECT_TRUE(l[2].getF());
EXPECT_TRUE(l[3].getF());
}
auto reader = root.asReader();
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
{
auto l = reader.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
ASSERT_EQ(4u, l.size());
EXPECT_TRUE(l[0].getF());
EXPECT_FALSE(l[1].getF());
EXPECT_TRUE(l[2].getF());
EXPECT_TRUE(l[3].getF());
}
}
TEST(Encoding, BitListUpgrade) {
// No longer supported!
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
root.getAnyPointerField().setAs<List<bool>>({true, false, true, true});
{
kj::Maybe<kj::Exception> e = kj::runCatchingExceptions([&]() {
root.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
#if !KJ_NO_EXCEPTIONS
ADD_FAILURE() << "Should have thrown an exception.";
#endif
});
KJ_EXPECT(e != nullptr, "Should have thrown an exception.");
}
auto reader = root.asReader();
{
kj::Maybe<kj::Exception> e = kj::runCatchingExceptions([&]() {
reader.getAnyPointerField().getAs<List<test::TestLists::Struct1>>();
#if !KJ_NO_EXCEPTIONS
ADD_FAILURE() << "Should have thrown an exception.";
#endif
});
KJ_EXPECT(e != nullptr, "Should have thrown an exception.");
}
}
TEST(Encoding, UpgradeStructInBuilder) {
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
test::TestOldVersion::Reader oldReader;
{
auto oldVersion = root.getAnyPointerField().initAs<test::TestOldVersion>();
oldVersion.setOld1(123);
oldVersion.setOld2("foo");
auto sub = oldVersion.initOld3();
sub.setOld1(456);
sub.setOld2("bar");
oldReader = oldVersion;
}
size_t size = builder.getSegmentsForOutput()[0].size();
size_t size2;
{
auto newVersion = root.getAnyPointerField().getAs<test::TestNewVersion>();
// The old instance should have been zero'd.
EXPECT_EQ(0, oldReader.getOld1());
EXPECT_EQ("", oldReader.getOld2());
EXPECT_EQ(0, oldReader.getOld3().getOld1());
EXPECT_EQ("", oldReader.getOld3().getOld2());
// Size should have increased due to re-allocating the struct.
size_t size1 = builder.getSegmentsForOutput()[0].size();
EXPECT_GT(size1, size);
auto sub = newVersion.getOld3();
// Size should have increased due to re-allocating the sub-struct.
size2 = builder.getSegmentsForOutput()[0].size();
EXPECT_GT(size2, size1);
// Check contents.
EXPECT_EQ(123, newVersion.getOld1());
EXPECT_EQ("foo", newVersion.getOld2());
EXPECT_EQ(987, newVersion.getNew1());
EXPECT_EQ("baz", newVersion.getNew2());
EXPECT_EQ(456, sub.getOld1());
EXPECT_EQ("bar", sub.getOld2());
EXPECT_EQ(987, sub.getNew1());
EXPECT_EQ("baz", sub.getNew2());
newVersion.setOld1(234);
newVersion.setOld2("qux");
newVersion.setNew1(321);
newVersion.setNew2("quux");
sub.setOld1(567);
sub.setOld2("corge");
sub.setNew1(654);
sub.setNew2("grault");
}
// We set four small text fields and implicitly initialized two to defaults, so the size should
// have raised by six words.
size_t size3 = builder.getSegmentsForOutput()[0].size();
EXPECT_EQ(size2 + 6, size3);
{
// Go back to old version. It should have the values set on the new version.
auto oldVersion = root.getAnyPointerField().getAs<test::TestOldVersion>();
EXPECT_EQ(234, oldVersion.getOld1());
EXPECT_EQ("qux", oldVersion.getOld2());
auto sub = oldVersion.getOld3();
EXPECT_EQ(567, sub.getOld1());
EXPECT_EQ("corge", sub.getOld2());
// Overwrite the old fields. The new fields should remain intact.
oldVersion.setOld1(345);
oldVersion.setOld2("garply");
sub.setOld1(678);
sub.setOld2("waldo");
}
// We set two small text fields, so the size should have raised by two words.
size_t size4 = builder.getSegmentsForOutput()[0].size();
EXPECT_EQ(size3 + 2, size4);
{
// Back to the new version again.
auto newVersion = root.getAnyPointerField().getAs<test::TestNewVersion>();
EXPECT_EQ(345, newVersion.getOld1());
EXPECT_EQ("garply", newVersion.getOld2());
EXPECT_EQ(321, newVersion.getNew1());
EXPECT_EQ("quux", newVersion.getNew2());
auto sub = newVersion.getOld3();
EXPECT_EQ(678, sub.getOld1());
EXPECT_EQ("waldo", sub.getOld2());
EXPECT_EQ(654, sub.getNew1());
EXPECT_EQ("grault", sub.getNew2());
}
// Size should not have changed because we didn't write anything and the structs were already
// the right size.
EXPECT_EQ(size4, builder.getSegmentsForOutput()[0].size());
}
TEST(Encoding, UpgradeStructInBuilderMultiSegment) {
// Exactly like the previous test, except that we force multiple segments. Since we force a
// separate segment for every object, every pointer is a far pointer, and far pointers are easily
// transferred, so this is actually not such a complicated case.
MallocMessageBuilder builder(0, AllocationStrategy::FIXED_SIZE);
auto root = builder.initRoot<test::TestAnyPointer>();
// Start with a 1-word first segment and the root object in the second segment.
size_t size = builder.getSegmentsForOutput().size();
EXPECT_EQ(2u, size);
{
auto oldVersion = root.getAnyPointerField().initAs<test::TestOldVersion>();
oldVersion.setOld1(123);
oldVersion.setOld2("foo");
auto sub = oldVersion.initOld3();
sub.setOld1(456);
sub.setOld2("bar");
}
// Allocated two structs and two strings.
size_t size2 = builder.getSegmentsForOutput().size();
EXPECT_EQ(size + 4, size2);
size_t size4;
{
auto newVersion = root.getAnyPointerField().getAs<test::TestNewVersion>();
// Allocated a new struct.
size_t size3 = builder.getSegmentsForOutput().size();
EXPECT_EQ(size2 + 1, size3);
auto sub = newVersion.getOld3();
// Allocated another new struct for its string field.
size4 = builder.getSegmentsForOutput().size();
EXPECT_EQ(size3 + 1, size4);
// Check contents.
EXPECT_EQ(123, newVersion.getOld1());
EXPECT_EQ("foo", newVersion.getOld2());
EXPECT_EQ(987, newVersion.getNew1());
EXPECT_EQ("baz", newVersion.getNew2());
EXPECT_EQ(456, sub.getOld1());
EXPECT_EQ("bar", sub.getOld2());
EXPECT_EQ(987, sub.getNew1());
EXPECT_EQ("baz", sub.getNew2());
newVersion.setOld1(234);
newVersion.setOld2("qux");
newVersion.setNew1(321);
newVersion.setNew2("quux");
sub.setOld1(567);
sub.setOld2("corge");
sub.setNew1(654);
sub.setNew2("grault");
}
// Set four strings and implicitly initialized two.
size_t size5 = builder.getSegmentsForOutput().size();
EXPECT_EQ(size4 + 6, size5);
{
// Go back to old version. It should have the values set on the new version.
auto oldVersion = root.getAnyPointerField().getAs<test::TestOldVersion>();
EXPECT_EQ(234, oldVersion.getOld1());
EXPECT_EQ("qux", oldVersion.getOld2());
auto sub = oldVersion.getOld3();
EXPECT_EQ(567, sub.getOld1());
EXPECT_EQ("corge", sub.getOld2());
// Overwrite the old fields. The new fields should remain intact.
oldVersion.setOld1(345);
oldVersion.setOld2("garply");
sub.setOld1(678);
sub.setOld2("waldo");
}
// Set two new strings.
size_t size6 = builder.getSegmentsForOutput().size();
EXPECT_EQ(size5 + 2, size6);
{
// Back to the new version again.
auto newVersion = root.getAnyPointerField().getAs<test::TestNewVersion>();
EXPECT_EQ(345, newVersion.getOld1());
EXPECT_EQ("garply", newVersion.getOld2());
EXPECT_EQ(321, newVersion.getNew1());
EXPECT_EQ("quux", newVersion.getNew2());
auto sub = newVersion.getOld3();
EXPECT_EQ(678, sub.getOld1());
EXPECT_EQ("waldo", sub.getOld2());
EXPECT_EQ(654, sub.getNew1());
EXPECT_EQ("grault", sub.getNew2());
}
// Size should not have changed because we didn't write anything and the structs were already
// the right size.
EXPECT_EQ(size6, builder.getSegmentsForOutput().size());
}
TEST(Encoding, UpgradeStructInBuilderFarPointers) {
// Force allocation of a Far pointer.
MallocMessageBuilder builder(7, AllocationStrategy::FIXED_SIZE);
auto root = builder.initRoot<test::TestAnyPointer>();
root.getAnyPointerField().initAs<test::TestOldVersion>().setOld2("foo");
// We should have allocated all but one word of the first segment.
EXPECT_EQ(1u, builder.getSegmentsForOutput().size());
EXPECT_EQ(6u, builder.getSegmentsForOutput()[0].size());
// Now if we upgrade...
EXPECT_EQ("foo", root.getAnyPointerField().getAs<test::TestNewVersion>().getOld2());
// We should have allocated the new struct in a new segment, but allocated the far pointer
// landing pad back in the first segment.
ASSERT_EQ(2u, builder.getSegmentsForOutput().size());
EXPECT_EQ(7u, builder.getSegmentsForOutput()[0].size());
EXPECT_EQ(6u, builder.getSegmentsForOutput()[1].size());
}
TEST(Encoding, UpgradeStructInBuilderDoubleFarPointers) {
// Force allocation of a double-Far pointer.
MallocMessageBuilder builder(6, AllocationStrategy::FIXED_SIZE);
auto root = builder.initRoot<test::TestAnyPointer>();
root.getAnyPointerField().initAs<test::TestOldVersion>().setOld2("foo");
// We should have allocated all of the first segment.
EXPECT_EQ(1u, builder.getSegmentsForOutput().size());
EXPECT_EQ(6u, builder.getSegmentsForOutput()[0].size());
// Now if we upgrade...
EXPECT_EQ("foo", root.getAnyPointerField().getAs<test::TestNewVersion>().getOld2());
// We should have allocated the new struct in a new segment, and also allocated the far pointer
// landing pad in yet another segment.
ASSERT_EQ(3u, builder.getSegmentsForOutput().size());
EXPECT_EQ(6u, builder.getSegmentsForOutput()[0].size());
EXPECT_EQ(6u, builder.getSegmentsForOutput()[1].size());
EXPECT_EQ(2u, builder.getSegmentsForOutput()[2].size());
}
void checkUpgradedList(test::TestAnyPointer::Builder root,
std::initializer_list<int64_t> expectedData,
std::initializer_list<Text::Reader> expectedPointers) {
{
auto builder = root.getAnyPointerField().getAs<List<test::TestNewVersion>>();
ASSERT_EQ(expectedData.size(), builder.size());
for (uint i = 0; i < expectedData.size(); i++) {
EXPECT_EQ(expectedData.begin()[i], builder[i].getOld1());
EXPECT_EQ(expectedPointers.begin()[i], builder[i].getOld2());
// Other fields shouldn't be set.
EXPECT_EQ(0, builder[i].asReader().getOld3().getOld1());
EXPECT_EQ("", builder[i].asReader().getOld3().getOld2());
EXPECT_EQ(987, builder[i].getNew1());
EXPECT_EQ("baz", builder[i].getNew2());
// Write some new data.
builder[i].setOld1(i * 123);
builder[i].setOld2(kj::str("qux", i, '\0').begin());
builder[i].setNew1(i * 456);
builder[i].setNew2(kj::str("corge", i, '\0').begin());
}
}
// Read the newly-written data as TestOldVersion to ensure it was updated.
{
auto builder = root.getAnyPointerField().getAs<List<test::TestOldVersion>>();
ASSERT_EQ(expectedData.size(), builder.size());
for (uint i = 0; i < expectedData.size(); i++) {
EXPECT_EQ(i * 123, builder[i].getOld1());
EXPECT_EQ(Text::Reader(kj::str("qux", i, "\0").begin()), builder[i].getOld2());
}
}
// Also read back as TestNewVersion again.
{
auto builder = root.getAnyPointerField().getAs<List<test::TestNewVersion>>();
ASSERT_EQ(expectedData.size(), builder.size());
for (uint i = 0; i < expectedData.size(); i++) {
EXPECT_EQ(i * 123, builder[i].getOld1());
EXPECT_EQ(Text::Reader(kj::str("qux", i, '\0').begin()), builder[i].getOld2());
EXPECT_EQ(i * 456, builder[i].getNew1());
EXPECT_EQ(Text::Reader(kj::str("corge", i, '\0').begin()), builder[i].getNew2());
}
}
}
TEST(Encoding, UpgradeListInBuilder) {
// Test every damned list upgrade.
MallocMessageBuilder builder;
auto root = builder.initRoot<test::TestAnyPointer>();
// -----------------------------------------------------------------
root.getAnyPointerField().setAs<List<Void>>({VOID, VOID, VOID, VOID});
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint8_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint16_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkUpgradedList(root, {0, 0, 0, 0}, {"", "", "", ""});
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<bool>>({true, false, true, true});
auto orig = root.asReader().getAnyPointerField().getAs<List<bool>>();
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Void>>());
checkList(root.getAnyPointerField().getAs<List<bool>>(), {true, false, true, true});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint8_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint16_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkList(orig, {true, false, true, true});
// Can't upgrade bit lists. (This used to be supported.)
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<test::TestNewVersion>>());
}
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<uint8_t>>({0x12, 0x23, 0x33, 0x44});
auto orig = root.asReader().getAnyPointerField().getAs<List<uint8_t>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0x12, 0x23, 0x33, 0x44});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint16_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkList(orig, {0x12, 0x23, 0x33, 0x44});
checkUpgradedList(root, {0x12, 0x23, 0x33, 0x44}, {"", "", "", ""});
checkList(orig, {0, 0, 0, 0}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<uint16_t>>({0x5612, 0x7823, 0xab33, 0xcd44});
auto orig = root.asReader().getAnyPointerField().getAs<List<uint16_t>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0x12, 0x23, 0x33, 0x44});
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {0x5612, 0x7823, 0xab33, 0xcd44});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkList(orig, {0x5612, 0x7823, 0xab33, 0xcd44});
checkUpgradedList(root, {0x5612, 0x7823, 0xab33, 0xcd44}, {"", "", "", ""});
checkList(orig, {0, 0, 0, 0}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<uint32_t>>({0x17595612, 0x29347823, 0x5923ab32, 0x1a39cd45});
auto orig = root.asReader().getAnyPointerField().getAs<List<uint32_t>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0x12, 0x23, 0x32, 0x45});
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {0x5612, 0x7823, 0xab32, 0xcd45});
checkList(root.getAnyPointerField().getAs<List<uint32_t>>(), {0x17595612u, 0x29347823u, 0x5923ab32u, 0x1a39cd45u});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkList(orig, {0x17595612u, 0x29347823u, 0x5923ab32u, 0x1a39cd45u});
checkUpgradedList(root, {0x17595612, 0x29347823, 0x5923ab32, 0x1a39cd45}, {"", "", "", ""});
checkList(orig, {0u, 0u, 0u, 0u}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<uint64_t>>({0x1234abcd8735fe21, 0x7173bc0e1923af36});
auto orig = root.asReader().getAnyPointerField().getAs<List<uint64_t>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0x21, 0x36});
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {0xfe21, 0xaf36});
checkList(root.getAnyPointerField().getAs<List<uint32_t>>(), {0x8735fe21u, 0x1923af36u});
checkList(root.getAnyPointerField().getAs<List<uint64_t>>(), {0x1234abcd8735fe21ull, 0x7173bc0e1923af36ull});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
checkList(orig, {0x1234abcd8735fe21ull, 0x7173bc0e1923af36ull});
checkUpgradedList(root, {0x1234abcd8735fe21ull, 0x7173bc0e1923af36ull}, {"", ""});
checkList(orig, {0u, 0u}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
{
root.getAnyPointerField().setAs<List<Text>>({"foo", "bar", "baz"});
auto orig = root.asReader().getAnyPointerField().getAs<List<Text>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint8_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint16_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
checkList(root.getAnyPointerField().getAs<List<Text>>(), {"foo", "bar", "baz"});
checkList(orig, {"foo", "bar", "baz"});
checkUpgradedList(root, {0, 0, 0}, {"foo", "bar", "baz"});
checkList(orig, {"", "", ""}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
{
{
auto l = root.getAnyPointerField().initAs<List<test::TestOldVersion>>(3);
l[0].setOld1(0x1234567890abcdef);
l[1].setOld1(0x234567890abcdef1);
l[2].setOld1(0x34567890abcdef12);
l[0].setOld2("foo");
l[1].setOld2("bar");
l[2].setOld2("baz");
}
auto orig = root.asReader().getAnyPointerField().getAs<List<test::TestOldVersion>>();
checkList(root.getAnyPointerField().getAs<List<Void>>(), {VOID, VOID, VOID});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0xefu, 0xf1u, 0x12u});
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {0xcdefu, 0xdef1u, 0xef12u});
checkList(root.getAnyPointerField().getAs<List<uint32_t>>(), {0x90abcdefu, 0x0abcdef1u, 0xabcdef12u});
checkList(root.getAnyPointerField().getAs<List<uint64_t>>(),
{0x1234567890abcdefull, 0x234567890abcdef1ull, 0x34567890abcdef12ull});
checkList(root.getAnyPointerField().getAs<List<Text>>(), {"foo", "bar", "baz"});
checkList(orig, {0x1234567890abcdefull, 0x234567890abcdef1ull, 0x34567890abcdef12ull},
{"foo", "bar", "baz"});
checkUpgradedList(root, {0x1234567890abcdefull, 0x234567890abcdef1ull, 0x34567890abcdef12ull},
{"foo", "bar", "baz"});
checkList(orig, {0u, 0u, 0u}, {"", "", ""}); // old location zero'd during upgrade
}
// -----------------------------------------------------------------
// OK, now we've tested upgrading every primitive list to every primitive list, every primitive
// list to a multi-word struct, and a multi-word struct to every primitive list. But we haven't
// tried upgrading primitive lists to sub-word structs.
// Upgrade from multi-byte, sub-word data.
root.getAnyPointerField().setAs<List<uint16_t>>({12u, 34u, 56u, 78u});
{
auto orig = root.asReader().getAnyPointerField().getAs<List<uint16_t>>();
checkList(orig, {12u, 34u, 56u, 78u});
auto l = root.getAnyPointerField().getAs<List<test::TestLists::Struct32>>();
checkList(orig, {0u, 0u, 0u, 0u}); // old location zero'd during upgrade
ASSERT_EQ(4u, l.size());
EXPECT_EQ(12u, l[0].getF());
EXPECT_EQ(34u, l[1].getF());
EXPECT_EQ(56u, l[2].getF());
EXPECT_EQ(78u, l[3].getF());
l[0].setF(0x65ac1235u);
l[1].setF(0x13f12879u);
l[2].setF(0x33423082u);
l[3].setF(0x12988948u);
}
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint8_t>>(), {0x35u, 0x79u, 0x82u, 0x48u});
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {0x1235u, 0x2879u, 0x3082u, 0x8948u});
checkList(root.getAnyPointerField().getAs<List<uint32_t>>(),
{0x65ac1235u, 0x13f12879u, 0x33423082u, 0x12988948u});
checkList(root.getAnyPointerField().getAs<List<uint64_t>>(),
{0x65ac1235u, 0x13f12879u, 0x33423082u, 0x12988948u});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
// Upgrade from void -> data struct
root.getAnyPointerField().setAs<List<Void>>({VOID, VOID, VOID, VOID});
{
auto l = root.getAnyPointerField().getAs<List<test::TestLists::Struct16>>();
ASSERT_EQ(4u, l.size());
EXPECT_EQ(0u, l[0].getF());
EXPECT_EQ(0u, l[1].getF());
EXPECT_EQ(0u, l[2].getF());
EXPECT_EQ(0u, l[3].getF());
l[0].setF(12573);
l[1].setF(3251);
l[2].setF(9238);
l[3].setF(5832);
}
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
checkList(root.getAnyPointerField().getAs<List<uint16_t>>(), {12573u, 3251u, 9238u, 5832u});
checkList(root.getAnyPointerField().getAs<List<uint32_t>>(), {12573u, 3251u, 9238u, 5832u});
checkList(root.getAnyPointerField().getAs<List<uint64_t>>(), {12573u, 3251u, 9238u, 5832u});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
// Upgrade from void -> pointer struct
root.getAnyPointerField().setAs<List<Void>>({VOID, VOID, VOID, VOID});
{
auto l = root.getAnyPointerField().getAs<List<test::TestLists::StructP>>();
ASSERT_EQ(4u, l.size());
EXPECT_EQ("", l[0].getF());
EXPECT_EQ("", l[1].getF());
EXPECT_EQ("", l[2].getF());
EXPECT_EQ("", l[3].getF());
l[0].setF("foo");
l[1].setF("bar");
l[2].setF("baz");
l[3].setF("qux");
}
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<bool>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint16_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint64_t>>());
checkList(root.getAnyPointerField().getAs<List<Text>>(), {"foo", "bar", "baz", "qux"});
// Verify that we cannot "side-grade" a pointer list to a data list, or a data list to
// a pointer struct list.
root.getAnyPointerField().setAs<List<Text>>({"foo", "bar", "baz", "qux"});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<uint32_t>>());
root.getAnyPointerField().setAs<List<uint32_t>>({12, 34, 56, 78});
EXPECT_NONFATAL_FAILURE(root.getAnyPointerField().getAs<List<Text>>());
}
TEST(Encoding, UpgradeUnion) {
// This tests for a specific case that was broken originally.
MallocMessageBuilder builder;
{
auto root = builder.getRoot<test::TestOldUnionVersion>();
root.setB(123);
}
{
auto root = builder.getRoot<test::TestNewUnionVersion>();
ASSERT_TRUE(root.isB())
EXPECT_EQ(123, root.getB());
}
}
// =======================================================================================
// Tests of generated code, not really of the encoding.
// TODO(cleanup): Move to a different test?
TEST(Encoding, NestedTypes) {
// This is more of a test of the generated code than the encoding.
MallocMessageBuilder builder;
TestNestedTypes::Reader reader = builder.getRoot<TestNestedTypes>().asReader();
EXPECT_EQ(TestNestedTypes::NestedEnum::BAR, reader.getOuterNestedEnum());
EXPECT_EQ(TestNestedTypes::NestedStruct::NestedEnum::QUUX, reader.getInnerNestedEnum());
TestNestedTypes::NestedStruct::Reader nested = reader.getNestedStruct();
EXPECT_EQ(TestNestedTypes::NestedEnum::BAR, nested.getOuterNestedEnum());
EXPECT_EQ(TestNestedTypes::NestedStruct::NestedEnum::QUUX, nested.getInnerNestedEnum());
}
TEST(Encoding, Imports) {
// Also just testing the generated code.
{
MallocMessageBuilder builder;
TestImport::Builder root = builder.getRoot<TestImport>();
initTestMessage(root.initField());
checkTestMessage(root.asReader().getField());
}
{
MallocMessageBuilder builder;
TestImport2::Builder root = builder.getRoot<TestImport2>();
initTestMessage(root.initFoo());
checkTestMessage(root.asReader().getFoo());
root.setBar(schemaProto<TestAllTypes>());
initTestMessage(root.initBaz().initField());
checkTestMessage(root.asReader().getBaz().getField());
}
}
TEST(Encoding, Using) {
MallocMessageBuilder builder;
TestUsing::Reader reader = builder.getRoot<TestUsing>().asReader();
EXPECT_EQ(TestNestedTypes::NestedEnum::BAR, reader.getOuterNestedEnum());
EXPECT_EQ(TestNestedTypes::NestedStruct::NestedEnum::QUUX, reader.getInnerNestedEnum());
}
TEST(Encoding, StructSetters) {
MallocMessageBuilder builder;
auto root = builder.getRoot<TestAllTypes>();
initTestMessage(root);
{
MallocMessageBuilder builder2;
builder2.setRoot(root.asReader());
checkTestMessage(builder2.getRoot<TestAllTypes>());
}
{
MallocMessageBuilder builder2;
auto root2 = builder2.getRoot<TestAllTypes>();
root2.setStructField(root);
checkTestMessage(root2.getStructField());
}
{
MallocMessageBuilder builder2;
auto root2 = builder2.getRoot<test::TestAnyPointer>();
root2.getAnyPointerField().setAs<test::TestAllTypes>(root);
checkTestMessage(root2.getAnyPointerField().getAs<test::TestAllTypes>());
}
}
TEST(Encoding, OneBitStructSetters) {
// Test case of setting a 1-bit struct.
MallocMessageBuilder builder;
auto root = builder.getRoot<test::TestLists>();
auto list = root.initList1(8);
list[0].setF(true);
list[1].setF(true);
list[2].setF(false);
list[3].setF(true);
list[4].setF(true);
list[5].setF(false);
list[6].setF(true);
list[7].setF(false);
MallocMessageBuilder builder2;
builder2.setRoot(list.asReader()[2]);
EXPECT_FALSE(builder2.getRoot<test::TestLists::Struct1>().getF());
builder2.setRoot(list.asReader()[6]);
EXPECT_TRUE(builder2.getRoot<test::TestLists::Struct1>().getF());
}
TEST(Encoding, ListSetters) {
MallocMessageBuilder builder;
auto root = builder.getRoot<TestListDefaults>();
initTestMessage(root);
{
MallocMessageBuilder builder2;
auto root2 = builder2.getRoot<TestListDefaults>();
root2.getLists().setList0(root.getLists().getList0());
root2.getLists().setList1(root.getLists().getList1());
root2.getLists().setList8(root.getLists().getList8());
root2.getLists().setList16(root.getLists().getList16());
root2.getLists().setList32(root.getLists().getList32());
root2.getLists().setList64(root.getLists().getList64());
root2.getLists().setListP(root.getLists().getListP());
{
auto dst = root2.getLists().initInt32ListList(3);
auto src = root.getLists().getInt32ListList();
dst.set(0, src[0]);
dst.set(1, src[1]);
dst.set(2, src[2]);
}
{
auto dst = root2.getLists().initTextListList(3);
auto src = root.getLists().getTextListList();
dst.set(0, src[0]);
dst.set(1, src[1]);
dst.set(2, src[2]);
}
{
auto dst = root2.getLists().initStructListList(2);
auto src = root.getLists().getStructListList();
dst.set(0, src[0]);
dst.set(1, src[1]);
}
}
}
TEST(Encoding, ZeroOldObject) {
MallocMessageBuilder builder;
auto root = builder.initRoot<TestAllTypes>();
initTestMessage(root);
auto oldRoot = root.asReader();
checkTestMessage(oldRoot);
auto oldSub = oldRoot.getStructField();
auto oldSub2 = oldRoot.getStructList()[0];
root = builder.initRoot<TestAllTypes>();
checkTestMessageAllZero(oldRoot);
checkTestMessageAllZero(oldSub);
checkTestMessageAllZero(oldSub2);
}
TEST(Encoding, Has) {
MallocMessageBuilder builder;
auto root = builder.initRoot<TestAllTypes>();
EXPECT_FALSE(root.hasTextField());
EXPECT_FALSE(root.hasDataField());
EXPECT_FALSE(root.hasStructField());
EXPECT_FALSE(root.hasInt32List());
EXPECT_FALSE(root.asReader().hasTextField());
EXPECT_FALSE(root.asReader().hasDataField());
EXPECT_FALSE(root.asReader().hasStructField());
EXPECT_FALSE(root.asReader().hasInt32List());
initTestMessage(root);
EXPECT_TRUE(root.hasTextField());
EXPECT_TRUE(root.hasDataField());
EXPECT_TRUE(root.hasStructField());
EXPECT_TRUE(root.hasInt32List());
EXPECT_TRUE(root.asReader().hasTextField());
EXPECT_TRUE(root.asReader().hasDataField());
EXPECT_TRUE(root.asReader().hasStructField());
EXPECT_TRUE(root.asReader().hasInt32List());
}
TEST(Encoding, VoidListAmplification) {
MallocMessageBuilder builder;
builder.initRoot<test::TestAnyPointer>().getAnyPointerField().initAs<List<Void>>(1u << 28);
auto segments = builder.getSegmentsForOutput();
EXPECT_EQ(1, segments.size());
EXPECT_LT(segments[0].size(), 16); // quite small for such a big list!
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
auto root = reader.getRoot<test::TestAnyPointer>().getAnyPointerField();
EXPECT_NONFATAL_FAILURE(root.getAs<List<TestAllTypes>>());
MallocMessageBuilder copy;
EXPECT_NONFATAL_FAILURE(copy.setRoot(reader.getRoot<AnyPointer>()));
}
TEST(Encoding, EmptyStructListAmplification) {
MallocMessageBuilder builder(1024);
auto listList = builder.initRoot<test::TestAnyPointer>().getAnyPointerField()
.initAs<List<List<test::TestEmptyStruct>>>(500);
for (uint i = 0; i < listList.size(); i++) {
listList.init(i, 1u << 28);
}
auto segments = builder.getSegmentsForOutput();
ASSERT_EQ(1, segments.size());
SegmentArrayMessageReader reader(builder.getSegmentsForOutput());
auto root = reader.getRoot<test::TestAnyPointer>();
auto listListReader = root.getAnyPointerField().getAs<List<List<TestAllTypes>>>();
EXPECT_NONFATAL_FAILURE(listListReader[0]);
EXPECT_NONFATAL_FAILURE(listListReader[10]);
EXPECT_EQ(segments[0].size() - 1, root.totalSize().wordCount);
}
TEST(Encoding, Constants) {
EXPECT_EQ(VOID, test::TestConstants::VOID_CONST);
EXPECT_EQ(true, test::TestConstants::BOOL_CONST);
EXPECT_EQ(-123, test::TestConstants::INT8_CONST);
EXPECT_EQ(-12345, test::TestConstants::INT16_CONST);
EXPECT_EQ(-12345678, test::TestConstants::INT32_CONST);
EXPECT_EQ(-123456789012345ll, test::TestConstants::INT64_CONST);
EXPECT_EQ(234u, test::TestConstants::UINT8_CONST);
EXPECT_EQ(45678u, test::TestConstants::UINT16_CONST);
EXPECT_EQ(3456789012u, test::TestConstants::UINT32_CONST);
EXPECT_EQ(12345678901234567890ull, test::TestConstants::UINT64_CONST);
EXPECT_FLOAT_EQ(1234.5f, test::TestConstants::FLOAT32_CONST);
EXPECT_DOUBLE_EQ(-123e45, test::TestConstants::FLOAT64_CONST);
EXPECT_EQ("foo", *test::TestConstants::TEXT_CONST);
EXPECT_EQ(data("bar"), test::TestConstants::DATA_CONST);
{
TestAllTypes::Reader subReader = test::TestConstants::STRUCT_CONST;
EXPECT_EQ(VOID, subReader.getVoidField());
EXPECT_EQ(true, subReader.getBoolField());
EXPECT_EQ(-12, subReader.getInt8Field());
EXPECT_EQ(3456, subReader.getInt16Field());
EXPECT_EQ(-78901234, subReader.getInt32Field());
EXPECT_EQ(56789012345678ll, subReader.getInt64Field());
EXPECT_EQ(90u, subReader.getUInt8Field());
EXPECT_EQ(1234u, subReader.getUInt16Field());
EXPECT_EQ(56789012u, subReader.getUInt32Field());
EXPECT_EQ(345678901234567890ull, subReader.getUInt64Field());
EXPECT_FLOAT_EQ(-1.25e-10f, subReader.getFloat32Field());
EXPECT_DOUBLE_EQ(345, subReader.getFloat64Field());
EXPECT_EQ("baz", subReader.getTextField());
EXPECT_EQ(data("qux"), subReader.getDataField());
{
auto subSubReader = subReader.getStructField();
EXPECT_EQ("nested", subSubReader.getTextField());
EXPECT_EQ("really nested", subSubReader.getStructField().getTextField());
}
EXPECT_EQ(TestEnum::BAZ, subReader.getEnumField());
checkList(subReader.getVoidList(), {VOID, VOID, VOID});
checkList(subReader.getBoolList(), {false, true, false, true, true});
checkList(subReader.getInt8List(), {12, -34, -0x80, 0x7f});
checkList(subReader.getInt16List(), {1234, -5678, -0x8000, 0x7fff});
// gcc warns on -0x800... and the only work-around I could find was to do -0x7ff...-1.
checkList(subReader.getInt32List(), {12345678, -90123456, -0x7fffffff - 1, 0x7fffffff});
checkList(subReader.getInt64List(), {123456789012345ll, -678901234567890ll, -0x7fffffffffffffffll-1, 0x7fffffffffffffffll});
checkList(subReader.getUInt8List(), {12u, 34u, 0u, 0xffu});
checkList(subReader.getUInt16List(), {1234u, 5678u, 0u, 0xffffu});
checkList(subReader.getUInt32List(), {12345678u, 90123456u, 0u, 0xffffffffu});
checkList(subReader.getUInt64List(), {123456789012345ull, 678901234567890ull, 0ull, 0xffffffffffffffffull});
checkList(subReader.getFloat32List(), {0.0f, 1234567.0f, 1e37f, -1e37f, 1e-37f, -1e-37f});
checkList(subReader.getFloat64List(), {0.0, 123456789012345.0, 1e306, -1e306, 1e-306, -1e-306});
checkList(subReader.getTextList(), {"quux", "corge", "grault"});
checkList(subReader.getDataList(), {data("garply"), data("waldo"), data("fred")});
{
auto listReader = subReader.getStructList();
ASSERT_EQ(3u, listReader.size());
EXPECT_EQ("x structlist 1", listReader[0].getTextField());
EXPECT_EQ("x structlist 2", listReader[1].getTextField());
EXPECT_EQ("x structlist 3", listReader[2].getTextField());
}
checkList(subReader.getEnumList(), {TestEnum::QUX, TestEnum::BAR, TestEnum::GRAULT});
}
EXPECT_EQ(TestEnum::CORGE, test::TestConstants::ENUM_CONST);
EXPECT_EQ(6u, test::TestConstants::VOID_LIST_CONST->size());
checkList(*test::TestConstants::BOOL_LIST_CONST, {true, false, false, true});
checkList(*test::TestConstants::INT8_LIST_CONST, {111, -111});
checkList(*test::TestConstants::INT16_LIST_CONST, {11111, -11111});
checkList(*test::TestConstants::INT32_LIST_CONST, {111111111, -111111111});
checkList(*test::TestConstants::INT64_LIST_CONST, {1111111111111111111ll, -1111111111111111111ll});
checkList(*test::TestConstants::UINT8_LIST_CONST, {111u, 222u});
checkList(*test::TestConstants::UINT16_LIST_CONST, {33333u, 44444u});
checkList(*test::TestConstants::UINT32_LIST_CONST, {3333333333u});
checkList(*test::TestConstants::UINT64_LIST_CONST, {11111111111111111111ull});
{
List<float>::Reader listReader = test::TestConstants::FLOAT32_LIST_CONST;
ASSERT_EQ(4u, listReader.size());
EXPECT_EQ(5555.5f, listReader[0]);
EXPECT_EQ(kj::inf(), listReader[1]);
EXPECT_EQ(-kj::inf(), listReader[2]);
EXPECT_TRUE(listReader[3] != listReader[3]);
}
{
List<double>::Reader listReader = test::TestConstants::FLOAT64_LIST_CONST;
ASSERT_EQ(4u, listReader.size());
EXPECT_EQ(7777.75, listReader[0]);
EXPECT_EQ(kj::inf(), listReader[1]);
EXPECT_EQ(-kj::inf(), listReader[2]);
EXPECT_TRUE(listReader[3] != listReader[3]);
}
checkList(*test::TestConstants::TEXT_LIST_CONST, {"plugh", "xyzzy", "thud"});
checkList(*test::TestConstants::DATA_LIST_CONST, {data("oops"), data("exhausted"), data("rfc3092")});
{
List<TestAllTypes>::Reader listReader = test::TestConstants::STRUCT_LIST_CONST;
ASSERT_EQ(3u, listReader.size());
EXPECT_EQ("structlist 1", listReader[0].getTextField());
EXPECT_EQ("structlist 2", listReader[1].getTextField());
EXPECT_EQ("structlist 3", listReader[2].getTextField());
}
checkList(*test::TestConstants::ENUM_LIST_CONST, {TestEnum::FOO, TestEnum::GARPLY});
}
TEST(Encoding, AnyPointerConstants) {
auto reader = test::ANY_POINTER_CONSTANTS.get();
EXPECT_EQ("baz", reader.getAnyKindAsStruct().getAs<TestAllTypes>().getTextField());
EXPECT_EQ("baz", reader.getAnyStructAsStruct().as<TestAllTypes>().getTextField());
EXPECT_EQ(111111111, reader.getAnyKindAsList().getAs<List<int32_t>>()[0]);
EXPECT_EQ(111111111, reader.getAnyListAsList().as<List<int32_t>>()[0]);
}
TEST(Encoding, GlobalConstants) {
EXPECT_EQ(12345u, test::GLOBAL_INT);
EXPECT_EQ("foobar", test::GLOBAL_TEXT.get());
EXPECT_EQ(54321, test::GLOBAL_STRUCT->getInt32Field());
TestAllTypes::Reader reader = test::DERIVED_CONSTANT;
EXPECT_EQ(12345, reader.getUInt32Field());
EXPECT_EQ("foo", reader.getTextField());
checkList(reader.getStructField().getTextList(), {"quux", "corge", "grault"});
checkList(reader.getInt16List(), {11111, -11111});
{
List<TestAllTypes>::Reader listReader = reader.getStructList();
ASSERT_EQ(3u, listReader.size());
EXPECT_EQ("structlist 1", listReader[0].getTextField());
EXPECT_EQ("structlist 2", listReader[1].getTextField());
EXPECT_EQ("structlist 3", listReader[2].getTextField());
}
}
TEST(Encoding, Embeds) {
{
kj::ArrayInputStream input(test::EMBEDDED_DATA);
PackedMessageReader reader(input);
checkTestMessage(reader.getRoot<TestAllTypes>());
}
#if !CAPNP_LITE
{
MallocMessageBuilder builder;
auto root = builder.getRoot<TestAllTypes>();
initTestMessage(root);
kj::StringPtr text = test::EMBEDDED_TEXT;
EXPECT_EQ(kj::str(root, text.endsWith("\r\n") ? "\r\n" : "\n"), text);
}
#endif // CAPNP_LITE
{
checkTestMessage(test::EMBEDDED_STRUCT);
}
}
TEST(Encoding, HasEmptyStruct) {
MallocMessageBuilder message;
auto root = message.initRoot<test::TestAnyPointer>();
EXPECT_EQ(1, root.totalSize().wordCount);
EXPECT_FALSE(root.asReader().hasAnyPointerField());
EXPECT_FALSE(root.hasAnyPointerField());
root.getAnyPointerField().initAs<test::TestEmptyStruct>();
EXPECT_TRUE(root.asReader().hasAnyPointerField());
EXPECT_TRUE(root.hasAnyPointerField());
EXPECT_EQ(1, root.totalSize().wordCount);
}
TEST(Encoding, HasEmptyList) {
MallocMessageBuilder message;
auto root = message.initRoot<test::TestAnyPointer>();
EXPECT_EQ(1, root.totalSize().wordCount);
EXPECT_FALSE(root.asReader().hasAnyPointerField());
EXPECT_FALSE(root.hasAnyPointerField());
root.getAnyPointerField().initAs<List<int32_t>>(0);
EXPECT_TRUE(root.asReader().hasAnyPointerField());
EXPECT_TRUE(root.hasAnyPointerField());
EXPECT_EQ(1, root.totalSize().wordCount);
}
TEST(Encoding, HasEmptyStructList) {
MallocMessageBuilder message;
auto root = message.initRoot<test::TestAnyPointer>();
EXPECT_EQ(1, root.totalSize().wordCount);
EXPECT_FALSE(root.asReader().hasAnyPointerField());
EXPECT_FALSE(root.hasAnyPointerField());
root.getAnyPointerField().initAs<List<TestAllTypes>>(0);
EXPECT_TRUE(root.asReader().hasAnyPointerField());
EXPECT_TRUE(root.hasAnyPointerField());
EXPECT_EQ(2, root.totalSize().wordCount);
}
TEST(Encoding, NameAnnotation) {
EXPECT_EQ(2, static_cast<uint16_t>(test::RenamedStruct::RenamedEnum::QUX));
EXPECT_EQ(2, static_cast<uint16_t>(test::RenamedStruct::RenamedNestedStruct::RenamedDeeplyNestedEnum::GARPLY));
MallocMessageBuilder message;
auto root = message.initRoot<test::RenamedStruct>();
root.setGoodFieldName(true);
EXPECT_EQ(true, root.getGoodFieldName());
EXPECT_TRUE(root.isGoodFieldName());
root.setBar(0xff);
EXPECT_FALSE(root.isGoodFieldName());
root.setAnotherGoodFieldName(test::RenamedStruct::RenamedEnum::QUX);
EXPECT_EQ(test::RenamedStruct::RenamedEnum::QUX, root.getAnotherGoodFieldName());
EXPECT_FALSE(root.getRenamedUnion().isQux());
auto quxBuilder = root.getRenamedUnion().initQux();
EXPECT_TRUE(root.getRenamedUnion().isQux());
EXPECT_FALSE(root.getRenamedUnion().getQux().hasAnotherGoodNestedFieldName());
quxBuilder.setGoodNestedFieldName(true);
EXPECT_EQ(true, quxBuilder.getGoodNestedFieldName());
EXPECT_FALSE(quxBuilder.hasAnotherGoodNestedFieldName());
auto nestedFieldBuilder = quxBuilder.initAnotherGoodNestedFieldName();
EXPECT_TRUE(quxBuilder.hasAnotherGoodNestedFieldName());
nestedFieldBuilder.setGoodNestedFieldName(true);
EXPECT_EQ(true, nestedFieldBuilder.getGoodNestedFieldName());
EXPECT_FALSE(nestedFieldBuilder.hasAnotherGoodNestedFieldName());
EXPECT_FALSE(root.getRenamedUnion().isRenamedGroup());
auto renamedGroupBuilder KJ_UNUSED = root.getRenamedUnion().initRenamedGroup();
EXPECT_TRUE(root.getRenamedUnion().isRenamedGroup());
test::RenamedInterface::RenamedMethodParams::Reader renamedInterfaceParams;
renamedInterfaceParams.getRenamedParam();
}
TEST(Encoding, DefaultFloatPlusNan) {
MallocMessageBuilder message;
auto root = message.initRoot<TestDefaults>();
root.setFloat32Field(kj::nan());
root.setFloat64Field(kj::nan());
float f = root.getFloat32Field();
EXPECT_TRUE(f != f);
double d = root.getFloat64Field();
EXPECT_TRUE(d != d);
}
TEST(Encoding, WholeFloatDefault) {
MallocMessageBuilder message;
auto root = message.initRoot<test::TestWholeFloatDefault>();
EXPECT_EQ(123.0f, root.getField());
EXPECT_EQ(2e30f, root.getBigField());
EXPECT_EQ(456.0f, test::TestWholeFloatDefault::CONSTANT);
EXPECT_EQ(4e30f, test::TestWholeFloatDefault::BIG_CONSTANT);
}
TEST(Encoding, Generics) {
MallocMessageBuilder message;
auto root = message.initRoot<test::TestUseGenerics>();
auto reader = root.asReader();
initTestMessage(root.initBasic().initFoo());
checkTestMessage(reader.getBasic().getFoo());
{
auto typed = root.getBasic();
test::TestGenerics<>::Reader generic = typed.asGeneric<>();
checkTestMessage(generic.getFoo().getAs<TestAllTypes>());
test::TestGenerics<TestAllTypes>::Reader halfGeneric = typed.asGeneric<TestAllTypes>();
checkTestMessage(halfGeneric.getFoo());
}
{
auto typed = root.getBasic().asReader();
test::TestGenerics<>::Reader generic = typed.asGeneric<>();
checkTestMessage(generic.getFoo().getAs<TestAllTypes>());
test::TestGenerics<TestAllTypes>::Reader halfGeneric = typed.asGeneric<TestAllTypes>();
checkTestMessage(halfGeneric.getFoo());
}
initTestMessage(root.initInner().initFoo());
checkTestMessage(reader.getInner().getFoo());
{
auto typed = root.getInner();
test::TestGenerics<>::Inner::Reader generic = typed.asTestGenericsGeneric<>();
checkTestMessage(generic.getFoo().getAs<TestAllTypes>());
test::TestGenerics<TestAllTypes>::Inner::Reader halfGeneric = typed.asTestGenericsGeneric<TestAllTypes>();
checkTestMessage(halfGeneric.getFoo());
}
{
auto typed = root.getInner().asReader();
test::TestGenerics<>::Inner::Reader generic = typed.asTestGenericsGeneric<>();
checkTestMessage(generic.getFoo().getAs<TestAllTypes>());
test::TestGenerics<TestAllTypes>::Inner::Reader halfGeneric = typed.asTestGenericsGeneric<TestAllTypes>();
checkTestMessage(halfGeneric.getFoo());
}
root.initInner2().setBaz("foo");
EXPECT_EQ("foo", reader.getInner2().getBaz());
initTestMessage(root.getInner2().initInnerBound().initFoo());
checkTestMessage(reader.getInner2().getInnerBound().getFoo());
initTestMessage(root.getInner2().initInnerUnbound().getFoo().initAs<TestAllTypes>());
checkTestMessage(reader.getInner2().getInnerUnbound().getFoo().getAs<TestAllTypes>());
initTestMessage(root.initUnspecified().getFoo().initAs<TestAllTypes>());
checkTestMessage(reader.getUnspecified().getFoo().getAs<TestAllTypes>());
initTestMessage(root.initWrapper().initValue().initFoo());
checkTestMessage(reader.getWrapper().getValue().getFoo());
}
TEST(Encoding, GenericDefaults) {
test::TestUseGenerics::Reader reader;
EXPECT_EQ(123, reader.getDefault().getFoo().getInt16Field());
EXPECT_EQ(123, reader.getDefaultInner().getFoo().getInt16Field());
EXPECT_EQ("text", reader.getDefaultInner().getBar());
EXPECT_EQ(123, reader.getDefaultUser().getBasic().getFoo().getInt16Field());
EXPECT_EQ("text", reader.getDefaultWrapper().getValue().getFoo());
EXPECT_EQ(321, reader.getDefaultWrapper().getValue().getRev().getFoo().getInt16Field());
EXPECT_EQ("text", reader.getDefaultWrapper2().getValue().getValue().getFoo());
EXPECT_EQ(321, reader.getDefaultWrapper2().getValue()
.getValue().getRev().getFoo().getInt16Field());
}
TEST(Encoding, UnionInGenerics) {
MallocMessageBuilder message;
auto builder = message.initRoot<test::TestGenerics<>>();
auto reader = builder.asReader();
//just call the methods to verify that generated code compiles
reader.which();
builder.which();
reader.isUv();
builder.isUv();
reader.getUv();
builder.getUv();
builder.setUv();
builder.initUg();
reader.isUg();
builder.isUg();
reader.getUg();
builder.getUg();
builder.initUg();
}
TEST(Encoding, DefaultListBuilder) {
// At one point, this wouldn't compile.
List<int>::Builder(nullptr);
List<TestAllTypes>::Builder(nullptr);
List<List<int>>::Builder(nullptr);
List<Text>::Builder(nullptr);
}
TEST(Encoding, ListSize) {
MallocMessageBuilder builder;
auto root = builder.initRoot<TestListDefaults>();
initTestMessage(root);
auto lists = root.asReader().getLists();
auto listSizes =
lists.getList0().totalSize() +
lists.getList1().totalSize() +
lists.getList8().totalSize() +
lists.getList16().totalSize() +
lists.getList32().totalSize() +
lists.getList64().totalSize() +
lists.getListP().totalSize() +
lists.getInt32ListList().totalSize() +
lists.getTextListList().totalSize() +
lists.getStructListList().totalSize();
auto structSize = lists.totalSize();
auto shallowSize = unbound(capnp::_::structSize<test::TestLists>().total() / WORDS);
EXPECT_EQ(structSize.wordCount - shallowSize, listSizes.wordCount);
}
KJ_TEST("list.setWithCaveats(i, list[i]) doesn't corrupt contents") {
MallocMessageBuilder builder;
auto root = builder.initRoot<TestAllTypes>();
auto list = root.initStructList(2);
initTestMessage(list[0]);
list.setWithCaveats(0, list[0]);
checkTestMessage(list[0]);
checkTestMessageAllZero(list[1]);
list.setWithCaveats(1, list[0]);
checkTestMessage(list[0]);
checkTestMessage(list[1]);
}
} // namespace
} // namespace _ (private)
} // namespace capnp
| {
"content_hash": "56ca6c5026b2328bed1a7bb753c0fa34",
"timestamp": "",
"source": "github",
"line_count": 1943,
"max_line_length": 128,
"avg_line_length": 36.98661863098302,
"alnum_prop": 0.6779238850622695,
"repo_name": "mologie/capnproto",
"id": "b7ac5f6517734ecf02a5274eb639019bf2451e60",
"size": "73280",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "c++/src/capnp/encoding-test.c++",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "4291998"
},
{
"name": "CMake",
"bytes": "11784"
},
{
"name": "Cap'n Proto",
"bytes": "165042"
},
{
"name": "Emacs Lisp",
"bytes": "2097"
},
{
"name": "Protocol Buffer",
"bytes": "5344"
},
{
"name": "Python",
"bytes": "3926"
},
{
"name": "Shell",
"bytes": "39592"
}
],
"symlink_target": ""
} |
To program the SCVM, open the `Program.h` file located in the `src` directory. The VM only supports
a single program at the moment, and to edit it, change the code in the `program` array (it's type `int`).
Here are the currently available instructions (please update this list if you add more):
- `HLT` (use at the end of your programs)
- `PSH` (pushes the value in the argument register onto the stack)
- `POP` (pops the top value on the stack into the argument register)
- `SET` (puts the value in the first argument into the register in the second argument)
- `MOV` (copies the value in the register in the first argument into the second)
- `OUT` (displays the value in the argument register in STDOUT)
- `IN` (reads from STDIN into the argument register)
- `ADD` (adds the values in the argument registers together, puts the result in the second register)
- `SUB` (subtracts the value in the first arg register from the second, puts the result in the second register)
- `MPY` (multiplies the values in the arg registers together, puts the result in the second register)
- `DIV` (divides the value in the first arg register by the second, puts the result in the second register)
- `JMP` (jumps to the point in the program specified by the argument (no register needed)
- `CHN` (changes the program instruction at the address in the first argument to the instruction in the second argument)
- `INC` (increments the value in the argument register by 1)
- `DEC` (decrements the value in the argument register by 1)
- `DJMP` (from Zilog Z80 instruction `djnz`, it loops to the address in the argument while register B > 0, decrementing that register each loop)
- `CALL` (calls a subroutine that lies at the address in the argument)
- `RET` (returns from a subroutine)
- `CMP` (compares two argument registers and branches to a third argument address if the registers are the same)
- `CMPF` (same as `CMP`, but branches if the arguments aren't the same)
- `PUT` (prints a register value as a character)
- `RND` (puts a random integer from 0 to 255 into the argument register)
- `POKE` (puts the value in the first argument register in the memory address (`0x00` to `0xFF`) specified in the second argument
- `PEEK` (puts the value at the memory address in the second argument (`0x00` to `0xFF`) into the register in the first argument
- `LESS` (compares the values in the first two argument registers, branching to the third argument if the first value is less than the second)
- `MORE` (compares the values in the first two argument registers, branching to the third argument if the first value is more than the second)
- `LTOE` (compares the values in the first two argument registers, branching to the third argument if the first value is less than or equal to the second)
- `GTOE` (same as `LTOE`, except the instruction checks for greater than or equal to instead of less than or equal to)
A note on the `CALL` and `RET` instructions: **YOU MUST POP EVERYTHING OFF THE STACK THAT YOU PUSH ONTO IT BEFORE RETURNING FROM A SUBROUTINE!!!**
Due to the way the instructions work, the program will jump to arbitrary addresses if you don't.
## How To Build
Download the repository, unzip it, `cd` into its folder, and type `./assemble.sh nameOfProgram`, where `nameOfProgram`
is the name of your program, or if you're running Windows, run `assemble.bat`. An executable will
appear in the `bin` directory. Run it to try out the VM, and then reprogram it to do what you want!
## Cleaning Up
Before each build, run either `./clean.sh` or `clean.bat`, depending on what OS you're running.
These scripts delete the past executable and make way for a new one. | {
"content_hash": "77c4765857943b93afb885f3064f55d1",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 154,
"avg_line_length": 77.80851063829788,
"alnum_prop": 0.7555373256767842,
"repo_name": "techgineer/simple-c-vm",
"id": "d3b8121cc7d5d335539bece717273b055a8cac3e",
"size": "3694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "539"
},
{
"name": "C",
"bytes": "8170"
},
{
"name": "C++",
"bytes": "3779"
},
{
"name": "Shell",
"bytes": "242"
}
],
"symlink_target": ""
} |
We technically don't need this plugin anymore, since we store the settings as
`local storage` in the usercache, and can directly access it from both native
code and javascript. BUT the server communication currently does not use the
usercache, and there might be places that still use this code (e.g. to display
the server that we are connected to) for debugging.
This also provides a convenient place to provide the format for the user settings.
So let's extend this plugin for now, but soon we should remove it and use the
JSON directly.
| {
"content_hash": "416e4b2ad3d22fb40e9ae14ac0eeb004",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 82,
"avg_line_length": 54.2,
"alnum_prop": 0.7952029520295203,
"repo_name": "e-mission/cordova-connection-settings",
"id": "85204e7add71b20b55b7ff9e4195f452a15b2dc7",
"size": "542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "11884"
},
{
"name": "JavaScript",
"bytes": "8579"
},
{
"name": "Objective-C",
"bytes": "8206"
}
],
"symlink_target": ""
} |
import { StandardArticle } from "@artsy/reaction/dist/Components/Publishing/Fixtures/Articles"
import { RichText } from "client/components/draft/rich_text/rich_text"
import { getEditorState } from "client/components/draft/shared/test_helpers"
import { EditorState, SelectionState } from "draft-js"
import { mount } from "enzyme"
import { cloneDeep } from "lodash"
import React from "react"
import { SectionText2 } from "../index2"
describe("SectionText", () => {
let props
let article
const getWrapper = (passedProps = props) => {
return mount(<SectionText2 {...passedProps} />)
}
beforeEach(() => {
article = cloneDeep(StandardArticle)
props = {
article,
index: 2,
onChangeSectionAction: jest.fn(),
maybeMergeTextSectionsAction: jest.fn(),
onSetEditing: jest.fn(),
onSplitTextSectionAction: jest.fn(),
removeSectionAction: jest.fn(),
setSectionAction: jest.fn(),
section: cloneDeep(article.sections[11]),
sections: article.sections,
}
})
it("Renders RichText component", () => {
const component = getWrapper()
expect(component.find(RichText).length).toBe(1)
})
describe("#getAllowedBlocks", () => {
it("Returns correct blocks for feature", () => {
props.article.layout = "feature"
const instance = getWrapper().instance() as SectionText2
const blocks = instance.getAllowedBlocks()
expect(blocks).toEqual(["h1", "h2", "h3", "blockquote", "ol", "ul", "p"])
})
it("Returns correct blocks for standard", () => {
const instance = getWrapper().instance() as SectionText2
const blocks = instance.getAllowedBlocks()
expect(blocks).toEqual(["h2", "h3", "blockquote", "ol", "ul", "p"])
})
it("Returns correct blocks for news", () => {
props.article.layout = "news"
const instance = getWrapper().instance() as SectionText2
const blocks = instance.getAllowedBlocks()
expect(blocks).toEqual(["h3", "blockquote", "ol", "ul", "p"])
})
it("Returns correct blocks for classic", () => {
props.article.layout = "classic"
const instance = getWrapper().instance() as SectionText2
const blocks = instance.getAllowedBlocks()
expect(blocks).toEqual(["h2", "h3", "blockquote", "ul", "ol", "p"])
})
})
describe("#onHandleReturn", () => {
it("calls #onSplitTextSectionAction if section should be split", () => {
const instance = getWrapper().instance() as SectionText2
instance.divideEditorState = jest.fn().mockReturnValue({
beforeHtml: "<p>First block</p>",
afterHtml: "<p>Second block</p>",
})
instance.onHandleReturn(EditorState.createEmpty())
expect(props.onSplitTextSectionAction).toBeCalledWith(
"<p>First block</p>",
"<p>Second block</p>"
)
})
it("does nothing if section should not be split", () => {
const instance = getWrapper().instance() as SectionText2
instance.divideEditorState = jest.fn()
instance.onHandleReturn(EditorState.createEmpty())
expect(props.onSplitTextSectionAction).not.toBeCalled()
})
})
describe("#onHandleTab", () => {
it("calls #setSectionAction for next section", () => {
const instance = getWrapper().instance() as SectionText2
instance.onHandleTab({})
expect(props.setSectionAction).toBeCalledWith(3)
})
it("calls #setSectionAction for previous section if shift key", () => {
const instance = getWrapper().instance() as SectionText2
instance.onHandleTab({ shiftKey: true })
expect(props.setSectionAction).toBeCalledWith(1)
})
})
describe("#onHandleBackspace", () => {
it("calls #maybeMergeTextSectionsAction if section is not first", () => {
const instance = getWrapper().instance() as SectionText2
instance.onHandleBackspace()
expect(props.maybeMergeTextSectionsAction).toBeCalled()
})
it("does nothing if section is first", () => {
props.index = 0
const instance = getWrapper().instance() as SectionText2
instance.onHandleBackspace()
expect(props.maybeMergeTextSectionsAction).not.toBeCalled()
})
})
describe("#divideEditorState", () => {
it("Returns html for two blocks if state can be divided", () => {
const editorState = getEditorState(
"<p>First block.</p><p>Second block.</p>"
)
const startSelection = editorState.getSelection()
const startEditorState = editorState.getCurrentContent()
// @ts-ignore
const { key } = startEditorState.getLastBlock()
const selection = startSelection.merge({
anchorKey: key,
anchorOffset: 12,
focusKey: key,
focusOffset: 0,
}) as SelectionState
const newEditorState = EditorState.acceptSelection(editorState, selection)
const instance = getWrapper().instance() as SectionText2
const newBlocks = instance.divideEditorState(newEditorState)
expect(newBlocks).toEqual({
beforeHtml: "<p>First block.</p>",
afterHtml: "<p>Second block.</p>",
})
})
it("does nothing if section should not be split", () => {
const editorState = getEditorState(
"<p>First block.</p><p>Second block.</p>"
)
const instance = getWrapper().instance() as SectionText2
const newBlocks = instance.divideEditorState(editorState)
expect(newBlocks).toBeUndefined()
})
})
})
| {
"content_hash": "93873c381f669072c0184669c5881274",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 94,
"avg_line_length": 32.92168674698795,
"alnum_prop": 0.6428179322964318,
"repo_name": "artsy/positron",
"id": "d1dc0a93eab603a5e3144d4bb8c6bae25ac8fcb8",
"size": "5465",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/client/apps/edit/components/content/sections/text/test/index2.test.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1000"
},
{
"name": "CoffeeScript",
"bytes": "350176"
},
{
"name": "Dockerfile",
"bytes": "760"
},
{
"name": "JavaScript",
"bytes": "260838"
},
{
"name": "Jinja",
"bytes": "64"
},
{
"name": "Pug",
"bytes": "20408"
},
{
"name": "Ruby",
"bytes": "152"
},
{
"name": "Shell",
"bytes": "4865"
},
{
"name": "Stylus",
"bytes": "50413"
},
{
"name": "TypeScript",
"bytes": "1002178"
}
],
"symlink_target": ""
} |
from django.db import migrations
def update_judging_commitment_view_url(apps, schema_editor):
NavTreeItem = apps.get_model('accelerator', 'NavTreeItem')
NavTreeItem.objects.filter(
url='/expert/commitments/').update(url='/judging/commitments/')
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0076_update_sitetree_panels_view_url'),
]
operations = [
migrations.RunPython(update_judging_commitment_view_url,
migrations.RunPython.noop)
]
| {
"content_hash": "55f7c7c94ef52a15d746ccb12a45dde5",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 71,
"avg_line_length": 30.166666666666668,
"alnum_prop": 0.6666666666666666,
"repo_name": "masschallenge/django-accelerator",
"id": "70756e5c40dacde51d2564bd2561224e856fe312",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "accelerator/migrations/0077_update_sitetree_judging_commitment_view_url.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1848"
},
{
"name": "Makefile",
"bytes": "6817"
},
{
"name": "Python",
"bytes": "996767"
},
{
"name": "Shell",
"bytes": "2453"
}
],
"symlink_target": ""
} |
<?php
namespace DvsaCommonTest\Dto\Event;
use DvsaCommon\Dto\Event\EventListDto;
use DvsaCommonTest\Dto\AbstractDtoTester;
/**
* Unit test for class EventListDto
*
* @package DvsaCommonTest\Dto\Event
*/
class EventListDtoTest extends AbstractDtoTester
{
protected $dtoClassName = EventListDto::class;
}
| {
"content_hash": "538770060ce83b16bc162a920075507c",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 50,
"avg_line_length": 19.625,
"alnum_prop": 0.7770700636942676,
"repo_name": "dvsa/mot",
"id": "4643ee5b9a09b1d2a776448d38458dda4f4fe821",
"size": "314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mot-common-web-module/test/DvsaCommonTest/Dto/Event/EventListDtoTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "604618"
},
{
"name": "Dockerfile",
"bytes": "2693"
},
{
"name": "Gherkin",
"bytes": "189981"
},
{
"name": "HTML",
"bytes": "1579702"
},
{
"name": "Java",
"bytes": "1631717"
},
{
"name": "JavaScript",
"bytes": "156823"
},
{
"name": "Makefile",
"bytes": "2877"
},
{
"name": "PHP",
"bytes": "20142004"
},
{
"name": "PLpgSQL",
"bytes": "61098"
},
{
"name": "Python",
"bytes": "3354"
},
{
"name": "Ruby",
"bytes": "72"
},
{
"name": "SQLPL",
"bytes": "1739266"
},
{
"name": "Shell",
"bytes": "203709"
}
],
"symlink_target": ""
} |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
-- | Module containing the 'Monad2' and 'MonadTrans2' class definitions. Put simply, these are
-- monads with 2 type arguments, so if @m@ is a 'Monad2' type then an instance of it has type
-- @m a b@ for types @a@ and @b@. Similarly, if @t@ is a 'MonadTrans2' and 'm' is a
-- 'Monad' then an instance of the transformer has type 't m a b'.
--
-- ['Monad2'] 'Monad2' generalises 'Monad' and defines two functions:
--
-- * @'return' :: ('Monad2' m) => a -> m a a@
--
-- * @('>>=') :: ('Monad2' m) => m a b -> (b -> m b c) -> m a c@
--
-- The only really surprising feature is that in '>>=' the pairs of types chain, so we
-- combine a @m a b@ and a @m b c@ to get a @m a c@. The function '>>' is defined in
-- the obvious way by analogy to 'Monad'.
--
-- ['MonadTrans2'] 'MonadTrans2' generalises 'MonadTrans' and defines one function:
--
-- * @'lift' :: ('MonadTrans2' t,'Monad' m) => m a -> t m a a@
--
-- There is also one constraint:
--
-- * If @t :: 'MonadTrans2'@ and @m :: 'Monad'@ then @t m :: 'Monad2'@.
--
-- /Relation to monads/: note that if 'm' is a 'Monad2' and define @n a = m a a@
-- and carry across |return| and |>>=| as is, then 'n' is a 'Monad'.
module Control.Monad2 (
Monad2,
MonadTrans2,
(>>=), return, lift
) where
import Prelude hiding (return,(>>=))
-- | The generalised monad type; simply a monad @m a b@ with two arguments and the operations
-- @return@ and @>>=@ acting so @>>=@ sends a @m a b@ and a @b -> m b c@
-- to a @m b c@, so parameter types chain in the obvious way.
class Monad2 m a b where
-- | wraps a value in the monad
return :: a -> m a a
-- | monadic bind with obvious generalisation
(>>=) :: m a b -> (b -> m b c) -> m a c
-- | bind that throws away the output of the first argument
(>>) :: m a b -> m b c -> m a c
(>>) x y = x >>= const y
-- | The generalised monad transformer; takes a 'Monad' and produces a 'Monad2'.
class MonadTrans2 t where
-- | the transformer lift operation
lift :: (Monad m) => m a -> t m a a
-- | If @t@ is a 'MonadTrans2' and @m@ is a 'Monad' then @t m@ must be a 'Monad2'.
-- The instance implementation is deliberately left empty. This forces
-- implementers of 'MonadTrans2' to provide the monadic functions.
instance (Monad m,MonadTrans2 t) => Monad2 (t m) a b
| {
"content_hash": "9cb08fe217aae0fdc8f37b512b5593fc",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 95,
"avg_line_length": 42.5,
"alnum_prop": 0.5862068965517241,
"repo_name": "Julianporter/Haskell-MapReduce",
"id": "d2242d1dd3d32824d9a030b9e2b51df1a0b291e1",
"size": "2465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Control/Monad2.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "25565"
}
],
"symlink_target": ""
} |
package org.apache.shiro.cache;
import org.apache.shiro.util.SoftHashMap;
/**
* Simple memory-only based {@link CacheManager CacheManager} implementation usable in production
* environments. It will not cause memory leaks as it produces {@link Cache Cache}s backed by
* {@link SoftHashMap SoftHashMap}s which auto-size themselves based on the runtime environment's memory
* limitations and garbage collection behavior.
* <p/>
* While the {@code Cache} instances created are thread-safe, they do not offer any enterprise-level features such as
* cache coherency, optimistic locking, failover or other similar features. For more enterprise features, consider
* using a different {@code CacheManager} implementation backed by an enterprise-grade caching product (Hazelcast,
* EhCache, TerraCotta, Coherence, GigaSpaces, etc, etc).
*
* @since 1.0
*/
public class MemoryConstrainedCacheManager extends AbstractCacheManager {
/**
* Returns a new {@link MapCache MapCache} instance backed by a {@link SoftHashMap}.
*
* @param name the name of the cache
* @return a new {@link MapCache MapCache} instance backed by a {@link SoftHashMap}.
*/
@Override
protected Cache createCache(String name) {
return new MapCache<Object, Object>(name, new SoftHashMap<Object, Object>());
}
}
| {
"content_hash": "d64956149cacfe0a230f0b18cac01c65",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 117,
"avg_line_length": 43.064516129032256,
"alnum_prop": 0.7393258426966293,
"repo_name": "xuegongzi/rabbitframework",
"id": "9b331e42dafb405f0f380b25524574e647c59e24",
"size": "2144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rabbitframework-security-pom/rabbitframework-security/src/main/java/org/apache/shiro/cache/MemoryConstrainedCacheManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "212"
},
{
"name": "FreeMarker",
"bytes": "2474"
},
{
"name": "Java",
"bytes": "3279211"
},
{
"name": "Shell",
"bytes": "376"
}
],
"symlink_target": ""
} |
<?php
use app\core\helpers\Html;
use app\core\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\modules\wechat\models\Tag */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="tag-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<?= Html::submitButton('保 存', ['class' => 'btn btn-primary btn-block']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
| {
"content_hash": "9f0e95f3fbb9b6c7213742997840082b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 87,
"avg_line_length": 23.56,
"alnum_prop": 0.5382003395585738,
"repo_name": "cboy868/lion",
"id": "70616eb68bcf7a738b88a531afda725f97e525f7",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/wechat/views/admin/user/_tagform.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "20283"
},
{
"name": "ApacheConf",
"bytes": "514"
},
{
"name": "Batchfile",
"bytes": "515"
},
{
"name": "CSS",
"bytes": "1596076"
},
{
"name": "HTML",
"bytes": "388819"
},
{
"name": "JavaScript",
"bytes": "8084067"
},
{
"name": "PHP",
"bytes": "10347057"
}
],
"symlink_target": ""
} |
package cf.rachlinski.cryspscript.runtime.exec;
/**
* Executable commands implement this interface
*/
public interface Executable
{
/**
* Run the command
*/
void run();
}
| {
"content_hash": "7c4dd660693f9035bfe0edc5b387c7dd",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 47,
"avg_line_length": 15,
"alnum_prop": 0.7,
"repo_name": "chrisco210/CryspScript",
"id": "0d717b39d44705e2dd314a1ba8c6df6b3a8911e5",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cf/rachlinski/cryspscript/runtime/exec/Executable.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1341"
},
{
"name": "Java",
"bytes": "67504"
},
{
"name": "Makefile",
"bytes": "705"
}
],
"symlink_target": ""
} |
package pt.rupeal.invoicexpress.charts;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import pt.rupeal.invoicexpress.MainActivity;
import pt.rupeal.invoicexpress.R;
import pt.rupeal.invoicexpress.model.QuarterChartModel;
import pt.rupeal.invoicexpress.server.InvoiceXpress;
import pt.rupeal.invoicexpress.server.InvoiceXpressParser;
import pt.rupeal.invoicexpress.utils.InvoiceXpressException;
import pt.rupeal.invoicexpress.utils.ScreenLayoutUtil;
import pt.rupeal.invoicexpress.utils.StringUtil;
import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
public class QuarterlyChart {
public View getView(Context context, View quarteryBoardView, List<QuarterChartModel> quartersChartData) {
if(QuarterChartModel.isNoChart(quartersChartData)) {
setGeneratedDataQuaterlyChart(quartersChartData);
}
MainActivity activity = (MainActivity) context;
int heightScreen = InvoiceXpress.getInstance().getScreenHeight(activity);
int widthScreen = InvoiceXpress.getInstance().getScreenWidth(activity);
// get table layout margins
TableLayout tableLayout = (TableLayout) quarteryBoardView.findViewById(R.id.dashboard_quarterly_table_layout);
int margin = ((ViewGroup.MarginLayoutParams) tableLayout.getLayoutParams()).leftMargin;
margin += ((ViewGroup.MarginLayoutParams) tableLayout.getLayoutParams()).rightMargin;
margin += ScreenLayoutUtil.convertDpToPixels(context, 10);
int tableLayoutWidth = widthScreen - margin;
float columnWidth = (float) (tableLayoutWidth * 0.28);
// Title
String title = ((TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_title)).getText().toString();
((TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_title)).setText(title
+ " "
+ InvoiceXpress.getInstance().getActiveAccountDetails().getCurrencySymbol());
// margins row
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_0)
.getLayoutParams()).bottomMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 14));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_1)
.getLayoutParams()).topMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_1)
.getLayoutParams()).bottomMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_2)
.getLayoutParams()).topMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_2)
.getLayoutParams()).bottomMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_3)
.getLayoutParams()).topMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_3)
.getLayoutParams()).bottomMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_4)
.getLayoutParams()).topMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
((ViewGroup.MarginLayoutParams) quarteryBoardView.findViewById(R.id.dashboard_quarterly_row_4)
.getLayoutParams()).bottomMargin = ScreenLayoutUtil.isLowerThanHdpi(context) ? 2 :
Math.round(ScreenLayoutUtil.convertDpToPixels(context, 6));
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_first_invoicing),
quartersChartData.get(0).getInvoicing(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_first_vat),
quartersChartData.get(0).getTaxes(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_first_yoy),
quartersChartData.get(0).getYtd(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_second_invoicing),
quartersChartData.get(1).getInvoicing(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_second_vat),
quartersChartData.get(1).getTaxes(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_second_yoy),
quartersChartData.get(1).getYtd(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_third_invoicing),
quartersChartData.get(2).getInvoicing(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_third_vat),
quartersChartData.get(2).getTaxes(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_third_yoy),
quartersChartData.get(2).getYtd(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_forth_invoicing),
quartersChartData.get(3).getInvoicing(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_forth_vat),
quartersChartData.get(3).getTaxes(), columnWidth);
setTextView(context, (TextView) quarteryBoardView.findViewById(R.id.dashboard_quarterly_forth_yoy),
quartersChartData.get(3).getYtd(), columnWidth);
((LinearLayout) quarteryBoardView.findViewById(R.id.dashboard_quarterly_legend_title_layout)).getLayoutParams().height = heightScreen / 16;
return quarteryBoardView;
}
private void setTextView(Context context, TextView textView, String value, float columnWidth) {
Paint paint = new Paint();
float textSize = textView.getTextSize();
paint.setTextSize(textSize);
float textWidth = paint.measureText(value);
while(columnWidth < textWidth) {
paint.setTextSize(textSize--);
textWidth = paint.measureText(value);
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX , textSize);
textView.setText(value);
}
/**
* Example: https://screen-name.invoicexpress.net/api/charts/quarterly-results.xml
* @return
*/
public static String buildRequestHttpGet() {
StringBuffer request = new StringBuffer(InvoiceXpress.getInstance().getActiveAccount().getUrl());
request.append("/api/charts/quarterly-results.xml");
request.append("?api_key=" + InvoiceXpress.getInstance().getActiveAccount().getApiKey());
if(InvoiceXpress.DEBUG) {
Log.d(QuarterlyChart.class.getCanonicalName(), request.toString());
}
return request.toString();
}
public static List<QuarterChartModel> getChart(Context context, String xml) throws InvoiceXpressException {
List<QuarterChartModel> quarters = new ArrayList<QuarterChartModel>();
InvoiceXpressParser parser = new InvoiceXpressParser(context);
Document documentDomElement = parser.getDomElement(xml);
NodeList nodeList = documentDomElement.getElementsByTagName("quarter-01");
Element elem = (Element) nodeList.item(0);
QuarterChartModel quarter = new QuarterChartModel();
quarter.setInvoicing(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "invoicing")));
quarter.setTaxes(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "taxes")));
quarter.setYtd(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "ytd")));
quarter.setSample(false);
quarters.add(quarter);
nodeList = documentDomElement.getElementsByTagName("quarter-02");
elem = (Element) nodeList.item(0);
quarter = new QuarterChartModel();
quarter.setInvoicing(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "invoicing")));
quarter.setTaxes(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "taxes")));
quarter.setYtd(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "ytd")));
quarter.setSample(false);
quarters.add(quarter);
nodeList = documentDomElement.getElementsByTagName("quarter-03");
elem = (Element) nodeList.item(0);
quarter = new QuarterChartModel();
quarter.setInvoicing(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "invoicing")));
quarter.setTaxes(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "taxes")));
quarter.setYtd(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "ytd")));
quarter.setSample(false);
quarters.add(quarter);
nodeList = documentDomElement.getElementsByTagName("quarter-04");
elem = (Element) nodeList.item(0);
quarter = new QuarterChartModel();
quarter.setInvoicing(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "invoicing")));
quarter.setTaxes(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "taxes")));
quarter.setYtd(StringUtil.convertToQuarterlyValue(parser.getValue(elem, "ytd")));
quarter.setSample(false);
quarters.add(quarter);
return quarters;
}
private static void setGeneratedDataQuaterlyChart(List<QuarterChartModel> quarters) {
String[][] values = new String[][] {
{"1200.10", "320", "100"},
{"0", "60000.5", "5503.45"},
{"11213.21", "213.22", "-972"},
{"13.33", "1254211.99", "600"}
};
quarters.clear();
for (int index = 0; index < values.length; index++) {
QuarterChartModel quarter = new QuarterChartModel();
quarter.setInvoicing(StringUtil.convertToQuarterlyValue(values[index][0]));
quarter.setTaxes(StringUtil.convertToQuarterlyValue(values[index][1]));
quarter.setYtd(StringUtil.convertToQuarterlyValue(values[index][2]));
quarter.setSample(true);
quarters.add(quarter);
}
}
}
| {
"content_hash": "fd7a60ced2924106c0e7624e1c29db89",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 141,
"avg_line_length": 47.39366515837104,
"alnum_prop": 0.7721978231812107,
"repo_name": "weareswat/invoicexpress-android",
"id": "2af17f9564be01188dfc5c9932f7c5f56c6353e9",
"size": "10474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "invoicexpress-android/src/pt/rupeal/invoicexpress/charts/QuarterlyChart.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "Java",
"bytes": "400582"
},
{
"name": "JavaScript",
"bytes": "373480"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.