answer stringlengths 15 1.25M |
|---|
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Disable <API key> because M.str is expected here:
/* eslint-disable <API key> */
define(['jquery', 'core/ajax', 'core/localstorage'], function($, ajax, storage) {
return /** @alias module:core/str */ {
// Public variables and functions.
/**
* Return a promise object that will be resolved into a string eventually (maybe immediately).
*
* @method get_string
* @param {string} key The language string key
* @param {string} component The language string component
* @param {string} param The param for variable expansion in the string.
* @param {string} lang The users language - if not passed it is deduced.
* @return {Promise}
*/
// <API key> camelcase
get_string: function(key, component, param, lang) {
var request = this.get_strings([{
key: key,
component: component,
param: param,
lang: lang
}]);
return request.then(function(results) {
return results[0];
});
},
/**
* Make a batch request to load a set of strings
*
* @method get_strings
* @param {Object[]} requests Array of { key: key, component: component, param: param, lang: lang };
* See get_string for more info on these args.
* @return {Promise}
*/
// <API key> camelcase
get_strings: function(requests) {
var deferred = $.Deferred();
var results = [];
var i = 0;
var missing = false;
var request;
// Try from local storage. If it's there - put it in M.str and resolve it.
for (i = 0; i < requests.length; i++) {
request = requests[i];
if (typeof request.lang === "undefined") {
request.lang = $('html').attr('lang').replace('-', '_');
}
if (typeof M.str[request.component] === "undefined" ||
typeof M.str[request.component][request.key] === "undefined") {
// Try and revive it from local storage.
var cached = storage.get('core_str/' + request.key + '/' + request.component + '/' + request.lang);
if (cached) {
if (typeof M.str[request.component] === "undefined") {
M.str[request.component] = [];
}
M.str[request.component][request.key] = cached;
} else {
// It's really not here.
missing = true;
}
}
}
if (!missing) {
// We have all the strings already.
for (i = 0; i < requests.length; i++) {
request = requests[i];
results[i] = M.util.get_string(request.key, request.component, request.param);
}
deferred.resolve(results);
} else {
// Something is missing, we might as well load them all.
var ajaxrequests = [];
for (i = 0; i < requests.length; i++) {
request = requests[i];
ajaxrequests.push({
methodname: 'core_get_string',
args: {
stringid: request.key,
component: request.component,
lang: request.lang,
stringparams: []
}
});
}
var deferreds = ajax.call(ajaxrequests, true, false);
$.when.apply(null, deferreds).done(
function() {
// Turn the list of arguments (unknown length) into a real array.
var i = 0;
for (i = 0; i < arguments.length; i++) {
request = requests[i];
// Cache all the string templates.
if (typeof M.str[request.component] === "undefined") {
M.str[request.component] = [];
}
M.str[request.component][request.key] = arguments[i];
storage.set('core_str/' + request.key + '/' + request.component + '/' + request.lang, arguments[i]);
// And set the results.
results[i] = M.util.get_string(request.key, request.component, request.param).trim();
}
deferred.resolve(results);
}
).fail(
function(ex) {
deferred.reject(ex);
}
);
}
return deferred.promise();
}
};
}); |
# - Find the MKL libraries (no includes)
# This module defines
# MKL_LIBRARIES, the libraries needed to use Intel's implementation of BLAS & LAPACK.
# MKL_FOUND, If false, do not try to use MKL.
## the link below explains why we're linking only with mkl_rt
set(MKL_NAMES ${MKL_NAMES} mkl_rt)
#set(MKL_NAMES ${MKL_NAMES} mkl_lapack)
#set(MKL_NAMES ${MKL_NAMES} mkl_intel_thread)
#set(MKL_NAMES ${MKL_NAMES} mkl_core)
#set(MKL_NAMES ${MKL_NAMES} guide)
#set(MKL_NAMES ${MKL_NAMES} mkl)
#set(MKL_NAMES ${MKL_NAMES} iomp5)
#set(MKL_NAMES ${MKL_NAMES} pthread)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
#set(MKL_NAMES ${MKL_NAMES} mkl_intel_lp64)
set(MKL_ARCH intel64)
else()
#set(MKL_NAMES ${MKL_NAMES} mkl_intel)
set(MKL_ARCH ia32)
endif()
set(MKL_ROOT $ENV{MKLROOT} CACHE TYPE STRING)
if(NOT MKL_ROOT)
set(MKL_ROOT "/opt/intel/mkl")
endif()
foreach (MKL_NAME ${MKL_NAMES})
find_library(${MKL_NAME}_LIBRARY
NAMES ${MKL_NAME}
PATHS
${<API key>}
${MKL_ROOT}/lib/${MKL_ARCH}
/usr/lib64
/usr/lib
/usr/local/lib64
/usr/local/lib
/opt/intel/composerxe/lib/intel64
/opt/intel/composerxe/lib/ia32
/opt/intel/composerxe/lib/mkl/lib/intel64
/opt/intel/composerxe/lib/mkl/lib/ia32
/usr/local/intel/composerxe/lib/intel64
/usr/local/intel/composerxe/lib/ia32
/usr/local/intel/composerxe/lib/mkl/lib/intel64
/usr/local/intel/composerxe/lib/mkl/lib/ia32
/opt/intel/lib
/opt/intel/lib/intel64
/opt/intel/lib/em64t
/opt/intel/lib/lib64
/opt/intel/lib/ia32
/opt/intel/mkl/lib
/opt/intel/mkl/lib/intel64
/opt/intel/mkl/lib/em64t
/opt/intel/mkl/lib/lib64
/opt/intel/mkl/lib/ia32
/opt/intel/mkl/*/lib
/opt/intel/mkl/*/lib/intel64
/opt/intel/mkl/*/lib/em64t
/opt/intel/mkl/*/lib/lib64
/opt/intel/mkl/*/lib/32
/opt/intel/*/mkl/lib
/opt/intel/*/mkl/lib/intel64
/opt/intel/*/mkl/lib/em64t
/opt/intel/*/mkl/lib/lib64
/opt/intel/*/mkl/lib/ia32
/opt/mkl/lib
/opt/mkl/lib/intel64
/opt/mkl/lib/em64t
/opt/mkl/lib/lib64
/opt/mkl/lib/ia32
/opt/mkl/*/lib
/opt/mkl/*/lib/intel64
/opt/mkl/*/lib/em64t
/opt/mkl/*/lib/lib64
/opt/mkl/*/lib/32
/usr/local/intel/lib
/usr/local/intel/lib/intel64
/usr/local/intel/lib/em64t
/usr/local/intel/lib/lib64
/usr/local/intel/lib/ia32
/usr/local/intel/mkl/lib
/usr/local/intel/mkl/lib/intel64
/usr/local/intel/mkl/lib/em64t
/usr/local/intel/mkl/lib/lib64
/usr/local/intel/mkl/lib/ia32
/usr/local/intel/mkl/*/lib
/usr/local/intel/mkl/*/lib/intel64
/usr/local/intel/mkl/*/lib/em64t
/usr/local/intel/mkl/*/lib/lib64
/usr/local/intel/mkl/*/lib/32
/usr/local/intel/*/mkl/lib
/usr/local/intel/*/mkl/lib/intel64
/usr/local/intel/*/mkl/lib/em64t
/usr/local/intel/*/mkl/lib/lib64
/usr/local/intel/*/mkl/lib/ia32
/usr/local/mkl/lib
/usr/local/mkl/lib/intel64
/usr/local/mkl/lib/em64t
/usr/local/mkl/lib/lib64
/usr/local/mkl/lib/ia32
/usr/local/mkl/*/lib
/usr/local/mkl/*/lib/intel64
/usr/local/mkl/*/lib/em64t
/usr/local/mkl/*/lib/lib64
/usr/local/mkl/*/lib/32
)
set(TMP_LIBRARY ${${MKL_NAME}_LIBRARY})
if(TMP_LIBRARY)
set(MKL_LIBRARIES ${MKL_LIBRARIES} ${TMP_LIBRARY})
endif()
endforeach()
if(MKL_LIBRARIES)
set(MKL_FOUND "YES")
else()
set(MKL_FOUND "NO")
endif()
if(MKL_FOUND)
if(NOT MKL_FIND_QUIETLY)
message(STATUS "Found MKL libraries: ${MKL_LIBRARIES}")
endif()
else()
if(MKL_FIND_REQUIRED)
message(FATAL_ERROR "Could not find MKL libraries")
endif()
endif()
# mark_as_advanced(MKL_LIBRARY) |
#include <pcp/pmapi.h>
#include <pcp/impl.h>
#include <pcp/pmda.h>
#include "includes.h"
#include "ctdb_private.h"
#include "ctdb_protocol.h"
#include "domain.h"
/*
* CTDB PMDA
*
* This PMDA connects to the locally running ctdbd daemon and pulls
* statistics for export via PCP. The ctdbd Unix domain socket path can be
* specified with the CTDB_SOCKET environment variable, otherwise the default
* path is used.
*/
/*
* All metrics supported in this PMDA - one table entry for each.
* The 4th field specifies the serial number of the instance domain
* for the metric, and must be either PM_INDOM_NULL (denoting a
* metric that only ever has a single value), or the serial number
* of one of the instance domains declared in the instance domain table
* (i.e. in indomtab, above).
*/
static pmdaMetric metrictab[] = {
/* num_clients */
{ NULL, { PMDA_PMID(0,0), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* frozen */
{ NULL, { PMDA_PMID(0,1), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* recovering */
{ NULL, { PMDA_PMID(0,2), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* client_packets_sent */
{ NULL, { PMDA_PMID(0,3), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* client_packets_recv */
{ NULL, { PMDA_PMID(0,4), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* node_packets_sent */
{ NULL, { PMDA_PMID(0,5), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* node_packets_recv */
{ NULL, { PMDA_PMID(0,6), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* <API key> */
{ NULL, { PMDA_PMID(0,7), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* <API key> */
{ NULL, { PMDA_PMID(0,8), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_call */
{ NULL, { PMDA_PMID(1,0), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* reply_call */
{ NULL, { PMDA_PMID(1,1), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_dmaster */
{ NULL, { PMDA_PMID(1,2), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* reply_dmaster */
{ NULL, { PMDA_PMID(1,3), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* reply_error */
{ NULL, { PMDA_PMID(1,4), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_message */
{ NULL, { PMDA_PMID(1,5), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_control */
{ NULL, { PMDA_PMID(1,6), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* reply_control */
{ NULL, { PMDA_PMID(1,7), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_call */
{ NULL, { PMDA_PMID(2,0), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_message */
{ NULL, { PMDA_PMID(2,1), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* req_control */
{ NULL, { PMDA_PMID(2,2), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* call */
{ NULL, { PMDA_PMID(3,0), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,0) }, },
/* control */
{ NULL, { PMDA_PMID(3,1), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,0) }, },
/* traverse */
{ NULL, { PMDA_PMID(3,2), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,0) }, },
/* total_calls */
{ NULL, { PMDA_PMID(0,9), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* pending_calls */
{ NULL, { PMDA_PMID(0,10), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* locks.num_calls */
{ NULL, { PMDA_PMID(0,11), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* locks.num_pending */
{ NULL, { PMDA_PMID(0,12), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* childwrite_calls */
{ NULL, { PMDA_PMID(0,13), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_COUNTER,
PMDA_PMUNITS(0,0,1,0,0,PM_COUNT_ONE) }, },
/* <API key> */
{ NULL, { PMDA_PMID(0,14), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* memory_used */
{ NULL, { PMDA_PMID(0,15), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(1,0,0,PM_SPACE_BYTE,0,0) }, },
/* max_hop_count */
{ NULL, { PMDA_PMID(0,16), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
/* reclock.ctdbd.max */
{ NULL, { PMDA_PMID(0,17), PM_TYPE_DOUBLE, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,1,0,0,PM_TIME_SEC,0) }, },
/* reclock.recd.max */
{ NULL, { PMDA_PMID(0,18), PM_TYPE_DOUBLE, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,1,0,0,PM_TIME_SEC,0) }, },
/* call_latency.max */
{ NULL, { PMDA_PMID(0,19), PM_TYPE_DOUBLE, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,1,0,0,PM_TIME_SEC,0) }, },
/* locks.latency.max */
{ NULL, { PMDA_PMID(0,20), PM_TYPE_DOUBLE, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,1,0,0,PM_TIME_SEC,0) }, },
/* childwrite_latency.max */
{ NULL, { PMDA_PMID(0,21), PM_TYPE_DOUBLE, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,1,0,0,PM_TIME_SEC,0) }, },
/* num_recoveries */
{ NULL, { PMDA_PMID(0,22), PM_TYPE_U32, PM_INDOM_NULL, PM_SEM_INSTANT,
PMDA_PMUNITS(0,0,0,0,0,0) }, },
};
static struct event_context *ev;
static struct ctdb_context *ctdb;
static struct ctdb_statistics *stats;
static void
pmda_ctdb_q_read_cb(uint8_t *data, size_t cnt, void *args)
{
if (cnt == 0) {
fprintf(stderr, "ctdbd unreachable\n");
/* cleanup on request timeout */
return;
}
ctdb_client_read_cb(data, cnt, args);
}
static int
<API key>(void)
{
const char *socket_name;
int ret;
struct sockaddr_un addr;
ev = event_context_init(NULL);
if (ev == NULL) {
fprintf(stderr, "Failed to init event ctx\n");
return -1;
}
ctdb = ctdb_init(ev);
if (ctdb == NULL) {
fprintf(stderr, "Failed to init ctdb\n");
goto err_ev;
}
socket_name = getenv("CTDB_SOCKET");
if (socket_name == NULL) {
socket_name = CTDB_SOCKET;
}
ret = ctdb_set_socketname(ctdb, socket_name);
if (ret == -1) {
fprintf(stderr, "ctdb_set_socketname failed - %s\n",
ctdb_errstr(ctdb));
goto err_ctdb;
}
/*
* ctdb_socket_connect() sets a default queue callback handler that
* calls exit() if ctdbd is unavailable on recv, use our own wrapper to
* work around this
*/
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, ctdb->daemon.name, sizeof(addr.sun_path));
ctdb->daemon.sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (ctdb->daemon.sd == -1) {
fprintf(stderr, "Failed to open client socket\n");
goto err_ctdb;
}
set_nonblocking(ctdb->daemon.sd);
set_close_on_exec(ctdb->daemon.sd);
if (connect(ctdb->daemon.sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
fprintf(stderr, "Failed to connect to ctdb daemon via %s\n",
ctdb->daemon.name);
goto err_sd;
}
ctdb->daemon.queue = ctdb_queue_setup(ctdb, ctdb, ctdb->daemon.sd,
CTDB_DS_ALIGNMENT,
pmda_ctdb_q_read_cb, ctdb,
"to-ctdbd");
if (ctdb->daemon.queue == NULL) {
fprintf(stderr, "Failed to setup queue\n");
goto err_sd;
}
ctdb->pnn = ctdb_ctrl_getpnn(ctdb, timeval_current_ofs(3, 0),
CTDB_CURRENT_NODE);
if (ctdb->pnn == (uint32_t)-1) {
fprintf(stderr, "Failed to get ctdb pnn\n");
goto err_sd;
}
return 0;
err_sd:
close(ctdb->daemon.sd);
err_ctdb:
talloc_free(ctdb);
err_ev:
talloc_free(ev);
ctdb = NULL;
return -1;
}
static void
<API key>(void)
{
if (ctdb->methods) {
ctdb->methods->shutdown(ctdb);
}
if (ctdb->daemon.sd != -1) {
close(ctdb->daemon.sd);
}
talloc_free(ctdb);
talloc_free(ev);
ctdb = NULL;
}
static int
fill_base(unsigned int item, pmAtomValue *atom)
{
switch (item) {
case 0:
atom->ul = stats->num_clients;
break;
case 1:
atom->ul = stats->frozen;
break;
case 2:
atom->ul = stats->recovering;
break;
case 3:
atom->ul = stats->client_packets_sent;
break;
case 4:
atom->ul = stats->client_packets_recv;
break;
case 5:
atom->ul = stats->node_packets_sent;
break;
case 6:
atom->ul = stats->node_packets_recv;
break;
case 7:
atom->ul = stats-><API key>;
break;
case 8:
atom->ul = stats-><API key>;
break;
case 9:
atom->ul = stats->total_calls;
break;
case 10:
atom->ul = stats->pending_calls;
break;
case 11:
atom->ul = stats->locks.num_calls;
break;
case 12:
atom->ul = stats->locks.num_pending;
break;
case 13:
atom->ul = stats->childwrite_calls;
break;
case 14:
atom->ul = stats-><API key>;
break;
case 15:
atom->ul = stats->memory_used;
break;
case 16:
atom->ul = stats->max_hop_count;
break;
case 17:
atom->d = stats->reclock.ctdbd.max;
break;
case 18:
atom->d = stats->reclock.recd.max;
break;
case 19:
atom->d = stats->call_latency.max;
break;
case 20:
atom->d = stats->locks.latency.max;
break;
case 21:
atom->d = stats->childwrite_latency.max;
break;
case 22:
atom->d = stats->num_recoveries;
break;
default:
return PM_ERR_PMID;
}
return 0;
}
static int
fill_node(unsigned int item, pmAtomValue *atom)
{
switch (item) {
case 0:
atom->ul = stats->node.req_call;
break;
case 1:
atom->ul = stats->node.reply_call;
break;
case 2:
atom->ul = stats->node.req_dmaster;
break;
case 3:
atom->ul = stats->node.reply_dmaster;
break;
case 4:
atom->ul = stats->node.reply_error;
break;
case 5:
atom->ul = stats->node.req_message;
break;
case 6:
atom->ul = stats->node.req_control;
break;
case 7:
atom->ul = stats->node.reply_control;
break;
default:
return PM_ERR_PMID;
}
return 0;
}
static int
fill_client(unsigned int item, pmAtomValue *atom)
{
switch (item) {
case 0:
atom->ul = stats->client.req_call;
break;
case 1:
atom->ul = stats->client.req_message;
break;
case 2:
atom->ul = stats->client.req_control;
break;
default:
return PM_ERR_PMID;
}
return 0;
}
static int
fill_timeout(unsigned int item, pmAtomValue *atom)
{
switch (item) {
case 0:
atom->ul = stats->timeouts.call;
break;
case 1:
atom->ul = stats->timeouts.control;
break;
case 2:
atom->ul = stats->timeouts.traverse;
break;
default:
return PM_ERR_PMID;
}
return 0;
}
/*
* callback provided to pmdaFetch
*/
static int
pmda_ctdb_fetch_cb(pmdaMetric *mdesc, unsigned int inst, pmAtomValue *atom)
{
int ret;
__pmID_int *id = (__pmID_int *)&(mdesc->m_desc.pmid);
if (inst != PM_IN_NULL) {
return PM_ERR_INST;
}
if (stats == NULL) {
fprintf(stderr, "stats not available\n");
ret = PM_ERR_VALUE;
goto err_out;
}
switch (id->cluster) {
case 0:
ret = fill_base(id->item, atom);
if (ret) {
goto err_out;
}
break;
case 1:
ret = fill_node(id->item, atom);
if (ret) {
goto err_out;
}
break;
case 2:
ret = fill_client(id->item, atom);
if (ret) {
goto err_out;
}
break;
case 3:
ret = fill_timeout(id->item, atom);
if (ret) {
goto err_out;
}
break;
default:
return PM_ERR_PMID;
}
ret = 0;
err_out:
return ret;
}
/*
* This routine is called once for each pmFetch(3) operation, so is a
* good place to do once-per-fetch functions, such as value caching or
* instance domain evaluation.
*/
static int
pmda_ctdb_fetch(int numpmid, pmID pmidlist[], pmResult **resp, pmdaExt *pmda)
{
int ret;
TDB_DATA data;
int32_t res;
struct timeval ctdb_timeout;
if (ctdb == NULL) {
fprintf(stderr, "attempting reconnect to ctdbd\n");
ret = <API key>();
if (ret < 0) {
fprintf(stderr, "reconnect failed\n");
return PM_ERR_VALUE;
}
}
ctdb_timeout = timeval_current_ofs(1, 0);
ret = ctdb_control(ctdb, ctdb->pnn, 0,
<API key>, 0, tdb_null,
ctdb, &data, &res, &ctdb_timeout, NULL);
if (ret != 0 || res != 0) {
fprintf(stderr, "ctdb control for statistics failed, reconnecting\n");
<API key>();
ret = PM_ERR_VALUE;
goto err_out;
}
stats = (struct ctdb_statistics *)data.dptr;
if (data.dsize != sizeof(struct ctdb_statistics)) {
fprintf(stderr, "incorrect statistics size %zu - not %zu\n",
data.dsize, sizeof(struct ctdb_statistics));
ret = PM_ERR_VALUE;
goto err_stats;
}
ret = pmdaFetch(numpmid, pmidlist, resp, pmda);
err_stats:
talloc_free(stats);
err_out:
return ret;
}
void pmda_ctdb_init(pmdaInterface *dp);
/*
* Initialise the agent
*/
void
pmda_ctdb_init(pmdaInterface *dp)
{
if (dp->status != 0) {
return;
}
dp->version.two.fetch = pmda_ctdb_fetch;
<API key>(dp, pmda_ctdb_fetch_cb);
pmdaInit(dp, NULL, 0, metrictab,
(sizeof(metrictab) / sizeof(metrictab[0])));
}
static char *
helpfile(void)
{
static char buf[MAXPATHLEN];
if (!buf[0]) {
snprintf(buf, sizeof(buf), "%s/ctdb/help",
pmGetConfig("PCP_PMDAS_DIR"));
}
return buf;
}
static void
usage(void)
{
fprintf(stderr, "Usage: %s [options]\n\n", pmProgname);
fputs("Options:\n"
" -d domain use domain (numeric) for metrics domain of PMDA\n"
" -l logfile write log into logfile rather than using default log name\n"
"\nExactly one of the following options may appear:\n"
" -i port expect PMCD to connect on given inet port (number or name)\n"
" -p expect PMCD to supply stdin/stdout (pipe)\n"
" -u socket expect PMCD to connect on given unix domain socket\n",
stderr);
exit(1);
}
/*
* Set up the agent if running as a daemon.
*/
int
main(int argc, char **argv)
{
int err = 0;
char log_file[] = "pmda_ctdb.log";
pmdaInterface dispatch;
__pmSetProgname(argv[0]);
pmdaDaemon(&dispatch, PMDA_INTERFACE_2, pmProgname, CTDB,
log_file, helpfile());
if (pmdaGetOpt(argc, argv, "d:i:l:pu:?", &dispatch, &err) != EOF) {
err++;
}
if (err) {
usage();
}
pmdaOpenLog(&dispatch);
pmda_ctdb_init(&dispatch);
pmdaConnect(&dispatch);
pmdaMain(&dispatch);
exit(0);
} |
// modification, are permitted provided that the following conditions are
// met:
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER 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.
#ifndef <API key>
#define <API key>
#include <stdint.h>
#include <sys/types.h>
#include <sys/ucontext.h>
#include <unistd.h>
#include <list>
#include <utility>
#include "client/linux/minidump_writer/linux_dumper.h"
#include "google_breakpad/common/minidump_format.h"
namespace google_breakpad {
class ExceptionHandler;
#if defined(__aarch64__)
typedef struct fpsimd_context fpstate_t;
#elif !defined(__ARM_EABI__) && !defined(__mips__)
typedef struct _libc_fpstate fpstate_t;
#endif
// These entries store a list of memory regions that the client wants included
// in the minidump.
struct AppMemory {
void* ptr;
size_t length;
bool operator==(const struct AppMemory& other) const {
return ptr == other.ptr;
}
bool operator==(const void* other) const {
return ptr == other;
}
};
typedef std::list<AppMemory> AppMemoryList;
// Writes a minidump to the filesystem. These functions do not malloc nor use
// libc functions which may. Thus, it can be used in contexts where the state
// of the heap may be corrupt.
// minidump_path: the path to the file to write to. This is opened O_EXCL and
// fails open fails.
// crashing_process: the pid of the crashing process. This must be trusted.
// blob: a blob of data from the crashing process. See exception_handler.h
// blob_size: the length of |blob|, in bytes
// Returns true iff successful.
bool WriteMinidump(const char* minidump_path, pid_t crashing_process,
const void* blob, size_t blob_size,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
// Same as above but takes an open file descriptor instead of a path.
bool WriteMinidump(int minidump_fd, pid_t crashing_process,
const void* blob, size_t blob_size,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
// Alternate form of WriteMinidump() that works with processes that
// are not expected to have crashed. If |<API key>| is
// meaningful, it will be the one from which a crash signature is
// extracted. It is not expected that this function will be called
// from a compromised context, but it is safe to do so.
bool WriteMinidump(const char* minidump_path, pid_t process,
pid_t <API key>);
// These overloads also allow passing a list of known mappings and
// a list of additional memory regions to be included in the minidump.
bool WriteMinidump(const char* minidump_path, pid_t crashing_process,
const void* blob, size_t blob_size,
const MappingList& mappings,
const AppMemoryList& appdata,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
bool WriteMinidump(int minidump_fd, pid_t crashing_process,
const void* blob, size_t blob_size,
const MappingList& mappings,
const AppMemoryList& appdata,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
// These overloads also allow passing a file size limit for the minidump.
bool WriteMinidump(const char* minidump_path, off_t minidump_size_limit,
pid_t crashing_process,
const void* blob, size_t blob_size,
const MappingList& mappings,
const AppMemoryList& appdata,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
bool WriteMinidump(int minidump_fd, off_t minidump_size_limit,
pid_t crashing_process,
const void* blob, size_t blob_size,
const MappingList& mappings,
const AppMemoryList& appdata,
bool <API key> = false,
uintptr_t <API key> = 0,
bool sanitize_stacks = false);
bool WriteMinidump(const char* filename,
const MappingList& mappings,
const AppMemoryList& appdata,
LinuxDumper* dumper);
} // namespace google_breakpad
#endif // <API key> |
#ifndef _WINBINDD_PROTO_H_
#define _WINBINDD_PROTO_H_
/* The following definitions come from winbindd/winbindd.c */
struct messaging_context *<API key>(void);
void request_error(struct winbindd_cli_state *state);
void request_ok(struct winbindd_cli_state *state);
bool <API key>(bool parent);
bool <API key>(const char *lfile);
bool <API key>(void);
bool winbindd_use_cache(void);
void <API key>(void);
const char *<API key>(void);
char *<API key>(void);
int main(int argc, char **argv, char **envp);
/* The following definitions come from winbindd/winbindd_ads.c */
/* The following definitions come from winbindd/winbindd_rpc.c */
NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
uint32_t num_sids,
const struct dom_sid *sids,
char ***domains,
char ***names,
enum lsa_SidType **types);
NTSTATUS rpc_lookup_sids(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
struct lsa_SidArray *sids,
struct lsa_RefDomainList **pdomains,
struct lsa_TransNameArray **pnames);
/* The following definitions come from winbindd/winbindd_cache.c */
struct cache_entry *centry_start(struct winbindd_domain *domain, NTSTATUS status);
NTSTATUS <API key>(struct winbindd_domain *domain, const struct dom_sid *sid);
NTSTATUS wcache_get_creds(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *sid,
const uint8 **cached_nt_pass,
const uint8 **cached_salt);
NTSTATUS wcache_save_creds(struct winbindd_domain *domain,
const struct dom_sid *sid,
const uint8 nt_pass[NT_HASH_LEN]);
void <API key>(struct winbindd_domain *domain,
const struct dom_sid *user_sid);
bool <API key>(void);
bool <API key>(void);
bool init_wcache(void);
bool <API key>(void);
void <API key>(void);
NTSTATUS wcache_sid_to_name(struct winbindd_domain *domain,
const struct dom_sid *sid,
TALLOC_CTX *mem_ctx,
char **domain_name,
char **name,
enum lsa_SidType *type);
NTSTATUS <API key>(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *group_sid,
uint32_t *num_names,
struct dom_sid **sid_mem, char ***names,
uint32_t **name_types);
bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const struct dom_sid *sid,
char **domain_name, char **name,
enum lsa_SidType *type);
bool lookup_cached_name(const char *domain_name,
const char *name,
struct dom_sid *sid,
enum lsa_SidType *type);
void cache_name2sid(struct winbindd_domain *domain,
const char *domain_name, const char *name,
enum lsa_SidType type, const struct dom_sid *sid);
NTSTATUS wcache_name_to_sid(struct winbindd_domain *domain,
const char *domain_name,
const char *name,
struct dom_sid *sid,
enum lsa_SidType *type);
NTSTATUS wcache_query_user(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *user_sid,
struct wbint_userinfo *info);
NTSTATUS <API key>(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
uint32 num_sids, const struct dom_sid *sids,
uint32 *pnum_aliases, uint32 **paliases);
NTSTATUS <API key>(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *user_sid,
uint32_t *pnum_sids,
struct dom_sid **psids);
void wcache_flush_cache(void);
NTSTATUS <API key>(struct winbindd_domain *domain, int *count);
NTSTATUS <API key>(struct winbindd_domain *domain, const struct dom_sid *sid) ;
bool <API key>(void);
void <API key>(void);
bool <API key>(void);
int <API key>(void);
int <API key>(void);
bool <API key>(void);
bool <API key>( struct winbindd_tdc_domain **domains, size_t *num_domains );
bool <API key>( struct winbindd_domain *domain );
struct winbindd_tdc_domain * <API key>( TALLOC_CTX *ctx, const char *name );
struct winbindd_tdc_domain* <API key>(TALLOC_CTX *ctx, const struct dom_sid *sid);
void wcache_tdc_clear( void );
#ifdef HAVE_ADS
struct ads_struct;
NTSTATUS nss_get_info_cached( struct winbindd_domain *domain,
const struct dom_sid *user_sid,
TALLOC_CTX *ctx,
const char **homedir, const char **shell,
const char **gecos, gid_t *p_gid);
#endif
bool wcache_store_seqnum(const char *domain_name, uint32_t seqnum,
time_t last_seq_check);
bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
uint32_t opnum, const DATA_BLOB *req, DATA_BLOB *resp);
void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
const DATA_BLOB *req, const DATA_BLOB *resp);
/* The following definitions come from winbindd/<API key>.c */
void <API key>(struct winbindd_cli_state *state);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
/* The following definitions come from winbindd/winbindd_cm.c */
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void set_domain_offline(struct winbindd_domain *domain);
void <API key>(struct winbindd_domain *domain);
void <API key>(struct winbindd_cm_conn *conn);
void <API key>(void);
NTSTATUS init_dc_connection(struct winbindd_domain *domain);
NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
struct rpc_pipe_client **cli, struct policy_handle *sam_handle);
NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
struct rpc_pipe_client **cli, struct policy_handle *lsa_policy);
NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
struct rpc_pipe_client **cli);
NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
struct rpc_pipe_client **cli,
struct policy_handle *lsa_policy);
NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
struct rpc_pipe_client **cli);
bool <API key>(TALLOC_CTX *mem_ctx,
const char *domain_name,
char **p_dc_name, char **p_dc_ip);
/* The following definitions come from winbindd/winbindd_cred_cache.c */
bool ccache_entry_exists(const char *username);
bool <API key>(const char *username,
uid_t uid,
const char *ccname);
void <API key>(void);
void <API key>(void);
NTSTATUS add_ccache_to_list(const char *princ_name,
const char *ccname,
const char *service,
const char *username,
const char *password,
const char *realm,
uid_t uid,
time_t create_time,
time_t ticket_end,
time_t renew_until,
bool postponed_request);
NTSTATUS remove_ccache(const char *username);
struct <API key> *<API key>(const char *username);
NTSTATUS <API key>(const char *username,
uid_t uid,
const char *pass);
NTSTATUS <API key>(const char *username);
NTSTATUS <API key>(const char *username,
const char *pass);
/* The following definitions come from winbindd/winbindd_creds.c */
NTSTATUS winbindd_get_creds(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *sid,
struct netr_SamInfo3 **info3,
const uint8 *cached_nt_pass[NT_HASH_LEN],
const uint8 *cred_salt[NT_HASH_LEN]);
NTSTATUS <API key>(struct winbindd_domain *domain,
const char *user,
const char *pass,
struct netr_SamInfo3 *info3);
NTSTATUS <API key>(struct winbindd_domain *domain,
const char *user,
const char *pass,
struct netr_SamInfo3 *info3);
NTSTATUS <API key>(struct winbindd_domain *domain,
const char *user,
const char *pass);
/* The following definitions come from winbindd/winbindd_domain.c */
void setup_domain_child(struct winbindd_domain *domain);
/* The following definitions come from winbindd/winbindd_dual.c */
struct <API key> *dom_child_handle(struct winbindd_domain *domain);
struct winbindd_child *choose_domain_child(struct winbindd_domain *domain);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_child *child,
struct winbindd_request *request);
int <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct winbindd_response **presponse, int *err);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_domain *domain,
struct winbindd_request *request);
int <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct winbindd_response **presponse, int *err);
void setup_child(struct winbindd_domain *domain, struct winbindd_child *child,
const struct <API key> *table,
const char *logprefix,
const char *logname);
void winbind_child_died(pid_t pid);
void <API key>(struct winbindd_domain *domain);
void winbind_msg_debug(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void winbind_msg_offline(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void winbind_msg_online(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
void <API key>(struct messaging_context *msg_ctx,
void *private_data,
uint32_t msg_type,
struct server_id server_id,
DATA_BLOB *data);
NTSTATUS <API key>(const struct winbindd_child *myself,
const char *logfilename);
struct winbindd_domain *wb_child_domain(void);
/* The following definitions come from winbindd/winbindd_group.c */
void winbindd_getgrnam(struct winbindd_cli_state *state);
void winbindd_getgrgid(struct winbindd_cli_state *state);
void winbindd_setgrent(struct winbindd_cli_state *state);
void winbindd_endgrent(struct winbindd_cli_state *state);
void winbindd_getgrent(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void winbindd_getgroups(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
bool fill_grent(TALLOC_CTX *mem_ctx, struct winbindd_gr *gr,
const char *dom_name, const char *gr_name, gid_t unix_gid);
NTSTATUS <API key>(struct talloc_dict *members,
TALLOC_CTX *mem_ctx,
int *num_members, char **result);
/* The following definitions come from winbindd/winbindd_idmap.c */
void init_idmap_child(void);
struct winbindd_child *idmap_child(void);
struct idmap_domain *idmap_find_domain(const char *domname);
/* The following definitions come from winbindd/winbindd_locator.c */
void init_locator_child(void);
struct winbindd_child *locator_child(void);
/* The following definitions come from winbindd/winbindd_misc.c */
void <API key>(struct winbindd_cli_state *state);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void winbindd_dc_info(struct winbindd_cli_state *state);
void winbindd_ping(struct winbindd_cli_state *state);
void winbindd_info(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
/* The following definitions come from winbindd/winbindd_ndr.c */
struct ndr_print;
void <API key>(struct ndr_print *ndr,
const char *name,
const struct winbindd_child *r);
void <API key>(struct ndr_print *ndr,
const char *name,
const struct winbindd_cm_conn *r);
void <API key>(struct ndr_print *ndr,
const char *name,
const struct winbindd_methods *r);
void <API key>(struct ndr_print *ndr,
const char *name,
const struct winbindd_domain *r);
/* The following definitions come from winbindd/winbindd_pam.c */
bool check_request_flags(uint32_t flags);
uid_t <API key>(struct winbindd_request *request);
struct winbindd_domain *find_auth_domain(uint8_t flags,
const char *domain_name);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state) ;
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state) ;
enum winbindd_result <API key>(struct winbindd_domain *contact_domain,
struct winbindd_cli_state *state);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state) ;
enum winbindd_result <API key>(struct winbindd_domain *domainSt, struct winbindd_cli_state *state);
/* The following definitions come from winbindd/winbindd_util.c */
struct winbindd_domain *domain_list(void);
bool <API key>(const struct winbindd_domain *domain);
void <API key>(struct tevent_context *ev, struct tevent_timer *te,
struct timeval now, void *private_data);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state);
bool init_domain_list(void);
struct winbindd_domain *<API key>(const char *domain_name);
struct winbindd_domain *<API key>(const char *domain_name);
struct winbindd_domain *<API key>(const struct dom_sid *sid);
struct winbindd_domain *<API key>(const struct dom_sid *sid);
struct winbindd_domain *find_our_domain(void);
struct winbindd_domain *find_root_domain(void);
struct winbindd_domain *find_builtin_domain(void);
struct winbindd_domain *<API key>(const struct dom_sid *sid);
struct winbindd_domain *<API key>(const char *domain_name);
bool parse_domain_user(const char *domuser, fstring domain, fstring user);
bool <API key>(TALLOC_CTX *mem_ctx, const char *domuser,
char **domain, char **user);
bool <API key>(fstring username_inout, fstring domain, fstring user);
void <API key>(fstring name, const char *domain, const char *user, bool can_assume);
char *<API key>(TALLOC_CTX *ctx,
const char *domain,
const char *user,
bool can_assume);
struct winbindd_cli_state *<API key>(void);
void winbindd_add_client(struct winbindd_cli_state *cli);
void <API key>(struct winbindd_cli_state *cli);
int <API key>(void);
NTSTATUS <API key>(struct winbindd_domain *domain,
TALLOC_CTX *mem_ctx,
const struct dom_sid *user_sid,
uint32 *p_num_groups, struct dom_sid **user_sids);
NTSTATUS normalize_name_map(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
const char *name,
char **normalized);
NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
char *name,
char **normalized);
NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
const char *name, char **alias);
NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
const char *alias, char **name);
bool <API key>(struct winbindd_domain *domain);
bool <API key>(struct winbindd_child *child);
void <API key>(const struct winbindd_domain *domain);
void <API key>(const struct winbindd_domain *domain);
void <API key>(const struct winbindd_domain *domain);
void <API key>(const struct winbindd_domain *domain);
void set_auth_errors(struct winbindd_response *resp, NTSTATUS result);
bool is_domain_offline(const struct winbindd_domain *domain);
bool is_domain_online(const struct winbindd_domain *domain);
bool parse_sidlist(TALLOC_CTX *mem_ctx, const char *sidstr,
struct dom_sid **sids, uint32_t *num_sids);
/* The following definitions come from winbindd/winbindd_wins.c */
void winbindd_wins_byip(struct winbindd_cli_state *state);
void <API key>(struct winbindd_cli_state *state);
struct tevent_req *wb_ping_send(TALLOC_CTX *mem_ctx, struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS wb_ping_recv(struct tevent_req *req,
struct winbindd_response *resp);
enum winbindd_result winbindd_dual_ping(struct winbindd_domain *domain,
struct winbindd_cli_state *state);
struct <API key> *<API key>(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
struct winbindd_child *child);
enum winbindd_result <API key>(struct winbindd_domain *domain,
struct winbindd_cli_state *state);
struct tevent_req *wb_lookupsid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid);
NTSTATUS wb_lookupsid_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
enum lsa_SidType *type, const char **domain,
const char **name);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_lookupname_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const char *dom_name, const char *name,
uint32_t flags);
NTSTATUS wb_lookupname_recv(struct tevent_req *req, struct dom_sid *sid,
enum lsa_SidType *type);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_sid2uid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid);
NTSTATUS wb_sid2uid_recv(struct tevent_req *req, uid_t *uid);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_sid2gid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid);
NTSTATUS wb_sid2gid_recv(struct tevent_req *req, gid_t *gid);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_uid2sid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
uid_t uid);
NTSTATUS wb_uid2sid_recv(struct tevent_req *req, struct dom_sid *sid);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_gid2sid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
gid_t gid);
NTSTATUS wb_gid2sid_recv(struct tevent_req *req, struct dom_sid *sid);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_queryuser_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *user_sid);
NTSTATUS wb_queryuser_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct wbint_userinfo **pinfo);
struct tevent_req *wb_getpwsid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *user_sid,
struct winbindd_pw *pw);
NTSTATUS wb_getpwsid_recv(struct tevent_req *req);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_domain *domain,
int num_sids,
const struct dom_sid *sids);
NTSTATUS <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
uint32_t *num_aliases, uint32_t **aliases);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_domain *domain,
const struct dom_sid *sid);
NTSTATUS <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
int *num_sids, struct dom_sid **sids);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_gettoken_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid);
NTSTATUS wb_gettoken_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
int *num_sids, struct dom_sid **sids);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_seqnum_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_domain *domain);
NTSTATUS wb_seqnum_recv(struct tevent_req *req, uint32_t *seqnum);
struct tevent_req *wb_seqnums_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev);
NTSTATUS wb_seqnums_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
int *num_domains, struct winbindd_domain ***domains,
NTSTATUS **stati, uint32_t **seqnums);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid,
enum lsa_SidType type,
int max_depth);
NTSTATUS <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct talloc_dict **members);
struct tevent_req *wb_getgrsid_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *group_sid,
int max_nesting);
NTSTATUS wb_getgrsid_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
const char **domname, const char **name, gid_t *gid,
struct talloc_dict **members);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_domain *domain);
NTSTATUS <API key>(struct tevent_req *req, TALLOC_CTX *mem_ctx,
int *num_users,
struct wbint_userinfo **users);
struct tevent_req *wb_fill_pwent_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct wbint_userinfo *info,
struct winbindd_pw *pw);
NTSTATUS wb_fill_pwent_recv(struct tevent_req *req);
struct tevent_req *wb_next_pwent_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct getpwent_state *gstate,
struct winbindd_pw *pw);
NTSTATUS wb_next_pwent_recv(struct tevent_req *req);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *presp);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_dsgetdcname_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const char *domain_name,
const struct GUID *domain_guid,
const char *site_name,
uint32_t flags);
NTSTATUS wb_dsgetdcname_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct <API key> **pdcinfo);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_next_grent_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
int max_nesting,
struct getgrent_state *gstate,
struct winbindd_gr *gr);
NTSTATUS wb_next_grent_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct talloc_dict **members);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *presp);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *presp);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *presp);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(
TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(
TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *<API key>(
TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(
struct tevent_req *req,
struct winbindd_response *response);
struct tevent_req *wb_lookupsids_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct dom_sid *sids,
uint32_t num_sids);
NTSTATUS wb_lookupsids_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
struct lsa_RefDomainList **domains,
struct lsa_TransNameArray **names);
struct tevent_req *<API key>(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct winbindd_cli_state *cli,
struct winbindd_request *request);
NTSTATUS <API key>(struct tevent_req *req,
struct winbindd_response *response);
/* The following definitions come from winbindd/winbindd_samr.c */
NTSTATUS <API key>(TALLOC_CTX *mem_ctx,
struct winbindd_domain *domain,
struct rpc_pipe_client **samr_pipe,
struct policy_handle *samr_domain_hnd);
#endif /* _WINBINDD_PROTO_H_ */ |
#include <assert.h>
#include "webrtc/base/nattypes.h"
namespace rtc {
class SymmetricNAT : public NAT {
public:
bool IsSymmetric() override { return true; }
bool FiltersIP() override { return true; }
bool FiltersPort() override { return true; }
};
class OpenConeNAT : public NAT {
public:
bool IsSymmetric() override { return false; }
bool FiltersIP() override { return false; }
bool FiltersPort() override { return false; }
};
class <API key> : public NAT {
public:
bool IsSymmetric() override { return false; }
bool FiltersIP() override { return true; }
bool FiltersPort() override { return false; }
};
class PortRestrictedNAT : public NAT {
public:
bool IsSymmetric() override { return false; }
bool FiltersIP() override { return true; }
bool FiltersPort() override { return true; }
};
NAT* NAT::Create(NATType type) {
switch (type) {
case NAT_OPEN_CONE: return new OpenConeNAT();
case NAT_ADDR_RESTRICTED: return new <API key>();
case NAT_PORT_RESTRICTED: return new PortRestrictedNAT();
case NAT_SYMMETRIC: return new SymmetricNAT();
default: assert(0); return 0;
}
}
} // namespace rtc |
define('cdf/dashboard/Dashboard.notifications.ext', [], function() {
var <API key> = {
getPing: function() {
return "";
}
};
return <API key>;
}); |
(function(define) {
'use strict';
define(
[
'jquery',
'backbone',
'common/js/discussion/content',
'common/js/discussion/discussion',
'common/js/discussion/utils',
'common/js/discussion/models/<API key>',
'common/js/discussion/models/discussion_user',
'common/js/discussion/views/new_post_view',
'discussion/js/discussion_router',
'discussion/js/views/<API key>'
],
function($, Backbone, Content, Discussion, DiscussionUtil, <API key>, DiscussionUser,
NewPostView, DiscussionRouter, DiscussionBoardView) {
return function(options) {
var userInfo = options.userInfo,
sortPreference = options.sortPreference,
threads = options.threads,
threadPages = options.threadPages,
<API key> = options.<API key>,
contentInfo = options.contentInfo,
user = new DiscussionUser(userInfo),
discussion,
courseSettings,
newPostView,
discussionBoardView,
router,
routerEvents;
// TODO: eliminate usage of global variables when possible
if (options.roles === undefined) {
options.roles = {};
}
DiscussionUtil.loadRoles(options.roles);
window.$$course_id = options.courseId;
window.courseName = options.courseName;
DiscussionUtil.setUser(user);
window.user = user;
Content.loadContentInfos(contentInfo);
// Create a discussion model
discussion = new Discussion(threads, {pages: threadPages, sort: sortPreference,
<API key>: <API key>});
courseSettings = new <API key>(options.courseSettings);
// Create the discussion board view
discussionBoardView = new DiscussionBoardView({
el: $('.discussion-board'),
discussion: discussion,
courseSettings: courseSettings
});
discussionBoardView.render();
// Create the new post view
newPostView = new NewPostView({
el: $('.new-post-article'),
collection: discussion,
course_settings: courseSettings,
discussionBoardView: discussionBoardView,
mode: 'tab',
startHeader: 2,
topicId: options.defaultTopicId
});
newPostView.render();
// Set up a router to manage the page's history
router = new DiscussionRouter({
rootUrl: options.rootUrl,
discussion: discussion,
courseSettings: courseSettings,
discussionBoardView: discussionBoardView,
newPostView: newPostView
});
router.start();
routerEvents = {
// Add new breadcrumbs and clear search box when the user selects topics
'topic:selected': function(topic) {
router.discussionBoardView.breadcrumbs.model.set('contents', topic);
},
// Clear search box when a thread is selected
'thread:selected': function() {
router.discussionBoardView.searchView.clearSearch();
}
};
Object.keys(routerEvents).forEach(function(key) {
router.discussionBoardView.on(key, routerEvents[key]);
});
};
});
}).call(this, define || RequireJS.define); |
package info.novatec.inspectit.rcp.preferences.valueproviders;
import info.novatec.inspectit.rcp.preferences.PreferenceException;
import info.novatec.inspectit.rcp.preferences.<API key>;
import info.novatec.inspectit.rcp.preferences.valueproviders.<API key>.<API key>;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.collections.MapUtils;
/**
* This {@link <API key>} converts any map that has keys and values in primitive
* warper types to preference value. Later on this preference value will be transformed to a map
* that has both string as key and value, and thus needs transformation to initial classes of keys
* and values.
*
* @author Ivan Senic
*
*/
public class <API key> extends <API key><Map<?, ?>> {
/**
* Constant for denoting the empty map.
*/
private static final String EMPTY_MAP = "EMPTY_MAP";
/**
* {@inheritDoc}
*/
public boolean isObjectValid(Object object) {
return object instanceof Map;
}
/**
* {@inheritDoc}
*/
public String getValueForObject(Map<?, ?> map) throws PreferenceException {
if (MapUtils.isEmpty(map)) {
return EMPTY_MAP;
} else {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
stringBuilder.append(String.valueOf(entry.getKey()));
stringBuilder.append(<API key>.PREF_SPLIT_REGEX);
stringBuilder.append(entry.getValue());
stringBuilder.append(<API key>.<API key>);
}
return stringBuilder.toString();
}
}
/**
* {@inheritDoc}
*/
public Map<?, ?> getObjectFromValue(String value) throws PreferenceException {
if (EMPTY_MAP.equals(value)) {
return Collections.emptyMap();
} else {
Map<String, String> map = new HashMap<String, String>();
StringTokenizer tokenizer = new StringTokenizer(value, <API key>.<API key>);
while (tokenizer.hasMoreElements()) {
String nextEntry = tokenizer.nextToken();
String[] splitted = nextEntry.split(<API key>.PREF_SPLIT_REGEX);
if (splitted.length == 2) {
map.put(splitted[0], splitted[1]);
} else {
throw new PreferenceException("Error loading map entry for the map saved in the preference store are not correct. Entry key and value received values via the string '"
+ nextEntry + "' are " + Arrays.asList(splitted) + ". Definition will be skipped.");
}
}
return map;
}
}
} |
/**
* View for the receipt page.
*/
var edx = edx || {};
(function ($, _, _s, Backbone) {
'use strict';
edx.commerce = edx.commerce || {};
edx.commerce.ReceiptView = Backbone.View.extend({
useEcommerceApi: true,
initialize: function () {
this.useEcommerceApi = !!($.url('?basket_id'));
_.bindAll(this, 'renderReceipt', 'renderError', 'getProviderData', 'renderProvider', 'getCourseData');
/* Mix non-conflicting functions from underscore.string (all but include, contains, and reverse) into
* the Underscore namespace.
*/
_.mixin(_s.exports());
this.render();
},
renderReceipt: function (data) {
var templateHtml = $("#receipt-tpl").html(),
context = {
platformName: this.$el.data('platform-name'),
verified: this.$el.data('verified').toLowerCase() === 'true'
},
providerId;
// Add the receipt info to the template context
this.courseKey = this.getOrderCourseKey(data);
this.username = this.$el.data('username');
_.extend(context, {
receipt: this.receiptContext(data),
courseKey: this.courseKey
});
this.$el.html(_.template(templateHtml, context));
this.trackLinks();
this.<API key>(this.courseKey);
providerId = this.getCreditProviderId(data);
if (providerId) {
this.getProviderData(providerId).then(this.renderProvider, this.renderError)
}
},
<API key>: function(courseId) {
// Display the course Id or name (if available) in the placeholder
var $<API key> = $(".<API key>");
$<API key>.text(courseId);
this.getCourseData(courseId).then(function(responseData) {
$<API key>.text(responseData.name);
});
},
renderProvider: function (context) {
var templateHtml = $("#provider-tpl").html(),
providerDiv = this.$el.find("#receipt-provider");
context.course_key = this.courseKey;
context.username = this.username;
providerDiv.html(_.template(templateHtml, context)).removeClass('hidden');
},
renderError: function () {
// Display an error
$('#error-container').removeClass('hidden');
},
render: function () {
var self = this,
orderId = $.url('?basket_id') || $.url('?payment-order-num');
if (orderId && this.$el.data('is-payment-complete')==='True') {
// Get the order details
self.$el.removeClass('hidden');
self.getReceiptData(orderId).then(self.renderReceipt, self.renderError);
} else {
self.renderError();
}
},
trackLinks: function () {
var $verifyNowButton = $('#verify_now_button'),
$verifyLaterButton = $('#verify_later_button');
// Track a virtual pageview, for easy funnel reconstruction.
window.analytics.page('payment', 'receipt');
// Track the user's decision to verify immediately
window.analytics.trackLink($verifyNowButton, 'edx.bi.user.verification.immediate', {
category: 'verification'
});
// Track the user's decision to defer their verification
window.analytics.trackLink($verifyLaterButton, 'edx.bi.user.verification.deferred', {
category: 'verification'
});
},
/**
* Retrieve receipt data from Oscar (via LMS).
* @param {int} basketId The basket that was purchased.
* @return {object} JQuery Promise.
*/
getReceiptData: function (basketId) {
var urlFormat = this.useEcommerceApi ? '/api/commerce/v0/baskets/%s/order/' : '/shoppingcart/receipt/%s/';
return $.ajax({
url: _.sprintf(urlFormat, basketId),
type: 'GET',
dataType: 'json'
}).retry({times: 5, timeout: 2000, statusCodes: [404]});
},
/**
* Retrieve credit provider data from LMS.
* @param {string} providerId The providerId of the credit provider.
* @return {object} JQuery Promise.
*/
getProviderData: function (providerId) {
var providerUrl = '/api/credit/v1/providers/%s/';
return $.ajax({
url: _.sprintf(providerUrl, providerId),
type: 'GET',
dataType: 'json'
}).retry({times: 5, timeout: 2000, statusCodes: [404]});
},
/**
* Retrieve course data from LMS.
* @param {string} courseId The courseId of the course.
* @return {object} JQuery Promise.
*/
getCourseData: function (courseId) {
var courseDetailUrl = '/api/course_structure/v0/courses/%s/';
return $.ajax({
url: _.sprintf(courseDetailUrl, courseId),
type: 'GET',
dataType: 'json'
});
},
/**
* Construct the template context from data received
* from the E-Commerce API.
*
* @param {object} order Receipt data received from the server
* @return {object} Receipt template context.
*/
receiptContext: function (order) {
var self = this,
receiptContext;
if (this.useEcommerceApi) {
receiptContext = {
orderNum: order.number,
currency: order.currency,
purchasedDatetime: order.date_placed,
totalCost: self.formatMoney(order.total_excl_tax),
isRefunded: false,
items: [],
billedTo: null
};
if (order.billing_address){
receiptContext.billedTo = {
firstName: order.billing_address.first_name,
lastName: order.billing_address.last_name,
city: order.billing_address.city,
state: order.billing_address.state,
postalCode: order.billing_address.postcode,
country: order.billing_address.country
}
}
receiptContext.items = _.map(
order.lines,
function (line) {
return {
lineDescription: line.description,
cost: self.formatMoney(line.line_price_excl_tax)
};
}
);
} else {
receiptContext = {
orderNum: order.orderNum,
currency: order.currency,
purchasedDatetime: order.purchase_datetime,
totalCost: self.formatMoney(order.total_cost),
isRefunded: order.status === "refunded",
billedTo: {
firstName: order.billed_to.first_name,
lastName: order.billed_to.last_name,
city: order.billed_to.city,
state: order.billed_to.state,
postalCode: order.billed_to.postal_code,
country: order.billed_to.country
},
items: []
};
receiptContext.items = _.map(
order.items,
function (item) {
return {
lineDescription: item.line_desc,
cost: self.formatMoney(item.line_cost)
};
}
);
}
return receiptContext;
},
getOrderCourseKey: function (order) {
var length, items;
if (this.useEcommerceApi) {
length = order.lines.length;
for (var i = 0; i < length; i++) {
var line = order.lines[i],
attributeValues = _.find(line.product.attribute_values, function (attribute) {
return attribute.name === 'course_key'
});
// This method assumes that all items in the order are related to a single course.
if (attributeValues != undefined) {
return attributeValues['value'];
}
}
} else {
items = _.filter(order.items, function (item) {
return item.course_key;
});
if (items.length > 0) {
return items[0].course_key;
}
}
return null;
},
formatMoney: function (moneyStr) {
return Number(moneyStr).toFixed(2);
},
/**
* Check whether the payment is for the credit course or not.
*
* @param {object} order Receipt data received from the server
* @return {string} String of the provider_id or null.
*/
getCreditProviderId: function (order) {
var attributeValues,
line = order.lines[0];
if (this.useEcommerceApi) {
attributeValues = _.find(line.product.attribute_values, function (attribute) {
return attribute.name === 'credit_provider'
});
// This method assumes that all items in the order are related to a single course.
if (attributeValues != undefined) {
return attributeValues['value'];
}
}
return null;
},
});
new edx.commerce.ReceiptView({
el: $('#receipt-container')
});
})(jQuery, _, _.str, Backbone);
function completeOrder (event) {
var courseKey = $(event).data("course-key"),
username = $(event).data("username"),
providerId = $(event).data("provider"),
postData = {
'course_key': courseKey,
'username': username
},
errorContainer = $("#error-container");
analytics.track(
"edx.bi.credit.<API key>",
{
category: "credit",
label: courseKey
}
);
$.ajax({
url: '/api/credit/v1/provider/' + providerId + '/request/',
type: 'POST',
headers: {
'X-CSRFToken': $.cookie('csrftoken')
},
data: JSON.stringify(postData) ,
context: this,
success: function(requestData){
var form = $('#complete-order-form');
$('input', form).remove();
form.attr( 'action', requestData.url );
form.attr( 'method', 'POST' );
_.each( requestData.parameters, function( value, key ) {
$('<input>').attr({
type: 'hidden',
name: key,
value: value
}).appendTo(form);
});
form.submit();
},
error: function(xhr){
errorContainer.removeClass("is-hidden");
errorContainer.removeClass("hidden");
}
});
} |
/**
* @ingroup cc430
* @{
*/
/**
* @file
* @brief eZ430 radio driver (cpu dependent part)
*
* @author Oliver Hahm <oliver.hahm@inria.fr>
*
*/
#include <stdint.h>
#include "irq.h"
#include "cc110x_legacy.h"
#include "board.h"
#include "hwtimer.h"
uint8_t cc110x_strobe(uint8_t c)
{
uint8_t statusByte = 0;
/* Check for valid strobe command */
if ((c == 0xBD) || ((c > RF_SRES) && (c < RF_SNOP))) {
uint16_t int_state = disableIRQ();
/* Clear the Status read flag */
RF1AIFCTL1 &= ~(RFSTATIFG);
/* Wait for radio to be ready for next instruction */
while (!(RF1AIFCTL1 & RFINSTRIFG));
/* Write the strobe instruction */
if ((c > RF_SRES) && (c < RF_SNOP)) {
uint16_t gdo_state = cc110x_read_reg(IOCFG2); /* buffer IOCFG2 state */
cc110x_write_reg(IOCFG2, 0x29); /* c-ready to GDO2 */
RF1AINSTRB = c;
if ((RF1AIN & 0x04) == 0x04) { /* chip at sleep mode */
if ((c == RF_SXOFF) || (c == RF_SPWD) || (c == RF_SWOR)) { }
else {
while ((RF1AIN & 0x04) == 0x04); /* c-ready ? */
hwtimer_wait(RTIMER_TICKS(9800)); /* Delay for ~810usec at 12MHz CPU clock */
}
}
cc110x_write_reg(IOCFG2, gdo_state); /* restore IOCFG2 setting */
}
else { /* chip active mode */
RF1AINSTRB = c;
}
statusByte = RF1ASTATB;
while (!(RF1AIFCTL1 & RFSTATIFG));
restoreIRQ(int_state);
}
return statusByte;
}
uint8_t cc110x_read_reg(uint8_t addr)
{
unsigned char x;
uint16_t int_state;
int_state = disableIRQ();
RF1AINSTR1B = (addr | RF_REGRD);
x = RF1ADOUT1B;
restoreIRQ(int_state);
return x;
}
void cc110x_write_reg(uint8_t addr, uint8_t value)
{
volatile unsigned int i;
uint16_t int_state;
int_state = disableIRQ();
while (!(RF1AIFCTL1 & RFINSTRIFG)); /* Wait for the Radio to be ready for the next instruction */
RF1AINSTRW = ((addr | RF_REGWR) << 8) + value; /* Send address + Instruction */
while (!(RFDINIFG & RF1AIFCTL1));
/* cppcheck: need to force a read to RF1ADOUTB to trigger reset */
/* cppcheck-suppress unreadVariable */
i = RF1ADOUTB; /* Reset RFDOUTIFG flag which contains status byte */
restoreIRQ(int_state);
}
uint8_t cc110x_read_status(uint8_t addr)
{
unsigned char x;
uint16_t int_state;
int_state = disableIRQ();
RF1AINSTR1B = (addr | RF_STATREGRD);
x = RF1ADOUT1B;
restoreIRQ(int_state);
return x;
}
void <API key>(uint8_t addr, char *buffer, uint8_t count)
{
unsigned int i;
uint16_t int_state;
int_state = disableIRQ();
while (!(RF1AIFCTL1 & RFINSTRIFG)); /* Wait for the Radio to be ready for next instruction */
RF1AINSTR1B = (addr | RF_REGRD); /* Send address + Instruction */
for (i = 0; i < (count - 1); i++) {
while (!(RFDOUTIFG & RF1AIFCTL1)); /* Wait for the Radio Core to update the RF1ADOUTB reg */
buffer[i] = RF1ADOUT1B; /* Read DOUT from Radio Core + clears RFDOUTIFG */
/* Also initiates auo-read for next DOUT byte */
}
buffer[count - 1] = RF1ADOUT0B; /* Store the last DOUT from Radio Core */
restoreIRQ(int_state);
}
void cc110x_read_fifo(char *buffer, uint8_t count)
{
unsigned int i;
uint16_t int_state;
int_state = disableIRQ();
while (!(RF1AIFCTL1 & RFINSTRIFG)); /* Wait for the Radio to be ready for next instruction */
RF1AINSTR1B = (RF_RXFIFORD); /* Send address + Instruction */
for (i = 0; i < (count - 1); i++) {
while (!(RFDOUTIFG & RF1AIFCTL1)); /* Wait for the Radio Core to update the RF1ADOUTB reg */
buffer[i] = RF1ADOUT1B; /* Read DOUT from Radio Core + clears RFDOUTIFG */
/* Also initiates auo-read for next DOUT byte */
}
buffer[count - 1] = RF1ADOUT0B; /* Store the last DOUT from Radio Core */
restoreIRQ(int_state);
}
uint8_t <API key>(uint8_t addr, char *buffer, uint8_t count)
{
/* Write Burst works wordwise not bytewise - bug known already */
unsigned char i;
uint16_t int_state;
int_state = disableIRQ();
while (!(RF1AIFCTL1 & RFINSTRIFG)); /* Wait for the Radio to be ready for next instruction */
RF1AINSTRW = ((addr | RF_REGWR) << 8) + buffer[0]; /* Send address + Instruction */
for (i = 1; i < count; i++) {
RF1ADINB = buffer[i]; /* Send data */
while (!(RFDINIFG & RF1AIFCTL1)); /* Wait for TX to finish */
}
/* cppcheck: need to force a read to RF1ADOUTB to trigger reset */
/* cppcheck-suppress unreadVariable */
i = RF1ADOUTB; /* Reset RFDOUTIFG flag which contains status byte */
restoreIRQ(int_state);
return count;
} |
/**
* @ingroup drivers_mma8x5x
* @{
*
* @file
* @brief Default configuration for MMA8x5x devices
*
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*/
#ifndef MMA8X5X_PARAMS_H
#define MMA8X5X_PARAMS_H
#include "board.h"
#include "saul_reg.h"
#include "mma8x5x.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @name Set default configuration parameters for the MMA8x5x driver
* @{
*/
#ifndef MMA8X5X_PARAM_I2C
#define MMA8X5X_PARAM_I2C (I2C_DEV(0))
#endif
#ifndef MMA8X5X_PARAM_ADDR
#define MMA8X5X_PARAM_ADDR (MMA8X5X_I2C_ADDRESS)
#endif
#ifndef MMA8X5X_PARAM_RATE
#define MMA8X5X_PARAM_RATE (MMA8X5X_RATE_200HZ)
#endif
#ifndef MMA8X5X_PARAM_RANGE
#define MMA8X5X_PARAM_RANGE (MMA8X5X_RANGE_2G)
#endif
#ifndef <API key>
#define <API key> { 0, 0, 0 }
#endif
#ifndef MMA8X5X_PARAMS
#define MMA8X5X_PARAMS { .i2c = MMA8X5X_PARAM_I2C, \
.addr = MMA8X5X_PARAM_ADDR, \
.rate = MMA8X5X_PARAM_RATE, \
.range = MMA8X5X_PARAM_RANGE, \
.offset = <API key> }
#endif
#ifndef MMA8X5X_SAUL_INFO
#define MMA8X5X_SAUL_INFO { .name = "mma8x5x" }
#endif
/**
* @brief MMA8x5x configuration
*/
static const mma8x5x_params_t mma8x5x_params[] =
{
MMA8X5X_PARAMS
};
/**
* @brief Additional meta information to keep in the SAUL registry
*/
static const saul_reg_info_t mma8x5x_saul_info[] =
{
MMA8X5X_SAUL_INFO
};
#ifdef __cplusplus
}
#endif
#endif /* MMA8X5X_PARAMS_H */ |
require 'spec_helper'
type_class = Puppet::Type.type(:route53_zone)
describe type_class do
let :params do
[
:name,
]
end
let :properties do
[
:ensure,
]
end
it 'should have expected properties' do
properties.each do |property|
expect(type_class.properties.map(&:name)).to be_include(property)
end
end
it 'should have expected parameters' do
params.each do |param|
expect(type_class.parameters).to be_include(param)
end
end
it 'should require a name' do
expect {
type_class.new({})
}.to raise_error(Puppet::Error, 'Title or name must be provided')
end
it 'should require a non-blank name' do
expect {
type_class.new({ name: '' })
}.to raise_error(Puppet::Error, /Empty values are not allowed/)
end
context 'with a valid name' do
it 'should create a valid instance' do
type_class.new({ name: 'name' })
end
end
end |
(function (GGRC, Generator) {
GGRC.Bootstrap.Mockups = GGRC.Bootstrap.Mockups || {};
GGRC.Bootstrap.Mockups.Workflow = GGRC.Bootstrap.Mockups.Workflow || {};
GGRC.Bootstrap.Mockups.Workflow.Workflows = {
title: "Active Cycles",
icon: "cycle",
template: "/workflow/cycle.mustache",
hide_filter: false,
children: Generator.create({
title: "%title",
type: "workflow",
due_on: '12/31/2017',
id: "%id",
children: Generator.create({
title: "Task Group",
type: "task_group",
icon: "task_group",
id: "%id",
children: Generator.get("task")
})
})
};
})(GGRC || {}, GGRC.Mockup.Generator); |
begin;
CREATE TABLE <API key>( phase text,a int,col001 char DEFAULT 'z',col002 numeric,col003 boolean DEFAULT false,col004 bit(3) DEFAULT '111',col005 text DEFAULT 'pookie', col006 integer[] DEFAULT '{5, 4, 3, 2, 1}', col007 character varying(512) DEFAULT 'Now is the time', col008 character varying DEFAULT 'Now is the time', col009 character varying(512)[], col010 numeric(8) ,col011 int,col012 double precision, col013 bigint, col014 char(8), col015 bytea,col016 timestamp with time zone,col017 interval, col018 cidr, col019 inet, col020 macaddr,col022 money, col024 timetz,col025 circle, col026 box, col027 name,col028 path, col029 int2, col031 bit varying(256),col032 date, col034 lseg,col035 point,col036 polygon,col037 real,col039 time, col040 timestamp );
INSERT INTO <API key> VALUES ('sync1_heap1',1,'a',11,true,'111', '1_one', '{1,2,3,4,5}', 'Hello .. how are you 1', 'Hello .. how are you 1', '{one,two,three,four,five}', 12345678, 1, 111.1111, 11, '1_one_11', 'd',
'2001-12-13 01:51:15+1359', '11', '0.0.0.0', '0.0.0.0', 'AA:AA:AA:AA:AA:AA', '34.23', '00:00:00+1359', '((2,2),1)', '((1,2),(2,1))', 'hello', '((1,2),(2,1))', 11, '010101', '2001-12-13', '((1,1),(2,2))', '(1,1)', '((1,2),(2,3),(3,4),(4,3),(3,2),(2,1))', 111111, '23:00:00', '2001-12-13 01:51:15');
commit;
select count(*) from <API key>;
DROP TABLE <API key>; |
package main
import (
kafka "github.com/stealthly/go_kafka_client"
"flag"
"os"
)
var zkConnect = flag.String("zookeeper", "", "zookeeper connection string host:port.")
var blueTopic = flag.String("blue.topic", "", "first topic name")
var blueGroup = flag.String("blue.group", "", "first consumer group name")
var bluePattern = flag.String("blue.pattern", "", "first consumer group name")
var greenTopic = flag.String("green.topic", "", "second topic name")
var greenGroup = flag.String("green.group", "", "second consumer group name")
var greenPattern = flag.String("green.pattern", "", "second consumer pattern")
func main() {
flag.Parse()
if *zkConnect == "" || *blueTopic == "" || *blueGroup == "" || *bluePattern == "" || *greenTopic == "" || *greenGroup == "" || *greenPattern == "" {
flag.Usage()
os.Exit(1)
}
blue := kafka.BlueGreenDeployment{*blueTopic, *bluePattern, *blueGroup}
green := kafka.BlueGreenDeployment{*greenTopic, *greenPattern, *greenGroup}
zkConfig := kafka.NewZookeeperConfig()
zkConfig.ZookeeperConnect = []string{*zkConnect}
zk := kafka.<API key>(zkConfig)
zk.Connect()
zk.<API key>(blue, green)
} |
// "Fix all 'Stream API call chain can be simplified' problems in file" "false"
import java.util.*;
import java.util.function.*;
class Test {
public void testToArray(List<String[]> data, IntFunction<String[]> generator) {
Object[] array = data.stream().toA<caret>rray(generator);
}
} |
<?php
/**
* default actions.
*
* @package OpenPNE
* @subpackage default
* @author Shinichi Urabe <urabe@tejimaya.com>
* @version SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
*/
class secureAction extends <API key>
{
} |
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#ifndef lint
static const char rcsid[] _U_ =
"@(#) $Header: /tcpdump/master/tcpdump/print-ppp.c,v 1.114 2005-12-05 11:35:58 hannes Exp $ (LBL)";
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <tcpdump-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include "interface.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/* Protocol Codes defined in ppp.h */
struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext",
"MRU",
"ACCM",
"Auth-Prot",
"Qual-Prot",
"Magic-Num",
"deprecated(6)", /* used to be a Quality Protocol */
"PFC",
"ACFC",
"FCS-Alt",
"SDP",
"Num-Mode",
"deprecated(12)", /* used to be a <API key>*/
"Call-Back",
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU",
"12-Bit seq #",
"End-Disc",
"Proprietary",
"DCE-Id",
"MP+",
"Link-Disc",
"LCP-Auth-Opt",
"COBS",
"Prefix-elision",
"<API key>",
"I18N",
"SDL-over-SONET/SDH",
"PPP-Muxing",
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define <API key> 0x61 /* rfc3544 */
#define <API key> 14
struct tok <API key>[] = {
{ PPP_VJC, "VJ-Comp" },
{ <API key>, "IP Header Compression" },
{ 0, NULL }
};
struct tok <API key>[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static void handle_ctrl_proto (u_int proto,const u_char *p, int length);
static void handle_chap (const u_char *p, int length);
static void handle_pap (const u_char *p, int length);
static void handle_bap (const u_char *p, int length);
static void handle_mlppp(const u_char *p, int length);
static int <API key> (const u_char *p, int);
static int <API key> (const u_char *p, int);
static int <API key> (const u_char *p, int);
static int <API key> (const u_char *p, int);
static int <API key> (const u_char *p, int);
static void handle_ppp (u_int proto, const u_char *p, int length);
static void ppp_hdlc(const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
printf("%s, ",typestr);
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
TCHECK2(*tptr, 2);
code = *tptr++;
printf("%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++,
length+2);
if (!vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
printf("\n\tencoded length %u (=Option(s) length %u)",len,len-4);
if (vflag>1)
print_unknown_data(pptr-2,"\n\t",6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
TCHECK2(*tptr, 4);
printf("\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr));
tptr += 4;
TCHECK2(*tptr, 3);
printf(" Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = <API key>;
break;
case PPP_IPCP:
pfunc = <API key>;
break;
case PPP_IPV6CP:
pfunc = <API key>;
break;
case PPP_CCP:
pfunc = <API key>;
break;
case PPP_BACP:
pfunc = <API key>;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
TCHECK2(*tptr, 2);
printf("\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr));
/* XXX: need to decode <API key>? - hexdump for now */
if (len > 6) {
printf("\n\t Rejected Packet");
print_unknown_data(tptr+2,"\n\t ",len-2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
TCHECK2(*tptr, 4);
printf("\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
printf("\n\t
TCHECK2(tptr[4], len-8);
print_unknown_data(tptr+4,"\n\t ",len-8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
TCHECK2(*tptr, 4);
printf("\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
printf("\n\t Message\n\t ");
fn_printn(tptr+4,len-4,snapend);
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
TCHECK2(*tptr, 4);
printf("\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr));
TCHECK2(*(tptr + 4), 4);
printf(", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (vflag <= 1)
print_unknown_data(pptr-2,"\n\t ",length+2);
break;
}
return;
trunc:
printf("[|%s]", typestr);
}
/* LCP config options */
static int
<API key>(const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
printf("\n\t %s Option (0x%02x), length %u (bogus, should be >= 2)", lcpconfopts[opt],opt,len);
else
printf("\n\tunknown LCP option 0x%02x", opt);
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
printf("\n\t %s Option (0x%02x), length %u: ", lcpconfopts[opt],opt,len);
else {
printf("\n\tunknown LCP option 0x%02x", opt);
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len >= 6) {
TCHECK2(*(p + 2), 3);
printf("Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p+2));
#if 0
TCHECK(p[5]);
printf(", kind: 0x%02x", p[5]);
printf(", Value: 0x")
for (i = 0; i < len - 6; i++) {
TCHECK(p[6 + i]);
printf("%02x", p[6 + i]);
}
#endif
}
break;
case LCPOPT_MRU:
if (len == 4) {
TCHECK2(*(p + 2), 2);
printf("%u", EXTRACT_16BITS(p + 2));
}
break;
case LCPOPT_ACCM:
if (len == 6) {
TCHECK2(*(p + 2), 4);
printf("0x%08x", EXTRACT_32BITS(p + 2));
}
break;
case LCPOPT_AP:
if (len >= 4) {
TCHECK2(*(p + 2), 2);
printf("%s", tok2str(ppptype2str,"Unknown Auth Proto (0x04x)",EXTRACT_16BITS(p+2)));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
TCHECK(p[4]);
printf(", %s",tok2str(authalg_values,"Unknown Auth Alg %u",p[4]));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(p,"\n\t",len);
}
}
break;
case LCPOPT_QP:
if (len >= 4) {
TCHECK2(*(p + 2), 2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
printf(" LQR");
else
printf(" unknown");
}
break;
case LCPOPT_MN:
if (len == 6) {
TCHECK2(*(p + 2), 4);
printf("0x%08x", EXTRACT_32BITS(p + 2));
}
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len == 4) {
TCHECK2(*(p + 2), 2);
printf("0x%04x", EXTRACT_16BITS(p + 2));
}
break;
case LCPOPT_CBACK:
if (len < 3)
break;
TCHECK(p[2]);
printf("Callback Operation %s (%u)",
tok2str(ppp_callback_values,"Unknown",p[2]),
p[2]);
break;
case LCPOPT_MLMRRU:
if (len == 4) {
TCHECK2(*(p + 2), 2);
printf("%u", EXTRACT_16BITS(p + 2));
}
break;
case LCPOPT_MLED:
if (len < 3)
break;
TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
printf("Null");
break;
case MEDCLASS_LOCAL:
printf("Local"); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7)
break;
TCHECK2(*(p + 3), 4);
printf("IPv4 %s", ipaddr_string(p + 3));
break;
case MEDCLASS_MAC:
if (len != 9)
break;
TCHECK(p[8]);
printf("MAC %02x:%02x:%02x:%02x:%02x:%02x",
p[3], p[4], p[5], p[6], p[7], p[8]);
break;
case MEDCLASS_MNB:
printf("Magic-Num-Block"); /* XXX */
break;
case MEDCLASS_PSNDN:
printf("PSNDN"); /* XXX */
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
if(vflag<2)
print_unknown_data(&p[2],"\n\t ",len-2);
break;
}
if (vflag>1)
print_unknown_data(&p[2],"\n\t ",len-2); /* exclude TLV header */
return len;
trunc:
printf("[|lcp]");
return 0;
}
/* ML-PPP*/
struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(const u_char *p, int length) {
if (!eflag)
printf("MLPPP, ");
printf("seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length);
return;
}
/* CHAP */
static void
handle_chap(const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
printf("[|chap]");
return;
} else if (length < 4) {
TCHECK(*p);
printf("[|chap 0x%02x]", *p);
return;
}
TCHECK(*p);
code = *p;
printf("CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code);
p++;
TCHECK(*p);
printf(", id %u", *p);
p++;
TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
printf(", Value ");
for (i = 0; i < val_size; i++) {
TCHECK(*p);
printf("%02x", *p++);
}
name_size = len - (p - p0);
printf(", Name ");
for (i = 0; i < name_size; i++) {
TCHECK(*p);
safeputchar(*p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
printf(", Msg ");
for (i = 0; i< msg_size; i++) {
TCHECK(*p);
safeputchar(*p++);
}
break;
}
return;
trunc:
printf("[|chap]");
}
/* PAP (see RFC 1334) */
static void
handle_pap(const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
printf("[|pap]");
return;
} else if (length < 4) {
TCHECK(*p);
printf("[|pap 0x%02x]", *p);
return;
}
TCHECK(*p);
code = *p;
printf("PAP, %s (0x%02x)",
tok2str(papcode_values,"unknown",code),
code);
p++;
TCHECK(*p);
printf(", id %u", *p);
p++;
TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
printf(", length %u > packet size", len);
return;
}
length = len;
if (length < (p - p0)) {
printf(", length %u < PAP header length", length);
return;
}
switch (code) {
case PAP_AREQ:
if (length - (p - p0) < 1)
return;
TCHECK(*p);
peerid_len = *p; /* Peer-ID Length */
p++;
if (length - (p - p0) < peerid_len)
return;
printf(", Peer ");
for (i = 0; i < peerid_len; i++) {
TCHECK(*p);
safeputchar(*p++);
}
if (length - (p - p0) < 1)
return;
TCHECK(*p);
passwd_len = *p; /* Password Length */
p++;
if (length - (p - p0) < passwd_len)
return;
printf(", Name ");
for (i = 0; i < passwd_len; i++) {
TCHECK(*p);
safeputchar(*p++);
}
break;
case PAP_AACK:
case PAP_ANAK:
if (length - (p - p0) < 1)
return;
TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
printf(", Msg ");
for (i = 0; i< msg_len; i++) {
TCHECK(*p);
safeputchar(*p++);
}
break;
}
return;
trunc:
printf("[|pap]");
}
/* BAP */
static void
handle_bap(const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
<API key>(const u_char *p, int length)
{
int len, opt;
u_int compproto, <API key>, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
printf("\n\t %s Option (0x%02x), length %u (bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len);
return 0;
}
printf("\n\t %s Option (0x%02x), length %u: ",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len);
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10)
goto invlen;
TCHECK2(*(p + 6), 4);
printf("src %s, dst %s",
ipaddr_string(p + 2),
ipaddr_string(p + 6));
break;
case IPCPOPT_IPCOMP:
if (len < 4)
goto invlen;
TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
printf("%s (0x%02x):",
tok2str(<API key>,"Unknown",compproto),
compproto);
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case <API key>:
if (len < <API key>)
goto invlen;
TCHECK2(*(p + 2), <API key>);
printf("\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12));
/* suboptions present ? */
if (len > <API key>) {
<API key> = len - <API key>;
p += <API key>;
printf("\n\t Suboptions, length %u", <API key>);
while (<API key> >= 2) {
TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
printf("\n\t\t%s Suboption #%u, length %u",
tok2str(<API key>,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen);
<API key> -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6)
goto invlen;
TCHECK2(*(p + 2), 4);
printf("%s", ipaddr_string(p + 2));
break;
default:
if(vflag<2)
print_unknown_data(&p[2],"\n\t ",len-2);
break;
}
if (vflag>1)
print_unknown_data(&p[2],"\n\t ",len-2); /* exclude TLV header */
return len;
invlen:
printf(", invalid-length-%d", opt);
return 0;
trunc:
printf("[|ipcp]");
return 0;
}
/* IP6CP config options */
static int
<API key>(const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
printf("\n\t %s Option (0x%02x), length %u (bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len);
return 0;
}
printf("\n\t %s Option (0x%02x), length %u: ",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len);
switch (opt) {
case IP6CP_IFID:
if (len != 10)
goto invlen;
TCHECK2(*(p + 2), 8);
printf("%04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8));
break;
default:
if(vflag<2)
print_unknown_data(&p[2],"\n\t ",len-2);
break;
}
if (vflag>1)
print_unknown_data(&p[2],"\n\t ",len-2); /* exclude TLV header */
return len;
invlen:
printf(", invalid-length-%d", opt);
return 0;
trunc:
printf("[|ip6cp]");
return 0;
}
/* CCP config options */
static int
<API key>(const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
printf("\n\t %s Option (0x%02x), length %u (bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len);
return 0;
}
printf("\n\t %s Option (0x%02x), length %u:",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len);
switch (opt) {
/* fall through --> default: nothing supported yet */
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_BSDCOMP:
case CCPOPT_LZSDCP:
case CCPOPT_MVRCA:
case CCPOPT_DEC:
case CCPOPT_DEFLATE:
case CCPOPT_RESV:
default:
if(vflag<2)
print_unknown_data(&p[2],"\n\t ",len-2);
break;
}
if (vflag>1)
print_unknown_data(&p[2],"\n\t ",len-2); /* exclude TLV header */
return len;
trunc:
printf("[|ccp]");
return 0;
}
/* BACP config options */
static int
<API key>(const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
printf("\n\t %s Option (0x%02x), length %u (bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len);
return 0;
}
printf("\n\t %s Option (0x%02x), length %u:",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len);
switch (opt) {
case BACPOPT_FPEER:
TCHECK2(*(p + 2), 4);
printf(", Magic-Num 0x%08x", EXTRACT_32BITS(p + 2));
break;
default:
if(vflag<2)
print_unknown_data(&p[2],"\n\t ",len-2);
break;
}
if (vflag>1)
print_unknown_data(&p[2],"\n\t ",len-2); /* exclude TLV header */
return len;
trunc:
printf("[|bacp]");
return 0;
}
static void
ppp_hdlc(const u_char *p, int length)
{
u_char *b, *s, *t, c;
int i, proto;
const void *se;
b = (u_int8_t *)malloc(length);
if (b == NULL)
return;
/*
* Unescape all the data into a temporary, private, buffer.
* Do this so that we dont overwrite the original packet
* contents.
*/
for (s = (u_char *)p, t = b, i = length; i > 0; i
c = *s++;
if (c == 0x7d) {
if (i > 1) {
i
c = *s++ ^ 0x20;
} else
continue;
}
*t++ = c;
}
se = snapend;
snapend = t;
/* now lets guess about the payload codepoint format */
proto = *b; /* start with a one-octet codepoint guess */
switch (proto) {
case PPP_IP:
ip_print(gndo, b+1, t - b - 1);
goto cleanup;
#ifdef INET6
case PPP_IPV6:
ip6_print(b+1, t - b - 1);
goto cleanup;
#endif
default: /* no luck - try next guess */
break;
}
proto = EXTRACT_16BITS(b); /* next guess - load two octets */
switch (proto) {
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
handle_ppp(proto, b+4, t - b - 4);
break;
default: /* last guess - proto must be a PPP proto-id */
handle_ppp(proto, b+2, t - b - 2);
break;
}
cleanup:
snapend = se;
free(b);
return;
}
/* PPP */
static void
handle_ppp(u_int proto, const u_char *p, int length)
{
if ((proto & 0xff00) == 0x7e00) {/* is this an escape code ? */
ppp_hdlc(p-1, length);
return;
}
switch (proto) {
case PPP_LCP: /* fall through */
case PPP_IPCP:
case PPP_OSICP:
case PPP_MPLSCP:
case PPP_IPV6CP:
case PPP_CCP:
case PPP_BACP:
handle_ctrl_proto(proto, p, length);
break;
case PPP_ML:
handle_mlppp(p, length);
break;
case PPP_CHAP:
handle_chap(p, length);
break;
case PPP_PAP:
handle_pap(p, length);
break;
case PPP_BAP: /* XXX: not yet completed */
handle_bap(p, length);
break;
case ETHERTYPE_IP: /*XXX*/
case PPP_VJNC:
case PPP_IP:
ip_print(gndo, p, length);
break;
#ifdef INET6
case ETHERTYPE_IPV6: /*XXX*/
case PPP_IPV6:
ip6_print(p, length);
break;
#endif
case ETHERTYPE_IPX: /*XXX*/
case PPP_IPX:
ipx_print(p, length);
break;
case PPP_OSI:
isoclns_print(p, length, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(p, length);
break;
case PPP_COMP:
printf("compressed PPP data");
break;
default:
printf("%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto));
print_unknown_data(p,"\n\t",length);
break;
}
}
/* Standard PPP printer */
u_int
ppp_print(register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (<API key> << 8 | PPP_CONTROL):
if (eflag) printf("In ");
p += 2;
length -= 2;
hdr_len += 2;
break;
case (<API key> << 8 | PPP_CONTROL):
if (eflag) printf("Out ");
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length
hdr_len++;
} else {
TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (eflag)
printf("%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen);
handle_ppp(proto, p, length);
return (hdr_len);
trunc:
printf("[|ppp]");
return (0);
}
/* PPP I/F printer */
u_int
ppp_if_print(const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < PPP_HDRLEN) {
printf("[|ppp]");
return (caplen);
}
#if 0
/*
* XXX: seems to assume that there are 2 octets prepended to an
* actual PPP frame. The 1st octet looks like Input/Output flag
* while 2nd octet is unknown, at least to me
* (mshindo@mshindo.net).
*
* That was what the original tcpdump code did.
*
* FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound
* packets and 0 for inbound packets - but only if the
* protocol field has the 0x8000 bit set (i.e., it's a network
* control protocol); it does so before running the packet through
* "bpf_filter" to see if it should be discarded, and to see
* if we should update the time we sent the most recent packet...
*
* ...but it puts the original address field back after doing
* so.
*
* NetBSD's "if_ppp.c" doesn't set the first octet in that fashion.
*
* I don't know if any PPP implementation handed up to a BPF
* device packets with the first octet being 1 for outbound and
* 0 for inbound packets, so I (guy@alum.mit.edu) don't know
* whether that ever needs to be checked or not.
*
* Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP,
* and its tcpdump appears to assume that the frame always
* begins with an address field and a control field, and that
* the address field might be 0x0f or 0x8f, for Cisco
* point-to-point with HDLC framing as per section 4.3.1 of RFC
* 1547, as well as 0xff, for PPP in HDLC-like framing as per
* RFC 1662.
*
* (Is the Cisco framing in question what DLT_C_HDLC, in
* BSD/OS, is?)
*/
if (eflag)
printf("%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1]);
#endif
ppp_print(p, length);
return (0);
}
/*
* PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like
* framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547,
* is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL,
* discard them *if* those are the first two octets, and parse the remaining
* packet as a PPP packet, as "ppp_print()" does).
*
* This handles, for example, DLT_PPP_SERIAL in NetBSD.
*/
u_int
ppp_hdlc_if_print(const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int proto;
u_int hdrlen = 0;
if (caplen < 2) {
printf("[|ppp]");
return (caplen);
}
switch (p[0]) {
case PPP_ADDRESS:
if (caplen < 4) {
printf("[|ppp]");
return (caplen);
}
if (eflag)
printf("%02x %02x %d ", p[0], p[1], length);
p += 2;
length -= 2;
hdrlen += 2;
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdrlen += 2;
printf("%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto));
handle_ppp(proto, p, length);
break;
case CHDLC_UNICAST:
case CHDLC_BCAST:
return (chdlc_if_print(h, p));
default:
if (eflag)
printf("%02x %02x %d ", p[0], p[1], length);
p += 2;
length -= 2;
hdrlen += 2;
/*
* XXX - NetBSD's "<API key>()" treats
* the next two octets as an Ethernet type; does that
* ever happen?
*/
printf("unknown addr %02x; ctrl %02x", p[0], p[1]);
break;
}
return (hdrlen);
}
#define PPP_BSDI_HDRLEN 24
/* BSD/OS specific PPP printer */
u_int
ppp_bsdos_if_print(const struct pcap_pkthdr *h _U_, register const u_char *p _U_)
{
register int hdrlength;
#ifdef __bsdi__
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int16_t ptype;
const u_char *q;
int i;
if (caplen < PPP_BSDI_HDRLEN) {
printf("[|ppp]");
return (caplen)
}
hdrlength = 0;
#if 0
if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) {
if (eflag)
printf("%02x %02x ", p[0], p[1]);
p += 2;
hdrlength = 2;
}
if (eflag)
printf("%d ", length);
/* Retrieve the protocol type */
if (*p & 01) {
/* Compressed protocol field */
ptype = *p;
if (eflag)
printf("%02x ", ptype);
p++;
hdrlength += 1;
} else {
/* Un-compressed protocol field */
ptype = EXTRACT_16BITS(p);
if (eflag)
printf("%04x ", ptype);
p += 2;
hdrlength += 2;
}
#else
ptype = 0; /*XXX*/
if (eflag)
printf("%c ", p[SLC_DIR] ? 'O' : 'I');
if (p[SLC_LLHL]) {
/* link level header */
struct ppp_header *ph;
q = p + SLC_BPFHDRLEN;
ph = (struct ppp_header *)q;
if (ph->phdr_addr == PPP_ADDRESS
&& ph->phdr_ctl == PPP_CONTROL) {
if (eflag)
printf("%02x %02x ", q[0], q[1]);
ptype = EXTRACT_16BITS(&ph->phdr_type);
if (eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) {
printf("%s ", tok2str(ppptype2str,
"proto-#%d", ptype));
}
} else {
if (eflag) {
printf("LLH=[");
for (i = 0; i < p[SLC_LLHL]; i++)
printf("%02x", q[i]);
printf("] ");
}
}
}
if (eflag)
printf("%d ", length);
if (p[SLC_CHL]) {
q = p + SLC_BPFHDRLEN + p[SLC_LLHL];
switch (ptype) {
case PPP_VJC:
ptype = vjc_print(q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
#ifdef INET6
case PPP_IPV6:
ip6_print(p, length);
break;
#endif
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(p, length);
break;
}
goto printx;
case PPP_VJNC:
ptype = vjc_print(q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
#ifdef INET6
case PPP_IPV6:
ip6_print(p, length);
break;
#endif
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(p, length);
break;
}
goto printx;
default:
if (eflag) {
printf("CH=[");
for (i = 0; i < p[SLC_LLHL]; i++)
printf("%02x", q[i]);
printf("] ");
}
break;
}
}
hdrlength = PPP_BSDI_HDRLEN;
#endif
length -= hdrlength;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
#ifdef INET6
case PPP_IPV6:
ip6_print(p, length);
break;
#endif
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(p, length);
break;
default:
printf("%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype));
}
printx:
#else /* __bsdi */
hdrlength = 0;
#endif /* __bsdi__ */
return (hdrlength);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/ |
package test
import (
"io"
"time"
"github.com/openshift/library-go/pkg/git"
)
type FakeGit struct {
RootDir string
GitURL string
Ref string
CloneCalled bool
CheckoutCalled bool
<API key> bool
}
func (g *FakeGit) GetRootDir(dir string) (string, error) {
return g.RootDir, nil
}
func (g *FakeGit) GetOriginURL(dir string) (string, bool, error) {
return g.GitURL, true, nil
}
func (g *FakeGit) GetRef(dir string) string {
return g.Ref
}
func (g *FakeGit) Clone(dir string, url string) error {
g.CloneCalled = true
return nil
}
func (g *FakeGit) CloneWithOptions(dir string, url string, args ...string) error {
g.CloneCalled = true
return nil
}
func (g *FakeGit) CloneBare(dir string, url string) error {
g.CloneCalled = true
return nil
}
func (g *FakeGit) CloneMirror(source, target string) error {
return nil
}
func (g *FakeGit) Checkout(dir string, ref string) error {
g.CheckoutCalled = true
return nil
}
func (g *FakeGit) SubmoduleUpdate(dir string, init, recurse bool) error {
g.<API key> = true
return nil
}
func (f *FakeGit) Fetch(source string) error {
return nil
}
func (f *FakeGit) Init(source string, _ bool) error {
return nil
}
func (f *FakeGit) AddLocalConfig(source, key, value string) error {
return nil
}
func (f *FakeGit) Archive(source, ref, format string, w io.Writer) error {
return nil
}
func (f *FakeGit) AddRemote(source, remote, url string) error {
return nil
}
func (f *FakeGit) ShowFormat(source, ref, format string) (string, error) {
return "", nil
}
func (f *FakeGit) ListRemote(url string, args ...string) (string, string, error) {
return "", "", nil
}
func (f *FakeGit) TimedListRemote(timeout time.Duration, url string, args ...string) (string, string, error) {
return "", "", nil
}
func (f *FakeGit) GetInfo(location string) (*git.SourceInfo, []error) {
return nil, nil
}
func (f *FakeGit) Add(location string, spec string) error {
return nil
}
func (f *FakeGit) Commit(location string, message string) error {
return nil
} |
# The Python Imaging Library.
# XPM File handling
# History:
# 1996-12-29 fl Created
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
import re
from . import Image, ImageFile, ImagePalette
from ._binary import i8, o8
__version__ = "0.2"
# XPM header
xpm_head = re.compile(b"\"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)")
def _accept(prefix):
return prefix[:9] == b"/* XPM */"
# Image plugin for X11 pixel maps.
class XpmImageFile(ImageFile.ImageFile):
format = "XPM"
format_description = "X11 Pixel Map"
def _open(self):
if not _accept(self.fp.read(9)):
raise SyntaxError("not an XPM file")
# skip forward to next string
while True:
s = self.fp.readline()
if not s:
raise SyntaxError("broken XPM file")
m = xpm_head.match(s)
if m:
break
self.size = int(m.group(1)), int(m.group(2))
pal = int(m.group(3))
bpp = int(m.group(4))
if pal > 256 or bpp != 1:
raise ValueError("cannot read this XPM file")
# load palette description
palette = [b"\0\0\0"] * 256
for i in range(pal):
s = self.fp.readline()
if s[-2:] == b'\r\n':
s = s[:-2]
elif s[-1:] in b'\r\n':
s = s[:-1]
c = i8(s[1])
s = s[2:-2].split()
for i in range(0, len(s), 2):
if s[i] == b"c":
# process colour key
rgb = s[i+1]
if rgb == b"None":
self.info["transparency"] = c
elif rgb[0:1] == b"
# FIXME: handle colour names (see ImagePalette.py)
rgb = int(rgb[1:], 16)
palette[c] = (o8((rgb >> 16) & 255) +
o8((rgb >> 8) & 255) +
o8(rgb & 255))
else:
# unknown colour
raise ValueError("cannot read this XPM file")
break
else:
# missing colour key
raise ValueError("cannot read this XPM file")
self.mode = "P"
self.palette = ImagePalette.raw("RGB", b"".join(palette))
self.tile = [("raw", (0, 0)+self.size, self.fp.tell(), ("P", 0, 1))]
def load_read(self, bytes):
# load all image data in one chunk
xsize, ysize = self.size
s = [None] * ysize
for i in range(ysize):
s[i] = self.fp.readline()[1:xsize+1].ljust(xsize)
return b"".join(s)
# Registry
Image.register_open(XpmImageFile.format, XpmImageFile, _accept)
Image.register_extension(XpmImageFile.format, ".xpm")
Image.register_mime(XpmImageFile.format, "image/xpm") |
// Generated source.
// Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator
// Origin: http://src.chromium.org/blink/trunk/Source/devtools/protocol.json@150309 with change #14672031
package org.chromium.sdk.internal.wip.protocol.output.debugger;
/**
Always returns true.
*/
public class <API key> extends org.chromium.sdk.internal.wip.protocol.output.<API key><org.chromium.sdk.internal.wip.protocol.input.debugger.<API key>> {
public <API key>() {
}
public static final String METHOD_NAME = org.chromium.sdk.internal.wip.protocol.BasicConstants.Domain.DEBUGGER + ".canSetScriptSource";
@Override protected String getRequestName() {
return METHOD_NAME;
}
@Override public org.chromium.sdk.internal.wip.protocol.input.debugger.<API key> parseResponse(org.chromium.sdk.internal.wip.protocol.input.WipCommandResponse.Data data, org.chromium.sdk.internal.wip.protocol.input.<API key> parser) throws org.chromium.sdk.internal.protocolparser.<API key> {
return parser.<API key>(data.getUnderlyingObject());
}
} |
// ATMEL Microcontroller Software Support - ROUSSET -
// kind, either express, implied or statutory. This includes without
// fitness for any particular purpose, or against the infringements of
// intellectual property rights of others.
// File Name : AT91R40008.h
// Object : AT91R40008 definitions
// Generated : AT91 SW Application Group 02/19/2003 (11:13:31)
// CVS Reference : /AT91R40008.pl/1.3/Tue Nov 12 16:01:52 2002//
// CVS Reference : /AIC_1246F.pl/1.4/Mon Nov 04 17:51:00 2002//
// CVS Reference : /WD_1241B.pl/1.1/Mon Nov 04 17:51:00 2002//
// CVS Reference : /PS_x40.pl/1.2/Tue Nov 12 16:01:52 2002//
// CVS Reference : /PIO_1321C.pl/1.5/Tue Oct 29 15:50:24 2002//
// CVS Reference : /TC_1243B.pl/1.4/Tue Nov 05 12:43:10 2002//
// CVS Reference : /PDC_1363D.pl/1.3/Wed Oct 23 14:49:48 2002//
// CVS Reference : /US_1242E.pl/1.5/Thu Nov 21 13:37:56 2002//
// CVS Reference : /SF_x40.pl/1.1/Tue Nov 12 13:27:20 2002//
// CVS Reference : /EBI_x40.pl/1.5/Wed Feb 19 09:25:22 2003//
#ifndef AT91R40008_H
#define AT91R40008_H
/* AT91 Register type */
typedef volatile unsigned int AT91_REG; // Hardware register definition
typedef volatile unsigned int at91_reg;
// SOFTWARE API DEFINITION FOR Advanced Interrupt Controller
typedef struct _AT91S_AIC {
AT91_REG AIC_SMR[32]; // Source Mode egister
AT91_REG AIC_SVR[32]; // Source Vector egister
AT91_REG AIC_IVR; // IRQ Vector Register
AT91_REG AIC_FVR; // FIQ Vector Register
AT91_REG AIC_ISR; // Interrupt Status Register
AT91_REG AIC_IPR; // Interrupt Pending Register
AT91_REG AIC_IMR; // Interrupt Mask Register
AT91_REG AIC_CISR; // Core Interrupt Status Register
AT91_REG Reserved0[2];
AT91_REG AIC_IECR; // Interrupt Enable Command Register
AT91_REG AIC_IDCR; // Interrupt Disable Command egister
AT91_REG AIC_ICCR; // Interrupt Clear Command Register
AT91_REG AIC_ISCR; // Interrupt Set Command Register
AT91_REG AIC_EOICR; // End of Interrupt Command Register
AT91_REG AIC_SPU; // Spurious Vector Register
} AT91S_AIC, *AT91PS_AIC;
#define AT91C_AIC_PRIOR ((unsigned int) 0x7 << 0) // (AIC) Priority Level
#define <API key> ((unsigned int) 0x0) // (AIC) Lowest priority level
#define <API key> ((unsigned int) 0x7) // (AIC) Highest priority level
#define AT91C_AIC_SRCTYPE ((unsigned int) 0x3 << 5) // (AIC) Interrupt Source Type
#define <API key> ((unsigned int) 0x0 << 5) // (AIC) Internal Sources Code Label Level Sensitive
#define <API key> ((unsigned int) 0x1 << 5) // (AIC) Internal Sources Code Label Edge triggered
#define <API key> ((unsigned int) 0x2 << 5) // (AIC) External Sources Code Label High-level Sensitive
#define <API key> ((unsigned int) 0x3 << 5) // (AIC) External Sources Code Label Positive Edge triggered
#define AT91C_AIC_NFIQ ((unsigned int) 0x1 << 0) // (AIC) NFIQ Status
#define AT91C_AIC_NIRQ ((unsigned int) 0x1 << 1) // (AIC) NIRQ Status
// SOFTWARE API DEFINITION FOR Watchdog Timer Interface
typedef struct _AT91S_WD {
AT91_REG WD_OMR; // Overflow Mode Register
AT91_REG WD_CMR; // Clock Mode Register
AT91_REG WD_CR; // Control Register
AT91_REG WD_SR; // Status Register
} AT91S_WD, *AT91PS_WD;
#define AT91C_WD_WDEN ((unsigned int) 0x1 << 0) // (WD) Watchdog Enable
#define AT91C_WD_RSTEN ((unsigned int) 0x1 << 1) // (WD) Reset Enable
#define AT91C_WD_IRQEN ((unsigned int) 0x1 << 2) // (WD) Interrupt Enable
#define AT91C_WD_EXTEN ((unsigned int) 0x1 << 3) // (WD) External Signal Enable
#define AT91C_WD_OKEY ((unsigned int) 0xFFF << 4) // (WD) Watchdog Enable
#define AT91C_WD_WDCLKS ((unsigned int) 0x3 << 0) // (WD) Clock Selection
#define <API key> ((unsigned int) 0x0) // (WD) Master Clock divided by 32
#define <API key> ((unsigned int) 0x1) // (WD) Master Clock divided by 128
#define <API key> ((unsigned int) 0x2) // (WD) Master Clock divided by 1024
#define <API key> ((unsigned int) 0x3) // (WD) Master Clock divided by 4096
#define AT91C_WD_HPCV ((unsigned int) 0xF << 2) // (WD) High Pre-load Counter Value
#define AT91C_WD_CKEY ((unsigned int) 0x1FF << 7) // (WD) Clock Access Key
#define AT91C_WD_RSTKEY ((unsigned int) 0xFFFF << 0) // (WD) Restart Key
#define AT91C_WD_WDOVF ((unsigned int) 0x1 << 0) // (WD) Watchdog Overflow
// SOFTWARE API DEFINITION FOR Power Saving Controler
typedef struct _AT91S_PS {
AT91_REG PS_CR; // Control Register
AT91_REG PS_PCER; // Peripheral Clock Enable Register
AT91_REG PS_PCDR; // Peripheral Clock Disable Register
AT91_REG PS_PCSR; // Peripheral Clock Status Register
} AT91S_PS, *AT91PS_PS;
#define AT91C_PS_US0 ((unsigned int) 0x1 << 2) // (PS) Usart 0 Clock
#define AT91C_PS_US1 ((unsigned int) 0x1 << 3) // (PS) Usart 1 Clock
#define AT91C_PS_TC0 ((unsigned int) 0x1 << 4) // (PS) Timer Counter 0 Clock
#define AT91C_PS_TC1 ((unsigned int) 0x1 << 5) // (PS) Timer Counter 1 Clock
#define AT91C_PS_TC2 ((unsigned int) 0x1 << 6) // (PS) Timer Counter 2 Clock
#define AT91C_PS_PIO ((unsigned int) 0x1 << 8) // (PS) PIO Clock
// SOFTWARE API DEFINITION FOR Parallel Input Output Controler
typedef struct _AT91S_PIO {
AT91_REG PIO_PER; // PIO Enable Register
AT91_REG PIO_PDR; // PIO Disable Register
AT91_REG PIO_PSR; // PIO Status Register
AT91_REG Reserved0[1];
AT91_REG PIO_OER; // Output Enable Register
AT91_REG PIO_ODR; // Output Disable Registerr
AT91_REG PIO_OSR; // Output Status Register
AT91_REG Reserved1[1];
AT91_REG PIO_IFER; // Input Filter Enable Register
AT91_REG PIO_IFDR; // Input Filter Disable Register
AT91_REG PIO_IFSR; // Input Filter Status Register
AT91_REG Reserved2[1];
AT91_REG PIO_SODR; // Set Output Data Register
AT91_REG PIO_CODR; // Clear Output Data Register
AT91_REG PIO_ODSR; // Output Data Status Register
AT91_REG PIO_PDSR; // Pin Data Status Register
AT91_REG PIO_IER; // Interrupt Enable Register
AT91_REG PIO_IDR; // Interrupt Disable Register
AT91_REG PIO_IMR; // Interrupt Mask Register
AT91_REG PIO_ISR; // Interrupt Status Register
AT91_REG PIO_MDER; // Multi-driver Enable Register
AT91_REG PIO_MDDR; // Multi-driver Disable Register
AT91_REG PIO_MDSR; // Multi-driver Status Register
} AT91S_PIO, *AT91PS_PIO;
// SOFTWARE API DEFINITION FOR Timer Counter Channel Interface
typedef struct _AT91S_TC {
AT91_REG TC_CCR; // Channel Control Register
AT91_REG TC_CMR; // Channel Mode Register
AT91_REG Reserved0[2];
AT91_REG TC_CV; // Counter Value
AT91_REG TC_RA; // Register A
AT91_REG TC_RB; // Register B
AT91_REG TC_RC; // Register C
AT91_REG TC_SR; // Status Register
AT91_REG TC_IER; // Interrupt Enable Register
AT91_REG TC_IDR; // Interrupt Disable Register
AT91_REG TC_IMR; // Interrupt Mask Register
} AT91S_TC, *AT91PS_TC;
#define AT91C_TC_CLKEN ((unsigned int) 0x1 << 0) // (TC) Counter Clock Enable Command
#define AT91C_TC_CLKDIS ((unsigned int) 0x1 << 1) // (TC) Counter Clock Disable Command
#define AT91C_TC_SWTRG ((unsigned int) 0x1 << 2) // (TC) Software Trigger Command
#define AT91C_TC_CPCSTOP ((unsigned int) 0x1 << 6) // (TC) Counter Clock Stopped with RC Compare
#define AT91C_TC_CPCDIS ((unsigned int) 0x1 << 7) // (TC) Counter Clock Disable with RC Compare
#define AT91C_TC_EEVTEDG ((unsigned int) 0x3 << 8) // (TC) External Event Edge Selection
#define <API key> ((unsigned int) 0x0 << 8) // (TC) Edge: None
#define <API key> ((unsigned int) 0x1 << 8) // (TC) Edge: rising edge
#define <API key> ((unsigned int) 0x2 << 8) // (TC) Edge: falling edge
#define <API key> ((unsigned int) 0x3 << 8) // (TC) Edge: each edge
#define AT91C_TC_EEVT ((unsigned int) 0x3 << 10) // (TC) External Event Selection
#define AT91C_TC_EEVT_NONE ((unsigned int) 0x0 << 10) // (TC) Signal selected as external event: TIOB TIOB direction: input
#define <API key> ((unsigned int) 0x1 << 10) // (TC) Signal selected as external event: XC0 TIOB direction: output
#define <API key> ((unsigned int) 0x2 << 10) // (TC) Signal selected as external event: XC1 TIOB direction: output
#define AT91C_TC_EEVT_BOTH ((unsigned int) 0x3 << 10) // (TC) Signal selected as external event: XC2 TIOB direction: output
#define AT91C_TC_ENETRG ((unsigned int) 0x1 << 12) // (TC) External Event Trigger enable
#define AT91C_TC_WAVESEL ((unsigned int) 0x3 << 13) // (TC) Waveform Selection
#define AT91C_TC_WAVESEL_UP ((unsigned int) 0x0 << 13) // (TC) UP mode without atomatic trigger on RC Compare
#define <API key> ((unsigned int) 0x1 << 13) // (TC) UP mode with automatic trigger on RC Compare
#define <API key> ((unsigned int) 0x2 << 13) // (TC) UPDOWN mode without automatic trigger on RC Compare
#define <API key> ((unsigned int) 0x3 << 13) // (TC) UPDOWN mode with automatic trigger on RC Compare
#define AT91C_TC_CPCTRG ((unsigned int) 0x1 << 14) // (TC) RC Compare Trigger Enable
#define AT91C_TC_WAVE ((unsigned int) 0x1 << 15)
#define AT91C_TC_ACPA ((unsigned int) 0x3 << 16) // (TC) RA Compare Effect on TIOA
#define AT91C_TC_ACPA_NONE ((unsigned int) 0x0 << 16) // (TC) Effect: none
#define AT91C_TC_ACPA_SET ((unsigned int) 0x1 << 16) // (TC) Effect: set
#define AT91C_TC_ACPA_CLEAR ((unsigned int) 0x2 << 16) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 16) // (TC) Effect: toggle
#define AT91C_TC_ACPC ((unsigned int) 0x3 << 18) // (TC) RC Compare Effect on TIOA
#define AT91C_TC_ACPC_NONE ((unsigned int) 0x0 << 18) // (TC) Effect: none
#define AT91C_TC_ACPC_SET ((unsigned int) 0x1 << 18) // (TC) Effect: set
#define AT91C_TC_ACPC_CLEAR ((unsigned int) 0x2 << 18) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 18) // (TC) Effect: toggle
#define AT91C_TC_AEEVT ((unsigned int) 0x3 << 20) // (TC) External Event Effect on TIOA
#define AT91C_TC_AEEVT_NONE ((unsigned int) 0x0 << 20) // (TC) Effect: none
#define AT91C_TC_AEEVT_SET ((unsigned int) 0x1 << 20) // (TC) Effect: set
#define <API key> ((unsigned int) 0x2 << 20) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 20) // (TC) Effect: toggle
#define AT91C_TC_ASWTRG ((unsigned int) 0x3 << 22) // (TC) Software Trigger Effect on TIOA
#define <API key> ((unsigned int) 0x0 << 22) // (TC) Effect: none
#define AT91C_TC_ASWTRG_SET ((unsigned int) 0x1 << 22) // (TC) Effect: set
#define <API key> ((unsigned int) 0x2 << 22) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 22) // (TC) Effect: toggle
#define AT91C_TC_BCPB ((unsigned int) 0x3 << 24) // (TC) RB Compare Effect on TIOB
#define AT91C_TC_BCPB_NONE ((unsigned int) 0x0 << 24) // (TC) Effect: none
#define AT91C_TC_BCPB_SET ((unsigned int) 0x1 << 24) // (TC) Effect: set
#define AT91C_TC_BCPB_CLEAR ((unsigned int) 0x2 << 24) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 24) // (TC) Effect: toggle
#define AT91C_TC_BCPC ((unsigned int) 0x3 << 26) // (TC) RC Compare Effect on TIOB
#define AT91C_TC_BCPC_NONE ((unsigned int) 0x0 << 26) // (TC) Effect: none
#define AT91C_TC_BCPC_SET ((unsigned int) 0x1 << 26) // (TC) Effect: set
#define AT91C_TC_BCPC_CLEAR ((unsigned int) 0x2 << 26) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 26) // (TC) Effect: toggle
#define AT91C_TC_BEEVT ((unsigned int) 0x3 << 28) // (TC) External Event Effect on TIOB
#define AT91C_TC_BEEVT_NONE ((unsigned int) 0x0 << 28) // (TC) Effect: none
#define AT91C_TC_BEEVT_SET ((unsigned int) 0x1 << 28) // (TC) Effect: set
#define <API key> ((unsigned int) 0x2 << 28) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 28) // (TC) Effect: toggle
#define AT91C_TC_BSWTRG ((unsigned int) 0x3 << 30) // (TC) Software Trigger Effect on TIOB
#define <API key> ((unsigned int) 0x0 << 30) // (TC) Effect: none
#define AT91C_TC_BSWTRG_SET ((unsigned int) 0x1 << 30) // (TC) Effect: set
#define <API key> ((unsigned int) 0x2 << 30) // (TC) Effect: clear
#define <API key> ((unsigned int) 0x3 << 30) // (TC) Effect: toggle
#define AT91C_TC_COVFS ((unsigned int) 0x1 << 0) // (TC) Counter Overflow
#define AT91C_TC_LOVRS ((unsigned int) 0x1 << 1) // (TC) Load Overrun
#define AT91C_TC_CPAS ((unsigned int) 0x1 << 2) // (TC) RA Compare
#define AT91C_TC_CPBS ((unsigned int) 0x1 << 3) // (TC) RB Compare
#define AT91C_TC_CPCS ((unsigned int) 0x1 << 4) // (TC) RC Compare
#define AT91C_TC_LDRAS ((unsigned int) 0x1 << 5) // (TC) RA Loading
#define AT91C_TC_LDRBS ((unsigned int) 0x1 << 6) // (TC) RB Loading
#define AT91C_TC_ETRCS ((unsigned int) 0x1 << 7) // (TC) External Trigger
#define AT91C_TC_ETRGS ((unsigned int) 0x1 << 16) // (TC) Clock Enabling
#define AT91C_TC_MTIOA ((unsigned int) 0x1 << 17) // (TC) TIOA Mirror
#define AT91C_TC_MTIOB ((unsigned int) 0x1 << 18) // (TC) TIOA Mirror
// SOFTWARE API DEFINITION FOR Timer Counter Interface
typedef struct _AT91S_TCB {
AT91S_TC TCB_TC0; // TC Channel 0
AT91_REG Reserved0[4];
AT91S_TC TCB_TC1; // TC Channel 1
AT91_REG Reserved1[4];
AT91S_TC TCB_TC2; // TC Channel 2
AT91_REG Reserved2[4];
AT91_REG TCB_BCR; // TC Block Control Register
AT91_REG TCB_BMR; // TC Block Mode Register
} AT91S_TCB, *AT91PS_TCB;
#define AT91C_TCB_SYNC ((unsigned int) 0x1 << 0) // (TCB) Synchro Command
#define AT91C_TCB_TC0XC0S ((unsigned int) 0x1 << 0) // (TCB) External Clock Signal 0 Selection
#define <API key> ((unsigned int) 0x0) // (TCB) TCLK0 connected to XC0
#define <API key> ((unsigned int) 0x1) // (TCB) None signal connected to XC0
#define <API key> ((unsigned int) 0x2) // (TCB) TIOA1 connected to XC0
#define <API key> ((unsigned int) 0x3) // (TCB) TIOA2 connected to XC0
#define AT91C_TCB_TC1XC1S ((unsigned int) 0x1 << 2) // (TCB) External Clock Signal 1 Selection
#define <API key> ((unsigned int) 0x0 << 2) // (TCB) TCLK1 connected to XC1
#define <API key> ((unsigned int) 0x1 << 2) // (TCB) None signal connected to XC1
#define <API key> ((unsigned int) 0x2 << 2) // (TCB) TIOA0 connected to XC1
#define <API key> ((unsigned int) 0x3 << 2) // (TCB) TIOA2 connected to XC1
#define AT91C_TCB_TC2XC2S ((unsigned int) 0x1 << 4) // (TCB) External Clock Signal 2 Selection
#define <API key> ((unsigned int) 0x0 << 4) // (TCB) TCLK2 connected to XC2
#define <API key> ((unsigned int) 0x1 << 4) // (TCB) None signal connected to XC2
#define <API key> ((unsigned int) 0x2 << 4) // (TCB) TIOA0 connected to XC2
#define <API key> ((unsigned int) 0x3 << 4) // (TCB) TIOA2 connected to XC2
// SOFTWARE API DEFINITION FOR Peripheral Data Controller
typedef struct _AT91S_PDC {
AT91_REG PDC_RPR; // Receive Pointer Register
AT91_REG PDC_RCR; // Receive Counter Register
AT91_REG PDC_TPR; // Transmit Pointer Register
AT91_REG PDC_TCR; // Transmit Counter Register
} AT91S_PDC, *AT91PS_PDC;
// SOFTWARE API DEFINITION FOR Usart
typedef struct _AT91S_USART {
AT91_REG US_CR; // Control Register
AT91_REG US_MR; // Mode Register
AT91_REG US_IER; // Interrupt Enable Register
AT91_REG US_IDR; // Interrupt Disable Register
AT91_REG US_IMR; // Interrupt Mask Register
AT91_REG US_CSR; // Channel Status Register
AT91_REG US_RHR; // Receiver Holding Register
AT91_REG US_THR; // Transmitter Holding Register
AT91_REG US_BRGR; // Baud Rate Generator Register
AT91_REG US_RTOR; // Receiver Time-out Register
AT91_REG US_TTGR; // Transmitter Time-guard Register
AT91_REG Reserved0[1];
AT91_REG US_RPR; // Receive Pointer Register
AT91_REG US_RCR; // Receive Counter Register
AT91_REG US_TPR; // Transmit Pointer Register
AT91_REG US_TCR; // Transmit Counter Register
} AT91S_USART, *AT91PS_USART;
#define AT91C_US_RSTRX ((unsigned int) 0x1 << 2) // (USART) Reset Receiver
#define AT91C_US_RSTTX ((unsigned int) 0x1 << 3) // (USART) Reset Transmitter
#define AT91C_US_RXEN ((unsigned int) 0x1 << 4) // (USART) Receiver Enable
#define AT91C_US_RXDIS ((unsigned int) 0x1 << 5) // (USART) Receiver Disable
#define AT91C_US_TXEN ((unsigned int) 0x1 << 6) // (USART) Transmitter Enable
#define AT91C_US_TXDIS ((unsigned int) 0x1 << 7) // (USART) Transmitter Disable
#define AT91C_US_RSTSTA ((unsigned int) 0x1 << 8) // (USART) Reset Status Bits
#define AT91C_US_STTBRK ((unsigned int) 0x1 << 9) // (USART) Start Break
#define AT91C_US_STPBRK ((unsigned int) 0x1 << 10) // (USART) Stop Break
#define AT91C_US_STTTO ((unsigned int) 0x1 << 11) // (USART) Start Time-out
#define AT91C_US_SENDA ((unsigned int) 0x1 << 12) // (USART) Send Address
#define AT91C_US_CLKS ((unsigned int) 0x3 << 4) // (USART) Clock Selection (Baud Rate generator Input Clock
#define AT91C_US_CLKS_CLOCK ((unsigned int) 0x0 << 4) // (USART) Clock
#define AT91C_US_CLKS_FDIV1 ((unsigned int) 0x1 << 4) // (USART) fdiv1
#define AT91C_US_CLKS_SLOW ((unsigned int) 0x2 << 4) // (USART) slow_clock (ARM)
#define AT91C_US_CLKS_EXT ((unsigned int) 0x3 << 4) // (USART) External (SCK)
#define AT91C_US_CHRL ((unsigned int) 0x3 << 6) // (USART) Clock Selection (Baud Rate generator Input Clock
#define <API key> ((unsigned int) 0x0 << 6) // (USART) Character Length: 5 bits
#define <API key> ((unsigned int) 0x1 << 6) // (USART) Character Length: 6 bits
#define <API key> ((unsigned int) 0x2 << 6) // (USART) Character Length: 7 bits
#define <API key> ((unsigned int) 0x3 << 6) // (USART) Character Length: 8 bits
#define AT91C_US_SYNC ((unsigned int) 0x1 << 8) // (USART) Synchronous Mode Select
#define AT91C_US_PAR ((unsigned int) 0x7 << 9) // (USART) Parity type
#define AT91C_US_PAR_EVEN ((unsigned int) 0x0 << 9) // (USART) Even Parity
#define AT91C_US_PAR_ODD ((unsigned int) 0x1 << 9) // (USART) Odd Parity
#define AT91C_US_PAR_SPACE ((unsigned int) 0x2 << 9) // (USART) Parity forced to 0 (Space)
#define AT91C_US_PAR_MARK ((unsigned int) 0x3 << 9) // (USART) Parity forced to 1 (Mark)
#define AT91C_US_PAR_NONE ((unsigned int) 0x4 << 9) // (USART) No Parity
#define <API key> ((unsigned int) 0x6 << 9) // (USART) Multi-drop mode
#define AT91C_US_NBSTOP ((unsigned int) 0x3 << 12) // (USART) Number of Stop bits
#define <API key> ((unsigned int) 0x0 << 12) // (USART) 1 stop bit
#define <API key> ((unsigned int) 0x1 << 12) // (USART) Asynchronous (SYNC=0) 2 stop bits Synchronous (SYNC=1) 2 stop bits
#define <API key> ((unsigned int) 0x2 << 12) // (USART) 2 stop bits
#define AT91C_US_CHMODE ((unsigned int) 0x3 << 14) // (USART) Channel Mode
#define <API key> ((unsigned int) 0x0 << 14) // (USART) Normal Mode: The USART channel operates as an RX/TX USART.
#define <API key> ((unsigned int) 0x1 << 14) // (USART) Automatic Echo: Receiver Data Input is connected to the TXD pin.
#define <API key> ((unsigned int) 0x2 << 14) // (USART) Local Loopback: Transmitter Output Signal is connected to Receiver Input Signal.
#define <API key> ((unsigned int) 0x3 << 14) // (USART) Remote Loopback: RXD pin is internally connected to TXD pin.
#define AT91C_US_MODE9 ((unsigned int) 0x1 << 17) // (USART) 9-bit Character length
#define AT91C_US_CKLO ((unsigned int) 0x1 << 18) // (USART) Clock Output Select
#define AT91C_US_RXRDY ((unsigned int) 0x1 << 0) // (USART) RXRDY Interrupt
#define AT91C_US_TXRDY ((unsigned int) 0x1 << 1) // (USART) TXRDY Interrupt
#define AT91C_US_RXBRK ((unsigned int) 0x1 << 2) // (USART) Break Received/End of Break
#define AT91C_US_ENDRX ((unsigned int) 0x1 << 3) // (USART) End of Receive Transfer Interrupt
#define AT91C_US_ENDTX ((unsigned int) 0x1 << 4) // (USART) End of Transmit Interrupt
#define AT91C_US_OVRE ((unsigned int) 0x1 << 5) // (USART) Overrun Interrupt
#define AT91C_US_FRAME ((unsigned int) 0x1 << 6) // (USART) Framing Error Interrupt
#define AT91C_US_PARE ((unsigned int) 0x1 << 7) // (USART) Parity Error Interrupt
#define AT91C_US_TIMEOUT ((unsigned int) 0x1 << 8) // (USART) Receiver Time-out
#define AT91C_US_TXEMPTY ((unsigned int) 0x1 << 9) // (USART) TXEMPTY Interrupt
// SOFTWARE API DEFINITION FOR Special Function Interface
typedef struct _AT91S_SF {
AT91_REG SF_CIDR; // Chip ID Register
AT91_REG SF_EXID; // Chip ID Extension Register
AT91_REG SF_RSR; // Reset Status Register
AT91_REG SF_MMR; // Memory Mode Register
AT91_REG Reserved0[2];
AT91_REG SF_PMR; // Protect Mode Register
} AT91S_SF, *AT91PS_SF;
#define AT91C_SF_VERSION ((unsigned int) 0x1F << 0) // (SF) Version of the chip
#define AT91C_SF_BIT5 ((unsigned int) 0x1 << 5) // (SF) Hardwired at 0
#define AT91C_SF_BIT6 ((unsigned int) 0x1 << 6) // (SF) Hardwired at 1
#define AT91C_SF_BIT7 ((unsigned int) 0x1 << 7) // (SF) Hardwired at 0
#define AT91C_SF_NVPSIZ ((unsigned int) 0xF << 8) // (SF) Nonvolatile Program Memory Size
#define <API key> ((unsigned int) 0x0 << 8) // (SF) None
#define AT91C_SF_NVPSIZ_32K ((unsigned int) 0x3 << 8) // (SF) 32K Bytes
#define AT91C_SF_NVPSIZ_64K ((unsigned int) 0x5 << 8) // (SF) 64K Bytes
#define <API key> ((unsigned int) 0x7 << 8) // (SF) 128K Bytes
#define <API key> ((unsigned int) 0x11 << 8) // (SF) 256K Bytes
#define AT91C_SF_NVDSIZ ((unsigned int) 0xF << 12) // (SF) Nonvolatile Data Memory Size
#define <API key> ((unsigned int) 0x0 << 12) // (SF) None
#define AT91C_SF_VDSIZ ((unsigned int) 0xF << 16) // (SF) Volatile Data Memory Size
#define AT91C_SF_VDSIZ_NONE ((unsigned int) 0x0 << 16) // (SF) None
#define AT91C_SF_VDSIZ_1K ((unsigned int) 0x3 << 16) // (SF) 1K Bytes
#define AT91C_SF_VDSIZ_2K ((unsigned int) 0x5 << 16) // (SF) 2K Bytes
#define AT91C_SF_VDSIZ_4K ((unsigned int) 0x7 << 16) // (SF) 4K Bytes
#define AT91C_SF_VDSIZ_8K ((unsigned int) 0x11 << 16) // (SF) 8K Bytes
#define AT91C_SF_ARCH ((unsigned int) 0xFF << 20) // (SF) Chip Architecture
#define <API key> ((unsigned int) 0x28 << 20) // (SF) AT91x40yyy
#define <API key> ((unsigned int) 0x37 << 20) // (SF) AT91x55yyy
#define <API key> ((unsigned int) 0x3F << 20) // (SF) AT91x63yyy
#define AT91C_SF_NVPTYP ((unsigned int) 0x7 << 28) // (SF) Nonvolatile Program Memory Type
#define <API key> ((unsigned int) 0x1 << 28) // (SF) 'M' Series or 'F' Series
#define <API key> ((unsigned int) 0x4 << 28) // (SF) 'R' Series
#define AT91C_SF_EXT ((unsigned int) 0x1 << 31) // (SF) Extension Flag
#define AT91C_SF_RESET ((unsigned int) 0xFF << 0) // (SF) Cause of Reset
#define AT91C_SF_RESET_WD ((unsigned int) 0x35) // (SF) Internal Watchdog
#define AT91C_SF_RESET_EXT ((unsigned int) 0x6C) // (SF) External Pin
#define AT91C_SF_RAMWU ((unsigned int) 0x1 << 0) // (SF) Internal Extended RAM Write Detection
#define AT91C_SF_AIC ((unsigned int) 0x1 << 5) // (SF) AIC Protect Mode Enable
#define AT91C_SF_PMRKEY ((unsigned int) 0xFFFF << 16) // (SF) Protect Mode Register Key
// SOFTWARE API DEFINITION FOR External Bus Interface
typedef struct _AT91S_EBI {
AT91_REG EBI_CSR[8]; // Chip-select Register
AT91_REG EBI_RCR; // Remap Control Register
AT91_REG EBI_MCR; // Memory Control Register
} AT91S_EBI, *AT91PS_EBI;
#define AT91C_EBI_DBW ((unsigned int) 0x3 << 0) // (EBI) Data Bus Width
#define AT91C_EBI_DBW_16 ((unsigned int) 0x1) // (EBI) 16-bit data bus width
#define AT91C_EBI_DBW_8 ((unsigned int) 0x2) // (EBI) 8-bit data bus width
#define AT91C_EBI_NWS ((unsigned int) 0x7 << 2) // (EBI) Number of wait states
#define AT91C_EBI_NWS_1 ((unsigned int) 0x0 << 2) // (EBI) 1 wait state
#define AT91C_EBI_NWS_2 ((unsigned int) 0x1 << 2) // (EBI) 2 wait state
#define AT91C_EBI_NWS_3 ((unsigned int) 0x2 << 2) // (EBI) 3 wait state
#define AT91C_EBI_NWS_4 ((unsigned int) 0x3 << 2) // (EBI) 4 wait state
#define AT91C_EBI_NWS_5 ((unsigned int) 0x4 << 2) // (EBI) 5 wait state
#define AT91C_EBI_NWS_6 ((unsigned int) 0x5 << 2) // (EBI) 6 wait state
#define AT91C_EBI_NWS_7 ((unsigned int) 0x6 << 2) // (EBI) 7 wait state
#define AT91C_EBI_NWS_8 ((unsigned int) 0x7 << 2) // (EBI) 8 wait state
#define AT91C_EBI_WSE ((unsigned int) 0x1 << 5) // (EBI) Wait State Enable
#define AT91C_EBI_PAGES ((unsigned int) 0x3 << 7) // (EBI) Pages Size
#define AT91C_EBI_PAGES_1M ((unsigned int) 0x0 << 7) // (EBI) 1M Byte
#define AT91C_EBI_PAGES_4M ((unsigned int) 0x1 << 7) // (EBI) 4M Byte
#define AT91C_EBI_PAGES_16M ((unsigned int) 0x2 << 7) // (EBI) 16M Byte
#define AT91C_EBI_PAGES_64M ((unsigned int) 0x3 << 7) // (EBI) 64M Byte
#define AT91C_EBI_TDF ((unsigned int) 0x7 << 9) // (EBI) Data Float Output Time
#define AT91C_EBI_TDF_0 ((unsigned int) 0x0 << 9) // (EBI) 1 TDF
#define AT91C_EBI_TDF_1 ((unsigned int) 0x1 << 9) // (EBI) 2 TDF
#define AT91C_EBI_TDF_2 ((unsigned int) 0x2 << 9) // (EBI) 3 TDF
#define AT91C_EBI_TDF_3 ((unsigned int) 0x3 << 9) // (EBI) 4 TDF
#define AT91C_EBI_TDF_4 ((unsigned int) 0x4 << 9) // (EBI) 5 TDF
#define AT91C_EBI_TDF_5 ((unsigned int) 0x5 << 9) // (EBI) 6 TDF
#define AT91C_EBI_TDF_6 ((unsigned int) 0x6 << 9) // (EBI) 7 TDF
#define AT91C_EBI_TDF_7 ((unsigned int) 0x7 << 9) // (EBI) 8 TDF
#define AT91C_EBI_BAT ((unsigned int) 0x1 << 12) // (EBI) Byte Access Type
#define AT91C_EBI_CSEN ((unsigned int) 0x1 << 13) // (EBI) Chip Select Enable
#define AT91C_EBI_BA ((unsigned int) 0xFFF << 20) // (EBI) Base Address
#define AT91C_EBI_RCB ((unsigned int) 0x1 << 0) // (EBI) 0 = No effect. 1 = Cancels the remapping (performed at reset) of the page zero memory devices.
#define AT91C_EBI_ALE ((unsigned int) 0x7 << 0) // (EBI) Address Line Enable
#define AT91C_EBI_ALE_16M ((unsigned int) 0x0) // (EBI) Valid Address Bits = A20, A21, A22, A23 Max Addressable Space = 16M Bytes Valid Chip Select=None
#define AT91C_EBI_ALE_8M ((unsigned int) 0x4) // (EBI) Valid Address Bits = A20, A21, A22 Max Addressable Space = 8M Bytes Valid Chip Select = CS4
#define AT91C_EBI_ALE_4M ((unsigned int) 0x5) // (EBI) Valid Address Bits = A20, A21 Max Addressable Space = 4M Bytes Valid Chip Select = CS4, CS5
#define AT91C_EBI_ALE_2M ((unsigned int) 0x6) // (EBI) Valid Address Bits = A20 Max Addressable Space = 2M Bytes Valid Chip Select = CS4, CS5, CS6
#define AT91C_EBI_ALE_1M ((unsigned int) 0x7) // (EBI) Valid Address Bits = None Max Addressable Space = 1M Byte Valid Chip Select = CS4, CS5, CS6, CS7
#define AT91C_EBI_DRP ((unsigned int) 0x1 << 4) // (EBI)
// REGISTER ADDRESS DEFINITION FOR AT91R40008
#define AT91C_AIC_EOICR ((AT91_REG *) 0xFFFFF130) // (AIC) End of Interrupt Command Register
#define AT91C_AIC_ICCR ((AT91_REG *) 0xFFFFF128) // (AIC) Interrupt Clear Command Register
#define AT91C_AIC_IECR ((AT91_REG *) 0xFFFFF120) // (AIC) Interrupt Enable Command Register
#define AT91C_AIC_SVR ((AT91_REG *) 0xFFFFF080) // (AIC) Source Vector egister
#define AT91C_AIC_SMR ((AT91_REG *) 0xFFFFF000) // (AIC) Source Mode egister
#define AT91C_AIC_SPU ((AT91_REG *) 0xFFFFF134) // (AIC) Spurious Vector Register
#define AT91C_AIC_FVR ((AT91_REG *) 0xFFFFF104) // (AIC) FIQ Vector Register
#define AT91C_AIC_IVR ((AT91_REG *) 0xFFFFF100) // (AIC) IRQ Vector Register
#define AT91C_AIC_ISR ((AT91_REG *) 0xFFFFF108) // (AIC) Interrupt Status Register
#define AT91C_AIC_IMR ((AT91_REG *) 0xFFFFF110) // (AIC) Interrupt Mask Register
#define AT91C_AIC_ISCR ((AT91_REG *) 0xFFFFF12C) // (AIC) Interrupt Set Command Register
#define AT91C_AIC_IPR ((AT91_REG *) 0xFFFFF10C) // (AIC) Interrupt Pending Register
#define AT91C_AIC_CISR ((AT91_REG *) 0xFFFFF114) // (AIC) Core Interrupt Status Register
#define AT91C_AIC_IDCR ((AT91_REG *) 0xFFFFF124) // (AIC) Interrupt Disable Command egister
#define AT91C_WD_SR ((AT91_REG *) 0xFFFF800C) // (WD) Status Register
#define AT91C_WD_CMR ((AT91_REG *) 0xFFFF8004) // (WD) Clock Mode Register
#define AT91C_WD_CR ((AT91_REG *) 0xFFFF8008) // (WD) Control Register
#define AT91C_WD_OMR ((AT91_REG *) 0xFFFF8000) // (WD) Overflow Mode Register
#define AT91C_PS_PCDR ((AT91_REG *) 0xFFFF4008) // (PS) Peripheral Clock Disable Register
#define AT91C_PS_CR ((AT91_REG *) 0xFFFF4000) // (PS) Control Register
#define AT91C_PS_PCSR ((AT91_REG *) 0xFFFF400C) // (PS) Peripheral Clock Status Register
#define AT91C_PS_PCER ((AT91_REG *) 0xFFFF4004) // (PS) Peripheral Clock Enable Register
#define AT91C_PIO_MDSR ((AT91_REG *) 0xFFFF0058) // (PIO) Multi-driver Status Register
#define AT91C_PIO_IFSR ((AT91_REG *) 0xFFFF0028) // (PIO) Input Filter Status Register
#define AT91C_PIO_IFER ((AT91_REG *) 0xFFFF0020) // (PIO) Input Filter Enable Register
#define AT91C_PIO_OSR ((AT91_REG *) 0xFFFF0018) // (PIO) Output Status Register
#define AT91C_PIO_OER ((AT91_REG *) 0xFFFF0010) // (PIO) Output Enable Register
#define AT91C_PIO_PSR ((AT91_REG *) 0xFFFF0008) // (PIO) PIO Status Register
#define AT91C_PIO_PDSR ((AT91_REG *) 0xFFFF003C) // (PIO) Pin Data Status Register
#define AT91C_PIO_CODR ((AT91_REG *) 0xFFFF0034) // (PIO) Clear Output Data Register
#define AT91C_PIO_IFDR ((AT91_REG *) 0xFFFF0024) // (PIO) Input Filter Disable Register
#define AT91C_PIO_MDER ((AT91_REG *) 0xFFFF0050) // (PIO) Multi-driver Enable Register
#define AT91C_PIO_IMR ((AT91_REG *) 0xFFFF0048) // (PIO) Interrupt Mask Register
#define AT91C_PIO_IER ((AT91_REG *) 0xFFFF0040) // (PIO) Interrupt Enable Register
#define AT91C_PIO_ODSR ((AT91_REG *) 0xFFFF0038) // (PIO) Output Data Status Register
#define AT91C_PIO_SODR ((AT91_REG *) 0xFFFF0030) // (PIO) Set Output Data Register
#define AT91C_PIO_PER ((AT91_REG *) 0xFFFF0000) // (PIO) PIO Enable Register
#define AT91C_PIO_MDDR ((AT91_REG *) 0xFFFF0054) // (PIO) Multi-driver Disable Register
#define AT91C_PIO_ISR ((AT91_REG *) 0xFFFF004C) // (PIO) Interrupt Status Register
#define AT91C_PIO_IDR ((AT91_REG *) 0xFFFF0044) // (PIO) Interrupt Disable Register
#define AT91C_PIO_PDR ((AT91_REG *) 0xFFFF0004) // (PIO) PIO Disable Register
#define AT91C_PIO_ODR ((AT91_REG *) 0xFFFF0014) // (PIO) Output Disable Registerr
#define AT91C_TC2_IDR ((AT91_REG *) 0xFFFE00A8) // (TC2) Interrupt Disable Register
#define AT91C_TC2_SR ((AT91_REG *) 0xFFFE00A0) // (TC2) Status Register
#define AT91C_TC2_RB ((AT91_REG *) 0xFFFE0098) // (TC2) Register B
#define AT91C_TC2_CV ((AT91_REG *) 0xFFFE0090) // (TC2) Counter Value
#define AT91C_TC2_CCR ((AT91_REG *) 0xFFFE0080) // (TC2) Channel Control Register
#define AT91C_TC2_IMR ((AT91_REG *) 0xFFFE00AC) // (TC2) Interrupt Mask Register
#define AT91C_TC2_IER ((AT91_REG *) 0xFFFE00A4) // (TC2) Interrupt Enable Register
#define AT91C_TC2_RC ((AT91_REG *) 0xFFFE009C) // (TC2) Register C
#define AT91C_TC2_RA ((AT91_REG *) 0xFFFE0094) // (TC2) Register A
#define AT91C_TC2_CMR ((AT91_REG *) 0xFFFE0084) // (TC2) Channel Mode Register
#define AT91C_TC1_IDR ((AT91_REG *) 0xFFFE0068) // (TC1) Interrupt Disable Register
#define AT91C_TC1_SR ((AT91_REG *) 0xFFFE0060) // (TC1) Status Register
#define AT91C_TC1_RB ((AT91_REG *) 0xFFFE0058) // (TC1) Register B
#define AT91C_TC1_CV ((AT91_REG *) 0xFFFE0050) // (TC1) Counter Value
#define AT91C_TC1_CCR ((AT91_REG *) 0xFFFE0040) // (TC1) Channel Control Register
#define AT91C_TC1_IMR ((AT91_REG *) 0xFFFE006C) // (TC1) Interrupt Mask Register
#define AT91C_TC1_IER ((AT91_REG *) 0xFFFE0064) // (TC1) Interrupt Enable Register
#define AT91C_TC1_RC ((AT91_REG *) 0xFFFE005C) // (TC1) Register C
#define AT91C_TC1_RA ((AT91_REG *) 0xFFFE0054) // (TC1) Register A
#define AT91C_TC1_CMR ((AT91_REG *) 0xFFFE0044) // (TC1) Channel Mode Register
#define AT91C_TC0_IDR ((AT91_REG *) 0xFFFE0028) // (TC0) Interrupt Disable Register
#define AT91C_TC0_SR ((AT91_REG *) 0xFFFE0020) // (TC0) Status Register
#define AT91C_TC0_RB ((AT91_REG *) 0xFFFE0018) // (TC0) Register B
#define AT91C_TC0_CV ((AT91_REG *) 0xFFFE0010) // (TC0) Counter Value
#define AT91C_TC0_CCR ((AT91_REG *) 0xFFFE0000) // (TC0) Channel Control Register
#define AT91C_TC0_IMR ((AT91_REG *) 0xFFFE002C) // (TC0) Interrupt Mask Register
#define AT91C_TC0_IER ((AT91_REG *) 0xFFFE0024) // (TC0) Interrupt Enable Register
#define AT91C_TC0_RC ((AT91_REG *) 0xFFFE001C) // (TC0) Register C
#define AT91C_TC0_RA ((AT91_REG *) 0xFFFE0014) // (TC0) Register A
#define AT91C_TC0_CMR ((AT91_REG *) 0xFFFE0004) // (TC0) Channel Mode Register
#define AT91C_TCB0_BCR ((AT91_REG *) 0xFFFE00C0) // (TCB0) TC Block Control Register
#define AT91C_TCB0_BMR ((AT91_REG *) 0xFFFE00C4) // (TCB0) TC Block Mode Register
#define AT91C_US1_TPR ((AT91_REG *) 0xFFFC4038) // (PDC_US1) Transmit Pointer Register
#define AT91C_US1_RPR ((AT91_REG *) 0xFFFC4030) // (PDC_US1) Receive Pointer Register
#define AT91C_US1_TCR ((AT91_REG *) 0xFFFC403C) // (PDC_US1) Transmit Counter Register
#define AT91C_US1_RCR ((AT91_REG *) 0xFFFC4034) // (PDC_US1) Receive Counter Register
#define AT91C_US1_RTOR ((AT91_REG *) 0xFFFCC024) // (US1) Receiver Time-out Register
#define AT91C_US1_THR ((AT91_REG *) 0xFFFCC01C) // (US1) Transmitter Holding Register
#define AT91C_US1_CSR ((AT91_REG *) 0xFFFCC014) // (US1) Channel Status Register
#define AT91C_US1_IDR ((AT91_REG *) 0xFFFCC00C) // (US1) Interrupt Disable Register
#define AT91C_US1_MR ((AT91_REG *) 0xFFFCC004) // (US1) Mode Register
#define AT91C_US1_TTGR ((AT91_REG *) 0xFFFCC028) // (US1) Transmitter Time-guard Register
#define AT91C_US1_BRGR ((AT91_REG *) 0xFFFCC020) // (US1) Baud Rate Generator Register
#define AT91C_US1_RHR ((AT91_REG *) 0xFFFCC018) // (US1) Receiver Holding Register
#define AT91C_US1_IMR ((AT91_REG *) 0xFFFCC010) // (US1) Interrupt Mask Register
#define AT91C_US1_IER ((AT91_REG *) 0xFFFCC008) // (US1) Interrupt Enable Register
#define AT91C_US1_CR ((AT91_REG *) 0xFFFCC000) // (US1) Control Register
#define AT91C_US0_TPR ((AT91_REG *) 0xFFFC0038) // (PDC_US0) Transmit Pointer Register
#define AT91C_US0_RPR ((AT91_REG *) 0xFFFC0030) // (PDC_US0) Receive Pointer Register
#define AT91C_US0_TCR ((AT91_REG *) 0xFFFC003C) // (PDC_US0) Transmit Counter Register
#define AT91C_US0_RCR ((AT91_REG *) 0xFFFC0034) // (PDC_US0) Receive Counter Register
#define AT91C_US0_RTOR ((AT91_REG *) 0xFFFD0024) // (US0) Receiver Time-out Register
#define AT91C_US0_THR ((AT91_REG *) 0xFFFD001C) // (US0) Transmitter Holding Register
#define AT91C_US0_CSR ((AT91_REG *) 0xFFFD0014) // (US0) Channel Status Register
#define AT91C_US0_IDR ((AT91_REG *) 0xFFFD000C) // (US0) Interrupt Disable Register
#define AT91C_US0_MR ((AT91_REG *) 0xFFFD0004) // (US0) Mode Register
#define AT91C_US0_TTGR ((AT91_REG *) 0xFFFD0028) // (US0) Transmitter Time-guard Register
#define AT91C_US0_BRGR ((AT91_REG *) 0xFFFD0020) // (US0) Baud Rate Generator Register
#define AT91C_US0_RHR ((AT91_REG *) 0xFFFD0018) // (US0) Receiver Holding Register
#define AT91C_US0_IMR ((AT91_REG *) 0xFFFD0010) // (US0) Interrupt Mask Register
#define AT91C_US0_IER ((AT91_REG *) 0xFFFD0008) // (US0) Interrupt Enable Register
#define AT91C_US0_CR ((AT91_REG *) 0xFFFD0000) // (US0) Control Register
#define AT91C_SF_PMR ((AT91_REG *) 0xFFF00018) // (SF) Protect Mode Register
#define AT91C_SF_RSR ((AT91_REG *) 0xFFF00008) // (SF) Reset Status Register
#define AT91C_SF_CIDR ((AT91_REG *) 0xFFF00000) // (SF) Chip ID Register
#define AT91C_SF_MMR ((AT91_REG *) 0xFFF0000C) // (SF) Memory Mode Register
#define AT91C_SF_EXID ((AT91_REG *) 0xFFF00004) // (SF) Chip ID Extension Register
#define AT91C_EBI_RCR ((AT91_REG *) 0xFFE00020) // (EBI) Remap Control Register
#define AT91C_EBI_CSR ((AT91_REG *) 0xFFE00000) // (EBI) Chip-select Register
#define AT91C_EBI_MCR ((AT91_REG *) 0xFFE00024) // (EBI) Memory Control Register
// PIO DEFINITIONS FOR AT91R40008
#define AT91C_PIO_P0 ((unsigned int) 1 << 0) // Pin Controlled by P0
#define AT91C_P0_TCLK0 ((unsigned int) AT91C_PIO_P0) // Timer 0 Clock signal
#define AT91C_PIO_P1 ((unsigned int) 1 << 1) // Pin Controlled by P1
#define AT91C_P1_TIOA0 ((unsigned int) AT91C_PIO_P1) // Timer 0 Signal A
#define AT91C_PIO_P10 ((unsigned int) 1 << 10) // Pin Controlled by P10
#define AT91C_P10_IRQ1 ((unsigned int) AT91C_PIO_P10) // External Interrupt 1
#define AT91C_PIO_P11 ((unsigned int) 1 << 11) // Pin Controlled by P11
#define AT91C_P11_IRQ2 ((unsigned int) AT91C_PIO_P11) // External Interrupt 2
#define AT91C_PIO_P12 ((unsigned int) 1 << 12) // Pin Controlled by P12
#define AT91C_P12_FIQ ((unsigned int) AT91C_PIO_P12) // Fast External Interrupt
#define AT91C_PIO_P13 ((unsigned int) 1 << 13) // Pin Controlled by P13
#define AT91C_P13_SCK0 ((unsigned int) AT91C_PIO_P13) // USART 0 Serial Clock
#define AT91C_PIO_P14 ((unsigned int) 1 << 14) // Pin Controlled by P14
#define AT91C_P14_TXD0 ((unsigned int) AT91C_PIO_P14) // USART 0 Transmit Data
#define AT91C_PIO_P15 ((unsigned int) 1 << 15) // Pin Controlled by P15
#define AT91C_P15_RXD0 ((unsigned int) AT91C_PIO_P15) // USART 0 Receive Data
#define AT91C_PIO_P16 ((unsigned int) 1 << 16) // Pin Controlled by P16
#define AT91C_PIO_P17 ((unsigned int) 1 << 17) // Pin Controlled by P17
#define AT91C_PIO_P18 ((unsigned int) 1 << 18) // Pin Controlled by P18
#define AT91C_PIO_P19 ((unsigned int) 1 << 19) // Pin Controlled by P19
#define AT91C_PIO_P2 ((unsigned int) 1 << 2) // Pin Controlled by P2
#define AT91C_P2_TIOB0 ((unsigned int) AT91C_PIO_P2) // Timer 0 Signal B
#define AT91C_PIO_P20 ((unsigned int) 1 << 20) // Pin Controlled by P20
#define AT91C_P20_SCK1 ((unsigned int) AT91C_PIO_P20) // USART 1 Serial Clock
#define AT91C_PIO_P21 ((unsigned int) 1 << 21) // Pin Controlled by P21
#define AT91C_P21_TXD1 ((unsigned int) AT91C_PIO_P21) // USART 1 Transmit Data
#define AT91C_P21_NTRI ((unsigned int) AT91C_PIO_P21) // Tri-state Mode
#define AT91C_PIO_P22 ((unsigned int) 1 << 22) // Pin Controlled by P22
#define AT91C_P22_RXD1 ((unsigned int) AT91C_PIO_P22) // USART 1 Receive Data
#define AT91C_PIO_P23 ((unsigned int) 1 << 23) // Pin Controlled by P23
#define AT91C_PIO_P24 ((unsigned int) 1 << 24) // Pin Controlled by P24
#define AT91C_P24_BMS ((unsigned int) AT91C_PIO_P24) // Boot Mode Select
#define AT91C_PIO_P25 ((unsigned int) 1 << 25) // Pin Controlled by P25
#define AT91C_P25_MCKO ((unsigned int) AT91C_PIO_P25) // Master Clock Out
#define AT91C_PIO_P26 ((unsigned int) 1 << 26) // Pin Controlled by P26
#define AT91C_P26_NCS2 ((unsigned int) AT91C_PIO_P26) // Chip Select 2
#define AT91C_PIO_P27 ((unsigned int) 1 << 27) // Pin Controlled by P27
#define AT91C_P27_NCS3 ((unsigned int) AT91C_PIO_P27) // Chip Select 3
#define AT91C_PIO_P28 ((unsigned int) 1 << 28) // Pin Controlled by P28
#define AT91C_P28_A20 ((unsigned int) AT91C_PIO_P28) // Address line A20
#define AT91C_P28_NCS7 ((unsigned int) AT91C_PIO_P28) // Chip Select 7
#define AT91C_PIO_P29 ((unsigned int) 1 << 29) // Pin Controlled by P29
#define AT91C_P29_A21 ((unsigned int) AT91C_PIO_P29) // Address line A21
#define AT91C_P29_NCS6 ((unsigned int) AT91C_PIO_P29) // Chip Select 6
#define AT91C_PIO_P3 ((unsigned int) 1 << 3) // Pin Controlled by P3
#define AT91C_P3_TCLK1 ((unsigned int) AT91C_PIO_P3) // Timer 1 Clock signal
#define AT91C_PIO_P30 ((unsigned int) 1 << 30) // Pin Controlled by P30
#define AT91C_P30_A22 ((unsigned int) AT91C_PIO_P30) // Address line A22
#define AT91C_P30_NCS5 ((unsigned int) AT91C_PIO_P30) // Chip Select 5
#define AT91C_PIO_P31 ((unsigned int) 1 << 31) // Pin Controlled by P31
#define AT91C_P31_A23 ((unsigned int) AT91C_PIO_P31) // Address line A23
#define AT91C_P31_NCS4 ((unsigned int) AT91C_PIO_P31) // Chip Select 4
#define AT91C_PIO_P4 ((unsigned int) 1 << 4) // Pin Controlled by P4
#define AT91C_P4_TIOA1 ((unsigned int) AT91C_PIO_P4) // Timer 1 Signal A
#define AT91C_PIO_P5 ((unsigned int) 1 << 5) // Pin Controlled by P5
#define AT91C_P5_TIOB1 ((unsigned int) AT91C_PIO_P5) // Timer 1 Signal B
#define AT91C_PIO_P6 ((unsigned int) 1 << 6) // Pin Controlled by P6
#define AT91C_P6_TCLK2 ((unsigned int) AT91C_PIO_P6) // Timer 2 Clock signal
#define AT91C_PIO_P7 ((unsigned int) 1 << 7) // Pin Controlled by P7
#define AT91C_P7_TIOA2 ((unsigned int) AT91C_PIO_P7) // Timer 2 Signal A
#define AT91C_PIO_P8 ((unsigned int) 1 << 8) // Pin Controlled by P8
#define AT91C_P8_TIOB2 ((unsigned int) AT91C_PIO_P8) // Timer 2 Signal B
#define AT91C_PIO_P9 ((unsigned int) 1 << 9) // Pin Controlled by P9
#define AT91C_P9_IRQ0 ((unsigned int) AT91C_PIO_P9) // External Interrupt 0
// PERIPHERAL ID DEFINITIONS FOR AT91R40008
#define AT91C_ID_FIQ ((unsigned int) 0) // Advanced Interrupt Controller (FIQ)
#define AT91C_ID_SYS ((unsigned int) 1) // SWI
#define AT91C_ID_US0 ((unsigned int) 2) // USART 0
#define AT91C_ID_US1 ((unsigned int) 3) // USART 1
#define AT91C_ID_TC0 ((unsigned int) 4) // Timer Counter 0
#define AT91C_ID_TC1 ((unsigned int) 5) // Timer Counter 1
#define AT91C_ID_TC2 ((unsigned int) 6) // Timer Counter 2
#define AT91C_ID_WD ((unsigned int) 7) // Watchdog Timer
#define AT91C_ID_PIO ((unsigned int) 8) // Parallel IO Controller
#define AT91C_ID_IRQ0 ((unsigned int) 16) // Advanced Interrupt Controller (IRQ0)
#define AT91C_ID_IRQ1 ((unsigned int) 17) // Advanced Interrupt Controller (IRQ1)
#define AT91C_ID_IRQ2 ((unsigned int) 18) // Advanced Interrupt Controller (IRQ2)
// BASE ADDRESS DEFINITIONS FOR AT91R40008
#define AT91C_BASE_AIC ((AT91PS_AIC) 0xFFFFF000) // (AIC) Base Address
#define AT91C_BASE_WD ((AT91PS_WD) 0xFFFF8000) // (WD) Base Address
#define AT91C_BASE_PS ((AT91PS_PS) 0xFFFF4000) // (PS) Base Address
#define AT91C_BASE_PIO ((AT91PS_PIO) 0xFFFF0000) // (PIO) Base Address
#define AT91C_BASE_TC2 ((AT91PS_TC) 0xFFFE0080) // (TC2) Base Address
#define AT91C_BASE_TC1 ((AT91PS_TC) 0xFFFE0040) // (TC1) Base Address
#define AT91C_BASE_TC0 ((AT91PS_TC) 0xFFFE0000) // (TC0) Base Address
#define AT91C_BASE_TCB0 ((AT91PS_TCB) 0xFFFE0000) // (TCB0) Base Address
#define AT91C_BASE_PDC_US1 ((AT91PS_PDC) 0xFFFC4030) // (PDC_US1) Base Address
#define AT91C_BASE_US1 ((AT91PS_USART) 0xFFFCC000) // (US1) Base Address
#define AT91C_BASE_PDC_US0 ((AT91PS_PDC) 0xFFFC0030) // (PDC_US0) Base Address
#define AT91C_BASE_US0 ((AT91PS_USART) 0xFFFD0000) // (US0) Base Address
#define AT91C_BASE_SF ((AT91PS_SF) 0xFFF00000) // (SF) Base Address
#define AT91C_BASE_EBI ((AT91PS_EBI) 0xFFE00000) // (EBI) Base Address
// MEMORY MAPPING DEFINITIONS FOR AT91R40008
#define <API key> ((char *) 0x00300000) // Internal SRAM before remap base address
#define <API key> ((unsigned int) 0x00040000) // Internal SRAM before remap size in byte (256 Kbyte)
#define <API key> ((char *) 0x00000000) // Internal SRAM after remap base address
#define <API key> ((unsigned int) 0x00040000) // Internal SRAM after remap size in byte (256 Kbyte)
#endif |
#!/bin/bash
REV='<SHA1-like>'
INSTALLED_FILE="${IROOT}/lwan-${REV}.installed"
RETCODE=$(fw_exists ${INSTALLED_FILE})
[ ! "$RETCODE" == 0 ] || { return 0; }
[ ! -e ${INSTALLED_FILE} -a -d ${IROOT}/lwan ] && rm -rf ${IROOT}/lwan
# Lwan is only built during installation as a dependency sanity check.
git clone git://github.com/lpereira/lwan.git
cd lwan
git checkout ${REV}
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make techempower
touch ${INSTALLED_FILE} |
package py4j.examples;
public class EnumExample {
public enum MyEnum {
FOO;
}
public class InnerClass {
public final static String MY_CONSTANT2 = "HELLO2";
}
} |
// <API key>: Apache-2.0 WITH LLVM-exception
// <random>
// template<class IntType = int>
// class <API key>
// result_type max() const;
#include <random>
#include <cassert>
#include "test_macros.h"
int main(int, char**)
{
{
typedef std::<API key><> D;
D d(4, .25);
assert(d.max() == std::numeric_limits<int>::max());
}
return 0;
} |
#include "native_client/src/trusted/debug_stub/debug_stub.h"
void <API key>() {
// TODO(noelallen): implement me
}
void <API key>() {
// TODO(noelallen): implement me
} |
if(!dojo._hasResource["dijit.robot"]){
dojo._hasResource["dijit.robot"]=true;
dojo.provide("dijit.robot");
dojo.require("dojo.robot");
} |
// Generated source.
// Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator
package org.chromium.sdk.internal.wip.protocol.common.page;
/**
Unique script identifier.
*/
public class <API key> {
/*
The class is 'typedef'.
If merely holds a type javadoc and its only field refers to an actual type.
*/
String actualType;
} |
<!DOCTYPE html>
<link rel="help" href="https://drafts.csswg.org/css-grid-1/#pagination">
<link rel="match" href="../../reference/<API key>.xht">
<title>Tests that a grid-item with a flexible track grows due to fragmentation.</title>
<p>Test passes if there is a filled green square and <strong>no red</strong>.</p>
<div style="position: relative; width: 100px; height: 100px; columns: 2; column-gap: 0; background: red;">
<div style="display: grid; grid-template-rows: 1fr;">
<div style="line-height: 0; background: green;">
<div style="display: inline-block; width: 50px; height: 50px;"></div>
<div style="display: inline-block; width: 50px; height: 100px;"></div>
</div>
</div>
</div> |
#ifndef <API key>
#define <API key>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "mojo/shell/app_child_process.mojom.h"
#include "mojo/shell/<API key>.h"
#include "mojo/shell/<API key>.h"
#include "mojo/shell/keep_alive.h"
namespace mojo {
namespace shell {
// An implementation of |<API key>| that loads/runs the given app
// (from the file system) in a separate process (of its own).
class <API key>
: public <API key>,
public <API key> {
public:
explicit <API key>(Context* context);
virtual ~<API key>();
// |<API key>| method:
virtual void Start(const base::FilePath& app_path,
<API key> service_handle,
const base::Closure& <API key>) OVERRIDE;
private:
// |<API key>| method:
virtual void AppCompleted(int32_t result) OVERRIDE;
Context* const context_;
KeepAlive keep_alive_;
base::FilePath app_path_;
<API key> service_handle_;
base::Closure <API key>;
scoped_ptr<AppChildProcessHost> <API key>;
<API key>(<API key>);
};
typedef <API key><<API key>>
<API key>;
} // namespace shell
} // namespace mojo
#endif // <API key> |
// Use of this source code is governed by a BSD-style
/*
Package table implements readers and writers of leveldb tables.
Tables are either opened for reading or created for writing but not both.
A reader can create iterators, which yield all key/value pairs whose keys
are 'greater than or equal' to a starting key. There may be multiple key/
value pairs that have the same key.
A reader can be used concurrently. Multiple goroutines can call Find
concurrently, and each iterator can run concurrently with other iterators.
However, any particular iterator should not be used concurrently, and
iterators should not be used once a reader is closed.
A writer writes key/value pairs in increasing key order, and cannot be used
concurrently. A table cannot be read until the writer has finished.
Readers and writers can be created with various options. Passing a nil
Options pointer is valid and means to use the default values.
One such option is to define the 'less than' ordering for keys. The default
Comparer uses the natural ordering consistent with bytes.Compare. The same
ordering should be used for reading and writing a table.
To return the value for a key:
r := table.NewReader(file, options)
defer r.Close()
return r.Get(key)
To count the number of entries in a table:
i, n := r.Find(nil, ropts), 0
for i.Next() {
n++
}
if err := i.Close(); err != nil {
return 0, err
}
return n, nil
To write a table with three entries:
w := table.NewWriter(file, options)
if err := w.Set([]byte("apple"), []byte("red"), wopts); err != nil {
w.Close()
return err
}
if err := w.Set([]byte("banana"), []byte("yellow"), wopts); err != nil {
w.Close()
return err
}
if err := w.Set([]byte("cherry"), []byte("red"), wopts); err != nil {
w.Close()
return err
}
return w.Close()
*/
package table
/*
The table file format looks like:
<start_of_file>
[data block 0]
[data block 1]
[data block N-1]
[meta block 0]
[meta block 1]
[meta block K-1]
[metaindex block]
[index block]
[footer]
<end_of_file>
Each block consists of some data and a 5 byte trailer: a 1 byte block type and
a 4 byte checksum of the compressed data. The block type gives the per-block
compression used; each block is compressed independently. The checksum
algorithm is described in the leveldb/crc package.
The decompressed block data consists of a sequence of key/value entries
followed by a trailer. Each key is encoded as a shared prefix length and a
remainder string. For example, if two adjacent keys are "tweedledee" and
"tweedledum", then the second key would be encoded as {8, "um"}. The shared
prefix length is varint encoded. The remainder string and the value are
encoded as a varint-encoded length followed by the literal contents. To
continue the example, suppose that the key "tweedledum" mapped to the value
"socks". The encoded key/value entry would be: "\x08\x02\x05umsocks".
Every block has a restart interval I. Every I'th key/value entry in that block
is called a restart point, and shares no key prefix with the previous entry.
Continuing the example above, if the key after "tweedledum" was "two", but was
part of a restart point, then that key would be encoded as {0, "two"} instead
of {2, "o"}. If a block has P restart points, then the block trailer consists
of (P+1)*4 bytes: (P+1) little-endian uint32 values. The first P of these
uint32 values are the block offsets of each restart point. The final uint32
value is P itself. Thus, when seeking for a particular key, one can use binary
search to find the largest restart point whose key is <= the key sought.
An index block is a block with N key/value entries. The i'th value is the
encoded block handle of the i'th data block. The i'th key is a separator for
i < N-1, and a successor for i == N-1. The separator between blocks i and i+1
is a key that is >= every key in block i and is < every key i block i+1. The
successor for the final block is a key that is >= every key in block N-1. The
index block restart interval is 1: every entry is a restart point.
The table footer is exactly 48 bytes long:
- the block handle for the metaindex block,
- the block handle for the index block,
- padding to take the two items above up to 40 bytes,
- an 8-byte magic string.
A block handle is an offset and a length; the length does not include the 5
byte trailer. Both numbers are varint-encoded, with no padding between the two
values. The maximum size of an encoded block handle is therefore 20 bytes.
*/
const (
blockTrailerLen = 5
footerLen = 48
magic = "\x57\xfb\x80\x8b\x24\x75\x47\xdb"
// The block type gives the per-block compression format.
// These constants are part of the file format and should not be changed.
// They are different from the db.Compression constants because the latter
// are designed so that the zero value of the db.Compression type means to
// use the default compression (which is snappy).
<API key> = 0
<API key> = 1
) |
<?php
namespace Zend\File\Transfer\Adapter;
use Zend\Filter\FilterPluginManager as BaseManager;
/**
* Plugin manager implementation for the filter chain.
*
* Enforces that filters retrieved are instances of
* FilterInterface. Additionally, it registers a number of default filters.
*
* @category Zend
* @package Zend_File_Transfer
*/
class FilterPluginManager extends BaseManager
{
/**
* Default set of filters
*
* @var array
*/
protected $aliases = array(
'decrypt' =>'filedecrypt',
'encrypt' =>'fileencrypt',
'lowercase' =>'filelowercase',
'rename' =>'filerename',
'uppercase' =>'fileuppercase',
);
} |
#ifndef _BFIN_PTRACE_H
#define _BFIN_PTRACE_H
#ifndef __ASSEMBLY__
struct task_struct;
/* this struct defines the way the registers are stored on the
stack during a system call. */
struct pt_regs {
long orig_pc;
long ipend;
long seqstat;
long rete;
long retn;
long retx;
long pc; /* PC == RETI */
long rets;
long reserved; /* Used as scratch during system calls */
long astat;
long lb1;
long lb0;
long lt1;
long lt0;
long lc1;
long lc0;
long a1w;
long a1x;
long a0w;
long a0x;
long b3;
long b2;
long b1;
long b0;
long l3;
long l2;
long l1;
long l0;
long m3;
long m2;
long m1;
long m0;
long i3;
long i2;
long i1;
long i0;
long usp;
long fp;
long p5;
long p4;
long p3;
long p2;
long p1;
long p0;
long r7;
long r6;
long r5;
long r4;
long r3;
long r2;
long r1;
long r0;
long orig_r0;
long orig_p0;
long syscfg;
};
/* Arbitrarily choose the same ptrace numbers as used by the Sparc code. */
#define PTRACE_GETREGS 12
#define PTRACE_SETREGS 13 /* ptrace signal */
#define PTRACE_GETFDPIC 31 /* get the ELF fdpic loadmap address */
#define <API key> 0 /* [addr] request the executable loadmap */
#define <API key> 1 /* [addr] request the interpreter loadmap */
#define PS_S (0x0002)
#ifdef __KERNEL__
/* user_mode returns true if only one bit is set in IPEND, other than the
master interrupt enable. */
#define user_mode(regs) (!(((regs)->ipend & ~0x10) & (((regs)->ipend & ~0x10) - 1)))
#define instruction_pointer(regs) ((regs)->pc)
#define user_stack_pointer(regs) ((regs)->usp)
#define profile_pc(regs) instruction_pointer(regs)
extern void show_regs(struct pt_regs *);
#define <API key>() (1)
extern void <API key>(struct task_struct *);
/* see arch/blackfin/kernel/ptrace.c about this redirect */
#define <API key>(child) ptrace_disable(child)
/*
* Get the address of the live pt_regs for the specified task.
* These are saved onto the top kernel stack when the process
* is not running.
*
* Note: if a user thread is execve'd from kernel space, the
* kernel stack will not be empty on entry to the kernel, so
* ptracing these tasks will fail.
*/
#define task_pt_regs(task) \
(struct pt_regs *) \
((unsigned long)task_stack_page(task) + \
(THREAD_SIZE - sizeof(struct pt_regs)))
#endif /* __KERNEL__ */
#endif /* __ASSEMBLY__ */
/*
* Offsets used by 'ptrace' system call interface.
*/
#define PT_R0 204
#define PT_R1 200
#define PT_R2 196
#define PT_R3 192
#define PT_R4 188
#define PT_R5 184
#define PT_R6 180
#define PT_R7 176
#define PT_P0 172
#define PT_P1 168
#define PT_P2 164
#define PT_P3 160
#define PT_P4 156
#define PT_P5 152
#define PT_FP 148
#define PT_USP 144
#define PT_I0 140
#define PT_I1 136
#define PT_I2 132
#define PT_I3 128
#define PT_M0 124
#define PT_M1 120
#define PT_M2 116
#define PT_M3 112
#define PT_L0 108
#define PT_L1 104
#define PT_L2 100
#define PT_L3 96
#define PT_B0 92
#define PT_B1 88
#define PT_B2 84
#define PT_B3 80
#define PT_A0X 76
#define PT_A0W 72
#define PT_A1X 68
#define PT_A1W 64
#define PT_LC0 60
#define PT_LC1 56
#define PT_LT0 52
#define PT_LT1 48
#define PT_LB0 44
#define PT_LB1 40
#define PT_ASTAT 36
#define PT_RESERVED 32
#define PT_RETS 28
#define PT_PC 24
#define PT_RETX 20
#define PT_RETN 16
#define PT_RETE 12
#define PT_SEQSTAT 8
#define PT_IPEND 4
#define PT_ORIG_R0 208
#define PT_ORIG_P0 212
#define PT_SYSCFG 216
#define PT_TEXT_ADDR 220
#define PT_TEXT_END_ADDR 224
#define PT_DATA_ADDR 228
#define PT_FDPIC_EXEC 232
#define PT_FDPIC_INTERP 236
#endif /* _BFIN_PTRACE_H */ |
// MessagePack for C++ static resolution routine
#ifndef <API key>
#define <API key>
#include "msgpack/versioning.hpp"
#include "msgpack/zone.hpp"
#include "msgpack/object.h"
#include <typeinfo>
namespace msgpack {
@cond
<API key>(v1) {
@endcond
namespace type {
enum object_type {
NIL = MSGPACK_OBJECT_NIL,
BOOLEAN = <API key>,
POSITIVE_INTEGER = <API key>,
NEGATIVE_INTEGER = <API key>,
FLOAT32 = <API key>,
FLOAT64 = <API key>,
FLOAT = <API key>,
#if defined(<API key>)
DOUBLE = MSGPACK_DEPRECATED("please use FLOAT64 instead") <API key>, // obsolete
#endif // <API key>
STR = MSGPACK_OBJECT_STR,
BIN = MSGPACK_OBJECT_BIN,
ARRAY = <API key>,
MAP = MSGPACK_OBJECT_MAP,
EXT = MSGPACK_OBJECT_EXT
};
}
struct object;
struct object_kv;
struct object_array;
struct object_map;
struct object_str;
struct object_bin;
struct object_ext;
#if !defined(MSGPACK_USE_CPP03)
namespace adaptor {
template <typename T, typename Enabler = void>
struct as;
} // namespace adaptor
template <typename T>
struct has_as;
#endif // !defined(MSGPACK_USE_CPP03)
class type_error;
@cond
} // <API key>(v1)
@endcond
} // namespace msgpack
#endif // <API key> |
// BmpView.cpp : main source file for BmpView.exe
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#ifndef _WIN32_WCE
#include <atlctrlw.h>
#endif // _WIN32_WCE
#include <atldlgs.h>
#include <atlscrl.h>
#include <atlmisc.h>
#ifndef _WIN32_WCE
#include <atlprint.h>
#endif // _WIN32_WCE
#include <atlcrack.h>
#ifndef _WIN32_WCE
#include "resource.h"
#else // _WIN32_WCE
#ifndef WIN32_PLATFORM_PSPC
#include "resourcece.h"
#else // WIN32_PLATFORM_PSPC
#include "resourceppc.h"
#endif // WIN32_PLATFORM_PSPC
#endif // _WIN32_WCE
#include "View.h"
#include "props.h"
#ifndef _WIN32_WCE
#include "list.h"
#endif // _WIN32_WCE
#include "MainFrm.h"
CAppModule _Module;
int Run(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow =
#ifndef _WIN32_WCE
SW_SHOWDEFAULT
#else // _WIN32_WCE
SW_SHOWNORMAL
#endif // _WIN32_WCE
)
{
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
CMainFrame wndMain;
if(wndMain.CreateEx() == NULL)
{
ATLTRACE(_T("Main window creation failed!\n"));
return 0;
}
wndMain.ShowWindow(nCmdShow);
int nRet = theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
#ifndef _WIN32_WCE
<API key> iccx;
iccx.dwSize = sizeof(iccx);
iccx.dwICC = ICC_COOL_CLASSES | ICC_BAR_CLASSES;
BOOL bRet = ::<API key>(&iccx);
bRet;
ATLASSERT(bRet);
#endif // _WIN32_WCE
HRESULT hRes = _Module.Init(NULL, hInstance);
hRes;
ATLASSERT(SUCCEEDED(hRes));
int nRet = Run(lpstrCmdLine, nCmdShow);
_Module.Term();
return nRet;
} |
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :display_name
t.string :user_name
t.string :signature
t.string :profile
t.string :password
t.boolean :admin
t.timestamps
end
end
def self.down
drop_table :users
end
end |
This Warning is signalled by methods which are deprecated.
The use of Object>>#<API key>: aString and Object>>#deprecated: aBlock explanation: aString is recommended.
Idiom: Imagine I want to deprecate the message #foo.
foo
^ 'foo'
I can replace it with:
foo
self <API key>: 'The method #foo was not good. Use Bar>>newFoo instead.'
^ 'foo'
Or, for certain cases such as when #foo implements a primitive, #foo can be renamed to #fooDeprecated.
fooDeprecated
^ <primitive>
foo
^ self deprecated: [self fooDeprecated] explanation: 'The method #foo was not good. Use Bar>>newFoo instead.' |
class Mixin < ActiveRecord::Base
end
class TreeMixin < Mixin
acts_as_tree :foreign_key => "parent_id", :order => "id"
end
class <API key> < Mixin
acts_as_tree :foreign_key => "parent_id"
end
class <API key> < Mixin
acts_as_tree :foreign_key => "parent_id"
has_one :first_child, :class_name => '<API key>', :foreign_key => :parent_id
end
class ListMixin < Mixin
acts_as_list :column => "pos", :scope => :parent
def self.table_name() "mixins" end
end
class ListMixinSub1 < ListMixin
end
class ListMixinSub2 < ListMixin
end
class <API key> < ActiveRecord::Base
acts_as_list :column => "pos", :scope => 'parent_id = #{parent_id}'
def self.table_name() "mixins" end
end
class NestedSet < Mixin
acts_as_nested_set :scope => "root_id IS NULL"
def self.table_name() "mixins" end
end
class <API key> < Mixin
acts_as_nested_set :scope => 'root_id = #{root_id}'
def self.table_name() "mixins" end
end
class <API key> < Mixin
acts_as_nested_set :scope => :root
def self.table_name() "mixins" end
end
class NestedSetSuperclass < Mixin
acts_as_nested_set :scope => :root
def self.table_name() "mixins" end
end
class NestedSetSubclass < NestedSetSuperclass
end |
/**
* @author vincent loh <vincent.ml@gmail.com>
* @update zhixin wen <wenzhixin2010@gmail.com>
*/
.fix-sticky {
position: fixed !important;
overflow: hidden;
z-index: 100;
}
.fix-sticky table thead {
background: #fff;
}
.fix-sticky table thead.thead-light {
background: #e9ecef;
}
.fix-sticky table thead.thead-dark {
background: #212529;
} |
#include "arm_math.h"
/**
* @ingroup groupFilters
*/
/**
* @addtogroup BiquadCascadeDF1
* @{
*/
/**
* @details
* @brief Initialization function for the floating-point Biquad cascade filter.
* @param[in,out] *S points to an instance of the floating-point Biquad cascade structure.
* @param[in] numStages number of 2nd order stages in the filter.
* @param[in] *pCoeffs points to the filter coefficients array.
* @param[in] *pState points to the state array.
* @return none
*
*
* <b>Coefficient and State Ordering:</b>
*
* \par
* The coefficients are stored in the array <code>pCoeffs</code> in the following order:
* <pre>
* {b10, b11, b12, a11, a12, b20, b21, b22, a21, a22, ...}
* </pre>
*
* \par
* where <code>b1x</code> and <code>a1x</code> are the coefficients for the first stage,
* <code>b2x</code> and <code>a2x</code> are the coefficients for the second stage,
* and so on. The <code>pCoeffs</code> array contains a total of <code>5*numStages</code> values.
*
* \par
* The <code>pState</code> is a pointer to state array.
* Each Biquad stage has 4 state variables <code>x[n-1], x[n-2], y[n-1],</code> and <code>y[n-2]</code>.
* The state variables are arranged in the <code>pState</code> array as:
* <pre>
* {x[n-1], x[n-2], y[n-1], y[n-2]}
* </pre>
* The 4 state variables for stage 1 are first, then the 4 state variables for stage 2, and so on.
* The state array has a total length of <code>4*numStages</code> values.
* The state variables are updated after each block of data is processed; the coefficients are untouched.
*
*/
void <API key>(
<API key> * S,
uint8_t numStages,
float32_t * pCoeffs,
float32_t * pState)
{
/* Assign filter stages */
S->numStages = numStages;
/* Assign coefficient pointer */
S->pCoeffs = pCoeffs;
/* Clear state buffer and size is always 4 * numStages */
memset(pState, 0, (4u * (uint32_t) numStages) * sizeof(float32_t));
/* Assign state pointer */
S->pState = pState;
}
/**
* @} end of BiquadCascadeDF1 group
*/ |
require './test/lib_read_write'
class <API key> < Test::Unit::TestCase
def setup
@host = ENV["TEST_HOST"] || '127.0.0.1'
@srv = Kgio::TCPServer.new(@host, 0)
@port = @srv.addr[1]
@wr = Kgio::TCPSocket.new(@host, @port)
@rd = @srv.kgio_accept
end
include LibReadWriteTest
end |
#include <stdint.h>
#include "platform.h"
#include "internals.h"
int <API key>( uint64_t *sigPtr )
{
uint64_t sig;
int_fast8_t shiftCount;
sig = *sigPtr;
shiftCount = <API key>( sig );
*sigPtr = sig<<shiftCount;
return -shiftCount;
} |
using System;
namespace Umbraco.Core.Events
{
<summary>
Extension methods for cancellable event operations
</summary>
public static class EventExtensions
{
<summary>
Raises the event and returns a boolean value indicating if the event was cancelled
</summary>
<typeparam name="TSender"></typeparam>
<typeparam name="TArgs"></typeparam>
<param name="eventHandler"></param>
<param name="args"></param>
<param name="sender"></param>
<returns></returns>
public static bool <API key><TSender, TArgs>(
this TypedEventHandler<TSender, TArgs> eventHandler,
TArgs args,
TSender sender)
where TArgs : <API key>
{
if (eventHandler != null)
eventHandler(sender, args);
return args.Cancel;
}
<summary>
Raises the event
</summary>
<typeparam name="TSender"></typeparam>
<typeparam name="TArgs"></typeparam>
<param name="eventHandler"></param>
<param name="args"></param>
<param name="sender"></param>
public static void RaiseEvent<TSender, TArgs>(
this TypedEventHandler<TSender, TArgs> eventHandler,
TArgs args,
TSender sender)
where TArgs : EventArgs
{
if (eventHandler != null)
eventHandler(sender, args);
}
}
} |
package org.eclipse.jdt.internal.corext.refactoring.util;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.internal.corext.refactoring.<API key>;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class <API key> {
private Map<IFile, TextChange> fChanges;
public <API key>() {
fChanges = new HashMap<IFile, TextChange>();
}
public TextChange getChange(IFile file) {
TextChange result = fChanges.get(file);
if (result == null) {
result = new TextFileChange(file.getName(), file);
fChanges.put(file, result);
}
return result;
}
public TextChange[] getAllChanges() {
Collection<TextChange> values = fChanges.values();
return values.toArray(new TextChange[values.size()]);
}
public IFile[] getAllFiles() {
Set<IFile> keys = fChanges.keySet();
return keys.toArray(new IFile[keys.size()]);
}
public Change getSingleChange(IFile[] alreadyTouchedFiles) {
Collection<TextChange> values = fChanges.values();
if (values.size() == 0)
return null;
CompositeChange result = new CompositeChange(<API key>.<API key>);
result.markAsSynthetic();
List<IFile> files = Arrays.asList(alreadyTouchedFiles);
for (Iterator<TextChange> iter = values.iterator(); iter.hasNext(); ) {
TextFileChange change = (TextFileChange)iter.next();
if (!files.contains(change.getFile())) {
result.add(change);
}
}
return result;
}
} |
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/sched/signal.h>
#include <net/llc.h>
#include <net/llc_sap.h>
#include <net/llc_pdu.h>
#include <net/llc_conn.h>
#include <net/tcp_states.h>
/* remember: uninitialized global data is zeroed because its in .bss */
static u16 <API key> = LLC_SAP_DYN_START;
static u16 <API key>[256];
static struct sockaddr_llc llc_ui_addrnull;
static const struct proto_ops llc_ui_ops;
static bool <API key>(struct sock *sk, long timeout);
static int <API key>(struct sock *sk, long timeout);
static int <API key>(struct sock *sk, long timeout);
#if 0
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
/* Maybe we'll add some more in the future. */
#define LLC_CMSG_PKTINFO 1
/**
* llc_ui_next_link_no - return the next unused link number for a sap
* @sap: Address of sap to get link number from.
*
* Return the next unused link number for a given sap.
*/
static inline u16 llc_ui_next_link_no(int sap)
{
return <API key>[sap]++;
}
/**
* llc_proto_type - return eth protocol for ARP header type
* @arphrd: ARP header type.
*
* Given an ARP header type return the corresponding ethernet protocol.
*/
static inline __be16 llc_proto_type(u16 arphrd)
{
return htons(ETH_P_802_2);
}
/**
* llc_ui_addr_null - determines if a address structure is null
* @addr: Address to test if null.
*/
static inline u8 llc_ui_addr_null(struct sockaddr_llc *addr)
{
return !memcmp(addr, &llc_ui_addrnull, sizeof(*addr));
}
/**
* llc_ui_header_len - return length of llc header based on operation
* @sk: Socket which contains a valid llc socket type.
* @addr: Complete sockaddr_llc structure received from the user.
*
* Provide the length of the llc header depending on what kind of
* operation the user would like to perform and the type of socket.
* Returns the correct llc header length.
*/
static inline u8 llc_ui_header_len(struct sock *sk, struct sockaddr_llc *addr)
{
u8 rc = LLC_PDU_LEN_U;
if (addr->sllc_test || addr->sllc_xid)
rc = LLC_PDU_LEN_U;
else if (sk->sk_type == SOCK_STREAM)
rc = LLC_PDU_LEN_I;
return rc;
}
/**
* llc_ui_send_data - send data via reliable llc2 connection
* @sk: Connection the socket is using.
* @skb: Data the user wishes to send.
* @noblock: can we block waiting for data?
*
* Send data via reliable llc2 connection.
* Returns 0 upon success, non-zero if action did not succeed.
*/
static int llc_ui_send_data(struct sock* sk, struct sk_buff *skb, int noblock)
{
struct llc_sock* llc = llc_sk(sk);
int rc = 0;
if (unlikely(<API key>(llc->state) ||
llc->remote_busy_flag ||
llc->p_flag)) {
long timeout = sock_sndtimeo(sk, noblock);
rc = <API key>(sk, timeout);
}
if (unlikely(!rc))
rc = <API key>(sk, skb);
return rc;
}
static void llc_ui_sk_init(struct socket *sock, struct sock *sk)
{
sock_graft(sk, sock);
sk->sk_type = sock->type;
sock->ops = &llc_ui_ops;
}
static struct proto llc_proto = {
.name = "LLC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct llc_sock),
.slab_flags = SLAB_DESTROY_BY_RCU,
};
/**
* llc_ui_create - alloc and init a new llc_ui socket
* @net: network namespace (must be default network)
* @sock: Socket to initialize and attach allocated sk to.
* @protocol: Unused.
* @kern: on behalf of kernel or userspace
*
* Allocate and initialize a new llc_ui socket, validate the user wants a
* socket type we have available.
* Returns 0 upon success, negative upon failure.
*/
static int llc_ui_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
int rc = -ESOCKTNOSUPPORT;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
if (likely(sock->type == SOCK_DGRAM || sock->type == SOCK_STREAM)) {
rc = -ENOMEM;
sk = llc_sk_alloc(net, PF_LLC, GFP_KERNEL, &llc_proto, kern);
if (sk) {
rc = 0;
llc_ui_sk_init(sock, sk);
}
}
return rc;
}
/**
* llc_ui_release - shutdown socket
* @sock: Socket to release.
*
* Shutdown and deallocate an existing socket.
*/
static int llc_ui_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct llc_sock *llc;
if (unlikely(sk == NULL))
goto out;
sock_hold(sk);
lock_sock(sk);
llc = llc_sk(sk);
dprintk("%s: closing local(%02X) remote(%02X)\n", __func__,
llc->laddr.lsap, llc->daddr.lsap);
if (!llc_send_disc(sk))
<API key>(sk, sk->sk_rcvtimeo);
if (!sock_flag(sk, SOCK_ZAPPED))
<API key>(llc->sap, sk);
release_sock(sk);
if (llc->dev)
dev_put(llc->dev);
sock_put(sk);
llc_sk_free(sk);
out:
return 0;
}
/**
* llc_ui_autoport - provide dynamically allocate SAP number
*
* Provide the caller with a dynamically allocated SAP number according
* to the rules that are set in this function. Returns: 0, upon failure,
* SAP number otherwise.
*/
static int llc_ui_autoport(void)
{
struct llc_sap *sap;
int i, tries = 0;
while (tries < LLC_SAP_DYN_TRIES) {
for (i = <API key>;
i < LLC_SAP_DYN_STOP; i += 2) {
sap = llc_sap_find(i);
if (!sap) {
<API key> = i + 2;
goto out;
}
llc_sap_put(sap);
}
<API key> = LLC_SAP_DYN_START;
tries++;
}
i = 0;
out:
return i;
}
/**
* llc_ui_autobind - automatically bind a socket to a sap
* @sock: socket to bind
* @addr: address to connect to
*
* Used by llc_ui_connect and llc_ui_sendmsg when the user hasn't
* specifically used llc_ui_bind to bind to an specific address/sap
*
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_autobind(struct socket *sock, struct sockaddr_llc *addr)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap;
int rc = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED))
goto out;
rc = -ENODEV;
if (sk->sk_bound_dev_if) {
llc->dev = dev_get_by_index(&init_net, sk->sk_bound_dev_if);
if (llc->dev && addr->sllc_arphrd != llc->dev->type) {
dev_put(llc->dev);
llc->dev = NULL;
}
} else
llc->dev = <API key>(&init_net, addr->sllc_arphrd);
if (!llc->dev)
goto out;
rc = -EUSERS;
llc->laddr.lsap = llc_ui_autoport();
if (!llc->laddr.lsap)
goto out;
rc = -EBUSY; /* some other network layer is using the sap */
sap = llc_sap_open(llc->laddr.lsap, NULL);
if (!sap)
goto out;
memcpy(llc->laddr.mac, llc->dev->dev_addr, IFHWADDRLEN);
memcpy(&llc->addr, addr, sizeof(llc->addr));
/* assign new connection to its SAP */
llc_sap_add_socket(sap, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out:
return rc;
}
/**
* llc_ui_bind - bind a socket to a specific address.
* @sock: Socket to bind an address to.
* @uaddr: Address the user wants the socket bound to.
* @addrlen: Length of the uaddr structure.
*
* Bind a socket to a specific address. For llc a user is able to bind to
* a specific sap only or mac + sap.
* If the user desires to bind to a specific mac + sap, it is possible to
* have multiple sap connections via multiple macs.
* Bind and autobind for that matter must enforce the correct sap usage
* otherwise all hell will break loose.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen)
{
struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct llc_sap *sap;
int rc = -EINVAL;
dprintk("%s: binding %02X\n", __func__, addr->sllc_sap);
if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr)))
goto out;
rc = -EAFNOSUPPORT;
if (unlikely(addr->sllc_family != AF_LLC))
goto out;
rc = -ENODEV;
rcu_read_lock();
if (sk->sk_bound_dev_if) {
llc->dev = <API key>(&init_net, sk->sk_bound_dev_if);
if (llc->dev) {
if (!addr->sllc_arphrd)
addr->sllc_arphrd = llc->dev->type;
if (is_zero_ether_addr(addr->sllc_mac))
memcpy(addr->sllc_mac, llc->dev->dev_addr,
IFHWADDRLEN);
if (addr->sllc_arphrd != llc->dev->type ||
!ether_addr_equal(addr->sllc_mac,
llc->dev->dev_addr)) {
rc = -EINVAL;
llc->dev = NULL;
}
}
} else
llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd,
addr->sllc_mac);
if (llc->dev)
dev_hold(llc->dev);
rcu_read_unlock();
if (!llc->dev)
goto out;
if (!addr->sllc_sap) {
rc = -EUSERS;
addr->sllc_sap = llc_ui_autoport();
if (!addr->sllc_sap)
goto out;
}
sap = llc_sap_find(addr->sllc_sap);
if (!sap) {
sap = llc_sap_open(addr->sllc_sap, NULL);
rc = -EBUSY; /* some other network layer is using the sap */
if (!sap)
goto out;
} else {
struct llc_addr laddr, daddr;
struct sock *ask;
memset(&laddr, 0, sizeof(laddr));
memset(&daddr, 0, sizeof(daddr));
/*
* FIXME: check if the address is multicast,
* only SOCK_DGRAM can do this.
*/
memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN);
laddr.lsap = addr->sllc_sap;
rc = -EADDRINUSE; /* mac + sap clash. */
ask = <API key>(sap, &daddr, &laddr);
if (ask) {
sock_put(ask);
goto out_put;
}
}
llc->laddr.lsap = addr->sllc_sap;
memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN);
memcpy(&llc->addr, addr, sizeof(llc->addr));
/* assign new connection to its SAP */
llc_sap_add_socket(sap, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out_put:
llc_sap_put(sap);
out:
return rc;
}
/**
* llc_ui_shutdown - shutdown a connect llc2 socket.
* @sock: Socket to shutdown.
* @how: What part of the socket to shutdown.
*
* Shutdown a connected llc2 socket. Currently this function only supports
* shutting down both sends and receives (2), we could probably make this
* function such that a user can shutdown only half the connection but not
* right now.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int rc = -ENOTCONN;
lock_sock(sk);
if (unlikely(sk->sk_state != TCP_ESTABLISHED))
goto out;
rc = -EINVAL;
if (how != 2)
goto out;
rc = llc_send_disc(sk);
if (!rc)
rc = <API key>(sk, sk->sk_rcvtimeo);
/* Wake up anyone sleeping in poll */
sk->sk_state_change(sk);
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_connect - Connect to a remote llc2 mac + sap.
* @sock: Socket which will be connected to the remote destination.
* @uaddr: Remote and possibly the local address of the new connection.
* @addrlen: Size of uaddr structure.
* @flags: Operational flags specified by the user.
*
* Connect to a remote llc2 mac + sap. The caller must specify the
* destination mac and address to connect to. If the user hasn't previously
* called bind(2) with a smac the address of the first interface of the
* specified arp type will be used.
* This function will autobind if user did not previously call bind.
* Returns: 0 upon success, negative otherwise.
*/
static int llc_ui_connect(struct socket *sock, struct sockaddr *uaddr,
int addrlen, int flags)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(addrlen != sizeof(*addr)))
goto out;
rc = -EAFNOSUPPORT;
if (unlikely(addr->sllc_family != AF_LLC))
goto out;
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EALREADY;
if (unlikely(sock->state == SS_CONNECTING))
goto out;
/* bind connection to sap if user hasn't done it. */
if (sock_flag(sk, SOCK_ZAPPED)) {
/* bind to sap with null dev, exclusive */
rc = llc_ui_autobind(sock, addr);
if (rc)
goto out;
}
llc->daddr.lsap = addr->sllc_sap;
memcpy(llc->daddr.mac, addr->sllc_mac, IFHWADDRLEN);
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
llc->link = llc_ui_next_link_no(llc->sap->laddr.lsap);
rc = <API key>(sk, llc->dev->dev_addr,
addr->sllc_mac, addr->sllc_sap);
if (rc) {
dprintk("%s: llc_ui_send_conn failed :-(\n", __func__);
sock->state = SS_UNCONNECTED;
sk->sk_state = TCP_CLOSE;
goto out;
}
if (sk->sk_state == TCP_SYN_SENT) {
const long timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
if (!timeo || !<API key>(sk, timeo))
goto out;
rc = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
}
if (sk->sk_state == TCP_CLOSE)
goto sock_error;
sock->state = SS_CONNECTED;
rc = 0;
out:
release_sock(sk);
return rc;
sock_error:
rc = sock_error(sk) ? : -ECONNABORTED;
sock->state = SS_UNCONNECTED;
goto out;
}
/**
* llc_ui_listen - allow a normal socket to accept incoming connections
* @sock: Socket to allow incoming connections on.
* @backlog: Number of connections to queue.
*
* Allow a normal socket to accept incoming connections.
* Returns 0 upon success, negative otherwise.
*/
static int llc_ui_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(sock->state != SS_UNCONNECTED))
goto out;
rc = -EOPNOTSUPP;
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EAGAIN;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
rc = 0;
if (!(unsigned int)backlog) /* BSDism */
backlog = 1;
sk->sk_max_ack_backlog = backlog;
if (sk->sk_state != TCP_LISTEN) {
sk->sk_ack_backlog = 0;
sk->sk_state = TCP_LISTEN;
}
sk->sk_socket->flags |= __SO_ACCEPTCON;
out:
release_sock(sk);
return rc;
}
static int <API key>(struct sock *sk, long timeout)
{
DEFINE_WAIT_FUNC(wait, woken_wake_function);
int rc = 0;
add_wait_queue(sk_sleep(sk), &wait);
while (1) {
if (sk_wait_event(sk, &timeout, sk->sk_state == TCP_CLOSE, &wait))
break;
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = -EAGAIN;
if (!timeout)
break;
rc = 0;
}
remove_wait_queue(sk_sleep(sk), &wait);
return rc;
}
static bool <API key>(struct sock *sk, long timeout)
{
DEFINE_WAIT_FUNC(wait, woken_wake_function);
add_wait_queue(sk_sleep(sk), &wait);
while (1) {
if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT, &wait))
break;
if (signal_pending(current) || !timeout)
break;
}
remove_wait_queue(sk_sleep(sk), &wait);
return timeout;
}
static int <API key>(struct sock *sk, long timeout)
{
DEFINE_WAIT_FUNC(wait, woken_wake_function);
struct llc_sock *llc = llc_sk(sk);
int rc;
add_wait_queue(sk_sleep(sk), &wait);
while (1) {
rc = 0;
if (sk_wait_event(sk, &timeout,
(sk->sk_shutdown & RCV_SHUTDOWN) ||
(!<API key>(llc->state) &&
!llc->remote_busy_flag &&
!llc->p_flag), &wait))
break;
rc = -ERESTARTSYS;
if (signal_pending(current))
break;
rc = -EAGAIN;
if (!timeout)
break;
}
remove_wait_queue(sk_sleep(sk), &wait);
return rc;
}
static int llc_wait_data(struct sock *sk, long timeo)
{
int rc;
while (1) {
/*
* POSIX 1003.1g mandates this order.
*/
rc = sock_error(sk);
if (rc)
break;
rc = 0;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
rc = -EAGAIN;
if (!timeo)
break;
rc = sock_intr_errno(timeo);
if (signal_pending(current))
break;
rc = 0;
if (sk_wait_data(sk, &timeo, NULL))
break;
}
return rc;
}
static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(skb->sk);
if (llc->cmsg_flags & LLC_CMSG_PKTINFO) {
struct llc_pktinfo info;
memset(&info, 0, sizeof(info));
info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex;
llc_pdu_decode_dsap(skb, &info.lpi_sap);
llc_pdu_decode_da(skb, info.lpi_mac);
put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info);
}
}
/**
* llc_ui_accept - accept a new incoming connection.
* @sock: Socket which connections arrive on.
* @newsock: Socket to move incoming connection to.
* @flags: User specified operational flags.
* @kern: If the socket is kernel internal
*
* Accept a new incoming connection.
* Returns 0 upon success, negative otherwise.
*/
static int llc_ui_accept(struct socket *sock, struct socket *newsock, int flags,
bool kern)
{
struct sock *sk = sock->sk, *newsk;
struct llc_sock *llc, *newllc;
struct sk_buff *skb;
int rc = -EOPNOTSUPP;
dprintk("%s: accepting on %02X\n", __func__,
llc_sk(sk)->laddr.lsap);
lock_sock(sk);
if (unlikely(sk->sk_type != SOCK_STREAM))
goto out;
rc = -EINVAL;
if (unlikely(sock->state != SS_UNCONNECTED ||
sk->sk_state != TCP_LISTEN))
goto out;
/* wait for a connection to arrive. */
if (skb_queue_empty(&sk->sk_receive_queue)) {
rc = llc_wait_data(sk, sk->sk_rcvtimeo);
if (rc)
goto out;
}
dprintk("%s: got a new connection on %02X\n", __func__,
llc_sk(sk)->laddr.lsap);
skb = skb_dequeue(&sk->sk_receive_queue);
rc = -EINVAL;
if (!skb->sk)
goto frees;
rc = 0;
newsk = skb->sk;
/* attach connection to a new socket. */
llc_ui_sk_init(newsock, newsk);
sock_reset_flag(newsk, SOCK_ZAPPED);
newsk->sk_state = TCP_ESTABLISHED;
newsock->state = SS_CONNECTED;
llc = llc_sk(sk);
newllc = llc_sk(newsk);
memcpy(&newllc->addr, &llc->addr, sizeof(newllc->addr));
newllc->link = llc_ui_next_link_no(newllc->laddr.lsap);
/* put original socket back into a clean listen state. */
sk->sk_state = TCP_LISTEN;
sk->sk_ack_backlog
dprintk("%s: ok success on %02X, client on %02X\n", __func__,
llc_sk(sk)->addr.sllc_sap, newllc->daddr.lsap);
frees:
kfree_skb(skb);
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_recvmsg - copy received data to the socket user.
* @sock: Socket to copy data from.
* @msg: Various user space related information.
* @len: Size of user buffer.
* @flags: User specified flags.
*
* Copy received data to the socket user.
* Returns non-negative upon success, negative otherwise.
*/
static int llc_ui_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
DECLARE_SOCKADDR(struct sockaddr_llc *, uaddr, msg->msg_name);
const int nonblock = flags & MSG_DONTWAIT;
struct sk_buff *skb = NULL;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
unsigned long cpu_flags;
size_t copied = 0;
u32 peek_seq = 0;
u32 *seq, skb_len;
unsigned long used;
int target; /* Read at least this many bytes */
long timeo;
lock_sock(sk);
copied = -ENOTCONN;
if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN))
goto out;
timeo = sock_rcvtimeo(sk, nonblock);
seq = &llc->copied_seq;
if (flags & MSG_PEEK) {
peek_seq = llc->copied_seq;
seq = &peek_seq;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
copied = 0;
do {
u32 offset;
/*
* We need to check signals first, to get correct SIGURG
* handling. FIXME: Need to check this doesn't impact 1003.1g
* and move it down to the bottom of the loop
*/
if (signal_pending(current)) {
if (copied)
break;
copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
break;
}
/* Next get a buffer. */
skb = skb_peek(&sk->sk_receive_queue);
if (skb) {
offset = *seq;
goto found_ok_skb;
}
/* Well, if we have backlog, try to process it now yet. */
if (copied >= target && !sk->sk_backlog.tail)
break;
if (copied) {
if (sk->sk_err ||
sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
!timeo ||
(flags & MSG_PEEK))
break;
} else {
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
copied = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) {
if (!sock_flag(sk, SOCK_DONE)) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
copied = -ENOTCONN;
break;
}
break;
}
if (!timeo) {
copied = -EAGAIN;
break;
}
}
if (copied >= target) { /* Do not sleep, just process backlog. */
release_sock(sk);
lock_sock(sk);
} else
sk_wait_data(sk, &timeo, NULL);
if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) {
net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n",
current->comm,
task_pid_nr(current));
peek_seq = llc->copied_seq;
}
continue;
found_ok_skb:
skb_len = skb->len;
/* Ok so how much can we use? */
used = skb->len - offset;
if (len < used)
used = len;
if (!(flags & MSG_TRUNC)) {
int rc = <API key>(skb, offset, msg, used);
if (rc) {
/* Exception. Bailout! */
if (!copied)
copied = -EFAULT;
break;
}
}
*seq += used;
copied += used;
len -= used;
/* For non stream protcols we get one packet per recvmsg call */
if (sk->sk_type != SOCK_STREAM)
goto copy_uaddr;
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb);
<API key>(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
/* Partial read */
if (used + offset < skb_len)
continue;
} while (len > 0);
out:
release_sock(sk);
return copied;
copy_uaddr:
if (uaddr != NULL && skb != NULL) {
memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr));
msg->msg_namelen = sizeof(*uaddr);
}
if (llc_sk(sk)->cmsg_flags)
llc_cmsg_rcv(msg, skb);
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb);
<API key>(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
goto out;
}
/**
* llc_ui_sendmsg - Transmit data provided by the socket user.
* @sock: Socket to transmit data from.
* @msg: Various user related information.
* @len: Length of data to transmit.
*
* Transmit data provided by the socket user.
* Returns non-negative upon success, negative otherwise.
*/
static int llc_ui_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_llc *, addr, msg->msg_name);
int flags = msg->msg_flags;
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
size_t size = 0;
int rc = -EINVAL, copied = 0, hdrlen;
dprintk("%s: sending from %02X to %02X\n", __func__,
llc->laddr.lsap, llc->daddr.lsap);
lock_sock(sk);
if (addr) {
if (msg->msg_namelen < sizeof(*addr))
goto release;
} else {
if (llc_ui_addr_null(&llc->addr))
goto release;
addr = &llc->addr;
}
/* must bind connection to sap if user hasn't done it. */
if (sock_flag(sk, SOCK_ZAPPED)) {
/* bind to sap with null dev, exclusive. */
rc = llc_ui_autobind(sock, addr);
if (rc)
goto release;
}
hdrlen = llc->dev->hard_header_len + llc_ui_header_len(sk, addr);
size = hdrlen + len;
if (size > llc->dev->mtu)
size = llc->dev->mtu;
copied = size - hdrlen;
release_sock(sk);
skb = sock_alloc_send_skb(sk, size, noblock, &rc);
lock_sock(sk);
if (!skb)
goto release;
skb->dev = llc->dev;
skb->protocol = llc_proto_type(addr->sllc_arphrd);
skb_reserve(skb, hdrlen);
rc = memcpy_from_msg(skb_put(skb, copied), msg, copied);
if (rc)
goto out;
if (sk->sk_type == SOCK_DGRAM || addr->sllc_ua) {
<API key>(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
if (addr->sllc_test) {
<API key>(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
if (addr->sllc_xid) {
<API key>(llc->sap, skb, addr->sllc_mac,
addr->sllc_sap);
goto out;
}
rc = -ENOPROTOOPT;
if (!(sk->sk_type == SOCK_STREAM && !addr->sllc_ua))
goto out;
rc = llc_ui_send_data(sk, skb, noblock);
out:
if (rc) {
kfree_skb(skb);
release:
dprintk("%s: failed sending from %02X to %02X: %d\n",
__func__, llc->laddr.lsap, llc->daddr.lsap, rc);
}
release_sock(sk);
return rc ? : copied;
}
/**
* llc_ui_getname - return the address info of a socket
* @sock: Socket to get address of.
* @uaddr: Address structure to return information.
* @uaddrlen: Length of address structure.
* @peer: Does user want local or remote address information.
*
* Return the address information of a socket.
*/
static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddrlen, int peer)
{
struct sockaddr_llc sllc;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
int rc = -EBADF;
memset(&sllc, 0, sizeof(sllc));
lock_sock(sk);
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
*uaddrlen = sizeof(sllc);
if (peer) {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if(llc->dev)
sllc.sllc_arphrd = llc->dev->type;
sllc.sllc_sap = llc->daddr.lsap;
memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN);
} else {
rc = -EINVAL;
if (!llc->sap)
goto out;
sllc.sllc_sap = llc->sap->laddr.lsap;
if (llc->dev) {
sllc.sllc_arphrd = llc->dev->type;
memcpy(&sllc.sllc_mac, llc->dev->dev_addr,
IFHWADDRLEN);
}
}
rc = 0;
sllc.sllc_family = AF_LLC;
memcpy(uaddr, &sllc, sizeof(sllc));
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_ioctl - io controls for PF_LLC
* @sock: Socket to get/set info
* @cmd: command
* @arg: optional argument for cmd
*
* get/set info on llc sockets
*/
static int llc_ui_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
return -ENOIOCTLCMD;
}
/**
* llc_ui_setsockopt - set various connection specific parameters.
* @sock: Socket to set options on.
* @level: Socket level user is requesting operations on.
* @optname: Operation name.
* @optval: User provided operation data.
* @optlen: Length of optval.
*
* Set various connection specific parameters.
*/
static int llc_ui_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
unsigned int opt;
int rc = -EINVAL;
lock_sock(sk);
if (unlikely(level != SOL_LLC || optlen != sizeof(int)))
goto out;
rc = get_user(opt, (int __user *)optval);
if (rc)
goto out;
rc = -EINVAL;
switch (optname) {
case LLC_OPT_RETRY:
if (opt > LLC_OPT_MAX_RETRY)
goto out;
llc->n2 = opt;
break;
case LLC_OPT_SIZE:
if (opt > LLC_OPT_MAX_SIZE)
goto out;
llc->n1 = opt;
break;
case LLC_OPT_ACK_TMR_EXP:
if (opt > <API key>)
goto out;
llc->ack_timer.expire = opt * HZ;
break;
case LLC_OPT_P_TMR_EXP:
if (opt > <API key>)
goto out;
llc->pf_cycle_timer.expire = opt * HZ;
break;
case LLC_OPT_REJ_TMR_EXP:
if (opt > <API key>)
goto out;
llc->rej_sent_timer.expire = opt * HZ;
break;
case <API key>:
if (opt > <API key>)
goto out;
llc->busy_state_timer.expire = opt * HZ;
break;
case LLC_OPT_TX_WIN:
if (opt > LLC_OPT_MAX_WIN)
goto out;
llc->k = opt;
break;
case LLC_OPT_RX_WIN:
if (opt > LLC_OPT_MAX_WIN)
goto out;
llc->rw = opt;
break;
case LLC_OPT_PKTINFO:
if (opt)
llc->cmsg_flags |= LLC_CMSG_PKTINFO;
else
llc->cmsg_flags &= ~LLC_CMSG_PKTINFO;
break;
default:
rc = -ENOPROTOOPT;
goto out;
}
rc = 0;
out:
release_sock(sk);
return rc;
}
/**
* llc_ui_getsockopt - get connection specific socket info
* @sock: Socket to get information from.
* @level: Socket level user is requesting operations on.
* @optname: Operation name.
* @optval: Variable to return operation data in.
* @optlen: Length of optval.
*
* Get connection specific socket information.
*/
static int llc_ui_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
int val = 0, len = 0, rc = -EINVAL;
lock_sock(sk);
if (unlikely(level != SOL_LLC))
goto out;
rc = get_user(len, optlen);
if (rc)
goto out;
rc = -EINVAL;
if (len != sizeof(int))
goto out;
switch (optname) {
case LLC_OPT_RETRY:
val = llc->n2; break;
case LLC_OPT_SIZE:
val = llc->n1; break;
case LLC_OPT_ACK_TMR_EXP:
val = llc->ack_timer.expire / HZ; break;
case LLC_OPT_P_TMR_EXP:
val = llc->pf_cycle_timer.expire / HZ; break;
case LLC_OPT_REJ_TMR_EXP:
val = llc->rej_sent_timer.expire / HZ; break;
case <API key>:
val = llc->busy_state_timer.expire / HZ; break;
case LLC_OPT_TX_WIN:
val = llc->k; break;
case LLC_OPT_RX_WIN:
val = llc->rw; break;
case LLC_OPT_PKTINFO:
val = (llc->cmsg_flags & LLC_CMSG_PKTINFO) != 0;
break;
default:
rc = -ENOPROTOOPT;
goto out;
}
rc = 0;
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
rc = -EFAULT;
out:
release_sock(sk);
return rc;
}
static const struct net_proto_family llc_ui_family_ops = {
.family = PF_LLC,
.create = llc_ui_create,
.owner = THIS_MODULE,
};
static const struct proto_ops llc_ui_ops = {
.family = PF_LLC,
.owner = THIS_MODULE,
.release = llc_ui_release,
.bind = llc_ui_bind,
.connect = llc_ui_connect,
.socketpair = sock_no_socketpair,
.accept = llc_ui_accept,
.getname = llc_ui_getname,
.poll = datagram_poll,
.ioctl = llc_ui_ioctl,
.listen = llc_ui_listen,
.shutdown = llc_ui_shutdown,
.setsockopt = llc_ui_setsockopt,
.getsockopt = llc_ui_getsockopt,
.sendmsg = llc_ui_sendmsg,
.recvmsg = llc_ui_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const char llc_proc_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the proc_fs entries\n";
static const char llc_sysctl_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the sysctl entries\n";
static const char llc_sock_err_msg[] __initconst =
KERN_CRIT "LLC: Unable to register the network family\n";
static int __init llc2_init(void)
{
int rc = proto_register(&llc_proto, 0);
if (rc != 0)
goto out;
<API key>();
llc_station_init();
<API key> = LLC_SAP_DYN_START;
rc = llc_proc_init();
if (rc != 0) {
printk(llc_proc_err_msg);
goto out_station;
}
rc = llc_sysctl_init();
if (rc) {
printk(llc_sysctl_err_msg);
goto out_proc;
}
rc = sock_register(&llc_ui_family_ops);
if (rc) {
printk(llc_sock_err_msg);
goto out_sysctl;
}
llc_add_pack(LLC_DEST_SAP, llc_sap_handler);
llc_add_pack(LLC_DEST_CONN, llc_conn_handler);
out:
return rc;
out_sysctl:
llc_sysctl_exit();
out_proc:
llc_proc_exit();
out_station:
llc_station_exit();
proto_unregister(&llc_proto);
goto out;
}
static void __exit llc2_exit(void)
{
llc_station_exit();
llc_remove_pack(LLC_DEST_SAP);
llc_remove_pack(LLC_DEST_CONN);
sock_unregister(PF_LLC);
llc_proc_exit();
llc_sysctl_exit();
proto_unregister(&llc_proto);
}
module_init(llc2_init);
module_exit(llc2_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Procom 1997, Jay Schullist 2001, Arnaldo C. Melo 2001-2003");
MODULE_DESCRIPTION("IEEE 802.2 PF_LLC support");
<API key>(PF_LLC); |
module Sass::Script
# The abstract superclass for SassScript objects.
# Many of these methods, especially the ones that correspond to SassScript operations,
# are designed to be overridden by subclasses which may change the semantics somewhat.
# The operations listed here are just the defaults.
class Literal < Node
require 'sass/script/string'
require 'sass/script/number'
require 'sass/script/color'
require 'sass/script/bool'
require 'sass/script/null'
require 'sass/script/list'
require 'sass/script/arg_list'
# Returns the Ruby value of the literal.
# The type of this value varies based on the subclass.
# @return [Object]
attr_reader :value
# Creates a new literal.
# @param value [Object] The object for \{#value}
def initialize(value = nil)
@value = value
super()
end
# Returns an empty array.
# @return [Array<Node>] empty
# @see Node#children
def children
[]
end
# @see Node#deep_copy
def deep_copy
dup
end
# Returns the options hash for this node.
# @return [{Symbol => Object}]
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
# This should only happen when the literal was created
# outside of the parser and \{#to\_s} was called on it
def options
opts = super
return opts if opts
raise Sass::SyntaxError.new(<<MSG)
The #options attribute is not set on this #{self.class}.
This error is probably occurring because #to_s was called
on this literal within a custom Sass function without first
setting the #option attribute.
MSG
end
# The SassScript `==` operation.
# **Note that this returns a {Sass::Script::Bool} object,
# not a Ruby boolean**.
# @param other [Literal] The right-hand side of the operator
# @return [Bool] True if this literal is the same as the other,
# false otherwise
def eq(other)
Sass::Script::Bool.new(self.class == other.class && self.value == other.value)
end
# The SassScript `!=` operation.
# **Note that this returns a {Sass::Script::Bool} object,
# not a Ruby boolean**.
# @param other [Literal] The right-hand side of the operator
# @return [Bool] False if this literal is the same as the other,
# true otherwise
def neq(other)
Sass::Script::Bool.new(!eq(other).to_bool)
end
# The SassScript `==` operation.
# **Note that this returns a {Sass::Script::Bool} object,
# not a Ruby boolean**.
# @param other [Literal] The right-hand side of the operator
# @return [Bool] True if this literal is the same as the other,
# false otherwise
def unary_not
Sass::Script::Bool.new(!to_bool)
end
# The SassScript default operation (e.g. `$a $b`, `"foo" "bar"`).
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# separated by a space
def space(other)
Sass::Script::String.new("#{self.to_s} #{other.to_s}")
end
# The SassScript `,` operation (e.g. `$a, $b`, `"foo", "bar"`).
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# separated by `", "`
def comma(other)
Sass::Script::String.new("#{self.to_s},#{' ' unless options[:style] == :compressed}#{other.to_s}")
end
# The SassScript `=` operation
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# separated by `"="`
def single_eq(other)
Sass::Script::String.new("#{self.to_s}=#{other.to_s}")
end
# The SassScript `+` operation.
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# without any separation
def plus(other)
if other.is_a?(Sass::Script::String)
return Sass::Script::String.new(self.to_s + other.value, other.type)
end
Sass::Script::String.new(self.to_s + other.to_s)
end
# The SassScript `-` operation.
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# separated by `"-"`
def minus(other)
Sass::Script::String.new("#{self.to_s}-#{other.to_s}")
end
# The SassScript `/` operation.
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing both literals
# separated by `"/"`
def div(other)
Sass::Script::String.new("#{self.to_s}/#{other.to_s}")
end
# The SassScript unary `+` operation (e.g. `+$a`).
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing the literal
# preceded by `"+"`
def unary_plus
Sass::Script::String.new("+#{self.to_s}")
end
# The SassScript unary `-` operation (e.g. `-$a`).
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing the literal
# preceded by `"-"`
def unary_minus
Sass::Script::String.new("-#{self.to_s}")
end
# The SassScript unary `/` operation (e.g. `/$a`).
# @param other [Literal] The right-hand side of the operator
# @return [Script::String] A string containing the literal
# preceded by `"/"`
def unary_div
Sass::Script::String.new("/#{self.to_s}")
end
# @return [String] A readable representation of the literal
def inspect
value.inspect
end
# @return [Boolean] `true` (the Ruby boolean value)
def to_bool
true
end
# Compares this object with another.
# @param other [Object] The object to compare with
# @return [Boolean] Whether or not this literal is equivalent to `other`
def ==(other)
eq(other).to_bool
end
# @return [Fixnum] The integer value of this literal
# @raise [Sass::SyntaxError] if this literal isn't an integer
def to_i
raise Sass::SyntaxError.new("#{self.inspect} is not an integer.")
end
# @raise [Sass::SyntaxError] if this literal isn't an integer
def assert_int!; to_i; end
# Returns the value of this literal as a list.
# Single literals are considered the same as single-element lists.
# @return [Array<Literal>] The of this literal as a list
def to_a
[self]
end
# Returns the string representation of this literal
# as it would be output to the CSS document.
# @return [String]
def to_s(opts = {})
raise Sass::SyntaxError.new("[BUG] All subclasses of Sass::Literal must implement #to_s.")
end
alias_method :to_sass, :to_s
# Returns whether or not this object is null.
# @return [Boolean] `false`
def null?
false
end
protected
# Evaluates the literal.
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
# @return [Literal] This literal
def _perform(environment)
self
end
end
end |
#include <asm/rtc.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/param.h>
#include <linux/jiffies.h>
#include <linux/bcd.h>
#include <linux/timex.h>
#include <linux/init.h>
#include <linux/profile.h>
#include <linux/sched.h> /* just for sched_clock() - funny that */
int have_rtc; /* used to remember if we have an RTC or not */;
#define TICK_SIZE tick
extern unsigned long loops_per_jiffy; /* init/main.c */
unsigned long loops_per_usec;
extern unsigned long <API key>(void);
static unsigned long (*do_gettimeoffset)(void) = <API key>;
/*
* This version of gettimeofday has near microsecond resolution.
*
* Note: Division is quite slow on CRIS and do_gettimeofday is called
* rather often. Maybe we should do some kind of approximation here
* (a naive approximation would be to divide by 1024).
*/
void do_gettimeofday(struct timeval *tv)
{
unsigned long flags;
signed long usec, sec;
local_irq_save(flags);
usec = do_gettimeoffset();
/*
* If time_adjust is negative then NTP is slowing the clock
* so make sure not to go into next possible interval.
* Better to lose some accuracy than have time go backwards..
*/
if (unlikely(time_adjust < 0) && usec > tickadj)
usec = tickadj;
sec = xtime.tv_sec;
usec += xtime.tv_nsec / 1000;
local_irq_restore(flags);
while (usec >= 1000000) {
usec -= 1000000;
sec++;
}
tv->tv_sec = sec;
tv->tv_usec = usec;
}
EXPORT_SYMBOL(do_gettimeofday);
int do_settimeofday(struct timespec *tv)
{
time_t wtm_sec, sec = tv->tv_sec;
long wtm_nsec, nsec = tv->tv_nsec;
if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
return -EINVAL;
write_seqlock_irq(&xtime_lock);
/*
* This is revolting. We need to set "xtime" correctly. However, the
* value in this location is the value at the most recent update of
* wall time. Discover what correction gettimeofday() would have
* made, and then undo it!
*/
nsec -= do_gettimeoffset() * NSEC_PER_USEC;
wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
<API key>(&xtime, sec, nsec);
<API key>(&wall_to_monotonic, wtm_sec, wtm_nsec);
ntp_clear();
write_sequnlock_irq(&xtime_lock);
clock_was_set();
return 0;
}
EXPORT_SYMBOL(do_settimeofday);
/*
* BUG: This routine does not handle hour overflow properly; it just
* sets the minutes. Usually you'll only notice that after reboot!
*/
int set_rtc_mmss(unsigned long nowtime)
{
int retval = 0;
int real_seconds, real_minutes, cmos_minutes;
printk(KERN_DEBUG "set_rtc_mmss(%lu)\n", nowtime);
if(!have_rtc)
return 0;
cmos_minutes = CMOS_READ(RTC_MINUTES);
BCD_TO_BIN(cmos_minutes);
/*
* since we're only adjusting minutes and seconds,
* don't interfere with hour overflow. This avoids
* messing with unknown time zones but requires your
* RTC not to be off by more than 15 minutes
*/
real_seconds = nowtime % 60;
real_minutes = nowtime / 60;
if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1)
real_minutes += 30; /* correct for half hour time zone */
real_minutes %= 60;
if (abs(real_minutes - cmos_minutes) < 30) {
BIN_TO_BCD(real_seconds);
BIN_TO_BCD(real_minutes);
CMOS_WRITE(real_seconds,RTC_SECONDS);
CMOS_WRITE(real_minutes,RTC_MINUTES);
} else {
printk(KERN_WARNING
"set_rtc_mmss: can't update from %d to %d\n",
cmos_minutes, real_minutes);
retval = -1;
}
return retval;
}
/* grab the time from the RTC chip */
unsigned long
get_cmos_time(void)
{
unsigned int year, mon, day, hour, min, sec;
sec = CMOS_READ(RTC_SECONDS);
min = CMOS_READ(RTC_MINUTES);
hour = CMOS_READ(RTC_HOURS);
day = CMOS_READ(RTC_DAY_OF_MONTH);
mon = CMOS_READ(RTC_MONTH);
year = CMOS_READ(RTC_YEAR);
BCD_TO_BIN(sec);
BCD_TO_BIN(min);
BCD_TO_BIN(hour);
BCD_TO_BIN(day);
BCD_TO_BIN(mon);
BCD_TO_BIN(year);
if ((year += 1900) < 1970)
year += 100;
return mktime(year, mon, day, hour, min, sec);
}
/* update xtime from the CMOS settings. used when /dev/rtc gets a SET_TIME.
* TODO: this doesn't reset the fancy NTP phase stuff as do_settimeofday does.
*/
void
<API key>(void)
{
if(have_rtc) {
xtime.tv_sec = get_cmos_time();
xtime.tv_nsec = 0;
}
}
extern void cris_profile_sample(struct pt_regs* regs);
void
cris_do_profile(struct pt_regs* regs)
{
#ifdef <API key>
cris_profile_sample(regs);
#endif
#ifdef CONFIG_PROFILING
profile_tick(CPU_PROFILING);
#endif
}
static int
__init init_udelay(void)
{
loops_per_usec = (loops_per_jiffy * HZ) / 1000000;
return 0;
}
__initcall(init_udelay); |
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
// The List of welcome pages tabs.
global $<API key>;
/**
* Get welcome pages main slug.
*
* @since 4.5
* @return mixed|string
*/
function <API key>() {
global $<API key>;
return isset( $<API key> ) ? key( $<API key> ) : '';
}
/**
* Build vc-welcome page block which will be shown after Vc installation.
*
* vc_filter: <API key>
*
* @since 4.5
*/
function <API key>() {
global $<API key>;
$slug = <API key>();
$tab_slug = vc_get_param( 'tab', $slug );
// If tab slug in the list please render;
if ( ! empty( $tab_slug ) && isset( $<API key>[ $tab_slug ] ) ) {
$pages_group = <API key>( $slug, $<API key>[ $tab_slug ], $tab_slug );
$pages_group->render();
}
}
function <API key>() {
// Add submenu page
$page = add_submenu_page( VC_PAGE_MAIN_SLUG,
__( 'About', 'js_composer' ),
__( 'About', 'js_composer' ),
'exist',
<API key>(), '<API key>' );
// Css for perfect styling.
add_action( 'admin_print_styles-' . $page, 'vc_page_css_enqueue' );
}
function <API key>() {
$<API key> = vc_user_access()->wpAny( 'manage_options' )
->part( 'settings' )
->can( 'vc-general-tab' )
->get();
add_action( 'vc_menu_page_build', '<API key>',
$<API key> ? 11 : 1 );
add_action( '<API key>', '<API key>', $<API key> ? 11 : 1 );
}
add_action( 'init', '<API key>' );
/**
* Set redirect transition on update or activation
* @since 4.5
*/
function <API key>() {
if ( ! is_network_admin() && ! vc_get_param( 'activate-multi' ) ) {
set_transient( '<API key>', 1, 30 );
}
}
/**
* Do redirect if required on welcome page
* @since 4.5
*/
function <API key>() {
$redirect = get_transient( '<API key>' );
delete_transient( '<API key>' );
$redirect && wp_redirect( admin_url( 'admin.php?page=' . rawurlencode( <API key>() ) ) );
}
// Enables redirect on activation.
add_action( 'vc_activation_hook', '<API key>' );
add_action( 'init', '<API key>' );
$<API key> = apply_filters( '<API key>',
array(
'vc-welcome' => __( 'What\'s New', 'js_composer' ),
'vc-faq' => __( 'FAQ', 'js_composer' ),
'vc-resources' => __( 'Resources', 'js_composer' ),
) ); |
#ifndef <API key>
#define <API key>
#include "qgis_sip.h"
#include "qgis_core.h"
#include <QMap>
#include <QString>
#include <QMetaType>
#include <QVariant>
class QgsVectorLayer;
class QDomNode;
class QDomDocument;
/**
* \ingroup core
* Manages QGIS Server properties for a vector layer
* \since QGIS 3.10
*/
class CORE_EXPORT <API key>
{
Q_GADGET
public:
/**
* Predefined/Restricted WMS Dimension name
* \since QGIS 3.10
*/
enum <API key>
{
TIME,
DATE,
ELEVATION
};
Q_ENUM( <API key> )
/**
* Setting to define QGIS Server WMS Dimension.
* \since QGIS 3.10
*/
struct CORE_EXPORT WmsDimensionInfo
{
/**
* Selection behavior for QGIS Server WMS Dimension default display
* \since QGIS 3.10
*/
enum DefaultDisplay
{
AllValues = 0, //!< Display all values of the dimension
MinValue = 1, //!< Add selection to current selection
MaxValue = 2, //!< Modify current selection to include only select features which match
ReferenceValue = 3, //!< Remove from current selection
};
/**
* Constructor for WmsDimensionInfo.
*/
explicit WmsDimensionInfo( const QString &dimName,
const QString &dimFieldName,
const QString &dimEndFieldName = QString(),
const QString &dimUnits = QString(),
const QString &dimUnitSymbol = QString(),
const int &<API key> = <API key>::WmsDimensionInfo::AllValues,
const QVariant &dimReferenceValue = QVariant() )
: name( dimName )
, fieldName( dimFieldName )
, endFieldName( dimEndFieldName )
, units( dimUnits )
, unitSymbol( dimUnitSymbol )
, defaultDisplayType( <API key> )
, referenceValue( dimReferenceValue )
{}
QString name;
QString fieldName;
QString endFieldName;
QString units;
QString unitSymbol;
int defaultDisplayType;
QVariant referenceValue;
};
/**
* Constructor - Creates a Vector Layer QGIS Server Properties
*
* \param layer The vector layer
*/
<API key>( QgsVectorLayer *layer = nullptr );
/**
* Returns WMS Dimension default display labels
* \since QGIS 3.10
*/
static QMap<int, QString> <API key>();
/**
* Adds a QGIS Server WMS Dimension
* \param wmsDimInfo QGIS Server WMS Dimension object with, name, field, etc
* \returns TRUE if QGIS Server WMS Dimension has been successfully added
* \since QGIS 3.10
*/
bool addWmsDimension( const <API key>::WmsDimensionInfo &wmsDimInfo );
/**
* Removes a QGIS Server WMS Dimension
* \returns TRUE if QGIS Server WMS Dimension was found and successfully removed
* \since QGIS 3.10
*/
bool removeWmsDimension( const QString &wmsDimName );
/**
* Returns the QGIS Server WMS Dimension list.
* \since QGIS 3.10
*/
const QList<<API key>::WmsDimensionInfo> wmsDimensions() const;
/**
* Saves server properties to xml under the layer node
* \since QGIS 3.10
*/
void writeXml( QDomNode &layer_node, QDomDocument &document ) const;
/**
* Reads server properties from project file.
* \since QGIS 3.10
*/
void readXml( const QDomNode &layer_node );
private: // Private attributes
QgsVectorLayer *mLayer = nullptr;
//!stores QGIS Server WMS Dimension definitions
QList<<API key>::WmsDimensionInfo> mWmsDimensions;
};
#endif // <API key> |
include $(TOPDIR)/rules.mk
PKG_NAME:=<API key>
PKG_VERSION:=0.7.0
PKG_RELEASE:=1
PYPI_NAME:=$(PKG_NAME)
PKG_HASH:=<SHA256-like>
PKG_MAINTAINER:=Eneas U de Queiroz <cotequeiroz@gmail.com>
PKG_LICENSE:=MIT
PKG_LICENSE_FILES:=LICENSE
include ../pypi.mk
include $(INCLUDE_DIR)/package.mk
include ../python3-package.mk
define Package/<API key>
SUBMENU:=Python
SECTION:=lang
CATEGORY:=Languages
TITLE:=Transparently use webpack in django
URL:=https://github.com/owais/<API key>
DEPENDS:= \
@BROKEN \
+python3 \
+python3-django1
endef
define Package/<API key>/description
Use webpack to generate your static bundles without django’s staticfiles or opaque wrappers.
endef
$(eval $(call Py3Package,<API key>))
$(eval $(call BuildPackage,<API key>))
$(eval $(call BuildPackage,<API key>)) |
package dom.ls;
import java.io.IOException;
import java.io.<API key>;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.<API key>;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSParserFilter;
import org.w3c.dom.traversal.NodeFilter;
import org.xml.sax.SAXException;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -DrunSecMngr=true dom.ls.LSParserTCKTest
* @run testng/othervm dom.ls.LSParserTCKTest
* @summary Test Specifications and Descriptions for LSParser.
*/
@Listeners({jaxp.library.BasePolicy.class})
public class LSParserTCKTest {
DOMImplementationLS implLS = null;
public String xml1 = "<?xml version=\"1.0\"?><ROOT><ELEMENT1><CHILD1/><CHILD1><COC1/></CHILD1></ELEMENT1><ELEMENT2>test1<CHILD2/></ELEMENT2></ROOT>";
/**
* Equivalence class partitioning
* with state, input and output values orientation
* for public Document parse(LSInput is),
* <br><b>pre-conditions</b>: set filter that REJECTs any CHILD* node,
* <br><b>is</b>: xml1
* <br><b>output</b>: XML document with ELEMNENT1 and ELEMENT2 only.
*/
@Test
public void testfilter0001() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
if (enode.getNodeName().startsWith("CHILD")) {
return FILTER_REJECT;
}
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<?xml version=\"1.0\"?><ROOT><ELEMENT1></ELEMENT1><ELEMENT2>test1</ELEMENT2></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
public LSParserTCKTest(String name) {
init();
}
protected void init() {
Document doc = null;
DocumentBuilder parser = null;
try {
parser = <API key>.newInstance().newDocumentBuilder();
} catch (<API key> e) {
e.printStackTrace();
}
<API key> is = new <API key>(xml1);
try {
doc = parser.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DOMImplementation impl = doc.getImplementation();
implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
}
public LSInput getXmlSource(String xmldoc) {
LSInput srcdoc = createLSInput();
srcdoc.setStringData(xmldoc);
return srcdoc;
}
public LSInput createLSInput() {
return implLS.createLSInput();
}
public LSParser createLSParser() {
return implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, "http:
}
public boolean match(String template, Node source) {
LSParser dp = createLSParser();
if (dp == null) {
System.out.println("Can not create LSParser.");
return false;
}
LSInput src = getXmlSource(template);
Document doc = dp.parse(src);
return checkXMLs(doc, source);
}
public boolean checkXMLs(Node template, Node source) {
if (source == null || template == null) {
return template == source;
}
String tname = template.getLocalName();
String tvalue = template.getNodeValue();
NamedNodeMap tattr = template.getAttributes();
NodeList tchildren = template.getChildNodes();
String sname = source.getLocalName();
String svalue = source.getNodeValue();
NamedNodeMap sattr = source.getAttributes();
NodeList schildren = source.getChildNodes();
if (tname != null && !tname.equals(sname)) {
return false;
}
if (tvalue != null && !tvalue.equals(svalue)) {
return false;
}
if (tattr != null && sattr != null) {
if (sattr.getLength() != tattr.getLength()) {
return false;
}
for (int i = 0; i < tattr.getLength(); i++) {
Attr t = (Attr) tattr.item(i);
Attr s = (Attr) sattr.getNamedItem(t.getName());
if (!checkXMLAttrs(t, s)) {
// ref.println(sname+": [expected attr: " + t +
// "; actual attr: " +s+"]");
return false;
}
}
} else if (tattr != null || sattr != null) {
return false;
}
for (int i = 0; i < tchildren.getLength(); i++) {
if (!checkXMLs(tchildren.item(i), schildren.item(i))) {
// ref.println(sname+": [expected node: "+tchildren.item(i)
// +"; actual node: "+schildren.item(i)+"]");
return false;
}
}
return true;
}
public boolean checkXMLAttrs(Attr template, Attr source) {
if (source == null || template == null) {
return template == source;
}
String tname = template.getName();
String tvalue = template.getValue();
String sname = source.getName();
String svalue = source.getValue();
System.out.println("Attr:" + tname + "?" + sname);
if (tname != null && !tname.equals(sname)) {
// ref.println("Attr Name:" + tname + "!=" + sname);
return false;
}
if (tvalue != null && !tvalue.equals(svalue)) {
// ref.println("Attr value:" + tvalue + "!=" + svalue);
return false;
}
// ref.println("Attr:" + tname + ":" + tvalue + "=" + sname + ":" +
// svalue);
return true;
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs ELEMENT1 node, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: XML document with CHILD1 and ELEMENT2 only.
*/
@Test
public void testFilter0002() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
if (enode.getNodeName().startsWith("ELEMENT1")) {
return FILTER_SKIP;
}
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<?xml version=\"1.0\"?><ROOT><CHILD1/><CHILD1><COC1/></CHILD1><ELEMENT2>test1<CHILD2/></ELEMENT2></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs ELEMENT1 node, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: XML document with ELEMENT1 only.
*/
@Test
public void testFilter0003() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
if (enode.getNodeName().startsWith("ELEMENT2")) {
return FILTER_INTERRUPT;
}
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<ROOT><ELEMENT1><CHILD1/><CHILD1><COC1/></CHILD1></ELEMENT1></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that accepts all, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: full XML document.
*/
@Test
public void testFilter0004() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<ROOT><ELEMENT1><CHILD1/><CHILD1><COC1/></CHILD1></ELEMENT1><ELEMENT2>test1<CHILD2/></ELEMENT2></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that REJECTs all, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: empty XML document.
*/
@Test
public void testFilter0005() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_REJECT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
Document doc = parser.parse(getXmlSource(xml1));
NodeList children = doc.getDocumentElement().getChildNodes();
if (children.getLength() != 0) {
Assert.fail("Not all children skipped");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs all, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: empty XML document.
*/
@Test
public void testFilter0006() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_SKIP;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
Document doc = parser.parse(getXmlSource(xml1));
NodeList children = doc.getDocumentElement().getChildNodes();
if (children.getLength() != 0) {
Assert.fail("Not all children skipped");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that REJECTs any CHILD* start element, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: XML document with ELEMENT1 and ELEMENT2 only.
*/
@Test
public void testFilter0007() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
if (elt.getTagName().startsWith("CHILD")) {
return FILTER_REJECT;
}
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<?xml version=\"1.0\"?><ROOT><ELEMENT1></ELEMENT1><ELEMENT2>test1</ELEMENT2></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs ELEMENT1 start element, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: XML document with CHILD1 and ELEMENT2 only.
*/
@Test
public void testFilter0008() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
if (elt.getTagName().equals("ELEMENT1")) {
return FILTER_SKIP;
}
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<?xml version=\"1.0\"?><ROOT><CHILD1/><CHILD1><COC1/></CHILD1><ELEMENT2>test1<CHILD2/></ELEMENT2></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs ELEMENT1 start element, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: XML document with ELEMENT1 only.
*/
@Test
public void testFilter0009() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser!");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
if (elt.getTagName().startsWith("ELEMENT2")) {
return FILTER_INTERRUPT;
}
return FILTER_ACCEPT;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
String expected = "<ROOT><ELEMENT1><CHILD1/><CHILD1><COC1/></CHILD1></ELEMENT1></ROOT>";
Document doc = parser.parse(getXmlSource(xml1));
if (!match(expected, doc)) {
Assert.fail("DOM structure after parsing is not equal to a structure of XML document, that being parsed");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that REJECTs all start element, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: empty XML document.
*/
@Test
public void testFilter0010() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_REJECT;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
Document doc = parser.parse(getXmlSource(xml1));
NodeList children = doc.getDocumentElement().getChildNodes();
if (children.getLength() != 0) {
Assert.fail("Not all children skipped");
}
System.out.println("OKAY");
}
/**
* Equivalence class partitioning with state, input and output values
* orientation for public Document parse(LSInput is), <br>
* <b>pre-conditions</b>: set filter that SKIPs all, <br>
* <b>is</b>: xml1 <br>
* <b>output</b>: empty XML document.
*/
@Test
public void testFilter0011() {
LSParser parser = createLSParser();
if (parser == null) {
Assert.fail("Unable to create LSParser");
}
// set filter
parser.setFilter(new LSParserFilter() {
public short startElement(Element elt) {
return FILTER_SKIP;
}
public short acceptNode(Node enode) {
return FILTER_ACCEPT;
}
public int getWhatToShow() {
return NodeFilter.SHOW_ALL;
}
});
Document doc = parser.parse(getXmlSource(xml1));
NodeList children = doc.getDocumentElement().getChildNodes();
if (children.getLength() != 1) {
Assert.fail("Not all Element nodes skipped");
}
System.out.println("OKAY");
}
} |
#include <device/device.h>
struct chip_operations <API key> = {
CHIP_NAME("Socket 940 CPU")
}; |
#include "common/memstream.h"
#include "pegasus/cursor.h"
#include "pegasus/pegasus.h"
#include "pegasus/ai/ai_area.h"
#include "pegasus/items/biochips/aichip.h"
#include "pegasus/items/biochips/biochipitem.h"
#include "pegasus/items/biochips/opticalchip.h"
#include "pegasus/items/biochips/pegasuschip.h"
#include "pegasus/items/inventory/airmask.h"
#include "pegasus/items/inventory/inventoryitem.h"
namespace Pegasus {
AIArea *g_AIArea = 0;
AIArea::AIArea(InputHandler *nextHandler) : InputHandler(nextHandler), _leftAreaMovie(kAILeftAreaID),
_middleAreaMovie(kAIMiddleAreaID), _rightAreaMovie(kAIRightAreaID), _AIMovie(kAIMovieID) {
g_AIArea = this;
_leftAreaOwner = kNoClientSignature;
_middleAreaOwner = kNoClientSignature;
_rightAreaOwner = kNoClientSignature;
_leftInventoryTime = 0xffffffff;
<API key> = 0xffffffff;
_middleBiochipTime = 0xffffffff;
_rightBiochipTime = 0xffffffff;
_lockCount = 0;
startIdling();
}
AIArea::~AIArea() {
if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip && currentBiochip->isSelected())
currentBiochip->giveUpSharedArea();
} else if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
if (currentItem && currentItem->isSelected())
currentItem->giveUpSharedArea();
}
stopIdling();
for (AIRuleList::iterator it = _AIRules.begin(); it != _AIRules.end(); it++)
delete *it;
g_AIArea = 0;
}
// Save last state of AI rules...
void AIArea::saveAIState() {
PegasusEngine *vm = (PegasusEngine *)g_engine;
delete vm->_aiSaveStream;
Common::<API key> out;
writeAIRules(&out);
vm->_aiSaveStream = new Common::MemoryReadStream(out.getData(), out.size(), DisposeAfterUse::YES);
}
void AIArea::restoreAIState() {
PegasusEngine *vm = (PegasusEngine *)g_engine;
if (vm->_aiSaveStream)
readAIRules(vm->_aiSaveStream);
}
void AIArea::writeAIRules(Common::WriteStream *stream) {
_AIRules.writeAIRules(stream);
}
void AIArea::readAIRules(Common::ReadStream *stream) {
_AIRules.readAIRules(stream);
}
void AIArea::initAIArea() {
allocateSurface(Common::Rect(0, 0, 384, 96));
_leftAreaMovie.shareSurface(this);
_leftAreaMovie.initFromMovieFile("Images/Items/Left Area Movie");
_leftAreaMovie.moveElementTo(kAILeftAreaLeft, kAILeftAreaTop);
_leftAreaMovie.setDisplayOrder(kAILeftAreaOrder);
_leftAreaMovie.startDisplaying();
_leftAreaMovie.setVolume(((PegasusEngine *)g_engine)->getSoundFXLevel());
_middleAreaMovie.shareSurface(this);
_middleAreaMovie.initFromMovieFile("Images/Items/Middle Area Movie");
_middleAreaMovie.moveElementTo(kAIMiddleAreaLeft, kAIMiddleAreaTop);
_middleAreaMovie.moveMovieBoxTo(kAIMiddleAreaLeft - kAILeftAreaLeft, 0);
_middleAreaMovie.setDisplayOrder(kAIMiddleAreaOrder);
_middleAreaMovie.startDisplaying();
_middleAreaMovie.setVolume(((PegasusEngine *)g_engine)->getSoundFXLevel());
_rightAreaMovie.shareSurface(this);
_rightAreaMovie.initFromMovieFile("Images/Items/Right Area Movie");
_rightAreaMovie.moveElementTo(kAIRightAreaLeft, kAIRightAreaTop);
_rightAreaMovie.moveMovieBoxTo(kAIRightAreaLeft - kAILeftAreaLeft, 0);
_rightAreaMovie.setDisplayOrder(kAIRightAreaOrder);
_rightAreaMovie.startDisplaying();
_rightAreaMovie.setVolume(((PegasusEngine *)g_engine)->getSoundFXLevel());
_AIMovie.setDisplayOrder(kAIMovieOrder);
}
void AIArea::setAIVolume(const uint16 volume) {
_leftAreaMovie.setVolume(volume);
_middleAreaMovie.setVolume(volume);
_rightAreaMovie.setVolume(volume);
}
// Here is the list of supported pairs:
// kInventorySignature kLeftAreaSignature
// kInventorySignature <API key>
// kBiochipSignature <API key>
// kBiochipSignature kRightAreaSignature
// kAISignature kLeftAreaSignature
// Further, the kAISignature never sets a static frame time in the left area,
// but only plays a sequence.
// If this function is called while a sequence is playing, it will just "remember"
// the time value, so that when the sequence finishes, the new time is asserted.
void AIArea::setAIAreaToTime(const <API key> client, const LowerAreaSignature area, const TimeValue time) {
switch (area) {
case kLeftAreaSignature:
// Only support kInventorySignature client, since AI never calls SetAIAreaToTime.
_leftAreaMovie.setSegment(0, _leftAreaMovie.getDuration());
if (time == 0xffffffff) {
_leftAreaMovie.hide();
_leftAreaOwner = kNoClientSignature;
} else {
setLeftMovieTime(time);
}
break;
case <API key>:
// Only support kInventorySignature and kBiochipSignature clients.
_middleAreaMovie.stop();
_middleAreaMovie.setFlags(0);
_middleAreaMovie.setSegment(0, _middleAreaMovie.getDuration());
if (time == 0xffffffff) {
if (client == kInventorySignature) {
if (_middleBiochipTime != 0xffffffff) {
setMiddleMovieTime(kBiochipSignature, _middleBiochipTime);
} else {
_middleAreaMovie.hide();
_middleAreaOwner = kNoClientSignature;
}
} else { // client == kBiochipSignature
if (<API key> != 0xffffffff) {
setMiddleMovieTime(kInventorySignature, <API key>);
} else {
_middleAreaMovie.hide();
_middleAreaOwner = kNoClientSignature;
}
}
} else {
setMiddleMovieTime(client, time);
}
break;
case kRightAreaSignature:
// Only support kBiochipSignature client.
_rightAreaMovie.setSegment(0, _rightAreaMovie.getDuration());
if (time == 0xffffffff) {
_rightAreaMovie.hide();
_rightAreaOwner = kNoClientSignature;
} else {
setRightMovieTime(time);
}
break;
}
}
// Plays a sequence on an area. When the sequence ends, the previous image
// is restored.
// Also, is input disabled or not?
// Easy answer: yes.
// Here is the list of supported pairs:
// kBiochipSignature <API key>
// kBiochipSignature kRightAreaSignature
// kInventorySignature <API key>
void AIArea::playAIAreaSequence(const <API key>, const LowerAreaSignature area, const TimeValue start, const TimeValue stop) {
PegasusEngine *vm = (PegasusEngine *)g_engine;
lockAIOut();
switch (area) {
case kLeftAreaSignature:
break;
case <API key>:
if (_middleAreaOwner == kInventorySignature)
<API key> = _middleAreaMovie.getTime();
else if (_middleAreaOwner == kBiochipSignature)
_middleBiochipTime = _middleAreaMovie.getTime();
_middleAreaMovie.stop();
_middleAreaMovie.setFlags(0);
_middleAreaMovie.setSegment(start, stop);
_middleAreaMovie.setTime(start);
_middleAreaMovie.show();
_middleAreaMovie.start();
vm->_cursor->hide();
while (_middleAreaMovie.isRunning()) {
InputDevice.pumpEvents();
vm->checkCallBacks();
vm->refreshDisplay();
g_system->delayMillis(10);
}
_middleAreaMovie.stop();
vm->_cursor->hideUntilMoved();
if (_middleAreaOwner == kInventorySignature)
setAIAreaToTime(_middleAreaOwner, <API key>, <API key>);
else if (_middleAreaOwner == kBiochipSignature)
setAIAreaToTime(_middleAreaOwner, <API key>, _middleBiochipTime);
else
setAIAreaToTime(_middleAreaOwner, <API key>, 0xffffffff);
break;
case kRightAreaSignature:
_rightBiochipTime = _rightAreaMovie.getTime();
_rightAreaMovie.setSegment(start, stop);
_rightAreaMovie.setTime(start);
_rightAreaMovie.show();
_rightAreaMovie.start();
vm->_cursor->hide();
while (_rightAreaMovie.isRunning()) {
InputDevice.pumpEvents();
vm->checkCallBacks();
vm->refreshDisplay();
g_system->delayMillis(10);
}
_rightAreaMovie.stop();
vm->_cursor->hideUntilMoved();
setAIAreaToTime(_rightAreaOwner, kRightAreaSignature, _rightBiochipTime);
break;
}
unlockAI();
}
bool AIArea::playAIMovie(const LowerAreaSignature area, const Common::String &movieName, bool keepLastFrame, const InputBits interruptFilter) {
PegasusEngine *vm = (PegasusEngine *)g_engine;
lockAIOut();
InputDevice.waitInput(interruptFilter);
if (_AIMovie.isMovieValid())
_AIMovie.releaseMovie();
_AIMovie.shareSurface(this);
_AIMovie.initFromMovieFile(movieName);
if (area == kLeftAreaSignature) {
_AIMovie.moveElementTo(kAILeftAreaLeft, kAILeftAreaTop);
_leftAreaMovie.hide();
} else {
_AIMovie.moveElementTo(kAIRightAreaLeft, kAIRightAreaTop);
_AIMovie.moveMovieBoxTo(kAIRightAreaLeft - kAILeftAreaLeft, 0);
_rightAreaMovie.hide();
}
_AIMovie.setTime(0);
_AIMovie.startDisplaying();
_AIMovie.show();
_AIMovie.redrawMovieWorld();
_AIMovie.setVolume(vm->getSoundFXLevel());
_AIMovie.start();
vm->_cursor->hide();
bool result = true;
bool saveAllowed = vm->swapSaveAllowed(false);
bool openAllowed = vm->swapLoadAllowed(false);
while (_AIMovie.isRunning()) {
Input input;
InputDevice.getInput(input, interruptFilter);
if (input.anyInput() || vm->shouldQuit() || vm->saveRequested() || vm->loadRequested()) {
result = false;
break;
}
vm->checkCallBacks();
vm->refreshDisplay();
g_system->delayMillis(10);
}
_AIMovie.stop();
vm->swapSaveAllowed(saveAllowed);
vm->swapLoadAllowed(openAllowed);
// This used to keep the last frame up even if the movie was interrupted.
// However, this only occurs in the recalibration, where interruption means skip the
// whole thing, so skipping causes the AI to go away even when keepLastFrame is true.
if (!(result && keepLastFrame)) {
_AIMovie.stopDisplaying();
_AIMovie.releaseMovie();
if (area == kLeftAreaSignature) {
_leftAreaMovie.setTime(_leftInventoryTime);
_leftAreaMovie.show();
_leftAreaMovie.redrawMovieWorld();
} else {
_rightAreaMovie.setTime(_rightBiochipTime);
_rightAreaMovie.show();
_rightAreaMovie.redrawMovieWorld();
}
}
vm->_cursor->hideUntilMoved();
unlockAI();
return result;
}
// Only implemented for <API key>, kInventorySignature
void AIArea::loopAIAreaSequence(const <API key> owner, const LowerAreaSignature area, const TimeValue start, const TimeValue stop) {
if (area == <API key> && owner == kInventorySignature && owner == _middleAreaOwner) {
_middleAreaMovie.stop();
_middleAreaMovie.setFlags(0);
_middleAreaMovie.setSegment(start, stop);
_middleAreaMovie.setFlags(kLoopTimeBase);
_middleAreaMovie.setTime(start);
_middleAreaMovie.show();
_middleAreaMovie.start();
}
}
// Only called by kInventorySignature.
void AIArea::setLeftMovieTime(const TimeValue time) {
if (!_AIMovie.isSurfaceValid()) {
_leftAreaMovie.setTime(time);
_leftAreaMovie.show();
_leftAreaMovie.redrawMovieWorld();
}
_leftAreaOwner = kInventorySignature;
_leftInventoryTime = time;
}
void AIArea::setMiddleMovieTime(const <API key> client, const TimeValue time) {
if (client == kInventorySignature) {
<API key> = time;
if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip && currentBiochip->isSelected())
currentBiochip->giveUpSharedArea();
}
} else {
_middleBiochipTime = time;
if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
if (currentItem && currentItem->isSelected())
currentItem->giveUpSharedArea();
}
}
_middleAreaMovie.setSegment(0, _middleAreaMovie.getDuration());
_middleAreaMovie.stop();
_middleAreaMovie.setFlags(0);
_middleAreaMovie.setTime(time);
_middleAreaMovie.show();
_middleAreaMovie.redrawMovieWorld();
_middleAreaOwner = client;
}
// Only called by kBiochipSignature.
void AIArea::setRightMovieTime(const TimeValue time) {
if (!_AIMovie.isSurfaceValid()) {
// Can't do it when the AI movie is up...
_rightAreaMovie.setTime(time);
_rightAreaMovie.show();
_rightAreaMovie.redrawMovieWorld();
}
_rightAreaOwner = kBiochipSignature;
_rightBiochipTime = time;
}
void AIArea::handleInput(const Input &input, const Hotspot *cursorSpot) {
if (JMPPPInput::<API key>(input))
<API key>();
else
InputHandler::handleInput(input, cursorSpot);
}
void AIArea::<API key>() {
if (_middleAreaOwner == kInventorySignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip) {
setMiddleMovieTime(kBiochipSignature, currentBiochip->getSharedAreaTime());
currentBiochip->takeSharedArea();
}
} else if (_middleAreaOwner == kBiochipSignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
if (currentItem) {
setMiddleMovieTime(kInventorySignature, currentItem->getSharedAreaTime());
currentItem->takeSharedArea();
}
}
}
void AIArea::activateHotspots() {
PegasusEngine *vm = (PegasusEngine *)g_engine;
if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip)
switch (currentBiochip->getObjectID()) {
case kAIBiochip:
((AIChip *)currentBiochip)->activateAIHotspots();
break;
case kPegasusBiochip:
if (!vm->isDemo())
((PegasusChip *)currentBiochip)-><API key>();
break;
case kOpticalBiochip:
((OpticalChip *)currentBiochip)-><API key>();
break;
}
} else if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
if (currentItem && currentItem->getObjectID() == kAirMask)
((AirMask *)currentItem)-><API key>();
}
InputHandler::activateHotspots();
}
void AIArea::clickInHotspot(const Input &input, const Hotspot *hotspot) {
PegasusEngine *vm = (PegasusEngine *)g_engine;
bool handled = false;
if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip) {
switch (currentBiochip->getObjectID()) {
case kAIBiochip:
if ((hotspot->getHotspotFlags() & kAIBiochipSpotFlag) != 0) {
((AIChip *)currentBiochip)->clickInAIHotspot(hotspot->getObjectID());
handled = true;
}
break;
case kPegasusBiochip:
if (!vm->isDemo() && ((hotspot->getHotspotFlags() & <API key>) != 0)) {
((PegasusChip *)currentBiochip)-><API key>();
handled = true;
}
break;
case kOpticalBiochip:
if ((hotspot->getHotspotFlags() & <API key>) != 0) {
((OpticalChip *)currentBiochip)-><API key>(hotspot->getObjectID());
handled = true;
}
break;
}
}
} else if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
if (currentItem) {
switch (currentItem->getObjectID()) {
case kAirMask:
if ((hotspot->getHotspotFlags() & kAirMaskSpotFlag) != 0) {
((AirMask *)currentItem)-><API key>();
handled = true;
}
break;
}
}
}
if (!handled)
InputHandler::clickInHotspot(input, hotspot);
}
void AIArea::lockAIOut() {
if (_lockCount == 0)
stopIdling();
_lockCount++;
}
void AIArea::unlockAI() {
if (_lockCount > 0) {
_lockCount
if (_lockCount == 0)
startIdling();
}
}
void AIArea::forceAIUnlocked() {
if (_lockCount > 0) {
_lockCount = 1;
unlockAI();
}
}
void AIArea::checkRules() {
if (_lockCount == 0 && ((PegasusEngine *)g_engine)->playerAlive())
for (AIRuleList::iterator it = _AIRules.begin(); it != _AIRules.end(); it++)
if ((*it)->fireRule())
break;
}
void AIArea::useIdleTime() {
checkRules();
}
void AIArea::addAIRule(AIRule *rule) {
_AIRules.push_back(rule);
}
void AIArea::removeAllRules() {
for (AIRuleList::iterator it = _AIRules.begin(); it != _AIRules.end(); it++)
delete *it;
_AIRules.clear();
}
void AIArea::checkMiddleArea() {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
if (currentBiochip) {
if (_middleAreaOwner == kBiochipSignature) {
switch (currentBiochip->getObjectID()) {
case kAIBiochip:
((AIChip *)currentBiochip)->setUpAIChip();
break;
case kPegasusBiochip:
((PegasusChip *)currentBiochip)->setUpPegasusChip();
break;
}
} else {
switch (currentBiochip->getObjectID()) {
case kAIBiochip:
((AIChip *)currentBiochip)->setUpAIChipRude();
break;
case kPegasusBiochip:
((PegasusChip *)currentBiochip)-><API key>();
break;
}
}
}
}
TimeValue AIArea::getBigInfoTime() {
if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
return currentItem->getInfoLeftTime();
} else if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
return currentBiochip->getInfoLeftTime();
}
return 0xffffffff;
}
void AIArea::getSmallInfoSegment(TimeValue &start, TimeValue &stop) {
if (_middleAreaOwner == kInventorySignature) {
InventoryItem *currentItem = ((PegasusEngine *)g_engine)-><API key>();
currentItem->getInfoRightTimes(start, stop);
} else if (_middleAreaOwner == kBiochipSignature) {
BiochipItem *currentBiochip = ((PegasusEngine *)g_engine)->getCurrentBiochip();
currentBiochip->getInfoRightTimes(start, stop);
} else {
start = 0xffffffff;
stop = 0xffffffff;
}
}
<API key> AIArea::getMiddleAreaOwner() {
return _middleAreaOwner;
}
} // End of namespace Pegasus |
#include <_ansi.h>
#include <signal.h>
#include "swi.h"
int _kill_shared (int, int, int) __attribute__((__noreturn__));
int _kill (int, int);
int
_kill (int pid, int sig)
{
if (sig == SIGABRT)
_kill_shared (pid, sig, <API key>);
else
_kill_shared (pid, sig, <API key>);
}
int
_kill_shared (int pid, int sig, int reason)
{
(void) pid; (void) sig;
#ifdef ARM_RDI_MONITOR
/* Note: The pid argument is thrown away. */
int block[2];
block[1] = sig;
block[0] = reason;
int insn;
#if SEMIHOST_V2
if (<API key> ())
{
insn = <API key>;
}
else
#endif
{
insn = <API key>;
}
#if SEMIHOST_V2
if (<API key> ())
do_AngelSWI (insn, block);
else
#endif
do_AngelSWI (insn, (void*)block[0]);
#else
asm ("swi %a0" :: "i" (SWI_Exit));
#endif
<API key>();
} |
/**
* @file Declaration of serializeble interface that all serializable classes
* should inherit.
*
* $Id$
*/
#ifndef GU_SERIALIZABLE_HPP
#define GU_SERIALIZABLE_HPP
#include "gu_types.hpp"
#include "gu_throw.hpp"
#include "gu_assert.hpp"
#include <vector>
#include <stdexcept> // for std::length_error
namespace gu
{
class Serializable
{
public:
/*! returns the size of a buffer required to serialize the object */
ssize_t serial_size () const
{
return my_serial_size();
}
/*!
* serializes this object into buf and returns serialized size
*
* @param buf pointer to buffer
* @param size size of buffer
* @return serialized size
*
* may throw exceptions
*/
ssize_t serialize_to (void* const buf, ssize_t const size) const
{
return my_serialize_to (buf, size);
}
/*!
* serializes this object into byte vector v, reallocating it if needed
* returns the size of serialized object
*/
ssize_t serialize_to (std::vector<byte_t>& v) const
{
size_t const old_size (v.size());
size_t const new_size (serial_size() + old_size);
try
{
v.resize (new_size, 0);
}
catch (std::length_error& l)
{
gu_throw_error(EMSGSIZE) << "length_error: " << l.what();
}
catch (...)
{
gu_throw_error(ENOMEM) << "could not resize to " << new_size
<< " bytes";
}
try
{
return serialize_to (&v[old_size], new_size - old_size);
}
catch (...)
{
v.resize (old_size);
throw;
}
}
protected:
~Serializable() {}
private:
virtual ssize_t my_serial_size () const = 0;
virtual ssize_t my_serialize_to (void* buf, ssize_t size) const = 0;
};
static inline std::vector<byte_t>&
operator << (std::vector<byte_t>& out, const Serializable& s)
{
s.serialize_to (out);
return out;
}
#if 0 // seems to be a pointless idea
class DeSerializable
{
public:
/* serial size of an object stored at ptr, may be not implemented */
template <class DS>
static ssize_t serial_size (const byte_t* const buf, ssize_t const size)
{
assert (size > 0);
return DS::my_serial_size (buf, size);
}
/* serial size of an object stored at ptr, may be not implemented */
ssize_t deserialize_from (const byte_t* const buf, ssize_t const size)
{
assert (size > 0);
return my_deserialize_from (buf, size);
}
ssize_t deserialize_from (const std::vector<byte_t>& in,size_t const offset)
{
return deserialize_from (&in[offset], in.size() - offset);
}
protected:
~DeSerializable() {}
private:
/* serial size of an object stored at ptr, may be not implemented */
virtual ssize_t my_deserialize_from (const byte_t* buf, ssize_t size) = 0;
};
#endif
} /* namespace gu */
#endif /* GU_SERIALIZABLE_HPP */ |
/* <API key>: GPL-2.0 */
#ifndef __LINUX_SMP_H
#define __LINUX_SMP_H
/*
* Generic SMP support
* Alan Cox. <alan@redhat.com>
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/cpumask.h>
#include <linux/init.h>
#include <linux/llist.h>
typedef void (*smp_call_func_t)(void *info);
typedef bool (*smp_cond_func_t)(int cpu, void *info);
enum {
CSD_FLAG_LOCK = 0x01,
/* IRQ_WORK_flags */
CSD_TYPE_ASYNC = 0x00,
CSD_TYPE_SYNC = 0x10,
CSD_TYPE_IRQ_WORK = 0x20,
CSD_TYPE_TTWU = 0x30,
CSD_FLAG_TYPE_MASK = 0xF0,
};
/*
* structure shares (partial) layout with struct irq_work
*/
struct __call_single_data {
struct llist_node llist;
unsigned int flags;
smp_call_func_t func;
void *info;
};
/* Use __aligned() to avoid to use 2 cache lines for 1 csd */
typedef struct __call_single_data call_single_data_t
__aligned(sizeof(struct __call_single_data));
/*
* Enqueue a llist_node on the call_single_queue; be very careful, read
* <API key>() in detail.
*/
extern void <API key>(int cpu, struct llist_node *node);
/* total number of cpus in this system (may exceed NR_CPUS) */
extern unsigned int total_cpus;
int <API key>(int cpuid, smp_call_func_t func, void *info,
int wait);
/*
* Call a function on all processors
*/
void on_each_cpu(smp_call_func_t func, void *info, int wait);
/*
* Call a function on processors specified by mask, which might include
* the local one.
*/
void on_each_cpu_mask(const struct cpumask *mask, smp_call_func_t func,
void *info, bool wait);
/*
* Call a function on each processor for which the supplied function
* cond_func returns a positive value. This may include the local
* processor.
*/
void on_each_cpu_cond(smp_cond_func_t cond_func, smp_call_func_t func,
void *info, bool wait);
void <API key>(smp_cond_func_t cond_func, smp_call_func_t func,
void *info, bool wait, const struct cpumask *mask);
int <API key>(int cpu, call_single_data_t *csd);
#ifdef CONFIG_SMP
#include <linux/preempt.h>
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/thread_info.h>
#include <asm/smp.h>
/*
* main cross-CPU interfaces, handles INIT, TLB flush, STOP, etc.
* (defined in asm header):
*/
/*
* stops all CPUs but the current one:
*/
extern void smp_send_stop(void);
/*
* sends a 'reschedule' event to another CPU:
*/
extern void smp_send_reschedule(int cpu);
/*
* Prepare machine for booting other CPUs.
*/
extern void smp_prepare_cpus(unsigned int max_cpus);
/*
* Bring a CPU up
*/
extern int __cpu_up(unsigned int cpunum, struct task_struct *tidle);
/*
* Final polishing of CPUs
*/
extern void smp_cpus_done(unsigned int max_cpus);
/*
* Call a function on all other processors
*/
void smp_call_function(smp_call_func_t func, void *info, int wait);
void <API key>(const struct cpumask *mask,
smp_call_func_t func, void *info, bool wait);
int <API key>(const struct cpumask *mask,
smp_call_func_t func, void *info, int wait);
void kick_all_cpus_sync(void);
void <API key>(void);
/*
* Generic and arch helpers
*/
void __init call_function_init(void);
void <API key>(void);
#define <API key> \
<API key>
/*
* Mark the boot cpu "online" so that it can call console drivers in
* printk() and can access its per-cpu storage.
*/
void <API key>(void);
extern unsigned int setup_max_cpus;
extern void __init setup_nr_cpu_ids(void);
extern void __init smp_init(void);
extern int __boot_cpu_id;
static inline int get_boot_cpu_id(void)
{
return __boot_cpu_id;
}
#else /* !SMP */
static inline void smp_send_stop(void) { }
/*
* These macros fold the SMP functionality into a single CPU system
*/
#define <API key>() 0
static inline void <API key>(smp_call_func_t func, void *info)
{
}
#define smp_call_function(func, info, wait) \
(<API key>(func, info))
static inline void smp_send_reschedule(int cpu) { }
#define <API key>() do {} while (0)
#define <API key>(mask, func, info, wait) \
(<API key>(func, info))
static inline void call_function_init(void) { }
static inline int
<API key>(const struct cpumask *mask, smp_call_func_t func,
void *info, int wait)
{
return <API key>(0, func, info, wait);
}
static inline void kick_all_cpus_sync(void) { }
static inline void <API key>(void) { }
#ifdef CONFIG_UP_LATE_INIT
extern void __init up_late_init(void);
static inline void smp_init(void) { up_late_init(); }
#else
static inline void smp_init(void) { }
#endif
static inline int get_boot_cpu_id(void)
{
return 0;
}
#endif /* !SMP */
/**
* raw_processor_id() - get the current (unstable) CPU id
*
* For then you know what you are doing and need an unstable
* CPU id.
*/
/**
* smp_processor_id() - get the current (stable) CPU id
*
* This is the normal accessor to the CPU id and should be used
* whenever possible.
*
* The CPU id is stable when:
*
* - IRQs are disabled;
* - preemption is disabled;
* - the task is CPU affine.
*
* When <API key>; we verify these assumption and WARN
* when smp_processor_id() is used when the CPU id is not stable.
*/
/*
* Allow the architecture to differentiate between a stable and unstable read.
* For example, x86 uses an IRQ-safe asm-volatile read for the unstable but a
* regular asm read for the stable.
*/
#ifndef __smp_processor_id
#define __smp_processor_id(x) <API key>(x)
#endif
#ifdef <API key>
extern unsigned int <API key>(void);
# define smp_processor_id() <API key>()
#else
# define smp_processor_id() __smp_processor_id()
#endif
#define get_cpu() ({ preempt_disable(); __smp_processor_id(); })
#define put_cpu() preempt_enable()
/*
* Callback to arch code if there's nosmp or maxcpus=0 on the
* boot command line:
*/
extern void <API key>(void);
extern void <API key>(void);
extern void <API key>(void);
void <API key>(void);
int smp_call_on_cpu(unsigned int cpu, int (*func)(void *), void *par,
bool phys);
/* SMP core functions */
int smpcfd_prepare_cpu(unsigned int cpu);
int smpcfd_dead_cpu(unsigned int cpu);
int smpcfd_dying_cpu(unsigned int cpu);
#endif /* __LINUX_SMP_H */ |
<?php
/**
* This struct contains content meta-data
*
* @package MvcTools
* @version //autogentag//
*/
class ezcMvcResultContent extends ezcBaseStruct
{
/**
* The content's language
*
* @var string
*/
public $language;
/**
* The content's mime-type
*
* @var string
*/
public $type;
/**
* The character set
*
* @var string
*/
public $charset;
/**
* The content "encoding" (gzip, etc).
*
* @var string
*/
public $encoding;
/**
* The content disposition information
*
* @var <API key>
*/
public $disposition;
/**
* Constructs a new ezcMvcResultContent.
*
* @param string $language
* @param string $type
* @param string $charset
* @param string $encoding
* @param <API key> $disposition
*/
public function __construct( $language = '', $type = '',
$charset = '', $encoding = '', $disposition = null )
{
$this->language = $language;
$this->type = $type;
$this->charset = $charset;
$this->encoding = $encoding;
$this->disposition = $disposition;
}
/**
* Returns a new instance of this class with the data specified by $array.
*
* $array contains all the data members of this class in the form:
* array('member_name'=>value).
*
* __set_state makes this class exportable with var_export.
* var_export() generates code, that calls this method when it
* is parsed with PHP.
*
* @param array(string=>mixed) $array
* @return ezcMvcResultContent
*/
static public function __set_state( array $array )
{
return new ezcMvcResultContent( $array['language'], $array['type'],
$array['charset'], $array['encoding'], $array['disposition'] );
}
}
?> |
#include "precompiled.hpp"
#include "c1/c1_MacroAssembler.hpp"
#include "c1/c1_Runtime1.hpp"
#include "classfile/systemDictionary.hpp"
#include "gc_interface/collectedHeap.hpp"
#include "interpreter/interpreter.hpp"
#include "oops/arrayOop.hpp"
#include "oops/markOop.hpp"
#include "runtime/basicLock.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/os.hpp"
#include "runtime/stubRoutines.hpp"
int C1_MacroAssembler::lock_object(Register hdr, Register obj, Register disp_hdr, Register scratch, Label& slow_case) {
const int aligned_mask = BytesPerWord -1;
const int hdr_offset = oopDesc::<API key>();
assert(hdr == rax, "hdr must be rax, for the cmpxchg instruction");
assert(hdr != obj && hdr != disp_hdr && obj != disp_hdr, "registers must be different");
Label done;
int null_check_offset = -1;
verify_oop(obj);
// save object being locked into the BasicObjectLock
movptr(Address(disp_hdr, BasicObjectLock::obj_offset_in_bytes()), obj);
if (UseBiasedLocking) {
assert(scratch != noreg, "should have scratch register at this point");
null_check_offset = <API key>(disp_hdr, obj, hdr, scratch, false, done, &slow_case);
} else {
null_check_offset = offset();
}
// Load object header
movptr(hdr, Address(obj, hdr_offset));
// and mark it as unlocked
orptr(hdr, markOopDesc::unlocked_value);
// save unlocked object header into the displaced header location on the stack
movptr(Address(disp_hdr, 0), hdr);
// test if object header is still the same (i.e. unlocked), and if so, store the
// displaced header address in the object header - if it is not the same, get the
// object header instead
if (os::is_MP()) MacroAssembler::lock(); // must be immediately before cmpxchg!
cmpxchgptr(disp_hdr, Address(obj, hdr_offset));
// if the object header was the same, we're done
if (<API key>) {
cond_inc32(Assembler::equal,
ExternalAddress((address)BiasedLocking::<API key>()));
}
jcc(Assembler::equal, done);
// if the object header was not the same, it is now in the hdr register
// => test if it is a stack pointer into the same stack (recursive locking), i.e.:
// 1) (hdr & aligned_mask) == 0
// 2) rsp <= hdr
// 3) hdr <= rsp + page_size
// these 3 tests can be done by evaluating the following expression:
// (hdr - rsp) & (aligned_mask - page_size)
// assuming both the stack pointer and page_size have their least
// significant 2 bits cleared and page_size is a power of 2
subptr(hdr, rsp);
andptr(hdr, aligned_mask - os::vm_page_size());
// for recursive locking, the result is zero => save it in the displaced header
// location (NULL in the displaced hdr location indicates recursive locking)
movptr(Address(disp_hdr, 0), hdr);
// otherwise we don't care about the result and handle locking via runtime call
jcc(Assembler::notZero, slow_case);
// done
bind(done);
return null_check_offset;
}
void C1_MacroAssembler::unlock_object(Register hdr, Register obj, Register disp_hdr, Label& slow_case) {
const int aligned_mask = BytesPerWord -1;
const int hdr_offset = oopDesc::<API key>();
assert(disp_hdr == rax, "disp_hdr must be rax, for the cmpxchg instruction");
assert(hdr != obj && hdr != disp_hdr && obj != disp_hdr, "registers must be different");
Label done;
if (UseBiasedLocking) {
// load object
movptr(obj, Address(disp_hdr, BasicObjectLock::obj_offset_in_bytes()));
biased_locking_exit(obj, hdr, done);
}
// load displaced header
movptr(hdr, Address(disp_hdr, 0));
// if the loaded hdr is NULL we had recursive locking
testptr(hdr, hdr);
// if we had recursive locking, we are done
jcc(Assembler::zero, done);
if (!UseBiasedLocking) {
// load object
movptr(obj, Address(disp_hdr, BasicObjectLock::obj_offset_in_bytes()));
}
verify_oop(obj);
// test if object header is pointing to the displaced header, and if so, restore
// the displaced header in the object - if the object header is not pointing to
// the displaced header, get the object header instead
if (os::is_MP()) MacroAssembler::lock(); // must be immediately before cmpxchg!
cmpxchgptr(hdr, Address(obj, hdr_offset));
// if the object header was not pointing to the displaced header,
// we do unlocking via runtime call
jcc(Assembler::notEqual, slow_case);
// done
bind(done);
}
// Defines obj, preserves var_size_in_bytes
void C1_MacroAssembler::try_allocate(Register obj, Register var_size_in_bytes, int con_size_in_bytes, Register t1, Register t2, Label& slow_case) {
if (UseTLAB) {
tlab_allocate(obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
} else {
eden_allocate(obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
<API key>(noreg, var_size_in_bytes, con_size_in_bytes, t1);
}
}
void C1_MacroAssembler::initialize_header(Register obj, Register klass, Register len, Register t1, Register t2) {
<API key>(obj, klass, len);
if (UseBiasedLocking && !len->is_valid()) {
<API key>(obj, klass, len, t1, t2);
movptr(t1, Address(klass, Klass::<API key>() + klassOopDesc::<API key>()));
movptr(Address(obj, oopDesc::<API key>()), t1);
} else {
// This assumes that all prototype bits fit in an int32_t
movptr(Address(obj, oopDesc::<API key> ()), (int32_t)(intptr_t)markOopDesc::prototype());
}
#ifdef _LP64
if (UseCompressedOops) { // Take care not to kill klass
movptr(t1, klass);
<API key>(t1);
movl(Address(obj, oopDesc::<API key>()), t1);
} else
#endif
{
movptr(Address(obj, oopDesc::<API key>()), klass);
}
if (len->is_valid()) {
movl(Address(obj, arrayOopDesc::<API key>()), len);
}
#ifdef _LP64
else if (UseCompressedOops) {
xorptr(t1, t1);
store_klass_gap(obj, t1);
}
#endif
}
// preserves obj, destroys len_in_bytes
void C1_MacroAssembler::initialize_body(Register obj, Register len_in_bytes, int hdr_size_in_bytes, Register t1) {
Label done;
assert(obj != len_in_bytes && obj != t1 && t1 != len_in_bytes, "registers must be different");
assert((hdr_size_in_bytes & (BytesPerWord - 1)) == 0, "header size is not a multiple of BytesPerWord");
Register index = len_in_bytes;
// index is positive and ptr sized
subptr(index, hdr_size_in_bytes);
jcc(Assembler::zero, done);
// initialize topmost word, divide index by 2, check if odd and test if zero
// note: for the remaining code to work, index must be a multiple of BytesPerWord
#ifdef ASSERT
{ Label L;
testptr(index, BytesPerWord - 1);
jcc(Assembler::zero, L);
stop("index is not a multiple of BytesPerWord");
bind(L);
}
#endif
xorptr(t1, t1); // use _zero reg to clear memory (shorter code)
if (UseIncDec) {
shrptr(index, 3); // divide by 8/16 and set carry flag if bit 2 was set
} else {
shrptr(index, 2); // use 2 instructions to avoid partial flag stall
shrptr(index, 1);
}
#ifndef _LP64
// index could have been not a multiple of 8 (i.e., bit 2 was set)
{ Label even;
// note: if index was a multiple of 8, than it cannot
// be 0 now otherwise it must have been 0 before
// => if it is even, we don't need to check for 0 again
jcc(Assembler::carryClear, even);
// clear topmost word (no jump needed if conditional assignment would work here)
movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - 0*BytesPerWord), t1);
// index could be 0 now, need to check again
jcc(Assembler::zero, done);
bind(even);
}
#endif // !_LP64
// initialize remaining object fields: rdx is a multiple of 2 now
{ Label loop;
bind(loop);
movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - 1*BytesPerWord), t1);
NOT_LP64(movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - 2*BytesPerWord), t1);)
decrement(index);
jcc(Assembler::notZero, loop);
}
// done
bind(done);
}
void C1_MacroAssembler::allocate_object(Register obj, Register t1, Register t2, int header_size, int object_size, Register klass, Label& slow_case) {
assert(obj == rax, "obj must be in rax, for cmpxchg");
<API key>(obj, t1, t2); // XXX really?
assert(header_size >= 0 && object_size >= header_size, "illegal sizes");
try_allocate(obj, noreg, object_size * BytesPerWord, t1, t2, slow_case);
initialize_object(obj, klass, noreg, object_size * HeapWordSize, t1, t2);
}
void C1_MacroAssembler::initialize_object(Register obj, Register klass, Register var_size_in_bytes, int con_size_in_bytes, Register t1, Register t2) {
assert((con_size_in_bytes & <API key>) == 0,
"con_size_in_bytes is not multiple of alignment");
const int hdr_size_in_bytes = instanceOopDesc::header_size() * HeapWordSize;
initialize_header(obj, klass, noreg, t1, t2);
// clear rest of allocated space
const Register t1_zero = t1;
const Register index = t2;
const int threshold = 6 * BytesPerWord; // approximate break even point for code size (see comments below)
if (var_size_in_bytes != noreg) {
mov(index, var_size_in_bytes);
initialize_body(obj, index, hdr_size_in_bytes, t1_zero);
} else if (con_size_in_bytes <= threshold) {
// use explicit null stores
// code size = 2 + 3*n bytes (n = number of fields to clear)
xorptr(t1_zero, t1_zero); // use t1_zero reg to clear memory (shorter code)
for (int i = hdr_size_in_bytes; i < con_size_in_bytes; i += BytesPerWord)
movptr(Address(obj, i), t1_zero);
} else if (con_size_in_bytes > hdr_size_in_bytes) {
// use loop to null out the fields
// code size = 16 bytes for even n (n = number of fields to clear)
// initialize last object field first if odd number of fields
xorptr(t1_zero, t1_zero); // use t1_zero reg to clear memory (shorter code)
movptr(index, (con_size_in_bytes - hdr_size_in_bytes) >> 3);
// initialize last object field if constant size is odd
if (((con_size_in_bytes - hdr_size_in_bytes) & 4) != 0)
movptr(Address(obj, con_size_in_bytes - (1*BytesPerWord)), t1_zero);
// initialize remaining object fields: rdx is a multiple of 2
{ Label loop;
bind(loop);
movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - (1*BytesPerWord)),
t1_zero);
NOT_LP64(movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - (2*BytesPerWord)),
t1_zero);)
decrement(index);
jcc(Assembler::notZero, loop);
}
}
if (CURRENT_ENV->dtrace_alloc_probes()) {
assert(obj == rax, "must be");
call(RuntimeAddress(Runtime1::entry_for(Runtime1::<API key>)));
}
verify_oop(obj);
}
void C1_MacroAssembler::allocate_array(Register obj, Register len, Register t1, Register t2, int header_size, Address::ScaleFactor f, Register klass, Label& slow_case) {
assert(obj == rax, "obj must be in rax, for cmpxchg");
<API key>(obj, len, t1, t2, klass);
// determine alignment mask
assert(!(BytesPerWord & 1), "must be a multiple of 2 for masking code to work");
// check for negative or excessive length
cmpptr(len, (int32_t)<API key>);
jcc(Assembler::above, slow_case);
const Register arr_size = t2; // okay to be the same
// align object end
movptr(arr_size, (int32_t)header_size * BytesPerWord + <API key>);
lea(arr_size, Address(arr_size, len, f));
andptr(arr_size, ~<API key>);
try_allocate(obj, arr_size, 0, t1, t2, slow_case);
initialize_header(obj, klass, len, t1, t2);
// clear rest of allocated space
const Register len_zero = len;
initialize_body(obj, arr_size, header_size * BytesPerWord, len_zero);
if (CURRENT_ENV->dtrace_alloc_probes()) {
assert(obj == rax, "must be");
call(RuntimeAddress(Runtime1::entry_for(Runtime1::<API key>)));
}
verify_oop(obj);
}
void C1_MacroAssembler::inline_cache_check(Register receiver, Register iCache) {
verify_oop(receiver);
// explicit NULL check not needed since load from [klass_offset] causes a trap
// check against inline cache
assert(!MacroAssembler::<API key>(oopDesc::<API key>()), "must add explicit null check");
int start_offset = offset();
if (UseCompressedOops) {
load_klass(rscratch1, receiver);
cmpptr(rscratch1, iCache);
} else {
cmpptr(iCache, Address(receiver, oopDesc::<API key>()));
}
// if icache check fails, then jump to runtime routine
// Note: RECEIVER must still contain the receiver!
jump_cc(Assembler::notEqual,
RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
const int ic_cmp_size = LP64_ONLY(10) NOT_LP64(9);
assert(UseCompressedOops || offset() - start_offset == ic_cmp_size, "check alignment in emit_method_entry");
}
void C1_MacroAssembler::build_frame(int frame_size_in_bytes) {
// Make sure there is enough stack space for this method's activation.
// Note that we do this before doing an enter(). This matches the
// ordering of C2's stack overflow check / rsp decrement and allows
// the SharedRuntime stack overflow handling to be consistent
// between the two compilers.
<API key>(frame_size_in_bytes);
push(rbp);
#ifdef TIERED
// c2 leaves fpu stack dirty. Clean it on entry
if (UseSSE < 2 ) {
empty_FPU_stack();
}
#endif // TIERED
decrement(rsp, frame_size_in_bytes); // does not emit code for frame_size == 0
}
void C1_MacroAssembler::remove_frame(int frame_size_in_bytes) {
increment(rsp, frame_size_in_bytes); // Does not emit code for frame_size == 0
pop(rbp);
}
void C1_MacroAssembler::unverified_entry(Register receiver, Register ic_klass) {
if (C1Breakpoint) int3();
inline_cache_check(receiver, ic_klass);
}
void C1_MacroAssembler::verified_entry() {
if (C1Breakpoint)int3();
// build frame
verify_FPU(0, "method_entry");
}
#ifndef PRODUCT
void C1_MacroAssembler::verify_stack_oop(int stack_offset) {
if (!VerifyOops) return;
verify_oop_addr(Address(rsp, stack_offset));
}
void C1_MacroAssembler::verify_not_null_oop(Register r) {
if (!VerifyOops) return;
Label not_null;
testptr(r, r);
jcc(Assembler::notZero, not_null);
stop("non-null oop required");
bind(not_null);
verify_oop(r);
}
void C1_MacroAssembler::<API key>(bool inv_rax, bool inv_rbx, bool inv_rcx, bool inv_rdx, bool inv_rsi, bool inv_rdi) {
#ifdef ASSERT
if (inv_rax) movptr(rax, 0xDEAD);
if (inv_rbx) movptr(rbx, 0xDEAD);
if (inv_rcx) movptr(rcx, 0xDEAD);
if (inv_rdx) movptr(rdx, 0xDEAD);
if (inv_rsi) movptr(rsi, 0xDEAD);
if (inv_rdi) movptr(rdi, 0xDEAD);
#endif
}
#endif // ifndef PRODUCT |
#include <avr/pgmspace.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "protocols/uip/uip.h"
#include "protocols/dns/resolv.h"
#include "netstat.h"
static const char PROGMEM netstat_header[] =
"POST " CONF_NETSTAT_API "update.php HTTP/1.1\n"
"Host: " <API key> "\n"
"Content-Type: application/<API key>\n"
"Content-Length: ";
static const char PROGMEM netstat_mac[] =
"\n\nmac=";
static void
netstat_net_main(void)
{
if (uip_aborted() || uip_timedout()) {
NETSTATDEBUG ("connection aborted\n");
return;
}
if (uip_closed()) {
NETSTATDEBUG ("connection closed\n");
return;
}
if (uip_connected() || uip_rexmit()) {
NETSTATDEBUG ("new connection or rexmit, sending message\n");
char *p = uip_appdata;
p += sprintf_P(p, netstat_header);
p += sprintf(p, "%d", 4 + 17); // -> mac=xx:xx:xx:xx:xx:xx
p += sprintf_P(p, netstat_mac);
p += sprintf(p, "%02x:%02x:%02x:%02x:%02x:%02x",
uip_ethaddr.addr[0],
uip_ethaddr.addr[1],
uip_ethaddr.addr[2],
uip_ethaddr.addr[3],
uip_ethaddr.addr[4],
uip_ethaddr.addr[5]
);
uip_udp_send(p - (char *)uip_appdata);
NETSTATDEBUG("send %d bytes\n", p - (char *)uip_appdata);
}
if (uip_acked()) {
NETSTATDEBUG("ACK\n");
uip_close();
} else {
NETSTATDEBUG("NACK\n");
}
}
#ifdef DNS_SUPPORT
static void
<API key>(char *name, uip_ipaddr_t *ipaddr) {
NETSTATDEBUG("got dns response, connecting\n");
if(!uip_connect(ipaddr, HTONS(80), netstat_net_main)) {
}
}
#endif /* DNS_SUPPORT */
uint8_t
netstat_send()
{
NETSTATDEBUG ("send\n");
#ifdef DNS_SUPPORT
uip_ipaddr_t *ipaddr;
if (!(ipaddr = resolv_lookup(<API key>))) {
resolv_query(<API key>, <API key>);
} else {
<API key>(NULL, ipaddr);
}
#else
uip_ipaddr_t ipaddr;
<API key>(&ipaddr);
if (! uip_connect(&ipaddr, HTONS(80), netstat_net_main))
{
NETSTATDEBUG ("failed\n");
}
#endif
return 1;
}
/*
-- Ethersex META --
header(protocols/netstat/netstat.h)
net_init(netstat_send)
*/ |
package com.engc.smartedu.dao.show;
import com.engc.smartedu.bean.UserBean;
import com.engc.smartedu.dao.URLHelper;
import com.engc.smartedu.support.error.WeiboException;
import com.engc.smartedu.support.http.HttpMethod;
import com.engc.smartedu.support.http.HttpUtility;
import com.engc.smartedu.support.utils.AppLogger;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.HashMap;
import java.util.Map;
public class ShowUserDao {
public UserBean getUserInfo() throws WeiboException {
String url = URLHelper.USER_SHOW;
Map<String, String> map = new HashMap<String, String>();
map.put("access_token", access_token);
map.put("uid", uid);
map.put("screen_name", screen_name);
String jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);
Gson gson = new Gson();
UserBean value = null;
try {
value = gson.fromJson(jsonData, UserBean.class);
} catch (JsonSyntaxException e) {
AppLogger.e(e.getMessage());
}
return value;
}
private String access_token;
private String uid;
private String screen_name;
public ShowUserDao(String access_token) {
this.access_token = access_token;
}
public ShowUserDao setScreen_name(String screen_name) {
this.screen_name = screen_name;
return this;
}
public ShowUserDao setUid(String uid) {
this.uid = uid;
return this;
}
} |
<?php
$lang['welcome_user'] = ', !';
$lang['input_invalid'] = '!';
?> |
/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
#include <config.h>
#include <stdlib.h>
#include "verify.h"
/* Check that EXIT_SUCCESS is 0, per POSIX. */
static int exitcode = EXIT_SUCCESS;
#if EXIT_SUCCESS
"oops"
#endif
/* Check for GNU value (not guaranteed by POSIX, but is guaranteed by
gnulib). */
#if EXIT_FAILURE != 1
"oops"
#endif
/* Check that NULL can be passed through varargs as a pointer type,
per POSIX 2008. */
verify (sizeof NULL == sizeof (void *));
#if <API key>
# include "test-sys_wait.h"
#else
# define <API key>() 0
#endif
int
main (void)
{
if (<API key> ())
return 1;
return exitcode;
} |
<?php
$viewdefs['Users']['DetailView'] = array(
'templateMeta' => array('maxColumns' => '2',
'widths' => array(
array('label' => '10', 'field' => '30'),
array('label' => '10', 'field' => '30')
),
'form' => array(
'headerTpl'=>'modules/Users/tpls/DetailViewHeader.tpl',
'footerTpl'=>'modules/Users/tpls/DetailViewFooter.tpl',
),
),
'panels' => array(
'<API key>' => array(
array('user_name',
array('name' => 'last_name',
'label' => 'LBL_LIST_NAME',
),
),
array('status',
'',
),
array(array(
'name'=>'UserType',
'customCode'=>'{$USER_TYPE_READONLY}',
),
),
),
),
); |
// <API key>: Apache-2.0 WITH LLVM-exception
// This file implements RISCV TargetInfo objects.
#include "RISCV.h"
#include "clang/Basic/MacroBuilder.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
using namespace clang::targets;
ArrayRef<const char *> RISCVTargetInfo::getGCCRegNames() const {
static const char *const GCCRegNames[] = {
"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7",
"x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
"x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23",
"x24", "x25", "x26", "x27", "x28", "x29", "x30", "x31"};
return llvm::makeArrayRef(GCCRegNames);
}
ArrayRef<TargetInfo::GCCRegAlias> RISCVTargetInfo::getGCCRegAliases() const {
static const TargetInfo::GCCRegAlias GCCRegAliases[] = {
{{"zero"}, "x0"}, {{"ra"}, "x1"}, {{"sp"}, "x2"}, {{"gp"}, "x3"},
{{"tp"}, "x4"}, {{"t0"}, "x5"}, {{"t1"}, "x6"}, {{"t2"}, "x7"},
{{"s0"}, "x8"}, {{"s1"}, "x9"}, {{"a0"}, "x10"}, {{"a1"}, "x11"},
{{"a2"}, "x12"}, {{"a3"}, "x13"}, {{"a4"}, "x14"}, {{"a5"}, "x15"},
{{"a6"}, "x16"}, {{"a7"}, "x17"}, {{"s2"}, "x18"}, {{"s3"}, "x19"},
{{"s4"}, "x20"}, {{"s5"}, "x21"}, {{"s6"}, "x22"}, {{"s7"}, "x23"},
{{"s8"}, "x24"}, {{"s9"}, "x25"}, {{"s10"}, "x26"}, {{"s11"}, "x27"},
{{"t3"}, "x28"}, {{"t4"}, "x29"}, {{"t5"}, "x30"}, {{"t6"}, "x31"}};
return llvm::makeArrayRef(GCCRegAliases);
}
bool RISCVTargetInfo::<API key>(
const char *&Name, TargetInfo::ConstraintInfo &Info) const {
switch (*Name) {
default:
return false;
case 'I':
// A 12-bit signed immediate.
Info.<API key>(-2048, 2047);
return true;
case 'J':
// Integer zero.
Info.<API key>(0);
return true;
case 'K':
// A 5-bit unsigned immediate for CSR access instructions.
Info.<API key>(0, 31);
return true;
case 'f':
// A floating-point register.
Info.setAllowsRegister();
return true;
case 'A':
// An address that is held in a general-purpose register.
Info.setAllowsMemory();
return true;
}
}
void RISCVTargetInfo::getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
Builder.defineMacro("__ELF__");
Builder.defineMacro("__riscv");
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
Builder.defineMacro("__riscv_xlen", Is64Bit ? "64" : "32");
// TODO: modify when more code models are supported.
Builder.defineMacro("<API key>");
StringRef ABIName = getABI();
if (ABIName == "ilp32f" || ABIName == "lp64f")
Builder.defineMacro("<API key>");
else if (ABIName == "ilp32d" || ABIName == "lp64d")
Builder.defineMacro("<API key>");
else if (ABIName == "ilp32e")
Builder.defineMacro("__riscv_abi_rve");
else
Builder.defineMacro("<API key>");
if (HasM) {
Builder.defineMacro("__riscv_mul");
Builder.defineMacro("__riscv_div");
Builder.defineMacro("__riscv_muldiv");
}
if (HasA)
Builder.defineMacro("__riscv_atomic");
if (HasF || HasD) {
Builder.defineMacro("__riscv_flen", HasD ? "64" : "32");
Builder.defineMacro("__riscv_fdiv");
Builder.defineMacro("__riscv_fsqrt");
}
if (HasC)
Builder.defineMacro("__riscv_compressed");
}
Return true if has this feature, need to sync with <API key>.
bool RISCVTargetInfo::hasFeature(StringRef Feature) const {
bool Is64Bit = getTriple().getArch() == llvm::Triple::riscv64;
return llvm::StringSwitch<bool>(Feature)
.Case("riscv", true)
.Case("riscv32", !Is64Bit)
.Case("riscv64", Is64Bit)
.Case("m", HasM)
.Case("a", HasA)
.Case("f", HasF)
.Case("d", HasD)
.Case("c", HasC)
.Default(false);
}
Perform initialization based on the user configured set of features.
bool RISCVTargetInfo::<API key>(std::vector<std::string> &Features,
DiagnosticsEngine &Diags) {
for (const auto &Feature : Features) {
if (Feature == "+m")
HasM = true;
else if (Feature == "+a")
HasA = true;
else if (Feature == "+f")
HasF = true;
else if (Feature == "+d")
HasD = true;
else if (Feature == "+c")
HasC = true;
}
return true;
} |
<?php
/* This file is part of the Thelia package. */
/* email : dev@thelia.net */
/* file that was distributed with this source code. */
namespace Thelia\Tests\Action;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Action\Folder;
use Thelia\Core\Event\Folder\FolderCreateEvent;
use Thelia\Core\Event\Folder\FolderDeleteEvent;
use Thelia\Core\Event\Folder\<API key>;
use Thelia\Core\Event\Folder\FolderUpdateEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\UpdateSeoEvent;
use Thelia\Model\FolderQuery;
use Thelia\Tests\<API key>;
use Thelia\Model\Folder as FolderModel;
/**
* Class FolderTest
* @package Thelia\Tests\Action
* @author Manuel Raynaud <manu@raynaud.io>
*/
class FolderTest extends <API key>
{
use <API key>;
use I18nTestTrait;
/** @var int folder id used in position tests */
protected static $<API key> = null;
public function getUpdateEvent(&$folder)
{
if (!$folder instanceof FolderModel) {
$folder = $this->getRandomFolder();
}
$event = new FolderUpdateEvent($folder->getId());
$event
->setVisible(1)
->setLocale($folder->getLocale())
->setTitle($folder->getTitle())
->setChapo($folder->getChapo())
->setDescription($folder->getDescription())
->setPostscriptum($folder->getPostscriptum())
->setParent($folder->getParent())
;
return $event;
}
public function getUpdateSeoEvent(&$folder)
{
if (!$folder instanceof FolderModel) {
$folder = $this->getRandomFolder();
}
$event = new UpdateSeoEvent($folder->getId());
$event
->setLocale($folder->getLocale())
->setMetaTitle($folder->getMetaTitle())
->setMetaDescription($folder->getMetaDescription())
->setMetaKeywords($folder->getMetaKeywords());
return $event;
}
public function <API key>($event)
{
$contentAction = new Folder();
return $contentAction->updateSeo($event, null, $this-><API key>());
}
/**
* @param FolderUpdateEvent $event
* @return FolderModel
*/
public function processUpdateAction($event)
{
$contentAction = new Folder();
$contentAction->update($event, null, $this-><API key>());
return $event->getFolder();
}
/**
* test folder creation
* @covers Thelia\Action\Folder::create
*/
public function testCreateFolder()
{
$event = new FolderCreateEvent();
$event
->setParent(0)
->setVisible(1)
->setLocale('en_US')
->setTitle('folder creation test');
$folderAction = new Folder();
$folderAction->create($event, null, $this-><API key>());
$folder = $event->getFolder();
$this->assertInstanceOf('Thelia\Model\Folder', $folder);
$this->assertEquals('folder creation test', $folder->getTitle());
$this->assertEquals(1, $folder->getVisible());
$this->assertEquals(0, $folder->getParent());
}
/**
* test update creation
* @covers Thelia\Action\Folder::update
*/
public function testUpdateFolder()
{
$folder = $this->getRandomFolder();
$visible = !$folder->getVisible();
$event = new FolderUpdateEvent($folder->getId());
$event
->setLocale('en_US')
->setTitle('test update folder')
->setVisible($visible)
->setChapo('test folder update chapo')
->setDescription('update folder description')
->setPostscriptum('update folder postscriptum')
->setParent(0)
;
$folderAction = new Folder();
$folderAction->update($event, null, $this-><API key>());
$updatedFolder = $event->getFolder();
$this->assertInstanceOf('Thelia\Model\Folder', $updatedFolder);
$this->assertEquals('test update folder', $updatedFolder->getTitle());
$this->assertEquals('test folder update chapo', $updatedFolder->getChapo());
$this->assertEquals('update folder description', $updatedFolder->getDescription());
$this->assertEquals('update folder postscriptum', $updatedFolder->getPostscriptum());
$this->assertEquals(0, $updatedFolder->getParent());
$this->assertEquals($visible, $updatedFolder->getVisible());
}
/**
* test folder removal
* @covers Thelia\Action\Folder::delete
*/
public function testDeleteFolder()
{
$folder = $this->getRandomFolder();
$event = new FolderDeleteEvent($folder->getId());
$folderAction = new Folder();
$folderAction->delete($event, null, $this-><API key>());
$deletedFolder = $event->getFolder();
$this->assertInstanceOf('Thelia\Model\Folder', $deletedFolder);
$this->assertTrue($deletedFolder->isDeleted());
}
/**
* test folder toggle visibility
* @covers Thelia\Action\Folder::toggleVisibility
*/
public function <API key>()
{
$folder = $this->getRandomFolder();
$visible = $folder->getVisible();
$event = new <API key>($folder);
$folderAction = new Folder();
$folderAction->toggleVisibility($event, null, $this-><API key>());
$updatedFolder = $event->getFolder();
$this->assertInstanceOf('Thelia\Model\Folder', $updatedFolder);
$this->assertEquals(!$visible, $updatedFolder->getVisible());
}
public function <API key>()
{
$folder = FolderQuery::create()
->filterByParent($this-><API key>())
->filterByPosition(1, Criteria::GREATER_THAN)
->findOne();
if (null === $folder) {
$this->fail('use fixtures before launching test, there is no folder in database');
}
$newPosition = $folder->getPosition()-1;
$event = new UpdatePositionEvent($folder->getId(), UpdatePositionEvent::POSITION_UP);
$folderAction = new Folder();
$folderAction->updatePosition($event, null, $this-><API key>());
$updatedFolder = FolderQuery::create()->findPk($folder->getId());
$this->assertEquals($newPosition, $updatedFolder->getPosition(), sprintf("new position is %d, new position expected is %d for folder %d", $newPosition, $updatedFolder->getPosition(), $updatedFolder->getId()));
}
public function <API key>()
{
$nextFolder = FolderQuery::create()
->filterByParent($this-><API key>())
->filterByPosition(2)
->findOne();
if (null === $nextFolder) {
$this->fail('use fixtures before launching test, there is not enough folder in database');
}
$folder = FolderQuery::create()
->filterByPosition(1)
->filterByParent($nextFolder->getParent())
->findOne();
if (null === $folder) {
$this->fail('use fixtures before launching test, there is not enough folder in database');
}
$newPosition = $folder->getPosition()+1;
$event = new UpdatePositionEvent($folder->getId(), UpdatePositionEvent::POSITION_DOWN);
$folderAction = new Folder();
$folderAction->updatePosition($event, null, $this-><API key>());
$updatedFolder = FolderQuery::create()->findPk($folder->getId());
$this->assertEquals($newPosition, $updatedFolder->getPosition(), sprintf("new position is %d, new position expected is %d for folder %d", $newPosition, $updatedFolder->getPosition(), $updatedFolder->getId()));
}
public function <API key>()
{
$folder = FolderQuery::create()
->filterByParent($this-><API key>())
->filterByPosition(1, Criteria::GREATER_THAN)
->findOne();
if (null === $folder) {
$this->fail('use fixtures before launching test, there is no folder in database');
}
$event = new UpdatePositionEvent($folder->getId(), UpdatePositionEvent::POSITION_ABSOLUTE, 1);
$folderAction = new Folder();
$folderAction->updatePosition($event, null, $this-><API key>());
$updatedFolder = FolderQuery::create()->findPk($folder->getId());
$this->assertEquals(1, $updatedFolder->getPosition(), sprintf("new position is 1, new position expected is %d for folder %d", $updatedFolder->getPosition(), $updatedFolder->getId()));
}
/**
* generates a folder and its sub folders to be used in Position tests
*
* @return int the parent folder id
*/
protected function <API key>()
{
if (null === self::$<API key>) {
$folder = new FolderModel();
$folder->setParent(0);
$folder->setVisible(1);
$folder->setPosition(1);
$this->setI18n($folder);
$folder->save();
for ($i = 0; $i < 4; $i++) {
$subFolder = new FolderModel();
$subFolder->setParent($folder->getId());
$subFolder->setVisible(1);
$subFolder->setPosition($i + 1);
$this->setI18n($subFolder);
$subFolder->save();
}
self::$<API key> = $folder->getId();
}
return self::$<API key>;
}
/**
* @return \Thelia\Model\Folder
*/
protected function getRandomFolder()
{
$folder = FolderQuery::create()
-><API key>('RAND()')
->findOne();
if (null === $folder) {
$this->fail('use fixtures before launching test, there is no folder in database');
}
return $folder;
}
} |
CKEDITOR.plugins.setLang( 'format', 'gl', {
label: 'Formato',
panelTitle: 'Formato do parágrafo',
tag_address: 'Enderezo',
tag_div: 'Normal (DIV)',
tag_h1: 'Enacabezado 1',
tag_h2: 'Encabezado 2',
tag_h3: 'Encabezado 3',
tag_h4: 'Encabezado 4',
tag_h5: 'Encabezado 5',
tag_h6: 'Encabezado 6',
tag_p: 'Normal',
tag_pre: 'Formatado'
} ); |
// Purpose:
#include "cbase.h"
#include "env_zoom.h"
#ifdef HL2_DLL
#include "hl2_player.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define ENV_ZOOM_OVERRIDE (1<<0)
class CEnvZoom : public CPointEntity
{
public:
DECLARE_CLASS( CEnvZoom, CPointEntity );
void InputZoom( inputdata_t &inputdata );
void InputUnZoom( inputdata_t &inputdata );
int GetFOV( void ) { return m_nFOV; }
float GetSpeed( void ) { return m_flSpeed; }
private:
float m_flSpeed;
int m_nFOV;
DECLARE_DATADESC();
};
<API key>( env_zoom, CEnvZoom );
BEGIN_DATADESC( CEnvZoom )
DEFINE_KEYFIELD( m_flSpeed, FIELD_FLOAT, "Rate" ),
DEFINE_KEYFIELD( m_nFOV, FIELD_INTEGER, "FOV" ),
DEFINE_INPUTFUNC( FIELD_VOID, "Zoom", InputZoom ),
DEFINE_INPUTFUNC( FIELD_VOID, "UnZoom", InputUnZoom ),
END_DATADESC()
bool <API key>( CBaseEntity *pZoomOwner )
{
CEnvZoom *pZoom = dynamic_cast<CEnvZoom*>(pZoomOwner );
if ( pZoom == NULL || pZoom && pZoom->HasSpawnFlags( ENV_ZOOM_OVERRIDE ) == false )
return false;
return true;
}
float <API key>( CBaseEntity *pZoomOwner )
{
if ( <API key>( pZoomOwner ) )
{
CEnvZoom *pZoom = dynamic_cast<CEnvZoom*>( pZoomOwner );
return pZoom->GetFOV();
}
return 0;
}
// Purpose:
// Input : &inputdata -
void CEnvZoom::InputZoom( inputdata_t &inputdata )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
if ( pPlayer )
{
#ifdef HL2_DLL
if ( pPlayer == pPlayer->GetFOVOwner() )
{
CHL2_Player *pHLPlayer = static_cast<CHL2_Player*>( pPlayer );
pHLPlayer->StopZooming();
}
#endif
// If the player's already holding a fov from another env_zoom, we're allowed to overwrite it
if ( pPlayer->GetFOVOwner() && FClassnameIs( pPlayer->GetFOVOwner(), "env_zoom" ) )
{
pPlayer->ClearZoomOwner();
}
//Stuff the values
pPlayer->SetFOV( this, m_nFOV, m_flSpeed );
}
}
// Purpose:
// Input : &inputdata -
void CEnvZoom::InputUnZoom( inputdata_t &inputdata )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayer();
if ( pPlayer )
{
// Stuff the values
pPlayer->SetFOV( this, 0 );
}
} |
describe("Ext.container.ButtonGroup", function() {
var group;
afterEach(function() {
if (group) {
group.destroy();
group = null;
}
});
function createButtonGroup(config) {
// ARIA warnings are expected
spyOn(Ext.log, 'warn');
group = new Ext.container.ButtonGroup(config || {});
return group;
}
function makeGroup(cfg) {
cfg = Ext.apply({
renderTo: Ext.getBody()
}, cfg);
return createButtonGroup(cfg);
}
describe("Structure and creation", function() {
it("should extend Ext.Panel", function() {
expect(createButtonGroup() instanceof Ext.Panel).toBeTruthy();
});
it("should allow instantiation via the 'buttongroup' xtype", function() {
var panel = new Ext.Panel({
items: [{
xtype: 'buttongroup'
}]
});
expect(panel.items.getAt(0) instanceof Ext.container.ButtonGroup).toBeTruthy();
panel.destroy();
});
});
describe("Layout", function() {
it("should default to table layout", function() {
createButtonGroup();
expect(group.getLayout() instanceof Ext.layout.container.Table).toBeTruthy();
});
it("should allow overriding the layout", function() {
createButtonGroup({
layout: {type: 'hbox'}
});
expect(group.getLayout() instanceof Ext.layout.container.HBox).toBeTruthy();
});
// TODO: move this spec to a future TableLayout test suite
xit("should default to one table row", function() {
createButtonGroup({
items: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
renderTo: Ext.getBody()
});
expect(group.el.select('tr').getCount()).toEqual(1);
expect(group.el.select('tr').item(0).select('td').getCount()).toEqual(10);
});
it("should honor a 'columns' config property", function() {
createButtonGroup({
columns: 5,
items: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
renderTo: Ext.getBody()
});
expect(group.getLayout().columns).toEqual(5);
});
});
describe("Children", function() {
it("should default child items to an xtype of 'button'", function() {
createButtonGroup({
items: [
{},
{xtype: 'splitbutton'}
]
});
expect(group.items.getAt(0).xtype).toEqual('button');
expect(group.items.getAt(1).xtype).toEqual('splitbutton');
});
});
describe("Title", function() {
it("should have no title by default", function() {
createButtonGroup({
renderTo: Ext.getBody()
});
expect(group.title).toBeNull();
expect(group.el.select('.x-btn-group-header').getCount()).toEqual(0);
});
it("should allow configuring a title", function() {
createButtonGroup({
title: 'Group Title',
renderTo: Ext.getBody()
});
expect(group.header.getTitle().getText()).toEqual('Group Title');
expect(group.el.select('.x-btn-group-header').getCount()).toEqual(1);
});
});
describe("Element classes", function() {
it("should have a className of 'x-btn-group-notitle' when no title is configured", function() {
createButtonGroup({
renderTo: Ext.getBody()
});
expect(group.el).toHaveCls('x-btn-group-notitle');
});
it("should not have a className of 'x-btn-group-notitle' when a title is configured", function() {
createButtonGroup({
title: 'Group Title',
renderTo: Ext.getBody()
});
expect(group.el).not.toHaveCls('x-btn-group-notitle');
});
it("should have a className of 'x-btn-group' by default", function() {
createButtonGroup({
renderTo: Ext.getBody()
});
expect(group.el).toHaveCls('x-btn-group');
});
it("should allow overriding the baseCls", function() {
createButtonGroup({
baseCls: 'x-test',
// x-test doesn't support sass framing we must deactivate frame to do this test in IE
frame: false,
renderTo: Ext.getBody()
});
expect(group.el).not.toHaveCls('x-btn-group');
expect(group.el).toHaveCls('x-test');
});
});
describe("Framing", function() {
it("should default to having a frame", function() {
createButtonGroup({
renderTo: Ext.getBody()
});
expect(group.frame).toBeTruthy();
expect(group.el).toHaveCls('<API key>')
});
it("should allow turning off the frame", function() {
createButtonGroup({
frame: false,
renderTo: Ext.getBody()
});
expect(group.frame).toBeFalsy();
expect(group.el).not.toHaveCls('<API key>')
});
});
describe("ARIA", function() {
describe("general", function() {
beforeEach(function() {
makeGroup();
});
it("should be a FocusableContainer", function() {
expect(group.<API key>).toBe(true);
});
it("should have presentation role on main el", function() {
expect(group.el).toHaveAttr('role', 'presentation');
});
it("should have toolbar role on body el", function() {
expect(group.body).toHaveAttr('role', 'toolbar');
});
});
describe("labels", function() {
describe("with header", function() {
beforeEach(function() {
makeGroup({
title: 'frobbe'
});
});
it("should have aria-labelledby", function() {
expect(group.body).toHaveAttr('aria-labelledby', group.header.titleCmp.textEl.id);
});
it("should not have aria-label", function() {
expect(group.body).not.toHaveAttr('aria-label');
});
});
describe("with title but no header", function() {
beforeEach(function() {
makeGroup({
title: 'bonzo',
header: false
});
});
it("should have aria-label", function() {
expect(group.body).toHaveAttr('aria-label', 'bonzo');
});
it("should not have aria-labelledby", function() {
expect(group.body).not.toHaveAttr('aria-labelledby');
});
});
describe("with title but header updated to none", function() {
beforeEach(function() {
makeGroup({
title: 'throbbe',
header: false
});
group.setIconCls('guzzard');
});
it("should have aria-label", function() {
expect(group.body).toHaveAttr('aria-label', 'throbbe');
});
it("should not have aria-labelledby", function() {
expect(group.body).not.toHaveAttr('aria-labelledby');
});
});
describe("no header no title", function() {
beforeEach(function() {
makeGroup();
});
it("should not have aria-labelledby", function() {
expect(group.body).not.toHaveAttr('aria-labelledby');
});
it("should not have aria-label", function() {
expect(group.body).not.toHaveAttr('aria-label');
});
});
});
});
}); |
"use strict";
module.exports = require("./is-implemented")() ? Number.isInteger : require("./shim"); |
"use strict";
var toPosInt = require("../../number/to-pos-integer")
, callable = require("../../object/valid-callable")
, defineLength = require("../_define-length")
, slice = Array.prototype.slice
, apply = Function.prototype.apply
, curry;
curry = function self(fn, length, preArgs) {
return defineLength(
function () {
var args = preArgs
? preArgs.concat(slice.call(arguments, 0, length - preArgs.length))
: slice.call(arguments, 0, length);
return args.length === length ? apply.call(fn, this, args) : self(fn, length, args);
},
preArgs ? length - preArgs.length : length
);
};
module.exports = function (/* Length*/) {
var length = arguments[0];
return curry(callable(this), isNaN(length) ? toPosInt(this.length) : toPosInt(length));
}; |
exports.command = function (fileName, callback) {
var self = this;
this.screenshot(function(err,result) {
if(err === null) {
self.writeFile(fileName, result.value, function(err) {
if (typeof callback === "function") {
callback(err);
}
});
} else {
if (typeof callback === "function") {
callback(err,result);
}
}
});
}; |
/**
* Check ToUint32(length) for non Array objects
*
* @path ch15/15.4/15.4.4/15.4.4.9/S15.4.4.9_A3_T2.js
* @description length is arbitrarily
*/
var obj = {};
obj.shift = Array.prototype.shift;
obj[0] = "x";
obj[1] = "y";
obj[4294967296] = "z";
obj.length = 4294967297;
//CHECK
var shift = obj.shift();
if (shift !== "x") {
$ERROR('
}
//CHECK
if (obj.length !== 0) {
$ERROR('
}
//CHECK
if (obj[0] !== undefined) {
$ERROR('
}
//CHECK
if (obj[1] !== "y") {
$ERROR('
}
//CHECK
if (obj[4294967296] !== "z") {
$ERROR('
} |
<div class="news-default-index">
<h1><?= $this->context->action->uniqueId ?></h1>
<p>
This is the view content for action "<?= $this->context->action->id ?>".
The action belongs to the controller "<?= get_class($this->context) ?>"
in the "<?= $this->context->module->id ?>" module.
</p>
<p>
You may customize this page by editing the following file:<br>
<code><?= __FILE__ ?></code>
</p>
</div> |
package org.newdawn.slick.tests;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
/**
* A test for reading image data from a teture
*
* @author kevin
*/
public class ImageReadTest extends BasicGame {
/** The image loaded to be read */
private Image image;
/** The four pixels read */
private Color[] read = new Color[6];
/** The main graphics context */
private Graphics g;
/**
* Create a new image reading test
*/
public ImageReadTest() {
super("Image Read Test");
}
/**
* @see org.newdawn.slick.BasicGame#init(org.newdawn.slick.GameContainer)
*/
public void init(GameContainer container) throws SlickException {
image = new Image("testdata/testcard.png");
read[0] = image.getColor(0, 0);
read[1] = image.getColor(30, 40);
read[2] = image.getColor(55, 70);
read[3] = image.getColor(80, 90);
}
/**
* @see org.newdawn.slick.BasicGame#render(org.newdawn.slick.GameContainer, org.newdawn.slick.Graphics)
*/
public void render(GameContainer container, Graphics g) {
this.g = g;
image.draw(100,100);
g.setColor(Color.white);
g.drawString("Move mouse over test image", 200, 20);
g.setColor(read[0]);
g.drawString(read[0].toString(), 100,300);
g.setColor(read[1]);
g.drawString(read[1].toString(), 150,320);
g.setColor(read[2]);
g.drawString(read[2].toString(), 200,340);
g.setColor(read[3]);
g.drawString(read[3].toString(), 250,360);
if (read[4] != null) {
g.setColor(read[4]);
g.drawString("On image: "+read[4].toString(), 100,250);
}
if (read[5] != null) {
g.setColor(Color.white);
g.drawString("On screen: "+read[5].toString(), 100,270);
}
}
/**
* @see org.newdawn.slick.BasicGame#update(org.newdawn.slick.GameContainer, int)
*/
public void update(GameContainer container, int delta) {
int mx = container.getInput().getMouseX();
int my = container.getInput().getMouseY();
if ((mx >= 100) && (my >= 100) && (mx < 200) && (my < 200)) {
read[4] = image.getColor(mx-100,my-100);
} else {
read[4] = Color.black;
}
read[5] = g.getPixel(mx, my);
}
/**
* Entry point to our test
*
* @param argv The arguments to pass into the test
*/
public static void main(String[] argv) {
try {
AppGameContainer container = new AppGameContainer(new ImageReadTest());
container.setDisplayMode(800,600,false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
} |
"use strict";
describe("Block:Validation", function(){
var element, editor, block;
beforeEach(function(){
element = $("<textarea>");
editor = new SirTrevor.Editor({ el: element });
block = new SirTrevor.Blocks.Text({}, editor.ID, editor.mediator);
});
describe("valid", function(){
beforeEach(function(){
block.performValidations = function(){};
spyOn(block, "performValidations");
});
it("will return true if there are no errors", function(){
expect(block.valid()).toBe(true);
});
it("will return false if there are errors", function(){
block.errors.push(1);
expect(block.valid()).toBe(false);
});
it("will call the performValidations method on calling valid", function(){
block.valid();
expect(block.performValidations).toHaveBeenCalled();
});
});
describe("performValidations", function(){
beforeEach(function(){
block.validations = ['testValidator'];
block.testValidator = function(){};
block.resetErrors = function(){};
spyOn(block, "testValidator");
spyOn(block, "resetErrors");
block.performValidations();
});
it("will call any custom validators in the validations array", function(){
expect(block.testValidator).toHaveBeenCalled();
});
it("will call resetErrors", function(){
expect(block.resetErrors).toHaveBeenCalled();
});
});
describe("validateField", function(){
var $field;
beforeEach(function(){
$field = $("<input>");
block.setError = function(field, reason){};
spyOn(block, "setError");
});
it("will call setError if the field has no content", function(){
block.validateField($field);
expect(block.setError).toHaveBeenCalled();
});
it("will won't call setError if the field has content", function(){
$field.val("Test");
block.validateField($field);
expect(block.setError).not.toHaveBeenCalled();
});
});
}); |
<?php
namespace App\Services\Auth;
use App\Utils;
use App\Services\Jwt;
class JwtToken extends Base
{
public function login($uid, $time)
{
$expireTime = time() + $time;
$ary = [
"uid" => $uid,
"expire_time" => $expireTime
];
$decode = Jwt::encode($ary);
Utils\Cookie::set([
//"uid" => $uid,
"token" => $decode
],$expireTime);
}
public function logout()
{
Utils\Cookie::set([
//"uid" => $uid,
"token" => ""
],time()-3600);
}
public function getUser()
{
$token = Utils\Cookie::get('token');
$tokenInfo = Jwt::decodeArray($token);
}
} |
"""Common operations on Posix pathnames.
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).
Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.
"""
import os
import sys
import stat
import genericpath
import warnings
from genericpath import *
from genericpath import _unicode
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","getctime","islink","exists","lexists","isdir","isfile",
"ismount","walk","expanduser","expandvars","normpath","abspath",
"samefile","sameopenfile","samestat",
"curdir","pardir","sep","pathsep","defpath","altsep","extsep",
"devnull","realpath","<API key>","relpath"]
# strings representing various path-related bits and pieces
curdir = '.'
pardir = '..'
extsep = '.'
sep = '/'
pathsep = ':'
defpath = ':/bin:/usr/bin'
altsep = None
devnull = '/dev/null'
# Normalize the case of a pathname. Trivial in Posix, string.lower on Mac.
# On MS-DOS this may also turn slashes into backslashes; however, other
# normalizations (such as optimizing '../' away) are not allowed
# (another function should be defined to do that).
def normcase(s):
"""Normalize case of pathname. Has no effect under Posix"""
return s
# Return whether a path is absolute.
# Trivial in Posix, harder on the Mac or MS-DOS.
def isabs(s):
"""Test whether a path is absolute"""
return s.startswith('/')
# Join pathnames.
# Ignore the previous parts if a part is absolute.
# Insert a '/' unless the first part is empty or already ends in '/'.
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path
# Split a path in head (everything up to the last '/') and tail (the
# rest). If the path ends in '/', tail will be empty. If there is no
# '/' in the path, head will be empty.
# Trailing '/'es are stripped from head unless it is the root.
def split(p):
"""Split a pathname. Returns tuple "(head, tail)" where "tail" is
everything after the final slash. Either part may be empty."""
i = p.rfind('/') + 1
head, tail = p[:i], p[i:]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head, tail
# Split a path in root and extension.
# The extension is everything starting at the last dot in the last
# pathname component; the root is everything before that.
# It is always true that root + ext == p.
def splitext(p):
return genericpath._splitext(p, sep, altsep, extsep)
splitext.__doc__ = genericpath._splitext.__doc__
# Split a pathname into a drive specification and the rest of the
# path. Useful on DOS/Windows/NT; on Unix, the drive is always empty.
def splitdrive(p):
"""Split a pathname into drive and path. On Posix, drive is always
empty."""
return '', p
# Return the tail (basename) part of a path, same as split(path)[1].
def basename(p):
"""Returns the final component of a pathname"""
i = p.rfind('/') + 1
return p[i:]
# Return the head (dirname) part of a path, same as split(path)[0].
def dirname(p):
"""Returns the directory component of a pathname"""
i = p.rfind('/') + 1
head = p[:i]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head
# Is a path a symbolic link?
# This will always return false on systems where os.lstat doesn't exist.
def islink(path):
"""Test whether a path is a symbolic link"""
try:
st = os.lstat(path)
except (os.error, AttributeError):
return False
return stat.S_ISLNK(st.st_mode)
# Being true for dangling symbolic links is also useful.
def lexists(path):
"""Test whether a path exists. Returns True for broken symbolic links"""
try:
os.lstat(path)
except os.error:
return False
return True
# Are two filenames really pointing to the same file?
def samefile(f1, f2):
"""Test whether two pathnames reference the same actual file"""
s1 = os.stat(f1)
s2 = os.stat(f2)
return samestat(s1, s2)
# Are two open files really referencing the same file?
# (Not necessarily the same file descriptor!)
def sameopenfile(fp1, fp2):
"""Test whether two open file objects reference the same file"""
s1 = os.fstat(fp1)
s2 = os.fstat(fp2)
return samestat(s1, s2)
# Are two stat buffers (obtained from stat, fstat or lstat)
# describing the same file?
def samestat(s1, s2):
"""Test whether two stat buffers reference the same file"""
return s1.st_ino == s2.st_ino and \
s1.st_dev == s2.st_dev
# Is a path a mount point?
# (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
def ismount(path):
"""Test whether a path is a mount point"""
if islink(path):
# A symlink can never be a mount point
return False
try:
s1 = os.lstat(path)
s2 = os.lstat(join(path, '..'))
except os.error:
return False # It doesn't exist -- so not a mount point :-)
dev1 = s1.st_dev
dev2 = s2.st_dev
if dev1 != dev2:
return True # path/.. on a different device as path
ino1 = s1.st_ino
ino2 = s2.st_ino
if ino1 == ino2:
return True # path/.. is the same i-node as path
return False
# Directory tree walk.
# For each directory under top (including top itself, but excluding
# '.' and '..'), func(arg, dirname, filenames) is called, where
# dirname is the name of the directory and filenames is the list
# of files (and subdirectories etc.) in the directory.
# The func may modify the filenames list, to implement a filter,
# or to impose a different order of visiting.
def walk(top, func, arg):
"""Directory tree walk with callback function.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
dirname is the name of the directory, and fnames a list of the names of
the files and subdirectories in dirname (excluding '.' and '..'). func
may modify the fnames list in-place (e.g. via del or slice assignment),
and walk will only recurse into the subdirectories whose names remain in
fnames; this can be used to implement a filter, or to impose a specific
order of visiting. No semantics are defined for, or required of, arg,
beyond that arg is always passed to func. It can be used, e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common."""
warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
stacklevel=2)
try:
names = os.listdir(top)
except os.error:
return
func(arg, top, names)
for name in names:
name = join(top, name)
try:
st = os.lstat(name)
except os.error:
continue
if stat.S_ISDIR(st.st_mode):
walk(name, func, arg)
# Expand paths beginning with '~' or '~user'.
# '~' means $HOME; '~user' means that user's home directory.
# If the path doesn't begin with '~', or if the user or $HOME is unknown,
# the path is returned unchanged (leaving error reporting to whatever
# function is called with the expanded path as argument).
# See also module 'glob' for expansion of *, ? and [...] in pathnames.
# (A function should also be defined to do full *sh-style environment
# variable expansion.)
def expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
if not path.startswith('~'):
return path
i = path.find('/', 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir
else:
userhome = os.environ['HOME']
else:
import pwd
try:
pwent = pwd.getpwnam(path[1:i])
except KeyError:
return path
userhome = pwent.pw_dir
userhome = userhome.rstrip('/')
return (userhome + path[i:]) or '/'
# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged.
_varprog = None
_uvarprog = None
def expandvars(path):
"""Expand shell variables of form $var and ${var}. Unknown variables
are left unchanged."""
global _varprog, _uvarprog
if '$' not in path:
return path
if isinstance(path, _unicode):
if not _uvarprog:
import re
_uvarprog = re.compile(ur'\$(\w+|\{[^}]*\})', re.UNICODE)
varprog = _uvarprog
encoding = sys.<API key>()
else:
if not _varprog:
import re
_varprog = re.compile(r'\$(\w+|\{[^}]*\})')
varprog = _varprog
encoding = None
i = 0
while True:
m = varprog.search(path, i)
if not m:
break
i, j = m.span(0)
name = m.group(1)
if name.startswith('{') and name.endswith('}'):
name = name[1:-1]
if encoding:
name = name.encode(encoding)
if name in os.environ:
tail = path[j:]
value = os.environ[name]
if encoding:
value = value.decode(encoding)
path = path[:i] + value
i = len(path)
path += tail
else:
i = j
return path
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
# It should be understood that this may change the meaning of the path
# if it contains symbolic links!
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX allows one or two initial slashes, but treats three or more
# as single slash.
if (initial_slashes and
path.startswith('//') and not path.startswith('///')):
initial_slashes = 2
comps = path.split('/')
new_comps = []
for comp in comps:
if comp in ('', '.'):
continue
if (comp != '..' or (not initial_slashes and not new_comps) or
(new_comps and new_comps[-1] == '..')):
new_comps.append(comp)
elif new_comps:
new_comps.pop()
comps = new_comps
path = slash.join(comps)
if initial_slashes:
path = slash*initial_slashes + path
return path or dot
def abspath(path):
"""Return an absolute path."""
if not isabs(path):
if isinstance(path, _unicode):
cwd = os.getcwdu()
else:
cwd = os.getcwd()
path = join(cwd, path)
return normpath(path)
# Return a canonical path (i.e. the absolute location of a file on the
# filesystem).
def realpath(filename):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path."""
path, ok = _joinrealpath('', filename, {})
return abspath(path)
# Join two paths, normalizing and eliminating any symbolic links
# encountered in the second path.
def _joinrealpath(path, rest, seen):
if isabs(rest):
rest = rest[1:]
path = sep
while rest:
name, _, rest = rest.partition(sep)
if not name or name == curdir:
# current dir
continue
if name == pardir:
# parent dir
if path:
path, name = split(path)
if name == pardir:
path = join(path, pardir, pardir)
else:
path = pardir
continue
newpath = join(path, name)
if not islink(newpath):
path = newpath
continue
# Resolve the symbolic link
if newpath in seen:
# Already seen this path
path = seen[newpath]
if path is not None:
# use cached value
continue
# The symlink is not resolved, so we must have a symlink loop.
# Return already resolved part + rest of the path unchanged.
return join(newpath, rest), False
seen[newpath] = None # not resolved symlink
path, ok = _joinrealpath(path, os.readlink(newpath), seen)
if not ok:
return join(path, rest), False
seen[newpath] = path # resolved symlink
return path, True
<API key> = (sys.platform == 'darwin')
def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = [x for x in abspath(start).split(sep) if x]
path_list = [x for x in abspath(path).split(sep) if x]
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list) |
var assert = require('assert');
var ElementWriter = require('../src/elementWriter');
describe('ElementWriter', function() {
var ew, ctx, page, tracker, fakePosition;
beforeEach(function() {
fakePosition = {fake: 'position'};
page = { items: [] };
ctx = {
x: 10,
y: 20,
availableWidth: 100,
availableHeight: 100,
getCurrentPage: function() { return page; },
getCurrentPosition: function() { return fakePosition; },
moveDown: function(offset) {
ctx.y += offset;
ctx.availableHeight -= offset;
}
};
tracker = {emit: function() {}};
ew = new ElementWriter(ctx, tracker);
});
function buildLine(height, alignment, x, y) {
return {
getHeight: function() { return height; },
getWidth: function() { return 60; },
inlines: [
{
alignment: alignment,
x: 0,
},
{
x: 30,
},
{
x: 50
}
],
x: x,
y: y
};
}
describe('addLine', function() {
it('should add lines to the current page if there\'s enough space', function() {
var line = buildLine(20);
var position = ew.addLine(line)
assert.equal(page.items.length, 1);
assert.equal(position, fakePosition);
});
it('should return position on page', function() {
var line = buildLine(20);
ew.pushContext(50,50);
ew.pushContext(20,30);
ew.pushContext(11,40);
var position = ew.addLine(line);
assert.equal(position, fakePosition);
});
it('should not add line and return false if there\'s not enough space', function() {
var line = buildLine(120);
assert(!ew.addLine(line));
assert.equal(page.items.length, 0);
});
it('should set line.x and line.y to current context\'s values', function(){
var line = buildLine(30);
ew.addLine(line);
assert.equal(line.x, 10);
assert.equal(line.y, 20);
});
it('should update context.y and context.availableHeight', function() {
ew.addLine(buildLine(30));
assert.equal(ctx.y, 20 + 30);
assert.equal(ctx.availableHeight, 100 - 30);
});
describe('should support line alignment', function() {
it('right', function() {
var line = buildLine(30, 'right');
ew.addLine(line);
assert.equal(line.x, 10 + 100 - line.getWidth());
});
it('center', function() {
var line = buildLine(30, 'center');
ew.addLine(line);
assert.equal(line.x, 10 + (100 - line.getWidth()) / 2);
});
it('justify', function() {
var line = buildLine(30, 'justify');
ew.addLine(line);
assert.equal(line.x, 10);
var additionalSpacing = (100 - 60)/2;
assert.equal(line.inlines[1].x, 30 + additionalSpacing);
assert.equal(line.inlines[2].x, 50 + 2 * additionalSpacing);
});
});
});
describe('addVector', function() {
it('should add vectors to the current page', function() {
ew.addVector({ type: 'rect', x: 10, y: 10 });
assert.equal(page.items.length, 1);
});
it('should offset vectors to the current position', function() {
var rect = { type: 'rect', x: 10, y: 10 };
var ellipse = { type: 'ellipse', x: 10, y: 10 };
var line = { type: 'line', x1: 10, x2: 50, y1: 10, y2: 20 };
var polyline = { type: 'polyline', points: [ { x: 0, y: 0 }, { x: 20, y: 20 }]};
ew.addVector(rect);
ew.addVector(ellipse);
ew.addVector(line);
ew.addVector(polyline);
assert.equal(rect.x, 20);
assert.equal(rect.y, 30);
assert.equal(ellipse.x, 20);
assert.equal(ellipse.y, 30);
assert.equal(line.x1, 20);
assert.equal(line.x2, 60);
assert.equal(line.y1, 30);
assert.equal(line.y2, 40);
assert.equal(polyline.points[0].x, 10);
assert.equal(polyline.points[0].y, 20);
assert.equal(polyline.points[1].x, 30);
assert.equal(polyline.points[1].y, 40);
});
});
describe('addFragment', function(){
var fragment;
beforeEach(function() {
fragment = {
items: [
{
type: 'line',
item: buildLine(30, 'left', 10, 10)
},
{
type: 'line',
item: buildLine(30, 'left', 10, 50)
},
{
type: 'vector',
item: { type: 'rect', x: 10, y: 20 }
},
{
type: 'vector',
item: { type: 'rect', x: 40, y: 60 }
}
]
};
});
it('should add all fragment vectors and lines', function() {
ew.addFragment(fragment);
assert.equal(page.items.length, 4);
});
it('should return false if fragment height is larger than available space', function(){
fragment.height = 120;
assert(!ew.addFragment(fragment));
});
it('should update current position', function() {
fragment.height = 50;
ew.addFragment(fragment);
assert.equal(ctx.y, 20 + 50);
});
it('should offset lines and vectors', function() {
ew.addFragment(fragment);
assert.equal(page.items[0].item.x, 20);
assert.equal(page.items[0].item.y, 30);
assert.equal(page.items[1].item.x, 20);
assert.equal(page.items[1].item.y, 70);
assert.equal(page.items[2].item.x, 20);
assert.equal(page.items[2].item.y, 40);
assert.equal(page.items[3].item.x, 50);
assert.equal(page.items[3].item.y, 80);
});
it('should not modify original line/vector positions', function() {
ew.addFragment(fragment);
assert.equal(fragment.items[0].item.x, 10);
assert.equal(fragment.items[0].item.y, 10);
assert.equal(fragment.items[3].item.x, 40);
assert.equal(fragment.items[3].item.y, 60);
});
});
}); |
<div>
When this option is checked, multiple builds of this project may be executed
in parallel.
<p>
By default, only a single build of a project is executed at a time — any
other requests to start building that project will remain in the build queue
until the first build is complete.<br>
This is a safe default, as projects can often require exclusive access to
certain resources, such as a database, or a piece of hardware.
<p>
But with this option enabled, if there are enough build executors available
that can handle this project, then multiple builds of this project will take
place in parallel. If there are not enough available executors at any point,
any further build requests will be held in the build queue as normal.
<p>
Enabling concurrent builds is useful for projects that execute lengthy test
suites, as it allows each build to contain a smaller number of changes, while
the total turnaround time decreases as subsequent builds do not need to wait
for previous test runs to complete.<br>
This feature is also useful for parameterised projects, whose individual build
executions — depending on the parameters used — can be
completely independent from one another.
<p>
Each concurrently executed build occurs in its own build workspace, isolated
from any other builds. By default, Jenkins appends "<tt>@<num></tt>" to
the workspace directory name, e.g. "<tt>@2</tt>".<br>
The separator "<tt>@</tt>" can be changed by setting the
<tt>hudson.slaves.WorkspaceList</tt> Java system property when starting
Jenkins. For example, "<tt>hudson.slaves.WorkspaceList=-</tt>" would change
the separator to a hyphen.<br>
For more information on setting system properties, see the <a
href="https://wiki.jenkins-ci.org/display/JENKINS/Features+controlled+by+system+properties"
target="_blank">wiki page</a>.
<p>
However, if you enable the <i>Use custom workspace</i> option, all builds will
be executed in the same workspace. Therefore caution is required, as multiple
builds may end up altering the same directory at the same time.
</div> |
Template.ionList.helpers({
classes: function () {
var classes = ['list'];
if (this.class) {
var customClasses = this.class.split(' ');
_(customClasses).each(function (customClass) {
classes.push(customClass);
});
}
return classes.join(' ');
}
}); |
#!/usr/bin/env python
import logging
import sys
from BCBio import GFF
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
if __name__ == "__main__":
attr = sys.argv[2]
for record in GFF.parse(sys.argv[1]):
if len(record.features) == 0:
continue
for feature in sorted(record.features, key=lambda x: x.location.start):
# chrom chromStart chromEnd
# name score strand
# thickStart thickEnd itemRgb
kv = {
"strand": 0 if not feature.location.strand else feature.location.strand,
"value": feature.qualifiers.get("score", [0])[0],
}
if attr not in feature.qualifiers:
continue
name = feature.qualifiers[attr][0]
line = [
record.id,
str(int(feature.location.start)),
str(int(feature.location.end)),
name,
",".join(["%s=%s" % x for x in sorted(kv.items())]),
]
sys.stdout.write("\t".join(line))
sys.stdout.write("\n") |
export { <API key> as default } from "../"; |
#pragma once
#include <dsound.h>
#include <audioclient.h>
#include "SoundTouch\Include\SoundTouch.h"
[uuid("<API key>")]
class CMpcAudioRenderer : public CBaseRenderer
{
public:
CMpcAudioRenderer(LPUNKNOWN punk, HRESULT *phr);
virtual ~CMpcAudioRenderer();
static const AMOVIESETUP_FILTER sudASFilter;
HRESULT CheckInputType (const CMediaType* mtIn);
virtual HRESULT CheckMediaType (const CMediaType *pmt);
virtual HRESULT DoRenderSample (IMediaSample *pMediaSample);
virtual void <API key> (IMediaSample *pMediaSample);
BOOL ScheduleSample (IMediaSample *pMediaSample);
virtual HRESULT SetMediaType (const CMediaType *pmt);
virtual HRESULT CompleteConnect (IPin *pReceivePin);
HRESULT EndOfStream(void);
DECLARE_IUNKNOWN
STDMETHODIMP <API key>(REFIID riid, void **ppv);
STDMETHOD(Run) (REFERENCE_TIME tStart);
STDMETHOD(Stop) ();
STDMETHOD(Pause) ();
private:
HRESULT <API key>(IMediaSample *pMediaSample);
HRESULT InitCoopLevel();
HRESULT ClearBuffer();
HRESULT CreateDSBuffer();
HRESULT <API key>(REFIID riid, void **ppv);
HRESULT <API key>(IMediaSample *pMediaSample, bool *looped);
HRESULT <API key>(IAudioClient **ppAudioClient);
HRESULT InitDevice(IAudioClient *pAudioClient, WAVEFORMATEX *pWaveFormatEx, IAudioRenderClient **ppRenderClient);
LPDIRECTSOUND8 m_pDS;
LPDIRECTSOUNDBUFFER m_pDSBuffer;
DWORD m_dwDSWriteOff;
WAVEFORMATEX *m_pWaveFileFormat;
int m_nDSBufSize;
CBaseReferenceClock* m_pReferenceClock;
double m_dRate;
soundtouch::SoundTouch* m_pSoundTouch;
// WASAPI
HRESULT <API key>(IMediaSample *pMediaSample);
bool useWASAPI;
IAudioClient *pAudioClient;
IAudioRenderClient *pRenderClient;
//HANDLE hEvent;
UINT32 bufferFrameCount;
REFERENCE_TIME <API key>;
HANDLE hTask;
}; |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#ifndef OLSR_AGENT_IMPL_H
#define OLSR_AGENT_IMPL_H
#include "olsr-header.h"
#include "ns3/test.h"
#include "olsr-state.h"
#include "olsr-repositories.h"
#include "ns3/object.h"
#include "ns3/packet.h"
#include "ns3/node.h"
#include "ns3/socket.h"
#include "ns3/<API key>.h"
#include "ns3/<API key>.h"
#include "ns3/timer.h"
#include "ns3/traced-callback.h"
#include "ns3/ipv4.h"
#include "ns3/<API key>.h"
#include "ns3/ipv4-static-routing.h"
#include <vector>
#include <map>
Testcase for MPR computation mechanism
class OlsrMprTestCase;
namespace ns3 {
namespace olsr {
\defgroup olsr OLSR Routing
This section documents the API of the ns-3 OLSR module. For a generic
functional description, please refer to the ns-3 manual.
An %OLSR's routing table entry.
struct RoutingTableEntry
{
Ipv4Address destAddr; ///< Address of the destination node.
Ipv4Address nextAddr; ///< Address of the next hop.
uint32_t interface; ///< Interface index
uint32_t distance; ///< Distance in hops to the destination.
RoutingTableEntry () : // default values
destAddr (), nextAddr (),
interface (0), distance (0) {};
};
class RoutingProtocol;
\ingroup olsr
\brief OLSR routing protocol for IPv4
class RoutingProtocol : public Ipv4RoutingProtocol
{
public:
friend class ::OlsrMprTestCase;
static TypeId GetTypeId (void);
RoutingProtocol ();
virtual ~RoutingProtocol ();
\brief Set the OLSR main address to the first address on the indicated
interface
\param interface IPv4 interface index
void SetMainInterface (uint32_t interface);
Dump the neighbor table, two-hop neighbor table, and routing table
to logging output (NS_LOG_DEBUG log level). If logging is disabled,
this function does nothing.
void Dump (void);
/**
* Return the list of routing table entries discovered by OLSR
**/
std::vector<RoutingTableEntry> <API key> () const;
/**
* Assign a fixed random variable stream number to the random variables
* used by this model. Return the number of streams (possibly zero) that
* have been assigned.
*
* \param stream first stream index to use
* \return the number of stream indices assigned by this model
*/
int64_t AssignStreams (int64_t stream);
/**
* TracedCallback signature for Packet transmit and receive events.
*
* \param [in] header
* \param [in] messages
*/
typedef void (* <API key>)
(const PacketHeader & header, const MessageList & messages);
/**
* TracedCallback signature for routing table computation.
*
* \param [in] size Final routing table size.
*/
typedef void (* <API key>) (uint32_t size);
private:
std::set<uint32_t> <API key>;
Ptr<Ipv4StaticRouting> <API key>;
public:
std::set<uint32_t> <API key> () const
{
return <API key>;
}
void <API key> (std::set<uint32_t> exceptions);
Inject Association to be sent in HNA message
void <API key> (Ipv4Address networkAddr, Ipv4Mask netmask);
Removes Association sent in HNA message
void <API key> (Ipv4Address networkAddr, Ipv4Mask netmask);
Inject Associations from an Ipv4StaticRouting instance
void <API key> (Ptr<Ipv4StaticRouting> routingTable);
/**
* \brief Returns the internal HNA table
* \returns the internal HNA table
*/
Ptr<const Ipv4StaticRouting> <API key> () const;
protected:
virtual void DoInitialize (void);
private:
std::map<Ipv4Address, RoutingTableEntry> m_table; ///< Data structure for the routing table.
Ptr<Ipv4StaticRouting> m_hnaRoutingTable;
<API key> m_events;
Packets sequence number counter.
uint16_t <API key>;
Messages sequence number counter.
uint16_t <API key>;
Advertised Neighbor Set sequence number.
uint16_t m_ansn;
HELLO messages' emission interval.
Time m_helloInterval;
TC messages' emission interval.
Time m_tcInterval;
MID messages' emission interval.
Time m_midInterval;
HNA messages' emission interval.
Time m_hnaInterval;
Willingness for forwarding packets on behalf of other nodes.
uint8_t m_willingness;
Internal state with all needed data structs.
OlsrState m_state;
Ptr<Ipv4> m_ipv4;
void Clear ();
uint32_t GetSize () const { return m_table.size (); }
void RemoveEntry (const Ipv4Address &dest);
void AddEntry (const Ipv4Address &dest,
const Ipv4Address &next,
uint32_t interface,
uint32_t distance);
void AddEntry (const Ipv4Address &dest,
const Ipv4Address &next,
const Ipv4Address &interfaceAddress,
uint32_t distance);
bool Lookup (const Ipv4Address &dest,
RoutingTableEntry &outEntry) const;
bool FindSendEntry (const RoutingTableEntry &entry,
RoutingTableEntry &outEntry) const;
// From Ipv4RoutingProtocol
virtual Ptr<Ipv4Route> RouteOutput (Ptr<Packet> p,
const Ipv4Header &header,
Ptr<NetDevice> oif,
Socket::SocketErrno &sockerr);
virtual bool RouteInput (Ptr<const Packet> p,
const Ipv4Header &header,
Ptr<const NetDevice> idev,
<API key> ucb,
<API key> mcb,
<API key> lcb,
ErrorCallback ecb);
virtual void NotifyInterfaceUp (uint32_t interface);
virtual void NotifyInterfaceDown (uint32_t interface);
virtual void NotifyAddAddress (uint32_t interface, <API key> address);
virtual void NotifyRemoveAddress (uint32_t interface, <API key> address);
virtual void SetIpv4 (Ptr<Ipv4> ipv4);
virtual void PrintRoutingTable (Ptr<OutputStreamWrapper> stream) const;
void DoDispose ();
void SendPacket (Ptr<Packet> packet, const MessageList &containedMessages);
Increments packet sequence number and returns the new value.
inline uint16_t <API key> ();
Increments message sequence number and returns the new value.
inline uint16_t <API key> ();
void RecvOlsr (Ptr<Socket> socket);
void MprComputation ();
void <API key> ();
Ipv4Address GetMainAddress (Ipv4Address iface_addr) const;
bool <API key> (const <API key> &route);
// Timer handlers
Timer m_helloTimer;
void HelloTimerExpire ();
Timer m_tcTimer;
void TcTimerExpire ();
Timer m_midTimer;
void MidTimerExpire ();
Timer m_hnaTimer;
void HnaTimerExpire ();
void DupTupleTimerExpire (Ipv4Address address, uint16_t sequenceNumber);
bool <API key>;
void <API key> (Ipv4Address neighborIfaceAddr);
void <API key> (Ipv4Address neighborMainAddr, Ipv4Address twoHopNeighborAddr);
void <API key> (Ipv4Address mainAddr);
void <API key> (Ipv4Address destAddr, Ipv4Address lastAddr);
void <API key> (Ipv4Address ifaceAddr);
void <API key> (Ipv4Address gatewayAddr, Ipv4Address networkAddr, Ipv4Mask netmask);
void IncrementAnsn ();
A list of pending messages which are buffered awaiting for being sent.
olsr::MessageList m_queuedMessages;
Timer <API key>; // timer for throttling outgoing messages
void ForwardDefault (olsr::MessageHeader olsrMessage,
DuplicateTuple *duplicated,
const Ipv4Address &localIface,
const Ipv4Address &senderAddress);
void QueueMessage (const olsr::MessageHeader &message, Time delay);
void SendQueuedMessages ();
void SendHello ();
void SendTc ();
void SendMid ();
void SendHna ();
void NeighborLoss (const LinkTuple &tuple);
void AddDuplicateTuple (const DuplicateTuple &tuple);
void <API key> (const DuplicateTuple &tuple);
void LinkTupleAdded (const LinkTuple &tuple, uint8_t willingness);
void RemoveLinkTuple (const LinkTuple &tuple);
void LinkTupleUpdated (const LinkTuple &tuple, uint8_t willingness);
void AddNeighborTuple (const NeighborTuple &tuple);
void RemoveNeighborTuple (const NeighborTuple &tuple);
void <API key> (const TwoHopNeighborTuple &tuple);
void <API key> (const TwoHopNeighborTuple &tuple);
void AddMprSelectorTuple (const MprSelectorTuple &tuple);
void <API key> (const MprSelectorTuple &tuple);
void AddTopologyTuple (const TopologyTuple &tuple);
void RemoveTopologyTuple (const TopologyTuple &tuple);
void AddIfaceAssocTuple (const IfaceAssocTuple &tuple);
void <API key> (const IfaceAssocTuple &tuple);
void AddAssociationTuple (const AssociationTuple &tuple);
void <API key> (const AssociationTuple &tuple);
void ProcessHello (const olsr::MessageHeader &msg,
const Ipv4Address &receiverIface,
const Ipv4Address &senderIface);
void ProcessTc (const olsr::MessageHeader &msg,
const Ipv4Address &senderIface);
void ProcessMid (const olsr::MessageHeader &msg,
const Ipv4Address &senderIface);
void ProcessHna (const olsr::MessageHeader &msg,
const Ipv4Address &senderIface);
void LinkSensing (const olsr::MessageHeader &msg,
const olsr::MessageHeader::Hello &hello,
const Ipv4Address &receiverIface,
const Ipv4Address &sender_iface);
void PopulateNeighborSet (const olsr::MessageHeader &msg,
const olsr::MessageHeader::Hello &hello);
void <API key> (const olsr::MessageHeader &msg,
const olsr::MessageHeader::Hello &hello);
void <API key> (const olsr::MessageHeader &msg,
const olsr::MessageHeader::Hello &hello);
int Degree (NeighborTuple const &tuple);
Check that address is one of my interfaces
bool IsMyOwnAddress (const Ipv4Address & a) const;
Ipv4Address m_mainAddress;
// One socket per interface, each bound to that interface's address
// (reason: for OLSR Link Sensing we need to know on which interface
// HELLO messages arrive)
std::map< Ptr<Socket>, <API key> > m_socketAddresses;
TracedCallback <const PacketHeader &,
const MessageList &> m_rxPacketTrace;
TracedCallback <const PacketHeader &,
const MessageList &> m_txPacketTrace;
TracedCallback <uint32_t> <API key>;
Provides uniform random variables.
Ptr<<API key>> <API key>;
};
}
} // namespace ns3
#endif /* OLSR_AGENT_IMPL_H */ |
#!/bin/ash
# Handler for config application of all types.
# Types supported:
# uci-* UCI config files
# file-* Undefined format for whatever
# edited-files-* raw edited files
. /usr/lib/webif/functions.sh
. /lib/config/uci.sh
config_cb() {
[ "$1" = "system" ] && system_cfg="$2"
[ "$1" = "server" ] && l2tpns_cfg="$2"
[ "$1" = "updatedd" ] && updatedd_cfg="$2"
}
# this line is for compatibility with webif-lua
#LUA="/usr/lib/webif/LUA/xwrt-apply.lua"
#if [ -e $LUA ]; then
# /usr/lib/webif/LUA/xwrt-apply.lua
HANDLERS_file='
hosts) rm -f /etc/hosts; mv $config /etc/hosts; killall -HUP dnsmasq ;;
ethers) rm -f /etc/ethers; mv $config /etc/ethers; killall -HUP dnsmasq ;;
dnsmasq.conf) mv /tmp/.webif/file-dnsmasq.conf /etc/dnsmasq.conf && /etc/init.d/dnsmasq restart;;
httpd.conf) mv -f /tmp/.webif/file-httpd.conf /etc/httpd.conf && HTTP_RESTART=1 ;;
'
# for some reason a for loop with "." doesn't work
eval "$(cat /usr/lib/webif/apply-*.sh 2>&-)"
mkdir -p "/tmp/.webif"
_pushed_dir=$(pwd)
cd "/tmp/.webif" |
#ifndef PNG_UTILS_H
#define PNG_UTILS_H
namespace png_utils
{
HBITMAP LoadBuffer(std::vector<unsigned char>& input_png);
HBITMAP LoadFile(const wchar_t* filename);
} // namespace png_utils
#endif // PNG_UTILS_H |
#include <linux/kernel.h>
#include <linux/delay.h>
#include "sprdfb_panel.h"
#define NT35516_SpiWriteCmd(cmd) \
{ \
spi_send_cmd((cmd >>8));\
spi_send_cmd((cmd & 0xFF));\
}
#define <API key>(data)\
{ \
spi_send_data((data >> 8));\
spi_send_data((data & 0xFF));\
}
static int32_t <API key>(struct panel_spec *self)
{
uint32_t data = 0;
spi_send_cmd_t spi_send_cmd = self->info.rgb->bus_info.spi->ops->spi_send_cmd;
spi_send_data_t spi_send_data = self->info.rgb->bus_info.spi->ops->spi_send_data;
spi_read_t spi_read = self->info.rgb->bus_info.spi->ops->spi_read;
// NT35516 + AUO 4.29'
// VCC=IOVCC=3.3V RGB_24Bit
NT35516_SpiWriteCmd(0xDB00);
spi_read(&data);
//TEST Commands
NT35516_SpiWriteCmd(0xFF00); <API key>(0xAA);
NT35516_SpiWriteCmd(0xFF01); <API key>(0x55);
NT35516_SpiWriteCmd(0xFF02); <API key>(0x25);
NT35516_SpiWriteCmd(0xFF03); <API key>(0x01);
//NT35516_SpiWriteCmd(0xFA0F); <API key>(0x20);
NT35516_SpiWriteCmd(0xF300); <API key>(0x02);
NT35516_SpiWriteCmd(0xF303); <API key>(0x15);
//ENABLE PAGE 0
NT35516_SpiWriteCmd(0xF000); <API key>(0x55); //Manufacture Command Set Control
NT35516_SpiWriteCmd(0xF001); <API key>(0xAA);
NT35516_SpiWriteCmd(0xF002); <API key>(0x52);
NT35516_SpiWriteCmd(0xF003); <API key>(0x08);
NT35516_SpiWriteCmd(0xF004); <API key>(0x00);
NT35516_SpiWriteCmd(0xB800); <API key>(0x01);
NT35516_SpiWriteCmd(0xB801); <API key>(0x02);
NT35516_SpiWriteCmd(0xB802); <API key>(0x02);
NT35516_SpiWriteCmd(0xB803); <API key>(0x02);
NT35516_SpiWriteCmd(0xBC00); <API key>(0x05); //Zig-Zag Inversion
NT35516_SpiWriteCmd(0xBC01); <API key>(0x05);
NT35516_SpiWriteCmd(0xBC02); <API key>(0x05);
NT35516_SpiWriteCmd(0x4C00); <API key>(0x11); //DB4=1,Enable Vivid Color,DB4=0 Disable Vivid Color
// ENABLE PAGE 1
NT35516_SpiWriteCmd(0xF000); <API key>(0x55); //Manufacture Command Set Control
NT35516_SpiWriteCmd(0xF001); <API key>(0xAA);
NT35516_SpiWriteCmd(0xF002); <API key>(0x52);
NT35516_SpiWriteCmd(0xF003); <API key>(0x08);
NT35516_SpiWriteCmd(0xF004); <API key>(0x01);//Page1
NT35516_SpiWriteCmd(0xB000); <API key>(0x05); // Setting AVDD Voltage 6V
NT35516_SpiWriteCmd(0xB001); <API key>(0x05);
NT35516_SpiWriteCmd(0xB002); <API key>(0x05);
NT35516_SpiWriteCmd(0xB600); <API key>(0x44); // Setting AVEE boosting time 2.5*vpnl
NT35516_SpiWriteCmd(0xB601); <API key>(0x44);
NT35516_SpiWriteCmd(0xB602); <API key>(0x44);
NT35516_SpiWriteCmd(0xB100); <API key>(0x05); // Setting AVEE Voltage -6V
NT35516_SpiWriteCmd(0xB101); <API key>(0x05);
NT35516_SpiWriteCmd(0xB102); <API key>(0x05);
//Setting AVEE boosting time -2.5xVPNL
NT35516_SpiWriteCmd(0xB700); <API key>(0x34);
NT35516_SpiWriteCmd(0xB701); <API key>(0x34);
NT35516_SpiWriteCmd(0xB702); <API key>(0x34);
//Setting VGLX boosting time AVEE-AVDD
NT35516_SpiWriteCmd(0xBA00); <API key>(0x14); //0x24 --> 0x14
NT35516_SpiWriteCmd(0xBA01); <API key>(0x14);
NT35516_SpiWriteCmd(0xBA02); <API key>(0x14);
//Gamma Voltage
NT35516_SpiWriteCmd(0xBC00); <API key>(0x00);
NT35516_SpiWriteCmd(0xBC01); <API key>(0xA0);//VGMP 0x88=4.7V 0x78=4.5V 0xA0=5.0V
NT35516_SpiWriteCmd(0xBC02); <API key>(0x00);//VGSP
//Gamma Voltage
NT35516_SpiWriteCmd(0xBD00); <API key>(0x00);
NT35516_SpiWriteCmd(0xBD01); <API key>(0xA0);//VGMN 0x88=-4.7V 0x78=-4.5V 0xA0=-5.0V
NT35516_SpiWriteCmd(0xBD02); <API key>(0x00);//VGSN
NT35516_SpiWriteCmd(0xBE00); <API key>(0x57);
//GAMMA RED Positive
NT35516_SpiWriteCmd(0xD100); <API key>(0x00);
NT35516_SpiWriteCmd(0xD101); <API key>(0x32);
NT35516_SpiWriteCmd(0xD102); <API key>(0x00);
NT35516_SpiWriteCmd(0xD103); <API key>(0x41);
NT35516_SpiWriteCmd(0xD104); <API key>(0x00);
NT35516_SpiWriteCmd(0xD105); <API key>(0x54);
NT35516_SpiWriteCmd(0xD106); <API key>(0x00);
NT35516_SpiWriteCmd(0xD107); <API key>(0x67);
NT35516_SpiWriteCmd(0xD108); <API key>(0x00);
NT35516_SpiWriteCmd(0xD109); <API key>(0x7A);
NT35516_SpiWriteCmd(0xD10A); <API key>(0x00);
NT35516_SpiWriteCmd(0xD10B); <API key>(0x98);
NT35516_SpiWriteCmd(0xD10C); <API key>(0x00);
NT35516_SpiWriteCmd(0xD10D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xD10E); <API key>(0x00);
NT35516_SpiWriteCmd(0xD10F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xD200); <API key>(0x01);
NT35516_SpiWriteCmd(0xD201); <API key>(0x01);
NT35516_SpiWriteCmd(0xD202); <API key>(0x01);
NT35516_SpiWriteCmd(0xD203); <API key>(0x3F);
NT35516_SpiWriteCmd(0xD204); <API key>(0x01);
NT35516_SpiWriteCmd(0xD205); <API key>(0x70);
NT35516_SpiWriteCmd(0xD206); <API key>(0x01);
NT35516_SpiWriteCmd(0xD207); <API key>(0xB4);
NT35516_SpiWriteCmd(0xD208); <API key>(0x01);
NT35516_SpiWriteCmd(0xD209); <API key>(0xEC);
NT35516_SpiWriteCmd(0xD20A); <API key>(0x01);
NT35516_SpiWriteCmd(0xD20B); <API key>(0xED);
NT35516_SpiWriteCmd(0xD20C); <API key>(0x02);
NT35516_SpiWriteCmd(0xD20D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xD20E); <API key>(0x02);
NT35516_SpiWriteCmd(0xD20F); <API key>(0x51);
NT35516_SpiWriteCmd(0xD300); <API key>(0x02);
NT35516_SpiWriteCmd(0xD301); <API key>(0x6C);
NT35516_SpiWriteCmd(0xD302); <API key>(0x02);
NT35516_SpiWriteCmd(0xD303); <API key>(0x8D);
NT35516_SpiWriteCmd(0xD304); <API key>(0x02);
NT35516_SpiWriteCmd(0xD305); <API key>(0xA5);
NT35516_SpiWriteCmd(0xD306); <API key>(0x02);
NT35516_SpiWriteCmd(0xD307); <API key>(0xC9);
NT35516_SpiWriteCmd(0xD308); <API key>(0x02);
NT35516_SpiWriteCmd(0xD309); <API key>(0xEA);
NT35516_SpiWriteCmd(0xD30A); <API key>(0x03);
NT35516_SpiWriteCmd(0xD30B); <API key>(0x19);
NT35516_SpiWriteCmd(0xD30C); <API key>(0x03);
NT35516_SpiWriteCmd(0xD30D); <API key>(0x45);
NT35516_SpiWriteCmd(0xD30E); <API key>(0x03);
NT35516_SpiWriteCmd(0xD30F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xD400); <API key>(0x03);
NT35516_SpiWriteCmd(0xD401); <API key>(0xB0);
NT35516_SpiWriteCmd(0xD402); <API key>(0x03);
NT35516_SpiWriteCmd(0xD403); <API key>(0xF4);
//Positive Gamma for GREEN
NT35516_SpiWriteCmd(0xD500); <API key>(0x00);
NT35516_SpiWriteCmd(0xD501); <API key>(0x37);
NT35516_SpiWriteCmd(0xD502); <API key>(0x00);
NT35516_SpiWriteCmd(0xD503); <API key>(0x41);
NT35516_SpiWriteCmd(0xD504); <API key>(0x00);
NT35516_SpiWriteCmd(0xD505); <API key>(0x54);
NT35516_SpiWriteCmd(0xD506); <API key>(0x00);
NT35516_SpiWriteCmd(0xD507); <API key>(0x67);
NT35516_SpiWriteCmd(0xD508); <API key>(0x00);
NT35516_SpiWriteCmd(0xD509); <API key>(0x7A);
NT35516_SpiWriteCmd(0xD50A); <API key>(0x00);
NT35516_SpiWriteCmd(0xD50B); <API key>(0x98);
NT35516_SpiWriteCmd(0xD50C); <API key>(0x00);
NT35516_SpiWriteCmd(0xD50D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xD50E); <API key>(0x00);
NT35516_SpiWriteCmd(0xD50F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xD600); <API key>(0x01);
NT35516_SpiWriteCmd(0xD601); <API key>(0x01);
NT35516_SpiWriteCmd(0xD602); <API key>(0x01);
NT35516_SpiWriteCmd(0xD603); <API key>(0x3F);
NT35516_SpiWriteCmd(0xD604); <API key>(0x01);
NT35516_SpiWriteCmd(0xD605); <API key>(0x70);
NT35516_SpiWriteCmd(0xD606); <API key>(0x01);
NT35516_SpiWriteCmd(0xD607); <API key>(0xB4);
NT35516_SpiWriteCmd(0xD608); <API key>(0x01);
NT35516_SpiWriteCmd(0xD609); <API key>(0xEC);
NT35516_SpiWriteCmd(0xD60A); <API key>(0x01);
NT35516_SpiWriteCmd(0xD60B); <API key>(0xED);
NT35516_SpiWriteCmd(0xD60C); <API key>(0x02);
NT35516_SpiWriteCmd(0xD60D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xD60E); <API key>(0x02);
NT35516_SpiWriteCmd(0xD60F); <API key>(0x51);
NT35516_SpiWriteCmd(0xD700); <API key>(0x02);
NT35516_SpiWriteCmd(0xD701); <API key>(0x6C);
NT35516_SpiWriteCmd(0xD702); <API key>(0x02);
NT35516_SpiWriteCmd(0xD703); <API key>(0x8D);
NT35516_SpiWriteCmd(0xD704); <API key>(0x02);
NT35516_SpiWriteCmd(0xD705); <API key>(0xA5);
NT35516_SpiWriteCmd(0xD706); <API key>(0x02);
NT35516_SpiWriteCmd(0xD707); <API key>(0xC9);
NT35516_SpiWriteCmd(0xD708); <API key>(0x02);
NT35516_SpiWriteCmd(0xD709); <API key>(0xEA);
NT35516_SpiWriteCmd(0xD70A); <API key>(0x03);
NT35516_SpiWriteCmd(0xD70B); <API key>(0x19);
NT35516_SpiWriteCmd(0xD70C); <API key>(0x03);
NT35516_SpiWriteCmd(0xD70D); <API key>(0x45);
NT35516_SpiWriteCmd(0xD70E); <API key>(0x03);
NT35516_SpiWriteCmd(0xD70F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xD800); <API key>(0x03);
NT35516_SpiWriteCmd(0xD801); <API key>(0xA0);
NT35516_SpiWriteCmd(0xD802); <API key>(0x03);
NT35516_SpiWriteCmd(0xD803); <API key>(0xF4);
//Positive Gamma for BLUE
NT35516_SpiWriteCmd(0xD900); <API key>(0x00);
NT35516_SpiWriteCmd(0xD901); <API key>(0x32);
NT35516_SpiWriteCmd(0xD902); <API key>(0x00);
NT35516_SpiWriteCmd(0xD903); <API key>(0x41);
NT35516_SpiWriteCmd(0xD904); <API key>(0x00);
NT35516_SpiWriteCmd(0xD905); <API key>(0x54);
NT35516_SpiWriteCmd(0xD906); <API key>(0x00);
NT35516_SpiWriteCmd(0xD907); <API key>(0x67);
NT35516_SpiWriteCmd(0xD908); <API key>(0x00);
NT35516_SpiWriteCmd(0xD909); <API key>(0x7A);
NT35516_SpiWriteCmd(0xD90A); <API key>(0x00);
NT35516_SpiWriteCmd(0xD90B); <API key>(0x98);
NT35516_SpiWriteCmd(0xD90C); <API key>(0x00);
NT35516_SpiWriteCmd(0xD90D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xD90E); <API key>(0x00);
NT35516_SpiWriteCmd(0xD90F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xDD00); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD01); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD02); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD03); <API key>(0x3F);
NT35516_SpiWriteCmd(0xDD04); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD05); <API key>(0x70);
NT35516_SpiWriteCmd(0xDD06); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD07); <API key>(0xB4);
NT35516_SpiWriteCmd(0xDD08); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD09); <API key>(0xEC);
NT35516_SpiWriteCmd(0xDD0A); <API key>(0x01);
NT35516_SpiWriteCmd(0xDD0B); <API key>(0xED);
NT35516_SpiWriteCmd(0xDD0C); <API key>(0x02);
NT35516_SpiWriteCmd(0xDD0D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xDD0E); <API key>(0x02);
NT35516_SpiWriteCmd(0xDD0F); <API key>(0x51);
NT35516_SpiWriteCmd(0xDE00); <API key>(0x02);
NT35516_SpiWriteCmd(0xDE01); <API key>(0x6C);
NT35516_SpiWriteCmd(0xDE02); <API key>(0x02);
NT35516_SpiWriteCmd(0xDE03); <API key>(0x8D);
NT35516_SpiWriteCmd(0xDE04); <API key>(0x02);
NT35516_SpiWriteCmd(0xDE05); <API key>(0xA5);
NT35516_SpiWriteCmd(0xDE06); <API key>(0x02);
NT35516_SpiWriteCmd(0xDE07); <API key>(0xC9);
NT35516_SpiWriteCmd(0xDE08); <API key>(0x02);
NT35516_SpiWriteCmd(0xDE09); <API key>(0xEA);
NT35516_SpiWriteCmd(0xDE0A); <API key>(0x03);
NT35516_SpiWriteCmd(0xDE0B); <API key>(0x19);
NT35516_SpiWriteCmd(0xDE0C); <API key>(0x03);
NT35516_SpiWriteCmd(0xDE0D); <API key>(0x45);
NT35516_SpiWriteCmd(0xDE0E); <API key>(0x03);
NT35516_SpiWriteCmd(0xDE0F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xDF00); <API key>(0x03);
NT35516_SpiWriteCmd(0xDF01); <API key>(0xA0);
NT35516_SpiWriteCmd(0xDF02); <API key>(0x03);
NT35516_SpiWriteCmd(0xDF03); <API key>(0xF4);
//Negative Gamma for RED
NT35516_SpiWriteCmd(0xE000); <API key>(0x00);
NT35516_SpiWriteCmd(0xE001); <API key>(0x32);
NT35516_SpiWriteCmd(0xE002); <API key>(0x00);
NT35516_SpiWriteCmd(0xE003); <API key>(0x41);
NT35516_SpiWriteCmd(0xE004); <API key>(0x00);
NT35516_SpiWriteCmd(0xE005); <API key>(0x54);
NT35516_SpiWriteCmd(0xE006); <API key>(0x00);
NT35516_SpiWriteCmd(0xE007); <API key>(0x67);
NT35516_SpiWriteCmd(0xE008); <API key>(0x00);
NT35516_SpiWriteCmd(0xE009); <API key>(0x7A);
NT35516_SpiWriteCmd(0xE00A); <API key>(0x00);
NT35516_SpiWriteCmd(0xE00B); <API key>(0x98);
NT35516_SpiWriteCmd(0xE00C); <API key>(0x00);
NT35516_SpiWriteCmd(0xE00D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xE00E); <API key>(0x00);
NT35516_SpiWriteCmd(0xE00F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xE100); <API key>(0x01);
NT35516_SpiWriteCmd(0xE101); <API key>(0x01);
NT35516_SpiWriteCmd(0xE102); <API key>(0x01);
NT35516_SpiWriteCmd(0xE103); <API key>(0x3F);
NT35516_SpiWriteCmd(0xE104); <API key>(0x01);
NT35516_SpiWriteCmd(0xE105); <API key>(0x70);
NT35516_SpiWriteCmd(0xE106); <API key>(0x01);
NT35516_SpiWriteCmd(0xE107); <API key>(0xB4);
NT35516_SpiWriteCmd(0xE108); <API key>(0x01);
NT35516_SpiWriteCmd(0xE109); <API key>(0xEC);
NT35516_SpiWriteCmd(0xE10A); <API key>(0x01);
NT35516_SpiWriteCmd(0xE10B); <API key>(0xED);
NT35516_SpiWriteCmd(0xE10C); <API key>(0x02);
NT35516_SpiWriteCmd(0xE10D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xE10E); <API key>(0x02);
NT35516_SpiWriteCmd(0xE10F); <API key>(0x51);
NT35516_SpiWriteCmd(0xE200); <API key>(0x02);
NT35516_SpiWriteCmd(0xE201); <API key>(0x6C);
NT35516_SpiWriteCmd(0xE202); <API key>(0x02);
NT35516_SpiWriteCmd(0xE203); <API key>(0x8D);
NT35516_SpiWriteCmd(0xE204); <API key>(0x02);
NT35516_SpiWriteCmd(0xE205); <API key>(0xA5);
NT35516_SpiWriteCmd(0xE206); <API key>(0x02);
NT35516_SpiWriteCmd(0xE207); <API key>(0xC9);
NT35516_SpiWriteCmd(0xE208); <API key>(0x02);
NT35516_SpiWriteCmd(0xE209); <API key>(0xEA);
NT35516_SpiWriteCmd(0xE20A); <API key>(0x03);
NT35516_SpiWriteCmd(0xE20B); <API key>(0x19);
NT35516_SpiWriteCmd(0xE20C); <API key>(0x03);
NT35516_SpiWriteCmd(0xE20D); <API key>(0x45);
NT35516_SpiWriteCmd(0xE20E); <API key>(0x03);
NT35516_SpiWriteCmd(0xE20F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xE300); <API key>(0x03);
NT35516_SpiWriteCmd(0xE301); <API key>(0xA0);
NT35516_SpiWriteCmd(0xE302); <API key>(0x03);
NT35516_SpiWriteCmd(0xE303); <API key>(0xF4);
//Negative Gamma for GERREN
NT35516_SpiWriteCmd(0xE400); <API key>(0x00);
NT35516_SpiWriteCmd(0xE401); <API key>(0x32);
NT35516_SpiWriteCmd(0xE402); <API key>(0x00);
NT35516_SpiWriteCmd(0xE403); <API key>(0x41);
NT35516_SpiWriteCmd(0xE404); <API key>(0x00);
NT35516_SpiWriteCmd(0xE405); <API key>(0x54);
NT35516_SpiWriteCmd(0xE406); <API key>(0x00);
NT35516_SpiWriteCmd(0xE407); <API key>(0x67);
NT35516_SpiWriteCmd(0xE408); <API key>(0x00);
NT35516_SpiWriteCmd(0xE409); <API key>(0x7A);
NT35516_SpiWriteCmd(0xE40A); <API key>(0x00);
NT35516_SpiWriteCmd(0xE40B); <API key>(0x98);
NT35516_SpiWriteCmd(0xE40C); <API key>(0x00);
NT35516_SpiWriteCmd(0xE40D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xE40E); <API key>(0x00);
NT35516_SpiWriteCmd(0xE40F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xE500); <API key>(0x01);
NT35516_SpiWriteCmd(0xE501); <API key>(0x01);
NT35516_SpiWriteCmd(0xE502); <API key>(0x01);
NT35516_SpiWriteCmd(0xE503); <API key>(0x3F);
NT35516_SpiWriteCmd(0xE504); <API key>(0x01);
NT35516_SpiWriteCmd(0xE505); <API key>(0x70);
NT35516_SpiWriteCmd(0xE506); <API key>(0x01);
NT35516_SpiWriteCmd(0xE507); <API key>(0xB4);
NT35516_SpiWriteCmd(0xE508); <API key>(0x01);
NT35516_SpiWriteCmd(0xE509); <API key>(0xEC);
NT35516_SpiWriteCmd(0xE50A); <API key>(0x01);
NT35516_SpiWriteCmd(0xE50B); <API key>(0xED);
NT35516_SpiWriteCmd(0xE50C); <API key>(0x02);
NT35516_SpiWriteCmd(0xE50D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xE50E); <API key>(0x02);
NT35516_SpiWriteCmd(0xE50F); <API key>(0x51);
NT35516_SpiWriteCmd(0xE600); <API key>(0x02);
NT35516_SpiWriteCmd(0xE601); <API key>(0x6C);
NT35516_SpiWriteCmd(0xE602); <API key>(0x02);
NT35516_SpiWriteCmd(0xE603); <API key>(0x8D);
NT35516_SpiWriteCmd(0xE604); <API key>(0x02);
NT35516_SpiWriteCmd(0xE605); <API key>(0xA5);
NT35516_SpiWriteCmd(0xE606); <API key>(0x02);
NT35516_SpiWriteCmd(0xE607); <API key>(0xC9);
NT35516_SpiWriteCmd(0xE608); <API key>(0x02);
NT35516_SpiWriteCmd(0xE609); <API key>(0xEA);
NT35516_SpiWriteCmd(0xE60A); <API key>(0x03);
NT35516_SpiWriteCmd(0xE60B); <API key>(0x19);
NT35516_SpiWriteCmd(0xE60C); <API key>(0x03);
NT35516_SpiWriteCmd(0xE60D); <API key>(0x45);
NT35516_SpiWriteCmd(0xE60E); <API key>(0x03);
NT35516_SpiWriteCmd(0xE60F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xE700); <API key>(0x03);
NT35516_SpiWriteCmd(0xE701); <API key>(0xA0);
NT35516_SpiWriteCmd(0xE702); <API key>(0x03);
NT35516_SpiWriteCmd(0xE703); <API key>(0xF4);
//Negative Gamma for BLUE
NT35516_SpiWriteCmd(0xE800); <API key>(0x00);
NT35516_SpiWriteCmd(0xE801); <API key>(0x32);
NT35516_SpiWriteCmd(0xE802); <API key>(0x00);
NT35516_SpiWriteCmd(0xE803); <API key>(0x41);
NT35516_SpiWriteCmd(0xE804); <API key>(0x00);
NT35516_SpiWriteCmd(0xE805); <API key>(0x54);
NT35516_SpiWriteCmd(0xE806); <API key>(0x00);
NT35516_SpiWriteCmd(0xE807); <API key>(0x67);
NT35516_SpiWriteCmd(0xE808); <API key>(0x00);
NT35516_SpiWriteCmd(0xE809); <API key>(0x7A);
NT35516_SpiWriteCmd(0xE80A); <API key>(0x00);
NT35516_SpiWriteCmd(0xE80B); <API key>(0x98);
NT35516_SpiWriteCmd(0xE80C); <API key>(0x00);
NT35516_SpiWriteCmd(0xE80D); <API key>(0xB0);
NT35516_SpiWriteCmd(0xE80E); <API key>(0x00);
NT35516_SpiWriteCmd(0xE80F); <API key>(0xDB);
NT35516_SpiWriteCmd(0xE900); <API key>(0x01);
NT35516_SpiWriteCmd(0xE901); <API key>(0x01);
NT35516_SpiWriteCmd(0xE902); <API key>(0x01);
NT35516_SpiWriteCmd(0xE903); <API key>(0x3F);
NT35516_SpiWriteCmd(0xE904); <API key>(0x01);
NT35516_SpiWriteCmd(0xE905); <API key>(0x70);
NT35516_SpiWriteCmd(0xE906); <API key>(0x01);
NT35516_SpiWriteCmd(0xE907); <API key>(0xB4);
NT35516_SpiWriteCmd(0xE908); <API key>(0x01);
NT35516_SpiWriteCmd(0xE909); <API key>(0xEC);
NT35516_SpiWriteCmd(0xE90A); <API key>(0x01);
NT35516_SpiWriteCmd(0xE90B); <API key>(0xED);
NT35516_SpiWriteCmd(0xE90C); <API key>(0x02);
NT35516_SpiWriteCmd(0xE90D); <API key>(0x1E);
NT35516_SpiWriteCmd(0xE90E); <API key>(0x02);
NT35516_SpiWriteCmd(0xE90F); <API key>(0x51);
NT35516_SpiWriteCmd(0xEA00); <API key>(0x02);
NT35516_SpiWriteCmd(0xEA01); <API key>(0x6C);
NT35516_SpiWriteCmd(0xEA02); <API key>(0x02);
NT35516_SpiWriteCmd(0xEA03); <API key>(0x8D);
NT35516_SpiWriteCmd(0xEA04); <API key>(0x02);
NT35516_SpiWriteCmd(0xEA05); <API key>(0xA5);
NT35516_SpiWriteCmd(0xEA06); <API key>(0x02);
NT35516_SpiWriteCmd(0xEA07); <API key>(0xC9);
NT35516_SpiWriteCmd(0xEA08); <API key>(0x02);
NT35516_SpiWriteCmd(0xEA09); <API key>(0xEA);
NT35516_SpiWriteCmd(0xEA0A); <API key>(0x03);
NT35516_SpiWriteCmd(0xEA0B); <API key>(0x19);
NT35516_SpiWriteCmd(0xEA0C); <API key>(0x03);
NT35516_SpiWriteCmd(0xEA0D); <API key>(0x45);
NT35516_SpiWriteCmd(0xEA0E); <API key>(0x03);
NT35516_SpiWriteCmd(0xEA0F); <API key>(0x7A);
NT35516_SpiWriteCmd(0xEB00); <API key>(0x03);
NT35516_SpiWriteCmd(0xEB01); <API key>(0xA0);
NT35516_SpiWriteCmd(0xEB02); <API key>(0x03);
NT35516_SpiWriteCmd(0xEB03); <API key>(0xF4);
NT35516_SpiWriteCmd(0x3A00); <API key>(0x77);
NT35516_SpiWriteCmd(0x3500); <API key>(0x00);
NT35516_SpiWriteCmd(0x1100); // Sleep out
udelay(120);
NT35516_SpiWriteCmd(0x2900); // Display On
}
static uint32_t <API key>(struct panel_spec *self)
{
/*Jessica TODO: need read id*/
return 0x16;
}
#if 0
void <API key>(
uint16 left, // start Horizon address
uint16 right, // end Horizon address
uint16 top, // start Vertical address
uint16 bottom // end Vertical address
)
{
NT35516_SpiWriteCmd(0x2A00); <API key>((left>>8));// set left address
NT35516_SpiWriteCmd(0x2A01); <API key>((left&0xff));
NT35516_SpiWriteCmd(0x2A02); <API key>((right>>8));// set right address
NT35516_SpiWriteCmd(0x2A03); <API key>((right&0xff));
NT35516_SpiWriteCmd(0x2B00); <API key>((top>>8));// set left address
NT35516_SpiWriteCmd(0x2B01); <API key>((top&0xff));
NT35516_SpiWriteCmd(0x2B02); <API key>((bottom>>8));// set bottom address
NT35516_SpiWriteCmd(0x2B03); <API key>((bottom&0xff));
}
LCD_ERR_E <API key>(BOOLEAN is_sleep)
{
if(is_sleep==1)
{
NT35516_SpiWriteCmd(0x2800);
LCD_Delay(200);
NT35516_SpiWriteCmd(0x1000);
LCD_Delay(200);
//Lcd_EnvidOnOff(0);//RGB TIMENG OFF
//LCD_Delay(200);
}
else
{
//Lcd_EnvidOnOff(1);//RGB TIMENG ON
//LCD_Delay(200);
//LCDinit_TFT();
//LCD_Delay(200);
}
return 0;
}
LCD_ERR_E <API key>(
uint16 left, //left of the window
uint16 top, //top of the window
uint16 right, //right of the window
uint16 bottom //bottom of the window
)
{
//<API key>(left, right, top, bottom);
NT35516_SpiWriteCmd(0x2C00);
return TRUE;
}
#endif
static struct panel_operations <API key> = {
.panel_init = <API key>,
.panel_readid = <API key>,
};
static struct timing_rgb <API key> = {
.hfp = 16, /* unit: pixel */
.hbp = 16,
.hsync = 1,
.vfp = 16, /*unit: line*/
.vbp = 16,
.vsync = 1,
};
static struct spi_info <API key> = {
.ops = NULL,
};
static struct info_rgb <API key> = {
.cmd_bus_mode = <API key>,
.video_bus_width = 24, /*18,16*/
.h_sync_pol = SPRDFB_POLARITY_POS,
.v_sync_pol = SPRDFB_POLARITY_POS,
.de_pol = SPRDFB_POLARITY_POS,
.timing = &<API key>,
.bus_info = {
.spi = &<API key>,
}
};
struct panel_spec <API key> = {
.width = 540,
.height = 960,
.type = LCD_MODE_RGB,
.direction = LCD_DIRECT_NORMAL,
.info = {
.rgb = &<API key>
},
.ops = &<API key>,
};
struct panel_cfg lcd_nt35516_rgb_spi = {
/* this panel can only be main lcd */
.dev_id = SPRDFB_MAINLCD_ID,
.lcd_id = 0x16,
.lcd_name = "lcd_nt35516_rgb_spi",
.panel = &<API key>,
};
static int __init <API key>(void)
{
return <API key>(&lcd_nt35516_rgb_spi);
}
subsys_initcall(<API key>); |
#include <linux/serial.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#define NR_PORTS 2
#define OFFSET_THR 0x00 /* Transmit Holding register */
#define OFFSET_RBR 0x00 /* Receive Buffer register */
#define OFFSET_DLL 0x00 /* Divisor Latch (Low-Byte) */
#define OFFSET_IER 0x04 /* Interrupt Enable Register */
#define OFFSET_DLH 0x04 /* Divisor Latch (High-Byte) */
#define OFFSET_IIR 0x08 /* Interrupt Identification Register */
#define OFFSET_LCR 0x0C /* Line Control Register */
#define OFFSET_MCR 0x10 /* Modem Control Register */
#define OFFSET_LSR 0x14 /* Line Status Register */
#define OFFSET_MSR 0x18 /* Modem Status Register */
#define OFFSET_SCR 0x1C /* SCR Scratch Register */
#define OFFSET_GCTL 0x24 /* Global Control Register */
#define UART_GET_CHAR(uart) bfin_read16(((uart)->port.membase + OFFSET_RBR))
#define UART_GET_DLL(uart) bfin_read16(((uart)->port.membase + OFFSET_DLL))
#define UART_GET_IER(uart) bfin_read16(((uart)->port.membase + OFFSET_IER))
#define UART_GET_DLH(uart) bfin_read16(((uart)->port.membase + OFFSET_DLH))
#define UART_GET_IIR(uart) bfin_read16(((uart)->port.membase + OFFSET_IIR))
#define UART_GET_LCR(uart) bfin_read16(((uart)->port.membase + OFFSET_LCR))
#define UART_GET_LSR(uart) bfin_read16(((uart)->port.membase + OFFSET_LSR))
#define UART_GET_GCTL(uart) bfin_read16(((uart)->port.membase + OFFSET_GCTL))
#define UART_PUT_CHAR(uart, v) bfin_write16(((uart)->port.membase + OFFSET_THR), v)
#define UART_PUT_DLL(uart, v) bfin_write16(((uart)->port.membase + OFFSET_DLL), v)
#define UART_PUT_IER(uart, v) bfin_write16(((uart)->port.membase + OFFSET_IER), v)
#define UART_PUT_DLH(uart, v) bfin_write16(((uart)->port.membase + OFFSET_DLH), v)
#define UART_PUT_LCR(uart, v) bfin_write16(((uart)->port.membase + OFFSET_LCR), v)
#define UART_PUT_GCTL(uart, v) bfin_write16(((uart)->port.membase + OFFSET_GCTL), v)
#if defined(<API key>) || defined(<API key>)
# define <API key>
# ifndef <API key>
# define <API key> -1
# endif
# ifndef <API key>
# define <API key> -1
# endif
# ifndef <API key>
# define <API key> -1
# endif
# ifndef <API key>
# define <API key> -1
# endif
#endif
/*
* The pin configuration is different from schematic
*/
struct bfin_serial_port {
struct uart_port port;
unsigned int old_status;
#ifdef <API key>
int tx_done;
int tx_count;
struct circ_buf rx_dma_buf;
struct timer_list rx_dma_timer;
int rx_dma_nrows;
unsigned int tx_dma_channel;
unsigned int rx_dma_channel;
struct work_struct tx_dma_workqueue;
#else
struct work_struct cts_workqueue;
#endif
#ifdef <API key>
int cts_pin;
int rts_pin;
#endif
};
struct bfin_serial_port bfin_serial_ports[NR_PORTS];
struct bfin_serial_res {
unsigned long uart_base_addr;
int uart_irq;
#ifdef <API key>
unsigned int uart_tx_dma_channel;
unsigned int uart_rx_dma_channel;
#endif
#ifdef <API key>
int uart_cts_pin;
int uart_rts_pin;
#endif
};
struct bfin_serial_res <API key>[] = {
#ifdef <API key>
{
0xFFC00400,
IRQ_UART0_RX,
#ifdef <API key>
CH_UART0_TX,
CH_UART0_RX,
#endif
#ifdef <API key>
<API key>,
<API key>,
#endif
},
#endif
#ifdef <API key>
{
0xFFC02000,
IRQ_UART1_RX,
#ifdef <API key>
CH_UART1_TX,
CH_UART1_RX,
#endif
#ifdef <API key>
<API key>,
<API key>,
#endif
},
#endif
};
int nr_ports = ARRAY_SIZE(<API key>);
#define DRIVER_NAME "bfin-uart"
static void bfin_serial_hw_init(struct bfin_serial_port *uart)
{
#ifdef <API key>
peripheral_request(P_UART0_TX, DRIVER_NAME);
peripheral_request(P_UART0_RX, DRIVER_NAME);
#endif
#ifdef <API key>
peripheral_request(P_UART1_TX, DRIVER_NAME);
peripheral_request(P_UART1_RX, DRIVER_NAME);
#endif
#ifdef <API key>
if (uart->cts_pin >= 0) {
gpio_request(uart->cts_pin, DRIVER_NAME);
<API key>(uart->cts_pin);
}
if (uart->rts_pin >= 0) {
gpio_request(uart->rts_pin, DRIVER_NAME);
<API key>(uart->rts_pin);
}
#endif
} |
<?php
/**
* CakeBaseReporter contains common reporting features used in the CakePHP Test suite
*
* @package cake
* @subpackage cake.tests.lib
*/
class CakeBaseReporter extends SimpleReporter {
/**
* Time the test runs started.
*
* @var integer
* @access protected
*/
var $_timeStart = 0;
/**
* Time the test runs ended
*
* @var integer
* @access protected
*/
var $_timeEnd = 0;
/**
* Duration of all test methods.
*
* @var integer
* @access protected
*/
var $_timeDuration = 0;
/**
* Array of request parameters. Usually parsed GET params.
*
* @var array
*/
var $params = array();
/**
* Character set for the output of test reporting.
*
* @var string
* @access protected
*/
var $_characterSet;
function CakeBaseReporter($charset = 'utf-8', $params = array()) {
$this->SimpleReporter();
if (!$charset) {
$charset = 'utf-8';
}
$this->_characterSet = $charset;
$this->params = $params;
}
/**
* Signals / Paints the beginning of a TestSuite executing.
* Starts the timer for the TestSuite execution time.
*
* @param string $test_name Name of the test that is being run.
* @param integer $size
* @return void
*/
function paintGroupStart($test_name, $size) {
if (empty($this->_timeStart)) {
$this->_timeStart = $this->_getTime();
}
parent::paintGroupStart($test_name, $size);
}
/**
* Signals/Paints the end of a TestSuite. All test cases have run
* and timers are stopped.
*
* @param string $test_name Name of the test that is being run.
* @return void
*/
function paintGroupEnd($test_name) {
$this->_timeEnd = $this->_getTime();
$this->_timeDuration = $this->_timeEnd - $this->_timeStart;
parent::paintGroupEnd($test_name);
}
/**
* Paints the beginning of a test method being run. This is used
* to start/resume the code coverage tool.
*
* @param string $method The method name being run.
* @return void
*/
function paintMethodStart($method) {
parent::paintMethodStart($method);
if (!empty($this->params['codeCoverage'])) {
CodeCoverageManager::start();
}
}
/**
* Paints the end of a test method being run. This is used
* to pause the collection of code coverage if its being used.
*
* @param string $method The name of the method being run.
* @return void
*/
function paintMethodEnd($method) {
parent::paintMethodEnd($method);
if (!empty($this->params['codeCoverage'])) {
CodeCoverageManager::stop();
}
}
/**
* Get the current time in microseconds. Similar to getMicrotime in basics.php
* but in a separate function to reduce dependancies.
*
* @return float Time in microseconds
* @access protected
*/
function _getTime() {
list($usec, $sec) = explode(' ', microtime());
return ((float)$sec + (float)$usec);
}
/**
* Retrieves a list of test cases from the active Manager class,
* displaying it in the correct format for the reporter subclass
*
* @return mixed
*/
function testCaseList() {
$testList = TestManager::getTestCaseList();
return $testList;
}
/**
* Retrieves a list of group test cases from the active Manager class
* displaying it in the correct format for the reporter subclass.
*
* @return void
*/
function groupTestList() {
$testList = TestManager::getGroupTestList();
return $testList;
}
/**
* Paints the start of the response from the test suite.
* Used to paint things like head elements in an html page.
*
* @return void
*/
function paintDocumentStart() {
}
/**
* Paints the end of the response from the test suite.
* Used to paint things like </body> in an html page.
*
* @return void
*/
function paintDocumentEnd() {
}
/**
* Paint a list of test sets, core, app, and plugin test sets
* available.
*
* @return void
*/
function paintTestMenu() {
}
/**
* Get the baseUrl if one is available.
*
* @return string The base url for the request.
*/
function baseUrl() {
if (!empty($_SERVER['PHP_SELF'])) {
return $_SERVER['PHP_SELF'];
}
return '';
}
} |
/**
* accordion - jQuery EasyUI
*
* Dependencies:
* panel
*
*/
(function($){
function setSize(container, param){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
var cc = $(container);
if (param){
$.extend(opts, {
width: param.width,
height: param.height
});
}
cc._size(opts);
var headerHeight = 0;
var bodyHeight = 'auto';
var headers = cc.find('>.panel>.accordion-header');
if (headers.length){
headerHeight = $(headers[0]).css('height', '')._outerHeight();
}
if (!isNaN(parseInt(opts.height))){
bodyHeight = cc.height() - headerHeight*headers.length;
}
_resize(true, bodyHeight - _resize(false) + 1);
function _resize(collapsible, height){
var totalHeight = 0;
for(var i=0; i<panels.length; i++){
var p = panels[i];
var h = p.panel('header')._outerHeight(headerHeight);
if (p.panel('options').collapsible == collapsible){
var pheight = isNaN(height) ? undefined : (height+headerHeight*h.length);
p.panel('resize', {
width: cc.width(),
height: (collapsible ? pheight : undefined)
});
totalHeight += p.panel('panel').outerHeight()-headerHeight*h.length;
}
}
return totalHeight;
}
}
/**
* find a panel by specified property, return the panel object or panel index.
*/
function findBy(container, property, value, all){
var panels = $.data(container, 'accordion').panels;
var pp = [];
for(var i=0; i<panels.length; i++){
var p = panels[i];
if (property){
if (p.panel('options')[property] == value){
pp.push(p);
}
} else {
if (p[0] == $(value)[0]){
return i;
}
}
}
if (property){
return all ? pp : (pp.length ? pp[0] : null);
} else {
return -1;
}
}
function getSelections(container){
return findBy(container, 'collapsed', false, true);
}
function getSelected(container){
var pp = getSelections(container);
return pp.length ? pp[0] : null;
}
/**
* get panel index, start with 0
*/
function getPanelIndex(container, panel){
return findBy(container, null, panel);
}
/**
* get the specified panel.
*/
function getPanel(container, which){
var panels = $.data(container, 'accordion').panels;
if (typeof which == 'number'){
if (which < 0 || which >= panels.length){
return null;
} else {
return panels[which];
}
}
return findBy(container, 'title', which);
}
function setProperties(container){
var opts = $.data(container, 'accordion').options;
var cc = $(container);
if (opts.border){
cc.removeClass('accordion-noborder');
} else {
cc.addClass('accordion-noborder');
}
}
function init(container){
var state = $.data(container, 'accordion');
var cc = $(container);
cc.addClass('accordion');
state.panels = [];
cc.children('div').each(function(){
var opts = $.extend({}, $.parser.parseOptions(this), {
selected: ($(this).attr('selected') ? true : undefined)
});
var pp = $(this);
state.panels.push(pp);
createPanel(container, pp, opts);
});
cc.bind('_resize', function(e,force){
if ($(this).hasClass('easyui-fluid') || force){
setSize(container);
}
return false;
});
}
function createPanel(container, pp, options){
var opts = $.data(container, 'accordion').options;
pp.panel($.extend({}, {
collapsible: true,
minimizable: false,
maximizable: false,
closable: false,
doSize: false,
collapsed: true,
headerCls: 'accordion-header',
bodyCls: 'accordion-body'
}, options, {
onBeforeExpand: function(){
if (options.onBeforeExpand){
if (options.onBeforeExpand.call(this) == false){return false}
}
if (!opts.multiple){
// get all selected panel
var all = $.grep(getSelections(container), function(p){
return p.panel('options').collapsible;
});
for(var i=0; i<all.length; i++){
unselect(container, getPanelIndex(container, all[i]));
}
}
var header = $(this).panel('header');
header.addClass('<API key>');
header.find('.accordion-collapse').removeClass('accordion-expand');
},
onExpand: function(){
if (options.onExpand){options.onExpand.call(this)}
opts.onSelect.call(container, $(this).panel('options').title, getPanelIndex(container, this));
},
onBeforeCollapse: function(){
if (options.onBeforeCollapse){
if (options.onBeforeCollapse.call(this) == false){return false}
}
var header = $(this).panel('header');
header.removeClass('<API key>');
header.find('.accordion-collapse').addClass('accordion-expand');
},
onCollapse: function(){
if (options.onCollapse){options.onCollapse.call(this)}
opts.onUnselect.call(container, $(this).panel('options').title, getPanelIndex(container, this));
}
}));
var header = pp.panel('header');
var tool = header.children('div.panel-tool');
tool.children('a.panel-tool-collapse').hide(); // hide the old collapse button
var t = $('<a href="javascript:void(0)"></a>').addClass('accordion-collapse accordion-expand').appendTo(tool);
t.bind('click', function(){
togglePanel(pp);
return false;
});
pp.panel('options').collapsible ? t.show() : t.hide();
header.click(function(){
togglePanel(pp);
return false;
});
function togglePanel(p){
var popts = p.panel('options');
if (popts.collapsible){
var index = getPanelIndex(container, p);
if (popts.collapsed){
select(container, index);
} else {
unselect(container, index);
}
}
}
}
/**
* select and set the specified panel active
*/
function select(container, which){
var p = getPanel(container, which);
if (!p){return}
stopAnimate(container);
var opts = $.data(container, 'accordion').options;
p.panel('expand', opts.animate);
}
function unselect(container, which){
var p = getPanel(container, which);
if (!p){return}
stopAnimate(container);
var opts = $.data(container, 'accordion').options;
p.panel('collapse', opts.animate);
}
function doFirstSelect(container){
var opts = $.data(container, 'accordion').options;
var p = findBy(container, 'selected', true);
if (p){
_select(getPanelIndex(container, p));
} else {
_select(opts.selected);
}
function _select(index){
var animate = opts.animate;
opts.animate = false;
select(container, index);
opts.animate = animate;
}
}
/**
* stop the animation of all panels
*/
function stopAnimate(container){
var panels = $.data(container, 'accordion').panels;
for(var i=0; i<panels.length; i++){
panels[i].stop(true,true);
}
}
function add(container, options){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
if (options.selected == undefined) options.selected = true;
stopAnimate(container);
var pp = $('<div></div>').appendTo(container);
panels.push(pp);
createPanel(container, pp, options);
setSize(container);
opts.onAdd.call(container, options.title, panels.length-1);
if (options.selected){
select(container, panels.length-1);
}
}
function remove(container, which){
var state = $.data(container, 'accordion');
var opts = state.options;
var panels = state.panels;
stopAnimate(container);
var panel = getPanel(container, which);
var title = panel.panel('options').title;
var index = getPanelIndex(container, panel);
if (!panel){return}
if (opts.onBeforeRemove.call(container, title, index) == false){return}
panels.splice(index, 1);
panel.panel('destroy');
if (panels.length){
setSize(container);
var curr = getSelected(container);
if (!curr){
select(container, 0);
}
}
opts.onRemove.call(container, title, index);
}
$.fn.accordion = function(options, param){
if (typeof options == 'string'){
return $.fn.accordion.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'accordion');
if (state){
$.extend(state.options, options);
} else {
$.data(this, 'accordion', {
options: $.extend({}, $.fn.accordion.defaults, $.fn.accordion.parseOptions(this), options),
accordion: $(this).addClass('accordion'),
panels: []
});
init(this);
}
setProperties(this);
setSize(this);
doFirstSelect(this);
});
};
$.fn.accordion.methods = {
options: function(jq){
return $.data(jq[0], 'accordion').options;
},
panels: function(jq){
return $.data(jq[0], 'accordion').panels;
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
getSelections: function(jq){
return getSelections(jq[0]);
},
getSelected: function(jq){
return getSelected(jq[0]);
},
getPanel: function(jq, which){
return getPanel(jq[0], which);
},
getPanelIndex: function(jq, panel){
return getPanelIndex(jq[0], panel);
},
select: function(jq, which){
return jq.each(function(){
select(this, which);
});
},
unselect: function(jq, which){
return jq.each(function(){
unselect(this, which);
});
},
add: function(jq, options){
return jq.each(function(){
add(this, options);
});
},
remove: function(jq, which){
return jq.each(function(){
remove(this, which);
});
}
};
$.fn.accordion.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
'width','height',
{fit:'boolean',border:'boolean',animate:'boolean',multiple:'boolean',selected:'number'}
]));
};
$.fn.accordion.defaults = {
width: 'auto',
height: 'auto',
fit: false,
border: true,
animate: true,
multiple: false,
selected: 0,
onSelect: function(title, index){},
onUnselect: function(title, index){},
onAdd: function(title, index){},
onBeforeRemove: function(title, index){},
onRemove: function(title, index){}
};
})(jQuery); |
(function ($) {
'use strict';
var defaultOptions = {
source: '',
formatDropdownItem: formatDropdownItem,
formatResult: formatResult
};
$.extend(true, $.trumbowyg, {
langs: {
en: {
mention: 'Mention'
},
da: {
mention: 'Nævn'
},
fr: {
mention: 'Mentioner'
},
ru: {
mention: 'Упомянуть'
},
tr: {
mention: 'Bahset'
},
zh_tw: {
mention: ''
},
pt_br: {
mention: 'Menção'
},
},
plugins: {
mention: {
init: function (trumbowyg) {
trumbowyg.o.plugins.mention = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.mention || {});
var btnDef = {
dropdown: buildDropdown(trumbowyg.o.plugins.mention.source, trumbowyg)
};
trumbowyg.addBtnDef('mention', btnDef);
}
}
}
});
/**
* Build dropdown list
*
* @param {Array} items Items
* @param {object} trumbowyg Editor
*
* @return {Array}
*/
function buildDropdown(items, trumbowyg) {
var dropdown = [];
// Check if source is an array
if (items.constructor === Array) {
$.each(items, function (i, item) {
var btn = 'mention-' + i,
btnDef = {
hasIcon: false,
text: trumbowyg.o.plugins.mention.formatDropdownItem(item),
fn: function () {
trumbowyg.execCmd('insertHTML', trumbowyg.o.plugins.mention.formatResult(item));
return true;
}
};
trumbowyg.addBtnDef(btn, btnDef);
dropdown.push(btn);
});
}
return dropdown;
}
/**
* Format item in dropdown.
*
* @param {object} item Item object.
*
* @return {string}
*/
function formatDropdownItem(item) {
return item.login;
}
/**
* Format result pasted in editor.
*
* @param {object} item Item object.
*
* @return {string}
*/
function formatResult(item) {
return '@' + item.login + ' ';
}
})(jQuery); |
using ShareX.HelpersLib;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace ShareX.ImageEffectsLib
{
internal class Canvas : ImageEffect
{
private Padding margin;
[DefaultValue(typeof(Padding), "0, 0, 0, 0")]
public Padding Margin
{
get
{
return margin;
}
set
{
if (value.Top >= 0 && value.Right >= 0 && value.Bottom >= 0 && value.Left >= 0)
{
margin = value;
}
}
}
public Canvas()
{
this.<API key>();
}
public override Image Apply(Image img)
{
if (Margin.All == 0) return img;
return ImageHelpers.AddCanvas(img, Margin);
}
}
} |
# ChangeLog
All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles.
## [2.1.3] - 2018-02-01
Changed
* This component is now compatible with version 3 of `sebastian/diff`
## [2.1.2] - 2018-01-12
Fixed
* Fix comparison of DateTimeImmutable objects
## [2.1.1] - 2017-12-22
Fixed
* Fixed [phpunit/
## [2.1.0] - 2017-11-03
Added
* Added `SebastianBergmann\Comparator\Factory::reset()` to unregister all non-default comparators
* Added support for `phpunit/<API key>` version `^5.0`
[2.1.3]: https://github.com/sebastianbergmann/comparator/compare/2.1.2...2.1.3
[2.1.2]: https://github.com/sebastianbergmann/comparator/compare/2.1.1...2.1.2
[2.1.1]: https://github.com/sebastianbergmann/comparator/compare/2.1.0...2.1.1
[2.1.0]: https://github.com/sebastianbergmann/comparator/compare/2.0.2...2.1.0 |
// -*- mode: java; c-basic-offset: 2; -*-
package com.google.appinventor.components.runtime;
import junit.framework.TestCase;
import java.util.Calendar;
import java.util.TimeZone;
/**
* Tests Clock.java.
*
*/
public class ClockTest extends TestCase {
private final Calendar tc = Clock.MakeInstant("10/11/1941 09:30:00");
public void testNow() throws Exception {
assertTrue(0 > Clock.Duration(Clock.Now(), tc));
}
public void testMakeInstant() throws Exception {
assertEquals("Oct 11, 1941 9:30:00 AM", Clock.FormatDateTime(tc));
}
public void <API key>() throws Exception {
assertEquals("Jan 1, 1970 12:00:00 AM",
Clock.FormatDateTime(Clock.<API key>(0
- TimeZone.getDefault().getRawOffset())));
}
public void testGetMillis() throws Exception {
assertEquals(-TimeZone.getDefault().getRawOffset(),
Clock.GetMillis(Clock.MakeInstant("1/1/1970 00:00:00")));
}
public void testAddYears() throws Exception {
assertEquals("Oct 11, 1943 9:30:00 AM", Clock.FormatDateTime(Clock.AddYears(tc, 2)));
}
public void testAddYears2() throws Exception {
assertEquals("Oct 11, 1931 9:30:00 AM", Clock.FormatDateTime(Clock.AddYears(tc, -10)));
}
public void testAddMonths() throws Exception {
assertEquals("Dec 11, 1941 9:30:00 AM", Clock.FormatDateTime(Clock.AddMonths(tc, 2)));
}
public void testAddMonths2() throws Exception {
assertEquals("Oct 11, 1942 9:30:00 AM", Clock.FormatDateTime(Clock.AddMonths(tc, 12)));
}
public void testAddWeeks() throws Exception {
assertEquals("Sep 10, 2002 12:00:00 AM", Clock.FormatDateTime(
Clock.AddWeeks(Clock.MakeInstant("9/11/2001 00:00:00"), 52)));
}
public void testAddWeeks2() throws Exception {
assertEquals("Sep 18, 2001 12:00:00 AM", Clock.FormatDateTime(
Clock.AddWeeks(Clock.MakeInstant("9/11/2001 00:00:00"), 1)));
}
public void testAddDays() throws Exception {
assertEquals("Oct 9, 1941", Clock.FormatDate(Clock.AddDays(tc, -2)));
}
public void testAddDays2() throws Exception {
assertEquals("Nov 1, 1941", Clock.FormatDate(Clock.AddDays(tc, 21)));
}
public void testAddHours() throws Exception {
assertEquals("Oct 11, 1941 7:30:00 AM", Clock.FormatDateTime(Clock.AddHours(tc, -2)));
}
public void testAddHours2() throws Exception {
assertEquals("Oct 12, 1941 9:30:00 AM", Clock.FormatDateTime(Clock.AddHours(tc, 24)));
}
public void testAddMinutes() throws Exception {
assertEquals("Oct 11, 1941 9:32:00 AM", Clock.FormatDateTime(Clock.AddMinutes(tc, 2)));
}
public void testAddSeconds() throws Exception {
assertEquals("9:31:01 AM", Clock.FormatTime(Clock.AddSeconds(tc, 61)));
}
public void testSecond() throws Exception {
assertEquals(0, Clock.Second(tc));
}
public void testMinute() throws Exception {
assertEquals(30, Clock.Minute(tc));
}
public void testHour() throws Exception {
assertEquals(9, Clock.Hour(tc));
}
public void testWeekday() throws Exception {
assertEquals(2, Clock.Weekday(Clock.MakeInstant("11/2/2009")));
}
public void testWeekdayName() throws Exception {
assertEquals("Monday", Clock.WeekdayName(Clock.MakeInstant("11/2/2009")));
}
public void testDayOfMonth() throws Exception {
assertEquals(11, Clock.DayOfMonth(tc));
}
public void testMonth() throws Exception {
assertEquals(10, Clock.Month(tc));
}
public void testMonthName() throws Exception {
assertEquals("October", Clock.MonthName(tc));
}
public void testYear() throws Exception {
assertEquals(1941, Clock.Year(tc));
}
} |
// Purpose: This is a panel which is rendered image on top of an entity
// $Revision: $
// $NoKeywords: $
#ifndef <API key>
#define <API key>
#include "vgui_EntityPanel.h"
#include "<API key>.h"
#include "vgui_HealthBar.h"
#include "vgui_BitmapPanel.h"
// forward declarations
class C_BaseEntity;
class KeyValues;
class BitmapImage;
// This is a base class for a panel which always is rendered on top of an entity
class <API key> : public CEntityPanel
{
public:
DECLARE_CLASS( <API key>, CEntityPanel );
// constructor
<API key>( vgui::Panel *parent, const char *panelName );
~<API key>();
// initialization
bool Init( KeyValues* pInitData, C_BaseEntity* pEntity );
// called when we're ticked...
virtual void OnTick();
virtual bool ShouldDraw( void );
virtual void ComputeAndSetSize( void );
private:
CHealthBarPanel *<API key>;
CHealthBarPanel *m_NormalHealthBar;
CHealthBarPanel *m_ResourceLevelBar;
<API key> *m_pImagePanel;
};
#endif // <API key> |
/* Generated By:JJTree: Do not edit this line. <API key>.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,<API key>=true */
package com.orientechnologies.orient.core.sql.parser;
import java.util.Map;
public class <API key> extends SimpleNode {
protected OIdentifier left;
protected OExpression right;
public <API key>(int id) {
super(id);
}
public <API key>(OrientSql p, int id) {
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public void replaceParameters(Map<Object, Object> params) {
right.replaceParameters(params);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(left.toString());
result.append(" = ");
result.append(right.toString());
return result.toString();
}
}
/* JavaCC - OriginalChecksum=<API key> (do not edit this line) */ |
package iradix
// rawIterator visits each of the nodes in the tree, even the ones that are not
// leaves. It keeps track of the effective path (what a leaf at a given node
// would be called), which is useful for comparing trees.
type rawIterator struct {
// node is the starting node in the tree for the iterator.
node *Node
// stack keeps track of edges in the frontier.
stack []rawStackEntry
// pos is the current position of the iterator.
pos *Node
// path is the effective path of the current iterator position,
// regardless of whether the current node is a leaf.
path string
}
// rawStackEntry is used to keep track of the cumulative common path as well as
// its associated edges in the frontier.
type rawStackEntry struct {
path string
edges edges
}
// Front returns the current node that has been iterated to.
func (i *rawIterator) Front() *Node {
return i.pos
}
// Path returns the effective path of the current node, even if it's not actually
// a leaf.
func (i *rawIterator) Path() string {
return i.path
}
// Next advances the iterator to the next node.
func (i *rawIterator) Next() {
// Initialize our stack if needed.
if i.stack == nil && i.node != nil {
i.stack = []rawStackEntry{
{
edges: edges{
edge{node: i.node},
},
},
}
}
for len(i.stack) > 0 {
// Inspect the last element of the stack.
n := len(i.stack)
last := i.stack[n-1]
elem := last.edges[0].node
// Update the stack.
if len(last.edges) > 1 {
i.stack[n-1].edges = last.edges[1:]
} else {
i.stack = i.stack[:n-1]
}
// Push the edges onto the frontier.
if len(elem.edges) > 0 {
path := last.path + string(elem.prefix)
i.stack = append(i.stack, rawStackEntry{path, elem.edges})
}
i.pos = elem
i.path = last.path + string(elem.prefix)
return
}
i.pos = nil
i.path = ""
} |
// <API key>: Apache-2.0 WITH LLVM-exception
// This file implements the MipsMCCodeEmitter class.
#include "MipsMCCodeEmitter.h"
#include "MCTargetDesc/MipsFixupKinds.h"
#include "MCTargetDesc/MipsMCExpr.h"
#include "MCTargetDesc/MipsMCTargetDesc.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
using namespace llvm;
#define DEBUG_TYPE "mccodeemitter"
#define GET_INSTRMAP_INFO
#include "MipsGenInstrInfo.inc"
#undef GET_INSTRMAP_INFO
namespace llvm {
MCCodeEmitter *<API key>(const MCInstrInfo &MCII,
const MCRegisterInfo &MRI,
MCContext &Ctx) {
return new MipsMCCodeEmitter(MCII, Ctx, false);
}
MCCodeEmitter *<API key>(const MCInstrInfo &MCII,
const MCRegisterInfo &MRI,
MCContext &Ctx) {
return new MipsMCCodeEmitter(MCII, Ctx, true);
}
} // end namespace llvm
// If the D<shift> instruction has a shift amount that is greater
// than 31 (checked in calling routine), lower it to a D<shift>32 instruction
static void LowerLargeShift(MCInst& Inst) {
assert(Inst.getNumOperands() == 3 && "Invalid no. of operands for shift!");
assert(Inst.getOperand(2).isImm());
int64_t Shift = Inst.getOperand(2).getImm();
if (Shift <= 31)
return; // Do nothing
Shift -= 32;
// saminus32
Inst.getOperand(2).setImm(Shift);
switch (Inst.getOpcode()) {
default:
// Calling function is not synchronized
llvm_unreachable("Unexpected shift instruction");
case Mips::DSLL:
Inst.setOpcode(Mips::DSLL32);
return;
case Mips::DSRL:
Inst.setOpcode(Mips::DSRL32);
return;
case Mips::DSRA:
Inst.setOpcode(Mips::DSRA32);
return;
case Mips::DROTR:
Inst.setOpcode(Mips::DROTR32);
return;
}
}
// Fix a bad compact branch encoding for beqc/bnec.
void MipsMCCodeEmitter::LowerCompactBranch(MCInst& Inst) const {
// easily fixed.
unsigned RegOp0 = Inst.getOperand(0).getReg();
unsigned RegOp1 = Inst.getOperand(1).getReg();
unsigned Reg0 = Ctx.getRegisterInfo()->getEncodingValue(RegOp0);
unsigned Reg1 = Ctx.getRegisterInfo()->getEncodingValue(RegOp1);
if (Inst.getOpcode() == Mips::BNEC || Inst.getOpcode() == Mips::BEQC ||
Inst.getOpcode() == Mips::BNEC64 || Inst.getOpcode() == Mips::BEQC64) {
assert(Reg0 != Reg1 && "Instruction has bad operands ($rs == $rt)!");
if (Reg0 < Reg1)
return;
} else if (Inst.getOpcode() == Mips::BNVC || Inst.getOpcode() == Mips::BOVC) {
if (Reg0 >= Reg1)
return;
} else if (Inst.getOpcode() == Mips::BNVC_MMR6 ||
Inst.getOpcode() == Mips::BOVC_MMR6) {
if (Reg1 >= Reg0)
return;
} else
llvm_unreachable("Cannot rewrite unknown branch!");
Inst.getOperand(0).setReg(RegOp1);
Inst.getOperand(1).setReg(RegOp0);
}
bool MipsMCCodeEmitter::isMicroMips(const MCSubtargetInfo &STI) const {
return STI.getFeatureBits()[Mips::FeatureMicroMips];
}
bool MipsMCCodeEmitter::isMips32r6(const MCSubtargetInfo &STI) const {
return STI.getFeatureBits()[Mips::FeatureMips32r6];
}
void MipsMCCodeEmitter::EmitByte(unsigned char C, raw_ostream &OS) const {
OS << (char)C;
}
void MipsMCCodeEmitter::EmitInstruction(uint64_t Val, unsigned Size,
const MCSubtargetInfo &STI,
raw_ostream &OS) const {
// Output the instruction encoding in little endian byte order.
// Little-endian byte ordering:
// mips32r2: 4 | 3 | 2 | 1
// microMIPS: 2 | 1 | 4 | 3
if (IsLittleEndian && Size == 4 && isMicroMips(STI)) {
EmitInstruction(Val >> 16, 2, STI, OS);
EmitInstruction(Val, 2, STI, OS);
} else {
for (unsigned i = 0; i < Size; ++i) {
unsigned Shift = IsLittleEndian ? i * 8 : (Size - 1 - i) * 8;
EmitByte((Val >> Shift) & 0xff, OS);
}
}
}
encodeInstruction - Emit the instruction.
Size the instruction with Desc.getSize().
void MipsMCCodeEmitter::
encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const
{
// Non-pseudo instructions that get changed for direct object
// only based on operand values.
// If this list of instructions get much longer we will move
// the check to a function call. Until then, this is more efficient.
MCInst TmpInst = MI;
switch (MI.getOpcode()) {
// If shift amount is >= 32 it the inst needs to be lowered further
case Mips::DSLL:
case Mips::DSRL:
case Mips::DSRA:
case Mips::DROTR:
LowerLargeShift(TmpInst);
break;
// Compact branches, enforce encoding restrictions.
case Mips::BEQC:
case Mips::BNEC:
case Mips::BEQC64:
case Mips::BNEC64:
case Mips::BOVC:
case Mips::BOVC_MMR6:
case Mips::BNVC:
case Mips::BNVC_MMR6:
LowerCompactBranch(TmpInst);
}
unsigned long N = Fixups.size();
uint32_t Binary = <API key>(TmpInst, Fixups, STI);
// Check for unimplemented opcodes.
// Unfortunately in MIPS both NOP and SLL will come in with Binary == 0
// so we have to special check for them.
const unsigned Opcode = TmpInst.getOpcode();
if ((Opcode != Mips::NOP) && (Opcode != Mips::SLL) &&
(Opcode != Mips::SLL_MM) && (Opcode != Mips::SLL_MMR6) && !Binary)
llvm_unreachable("unimplemented opcode in encodeInstruction()");
int NewOpcode = -1;
if (isMicroMips(STI)) {
if (isMips32r6(STI)) {
NewOpcode = Mips::MipsR62MicroMipsR6(Opcode, Mips::Arch_micromipsr6);
if (NewOpcode == -1)
NewOpcode = Mips::Std2MicroMipsR6(Opcode, Mips::Arch_micromipsr6);
}
else
NewOpcode = Mips::Std2MicroMips(Opcode, Mips::Arch_micromips);
// Check whether it is Dsp instruction.
if (NewOpcode == -1)
NewOpcode = Mips::Dsp2MicroMips(Opcode, Mips::Arch_mmdsp);
if (NewOpcode != -1) {
if (Fixups.size() > N)
Fixups.pop_back();
TmpInst.setOpcode (NewOpcode);
Binary = <API key>(TmpInst, Fixups, STI);
}
if (((MI.getOpcode() == Mips::MOVEP_MM) ||
(MI.getOpcode() == Mips::MOVEP_MMR6))) {
unsigned RegPair = <API key>(MI, 0, Fixups, STI);
Binary = (Binary & 0xFFFFFC7F) | (RegPair << 7);
}
}
const MCInstrDesc &Desc = MCII.get(TmpInst.getOpcode());
// Get byte count of instruction
unsigned Size = Desc.getSize();
if (!Size)
llvm_unreachable("Desc.getSize() returns 0");
EmitInstruction(Binary, Size, STI, OS);
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm()) return MO.getImm() >> 2;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_Mips_PC16)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm()) return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_Mips_PC16)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm())
return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-2, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_Mips_PC16)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm())
return MO.getImm() >> 2;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_Mips_PC16)));
return 0;
}
<API key> - Return binary encoding of the microMIPS branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm()) return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::create(0, Expr,
MCFixupKind(Mips::<API key>)));
return 0;
}
<API key> - Return binary encoding of the microMIPS
10-bit branch target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm()) return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::create(0, Expr,
MCFixupKind(Mips::<API key>)));
return 0;
}
<API key> - Return binary encoding of the microMIPS branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm()) return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::create(0, Expr,
MCFixupKind(Mips::
<API key>)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm()) return MO.getImm() >> 2;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_MIPS_PC21_S2)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand for microMIPS. If the machine operand requires
relocation, record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm()) return MO.getImm() >> 2;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::<API key>)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm()) return MO.getImm() >> 2;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::fixup_MIPS_PC26_S2)));
return 0;
}
<API key> - Return binary encoding of the branch
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::<API key>(
const MCInst &MI, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm())
return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or immediates");
const MCExpr *FixupExpression = MCBinaryExpr::createAdd(
MO.getExpr(), MCConstantExpr::create(-4, Ctx), Ctx);
Fixups.push_back(MCFixup::create(0, FixupExpression,
MCFixupKind(Mips::<API key>)));
return 0;
}
<API key> - Return binary encoding of the jump
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) return MO.getImm();
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
// TODO: Push fixup.
return 0;
}
<API key> - Return binary encoding of the jump
target operand. If the machine operand requires relocation,
record the relocation and return zero.
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 4.
if (MO.isImm()) return MO.getImm()>>2;
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::create(0, Expr,
MCFixupKind(Mips::fixup_Mips_26)));
return 0;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
// If the destination is an immediate, divide by 2.
if (MO.isImm()) return MO.getImm() >> 1;
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::create(0, Expr,
MCFixupKind(Mips::<API key>)));
return 0;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
// The immediate is encoded as 'immediate << 2'.
unsigned Res = getMachineOpValue(MI, MO, Fixups, STI);
assert((Res & 3) == 0);
return Res >> 2;
}
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
return 0;
}
unsigned MipsMCCodeEmitter::
getSImm3Lsa2Value(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
int Value = MO.getImm();
return Value >> 2;
}
return 0;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
unsigned Value = MO.getImm();
return Value >> 2;
}
return 0;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
unsigned Binary = (MO.getImm() >> 2) & 0x0000ffff;
return (((Binary & 0x8000) >> 7) | (Binary & 0x00ff));
}
return 0;
}
unsigned MipsMCCodeEmitter::
getExprOpValue(const MCExpr *Expr, SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
int64_t Res;
if (Expr->evaluateAsAbsolute(Res))
return Res;
MCExpr::ExprKind Kind = Expr->getKind();
if (Kind == MCExpr::Constant) {
return cast<MCConstantExpr>(Expr)->getValue();
}
if (Kind == MCExpr::Binary) {
unsigned Res = getExprOpValue(cast<MCBinaryExpr>(Expr)->getLHS(), Fixups, STI);
Res += getExprOpValue(cast<MCBinaryExpr>(Expr)->getRHS(), Fixups, STI);
return Res;
}
if (Kind == MCExpr::Target) {
const MipsMCExpr *MipsExpr = cast<MipsMCExpr>(Expr);
Mips::Fixups FixupKind = Mips::Fixups(0);
switch (MipsExpr->getKind()) {
case MipsMCExpr::MEK_None:
case MipsMCExpr::MEK_Special:
llvm_unreachable("Unhandled fixup kind!");
break;
case MipsMCExpr::MEK_DTPREL:
// MEK_DTPREL is used for marking TLS DIEExpr only
// and contains a regular sub-expression.
return getExprOpValue(MipsExpr->getSubExpr(), Fixups, STI);
case MipsMCExpr::MEK_CALL_HI16:
FixupKind = Mips::<API key>;
break;
case MipsMCExpr::MEK_CALL_LO16:
FixupKind = Mips::<API key>;
break;
case MipsMCExpr::MEK_DTPREL_HI:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::<API key>;
break;
case MipsMCExpr::MEK_DTPREL_LO:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::<API key>;
break;
case MipsMCExpr::MEK_GOTTPREL:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GOTTPREL;
break;
case MipsMCExpr::MEK_GOT:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GOT;
break;
case MipsMCExpr::MEK_GOT_CALL:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_CALL16;
break;
case MipsMCExpr::MEK_GOT_DISP:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GOT_DISP;
break;
case MipsMCExpr::MEK_GOT_HI16:
FixupKind = Mips::fixup_Mips_GOT_HI16;
break;
case MipsMCExpr::MEK_GOT_LO16:
FixupKind = Mips::fixup_Mips_GOT_LO16;
break;
case MipsMCExpr::MEK_GOT_PAGE:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GOT_PAGE;
break;
case MipsMCExpr::MEK_GOT_OFST:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GOT_OFST;
break;
case MipsMCExpr::MEK_GPREL:
FixupKind = Mips::fixup_Mips_GPREL16;
break;
case MipsMCExpr::MEK_LO:
// Check for %lo(%neg(%gp_rel(X)))
if (MipsExpr->isGpOff())
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GPOFF_LO;
else
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_LO16;
break;
case MipsMCExpr::MEK_HIGHEST:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_HIGHEST;
break;
case MipsMCExpr::MEK_HIGHER:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_HIGHER;
break;
case MipsMCExpr::MEK_HI:
// Check for %hi(%neg(%gp_rel(X)))
if (MipsExpr->isGpOff())
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_GPOFF_HI;
else
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_HI16;
break;
case MipsMCExpr::MEK_PCREL_HI16:
FixupKind = Mips::fixup_MIPS_PCHI16;
break;
case MipsMCExpr::MEK_PCREL_LO16:
FixupKind = Mips::fixup_MIPS_PCLO16;
break;
case MipsMCExpr::MEK_TLSGD:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_TLSGD;
break;
case MipsMCExpr::MEK_TLSLDM:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_TLSLDM;
break;
case MipsMCExpr::MEK_TPREL_HI:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_TPREL_HI;
break;
case MipsMCExpr::MEK_TPREL_LO:
FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_Mips_TPREL_LO;
break;
case MipsMCExpr::MEK_NEG:
FixupKind =
isMicroMips(STI) ? Mips::fixup_MICROMIPS_SUB : Mips::fixup_Mips_SUB;
break;
}
Fixups.push_back(MCFixup::create(0, MipsExpr, MCFixupKind(FixupKind)));
return 0;
}
if (Kind == MCExpr::SymbolRef) {
Mips::Fixups FixupKind = Mips::Fixups(0);
switch(cast<MCSymbolRefExpr>(Expr)->getKind()) {
default: llvm_unreachable("Unknown fixup kind!");
break;
case MCSymbolRefExpr::VK_None:
FixupKind = Mips::fixup_Mips_32; // FIXME: This is ok for O32/N32 but not N64.
break;
} // switch
Fixups.push_back(MCFixup::create(0, Expr, MCFixupKind(FixupKind)));
return 0;
}
return 0;
}
getMachineOpValue - Return binary encoding of operand. If the machine
operand requires relocation, record the relocation and return zero.
unsigned MipsMCCodeEmitter::
getMachineOpValue(const MCInst &MI, const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
if (MO.isReg()) {
unsigned Reg = MO.getReg();
unsigned RegNo = Ctx.getRegisterInfo()->getEncodingValue(Reg);
return RegNo;
} else if (MO.isImm()) {
return static_cast<unsigned>(MO.getImm());
} else if (MO.isFPImm()) {
return static_cast<unsigned>(APFloat(MO.getFPImm())
.bitcastToAPInt().getHiBits(32).getLimitedValue());
}
// MO must be an Expr.
assert(MO.isExpr());
return getExprOpValue(MO.getExpr(),Fixups, STI);
}
Return binary encoding of memory related operand.
If the offset operand requires relocation, record the relocation.
template <unsigned ShiftAmount>
unsigned MipsMCCodeEmitter::getMemEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo),Fixups, STI) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI);
// Apply the scale factor if there is one.
OffBits >>= ShiftAmount;
return (OffBits & 0xFFFF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 6-4, offset is encoded in bits 3-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo),
Fixups, STI) << 4;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1),
Fixups, STI);
return (OffBits & 0xF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 6-4, offset is encoded in bits 3-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo),
Fixups, STI) << 4;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1),
Fixups, STI) >> 1;
return (OffBits & 0xF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 6-4, offset is encoded in bits 3-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo),
Fixups, STI) << 4;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1),
Fixups, STI) >> 2;
return (OffBits & 0xF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Register is encoded in bits 9-5, offset is encoded in bits 4-0.
assert(MI.getOperand(OpNo).isReg() &&
(MI.getOperand(OpNo).getReg() == Mips::SP ||
MI.getOperand(OpNo).getReg() == Mips::SP_64) &&
"Unexpected base register!");
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1),
Fixups, STI) >> 2;
return OffBits & 0x1F;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Register is encoded in bits 9-7, offset is encoded in bits 6-0.
assert(MI.getOperand(OpNo).isReg() &&
MI.getOperand(OpNo).getReg() == Mips::GP &&
"Unexpected base register!");
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1),
Fixups, STI) >> 2;
return OffBits & 0x7F;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 20-16, offset is encoded in bits 8-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups,
STI) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI);
return (OffBits & 0x1FF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 20-16, offset is encoded in bits 10-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups,
STI) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI);
return (OffBits & 0x07FF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// opNum can be invalid if instruction had reglist as operand.
// MemOperand is always last operand of instruction (base + offset).
switch (MI.getOpcode()) {
default:
break;
case Mips::SWM32_MM:
case Mips::LWM32_MM:
OpNo = MI.getNumOperands() - 2;
break;
}
// Base register is encoded in bits 20-16, offset is encoded in bits 11-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups, STI) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI);
return (OffBits & 0x0FFF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups,
STI) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI);
return (OffBits & 0xFFFF) | RegBits;
}
unsigned MipsMCCodeEmitter::
<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
// opNum can be invalid if instruction had reglist as operand
// MemOperand is always last operand of instruction (base + offset)
switch (MI.getOpcode()) {
default:
break;
case Mips::SWM16_MM:
case Mips::SWM16_MMR6:
case Mips::LWM16_MM:
case Mips::LWM16_MMR6:
OpNo = MI.getNumOperands() - 2;
break;
}
// Offset is encoded in bits 4-0.
assert(MI.getOperand(OpNo).isReg());
// Base register is always SP - thus it is not encoded.
assert(MI.getOperand(OpNo+1).isImm());
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI);
return ((OffBits >> 2) & 0x0F);
}
// FIXME: should be called getMSBEncoding
unsigned
MipsMCCodeEmitter::getSizeInsEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
assert(MI.getOperand(OpNo-1).isImm());
assert(MI.getOperand(OpNo).isImm());
unsigned Position = getMachineOpValue(MI, MI.getOperand(OpNo-1), Fixups, STI);
unsigned Size = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups, STI);
return Position + Size - 1;
}
template <unsigned Bits, int Offset>
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
assert(MI.getOperand(OpNo).isImm());
unsigned Value = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups, STI);
Value -= Offset;
return Value;
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
// The immediate is encoded as 'immediate << 2'.
unsigned Res = getMachineOpValue(MI, MO, Fixups, STI);
assert((Res & 3) == 0);
return Res >> 2;
}
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
const MCExpr *Expr = MO.getExpr();
Mips::Fixups FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_MIPS_PC19_S2;
Fixups.push_back(MCFixup::create(0, Expr, MCFixupKind(FixupKind)));
return 0;
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isImm()) {
// The immediate is encoded as 'immediate << 3'.
unsigned Res = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups, STI);
assert((Res & 7) == 0);
return Res >> 3;
}
assert(MO.isExpr() &&
"<API key> expects only expressions or an immediate");
const MCExpr *Expr = MO.getExpr();
Mips::Fixups FixupKind = isMicroMips(STI) ? Mips::<API key>
: Mips::fixup_MIPS_PC18_S3;
Fixups.push_back(MCFixup::create(0, Expr, MCFixupKind(FixupKind)));
return 0;
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
assert(MI.getOperand(OpNo).isImm());
const MCOperand &MO = MI.getOperand(OpNo);
return MO.getImm() % 8;
}
unsigned
MipsMCCodeEmitter::getUImm4AndValue(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
assert(MI.getOperand(OpNo).isImm());
const MCOperand &MO = MI.getOperand(OpNo);
unsigned Value = MO.getImm();
switch (Value) {
case 128: return 0x0;
case 1: return 0x1;
case 2: return 0x2;
case 3: return 0x3;
case 4: return 0x4;
case 7: return 0x5;
case 8: return 0x6;
case 15: return 0x7;
case 16: return 0x8;
case 31: return 0x9;
case 32: return 0xa;
case 63: return 0xb;
case 64: return 0xc;
case 255: return 0xd;
case 32768: return 0xe;
case 65535: return 0xf;
}
llvm_unreachable("Unexpected value");
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
unsigned res = 0;
// Register list operand is always first operand of instruction and it is
// placed before memory operand (register + imm).
for (unsigned I = OpNo, E = MI.getNumOperands() - 2; I < E; ++I) {
unsigned Reg = MI.getOperand(I).getReg();
unsigned RegNo = Ctx.getRegisterInfo()->getEncodingValue(Reg);
if (RegNo != 31)
res++;
else
res |= 0x10;
}
return res;
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
return (MI.getNumOperands() - 4);
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
unsigned res = 0;
if (MI.getOperand(0).getReg() == Mips::A1 &&
MI.getOperand(1).getReg() == Mips::A2)
res = 0;
else if (MI.getOperand(0).getReg() == Mips::A1 &&
MI.getOperand(1).getReg() == Mips::A3)
res = 1;
else if (MI.getOperand(0).getReg() == Mips::A2 &&
MI.getOperand(1).getReg() == Mips::A3)
res = 2;
else if (MI.getOperand(0).getReg() == Mips::A0 &&
MI.getOperand(1).getReg() == Mips::S5)
res = 3;
else if (MI.getOperand(0).getReg() == Mips::A0 &&
MI.getOperand(1).getReg() == Mips::S6)
res = 4;
else if (MI.getOperand(0).getReg() == Mips::A0 &&
MI.getOperand(1).getReg() == Mips::A1)
res = 5;
else if (MI.getOperand(0).getReg() == Mips::A0 &&
MI.getOperand(1).getReg() == Mips::A2)
res = 6;
else if (MI.getOperand(0).getReg() == Mips::A0 &&
MI.getOperand(1).getReg() == Mips::A3)
res = 7;
return res;
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
assert(((OpNo == 2) || (OpNo == 3)) &&
"Unexpected OpNo for movep operand encoding!");
MCOperand Op = MI.getOperand(OpNo);
assert(Op.isReg() && "Operand of movep is not a register!");
switch (Op.getReg()) {
default:
llvm_unreachable("Unknown register for movep!");
case Mips::ZERO: return 0;
case Mips::S1: return 1;
case Mips::V0: return 2;
case Mips::V1: return 3;
case Mips::S0: return 4;
case Mips::S2: return 5;
case Mips::S3: return 6;
case Mips::S4: return 7;
}
}
unsigned
MipsMCCodeEmitter::<API key>(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
assert(MO.isImm() && "<API key> expects only an immediate");
// The immediate is encoded as 'immediate >> 2'.
unsigned Res = static_cast<unsigned>(MO.getImm());
assert((Res & 3) == 0);
return Res >> 2;
}
#include "<API key>.inc" |
package volumemanager_test
import (
"bytes"
"fmt"
"math"
"os"
"os/exec"
"path/filepath"
"testing"
. "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-check"
gzfs "github.com/flynn/flynn/Godeps/_workspace/src/github.com/mistifyio/go-zfs"
"github.com/flynn/flynn/host/volume"
"github.com/flynn/flynn/host/volume/manager"
"github.com/flynn/flynn/host/volume/zfs"
"github.com/flynn/flynn/pkg/random"
"github.com/flynn/flynn/pkg/testutils"
)
func Test(t *testing.T) { TestingT(t) }
// note: many of these tests are not zfs specific; refactoring this when we have more concrete backends will be wise.
type PersistenceTests struct{}
var _ = Suite(&PersistenceTests{})
func (PersistenceTests) SetUpSuite(c *C) {
// Skip all tests in this suite if not running as root.
// Many zfs operations require root priviledges.
testutils.SkipIfNotRoot(c)
}
// covers basic volume persistence and named volume persistence
func (s *PersistenceTests) TestPersistence(c *C) {
idString := random.String(12)
vmanDBfilePath := fmt.Sprintf("/tmp/flynn-volumes-%s.bolt", idString)
zfsDatasetName := fmt.Sprintf("flynn-test-dataset-%s", idString)
zfsVdevFilePath := fmt.Sprintf("/tmp/flynn-test-zpool-%s.vdev", idString)
defer os.Remove(vmanDBfilePath)
defer os.Remove(zfsVdevFilePath)
defer func() {
pool, _ := gzfs.GetZpool(zfsDatasetName)
if pool != nil {
if datasets, err := pool.Datasets(); err == nil {
for _, dataset := range datasets {
dataset.Destroy(gzfs.DestroyRecursive | gzfs.DestroyForceUmount)
os.Remove(dataset.Mountpoint)
}
}
err := pool.Destroy()
c.Assert(err, IsNil)
}
}()
// new volume manager with a new backing zfs vdev file and a new boltdb
volProv, err := zfs.NewProvider(&zfs.ProviderConfig{
DatasetName: zfsDatasetName,
Make: &zfs.MakeDev{
BackingFilename: zfsVdevFilePath,
Size: int64(math.Pow(2, float64(30))),
},
})
c.Assert(err, IsNil)
// new volume manager with that shiny new backing zfs vdev file and a new boltdb
vman, err := volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) { return volProv, nil },
)
c.Assert(err, IsNil)
// make a volume
vol1, err := vman.NewVolume()
c.Assert(err, IsNil)
// assert existence of filesystems; emplace some data
f, err := os.Create(filepath.Join(vol1.Location(), "alpha"))
c.Assert(err, IsNil)
f.Close()
// close persistence
c.Assert(vman.PersistenceDBClose(), IsNil)
// hack zfs export/umounting to emulate host shutdown
err = exec.Command("zpool", "export", "-f", zfsDatasetName).Run()
c.Assert(err, IsNil)
// sanity check: assert the filesystems are gone
// note that the directories remain present after 'zpool export'
_, err = os.Stat(filepath.Join(vol1.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
// restore
vman, err = volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) {
c.Fatal("default provider setup should not be called if the previous provider was restored")
return nil, nil
},
)
c.Assert(err, IsNil)
// assert volumes
restoredVolumes := vman.Volumes()
c.Assert(restoredVolumes, HasLen, 2)
c.Assert(restoredVolumes[vol1.Info().ID], NotNil)
// switch to the new volume references; do a bunch of smell checks on those
vol1restored := restoredVolumes[vol1.Info().ID]
c.Assert(vol1restored.Info(), DeepEquals, vol1.Info())
c.Assert(vol1restored.Provider(), NotNil)
// assert existences of filesystems and previous data
c.Assert(vol1restored.Location(), testutils.DirContains, []string{"alpha"})
}
// covers deletion persistence for a (named) volume
func (s *PersistenceTests) TestVolumeDeletion(c *C) {
idString := random.String(12)
vmanDBfilePath := fmt.Sprintf("/tmp/flynn-volumes-%s.bolt", idString)
zfsDatasetName := fmt.Sprintf("flynn-test-dataset-%s", idString)
zfsVdevFilePath := fmt.Sprintf("/tmp/flynn-test-zpool-%s.vdev", idString)
defer os.Remove(vmanDBfilePath)
defer os.Remove(zfsVdevFilePath)
defer func() {
pool, _ := gzfs.GetZpool(zfsDatasetName)
if pool != nil {
if datasets, err := pool.Datasets(); err == nil {
for _, dataset := range datasets {
dataset.Destroy(gzfs.DestroyRecursive | gzfs.DestroyForceUmount)
os.Remove(dataset.Mountpoint)
}
}
err := pool.Destroy()
c.Assert(err, IsNil)
}
}()
// new volume provider with a new backing zfs vdev file
volProv, err := zfs.NewProvider(&zfs.ProviderConfig{
DatasetName: zfsDatasetName,
Make: &zfs.MakeDev{
BackingFilename: zfsVdevFilePath,
Size: int64(math.Pow(2, float64(30))),
},
})
c.Assert(err, IsNil)
// new volume manager with that shiny new backing zfs vdev file and a new boltdb
vman, err := volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) { return volProv, nil },
)
c.Assert(err, IsNil)
// make a named volume
vol, err := vman.NewVolume()
c.Assert(err, IsNil)
// assert existence of filesystems; emplace some data
f, err := os.Create(filepath.Join(vol.Location(), "alpha"))
c.Assert(err, IsNil)
f.Close()
// delete the volume again
err = vman.DestroyVolume(vol.Info().ID)
c.Assert(err, IsNil)
// close persistence
c.Assert(vman.PersistenceDBClose(), IsNil)
// hack zfs export/umounting to emulate host shutdown
err = exec.Command("zpool", "export", "-f", zfsDatasetName).Run()
c.Assert(err, IsNil)
// sanity check: assert the filesystems are gone
// note that the directories remain present after 'zpool export'
_, err = os.Stat(filepath.Join(vol.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
// restore
vman, err = volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) {
c.Fatal("default provider setup should not be called if the previous provider was restored")
return nil, nil
},
)
c.Assert(err, IsNil)
// assert volumes gone
restoredVolumes := vman.Volumes()
c.Assert(restoredVolumes, HasLen, 0)
// assert volume mount locations are gone
_, err = os.Stat(vol.Location())
c.Assert(os.IsNotExist(err), Equals, true)
}
func (s *PersistenceTests) <API key>(c *C) {
idString := random.String(12)
vmanDBfilePath := fmt.Sprintf("/tmp/flynn-volumes-%s.bolt", idString)
zfsDatasetName := fmt.Sprintf("flynn-test-dataset-%s", idString)
zfsVdevFilePath := fmt.Sprintf("/tmp/flynn-test-zpool-%s.vdev", idString)
defer os.Remove(vmanDBfilePath)
defer os.Remove(zfsVdevFilePath)
defer func() {
pool, _ := gzfs.GetZpool(zfsDatasetName)
if pool != nil {
if datasets, err := pool.Datasets(); err == nil {
for _, dataset := range datasets {
dataset.Destroy(gzfs.DestroyRecursive | gzfs.DestroyForceUmount)
os.Remove(dataset.Mountpoint)
}
}
err := pool.Destroy()
c.Assert(err, IsNil)
}
}()
// new volume provider with a new backing zfs vdev file
volProv, err := zfs.NewProvider(&zfs.ProviderConfig{
DatasetName: zfsDatasetName,
Make: &zfs.MakeDev{
BackingFilename: zfsVdevFilePath,
Size: int64(math.Pow(2, float64(30))),
},
})
c.Assert(err, IsNil)
// new volume manager with that shiny new backing zfs vdev file and a new boltdb
vman, err := volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) { return volProv, nil },
)
c.Assert(err, IsNil)
// make a volume
vol1, err := vman.NewVolume()
c.Assert(err, IsNil)
// assert existence of filesystems; emplace some data
f, err := os.Create(filepath.Join(vol1.Location(), "alpha"))
c.Assert(err, IsNil)
f.Close()
// snapshot it
snap, err := vman.CreateSnapshot(vol1.Info().ID)
// close persistence
c.Assert(vman.PersistenceDBClose(), IsNil)
// hack zfs export/umounting to emulate host shutdown
err = exec.Command("zpool", "export", "-f", zfsDatasetName).Run()
c.Assert(err, IsNil)
// sanity check: assert the filesystems are gone
// note that the directories remain present after 'zpool export'
_, err = os.Stat(filepath.Join(vol1.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
_, err = os.Stat(filepath.Join(snap.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
// restore
vman, err = volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) {
c.Fatal("default provider setup should not be called if the previous provider was restored")
return nil, nil
},
)
c.Assert(err, IsNil)
// assert volumes
restoredVolumes := vman.Volumes()
c.Assert(restoredVolumes, HasLen, 2)
c.Assert(restoredVolumes[vol1.Info().ID], NotNil)
c.Assert(restoredVolumes[snap.Info().ID], NotNil)
// switch to the new volume references; do a bunch of smell checks on those
vol1restored := restoredVolumes[vol1.Info().ID]
snapRestored := restoredVolumes[snap.Info().ID]
c.Assert(vol1restored.Info(), DeepEquals, vol1.Info())
c.Assert(snapRestored.Info(), DeepEquals, snap.Info())
c.Assert(vol1restored.Provider(), NotNil)
c.Assert(vol1restored.Provider(), Equals, snapRestored.Provider())
// assert existences of filesystems and previous data
c.Assert(vol1restored.Location(), testutils.DirContains, []string{"alpha"})
c.Assert(snapRestored.Location(), testutils.DirContains, []string{"alpha"})
}
func (s *PersistenceTests) <API key>(c *C) {
idString := random.String(12)
vmanDBfilePath := fmt.Sprintf("/tmp/flynn-volumes-%s.bolt", idString)
zfsDatasetName := fmt.Sprintf("flynn-test-dataset-%s", idString)
zfsVdevFilePath := fmt.Sprintf("/tmp/flynn-test-zpool-%s.vdev", idString)
defer os.Remove(vmanDBfilePath)
defer os.Remove(zfsVdevFilePath)
defer func() {
pool, _ := gzfs.GetZpool(zfsDatasetName)
if pool != nil {
if datasets, err := pool.Datasets(); err == nil {
for _, dataset := range datasets {
dataset.Destroy(gzfs.DestroyRecursive | gzfs.DestroyForceUmount)
os.Remove(dataset.Mountpoint)
}
}
err := pool.Destroy()
c.Assert(err, IsNil)
}
}()
// new volume provider with a new backing zfs vdev file
volProv, err := zfs.NewProvider(&zfs.ProviderConfig{
DatasetName: zfsDatasetName,
Make: &zfs.MakeDev{
BackingFilename: zfsVdevFilePath,
Size: int64(math.Pow(2, float64(30))),
},
})
c.Assert(err, IsNil)
// new volume manager with that shiny new backing zfs vdev file and a new boltdb
vman, err := volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) { return volProv, nil },
)
c.Assert(err, IsNil)
// make a volume
vol1, err := vman.NewVolume()
c.Assert(err, IsNil)
// assert existence of filesystems; emplace some data
f, err := os.Create(filepath.Join(vol1.Location(), "alpha"))
c.Assert(err, IsNil)
f.Close()
// make a snapshot, make a new volume to receive it, and do the transmit
snap, err := vman.CreateSnapshot(vol1.Info().ID)
vol2, err := vman.NewVolume()
c.Assert(err, IsNil)
var buf bytes.Buffer
haves, err := vman.ListHaves(vol2.Info().ID)
c.Assert(err, IsNil)
err = vman.SendSnapshot(snap.Info().ID, haves, &buf)
c.Assert(err, IsNil)
snapTransmitted, err := vman.ReceiveSnapshot(vol2.Info().ID, &buf)
// sanity check: snapshot transmission worked
c.Assert(vol2.Location(), testutils.DirContains, []string{"alpha"})
c.Assert(snapTransmitted.Location(), testutils.DirContains, []string{"alpha"})
// close persistence
c.Assert(vman.PersistenceDBClose(), IsNil)
// hack zfs export/umounting to emulate host shutdown
err = exec.Command("zpool", "export", "-f", zfsDatasetName).Run()
c.Assert(err, IsNil)
// sanity check: assert the filesystems are gone
// note that the directories remain present after 'zpool export'
_, err = os.Stat(filepath.Join(snap.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
_, err = os.Stat(filepath.Join(snapTransmitted.Location(), "alpha"))
c.Assert(os.IsNotExist(err), Equals, true)
// restore
vman, err = volumemanager.New(
vmanDBfilePath,
func() (volume.Provider, error) {
c.Fatal("default provider setup should not be called if the previous provider was restored")
return nil, nil
},
)
c.Assert(err, IsNil)
// assert volumes
restoredVolumes := vman.Volumes()
c.Assert(restoredVolumes, HasLen, 4)
c.Assert(restoredVolumes[vol1.Info().ID], NotNil)
c.Assert(restoredVolumes[snap.Info().ID], NotNil)
c.Assert(restoredVolumes[vol2.Info().ID], NotNil)
c.Assert(restoredVolumes[snapTransmitted.Info().ID], NotNil)
// still look like a snapshot?
snapRestored := restoredVolumes[snapTransmitted.Info().ID]
c.Assert(snapRestored.Info(), DeepEquals, snapTransmitted.Info())
c.Assert(snapRestored.IsSnapshot(), Equals, true)
// assert existences of filesystems and previous data
c.Assert(snapRestored.Location(), testutils.DirContains, []string{"alpha"})
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.