answer stringlengths 15 1.25M |
|---|
package org.jaudiotagger.issues;
import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.audio.mp3.MPEGFrameHeader;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.id3.ID3v23Tag;
import java.io.File;
/**
* Test reading Version 2 Layer III file correctly
*/
public class Issue028Test extends AbstractTestCase
{
public void testReadV2L3Stereo()
{
File orig = new File("testdata", "test97.mp3");
if (!orig.isFile())
{
System.err.println("Unable to test file - not available");
return;
}
Exception exceptionCaught = null;
File testFile = AbstractTestCase.copyAudioToTmp("test97.mp3");
MP3AudioHeader mp3AudioHeader = null;
try
{
mp3AudioHeader = new MP3File(testFile).getMP3AudioHeader();
}
catch (Exception e)
{
exceptionCaught = e;
}
assertNull(exceptionCaught);
assertEquals("22050", mp3AudioHeader.getSampleRate());
assertEquals("04:03", mp3AudioHeader.<API key>());
assertFalse(mp3AudioHeader.isVariableBitRate());
assertEquals(MPEGFrameHeader.mpegVersionMap.get(new Integer(MPEGFrameHeader.VERSION_2)), mp3AudioHeader.getMpegVersion());
assertEquals(MPEGFrameHeader.mpegLayerMap.get(new Integer(MPEGFrameHeader.LAYER_III)), mp3AudioHeader.getMpegLayer());
assertEquals(MPEGFrameHeader.modeMap.get(new Integer(MPEGFrameHeader.MODE_JOINT_STEREO)), mp3AudioHeader.getChannels());
assertFalse(mp3AudioHeader.isOriginal());
assertFalse(mp3AudioHeader.isCopyrighted());
assertFalse(mp3AudioHeader.isPrivate());
assertFalse(mp3AudioHeader.isProtected());
assertEquals("32", mp3AudioHeader.getBitRate());
assertEquals("mp3", mp3AudioHeader.getEncodingType());
}
} |
// application.cc
// 11/18/2011
#include "application.h"
#include "global.h"
#ifdef Q_OS_WIN
# include "win/qtwin/qtwin.h"
#endif // Q_OS_WIN
#ifdef Q_OS_MAC
# include "mac/qtmac/qtmac.h"
#endif // Q_OS_MAC
#include "src/common/acpaths.h"
#include <QtCore/QDir>
#define DEBUG "application"
#include "qtx/qxdebug.h"
// - Constructions -
Application::Application(int &argc, char **argv)
: Base(argc, argv, true)
{
DOUT("enter");
<API key>(G_DOMAIN);
setOrganizationName(G_ORGANIZATION);
setApplicationName(G_APPLICATION);
<API key>(G_VERSION);
setLogFileName(G_PATH_DEBUG);
#ifdef Q_OS_LINUX
setLockFileName(G_PATH_LOCK_RUNNING);
#endif // Q_OS_LINUX
createDirectories();
//<API key>();
DOUT("exit");
}
Application::~Application()
{
DOUT("enter");
DOUT("exit");
}
void
Application::createDirectories()
{
QDir d(AC_PATH_CACHES);
if (!d.exists())
d.mkpath(d.absolutePath());
d = QDir(G_PATH_PROFILE);
if (!d.exists())
d.mkpath(d.absolutePath());
d = QDir(G_PATH_LOGS);
if (!d.exists())
d.mkpath(d.absolutePath());
#ifdef Q_OS_LINUX
d = QDir(G_PATH_LOCK);
if (!d.exists())
d.mkpath(d.absolutePath());
#endif // Q_OS_LINUX
}
// EOF |
<?php
/**
* @defgroup <API key> File Upload Wizard
* The file upload wizard implements the 3-step wizard used to manage
* uploads of submission files.
*/
// Import the base handler.
import('lib.pkp.controllers.wizard.fileUpload.<API key>');
class <API key> extends <API key> {
/**
* Constructor
*/
function __construct() {
parent::__construct();
}
// Implement template methods from PKPHandler
function authorize($request, &$args, $roleAssignments) {
// This is validated in parent's authorization policy.
$stageId = (int)$request->getUserVar('stageId');
// Authorize review round id when this handler is used in review stages.
import('lib.pkp.classes.submission.SubmissionFile');
if ($stageId == <API key> && $request->getUserVar('fileStage') != <API key>) {
import('lib.pkp.classes.security.authorization.internal.<API key>');
$this->addPolicy(new <API key>($request, $args));
}
// We validate file stage outside a policy because
// we don't need to validate in another places.
$fileStage = $request->getUserVar('fileStage');
if ($fileStage) {
$submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO');
$fileStages = $submissionFileDao->getAllFileStages();
if (!in_array($fileStage, $fileStages)) {
return false;
}
}
// Validate file ids. We have two cases where we might have a file id.
// CASE 1: user is uploading a revision to a file, the revised file id
// will need validation.
$revisedFileId = (int)$request->getUserVar('revisedFileId');
// CASE 2: user already have uploaded a file (and it's editing the metadata),
// we will need to validate the uploaded file id.
$fileId = (int)$request->getUserVar('fileId');
// Get the right one to validate.
$fileIdToValidate = null;
if ($revisedFileId && !$fileId) {
$fileIdToValidate = $revisedFileId;
} else if ($fileId && !$revisedFileId) {
$fileIdToValidate = $fileId;
} else if ($revisedFileId && $fileId) {
// Those two cases will not happen at the same time.
return false;
}
if ($fileIdToValidate) {
import('lib.pkp.classes.security.authorization.<API key>');
$this->addPolicy(new <API key>($request, $args, $roleAssignments, <API key>, $fileIdToValidate));
}
return parent::authorize($request, $args, $roleAssignments);
}
/**
* @copydoc <API key>::_attachEntities
*/
protected function _attachEntities($submissionFile) {
parent::_attachEntities($submissionFile);
switch ($submissionFile->getFileStage()) {
case <API key>:
$galleyDao = DAORegistry::getDAO('ArticleGalleyDAO');
assert($submissionFile->getAssocType() == <API key>);
$galley = $galleyDao->getById($submissionFile->getAssocId(), $submissionFile->getSubmissionId());
if ($galley) {
$galley->setFileId($submissionFile->getFileId());
$galleyDao->updateObject($galley);
}
break;
}
}
}
?> |
#pragma once
#include "AP_RCProtocol.h"
#include "SoftSerial.h"
#define <API key> 8000U /* Minumum space between srxl frames in us (applies to all variants) */
#define SRXL_MAX_CHANNELS 20U /* Maximum number of channels from srxl datastream */
/* Variant specific SRXL datastream characteristics */
/* Framelength in byte */
#define SRXL_FRAMELEN_V1 27U /* Framelength with header in byte for: Mpx SRXLv1 or XBUS Mode B */
#define SRXL_FRAMELEN_V2 35U /* Framelength with header in byte for: Mpx SRXLv2 */
#define SRXL_FRAMELEN_V5 18U /* Framelength with header in byte for Spk AR7700 etc. */
#define SRXL_FRAMELEN_MAX 35U /* maximum possible framelengh */
/* Headerbyte */
#define SRXL_HEADER_V1 0xA1U /* Headerbyte for: Mpx SRXLv1 or XBUS Mode B */
#define SRXL_HEADER_V2 0xA2U /* Headerbyte for: Mpx SRXLv2 */
#define SRXL_HEADER_V5 0xA5U /* Headerbyte for: Spk AR7700 etc. */
#define <API key> 0xFFU /* Headerbyte for non impemented srxl header*/
class AP_RCProtocol_SRXL : public <API key> {
public:
AP_RCProtocol_SRXL(AP_RCProtocol &_frontend) : <API key>(_frontend) {}
void process_pulse(uint32_t width_s0, uint32_t width_s1) override;
void process_byte(uint8_t byte, uint32_t baudrate) override;
private:
void _process_byte(uint32_t timestamp_us, uint8_t byte);
static uint16_t srxl_crc16(uint16_t crc, uint8_t new_byte);
int <API key>(uint16_t max_values, uint8_t *num_values, uint16_t *values, bool *failsafe_state);
int <API key>(uint16_t max_values, uint8_t *num_values, uint16_t *values, bool *failsafe_state);
uint8_t buffer[SRXL_FRAMELEN_MAX]; /* buffer for raw srxl frame data in correct order --> buffer[0]=byte0 buffer[1]=byte1 */
uint8_t buflen; /* length in number of bytes of received srxl dataframe in buffer */
uint32_t last_data_us; /* timespan since last received data in us */
uint16_t channels[SRXL_MAX_CHANNELS] = {0}; /* buffer for extracted RC channel data as pulsewidth in microseconds */
uint16_t max_channels = 0;
enum {
STATE_IDLE, /* do nothing */
STATE_NEW, /* get header of frame + prepare for frame reception + begin new crc cycle */
STATE_COLLECT /* collect RC channel data from frame + concurrently calc crc over payload data + extract channel information */
};
uint8_t frame_header = 0U; /* Frame header from SRXL datastream */
uint8_t frame_len_full = 0U; /* Length in number of bytes of full srxl datastream */
uint8_t decode_state = STATE_IDLE; /* Current state of SRXL frame decoding */
uint8_t decode_state_next = STATE_IDLE; /* State of frame decoding thatwill be applied when the next byte from dataframe drops in */
uint16_t crc_fmu = 0U; /* CRC calculated over payload from srxl datastream on this machine */
uint16_t crc_receiver = 0U; /* CRC extracted from srxl datastream */
SoftSerial ss{115200, SoftSerial::SERIAL_CONFIG_8N1};
}; |
// test028
public class A {
public void foo(boolean b) {
;;}
} |
body{font-size:12px;}
a{color: #0089FE; text-decoration: none;}
a:hover{color:#E8A02C; text-decoration: underline;}
p{ line-height:1.8em; text-indent: 2em; }
#main{width:950px; margin: 0 auto; border:0px solid #CEEBA2; background:#FFF;}
#header{padding:20px;}
#header h1{font-size:22px; text-align:left;color:#0061CA;padding-left:100px;line-height:2.4em;height:70px;background:url(../images/banner_bg.jpg) no-repeat left top;}
#header h1 span{float:right; font-size:14px; color:#FFCC00;}
#header h1 span a{color:#FFCC00;text-decoration:underline;}
#header h1 span a:hover{text-decoration:none;}
#header p {line-height:2em; margin-bottom:10px ; text-align:center; padding-left:10em;}
#nav{height:30px; margin:0;background:url(../images/header_bg.png) repeat-x 0 0;}
#nav ul{float:right;width:356px;}
#nav ul li{float:left; margin-right:20px;padding:0 4px;}
#nav ul li.first{margin:0;}
#nav ul li a{display:block; height:30px; line-height:30px;font-size:14px; color:#FFF;text-decoration:none; width: 60px; text-align: center;}
#nav ul li a:hover{color:#FFCC00;}
#contain{padding:20px;}
#contain h2{font-size:14px; line-height:2em; margin-top:10px;border-bottom: 0px solid #0094D6; color:#FF5A00;}
#flashbox{width:320px; height:200px;border:none;}
#footer{text-align:center;background:url(../images/inner-bg2.gif) repeat 0 0}
.section{margin-bottom: 10px;}
.update{margin-bottom: 10px;}
.update p{margin-top:10px;}
.update p span{float:right;padding-left: 2em;}
.expoes{background-color:#EEEEFF; border:1px solid #D9D9FF; padding: 15px;}
.expo{ padding:20px; border-bottom: 1px solid #EEE;}
.para{margin-bottom:20px;}
.box{padding:10px 30px;background:#FFFDE5;border:1px solid #F6F3D3;color:#993300;margin-bottom:20px;}
.list{padding:0 30px;}
.list li{line-height:2em;}
.source{margin:10px auto; padding:10px 20px; border: 1px dashed #FF3333; background:#F9F9F9;}
.code{margin-bottom: 20px;}
.codetit{background: #F7F6F1;border:1px solid #E9E8E3; border-bottom: none; line-height: 24px; height: 24px;padding-left: 10px;}
.insertcode ol {background: #F7F6F1;border:1px solid #E9E8E3; list-style-position:outside; padding-left: 36px;}
.insertcode ol li {background:#FFFFFF;border-left:3px solid #FF9933;color:#654322;padding-left:6px; line-height: 20px;}
.insertcode ol li div{line-height: 20px;}
.tblist{background:#FFEEFF;border-collapse:collapse;}
.tblist th, .tblist td{border:1px solid #B4C4FF; text-align:left; padding:5px 20px;}
.tblist th{color:#3366CC;}
.tblist td{}
.exmp{width:320px; height:200px; float:left;}
.exmp-txt{width:440px; height:180px; float:right; border-left:2px solid orange;padding:10px 20px;}
.compatible{margin: 0px auto; text-align: right;}
.compatible span{display: inline-block;margin-left: 10px; width: 80px; text-align: center;}
.compatible span img{}
.compatible span em{display:block; font-style: normal;}
#expo1,#expo2{border-bottom:1px solid #D9D9FF; }
#down{margin: 20px 0; padding: 6px;}
#down p{text-indent: 0px;}
#down a{display:block;background: url(../images/Down.png) no-repeat 10px 10px; height:58px ; width:150px;
padding: 5px 0 5px 60px; line-height:52px; border:1px solid #EEE; color: #0089FE; text-decoration: none;
}
#down a:hover{color:#E8A02C;} |
#! /bin/sh
# Test suite for exclude.
# This file is part of the GNUlib Library.
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
. "${srcdir=.}/init.sh"; path_prepend_ .
fail=0
# Test escaped metacharacters.
cat > in <<'EOT'
f\*e
b[a\*]r
EOT
cat > expected <<'EOT'
f*e: 1
file: 0
bar: 1
EOT
test-exclude -wildcards in -- 'f*e' 'file' 'bar' > out || exit $?
# Find out how to remove carriage returns from output. Solaris /usr/ucb/tr
# does not understand '\r'.
case $(echo r | tr -d '\r') in '') cr='\015';; *) cr='\r';; esac
# normalize output
LC_ALL=C tr -d "$cr" < out > k && mv k out
compare expected out || fail=1
Exit $fail |
package com.github.bordertech.wcomponents;
import java.io.IOException;
/**
* This escape is thrown to forward the browser to a different URL rather than rendering the UI.
*
* @author Martin Shevchenko
*/
public class ForwardException extends ActionEscape {
/**
* The URL to forward to.
*/
private final String forwardTo;
/**
* Creates a ForwardException.
*
* @param forwardTo the URL to forward to.
*/
public ForwardException(final String forwardTo) {
this.forwardTo = forwardTo;
}
/**
* @return the URL to forward to.
*/
public String getForwardTo() {
return forwardTo;
}
/**
* {@inheritDoc}
*/
@Override
public void escape() throws IOException {
getResponse().sendRedirect(getForwardTo());
}
} |
/**
* Prompt user for confirmation prior to loading a URL.
*/
function confirmAction(url, msg) {
if (confirm(msg)) {
if (url) {
document.location.href=url;
}
return true;
}
return false;
}
/**
* Open window displaying help.
*/
function openHelp(url) {
window.open(url, 'Help', 'width=700,height=600,screenX=100,screenY=100,toolbar=0,scrollbars=1');
}
/**
* Open window displaying comments.
*/
function openComments(url) {
window.open(url, 'Comments', 'width=700,height=600,screenX=100,screenY=100,toolbar=0,resizable=1,scrollbars=1');
}
/**
* Open window for preview.
*/
function openWindow(url) {
window.open(url, 'Window', 'width=600,height=550,screenX=100,screenY=100,toolbar=0,resizable=1,scrollbars=1');
}
/**
* Open window for reading tools.
*/
function openRTWindow(url) {
window.open(url, 'RT', 'width=700,height=500,screenX=100,screenY=100,toolbar=0,resizable=1,scrollbars=1');
}
function <API key>(url) {
window.open(url, 'RT', 'width=700,height=500,screenX=100,screenY=100,toolbar=1,resizable=1,scrollbars=1');
}
/**
* browser object availability detection
* @param objectId string of object needed
* @param style int (0 or 1) if style object is needed
* @return javascript object specific to current browser
*/
function getBrowserObject(objectId, style) {
var isNE4 = 0;
var currObject;
// browser object for ie5+ and ns6+
if (document.getElementById) {
currObject = document.getElementById(objectId);
// browser object for ie4+
} else if (document.all) {
currObject = document.all[objectId];
// browser object for ne4
} else if (document.layers) {
currObject = document.layers[objectId];
isNE4 = 1;
} else {
// do nothing
}
// check if style is needed
if (style && !isNE4) {
currObject = currObject.style;
}
return currObject;
}
/**
* Load a URL.
*/
function loadUrl(url) {
document.location.href=url;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
/**
* Asynchronous request functions
*/
function makeAsyncRequest(){
var req=(window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
return req;
}
function sendAsyncRequest(req, url, data, method) {
var header = 'Content-Type:text/html; Charset=utf-8';
req.open(method, url, true);
req.setRequestHeader(header.split(':')[0],header.split(':')[1]);
req.send(data);
}
/**
* Change the form action
* @param formId string
* @param action string
*/
function changeFormAction(formId, action) {
document.getElementById(formId).action = action;
document.getElementById(formId).submit();
}
/**
* Encode a URL parameter
* @param s string
*/
function urlEncode(s) {
return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}
/**
* HTML encode a string
* @param s string
*/
function escapeHTML(s) {
return $('<div/>').text(s).html();
}
/**
* HTML decode a string
* @param s string
*/
function unescapeHTML(s) {
return $('<div/>').html(s).text();
} |
package net.minecraft.client.resources;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.<API key>;
@SideOnly(Side.CLIENT)
public class <API key> extends <API key>
{
private final <API key>.Entry field_148319_c;
private static final String __OBFID = "CL_00000823";
public <API key>(<API key> p_i45053_1_, <API key>.Entry p_i45053_2_)
{
super(p_i45053_1_);
this.field_148319_c = p_i45053_2_;
}
protected void func_148313_c()
{
this.field_148319_c.bindTexturePackIcon(this.field_148317_a.getTextureManager());
}
protected String func_148311_a()
{
return this.field_148319_c.<API key>();
}
protected String func_148312_b()
{
return this.field_148319_c.getResourcePackName();
}
public <API key>.Entry func_148318_i()
{
return this.field_148319_c;
}
} |
#include <assert.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <netinet/in.h>
#include "main.h"
#include "arch/arch.h"
#include "arch/threads.h"
#include "asyncio.h"
#include "misc/queue.h"
#include "prop/prop.h"
#include "misc/minmax.h"
#if ENABLE_OPENSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include "net_openssl.h"
static void asyncio_ssl_write(asyncio_fd_t *af);
static void asyncio_ssl_read(asyncio_fd_t *af);
static int asyncio_ssl_events(asyncio_fd_t *af);
static void <API key>(asyncio_fd_t *af);
#endif
LIST_HEAD(asyncio_fd_list, asyncio_fd);
LIST_HEAD(asyncio_worker_list, asyncio_worker);
LIST_HEAD(asyncio_timer_list, asyncio_timer);
TAILQ_HEAD(<API key>, asyncio_dns_req);
TAILQ_HEAD(asyncio_task_queue, asyncio_task);
static hts_thread_t asyncio_thread_id;
static struct asyncio_timer_list asyncio_timers;
static hts_mutex_t <API key>;
static struct asyncio_worker_list asyncio_workers;
static int asyncio_pipe[2];
static struct asyncio_fd_list asyncio_fds;
static int asyncio_num_fds;
struct prop_courier *asyncio_courier;
static hts_mutex_t asyncio_dns_mutex;
static int asyncio_dns_worker;
static struct <API key> asyncio_dns_pending;
static struct <API key> <API key>;
static hts_mutex_t asyncio_task_mutex;
static struct asyncio_task_queue asyncio_tasks;
static void adr_deliver_cb(void);
static int64_t async_now;
static __inline void <API key>(void) {
assert(hts_thread_current() == asyncio_thread_id);
}
typedef struct asyncio_worker {
LIST_ENTRY(asyncio_worker) link;
void (*fn)(void);
int id;
int pending;
} asyncio_worker_t;
struct asyncio_fd {
LIST_ENTRY(asyncio_fd) af_link;
<API key> *af_callback;
void *af_opaque;
char *af_name;
union {
<API key> *af_accept_callback;
<API key> *af_udp_callback;
<API key> *af_error_callback;
};
<API key> *af_read_callback;
htsbuf_queue_t af_sendq;
htsbuf_queue_t af_recvq;
int64_t af_timeout;
int af_refcount;
int af_fd;
int af_poll_events;
int af_pending_errno;
uint16_t af_ext_events;
uint8_t af_connected;
char *af_hostname;
net_addr_t af_bind_addr;
void (*af_resume)(struct asyncio_fd *af);
int af_suspended : 1;
int af_bind_any : 1;
int af_broadcast : 1;
#if ENABLE_OPENSSL
int af_ssl_read_status;
int af_ssl_write_status;
int af_ssl_established;
SSL *af_ssl;
#endif
};
typedef struct asyncio_task {
TAILQ_ENTRY(asyncio_task) at_link;
void (*at_fn)(void *aux);
void *at_aux;
} asyncio_task_t;
int64_t
async_current_time(void)
{
return async_now;
}
static void
no_sigpipe(int fd)
{
#ifdef SO_NOSIGPIPE
int val = 1;
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val));
#endif
}
static void
<API key>(net_addr_t *na, const struct sockaddr_in *sin)
{
na->na_family = 4;
na->na_port = ntohs(sin->sin_port);
memcpy(na->na_addr, &sin->sin_addr, 4);
}
static void
<API key>(net_addr_t *na, int fd)
{
socklen_t slen = sizeof(struct sockaddr_in);
struct sockaddr_in self;
if(!getsockname(fd, (struct sockaddr *)&self, &slen)) {
<API key>(na, &self);
} else {
memset(na, 0, sizeof(net_addr_t));
}
}
static void
<API key>(net_addr_t *na, int fd)
{
socklen_t slen = sizeof(struct sockaddr_in);
struct sockaddr_in self;
if(!getpeername(fd, (struct sockaddr *)&self, &slen)) {
<API key>(na, &self);
} else {
memset(na, 0, sizeof(net_addr_t));
}
}
static void
asyncio_wakeup(int id)
{
char x = id;
int r = write(asyncio_pipe[1], &x, 1);
if(r != 1)
TRACE(TRACE_ERROR, "TCP", "Pipe problems r=%d errno=%d", r, errno);
}
static void
<API key>(void *opaque)
{
asyncio_wakeup(0);
}
void
<API key>(int id)
{
return asyncio_wakeup(id);
}
void
asyncio_timer_init(asyncio_timer_t *at, void (*fn)(void *opaque),
void *opaque)
{
at->at_fn = fn;
at->at_opaque = opaque;
at->at_expire = 0;
}
static int
at_compar(const asyncio_timer_t *a, const asyncio_timer_t *b)
{
if(a->at_expire < b->at_expire)
return -1;
return 1;
}
void
asyncio_timer_arm(asyncio_timer_t *at, int64_t expire)
{
<API key>();
if(at->at_expire)
LIST_REMOVE(at, at_link);
at->at_expire = expire;
LIST_INSERT_SORTED(&asyncio_timers, at, at_link, at_compar, asyncio_timer_t);
}
void
<API key>(asyncio_timer_t *at, int delta)
{
asyncio_timer_arm(at, async_now + delta * 1000000LL);
}
void
<API key>(asyncio_timer_t *at)
{
<API key>();
if(at->at_expire) {
LIST_REMOVE(at, at_link);
at->at_expire = 0;
}
}
static void
af_release(asyncio_fd_t *af)
{
<API key>();
af->af_refcount
if(af->af_refcount > 0)
return;
htsbuf_queue_flush(&af->af_recvq);
htsbuf_queue_flush(&af->af_sendq);
free(af->af_name);
free(af->af_hostname);
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
SSL_shutdown(af->af_ssl);
SSL_free(af->af_ssl);
}
#endif
free(af);
}
static int
events_to_poll(int events)
{
return
(events & ASYNCIO_READ ? POLLIN : 0) |
(events & ASYNCIO_WRITE ? POLLOUT : 0) |
(events & ASYNCIO_ERROR ? (POLLHUP|POLLERR) : 0);
}
static void
asyncio_dopoll(void)
{
asyncio_timer_t *at;
while((at = LIST_FIRST(&asyncio_timers)) != NULL &&
at->at_expire <= async_now) {
LIST_REMOVE(at, at_link);
at->at_expire = 0;
at->at_fn(at->at_opaque);
}
asyncio_fd_t *af;
struct pollfd *fds = alloca(asyncio_num_fds * sizeof(struct pollfd));
asyncio_fd_t **afds = alloca(asyncio_num_fds * sizeof(asyncio_fd_t *));
int n = 0;
int timeout = INT32_MAX;
LIST_FOREACH(af, &asyncio_fds, af_link) {
if(af->af_pending_errno) {
af->af_callback(af, af->af_opaque, ASYNCIO_ERROR, af->af_pending_errno);
goto release;
}
if(af->af_timeout) {
if(af->af_timeout <= async_now) {
af->af_timeout = 0;
af->af_callback(af, af->af_opaque, ASYNCIO_TIMEOUT, 0);
goto release;
}
timeout = MIN(timeout, (af->af_timeout - async_now + 999) / 1000);
}
if(af->af_fd == -1) {
continue;
}
fds[n].fd = af->af_fd;
#if ENABLE_OPENSSL
if(af->af_ssl != NULL)
fds[n].events = asyncio_ssl_events(af);
else
#endif
fds[n].events = af->af_poll_events;
fds[n].revents = 0;
afds[n] = af;
af->af_refcount++;
n++;
}
if((at = LIST_FIRST(&asyncio_timers)) != NULL)
timeout = MIN(timeout, (at->at_expire - async_now + 999) / 1000);
if(timeout == INT32_MAX)
timeout = -1;
int err = poll(fds, n, timeout);
async_now = arch_get_ts();
for(int i = 0; i < n; i++) {
af = afds[i];
if(af->af_callback == NULL)
continue;
if(fds[i].revents & POLLHUP) {
af->af_callback(af, af->af_opaque, ASYNCIO_ERROR, ECONNRESET);
continue;
}
if(fds[i].revents & POLLERR || err < 0) {
int err;
socklen_t errlen = sizeof(int);
if(getsockopt(af->af_fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen)) {
TRACE(TRACE_ERROR, "ASYNCIO", "getsockopt failed for %s 0x%x
af->af_name, af->af_fd, strerror(errno));
af->af_callback(af, af->af_opaque, ASYNCIO_ERROR, ENOBUFS);
} else {
if(err) {
af->af_callback(af, af->af_opaque, ASYNCIO_ERROR, err);
continue;
}
}
}
const int events =
(fds[i].revents & POLLIN ? ASYNCIO_READ : 0) |
(fds[i].revents & POLLOUT ? ASYNCIO_WRITE : 0);
if(events)
af->af_callback(af, af->af_opaque, events, 0);
if(0) {
int64_t now = arch_get_ts();
if(now - async_now > 10000) {
TRACE(TRACE_ERROR, "ASYNCIO", "Long callback on socktet %s (%d µs)",
af->af_name, (int) (now - async_now));
}
async_now = now;
}
}
release:
for(int i = 0; i < n; i++)
af_release(afds[i]);
}
static void
asyncio_set_events(asyncio_fd_t *af, int events)
{
<API key>();
af->af_ext_events = events;
af->af_poll_events = events_to_poll(events);
}
static void
asyncio_add_events(asyncio_fd_t *af, int events)
{
asyncio_set_events(af, af->af_ext_events | events);
}
static void
asyncio_rem_events(asyncio_fd_t *af, int events)
{
asyncio_set_events(af, af->af_ext_events & ~events);
}
asyncio_fd_t *
asyncio_add_fd(int fd, int events, <API key> *cb, void *opaque,
const char *name)
{
<API key>();
asyncio_fd_t *af = calloc(1, sizeof(asyncio_fd_t));
htsbuf_queue_init(&af->af_recvq, INT32_MAX);
htsbuf_queue_init(&af->af_sendq, INT32_MAX);
af->af_refcount = 1;
af->af_fd = fd;
af->af_name = strdup(name);
asyncio_set_events(af, events);
af->af_callback = cb;
af->af_opaque = opaque;
<API key>(fd, 1);
LIST_INSERT_HEAD(&asyncio_fds, af, af_link);
asyncio_num_fds++;
return af;
}
void
asyncio_del_fd(asyncio_fd_t *af)
{
<API key>();
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
SSL_shutdown(af->af_ssl);
SSL_free(af->af_ssl);
af->af_ssl = NULL;
}
#endif
if(af->af_fd != -1)
close(af->af_fd);
af->af_fd = -1;
LIST_REMOVE(af, af_link);
asyncio_num_fds
af->af_callback = NULL;
af_release(af);
}
void
<API key>(asyncio_fd_t *af, int delta)
{
af->af_timeout = delta * 1000000LL + async_now;
}
static int
asyncio_handle_pipe(asyncio_fd_t *af, void *opaque, int event, int error)
{
char x;
if(read(asyncio_pipe[0], &x, 1) != 1)
return 0;
if(x == 0) {
prop_courier_poll(opaque);
return 0;
}
if(x == 1) {
struct asyncio_task_queue atq;
asyncio_task_t *at, *next;
hts_mutex_lock(&asyncio_task_mutex);
TAILQ_MOVE(&atq, &asyncio_tasks, at_link);
TAILQ_INIT(&asyncio_tasks);
hts_mutex_unlock(&asyncio_task_mutex);
for(at = TAILQ_FIRST(&atq); at != NULL; at = next) {
next = TAILQ_NEXT(at, at_link);
at->at_fn(at->at_aux);
free(at);
}
return 0;
}
asyncio_worker_t *aw;
hts_mutex_lock(&<API key>);
LIST_FOREACH(aw, &asyncio_workers, link)
if(aw->id == x)
break;
hts_mutex_unlock(&<API key>);
if(aw != NULL)
aw->fn();
return 0;
}
int
asyncio_add_worker(void (*fn)(void))
{
asyncio_worker_t *aw = calloc(1, sizeof(asyncio_worker_t));
aw->fn = fn;
static int generator = 1;
hts_mutex_lock(&<API key>);
generator++;
aw->id = generator;
LIST_INSERT_HEAD(&asyncio_workers, aw, link);
hts_mutex_unlock(&<API key>);
return aw->id;
}
static void *
asyncio_thread(void *aux)
{
asyncio_thread_id = hts_thread_current();
asyncio_courier = <API key>(<API key>, NULL);
asyncio_add_fd(asyncio_pipe[0], ASYNCIO_READ, asyncio_handle_pipe,
asyncio_courier, "Pipe");
async_now = arch_get_ts();
init_group(INIT_GROUP_ASYNCIO);
<API key>();
while(1)
asyncio_dopoll();
return NULL;
}
static void
asyncio_do_shutdown(void *aux)
{
fini_group(INIT_GROUP_ASYNCIO);
}
static void
asyncio_shutdown(void *opaque, int retcode)
{
TRACE(TRACE_DEBUG, "ASYNCIO", "Shutdown");
asyncio_run_task(asyncio_do_shutdown, NULL);
}
void
asyncio_init_early(void)
{
TAILQ_INIT(&asyncio_tasks);
TAILQ_INIT(&asyncio_dns_pending);
TAILQ_INIT(&<API key>);
TAILQ_INIT(&asyncio_tasks);
hts_mutex_init(&<API key>);
hts_mutex_init(&asyncio_dns_mutex);
hts_mutex_init(&asyncio_task_mutex);
arch_pipe(asyncio_pipe);
asyncio_dns_worker = asyncio_add_worker(adr_deliver_cb);
}
void
asyncio_start(void)
{
<API key>("asyncio", asyncio_thread,
NULL, THREAD_PRIO_MODEL);
shutdown_hook_add(asyncio_shutdown, NULL, 1);
}
void
asyncio_run_task(void (*fn)(void *aux), void *aux)
{
asyncio_task_t *at = malloc(sizeof(asyncio_task_t));
at->at_fn = fn;
at->at_aux = aux;
hts_mutex_lock(&asyncio_task_mutex);
int do_signal = TAILQ_EMPTY(&asyncio_tasks);
TAILQ_INSERT_TAIL(&asyncio_tasks, at, at_link);
hts_mutex_unlock(&asyncio_task_mutex);
if(do_signal)
asyncio_wakeup(1);
}
static int
asyncio_tcp_accept(asyncio_fd_t *af, void *opaque, int events, int error)
{
assert(events & ASYNCIO_READ);
struct sockaddr_in si;
socklen_t sl = sizeof(struct sockaddr_in);
int fd, val;
fd = accept(af->af_fd, (struct sockaddr *)&si, &sl);
<API key>(fd, 0);
if(fd == -1) {
TRACE(TRACE_ERROR, "TCP", "%s: Accept error: %s",
af->af_name, strerror(errno));
sleep(1);
return 0;
}
val = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
#ifdef TCP_KEEPIDLE
val = 30;
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, sizeof(val));
#endif
#ifdef TCP_KEEPINVL
val = 15;
setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, sizeof(val));
#endif
#ifdef TCP_KEEPCNT
val = 5;
setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, sizeof(val));
#endif
#ifdef __PPU__
#define TCP_NODELAY 1
#endif
#ifdef TCP_NODELAY
val = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
#endif
net_addr_t local, remote;
<API key>(&local, fd);
<API key>(&remote, fd);
af->af_accept_callback(af->af_opaque, fd, &local, &remote);
return 0;
}
static int
<API key>(int bind_any, int port, const char *name)
{
struct sockaddr_in si = {0};
int one = 1;
int fd;
if((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
no_sigpipe(fd);
si.sin_family = AF_INET;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
if(port) {
si.sin_port = htons(port);
if(bind(fd, (struct sockaddr *)&si, sizeof(struct sockaddr_in))) {
if(!bind_any) {
TRACE(TRACE_ERROR, "TCP", "%s: Bind failed -- %s", name,
strerror(errno));
close(fd);
return -1;
} else {
port = 0;
}
}
}
if(!port) {
si.sin_port = 0;
if(bind(fd, (struct sockaddr *)&si, sizeof(struct sockaddr_in)) == -1) {
TRACE(TRACE_ERROR, "TCP", "%s: Unable to bind -- %s", name,
strerror(errno));
close(fd);
return -1;
}
}
listen(fd, 100);
return fd;
}
static void
asyncio_tcp_resume(asyncio_fd_t *af)
{
int fd = <API key>(af->af_bind_any, af->af_bind_addr.na_port,
af->af_name);
if(fd == -1)
return;
<API key>(fd, 1);
af->af_fd = fd;
asyncio_set_events(af, ASYNCIO_READ);
af->af_suspended = 0;
TRACE(TRACE_INFO, "TCP", "%s: Resumed listening on port %d", af->af_name, asyncio_get_port(af));
}
asyncio_fd_t *
asyncio_listen(const char *name, int port, <API key> *cb,
void *opaque, int bind_any)
{
int fd = <API key>(bind_any, port, name);
if(fd == -1)
return NULL;
asyncio_fd_t *af = asyncio_add_fd(fd, ASYNCIO_READ,
asyncio_tcp_accept, opaque, name);
af->af_bind_any = bind_any;
af->af_bind_addr.na_port = port;
TRACE(TRACE_INFO, "TCP", "%s: Listening on port %d", name, asyncio_get_port(af));
af->af_accept_callback = cb;
af->af_resume = asyncio_tcp_resume;
return af;
}
static void
do_write(asyncio_fd_t *af)
{
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
asyncio_ssl_write(af);
return;
}
#endif
char tmp[1024];
while(1) {
int avail = htsbuf_peek(&af->af_sendq, tmp, sizeof(tmp));
if(avail == 0) {
// Nothing more to send
asyncio_rem_events(af, ASYNCIO_WRITE);
return;
}
#ifdef MSG_NOSIGNAL
int r = send(af->af_fd, tmp, avail, MSG_NOSIGNAL);
#else
int r = send(af->af_fd, tmp, avail, 0);
#endif
if(r == 0)
break;
if(r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS))
break;
if(r == -1) {
asyncio_rem_events(af, ASYNCIO_WRITE);
af->af_pending_errno = errno;
return;
}
htsbuf_drop(&af->af_sendq, r);
if(r != avail)
break;
}
asyncio_add_events(af, ASYNCIO_WRITE);
}
static void
do_read(asyncio_fd_t *af)
{
char tmp[1024];
while(1) {
int r = read(af->af_fd, tmp, sizeof(tmp));
if(r == 0) {
af->af_error_callback(af->af_opaque, "Connection reset");
return;
}
if(r == -1 && (errno == EAGAIN))
break;
if(r == -1) {
char buf[256];
snprintf(buf, sizeof(buf), "%s", strerror(errno));
af->af_error_callback(af->af_opaque, buf);
return;
}
htsbuf_append(&af->af_recvq, tmp, r);
}
af->af_read_callback(af->af_opaque, &af->af_recvq);
}
static int
<API key>(asyncio_fd_t *af, void *opaque, int events, int error)
{
if(events & ASYNCIO_TIMEOUT) {
af->af_error_callback(af->af_opaque, "Connection timed out");
return 0;
}
if(events & ASYNCIO_ERROR) {
char buf[256];
snprintf(buf, sizeof(buf), "%s", strerror(error));
af->af_timeout = 0;
af->af_error_callback(af->af_opaque, buf);
return 0;
}
if(events & ASYNCIO_READ) {
af->af_timeout = 0;
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
asyncio_ssl_read(af);
return 0;
}
#endif
do_read(af);
return 0;
}
if(events & ASYNCIO_WRITE) {
if(af->af_connected) {
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
asyncio_ssl_write(af);
return 0;
}
#endif
do_write(af);
return 0;
}
af->af_timeout = 0;
asyncio_rem_events(af, ASYNCIO_WRITE);
int err;
socklen_t errlen = sizeof(int);
if(getsockopt(af->af_fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen)) {
TRACE(TRACE_ERROR, "ASYNCIO", "getsockopt failed for %s 0x%x
af->af_name, af->af_fd, errno);
return 0;
}
if(err) {
char buf[256];
snprintf(buf, sizeof(buf), "%s", strerror(errno));
af->af_error_callback(af->af_opaque, buf);
} else {
#if ENABLE_OPENSSL
if(af->af_ssl != NULL) {
if(SSL_set_fd(af->af_ssl, af->af_fd) == 0) {
TRACE(TRACE_ERROR, "ASYNCIO", "SSL: Unable to set FD");
}
<API key>(af->af_ssl);
<API key>(af);
af->af_connected = 2;
return 0;
}
#endif
af->af_connected = 1;
af->af_error_callback(af->af_opaque, NULL);
do_write(af);
}
}
return 0;
}
void
asyncio_send(asyncio_fd_t *af, const void *buf, size_t len, int cork)
{
<API key>();
htsbuf_append(&af->af_sendq, buf, len);
if(af->af_fd != -1 && !cork)
do_write(af);
}
void
asyncio_sendq(asyncio_fd_t *af, htsbuf_queue_t *q, int cork)
{
<API key>();
htsbuf_appendq(&af->af_sendq, q);
if(af->af_fd != -1 && !cork)
do_write(af);
}
asyncio_fd_t *
asyncio_connect(const char *name, const net_addr_t *addr,
<API key> *error_cb,
<API key> *read_cb,
void *opaque, int timeout,
void *tlsctx, const char *hostname)
{
struct sockaddr_in si = {0};
int fd;
if((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
return NULL;
no_sigpipe(fd);
<API key>(fd, 1);
net_change_ndelay(fd, 1);
si.sin_family = AF_INET;
si.sin_port = htons(addr->na_port);
memcpy(&si.sin_addr, addr->na_addr, 4);
asyncio_fd_t *af = asyncio_add_fd(fd, ASYNCIO_READ,
<API key>, opaque,
name);
af->af_error_callback = error_cb;
af->af_read_callback = read_cb;
af->af_timeout = arch_get_ts() + timeout * 1000;
af->af_hostname = hostname ? strdup(hostname) : NULL;
#if ENABLE_OPENSSL
if(tlsctx != NULL) {
af->af_ssl = SSL_new(tlsctx);
if(hostname != NULL)
<API key>(af->af_ssl, hostname);
}
#endif
int r = connect(fd, (struct sockaddr *)&si, sizeof(struct sockaddr_in));
if(r == -1) {
if(errno == EINPROGRESS) {
asyncio_add_events(af, ASYNCIO_WRITE);
} else {
// Got fail directly, but we still want to notify the user about
// the error asynchronously. Just to make things easier
af->af_pending_errno = errno;
}
} else {
asyncio_add_events(af, ASYNCIO_WRITE);
}
return af;
}
asyncio_fd_t *
asyncio_attach(const char *name, int fd,
<API key> *error_cb,
<API key> *read_cb,
void *opaque,
void *tlsctx)
{
no_sigpipe(fd);
<API key>(fd, 1);
net_change_ndelay(fd, 1);
asyncio_fd_t *af = asyncio_add_fd(fd, ASYNCIO_READ | ASYNCIO_ERROR,
<API key>, opaque,
name);
#if ENABLE_OPENSSL
if(tlsctx != NULL) {
af->af_ssl = SSL_new(tlsctx);
if(SSL_set_fd(af->af_ssl, fd) == 0) {
TRACE(TRACE_ERROR, "ASYNCIO", "SSL: Unable to set FD");
}
<API key>(af->af_ssl);
}
#endif
af->af_connected = 1;
af->af_fd = fd;
af->af_error_callback = error_cb;
af->af_read_callback = read_cb;
return af;
}
int
asyncio_get_port(asyncio_fd_t *af)
{
struct sockaddr_in si = {0};
socklen_t sl = sizeof(struct sockaddr_in);
if(getsockname(af->af_fd, (struct sockaddr *)&si, &sl) == -1)
return -1;
return ntohs(si.sin_port);
}
/**
* DNS handling
*/
struct asyncio_dns_req {
TAILQ_ENTRY(asyncio_dns_req) adr_link;
char *adr_hostname;
void *adr_opaque;
void (*adr_cb)(void *opaque, int status, const void *data);
int adr_status;
int adr_cancelled;
const void *adr_data;
const char *adr_errmsg;
net_addr_t adr_addr;
};
static int <API key>;
static int
adr_resolve(asyncio_dns_req_t *adr)
{
return net_resolve(adr->adr_hostname, &adr->adr_addr, &adr->adr_errmsg);
}
static void *
adr_resolver(void *aux)
{
asyncio_dns_req_t *adr;
hts_mutex_lock(&asyncio_dns_mutex);
while((adr = TAILQ_FIRST(&asyncio_dns_pending)) != NULL) {
TAILQ_REMOVE(&asyncio_dns_pending, adr, adr_link);
hts_mutex_unlock(&asyncio_dns_mutex);
if(adr_resolve(adr)) {
adr->adr_status = <API key>;
adr->adr_data = adr->adr_errmsg;
} else {
adr->adr_status = <API key>;
adr->adr_data = &adr->adr_addr;
}
hts_mutex_lock(&asyncio_dns_mutex);
TAILQ_INSERT_TAIL(&<API key>, adr, adr_link);
asyncio_wakeup(asyncio_dns_worker);
}
<API key> = 0;
hts_mutex_unlock(&asyncio_dns_mutex);
return NULL;
}
asyncio_dns_req_t *
<API key>(const char *hostname,
void (*cb)(void *opaque,
int status,
const void *data),
void *opaque)
{
asyncio_dns_req_t *adr;
adr = calloc(1, sizeof(asyncio_dns_req_t));
adr->adr_hostname = strdup(hostname);
adr->adr_cb = cb;
adr->adr_opaque = opaque;
hts_mutex_lock(&asyncio_dns_mutex);
TAILQ_INSERT_TAIL(&asyncio_dns_pending, adr, adr_link);
if(!<API key>) {
<API key> = 1;
<API key>("DNS resolver", adr_resolver, NULL,
THREAD_PRIO_BGTASK);
}
hts_mutex_unlock(&asyncio_dns_mutex);
return adr;
}
/**
* Return async DNS requests to caller
*/
static void
adr_deliver_cb(void)
{
asyncio_dns_req_t *adr;
hts_mutex_lock(&asyncio_dns_mutex);
while((adr = TAILQ_FIRST(&<API key>)) != NULL) {
TAILQ_REMOVE(&<API key>, adr, adr_link);
hts_mutex_unlock(&asyncio_dns_mutex);
if(!adr->adr_cancelled)
adr->adr_cb(adr->adr_opaque, adr->adr_status, adr->adr_data);
free(adr->adr_hostname);
free(adr);
hts_mutex_lock(&asyncio_dns_mutex);
}
hts_mutex_unlock(&asyncio_dns_mutex);
}
/**
* Cancel a pending DNS lookup
*/
void
asyncio_dns_cancel(asyncio_dns_req_t *adr)
{
<API key>();
adr->adr_cancelled = 1;
}
static int
<API key>(int bind_any, int broadcast, const net_addr_t *na,
const char *name)
{
int fd;
int one = 1;
struct sockaddr_in si = {0};
if((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
return -1;
no_sigpipe(fd);
si.sin_family = AF_INET;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
#if defined(SO_REUSEPORT)
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int));
#endif
if(broadcast)
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));
if(na) {
si.sin_port = htons(na->na_port);
memcpy(&si.sin_addr, na->na_addr, 4);
if(bind(fd, (struct sockaddr *)&si, sizeof(struct sockaddr_in))) {
if(!bind_any) {
TRACE(TRACE_ERROR, "UDP", "%s: Bind failed -- %s", name,
strerror(errno));
close(fd);
return -1;
} else {
na = NULL;
}
}
}
if(na == NULL) {
si.sin_port = 0;
if(bind(fd, (struct sockaddr *)&si, sizeof(struct sockaddr_in)) == -1) {
TRACE(TRACE_ERROR, "UDP", "%s: Unable to bind -- %s", name,
strerror(errno));
close(fd);
return -1;
}
}
return fd;
}
static void
asyncio_udp_resume(asyncio_fd_t *af)
{
int fd = <API key>(af->af_bind_any, af->af_broadcast,
af->af_bind_addr.na_family ?
&af->af_bind_addr : NULL, af->af_name);
if(fd == -1)
return;
<API key>(fd, 1);
af->af_fd = fd;
asyncio_set_events(af, af->af_ext_events);
af->af_suspended = 0;
TRACE(TRACE_INFO, "UDP", "%s: Resumed listening on port %d", af->af_name, asyncio_get_port(af));
}
static int
asyncio_udp_event(asyncio_fd_t *af, void *opaque, int events, int error)
{
static uint8_t udp_recv_buf[8192];
if(events & ASYNCIO_ERROR) {
close(af->af_fd);
af->af_fd = -1;
af->af_suspended = 1;
return 0;
}
assert(events & ASYNCIO_READ);
struct sockaddr_in sin;
socklen_t sl = sizeof(struct sockaddr_in);
int r = recvfrom(af->af_fd, &udp_recv_buf, sizeof(udp_recv_buf), 0,
(struct sockaddr *)&sin, &sl);
if(r <= 0)
return 0;
net_addr_t na = {0};
na.na_family = 4;
na.na_port = ntohs(sin.sin_port);
memcpy(na.na_addr, &sin.sin_addr, 4);
af->af_udp_callback(opaque, udp_recv_buf, r, &na);
return 0;
}
asyncio_fd_t *
asyncio_udp_bind(const char *name,
const net_addr_t *na,
<API key> *cb,
void *opaque,
int bind_any,
int broadcast)
{
int fd = <API key>(bind_any, broadcast, na, name);
if(fd == -1)
return NULL;
asyncio_fd_t *af = asyncio_add_fd(fd, ASYNCIO_READ,
asyncio_udp_event, opaque, name);
af->af_udp_callback = cb;
af->af_bind_any = bind_any;
af->af_broadcast = broadcast;
if(na != NULL)
af->af_bind_addr = *na;
af->af_resume = asyncio_udp_resume;
TRACE(TRACE_INFO, "UDP", "%s: Listening on port %d", name, asyncio_get_port(af));
return af;
}
void
asyncio_udp_send(asyncio_fd_t *af, const void *data, int size,
const net_addr_t *remote_addr)
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(remote_addr->na_port);
memcpy(&sin.sin_addr, remote_addr->na_addr, 4);
sendto(af->af_fd, data, size, 0,
(const struct sockaddr *)&sin, sizeof(struct sockaddr_in));
}
#ifndef IP_ADD_MEMBERSHIP
#define IP_ADD_MEMBERSHIP 12
struct ip_mreq {
struct in_addr imr_multiaddr;
struct in_addr imr_interface;
};
#endif
int
<API key>(asyncio_fd_t *af, const net_addr_t *group,
const net_addr_t *interface)
{
struct ip_mreq imr = {};
memcpy(&imr.imr_multiaddr.s_addr, group->na_addr, 4);
if(interface != NULL)
memcpy(&imr.imr_interface.s_addr, interface->na_addr, 4);
return setsockopt(af->af_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr,
sizeof(struct ip_mreq));
}
typedef struct netifchange {
void (*cb)(const struct netif *ni);
LIST_ENTRY(netifchange) link;
} netifchange_t;
static LIST_HEAD(, netifchange) netifchanges;
void
<API key>(void (*cb)(const struct netif *ni))
{
<API key>();
netifchange_t *nic = malloc(sizeof(netifchange_t));
nic->cb = cb;
LIST_INSERT_HEAD(&netifchanges, nic, link);
struct netif *ni = net_get_interfaces();
nic->cb(ni);
free(ni);
}
static void
<API key>(void *aux)
{
netifchange_t *nic;
struct netif *ni = net_get_interfaces();
LIST_FOREACH(nic, &netifchanges, link) {
nic->cb(ni);
}
free(ni);
}
void
<API key>(void)
{
<API key>();
asyncio_run_task(<API key>, NULL);
}
static void
asyncio_do_suspend(void *aux)
{
netifchange_t *nic;
LIST_FOREACH(nic, &netifchanges, link) {
nic->cb(NULL);
}
asyncio_fd_t *af;
LIST_FOREACH(af, &asyncio_fds, af_link) {
if(af->af_resume == NULL)
continue; // Socket can't be resumed, skip
if(af->af_fd == -1)
continue;
af->af_suspended = 1;
close(af->af_fd);
af->af_fd = -1;
}
}
static void
asyncio_do_resume(void *aux)
{
asyncio_fd_t *af;
LIST_FOREACH(af, &asyncio_fds, af_link) {
if(af->af_suspended) {
af->af_resume(af);
}
}
<API key>(NULL);
}
void
asyncio_suspend(void)
{
asyncio_run_task(asyncio_do_suspend, NULL);
}
void
asyncio_resume(void)
{
asyncio_run_task(asyncio_do_resume, NULL);
}
#if ENABLE_OPENSSL
static void
<API key>(asyncio_fd_t *af)
{
char errbuf[512];
int r = SSL_do_handshake(af->af_ssl);
int err = SSL_get_error(af->af_ssl, r);
switch(err) {
case SSL_ERROR_WANT_READ:
case <API key>:
af->af_ssl_read_status = err;
break;
case SSL_ERROR_NONE:
af->af_ssl_read_status = 0;
af->af_ssl_established = 1;
if(af->af_connected == 2) {
if(<API key>(af->af_ssl, af->af_hostname,
errbuf, sizeof(errbuf), 1)) {
af->af_error_callback(af->af_opaque, errbuf);
return;
}
af->af_connected = 1;
af->af_error_callback(af->af_opaque, NULL);
}
break;
default:
TRACE(TRACE_ERROR, "ASYNCIO",
"SSL: Unable to handshake, err:%d r:%d errno:%d",
err, r, errno);
unsigned long e;
while((e = ERR_get_error()) != 0) {
ERR_error_string_n(e, errbuf, sizeof(errbuf));
TRACE(TRACE_ERROR, "ASYNCIO", "SSL: %s", errbuf);
}
af->af_error_callback(af->af_opaque, "SSL Handshake error");
break;
}
}
static int
asyncio_ssl_events(asyncio_fd_t *af)
{
int events = 0;
if(!af->af_connected)
return POLLOUT;
if(af->af_ssl_read_status == <API key>) {
events |= POLLOUT;
} else {
events |= POLLIN;
if(af->af_ssl_established) {
asyncio_ssl_write(af);
}
}
if(af->af_ssl_write_status == <API key>) {
events |= POLLOUT;
} else if(af->af_ssl_write_status == SSL_ERROR_WANT_READ) {
events |= POLLIN;
}
return events;
}
static void
asyncio_ssl_write(asyncio_fd_t *af)
{
if(!af->af_ssl_established) {
<API key>(af);
return;
}
htsbuf_data_t *hd;
htsbuf_queue_t *q = &af->af_sendq;
int len;
af->af_ssl_write_status = 0;
while((hd = TAILQ_FIRST(&q->hq_q)) != NULL) {
len = hd->hd_data_len - hd->hd_data_off;
assert(len > 0);
int r = SSL_write(af->af_ssl, hd->hd_data + hd->hd_data_off, len);
int err = SSL_get_error(af->af_ssl, r);
switch(err) {
case SSL_ERROR_NONE:
hd->hd_data_off += r;
assert(hd->hd_data_off <= hd->hd_data_len);
if(hd->hd_data_off == hd->hd_data_len) {
TAILQ_REMOVE(&q->hq_q, hd, hd_link);
free(hd->hd_data);
free(hd);
}
continue;
case SSL_ERROR_WANT_READ:
case <API key>:
af->af_ssl_write_status = err;
return;
default:
return;
}
}
}
static void
asyncio_ssl_read(asyncio_fd_t *af)
{
if(!af->af_ssl_established) {
<API key>(af);
return;
}
while(af->af_ssl != NULL) {
char buf[4096];
if(af->af_ssl_write_status == SSL_ERROR_WANT_READ) {
return;
}
af->af_ssl_read_status = 0;
int r = SSL_read(af->af_ssl, buf, sizeof(buf));
int err = SSL_get_error(af->af_ssl, r);
switch(err) {
case SSL_ERROR_NONE:
htsbuf_append(&af->af_recvq, buf, r);
break;
default:
af->af_error_callback(af->af_opaque, "SSL Error");
return;
case SSL_ERROR_WANT_READ:
case <API key>:
af->af_ssl_read_status = err;
return;
}
af->af_read_callback(af->af_opaque, &af->af_recvq);
}
}
void *
<API key>(const char *privkeyfile, const char *certfile)
{
SSL_CTX *ctx = SSL_CTX_new(TLSv1_server_method());
int r = <API key>(ctx, privkeyfile, SSL_FILETYPE_PEM);
if(r != 1) {
TRACE(TRACE_ERROR, "ASYNCIO", "Unable to load private key file %s",
privkeyfile);
return NULL;
}
r = <API key>(ctx, certfile, SSL_FILETYPE_PEM);
if(r != 1) {
TRACE(TRACE_ERROR, "ASYNCIO", "Unable to load certificate file %s",
certfile);
return NULL;
}
r = <API key>(ctx);
if(r != 1) {
TRACE(TRACE_ERROR, "ASYNCIO", "Certificate/private key file mismatch");
return NULL;
}
return ctx;
}
void *
<API key>(void)
{
SSL_CTX *ctx = SSL_CTX_new(TLSv1_client_method());
if(!<API key>(ctx, NULL, "/etc/ssl/certs")) {
return NULL;
}
return ctx;
}
void
asyncio_ssl_free(void *ctx)
{
SSL_CTX_free(ctx);
}
#else
void *
<API key>(const char *privkeyfile, const char *certfile)
{
return NULL;
}
void *
<API key>(void)
{
return NULL;
}
void
asyncio_ssl_free(void *ctx)
{
}
#endif |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<TITLE>
HwmfDraw.WmfSetPixel (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="HwmfDraw.WmfSetPixel (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/HwmfDraw.WmfSetPixel.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSelectObject.html" title="class in org.apache.poi.hwmf.record"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/poi/hwmf/record/HwmfEscape.html" title="class in org.apache.poi.hwmf.record"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html" target="_top"><B>FRAMES</B></A>
<A HREF="HwmfDraw.WmfSetPixel.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.apache.poi.hwmf.record</FONT>
<BR>
Class HwmfDraw.WmfSetPixel</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.hwmf.record.HwmfDraw.WmfSetPixel</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html" title="interface in org.apache.poi.hwmf.record">HwmfRecord</A></DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.html" title="class in org.apache.poi.hwmf.record">HwmfDraw</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public static class <B>HwmfDraw.WmfSetPixel</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html" title="interface in org.apache.poi.hwmf.record">HwmfRecord</A></DL>
</PRE>
<P>
The META_RECTANGLE record paints a rectangle. The rectangle is outlined by using the pen and
filled by using the brush that are defined in the playback device context.
<P>
<P>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html#HwmfDraw.WmfSetPixel()">HwmfDraw.WmfSetPixel</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html#draw(org.apache.poi.hwmf.draw.HwmfGraphics)">draw</A></B>(<A HREF="../../../../../org/apache/poi/hwmf/draw/HwmfGraphics.html" title="class in org.apache.poi.hwmf.draw">HwmfGraphics</A> ctx)</CODE>
<BR>
Apply the record settings to the graphics context</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecordType.html" title="enum in org.apache.poi.hwmf.record">HwmfRecordType</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html#getRecordType()">getRecordType</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html#init(org.apache.poi.util.<API key>, long, int)">init</A></B>(<A HREF="../../../../../org/apache/poi/util/<API key>.html" title="class in org.apache.poi.util"><API key></A> leis,
long recordSize,
int recordFunction)</CODE>
<BR>
Init record from stream</TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="HwmfDraw.WmfSetPixel()"></A><H3>
HwmfDraw.WmfSetPixel</H3>
<PRE>
public <B>HwmfDraw.WmfSetPixel</B>()</PRE>
<DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getRecordType()"></A><H3>
getRecordType</H3>
<PRE>
public <A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecordType.html" title="enum in org.apache.poi.hwmf.record">HwmfRecordType</A> <B>getRecordType</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html#getRecordType()">getRecordType</A></CODE> in interface <CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html" title="interface in org.apache.poi.hwmf.record">HwmfRecord</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="init(org.apache.poi.util.<API key>, long, int)"></A><H3>
init</H3>
<PRE>
public int <B>init</B>(<A HREF="../../../../../org/apache/poi/util/<API key>.html" title="class in org.apache.poi.util"><API key></A> leis,
long recordSize,
int recordFunction)
throws java.io.IOException</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html#init(org.apache.poi.util.<API key>, long, int)">HwmfRecord</A></CODE></B></DD>
<DD>Init record from stream
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html#init(org.apache.poi.util.<API key>, long, int)">init</A></CODE> in interface <CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html" title="interface in org.apache.poi.hwmf.record">HwmfRecord</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>leis</CODE> - the little endian input stream
<DT><B>Returns:</B><DD>count of processed bytes
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="draw(org.apache.poi.hwmf.draw.HwmfGraphics)"></A><H3>
draw</H3>
<PRE>
public void <B>draw</B>(<A HREF="../../../../../org/apache/poi/hwmf/draw/HwmfGraphics.html" title="class in org.apache.poi.hwmf.draw">HwmfGraphics</A> ctx)</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html#draw(org.apache.poi.hwmf.draw.HwmfGraphics)">HwmfRecord</A></CODE></B></DD>
<DD>Apply the record settings to the graphics context
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html#draw(org.apache.poi.hwmf.draw.HwmfGraphics)">draw</A></CODE> in interface <CODE><A HREF="../../../../../org/apache/poi/hwmf/record/HwmfRecord.html" title="interface in org.apache.poi.hwmf.record">HwmfRecord</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>ctx</CODE> - the graphics context to modify</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/HwmfDraw.WmfSetPixel.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/apache/poi/hwmf/record/HwmfDraw.WmfSelectObject.html" title="class in org.apache.poi.hwmf.record"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/apache/poi/hwmf/record/HwmfEscape.html" title="class in org.apache.poi.hwmf.record"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/poi/hwmf/record/HwmfDraw.WmfSetPixel.html" target="_top"><B>FRAMES</B></A>
<A HREF="HwmfDraw.WmfSetPixel.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright 2017 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML> |
package org.graylog2.indexer.elasticsearch;
import org.elasticsearch.<API key>;
import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.<API key>;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.ClusterAdminClient;
import org.elasticsearch.client.FilterClient;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.common.unit.TimeValue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class GlobalTimeoutClient extends FilterClient {
private final long timeout;
private final TimeUnit unit;
public GlobalTimeoutClient(Client in, long timeout, TimeUnit unit) {
super(in);
checkArgument(timeout > 0);
this.timeout = timeout;
this.unit = checkNotNull(unit);
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends <API key><Request, Response, RequestBuilder, Client>> ActionFuture<Response> execute(Action<Request, Response, RequestBuilder, Client> action, Request request) {
return <API key>.create(super.execute(action, request), timeout, unit);
}
@Override
public ClusterAdminClient cluster() {
return new <API key>(super.cluster(), timeout, unit);
}
@Override
public IndicesAdminClient indices() {
return new <API key>(super.indices(), timeout, unit);
}
@Override
public AdminClient admin() {
return new <API key>(super.admin(), timeout, unit);
}
public static class <API key> implements AdminClient {
private final AdminClient in;
private final long timeout;
private final TimeUnit unit;
public <API key>(AdminClient in, long timeout, TimeUnit unit) {
this.in = checkNotNull(in);
checkArgument(timeout > 0);
this.timeout = timeout;
this.unit = checkNotNull(unit);
}
@Override
public IndicesAdminClient indices() {
return new <API key>(in.indices(), timeout, unit);
}
@Override
public ClusterAdminClient cluster() {
return new <API key>(in.cluster(), timeout, unit);
}
}
public static class <API key> extends FilterClient.ClusterAdmin {
private final long timeout;
private final TimeUnit unit;
public <API key>(ClusterAdminClient in, long timeout, TimeUnit unit) {
super(in);
checkArgument(timeout > 0);
this.timeout = timeout;
this.unit = checkNotNull(unit);
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends <API key><Request, Response, RequestBuilder, ClusterAdminClient>> ActionFuture<Response> execute(Action<Request, Response, RequestBuilder, ClusterAdminClient> action, Request request) {
return <API key>.create(super.execute(action, request), timeout, unit);
}
}
public static class <API key> extends FilterClient.IndicesAdmin {
private final long timeout;
private final TimeUnit unit;
public <API key>(IndicesAdminClient in, long timeout, TimeUnit unit) {
super(in);
checkArgument(timeout > 0);
this.timeout = timeout;
this.unit = checkNotNull(unit);
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends <API key><Request, Response, RequestBuilder, IndicesAdminClient>> ActionFuture<Response> execute(Action<Request, Response, RequestBuilder, IndicesAdminClient> action, Request request) {
return <API key>.create(super.execute(action, request), timeout, unit);
}
}
public static class <API key><T> implements ActionFuture<T> {
private final ActionFuture<T> in;
private final long timeout;
private final TimeUnit unit;
private <API key>(ActionFuture<T> in, long timeout, TimeUnit unit) {
this.in = checkNotNull(in);
checkArgument(timeout > 0);
this.timeout = timeout;
this.unit = checkNotNull(unit);
}
public static <Response extends ActionResponse> <API key><Response> create(ActionFuture<Response> actionFuture, long timeout, TimeUnit unit) {
return actionFuture == null ? null : new <API key><>(actionFuture, timeout, unit);
}
@Override
public T actionGet() throws <API key> {
return in.actionGet(timeout, unit);
}
@Override
public T actionGet(String timeout) throws <API key> {
return in.actionGet(timeout);
}
@Override
public T actionGet(long timeoutMillis) throws <API key> {
return in.actionGet(timeoutMillis);
}
@Override
public T actionGet(long timeout, TimeUnit unit) throws <API key> {
return in.actionGet(timeout, unit);
}
@Override
public T actionGet(TimeValue timeout) throws <API key> {
return in.actionGet(timeout);
}
@Override
public Throwable getRootFailure() {
return in.getRootFailure();
}
@Override
public boolean cancel(boolean <API key>) {
return in.cancel(<API key>);
}
@Override
public boolean isCancelled() {
return in.isCancelled();
}
@Override
public boolean isDone() {
return in.isDone();
}
@Override
public T get() throws <API key>, ExecutionException {
try {
return in.get(timeout, unit);
} catch (TimeoutException e) {
throw new ExecutionException(e.getCause());
}
}
@Override
public T get(long timeout, TimeUnit unit) throws <API key>, ExecutionException, TimeoutException {
return in.get(timeout, unit);
}
}
} |
#ifndef _MAGICKCORE_BLOB_H
#define _MAGICKCORE_BLOB_H
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#include "magick/image.h"
#include "magick/stream.h"
#define <API key> (32*8192)
typedef enum
{
ReadMode,
WriteMode,
IOMode
} MapMode;
extern MagickExport FILE
*GetBlobFileHandle(const Image *);
extern MagickExport Image
*BlobToImage(const ImageInfo *,const void *,const size_t,ExceptionInfo *),
*PingBlob(const ImageInfo *,const void *,const size_t,ExceptionInfo *);
extern MagickExport MagickBooleanType
BlobToFile(char *,const void *,const size_t,ExceptionInfo *),
FileToImage(Image *,const char *),
GetBlobError(const Image *),
ImageToFile(Image *,char *,ExceptionInfo *),
InjectImageBlob(const ImageInfo *,Image *,Image *,const char *,
ExceptionInfo *),
IsBlobExempt(const Image *),
IsBlobSeekable(const Image *),
IsBlobTemporary(const Image *);
extern MagickExport MagickSizeType
GetBlobSize(const Image *);
extern MagickExport StreamHandler
<API key>(const Image *);
extern MagickExport unsigned char
*FileToBlob(const char *,const size_t,size_t *,ExceptionInfo *),
*GetBlobStreamData(const Image *),
*ImageToBlob(const ImageInfo *,Image *,size_t *,ExceptionInfo *),
*ImagesToBlob(const ImageInfo *,Image *,size_t *,ExceptionInfo *);
extern MagickExport void
DestroyBlob(Image *),
DuplicateBlob(Image *,const Image *),
SetBlobExempt(Image *,const MagickBooleanType);
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
#endif |
void gpib_send(unsigned int gpib_board, unsigned int gpib_device, char* command_string); |
// 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.
// Google Mock - a framework for writing C++ mock classes.
// This file implements some commonly used argument matchers. More
// matchers can be defined by the user implementing the
// MatcherInterface<T> interface if necessary.
#ifndef <API key>
#define <API key>
#include <algorithm>
#include <limits>
#include <ostream> // NOLINT
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <gmock/internal/<API key>.h>
#include <gmock/internal/gmock-port.h>
#include <gtest/gtest.h>
namespace testing {
// To implement a matcher Foo for type T, define:
// 1. a class FooMatcherImpl that implements the
// MatcherInterface<T> interface, and
// 2. a factory function that creates a Matcher<T> object from a
// FooMatcherImpl*.
// The two-level delegation design makes it possible to allow a user
// to write "v" instead of "Eq(v)" where a Matcher is expected, which
// is impossible if we pass matchers by pointers. It also eases
// ownership management as Matcher objects can now be copied like
// plain values.
// MatchResultListener is an abstract class. Its << operator can be
// used by a matcher to explain why a value matches or doesn't match.
// TODO(wan@google.com): add method
// bool InterestedInWhy(bool result) const;
// to indicate whether the listener is interested in why the match
// result is 'result'.
class MatchResultListener {
public:
// Creates a listener object with the given underlying ostream. The
// listener does not own the ostream.
explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
virtual ~MatchResultListener() = 0; // Makes this class abstract.
// Streams x to the underlying ostream; does nothing if the ostream
// is NULL.
template <typename T>
MatchResultListener& operator<<(const T& x) {
if (stream_ != NULL)
*stream_ << x;
return *this;
}
// Returns the underlying ostream.
::std::ostream* stream() { return stream_; }
// Returns true iff the listener is interested in an explanation of
// the match result. A matcher's MatchAndExplain() method can use
// this information to avoid generating the explanation when no one
// intends to hear it.
bool IsInterested() const { return stream_ != NULL; }
private:
::std::ostream* const stream_;
<API key>(MatchResultListener);
};
inline MatchResultListener::~MatchResultListener() {
}
// The implementation of a matcher.
template <typename T>
class MatcherInterface {
public:
virtual ~MatcherInterface() {}
// Returns true iff the matcher matches x; also explains the match
// result to 'listener', in the form of a non-restrictive relative
// clause ("which ...", "whose ...", etc) that describes x. For
// example, the MatchAndExplain() method of the Pointee(...) matcher
// should generate an explanation like "which points to ...".
// You should override this method when defining a new matcher.
// It's the responsibility of the caller (Google Mock) to guarantee
// that 'listener' is not NULL. This helps to simplify a matcher's
// implementation when it doesn't care about the performance, as it
// can talk to 'listener' without checking its validity first.
// However, in order to implement dummy listeners efficiently,
// listener->stream() may be NULL.
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
// Describes this matcher to an ostream. The function should print
// a verb phrase that describes the property a value matching this
// matcher should have. The subject of the verb phrase is the value
// being matched. For example, the DescribeTo() method of the Gt(7)
// matcher prints "is greater than 7".
virtual void DescribeTo(::std::ostream* os) const = 0;
// Describes the negation of this matcher to an ostream. For
// example, if the description of this matcher is "is greater than
// 7", the negated description could be "is not greater than 7".
// You are not required to override this when implementing
// MatcherInterface, but it is highly advised so that your matcher
// can produce good error messages.
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "not (";
DescribeTo(os);
*os << ")";
}
};
namespace internal {
// A match result listener that ignores the explanation.
class <API key> : public MatchResultListener {
public:
<API key>() : MatchResultListener(NULL) {}
private:
<API key>(<API key>);
};
// A match result listener that forwards the explanation to a given
// ostream. The difference between this and MatchResultListener is
// that the former is concrete.
class <API key> : public MatchResultListener {
public:
explicit <API key>(::std::ostream* os)
: MatchResultListener(os) {}
private:
<API key>(<API key>);
};
// A match result listener that stores the explanation in a string.
class <API key> : public MatchResultListener {
public:
<API key>() : MatchResultListener(&ss_) {}
// Returns the explanation heard so far.
internal::string str() const { return ss_.str(); }
private:
::std::stringstream ss_;
<API key>(<API key>);
};
// An internal class for implementing Matcher<T>, which will derive
// from it. We put functionalities common to all Matcher<T>
// specializations here to avoid code duplication.
template <typename T>
class MatcherBase {
public:
// Returns true iff the matcher matches x; also explains the match
// result to 'listener'.
bool MatchAndExplain(T x, MatchResultListener* listener) const {
return impl_->MatchAndExplain(x, listener);
}
// Returns true iff this matcher matches x.
bool Matches(T x) const {
<API key> dummy;
return MatchAndExplain(x, &dummy);
}
// Describes this matcher to an ostream.
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
// Describes the negation of this matcher to an ostream.
void DescribeNegationTo(::std::ostream* os) const {
impl_->DescribeNegationTo(os);
}
// Explains why x matches, or doesn't match, the matcher.
void <API key>(T x, ::std::ostream* os) const {
<API key> listener(os);
MatchAndExplain(x, &listener);
}
protected:
MatcherBase() {}
// Constructs a matcher from its implementation.
explicit MatcherBase(const MatcherInterface<T>* impl)
: impl_(impl) {}
virtual ~MatcherBase() {}
private:
// shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
// interfaces. The former dynamically allocates a chunk of memory
// to hold the reference count, while the latter tracks all
// references using a circular linked list without allocating
// memory. It has been observed that linked_ptr performs better in
// typical scenarios. However, shared_ptr can out-perform
// linked_ptr when there are many more uses of the copy constructor
// than the default constructor.
// If performance becomes a problem, we should see if using
// shared_ptr helps.
::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
};
} // namespace internal
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
// object that can check whether a value of type T matches. The
// implementation of Matcher<T> is just a linked_ptr to const
// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
// from Matcher!
template <typename T>
class Matcher : public internal::MatcherBase<T> {
public:
// Constructs a null matcher. Needed for storing Matcher objects in
// STL containers.
Matcher() {}
// Constructs a matcher from its implementation.
explicit Matcher(const MatcherInterface<T>* impl)
: internal::MatcherBase<T>(impl) {}
// Implicit constructor here allows people to write
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
Matcher(T value); // NOLINT
};
// The following two specializations allow the user to write str
// instead of Eq(str) and "foo" instead of Eq("foo") when a string
// matcher is expected.
template <>
class Matcher<const internal::string&>
: public internal::MatcherBase<const internal::string&> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<const internal::string&>* impl)
: internal::MatcherBase<const internal::string&>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const internal::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
template <>
class Matcher<internal::string>
: public internal::MatcherBase<internal::string> {
public:
Matcher() {}
explicit Matcher(const MatcherInterface<internal::string>* impl)
: internal::MatcherBase<internal::string>(impl) {}
// Allows the user to write str instead of Eq(str) sometimes, where
// str is a string object.
Matcher(const internal::string& s); // NOLINT
// Allows the user to write "foo" instead of Eq("foo") sometimes.
Matcher(const char* s); // NOLINT
};
// The PolymorphicMatcher class template makes it easy to implement a
// polymorphic matcher (i.e. a matcher that can match values of more
// than one type, e.g. Eq(n) and NotNull()).
// To define a polymorphic matcher, a user should provide an Impl
// class that has a DescribeTo() method and a DescribeNegationTo()
// method, and define a member function (or member function template)
// bool MatchAndExplain(const Value& value,
// MatchResultListener* listener) const;
// See the definition of NotNull() for a complete example.
template <class Impl>
class PolymorphicMatcher {
public:
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
// Returns a mutable reference to the underlying matcher
// implementation object.
Impl& mutable_impl() { return impl_; }
// Returns an immutable reference to the underlying matcher
// implementation object.
const Impl& impl() const { return impl_; }
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new MonomorphicImpl<T>(impl_));
}
private:
template <typename T>
class MonomorphicImpl : public MatcherInterface<T> {
public:
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
virtual void DescribeTo(::std::ostream* os) const {
impl_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
impl_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
return impl_.MatchAndExplain(x, listener);
}
private:
const Impl impl_;
<API key>(MonomorphicImpl);
};
Impl impl_;
<API key>(PolymorphicMatcher);
};
// Creates a matcher from its implementation. This is easier to use
// than the Matcher<T> constructor as it doesn't require you to
// explicitly write the template argument, e.g.
// MakeMatcher(foo);
// Matcher<const string&>(foo);
template <typename T>
inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
return Matcher<T>(impl);
};
// Creates a polymorphic matcher from its implementation. This is
// easier to use than the PolymorphicMatcher<Impl> constructor as it
// doesn't require you to explicitly write the template argument, e.g.
// <API key>(foo);
// PolymorphicMatcher<TypeOfFoo>(foo);
template <class Impl>
inline PolymorphicMatcher<Impl> <API key>(const Impl& impl) {
return PolymorphicMatcher<Impl>(impl);
}
// In order to be safe and clear, casting between different matcher
// types is done explicitly via MatcherCast<T>(m), which takes a
// matcher m and returns a Matcher<T>. It compiles only when T can be
// statically converted to the argument type of m.
template <typename T, typename M>
Matcher<T> MatcherCast(M m);
// Implements SafeMatcherCast().
// We use an intermediate class to do the actual safe casting as Nokia's
// Symbian compiler cannot decide between
// template <T, M> ... (M) and
// template <T, U> ... (const Matcher<U>&)
// for function templates but can for member function templates.
template <typename T>
class SafeMatcherCastImpl {
public:
// This overload handles polymorphic matchers only since monomorphic
// matchers are handled by the next one.
template <typename M>
static inline Matcher<T> Cast(M polymorphic_matcher) {
return Matcher<T>(polymorphic_matcher);
}
// This overload handles monomorphic matchers.
// In general, if type T can be implicitly converted to type U, we can
// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
// contravariant): just keep a copy of the original Matcher<U>, convert the
// argument from type T to U, and then pass it to the underlying Matcher<U>.
// The only exception is when U is a reference and T is not, as the
// underlying Matcher<U> may be interested in the argument's address, which
// is not preserved in the conversion from T to U.
template <typename U>
static inline Matcher<T> Cast(const Matcher<U>& matcher) {
// Enforce that T can be implicitly converted to U.
<API key>((internal::<API key><T, U>::value),
<API key>);
// Enforce that we are not converting a non-reference type T to a reference
// type U.
<API key>(
internal::is_reference<T>::value || !internal::is_reference<U>::value,
<API key>);
// In case both T and U are arithmetic types, enforce that the
// conversion is not lossy.
typedef <API key>(T) RawT;
typedef <API key>(U) RawU;
const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
<API key>(
kTIsOther || kUIsOther ||
(internal::<API key><RawT, RawU>::value),
<API key>);
return MatcherCast<T>(matcher);
}
};
template <typename T, typename M>
inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
}
// A<T>() returns a matcher that matches any value of type T.
template <typename T>
Matcher<T> A();
// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
// and MUST NOT BE USED IN USER CODE!!!
namespace internal {
// If the explanation is not empty, prints it to the ostream.
inline void PrintIfNotEmpty(const internal::string& explanation,
std::ostream* os) {
if (explanation != "" && os != NULL) {
*os << ", " << explanation;
}
}
// Matches the value against the given matcher, prints the value and explains
// the match result to the listener. Returns the match result.
// 'listener' must not be NULL.
// Value cannot be passed by const reference, because some matchers take a
// non-const argument.
template <typename Value, typename T>
bool <API key>(Value& value, const Matcher<T>& matcher,
MatchResultListener* listener) {
if (!listener->IsInterested()) {
// If the listener is not interested, we do not need to construct the
// inner explanation.
return matcher.Matches(value);
}
<API key> inner_listener;
const bool match = matcher.MatchAndExplain(value, &inner_listener);
UniversalPrint(value, listener->stream());
PrintIfNotEmpty(inner_listener.str(), listener->stream());
return match;
}
// An internal helper class for doing compile-time loop on a tuple's
// fields.
template <size_t N>
class TuplePrefix {
public:
// TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
// iff the first N fields of matcher_tuple matches the first N
// fields of value_tuple, respectively.
template <typename MatcherTuple, typename ValueTuple>
static bool Matches(const MatcherTuple& matcher_tuple,
const ValueTuple& value_tuple) {
using ::std::tr1::get;
return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
&& get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
}
// TuplePrefix<N>::<API key>(matchers, values, os)
// describes failures in matching the first N fields of matchers
// against the first N fields of values. If there is no failure,
// nothing will be streamed to os.
template <typename MatcherTuple, typename ValueTuple>
static void <API key>(const MatcherTuple& matchers,
const ValueTuple& values,
::std::ostream* os) {
using ::std::tr1::tuple_element;
using ::std::tr1::get;
// First, describes failures in the first N - 1 fields.
TuplePrefix<N - 1>::<API key>(matchers, values, os);
// Then describes the failure (if any) in the (N - 1)-th (0-based)
// field.
typename tuple_element<N - 1, MatcherTuple>::type matcher =
get<N - 1>(matchers);
typedef typename tuple_element<N - 1, ValueTuple>::type Value;
Value value = get<N - 1>(values);
<API key> listener;
if (!matcher.MatchAndExplain(value, &listener)) {
// TODO(wan): include in the message the name of the parameter
// as used in MOCK_METHOD*() when possible.
*os << " Expected arg #" << N - 1 << ": ";
get<N - 1>(matchers).DescribeTo(os);
*os << "\n Actual: ";
// We remove the reference in type Value to prevent the
// universal printer from printing the address of value, which
// isn't interesting to the user most of the time. The
// matcher's MatchAndExplain() method handles the case when
// the address is interesting.
internal::UniversalPrint(value, os);
PrintIfNotEmpty(listener.str(), os);
*os << "\n";
}
}
};
// The base case.
template <>
class TuplePrefix<0> {
public:
template <typename MatcherTuple, typename ValueTuple>
static bool Matches(const MatcherTuple& /* matcher_tuple */,
const ValueTuple& /* value_tuple */) {
return true;
}
template <typename MatcherTuple, typename ValueTuple>
static void <API key>(const MatcherTuple& /* matchers */,
const ValueTuple& /* values */,
::std::ostream* ) {}
};
// TupleMatches(matcher_tuple, value_tuple) returns true iff all
// matchers in matcher_tuple match the corresponding fields in
// value_tuple. It is a compiler error if matcher_tuple and
// value_tuple have different number of fields or incompatible field
// types.
template <typename MatcherTuple, typename ValueTuple>
bool TupleMatches(const MatcherTuple& matcher_tuple,
const ValueTuple& value_tuple) {
using ::std::tr1::tuple_size;
// Makes sure that matcher_tuple and value_tuple have the same
// number of fields.
<API key>(tuple_size<MatcherTuple>::value ==
tuple_size<ValueTuple>::value,
<API key>);
return TuplePrefix<tuple_size<ValueTuple>::value>::
Matches(matcher_tuple, value_tuple);
}
// Describes failures in matching matchers against values. If there
// is no failure, nothing will be streamed to os.
template <typename MatcherTuple, typename ValueTuple>
void <API key>(const MatcherTuple& matchers,
const ValueTuple& values,
::std::ostream* os) {
using ::std::tr1::tuple_size;
TuplePrefix<tuple_size<MatcherTuple>::value>::<API key>(
matchers, values, os);
}
// The MatcherCastImpl class template is a helper for implementing
// MatcherCast(). We need this helper in order to partially
// specialize the implementation of MatcherCast() (C++ allows
// class/struct templates to be partially specialized, but not
// function templates.).
// This general version is used when MatcherCast()'s argument is a
// polymorphic matcher (i.e. something that can be converted to a
// Matcher but is not one yet; for example, Eq(value)).
template <typename T, typename M>
class MatcherCastImpl {
public:
static Matcher<T> Cast(M polymorphic_matcher) {
return Matcher<T>(polymorphic_matcher);
}
};
// This more specialized version is used when MatcherCast()'s argument
// is already a Matcher. This only compiles when type T can be
// statically converted to type U.
template <typename T, typename U>
class MatcherCastImpl<T, Matcher<U> > {
public:
static Matcher<T> Cast(const Matcher<U>& source_matcher) {
return Matcher<T>(new Impl(source_matcher));
}
private:
class Impl : public MatcherInterface<T> {
public:
explicit Impl(const Matcher<U>& source_matcher)
: source_matcher_(source_matcher) {}
// We delegate the matching logic to the source matcher.
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
}
virtual void DescribeTo(::std::ostream* os) const {
source_matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
source_matcher_.DescribeNegationTo(os);
}
private:
const Matcher<U> source_matcher_;
<API key>(Impl);
};
};
// This even more specialized version is used for efficiently casting
// a matcher to its own type.
template <typename T>
class MatcherCastImpl<T, Matcher<T> > {
public:
static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
};
// Implements A<T>().
template <typename T>
class AnyMatcherImpl : public MatcherInterface<T> {
public:
virtual bool MatchAndExplain(
T , MatchResultListener* ) const { return true; }
virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
virtual void DescribeNegationTo(::std::ostream* os) const {
// This is mostly for completeness' safe, as it's not very useful
// to write Not(A<bool>()). However we cannot completely rule out
// such a possibility, and it doesn't hurt to be prepared.
*os << "never matches";
}
};
// Implements _, a matcher that matches any value of any
// type. This is a polymorphic matcher, so we need a template type
// conversion operator to make it appearing as a Matcher<T> for any
// type T.
class AnythingMatcher {
public:
template <typename T>
operator Matcher<T>() const { return A<T>(); }
};
// Implements a matcher that compares a given value with a
// pre-supplied value using one of the ==, <=, <, etc, operators. The
// two values being compared don't have to have the same type.
// The matcher defined here is polymorphic (for example, Eq(5) can be
// used to match an int, a short, a double, etc). Therefore we use
// a template type conversion operator in the implementation.
// We define this as a macro in order to eliminate duplicated source
// code.
// The following template definition assumes that the Rhs parameter is
// a "bare" type (i.e. neither 'const T' nor 'T&').
#define <API key>( \
name, op, relation, negated_relation) \
template <typename Rhs> class name##Matcher { \
public: \
explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
template <typename Lhs> \
operator Matcher<Lhs>() const { \
return MakeMatcher(new Impl<Lhs>(rhs_)); \
} \
private: \
template <typename Lhs> \
class Impl : public MatcherInterface<Lhs> { \
public: \
explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
virtual bool MatchAndExplain(\
Lhs lhs, MatchResultListener* /* listener */) const { \
return lhs op rhs_; \
} \
virtual void DescribeTo(::std::ostream* os) const { \
*os << relation " "; \
UniversalPrint(rhs_, os); \
} \
virtual void DescribeNegationTo(::std::ostream* os) const { \
*os << negated_relation " "; \
UniversalPrint(rhs_, os); \
} \
private: \
Rhs rhs_; \
<API key>(Impl); \
}; \
Rhs rhs_; \
<API key>(name##Matcher); \
}
// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
// respectively.
<API key>(Eq, ==, "is equal to", "isn't equal to");
<API key>(Ge, >=, "is >=", "isn't >=");
<API key>(Gt, >, "is >", "isn't >");
<API key>(Le, <=, "is <=", "isn't <=");
<API key>(Lt, <, "is <", "isn't <");
<API key>(Ne, !=, "isn't equal to", "is equal to");
#undef <API key>
// Implements the polymorphic IsNull() matcher, which matches any raw or smart
// pointer that is NULL.
class IsNullMatcher {
public:
template <typename Pointer>
bool MatchAndExplain(const Pointer& p,
MatchResultListener* /* listener */) const {
return GetRawPointer(p) == NULL;
}
void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
void DescribeNegationTo(::std::ostream* os) const {
*os << "isn't NULL";
}
};
// Implements the polymorphic NotNull() matcher, which matches any raw or smart
// pointer that is not NULL.
class NotNullMatcher {
public:
template <typename Pointer>
bool MatchAndExplain(const Pointer& p,
MatchResultListener* /* listener */) const {
return GetRawPointer(p) != NULL;
}
void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
void DescribeNegationTo(::std::ostream* os) const {
*os << "is NULL";
}
};
// Ref(variable) matches any argument that is a reference to
// 'variable'. This matcher is polymorphic as it can match any
// super type of the type of 'variable'.
// The RefMatcher template class implements Ref(variable). It can
// only be instantiated with a reference type. This prevents a user
// from mistakenly using Ref(x) to match a non-reference function
// argument. For example, the following will righteously cause a
// compiler error:
// int n;
// Matcher<int> m1 = Ref(n); // This won't compile.
// Matcher<int&> m2 = Ref(n); // This will compile.
template <typename T>
class RefMatcher;
template <typename T>
class RefMatcher<T&> {
// Google Mock is a generic framework and thus needs to support
// mocking any function types, including those that take non-const
// reference arguments. Therefore the template parameter T (and
// Super below) can be instantiated to either a const type or a
// non-const type.
public:
// RefMatcher() takes a T& instead of const T&, as we want the
// compiler to catch using Ref(const_value) as a matcher for a
// non-const reference.
explicit RefMatcher(T& x) : object_(x) {} // NOLINT
template <typename Super>
operator Matcher<Super&>() const {
// By passing object_ (type T&) to Impl(), which expects a Super&,
// we make sure that Super is a super type of T. In particular,
// this catches using Ref(const_value) as a matcher for a
// non-const reference, as you cannot implicitly convert a const
// reference to a non-const reference.
return MakeMatcher(new Impl<Super>(object_));
}
private:
template <typename Super>
class Impl : public MatcherInterface<Super&> {
public:
explicit Impl(Super& x) : object_(x) {} // NOLINT
// MatchAndExplain() takes a Super& (as opposed to const Super&)
// in order to match the interface MatcherInterface<Super&>.
virtual bool MatchAndExplain(
Super& x, MatchResultListener* listener) const {
*listener << "which is located @" << static_cast<const void*>(&x);
return &x == &object_;
}
virtual void DescribeTo(::std::ostream* os) const {
*os << "references the variable ";
UniversalPrinter<Super&>::Print(object_, os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "does not reference the variable ";
UniversalPrinter<Super&>::Print(object_, os);
}
private:
const Super& object_;
<API key>(Impl);
};
T& object_;
<API key>(RefMatcher);
};
// Polymorphic helper functions for narrow and wide string matchers.
inline bool <API key>(const char* lhs, const char* rhs) {
return String::<API key>(lhs, rhs);
}
inline bool <API key>(const wchar_t* lhs,
const wchar_t* rhs) {
return String::<API key>(lhs, rhs);
}
// String comparison for narrow or wide strings that can have embedded NUL
// characters.
template <typename StringType>
bool <API key>(const StringType& s1,
const StringType& s2) {
// Are the heads equal?
if (!<API key>(s1.c_str(), s2.c_str())) {
return false;
}
// Skip the equal heads.
const typename StringType::value_type nul = 0;
const size_t i1 = s1.find(nul), i2 = s2.find(nul);
// Are we at the end of either s1 or s2?
if (i1 == StringType::npos || i2 == StringType::npos) {
return i1 == i2;
}
// Are the tails equal?
return <API key>(s1.substr(i1 + 1), s2.substr(i2 + 1));
}
// String matchers.
// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
template <typename StringType>
class StrEqualityMatcher {
public:
typedef typename StringType::const_pointer ConstCharPointer;
StrEqualityMatcher(const StringType& str, bool expect_eq,
bool case_sensitive)
: string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
// When expect_eq_ is true, returns true iff s is equal to string_;
// otherwise returns true iff s is not equal to string_.
bool MatchAndExplain(ConstCharPointer s,
MatchResultListener* listener) const {
if (s == NULL) {
return !expect_eq_;
}
return MatchAndExplain(StringType(s), listener);
}
bool MatchAndExplain(const StringType& s,
MatchResultListener* /* listener */) const {
const bool eq = case_sensitive_ ? s == string_ :
<API key>(s, string_);
return expect_eq_ == eq;
}
void DescribeTo(::std::ostream* os) const {
DescribeToHelper(expect_eq_, os);
}
void DescribeNegationTo(::std::ostream* os) const {
DescribeToHelper(!expect_eq_, os);
}
private:
void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
*os << (expect_eq ? "is " : "isn't ");
*os << "equal to ";
if (!case_sensitive_) {
*os << "(ignoring case) ";
}
UniversalPrint(string_, os);
}
const StringType string_;
const bool expect_eq_;
const bool case_sensitive_;
<API key>(StrEqualityMatcher);
};
// Implements the polymorphic HasSubstr(substring) matcher, which
// can be used as a Matcher<T> as long as T can be converted to a
// string.
template <typename StringType>
class HasSubstrMatcher {
public:
typedef typename StringType::const_pointer ConstCharPointer;
explicit HasSubstrMatcher(const StringType& substring)
: substring_(substring) {}
// These overloaded methods allow HasSubstr(substring) to be used as a
// Matcher<T> as long as T can be converted to string. Returns true
// iff s contains substring_ as a substring.
bool MatchAndExplain(ConstCharPointer s,
MatchResultListener* listener) const {
return s != NULL && MatchAndExplain(StringType(s), listener);
}
bool MatchAndExplain(const StringType& s,
MatchResultListener* /* listener */) const {
return s.find(substring_) != StringType::npos;
}
// Describes what this matcher matches.
void DescribeTo(::std::ostream* os) const {
*os << "has substring ";
UniversalPrint(substring_, os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "has no substring ";
UniversalPrint(substring_, os);
}
private:
const StringType substring_;
<API key>(HasSubstrMatcher);
};
// Implements the polymorphic StartsWith(substring) matcher, which
// can be used as a Matcher<T> as long as T can be converted to a
// string.
template <typename StringType>
class StartsWithMatcher {
public:
typedef typename StringType::const_pointer ConstCharPointer;
explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
}
// These overloaded methods allow StartsWith(prefix) to be used as a
// Matcher<T> as long as T can be converted to string. Returns true
// iff s starts with prefix_.
bool MatchAndExplain(ConstCharPointer s,
MatchResultListener* listener) const {
return s != NULL && MatchAndExplain(StringType(s), listener);
}
bool MatchAndExplain(const StringType& s,
MatchResultListener* /* listener */) const {
return s.length() >= prefix_.length() &&
s.substr(0, prefix_.length()) == prefix_;
}
void DescribeTo(::std::ostream* os) const {
*os << "starts with ";
UniversalPrint(prefix_, os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't start with ";
UniversalPrint(prefix_, os);
}
private:
const StringType prefix_;
<API key>(StartsWithMatcher);
};
// Implements the polymorphic EndsWith(substring) matcher, which
// can be used as a Matcher<T> as long as T can be converted to a
// string.
template <typename StringType>
class EndsWithMatcher {
public:
typedef typename StringType::const_pointer ConstCharPointer;
explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
// These overloaded methods allow EndsWith(suffix) to be used as a
// Matcher<T> as long as T can be converted to string. Returns true
// iff s ends with suffix_.
bool MatchAndExplain(ConstCharPointer s,
MatchResultListener* listener) const {
return s != NULL && MatchAndExplain(StringType(s), listener);
}
bool MatchAndExplain(const StringType& s,
MatchResultListener* /* listener */) const {
return s.length() >= suffix_.length() &&
s.substr(s.length() - suffix_.length()) == suffix_;
}
void DescribeTo(::std::ostream* os) const {
*os << "ends with ";
UniversalPrint(suffix_, os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't end with ";
UniversalPrint(suffix_, os);
}
private:
const StringType suffix_;
<API key>(EndsWithMatcher);
};
// Implements polymorphic matchers MatchesRegex(regex) and
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
// T can be converted to a string.
class MatchesRegexMatcher {
public:
MatchesRegexMatcher(const RE* regex, bool full_match)
: regex_(regex), full_match_(full_match) {}
// These overloaded methods allow MatchesRegex(regex) to be used as
// a Matcher<T> as long as T can be converted to string. Returns
// true iff s matches regular expression regex. When full_match_ is
// true, a full match is done; otherwise a partial match is done.
bool MatchAndExplain(const char* s,
MatchResultListener* listener) const {
return s != NULL && MatchAndExplain(internal::string(s), listener);
}
bool MatchAndExplain(const internal::string& s,
MatchResultListener* /* listener */) const {
return full_match_ ? RE::FullMatch(s, *regex_) :
RE::PartialMatch(s, *regex_);
}
void DescribeTo(::std::ostream* os) const {
*os << (full_match_ ? "matches" : "contains")
<< " regular expression ";
UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't " << (full_match_ ? "match" : "contain")
<< " regular expression ";
UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
}
private:
const internal::linked_ptr<const RE> regex_;
const bool full_match_;
<API key>(MatchesRegexMatcher);
};
// Implements a matcher that compares the two fields of a 2-tuple
// using one of the ==, <=, <, etc, operators. The two fields being
// compared don't have to have the same type.
// The matcher defined here is polymorphic (for example, Eq() can be
// used to match a tuple<int, short>, a tuple<const long&, double>,
// etc). Therefore we use a template type conversion operator in the
// implementation.
// We define this as a macro in order to eliminate duplicated source
// code.
#define <API key>(name, op, relation) \
class name##2Matcher { \
public: \
template <typename T1, typename T2> \
operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
} \
template <typename T1, typename T2> \
operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
} \
private: \
template <typename Tuple> \
class Impl : public MatcherInterface<Tuple> { \
public: \
virtual bool MatchAndExplain( \
Tuple args, \
MatchResultListener* /* listener */) const { \
return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
} \
virtual void DescribeTo(::std::ostream* os) const { \
*os << "are " relation; \
} \
virtual void DescribeNegationTo(::std::ostream* os) const { \
*os << "aren't " relation; \
} \
}; \
}
// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
<API key>(Eq, ==, "an equal pair");
<API key>(
Ge, >=, "a pair where the first >= the second");
<API key>(
Gt, >, "a pair where the first > the second");
<API key>(
Le, <=, "a pair where the first <= the second");
<API key>(
Lt, <, "a pair where the first < the second");
<API key>(Ne, !=, "an unequal pair");
#undef <API key>
// Implements the Not(...) matcher for a particular argument type T.
// We do not nest it inside the NotMatcher class template, as that
// will prevent different instantiations of NotMatcher from sharing
// the same NotMatcherImpl<T> class.
template <typename T>
class NotMatcherImpl : public MatcherInterface<T> {
public:
explicit NotMatcherImpl(const Matcher<T>& matcher)
: matcher_(matcher) {}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
return !matcher_.MatchAndExplain(x, listener);
}
virtual void DescribeTo(::std::ostream* os) const {
matcher_.DescribeNegationTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
matcher_.DescribeTo(os);
}
private:
const Matcher<T> matcher_;
<API key>(NotMatcherImpl);
};
// Implements the Not(m) matcher, which matches a value that doesn't
// match matcher m.
template <typename InnerMatcher>
class NotMatcher {
public:
explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
// This template type conversion operator allows Not(m) to be used
// to match any type m can match.
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
}
private:
InnerMatcher matcher_;
<API key>(NotMatcher);
};
// Implements the AllOf(m1, m2) matcher for a particular argument type
// T. We do not nest it inside the BothOfMatcher class template, as
// that will prevent different instantiations of BothOfMatcher from
// sharing the same BothOfMatcherImpl<T> class.
template <typename T>
class BothOfMatcherImpl : public MatcherInterface<T> {
public:
BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeTo(os);
*os << ") and (";
matcher2_.DescribeTo(os);
*os << ")";
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeNegationTo(os);
*os << ") or (";
matcher2_.DescribeNegationTo(os);
*os << ")";
}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
// If either matcher1_ or matcher2_ doesn't match x, we only need
// to explain why one of them fails.
<API key> listener1;
if (!matcher1_.MatchAndExplain(x, &listener1)) {
*listener << listener1.str();
return false;
}
<API key> listener2;
if (!matcher2_.MatchAndExplain(x, &listener2)) {
*listener << listener2.str();
return false;
}
// Otherwise we need to explain why *both* of them match.
const internal::string s1 = listener1.str();
const internal::string s2 = listener2.str();
if (s1 == "") {
*listener << s2;
} else {
*listener << s1;
if (s2 != "") {
*listener << ", and " << s2;
}
}
return true;
}
private:
const Matcher<T> matcher1_;
const Matcher<T> matcher2_;
<API key>(BothOfMatcherImpl);
};
// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
// matches a value that matches all of the matchers m_1, ..., and m_n.
template <typename Matcher1, typename Matcher2>
class BothOfMatcher {
public:
BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
// This template type conversion operator allows a
// BothOfMatcher<Matcher1, Matcher2> object to match any type that
// both Matcher1 and Matcher2 can match.
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
SafeMatcherCast<T>(matcher2_)));
}
private:
Matcher1 matcher1_;
Matcher2 matcher2_;
<API key>(BothOfMatcher);
};
// Implements the AnyOf(m1, m2) matcher for a particular argument type
// T. We do not nest it inside the AnyOfMatcher class template, as
// that will prevent different instantiations of AnyOfMatcher from
// sharing the same EitherOfMatcherImpl<T> class.
template <typename T>
class EitherOfMatcherImpl : public MatcherInterface<T> {
public:
EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeTo(os);
*os << ") or (";
matcher2_.DescribeTo(os);
*os << ")";
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "(";
matcher1_.DescribeNegationTo(os);
*os << ") and (";
matcher2_.DescribeNegationTo(os);
*os << ")";
}
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
// If either matcher1_ or matcher2_ matches x, we just need to
// explain why *one* of them matches.
<API key> listener1;
if (matcher1_.MatchAndExplain(x, &listener1)) {
*listener << listener1.str();
return true;
}
<API key> listener2;
if (matcher2_.MatchAndExplain(x, &listener2)) {
*listener << listener2.str();
return true;
}
// Otherwise we need to explain why *both* of them fail.
const internal::string s1 = listener1.str();
const internal::string s2 = listener2.str();
if (s1 == "") {
*listener << s2;
} else {
*listener << s1;
if (s2 != "") {
*listener << ", and " << s2;
}
}
return false;
}
private:
const Matcher<T> matcher1_;
const Matcher<T> matcher2_;
<API key>(EitherOfMatcherImpl);
};
// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
// matches a value that matches at least one of the matchers m_1, ...,
// and m_n.
template <typename Matcher1, typename Matcher2>
class EitherOfMatcher {
public:
EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
: matcher1_(matcher1), matcher2_(matcher2) {}
// This template type conversion operator allows a
// EitherOfMatcher<Matcher1, Matcher2> object to match any type that
// both Matcher1 and Matcher2 can match.
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new EitherOfMatcherImpl<T>(
SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
}
private:
Matcher1 matcher1_;
Matcher2 matcher2_;
<API key>(EitherOfMatcher);
};
// Used for implementing Truly(pred), which turns a predicate into a
// matcher.
template <typename Predicate>
class TrulyMatcher {
public:
explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
// This method template allows Truly(pred) to be used as a matcher
// for type T where T is the argument type of predicate 'pred'. The
// argument is passed by reference as the predicate may be
// interested in the address of the argument.
template <typename T>
bool MatchAndExplain(T& x, // NOLINT
MatchResultListener* /* listener */) const {
#if GTEST_OS_WINDOWS
// MSVC warns about converting a value into bool (warning 4800).
#pragma warning(push) // Saves the current warning state.
#pragma warning(disable:4800) // Temporarily disables warning 4800.
#endif // GTEST_OS_WINDOWS
return predicate_(x);
#if GTEST_OS_WINDOWS
#pragma warning(pop) // Restores the warning state.
#endif // GTEST_OS_WINDOWS
}
void DescribeTo(::std::ostream* os) const {
*os << "satisfies the given predicate";
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't satisfy the given predicate";
}
private:
Predicate predicate_;
<API key>(TrulyMatcher);
};
// Used for implementing Matches(matcher), which turns a matcher into
// a predicate.
template <typename M>
class MatcherAsPredicate {
public:
explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
// This template operator() allows Matches(m) to be used as a
// predicate on type T where m is a matcher on type T.
// The argument x is passed by reference instead of by value, as
// some matcher may be interested in its address (e.g. as in
// Matches(Ref(n))(x)).
template <typename T>
bool operator()(const T& x) const {
// We let matcher_ commit to a particular type here instead of
// when the MatcherAsPredicate object was constructed. This
// allows us to write Matches(m) where m is a polymorphic matcher
// (e.g. Eq(5)).
// If we write Matcher<T>(matcher_).Matches(x) here, it won't
// compile when matcher_ has type Matcher<const T&>; if we write
// Matcher<const T&>(matcher_).Matches(x) here, it won't compile
// when matcher_ has type Matcher<T>; if we just write
// matcher_.Matches(x), it won't compile when matcher_ is
// polymorphic, e.g. Eq(5).
// MatcherCast<const T&>() is necessary for making the code work
// in all of the above situations.
return MatcherCast<const T&>(matcher_).Matches(x);
}
private:
M matcher_;
<API key>(MatcherAsPredicate);
};
// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
// argument M must be a type that can be converted to a matcher.
template <typename M>
class <API key> {
public:
explicit <API key>(const M& m) : matcher_(m) {}
// This template () operator allows a <API key>
// object to act as a predicate-formatter suitable for using with
// Google Test's EXPECT_PRED_FORMAT1() macro.
template <typename T>
AssertionResult operator()(const char* value_text, const T& x) const {
// We convert matcher_ to a Matcher<const T&> *now* instead of
// when the <API key> object was constructed,
// as matcher_ may be polymorphic (e.g. NotNull()) and we won't
// know which type to instantiate it to until we actually see the
// type of x here.
// We write MatcherCast<const T&>(matcher_) instead of
// Matcher<const T&>(matcher_), as the latter won't compile when
// matcher_ has type Matcher<T> (e.g. An<int>()).
const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
<API key> listener;
if (<API key>(x, matcher, &listener))
return AssertionSuccess();
::std::stringstream ss;
ss << "Value of: " << value_text << "\n"
<< "Expected: ";
matcher.DescribeTo(&ss);
ss << "\n Actual: " << listener.str();
return AssertionFailure() << ss.str();
}
private:
const M matcher_;
<API key>(<API key>);
};
// A helper function for converting a matcher to a predicate-formatter
// without the user needing to explicitly write the type. This is
// used for implementing ASSERT_THAT() and EXPECT_THAT().
template <typename M>
inline <API key><M>
<API key>(const M& matcher) {
return <API key><M>(matcher);
}
// Implements the polymorphic floating point equality matcher, which
// matches two float values using ULP-based approximation. The
// template is meant to be instantiated with FloatType being either
// float or double.
template <typename FloatType>
class FloatingEqMatcher {
public:
// Constructor for FloatingEqMatcher.
// The matcher's input will be compared with rhs. The matcher treats two
// NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
// equality comparisons between NANs will always return false.
FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
// Implements floating point equality matcher as a Matcher<T>.
template <typename T>
class Impl : public MatcherInterface<T> {
public:
Impl(FloatType rhs, bool nan_eq_nan) :
rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
virtual bool MatchAndExplain(T value,
MatchResultListener* /* listener */) const {
const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
// Compares NaNs first, if nan_eq_nan_ is true.
if (nan_eq_nan_ && lhs.is_nan()) {
return rhs.is_nan();
}
return lhs.AlmostEquals(rhs);
}
virtual void DescribeTo(::std::ostream* os) const {
// os->precision() returns the previously set precision, which we
// store to restore the ostream to its original configuration
// after outputting.
const ::std::streamsize old_precision = os->precision(
::std::numeric_limits<FloatType>::digits10 + 2);
if (FloatingPoint<FloatType>(rhs_).is_nan()) {
if (nan_eq_nan_) {
*os << "is NaN";
} else {
*os << "never matches";
}
} else {
*os << "is approximately " << rhs_;
}
os->precision(old_precision);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
// As before, get original precision.
const ::std::streamsize old_precision = os->precision(
::std::numeric_limits<FloatType>::digits10 + 2);
if (FloatingPoint<FloatType>(rhs_).is_nan()) {
if (nan_eq_nan_) {
*os << "isn't NaN";
} else {
*os << "is anything";
}
} else {
*os << "isn't approximately " << rhs_;
}
// Restore original precision.
os->precision(old_precision);
}
private:
const FloatType rhs_;
const bool nan_eq_nan_;
<API key>(Impl);
};
// The following 3 type conversion operators allow FloatEq(rhs) and
// NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
// Matcher<const float&>, or a Matcher<float&>, but nothing else.
// (While Google's C++ coding style doesn't allow arguments passed
// by non-const reference, we may see them in code not conforming to
// the style. Therefore Google Mock needs to support them.)
operator Matcher<FloatType>() const {
return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
}
operator Matcher<const FloatType&>() const {
return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
}
operator Matcher<FloatType&>() const {
return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
}
private:
const FloatType rhs_;
const bool nan_eq_nan_;
<API key>(FloatingEqMatcher);
};
// Implements the Pointee(m) matcher for matching a pointer whose
// pointee matches matcher m. The pointer can be either raw or smart.
template <typename InnerMatcher>
class PointeeMatcher {
public:
explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
// This type conversion operator template allows Pointee(m) to be
// used as a matcher for any pointer type whose pointee type is
// compatible with the inner matcher, where type Pointer can be
// either a raw pointer or a smart pointer.
// The reason we do this instead of relying on
// <API key>() is that the latter is not flexible
// enough for implementing the DescribeTo() method of Pointee().
template <typename Pointer>
operator Matcher<Pointer>() const {
return MakeMatcher(new Impl<Pointer>(matcher_));
}
private:
// The monomorphic implementation that works for a particular pointer type.
template <typename Pointer>
class Impl : public MatcherInterface<Pointer> {
public:
typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
<API key>(Pointer))>::type Pointee;
explicit Impl(const InnerMatcher& matcher)
: matcher_(MatcherCast<const Pointee&>(matcher)) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "points to a value that ";
matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "does not point to a value that ";
matcher_.DescribeTo(os);
}
virtual bool MatchAndExplain(Pointer pointer,
MatchResultListener* listener) const {
if (GetRawPointer(pointer) == NULL)
return false;
*listener << "which points to ";
return <API key>(*pointer, matcher_, listener);
}
private:
const Matcher<const Pointee&> matcher_;
<API key>(Impl);
};
const InnerMatcher matcher_;
<API key>(PointeeMatcher);
};
// Implements the Field() matcher for matching a field (i.e. member
// variable) of an object.
template <typename Class, typename FieldType>
class FieldMatcher {
public:
FieldMatcher(FieldType Class::*field,
const Matcher<const FieldType&>& matcher)
: field_(field), matcher_(matcher) {}
void DescribeTo(::std::ostream* os) const {
*os << "is an object whose given field ";
matcher_.DescribeTo(os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "is an object whose given field ";
matcher_.DescribeNegationTo(os);
}
template <typename T>
bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
return MatchAndExplainImpl(
typename ::testing::internal::
is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
value, listener);
}
private:
// The first argument of MatchAndExplainImpl() is needed to help
// Symbian's C++ compiler choose which overload to use. Its type is
// true_type iff the Field() matcher is used to match a pointer.
bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
MatchResultListener* listener) const {
*listener << "whose given field is ";
return <API key>(obj.*field_, matcher_, listener);
}
bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
MatchResultListener* listener) const {
if (p == NULL)
return false;
*listener << "which points to an object ";
// Since *p has a field, it must be a class/struct/union type and
// thus cannot be a pointer. Therefore we pass false_type() as
// the first argument.
return MatchAndExplainImpl(false_type(), *p, listener);
}
const FieldType Class::*field_;
const Matcher<const FieldType&> matcher_;
<API key>(FieldMatcher);
};
// Implements the Property() matcher for matching a property
// (i.e. return value of a getter method) of an object.
template <typename Class, typename PropertyType>
class PropertyMatcher {
public:
// The property may have a reference type, so 'const PropertyType&'
// may cause double references and fail to compile. That's why we
// need <API key>, which works regardless of
// PropertyType being a reference or not.
typedef <API key>(PropertyType) RefToConstProperty;
PropertyMatcher(PropertyType (Class::*property)() const,
const Matcher<RefToConstProperty>& matcher)
: property_(property), matcher_(matcher) {}
void DescribeTo(::std::ostream* os) const {
*os << "is an object whose given property ";
matcher_.DescribeTo(os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "is an object whose given property ";
matcher_.DescribeNegationTo(os);
}
template <typename T>
bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
return MatchAndExplainImpl(
typename ::testing::internal::
is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
value, listener);
}
private:
// The first argument of MatchAndExplainImpl() is needed to help
// Symbian's C++ compiler choose which overload to use. Its type is
// true_type iff the Property() matcher is used to match a pointer.
bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
MatchResultListener* listener) const {
*listener << "whose given property is ";
// Cannot pass the return value (for example, int) to <API key>,
// which takes a non-const reference as argument.
RefToConstProperty result = (obj.*property_)();
return <API key>(result, matcher_, listener);
}
bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
MatchResultListener* listener) const {
if (p == NULL)
return false;
*listener << "which points to an object ";
// Since *p has a property method, it must be a class/struct/union
// type and thus cannot be a pointer. Therefore we pass
// false_type() as the first argument.
return MatchAndExplainImpl(false_type(), *p, listener);
}
PropertyType (Class::*property_)() const;
const Matcher<RefToConstProperty> matcher_;
<API key>(PropertyMatcher);
};
// Type traits specifying various features of different functors for ResultOf.
// The default template specifies features for functor objects.
// Functor classes have to typedef argument_type and result_type
// to be compatible with ResultOf.
template <typename Functor>
struct CallableTraits {
typedef typename Functor::result_type ResultType;
typedef Functor StorageType;
static void CheckIsValid(Functor /* functor */) {}
template <typename T>
static ResultType Invoke(Functor f, T arg) { return f(arg); }
};
// Specialization for function pointers.
template <typename ArgType, typename ResType>
struct CallableTraits<ResType(*)(ArgType)> {
typedef ResType ResultType;
typedef ResType(*StorageType)(ArgType);
static void CheckIsValid(ResType(*f)(ArgType)) {
GTEST_CHECK_(f != NULL)
<< "NULL function pointer is passed into ResultOf().";
}
template <typename T>
static ResType Invoke(ResType(*f)(ArgType), T arg) {
return (*f)(arg);
}
};
// Implements the ResultOf() matcher for matching a return value of a
// unary function of an object.
template <typename Callable>
class ResultOfMatcher {
public:
typedef typename CallableTraits<Callable>::ResultType ResultType;
ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
: callable_(callable), matcher_(matcher) {
CallableTraits<Callable>::CheckIsValid(callable_);
}
template <typename T>
operator Matcher<T>() const {
return Matcher<T>(new Impl<T>(callable_, matcher_));
}
private:
typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
template <typename T>
class Impl : public MatcherInterface<T> {
public:
Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
: callable_(callable), matcher_(matcher) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "is mapped by the given callable to a value that ";
matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "is mapped by the given callable to a value that ";
matcher_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
*listener << "which is mapped by the given callable to ";
// Cannot pass the return value (for example, int) to
// <API key>, which takes a non-const reference as argument.
ResultType result =
CallableTraits<Callable>::template Invoke<T>(callable_, obj);
return <API key>(result, matcher_, listener);
}
private:
// Functors often define operator() as non-const method even though
// they are actualy stateless. But we need to use them even when
// 'this' is a const pointer. It's the user's responsibility not to
// use stateful callables with ResultOf(), which does't guarantee
// how many times the callable will be invoked.
mutable CallableStorageType callable_;
const Matcher<ResultType> matcher_;
<API key>(Impl);
}; // class Impl
const CallableStorageType callable_;
const Matcher<ResultType> matcher_;
<API key>(ResultOfMatcher);
};
// Implements an equality matcher for any STL-style container whose elements
// support ==. This matcher is like Eq(), but its failure explanations provide
// more detailed information that is useful when the container is used as a set.
// The failure message reports elements that are in one of the operands but not
// the other. The failure messages do not report duplicate or out-of-order
// elements in the containers (which don't properly matter to sets, but can
// occur if the containers are vectors or lists, for example).
// Uses the container's const_iterator, value_type, operator ==,
// begin(), and end().
template <typename Container>
class ContainerEqMatcher {
public:
typedef internal::StlContainerView<Container> View;
typedef typename View::type StlContainer;
typedef typename View::const_reference <API key>;
// We make a copy of rhs in case the elements in it are modified
// after this matcher is created.
explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
// Makes sure the user doesn't instantiate this class template
// with a const or reference type.
(void)testing::StaticAssertTypeEq<Container,
<API key>(Container)>();
}
void DescribeTo(::std::ostream* os) const {
*os << "equals ";
UniversalPrint(rhs_, os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "does not equal ";
UniversalPrint(rhs_, os);
}
template <typename LhsContainer>
bool MatchAndExplain(const LhsContainer& lhs,
MatchResultListener* listener) const {
// GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
// that causes LhsContainer to be a const type sometimes.
typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
LhsView;
typedef typename LhsView::type LhsStlContainer;
<API key> lhs_stl_container = LhsView::ConstReference(lhs);
if (lhs_stl_container == rhs_)
return true;
::std::ostream* const os = listener->stream();
if (os != NULL) {
// Something is different. Check for extra values first.
bool printed_header = false;
for (typename LhsStlContainer::const_iterator it =
lhs_stl_container.begin();
it != lhs_stl_container.end(); ++it) {
if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
rhs_.end()) {
if (printed_header) {
*os << ", ";
} else {
*os << "which has these unexpected elements: ";
printed_header = true;
}
UniversalPrint(*it, os);
}
}
// Now check for missing values.
bool printed_header2 = false;
for (typename StlContainer::const_iterator it = rhs_.begin();
it != rhs_.end(); ++it) {
if (internal::ArrayAwareFind(
lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
lhs_stl_container.end()) {
if (printed_header2) {
*os << ", ";
} else {
*os << (printed_header ? ",\nand" : "which")
<< " doesn't have these expected elements: ";
printed_header2 = true;
}
UniversalPrint(*it, os);
}
}
}
return false;
}
private:
const StlContainer rhs_;
<API key>(ContainerEqMatcher);
};
// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
// must be able to be safely cast to Matcher<tuple<const T1&, const
// T2&> >, where T1 and T2 are the types of elements in the LHS
// container and the RHS container respectively.
template <typename TupleMatcher, typename RhsContainer>
class PointwiseMatcher {
public:
typedef internal::StlContainerView<RhsContainer> RhsView;
typedef typename RhsView::type RhsStlContainer;
typedef typename RhsStlContainer::value_type RhsValue;
// Like ContainerEq, we make a copy of rhs in case the elements in
// it are modified after this matcher is created.
PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
: tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
// Makes sure the user doesn't instantiate this class template
// with a const or reference type.
(void)testing::StaticAssertTypeEq<RhsContainer,
<API key>(RhsContainer)>();
}
template <typename LhsContainer>
operator Matcher<LhsContainer>() const {
return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
}
template <typename LhsContainer>
class Impl : public MatcherInterface<LhsContainer> {
public:
typedef internal::StlContainerView<
<API key>(LhsContainer)> LhsView;
typedef typename LhsView::type LhsStlContainer;
typedef typename LhsView::const_reference <API key>;
typedef typename LhsStlContainer::value_type LhsValue;
// We pass the LHS value and the RHS value to the inner matcher by
// reference, as they may be expensive to copy. We must use tuple
// instead of pair here, as a pair cannot hold references (C++ 98,
// 20.2.2 [lib.pairs]).
typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
// mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
: mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
rhs_(rhs) {}
virtual void DescribeTo(::std::ostream* os) const {
*os << "contains " << rhs_.size()
<< " values, where each value and its corresponding value in ";
UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
*os << " ";
mono_tuple_matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't contain exactly " << rhs_.size()
<< " values, or contains a value x at some index i"
<< " where x and the i-th value of ";
UniversalPrint(rhs_, os);
*os << " ";
mono_tuple_matcher_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(LhsContainer lhs,
MatchResultListener* listener) const {
<API key> lhs_stl_container = LhsView::ConstReference(lhs);
const size_t actual_size = lhs_stl_container.size();
if (actual_size != rhs_.size()) {
*listener << "which contains " << actual_size << " values";
return false;
}
typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
typename RhsStlContainer::const_iterator right = rhs_.begin();
for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
const InnerMatcherArg value_pair(*left, *right);
if (listener->IsInterested()) {
<API key> inner_listener;
if (!mono_tuple_matcher_.MatchAndExplain(
value_pair, &inner_listener)) {
*listener << "where the value pair (";
UniversalPrint(*left, listener->stream());
*listener << ", ";
UniversalPrint(*right, listener->stream());
*listener << ") at index #" << i << " don't match";
PrintIfNotEmpty(inner_listener.str(), listener->stream());
return false;
}
} else {
if (!mono_tuple_matcher_.Matches(value_pair))
return false;
}
}
return true;
}
private:
const Matcher<InnerMatcherArg> mono_tuple_matcher_;
const RhsStlContainer rhs_;
<API key>(Impl);
};
private:
const TupleMatcher tuple_matcher_;
const RhsStlContainer rhs_;
<API key>(PointwiseMatcher);
};
// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
template <typename Container>
class <API key> : public MatcherInterface<Container> {
public:
typedef <API key>(Container) RawContainer;
typedef StlContainerView<RawContainer> View;
typedef typename View::type StlContainer;
typedef typename View::const_reference <API key>;
typedef typename StlContainer::value_type Element;
template <typename InnerMatcher>
explicit <API key>(InnerMatcher inner_matcher)
: inner_matcher_(
testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
// Checks whether:
// * All elements in the container match, if <API key>.
// * Any element in the container matches, if !<API key>.
bool MatchAndExplainImpl(bool <API key>,
Container container,
MatchResultListener* listener) const {
<API key> stl_container = View::ConstReference(container);
size_t i = 0;
for (typename StlContainer::const_iterator it = stl_container.begin();
it != stl_container.end(); ++it, ++i) {
<API key> inner_listener;
const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
if (matches != <API key>) {
*listener << "whose element
<< (matches ? " matches" : " doesn't match");
PrintIfNotEmpty(inner_listener.str(), listener->stream());
return !<API key>;
}
}
return <API key>;
}
protected:
const Matcher<const Element&> inner_matcher_;
<API key>(<API key>);
};
// Implements Contains(element_matcher) for the given argument type Container.
// Symmetric to EachMatcherImpl.
template <typename Container>
class ContainsMatcherImpl : public <API key><Container> {
public:
template <typename InnerMatcher>
explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
: <API key><Container>(inner_matcher) {}
// Describes what this matcher does.
virtual void DescribeTo(::std::ostream* os) const {
*os << "contains at least one element that ";
this->inner_matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't contain any element that ";
this->inner_matcher_.DescribeTo(os);
}
virtual bool MatchAndExplain(Container container,
MatchResultListener* listener) const {
return this->MatchAndExplainImpl(false, container, listener);
}
private:
<API key>(ContainsMatcherImpl);
};
// Implements Each(element_matcher) for the given argument type Container.
// Symmetric to ContainsMatcherImpl.
template <typename Container>
class EachMatcherImpl : public <API key><Container> {
public:
template <typename InnerMatcher>
explicit EachMatcherImpl(InnerMatcher inner_matcher)
: <API key><Container>(inner_matcher) {}
// Describes what this matcher does.
virtual void DescribeTo(::std::ostream* os) const {
*os << "only contains elements that ";
this->inner_matcher_.DescribeTo(os);
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "contains some element that ";
this->inner_matcher_.DescribeNegationTo(os);
}
virtual bool MatchAndExplain(Container container,
MatchResultListener* listener) const {
return this->MatchAndExplainImpl(true, container, listener);
}
private:
<API key>(EachMatcherImpl);
};
// Implements polymorphic Contains(element_matcher).
template <typename M>
class ContainsMatcher {
public:
explicit ContainsMatcher(M m) : inner_matcher_(m) {}
template <typename Container>
operator Matcher<Container>() const {
return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
}
private:
const M inner_matcher_;
<API key>(ContainsMatcher);
};
// Implements polymorphic Each(element_matcher).
template <typename M>
class EachMatcher {
public:
explicit EachMatcher(M m) : inner_matcher_(m) {}
template <typename Container>
operator Matcher<Container>() const {
return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
}
private:
const M inner_matcher_;
<API key>(EachMatcher);
};
// Implements Key(inner_matcher) for the given argument pair type.
// Key(inner_matcher) matches an std::pair whose 'first' field matches
// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
// std::map that contains at least one element whose key is >= 5.
template <typename PairType>
class KeyMatcherImpl : public MatcherInterface<PairType> {
public:
typedef <API key>(PairType) RawPairType;
typedef typename RawPairType::first_type KeyType;
template <typename InnerMatcher>
explicit KeyMatcherImpl(InnerMatcher inner_matcher)
: inner_matcher_(
testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
}
// Returns true iff 'key_value.first' (the key) matches the inner matcher.
virtual bool MatchAndExplain(PairType key_value,
MatchResultListener* listener) const {
<API key> inner_listener;
const bool match = inner_matcher_.MatchAndExplain(key_value.first,
&inner_listener);
const internal::string explanation = inner_listener.str();
if (explanation != "") {
*listener << "whose first field is a value " << explanation;
}
return match;
}
// Describes what this matcher does.
virtual void DescribeTo(::std::ostream* os) const {
*os << "has a key that ";
inner_matcher_.DescribeTo(os);
}
// Describes what the negation of this matcher does.
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "doesn't have a key that ";
inner_matcher_.DescribeTo(os);
}
private:
const Matcher<const KeyType&> inner_matcher_;
<API key>(KeyMatcherImpl);
};
// Implements polymorphic Key(matcher_for_key).
template <typename M>
class KeyMatcher {
public:
explicit KeyMatcher(M m) : matcher_for_key_(m) {}
template <typename PairType>
operator Matcher<PairType>() const {
return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
}
private:
const M matcher_for_key_;
<API key>(KeyMatcher);
};
// Implements Pair(first_matcher, second_matcher) for the given argument pair
// type with its two matchers. See Pair() function below.
template <typename PairType>
class PairMatcherImpl : public MatcherInterface<PairType> {
public:
typedef <API key>(PairType) RawPairType;
typedef typename RawPairType::first_type FirstType;
typedef typename RawPairType::second_type SecondType;
template <typename FirstMatcher, typename SecondMatcher>
PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
: first_matcher_(
testing::SafeMatcherCast<const FirstType&>(first_matcher)),
second_matcher_(
testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
}
// Describes what this matcher does.
virtual void DescribeTo(::std::ostream* os) const {
*os << "has a first field that ";
first_matcher_.DescribeTo(os);
*os << ", and has a second field that ";
second_matcher_.DescribeTo(os);
}
// Describes what the negation of this matcher does.
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "has a first field that ";
first_matcher_.DescribeNegationTo(os);
*os << ", or has a second field that ";
second_matcher_.DescribeNegationTo(os);
}
// Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
// matches second_matcher.
virtual bool MatchAndExplain(PairType a_pair,
MatchResultListener* listener) const {
if (!listener->IsInterested()) {
// If the listener is not interested, we don't need to construct the
// explanation.
return first_matcher_.Matches(a_pair.first) &&
second_matcher_.Matches(a_pair.second);
}
<API key> <API key>;
if (!first_matcher_.MatchAndExplain(a_pair.first,
&<API key>)) {
*listener << "whose first field does not match";
PrintIfNotEmpty(<API key>.str(), listener->stream());
return false;
}
<API key> <API key>;
if (!second_matcher_.MatchAndExplain(a_pair.second,
&<API key>)) {
*listener << "whose second field does not match";
PrintIfNotEmpty(<API key>.str(), listener->stream());
return false;
}
ExplainSuccess(<API key>.str(), <API key>.str(),
listener);
return true;
}
private:
void ExplainSuccess(const internal::string& first_explanation,
const internal::string& second_explanation,
MatchResultListener* listener) const {
*listener << "whose both fields match";
if (first_explanation != "") {
*listener << ", where the first field is a value " << first_explanation;
}
if (second_explanation != "") {
*listener << ", ";
if (first_explanation != "") {
*listener << "and ";
} else {
*listener << "where ";
}
*listener << "the second field is a value " << second_explanation;
}
}
const Matcher<const FirstType&> first_matcher_;
const Matcher<const SecondType&> second_matcher_;
<API key>(PairMatcherImpl);
};
// Implements polymorphic Pair(first_matcher, second_matcher).
template <typename FirstMatcher, typename SecondMatcher>
class PairMatcher {
public:
PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
: first_matcher_(first_matcher), second_matcher_(second_matcher) {}
template <typename PairType>
operator Matcher<PairType> () const {
return MakeMatcher(
new PairMatcherImpl<PairType>(
first_matcher_, second_matcher_));
}
private:
const FirstMatcher first_matcher_;
const SecondMatcher second_matcher_;
<API key>(PairMatcher);
};
// Implements ElementsAre() and ElementsAreArray().
template <typename Container>
class <API key> : public MatcherInterface<Container> {
public:
typedef <API key>(Container) RawContainer;
typedef internal::StlContainerView<RawContainer> View;
typedef typename View::type StlContainer;
typedef typename View::const_reference <API key>;
typedef typename StlContainer::value_type Element;
// Constructs the matcher from a sequence of element values or
// element matchers.
template <typename InputIter>
<API key>(InputIter first, size_t a_count) {
matchers_.reserve(a_count);
InputIter it = first;
for (size_t i = 0; i != a_count; ++i, ++it) {
matchers_.push_back(MatcherCast<const Element&>(*it));
}
}
// Describes what this matcher does.
virtual void DescribeTo(::std::ostream* os) const {
if (count() == 0) {
*os << "is empty";
} else if (count() == 1) {
*os << "has 1 element that ";
matchers_[0].DescribeTo(os);
} else {
*os << "has " << Elements(count()) << " where\n";
for (size_t i = 0; i != count(); ++i) {
*os << "element
matchers_[i].DescribeTo(os);
if (i + 1 < count()) {
*os << ",\n";
}
}
}
}
// Describes what the negation of this matcher does.
virtual void DescribeNegationTo(::std::ostream* os) const {
if (count() == 0) {
*os << "isn't empty";
return;
}
*os << "doesn't have " << Elements(count()) << ", or\n";
for (size_t i = 0; i != count(); ++i) {
*os << "element
matchers_[i].DescribeNegationTo(os);
if (i + 1 < count()) {
*os << ", or\n";
}
}
}
virtual bool MatchAndExplain(Container container,
MatchResultListener* listener) const {
<API key> stl_container = View::ConstReference(container);
const size_t actual_count = stl_container.size();
if (actual_count != count()) {
// The element count doesn't match. If the container is empty,
// there's no need to explain anything as Google Mock already
// prints the empty container. Otherwise we just need to show
// how many elements there actually are.
if (actual_count != 0) {
*listener << "which has " << Elements(actual_count);
}
return false;
}
typename StlContainer::const_iterator it = stl_container.begin();
// explanations[i] is the explanation of the element at index i.
std::vector<internal::string> explanations(count());
for (size_t i = 0; i != count(); ++it, ++i) {
<API key> s;
if (matchers_[i].MatchAndExplain(*it, &s)) {
explanations[i] = s.str();
} else {
// The container has the right size but the i-th element
// doesn't match its expectation.
*listener << "whose element #" << i << " doesn't match";
PrintIfNotEmpty(s.str(), listener->stream());
return false;
}
}
// Every element matches its expectation. We need to explain why
// (the obvious ones can be skipped).
bool reason_printed = false;
for (size_t i = 0; i != count(); ++i) {
const internal::string& s = explanations[i];
if (!s.empty()) {
if (reason_printed) {
*listener << ",\nand ";
}
*listener << "whose element #" << i << " matches, " << s;
reason_printed = true;
}
}
return true;
}
private:
static Message Elements(size_t count) {
return Message() << count << (count == 1 ? " element" : " elements");
}
size_t count() const { return matchers_.size(); }
std::vector<Matcher<const Element&> > matchers_;
<API key>(<API key>);
};
// Implements ElementsAre() of 0 arguments.
class ElementsAreMatcher0 {
public:
ElementsAreMatcher0() {}
template <typename Container>
operator Matcher<Container>() const {
typedef <API key>(Container) RawContainer;
typedef typename internal::StlContainerView<RawContainer>::type::value_type
Element;
const Matcher<const Element&>* const matchers = NULL;
return MakeMatcher(new <API key><Container>(matchers, 0));
}
};
// Implements ElementsAreArray().
template <typename T>
class <API key> {
public:
<API key>(const T* first, size_t count) :
first_(first), count_(count) {}
template <typename Container>
operator Matcher<Container>() const {
typedef <API key>(Container) RawContainer;
typedef typename internal::StlContainerView<RawContainer>::type::value_type
Element;
return MakeMatcher(new <API key><Container>(first_, count_));
}
private:
const T* const first_;
const size_t count_;
<API key>(<API key>);
};
// Returns the description for a matcher defined using the MATCHER*()
// macro where the user-supplied description string is "", if
// 'negation' is false; otherwise returns the description of the
// negation of the matcher. 'param_values' contains a list of strings
// that are the print-out of the matcher's parameters.
string <API key>(bool negation, const char* matcher_name,
const Strings& param_values);
} // namespace internal
// Implements MatcherCast().
template <typename T, typename M>
inline Matcher<T> MatcherCast(M matcher) {
return internal::MatcherCastImpl<T, M>::Cast(matcher);
}
// _ is a matcher that matches anything of any type.
// This definition is fine as:
// 1. The C++ standard permits using the name _ in a namespace that
// is not the global namespace or ::std.
// 2. The AnythingMatcher class has no data member or constructor,
// so it's OK to create global variables of this type.
// 3. c-style has approved of using _ in this case.
const internal::AnythingMatcher _ = {};
// Creates a matcher that matches any value of the given type T.
template <typename T>
inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
// Creates a matcher that matches any value of the given type T.
template <typename T>
inline Matcher<T> An() { return A<T>(); }
// Creates a polymorphic matcher that matches anything equal to x.
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
// wouldn't compile.
template <typename T>
inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
// Constructs a Matcher<T> from a 'value' of type T. The constructed
// matcher matches any value that's equal to 'value'.
template <typename T>
Matcher<T>::Matcher(T value) { *this = Eq(value); }
// Creates a monomorphic matcher that matches anything with type Lhs
// and equal to rhs. A user may need to use this instead of Eq(...)
// in order to resolve an overloading ambiguity.
// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
// or Matcher<T>(x), but more readable than the latter.
// We could define similar monomorphic matchers for other comparison
// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
// it yet as those are used much less than Eq() in practice. A user
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
// for example.
template <typename Lhs, typename Rhs>
inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
// Creates a polymorphic matcher that matches anything >= x.
template <typename Rhs>
inline internal::GeMatcher<Rhs> Ge(Rhs x) {
return internal::GeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything > x.
template <typename Rhs>
inline internal::GtMatcher<Rhs> Gt(Rhs x) {
return internal::GtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything <= x.
template <typename Rhs>
inline internal::LeMatcher<Rhs> Le(Rhs x) {
return internal::LeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything < x.
template <typename Rhs>
inline internal::LtMatcher<Rhs> Lt(Rhs x) {
return internal::LtMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches anything != x.
template <typename Rhs>
inline internal::NeMatcher<Rhs> Ne(Rhs x) {
return internal::NeMatcher<Rhs>(x);
}
// Creates a polymorphic matcher that matches any NULL pointer.
inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
return <API key>(internal::IsNullMatcher());
}
// Creates a polymorphic matcher that matches any non-NULL pointer.
// This is convenient as Not(NULL) doesn't compile (the compiler
// thinks that that expression is comparing a pointer with an integer).
inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
return <API key>(internal::NotNullMatcher());
}
// Creates a polymorphic matcher that matches any argument that
// references variable x.
template <typename T>
inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
return internal::RefMatcher<T&>(x);
}
// Creates a matcher that matches any double argument approximately
// equal to rhs, where two NANs are considered unequal.
inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
return internal::FloatingEqMatcher<double>(rhs, false);
}
// Creates a matcher that matches any double argument approximately
// equal to rhs, including NaN values when rhs is NaN.
inline internal::FloatingEqMatcher<double> <API key>(double rhs) {
return internal::FloatingEqMatcher<double>(rhs, true);
}
// Creates a matcher that matches any float argument approximately
// equal to rhs, where two NANs are considered unequal.
inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
return internal::FloatingEqMatcher<float>(rhs, false);
}
// Creates a matcher that matches any double argument approximately
// equal to rhs, including NaN values when rhs is NaN.
inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
return internal::FloatingEqMatcher<float>(rhs, true);
}
// Creates a matcher that matches a pointer (raw or smart) that points
// to a value that matches inner_matcher.
template <typename InnerMatcher>
inline internal::PointeeMatcher<InnerMatcher> Pointee(
const InnerMatcher& inner_matcher) {
return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
}
// Creates a matcher that matches an object whose given field matches
// 'matcher'. For example,
// Field(&Foo::number, Ge(5))
// matches a Foo object x iff x.number >= 5.
template <typename Class, typename FieldType, typename FieldMatcher>
inline PolymorphicMatcher<
internal::FieldMatcher<Class, FieldType> > Field(
FieldType Class::*field, const FieldMatcher& matcher) {
return <API key>(
internal::FieldMatcher<Class, FieldType>(
field, MatcherCast<const FieldType&>(matcher)));
// The call to MatcherCast() is required for supporting inner
// matchers of compatible types. For example, it allows
// Field(&Foo::bar, m)
// to compile where bar is an int32 and m is a matcher for int64.
}
// Creates a matcher that matches an object whose given property
// matches 'matcher'. For example,
// Property(&Foo::str, StartsWith("hi"))
// matches a Foo object x iff x.str() starts with "hi".
template <typename Class, typename PropertyType, typename PropertyMatcher>
inline PolymorphicMatcher<
internal::PropertyMatcher<Class, PropertyType> > Property(
PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
return <API key>(
internal::PropertyMatcher<Class, PropertyType>(
property,
MatcherCast<<API key>(PropertyType)>(matcher)));
// The call to MatcherCast() is required for supporting inner
// matchers of compatible types. For example, it allows
// Property(&Foo::bar, m)
// to compile where bar() returns an int32 and m is a matcher for int64.
}
// Creates a matcher that matches an object iff the result of applying
// a callable to x matches 'matcher'.
// For example,
// ResultOf(f, StartsWith("hi"))
// matches a Foo object x iff f(x) starts with "hi".
// callable parameter can be a function, function pointer, or a functor.
// Callable has to satisfy the following conditions:
// * It is required to keep no state affecting the results of
// the calls on it and make no assumptions about how many calls
// will be made. Any state it keeps must be protected from the
// concurrent access.
// * If it is a function object, it has to define type result_type.
// We recommend deriving your functor classes from std::unary_function.
template <typename Callable, typename ResultOfMatcher>
internal::ResultOfMatcher<Callable> ResultOf(
Callable callable, const ResultOfMatcher& matcher) {
return internal::ResultOfMatcher<Callable>(
callable,
MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
matcher));
// The call to MatcherCast() is required for supporting inner
// matchers of compatible types. For example, it allows
// ResultOf(Function, m)
// to compile where Function() returns an int32 and m is a matcher for int64.
}
// String matchers.
// Matches a string equal to str.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
StrEq(const internal::string& str) {
return <API key>(internal::StrEqualityMatcher<internal::string>(
str, true, true));
}
// Matches a string not equal to str.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
StrNe(const internal::string& str) {
return <API key>(internal::StrEqualityMatcher<internal::string>(
str, false, true));
}
// Matches a string equal to str, ignoring case.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
StrCaseEq(const internal::string& str) {
return <API key>(internal::StrEqualityMatcher<internal::string>(
str, true, false));
}
// Matches a string not equal to str, ignoring case.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
StrCaseNe(const internal::string& str) {
return <API key>(internal::StrEqualityMatcher<internal::string>(
str, false, false));
}
// Creates a matcher that matches any string, std::string, or C string
// that contains the given substring.
inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
HasSubstr(const internal::string& substring) {
return <API key>(internal::HasSubstrMatcher<internal::string>(
substring));
}
// Matches a string that starts with 'prefix' (case-sensitive).
inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
StartsWith(const internal::string& prefix) {
return <API key>(internal::StartsWithMatcher<internal::string>(
prefix));
}
// Matches a string that ends with 'suffix' (case-sensitive).
inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
EndsWith(const internal::string& suffix) {
return <API key>(internal::EndsWithMatcher<internal::string>(
suffix));
}
// Matches a string that fully matches regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::RE* regex) {
return <API key>(internal::MatchesRegexMatcher(regex, true));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
const internal::string& regex) {
return MatchesRegex(new internal::RE(regex));
}
// Matches a string that contains regular expression 'regex'.
// The matcher takes ownership of 'regex'.
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::RE* regex) {
return <API key>(internal::MatchesRegexMatcher(regex, false));
}
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
const internal::string& regex) {
return ContainsRegex(new internal::RE(regex));
}
#if <API key> || <API key>
// Wide string matchers.
// Matches a string equal to str.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
StrEq(const internal::wstring& str) {
return <API key>(internal::StrEqualityMatcher<internal::wstring>(
str, true, true));
}
// Matches a string not equal to str.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
StrNe(const internal::wstring& str) {
return <API key>(internal::StrEqualityMatcher<internal::wstring>(
str, false, true));
}
// Matches a string equal to str, ignoring case.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
StrCaseEq(const internal::wstring& str) {
return <API key>(internal::StrEqualityMatcher<internal::wstring>(
str, true, false));
}
// Matches a string not equal to str, ignoring case.
inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
StrCaseNe(const internal::wstring& str) {
return <API key>(internal::StrEqualityMatcher<internal::wstring>(
str, false, false));
}
// Creates a matcher that matches any wstring, std::wstring, or C wide string
// that contains the given substring.
inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
HasSubstr(const internal::wstring& substring) {
return <API key>(internal::HasSubstrMatcher<internal::wstring>(
substring));
}
// Matches a string that starts with 'prefix' (case-sensitive).
inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
StartsWith(const internal::wstring& prefix) {
return <API key>(internal::StartsWithMatcher<internal::wstring>(
prefix));
}
// Matches a string that ends with 'suffix' (case-sensitive).
inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
EndsWith(const internal::wstring& suffix) {
return <API key>(internal::EndsWithMatcher<internal::wstring>(
suffix));
}
#endif // <API key> || <API key>
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field == the second field.
inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field >= the second field.
inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field > the second field.
inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field <= the second field.
inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field < the second field.
inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
// Creates a polymorphic matcher that matches a 2-tuple where the
// first field != the second field.
inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
// Creates a matcher that matches any value of type T that m doesn't
// match.
template <typename InnerMatcher>
inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
return internal::NotMatcher<InnerMatcher>(m);
}
// Returns a matcher that matches anything that satisfies the given
// predicate. The predicate can be any unary function or functor
// whose return type can be implicitly converted to bool.
template <typename Predicate>
inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
Truly(Predicate pred) {
return <API key>(internal::TrulyMatcher<Predicate>(pred));
}
// Returns a matcher that matches an equal container.
// This matcher behaves like Eq(), but in the event of mismatch lists the
// values that are included in one container but not the other. (Duplicate
// values and order differences are not explained.)
template <typename Container>
inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
GTEST_REMOVE_CONST_(Container)> >
ContainerEq(const Container& rhs) {
// This following line is for working around a bug in MSVC 8.0,
// which causes Container to be a const type sometimes.
typedef GTEST_REMOVE_CONST_(Container) RawContainer;
return <API key>(
internal::ContainerEqMatcher<RawContainer>(rhs));
}
// Matches an STL-style container or a native array that contains the
// same number of elements as in rhs, where its i-th element and rhs's
// i-th element (as a pair) satisfy the given pair matcher, for all i.
// TupleMatcher must be able to be safely cast to Matcher<tuple<const
// T1&, const T2&> >, where T1 and T2 are the types of elements in the
// LHS container and the RHS container respectively.
template <typename TupleMatcher, typename Container>
inline internal::PointwiseMatcher<TupleMatcher,
GTEST_REMOVE_CONST_(Container)>
Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
// This following line is for working around a bug in MSVC 8.0,
// which causes Container to be a const type sometimes.
typedef GTEST_REMOVE_CONST_(Container) RawContainer;
return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
tuple_matcher, rhs);
}
// Matches an STL-style container or a native array that contains at
// least one element matching the given value or matcher.
// Examples:
// ::std::set<int> page_ids;
// page_ids.insert(3);
// page_ids.insert(1);
// EXPECT_THAT(page_ids, Contains(1));
// EXPECT_THAT(page_ids, Contains(Gt(2)));
// EXPECT_THAT(page_ids, Not(Contains(4)));
// ::std::map<int, size_t> page_lengths;
// page_lengths[1] = 100;
// EXPECT_THAT(page_lengths,
// Contains(::std::pair<const int, size_t>(1, 100)));
// const char* user_ids[] = { "joe", "mike", "tom" };
// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
template <typename M>
inline internal::ContainsMatcher<M> Contains(M matcher) {
return internal::ContainsMatcher<M>(matcher);
}
// Matches an STL-style container or a native array that contains only
// elements matching the given value or matcher.
// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
// the messages are different.
// Examples:
// ::std::set<int> page_ids;
// // Each(m) matches an empty container, regardless of what m is.
// EXPECT_THAT(page_ids, Each(Eq(1)));
// EXPECT_THAT(page_ids, Each(Eq(77)));
// page_ids.insert(3);
// EXPECT_THAT(page_ids, Each(Gt(0)));
// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
// page_ids.insert(1);
// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
// ::std::map<int, size_t> page_lengths;
// page_lengths[1] = 100;
// page_lengths[2] = 200;
// page_lengths[3] = 300;
// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
// const char* user_ids[] = { "joe", "mike", "tom" };
// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
template <typename M>
inline internal::EachMatcher<M> Each(M matcher) {
return internal::EachMatcher<M>(matcher);
}
// Key(inner_matcher) matches an std::pair whose 'first' field matches
// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
// std::map that contains at least one element whose key is >= 5.
template <typename M>
inline internal::KeyMatcher<M> Key(M inner_matcher) {
return internal::KeyMatcher<M>(inner_matcher);
}
// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
// matches first_matcher and whose 'second' field matches second_matcher. For
// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
// to match a std::map<int, string> that contains exactly one element whose key
// is >= 5 and whose value equals "foo".
template <typename FirstMatcher, typename SecondMatcher>
inline internal::PairMatcher<FirstMatcher, SecondMatcher>
Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
return internal::PairMatcher<FirstMatcher, SecondMatcher>(
first_matcher, second_matcher);
}
// Returns a predicate that is satisfied by anything that matches the
// given matcher.
template <typename M>
inline internal::MatcherAsPredicate<M> Matches(M matcher) {
return internal::MatcherAsPredicate<M>(matcher);
}
// Returns true iff the value matches the matcher.
template <typename T, typename M>
inline bool Value(const T& value, M matcher) {
return testing::Matches(matcher)(value);
}
// Matches the value against the given matcher and explains the match
// result to listener.
template <typename T, typename M>
inline bool ExplainMatchResult(
M matcher, const T& value, MatchResultListener* listener) {
return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
}
// AllArgs(m) is a synonym of m. This is useful in
// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
// which is easier to read than
// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
template <typename InnerMatcher>
inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
// These macros allow using matchers to check values in Google Test
// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
// succeed iff the value matches the matcher. If the assertion fails,
// the value and the description of the matcher will be printed.
#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
::testing::internal::<API key>(matcher), value)
#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
::testing::internal::<API key>(matcher), value)
} // namespace testing
#endif // <API key> |
from frappe import _
def get_data():
return {
'docstatus': 1,
'fieldname': '<API key>',
'transactions': [
{
'label': _('Related'),
'items': ['Supplier Quotation']
},
]
} |
void _asn1_str_cpy (char *dest, size_t dest_tot_size, const char *src);
void _asn1_str_cat (char *dest, size_t dest_tot_size, const char *src);
#define Estrcpy(x,y) _asn1_str_cpy(x,<API key>,y)
#define Estrcat(x,y) _asn1_str_cat(x,<API key>,y) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
# FIXME: Add more, better examples
EXAMPLES = r'''
- <API key>:
host: apic
username: admin
<API key>
rtp: '{{ rtp_name }}'
tenant: production
tag: '{{ tag }}'
description: '{{ description }}'
delegate_to: localhost
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec
def main():
argument_spec = aci_argument_spec()
argument_spec.update(
tenant=dict(type='str', aliases=['tenant_name']), # Not required for querying all objects
rtp=dict(type='str', aliases=['name', 'rtp_name']), # Not required for querying all objects
description=dict(type='str', aliases=['descr']),
tag=dict(type='int'),
state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
name_alias=dict(type='str'),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['rtp', 'tenant']],
['state', 'present', ['rtp', 'tenant']],
],
)
rtp = module.params.get('rtp')
description = module.params.get('description')
tag = module.params.get('tag')
state = module.params.get('state')
tenant = module.params.get('tenant')
name_alias = module.params.get('name_alias')
aci = ACIModule(module)
aci.construct_url(
root_class=dict(
aci_class='fvTenant',
aci_rn='tn-{0}'.format(tenant),
module_object=tenant,
target_filter={'name': tenant},
),
subclass_1=dict(
aci_class='l3extRouteTagPol',
aci_rn='rttag-{0}'.format(rtp),
module_object=rtp,
target_filter={'name': rtp},
),
)
aci.get_existing()
if state == 'present':
aci.payload(
aci_class='l3extRouteTagPol',
class_config=dict(
name=rtp,
descr=description, tag=tag,
nameAlias=name_alias,
),
)
aci.get_diff(aci_class='l3extRouteTagPol')
aci.post_config()
elif state == 'absent':
aci.delete_config()
aci.exit_json()
if __name__ == "__main__":
main() |
/*!
* Styles for Special:ApiSandbox
*/
.client-js .mw-apisandbox-nojs {
display: none;
} |
package com.cburch.logisim.tools.move;
public interface MoveRequestListener {
public void requestSatisfied(MoveGesture gesture, int dx, int dy);
} |
// This file is part of BOINC.
// BOINC is free software; you can redistribute it and/or modify it
// as published by the Free Software Foundation,
// BOINC is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#include "boinc_db.h"
#include "str_util.h"
#include "str_replace.h"
#include "parse.h"
#include "credit.h"
#include "sched_types.h"
#include "sched_msgs.h"
#include "sched_util.h"
#include "sched_main.h"
#include "sched_config.h"
#include "sched_result.h"
// got a SUCCESS result. Doesn't mean it's valid!
static inline void got_good_result(SCHED_RESULT_ITEM& sri) {
int gavid = <API key>(sri.app_version_id, sri.appid);
DB_HOST_APP_VERSION* havp = gavid_to_havp(gavid);
if (!havp) {
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle] No app version for %d\n", gavid
);
}
return;
}
if (havp->max_jobs_per_day < config.daily_result_quota) {
int n = havp->max_jobs_per_day*2;
if (n > config.daily_result_quota) {
n = config.daily_result_quota;
}
if (config.debug_quota) {
log_messages.printf(MSG_NORMAL,
"[quota] increasing max_jobs_per_day for %d: %d->%d\n",
gavid, havp->max_jobs_per_day, n
);
}
havp->max_jobs_per_day = n;
}
}
static inline void got_bad_result(SCHED_RESULT_ITEM& sri) {
int gavid = <API key>(sri.app_version_id, sri.appid);
DB_HOST_APP_VERSION* havp = gavid_to_havp(gavid);
if (!havp) {
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle] No app version for %d\n", gavid
);
}
return;
}
int n = havp->max_jobs_per_day;
if (n > config.daily_result_quota) {
n = config.daily_result_quota;
}
n -= 1;
if (n < 1) {
n = 1;
}
if (config.debug_quota) {
log_messages.printf(MSG_NORMAL,
"[quota] decreasing max_jobs_per_day for %d: %d->%d\n",
gavid, havp->max_jobs_per_day, n
);
}
havp->max_jobs_per_day = n;
havp->consecutive_valid = 0;
}
// handle completed results
int handle_results() {
<API key> result_handler;
SCHED_RESULT_ITEM* srip;
unsigned int i;
int retval;
RESULT* rp;
if (g_request->results.size() == 0) return 0;
// allow projects to limit the # of results handled
// (in case of server memory limits)
if (config.report_max
&& (int)g_request->results.size() > config.report_max
) {
g_request->results.resize(config.report_max);
}
// copy reported results to a separate vector, "result_handler",
// initially with only the "name" field present
for (i=0; i<g_request->results.size(); i++) {
result_handler.add_result(g_request->results[i].name);
}
// read results from database into "result_handler".
// Quantities that must be read from the DB are those
// where srip (see below) appears as an rval.
// These are: id, name, server_state, received_time, hostid, validate_state.
// Quantities that must be written to the DB are those for
// which srip appears as an lval. These are:
// hostid, teamid, received_time, client_state, cpu_time, exit_status,
// app_version_num, claimed_credit, server_state, stderr_out,
// xml_doc_out, outcome, validate_state, elapsed_time
retval = result_handler.enumerate();
if (retval) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] Batch query failed\n",
g_reply->host.id
);
}
// loop over results reported by client
// A note about acks: we send an ack for result received if either
// 1) there's some problem with it (wrong state, host, not in DB) or
// 2) we update it successfully.
// In other words, the only time we don't ack a result is when
// it looks OK but the update failed.
for (i=0; i<g_request->results.size(); i++) {
rp = &g_request->results[i];
retval = result_handler.lookup_result(rp->name, &srip);
if (retval) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#? %s] reported result not in DB\n",
g_reply->host.id, rp->name
);
g_reply->result_acks.push_back(std::string(rp->name));
continue;
}
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle] [HOST#%d] [RESULT#%u] [WU#%u] got result (DB: server_state=%d outcome=%d client_state=%d validate_state=%d delete_state=%d)\n",
g_reply->host.id, srip->id, srip->workunitid, srip->server_state,
srip->outcome, srip->client_state, srip->validate_state,
srip->file_delete_state
);
}
// Do various sanity checks.
// If one of them fails, set srip->id = 0,
// which suppresses the DB update later on
// If result has server_state OVER
// if outcome NO_REPLY accept it (it's just late).
// else ignore it
if (srip->server_state == <API key>) {
const char *msg = NULL;
switch (srip->outcome) {
case RESULT_OUTCOME_INIT:
// should never happen!
msg = "this result was never sent";
break;
case <API key>:
// don't replace a successful result!
msg = "result already reported as success";
// Client is reporting a result twice.
// That could mean it didn't get the first reply.
// That reply may have contained new jobs.
// So make sure we resend lost jobs
g_wreq->resend_lost_results = true;
break;
case <API key>:
// should never happen!
msg = "this result couldn't be sent";
break;
case <API key>:
// should never happen!
msg = "result already reported as error";
break;
case <API key>:
case <API key>:
// result is late in arriving, but keep it anyhow
break;
case <API key>:
// should never happen
msg = "this result wasn't sent (not needed)";
break;
case <API key>:
// we already passed through the validator, so
// don't keep the new result
msg = "result already reported, validate error";
break;
default:
msg = "server logic bug; please alert BOINC developers";
break;
}
if (msg) {
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle][HOST#%d][RESULT#%u][WU#%u] result already over [outcome=%d validate_state=%d]: %s\n",
g_reply->host.id, srip->id, srip->workunitid,
srip->outcome, srip->validate_state, msg
);
}
srip->id = 0;
g_reply->result_acks.push_back(std::string(rp->name));
continue;
}
}
if (srip->server_state == <API key>) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] got unexpected result: server state is %d\n",
g_reply->host.id, srip->id, srip->workunitid, srip->server_state
);
srip->id = 0;
g_reply->result_acks.push_back(std::string(rp->name));
continue;
}
if (srip->received_time) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] already got result, at %s \n",
g_reply->host.id, srip->id, srip->workunitid,
time_to_string(srip->received_time)
);
srip->id = 0;
g_reply->result_acks.push_back(std::string(rp->name));
continue;
}
if (srip->hostid != g_reply->host.id) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] got result from wrong host; expected [HOST#%d]\n",
g_reply->host.id, srip->id, srip->workunitid, srip->hostid
);
DB_HOST result_host;
retval = result_host.lookup_id(srip->hostid);
if (retval) {
log_messages.printf(MSG_CRITICAL,
"[RESULT#%u] [WU#%u] Can't lookup [HOST#%d]\n",
srip->id, srip->workunitid, srip->hostid
);
srip->id = 0;
g_reply->result_acks.push_back(std::string(rp->name));
continue;
} else if (result_host.userid != g_reply->host.userid) {
log_messages.printf(MSG_CRITICAL,
"[USER#%d] [HOST#%d] [RESULT#%u] [WU#%u] Not even the same user; expected [USER#%d]\n",
g_reply->host.userid, g_reply->host.id, srip->id, srip->workunitid, result_host.userid
);
srip->id = 0;
g_reply->result_acks.push_back(std::string(rp->name));
continue;
} else {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] Allowing result because same USER#%d\n",
g_reply->host.id, srip->id, srip->workunitid, g_reply->host.userid
);
}
} // hostids do not match
// Modify the in-memory copy obtained from the DB earlier.
// If we found a problem above,
// we have continued and skipped this modify
srip->hostid = g_reply->host.id;
srip->teamid = g_reply->user.teamid;
srip->received_time = time(0);
srip->client_state = rp->client_state;
srip->cpu_time = rp->cpu_time;
srip->elapsed_time = rp->elapsed_time;
// Some buggy clients sporadically report very low elapsed time
// but actual CPU time.
// Try to fix the elapsed time, since it's critical to credit
if (srip->elapsed_time < srip->cpu_time) {
int avid = srip->app_version_id;
if (avid > 0) {
APP_VERSION* avp = ssp->lookup_app_version(avid);
if (avp && !avp->is_multithread()) {
srip->elapsed_time = srip->cpu_time;
}
}
}
// check for impossible elapsed time
if (srip->elapsed_time < 0) {
log_messages.printf(MSG_NORMAL,
"[HOST#%d] [RESULT#%u] [WU#%u] negative elapsed time: %f\n",
srip->hostid, srip->id, srip->workunitid,
srip->elapsed_time
);
srip->elapsed_time = 0;
}
double turnaround_time = srip->received_time - srip->sent_time;
if (turnaround_time < 0) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] inconsistent sent/received times\n",
srip->hostid, srip->id, srip->workunitid
);
} else {
if (srip->elapsed_time > turnaround_time) {
log_messages.printf(MSG_NORMAL,
"[HOST#%d] [RESULT#%u] [WU#%u] impossible elapsed time: reported %f > turnaround %f\n",
srip->hostid, srip->id, srip->workunitid,
srip->elapsed_time, turnaround_time
);
srip->elapsed_time = turnaround_time;
}
}
srip->exit_status = rp->exit_status;
srip->app_version_num = rp->app_version_num;
srip->server_state = <API key>;
strlcpy(srip->stderr_out, rp->stderr_out, sizeof(srip->stderr_out));
strlcpy(srip->xml_doc_out, rp->xml_doc_out, sizeof(srip->xml_doc_out));
// look for exit status and app version in stderr_out
// (historical - can be deleted at some point)
parse_int(srip->stderr_out, "<exit_status>", srip->exit_status);
parse_int(srip->stderr_out, "<app_version>", srip->app_version_num);
if ((srip->client_state == <API key>) && (srip->exit_status == 0)) {
srip->outcome = <API key>;
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle] [RESULT#%u] [WU#%u]: setting outcome SUCCESS\n",
srip->id, srip->workunitid
);
}
got_good_result(*srip);
if (config.<API key>) {
strcpy(srip->stderr_out, "");
}
} else {
if (config.<API key>) {
log_messages.printf(MSG_NORMAL,
"[handle] [RESULT#%u] [WU#%u]: client_state %d exit_status %d; setting outcome ERROR\n",
srip->id, srip->workunitid, srip->client_state, srip->exit_status
);
}
srip->outcome = <API key>;
srip->validate_state = <API key>;
// adjust quota and reset error rate
got_bad_result(*srip);
}
} // loop over all incoming results
// Update the result records
// (skip items that we previously marked to skip)
for (i=0; i<result_handler.results.size(); i++) {
SCHED_RESULT_ITEM& sri = result_handler.results[i];
if (sri.id == 0) continue;
retval = result_handler.update_result(sri);
if (retval) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] [RESULT#%u] [WU#%u] can't update result: %s\n",
g_reply->host.id, sri.id, sri.workunitid, boinc_db.error_string()
);
} else {
g_reply->result_acks.push_back(std::string(sri.name));
}
}
// set transition_time for the results' WUs
retval = result_handler.update_workunits();
if (retval) {
log_messages.printf(MSG_CRITICAL,
"[HOST#%d] can't update WUs: %s\n",
g_reply->host.id, boincerror(retval)
);
}
return 0;
} |
#include "StdInc.h"
namespace
{
struct SLineInfo
{
std::vector < SString > strCellList;
CTickCount endTickCount;
bool bHasEndTime;
};
}
// <API key>
class <API key> : public CPerfStatDebugTable
{
public:
ZERO_ON_NEW
<API key> ( void );
virtual ~<API key> ( void );
// CPerfStatModule
virtual const SString& GetCategoryName ( void );
virtual void DoPulse ( void );
virtual void GetStats ( CPerfStatResult* pOutResult, const std::map < SString, int >& optionMap, const SString& strFilter );
// CPerfStatDebugTable
virtual void RemoveLines ( const SString& strKeyMatch );
virtual void UpdateLine ( const SString& strKey, int iLifeTimeMs, ... );
SString m_strCategoryName;
CElapsedTime <API key>;
std::map < SString, SLineInfo > m_LineMap;
CCriticalSection m_CS; // Required as some methods are called from the database thread
};
// Temporary home for global object
static std::unique_ptr<<API key>> <API key>;
CPerfStatDebugTable* CPerfStatDebugTable::GetSingleton ()
{
if ( !<API key> )
<API key>.reset(new <API key> ());
return <API key>.get();
}
// <API key>::<API key>
<API key>::<API key> ( void )
{
<API key>.SetMaxIncrement ( 500, true );
m_strCategoryName = "Debug table";
}
// <API key>::<API key>
<API key>::~<API key> ( void )
{
}
// <API key>::GetCategoryName
const SString& <API key>::GetCategoryName ( void )
{
return m_strCategoryName;
}
// <API key>::DoPulse
void <API key>::DoPulse ( void )
{
// Do remove old once every second
if ( <API key>.Get () < 1000 )
return;
<API key>.Reset ();
LOCK_SCOPE ( m_CS );
CTickCount nowTickCount = CTickCount::Now ( true );
// Remove old
for ( std::map < SString, SLineInfo >::iterator iter = m_LineMap.begin () ; iter != m_LineMap.end () ; )
{
SLineInfo& info = iter->second;
if ( info.bHasEndTime && info.endTickCount < nowTickCount )
m_LineMap.erase ( iter++ );
else
++iter;
}
}
// <API key>::RemoveLines
// Remove one or several lines. Use wildcard match for multiple removes
void <API key>::RemoveLines ( const SString& strKeyMatch )
{
LOCK_SCOPE ( m_CS );
if ( strKeyMatch.Contains ( "*" ) || strKeyMatch.Contains ( "?" ) )
{
// Wildcard remove
for ( std::map < SString, SLineInfo >::iterator iter = m_LineMap.begin () ; iter != m_LineMap.end () ; )
{
// Find each row match
if ( WildcardMatch ( strKeyMatch, iter->first ) )
m_LineMap.erase ( iter++ );
else
++iter;
}
}
else
{
// Standard remove
MapRemove ( m_LineMap, strKeyMatch );
}
}
// <API key>::UpdateLine
// Add/update a line by a string key.
void <API key>::UpdateLine ( const SString& strKey, int iLifeTimeMs, ... )
{
LOCK_SCOPE ( m_CS );
SLineInfo& info = MapGet( m_LineMap, strKey );
info.strCellList.clear ();
// Get cells
va_list vl;
va_start ( vl, iLifeTimeMs );
while ( true )
{
char* szText = va_arg ( vl, char* );
if ( !szText )
break;
info.strCellList.push_back ( szText );
}
va_end ( vl );
if ( info.strCellList.empty () )
info.strCellList.push_back ( "" );
// Update end time
info.bHasEndTime = ( iLifeTimeMs > 0 );
if ( info.bHasEndTime )
info.endTickCount = CTickCount::Now ( true ) + CTickCount ( (long long)iLifeTimeMs );
}
// <API key>::GetStats
void <API key>::GetStats ( CPerfStatResult* pResult, const std::map < SString, int >& strOptionMap, const SString& strFilter )
{
LOCK_SCOPE ( m_CS );
// Set option flags
bool bHelp = MapContains ( strOptionMap, "h" );
// Process help
if ( bHelp )
{
pResult->AddColumn ( "Debug table help" );
pResult->AddRow ()[0] = "Option h - This help";
return;
}
// Add columns
const int iNumColumns = 4;
for ( int i = 0 ; i < iNumColumns ; i++ )
pResult->AddColumn ( "" );
for ( std::map < SString, SLineInfo >::iterator iter = m_LineMap.begin () ; iter != m_LineMap.end () ; ++iter )
{
const SLineInfo& info = iter->second;
// Apply filter
if ( !strFilter.empty () && !info.strCellList[0].ContainsI ( strFilter ) )
continue;
SString* row = pResult->AddRow ();
int c = 0;
// Add cells
for ( uint i = 0 ; i < info.strCellList.size () && c < iNumColumns ; i++ )
row[c++] = info.strCellList[i];
}
} |
<?php
/**
* Forums Loop - Single Forum
*
* @package bbPress
* @subpackage Theme
*/
// Exit if accessed directly
defined( 'ABSPATH' ) || exit;
?>
<ul id="bbp-forum-<?php bbp_forum_id(); ?>" <?php bbp_forum_class(); ?>>
<li class="bbp-forum-info">
<?php if ( bbp_is_user_home() && <API key>() ) : ?>
<span class="bbp-row-actions">
<?php do_action( '<API key>' ); ?>
<?php <API key>( array( 'before' => '', 'subscribe' => '+', 'unsubscribe' => '×' ) ); ?>
<?php do_action( '<API key>' ); ?>
</span>
<?php endif; ?>
<?php do_action( '<API key>' ); ?>
<a class="bbp-forum-title" href="<?php bbp_forum_permalink(); ?>"><?php bbp_forum_title(); ?></a>
<?php do_action( '<API key>' ); ?>
<?php do_action( '<API key>' ); ?>
<div class="bbp-forum-content"><?php bbp_forum_content(); ?></div>
<?php do_action( '<API key>' ); ?>
<?php do_action( '<API key>' ); ?>
<?php bbp_list_forums(); ?>
<?php do_action( '<API key>' ); ?>
<?php <API key>(); ?>
</li>
<li class="<API key>"><?php <API key>(); ?></li>
<li class="<API key>"><?php bbp_show_lead_topic() ? <API key>() : <API key>(); ?></li>
<li class="bbp-forum-freshness">
<?php do_action( '<API key>' ); ?>
<?php <API key>(); ?>
<?php do_action( '<API key>' ); ?>
<p class="bbp-topic-meta">
<?php do_action( '<API key>' ); ?>
<span class="<API key>"><?php bbp_author_link( array( 'post_id' => <API key>(), 'size' => 14 ) ); ?></span>
<?php do_action( '<API key>' ); ?>
</p>
</li>
</ul><!-- #bbp-forum-<?php bbp_forum_id(); ?> --> |
#ifndef <API key>
#define <API key>
#include <QtCore/qglobal.h>
#if defined(<API key>)
# define IPconnection_EXPORT Q_DECL_EXPORT
#else
# define IPconnection_EXPORT Q_DECL_IMPORT
#endif
#endif // <API key> |
jQuery('#world-map-markers').vectorMap(
{
map: 'world_mill_en',
backgroundColor: '#fff',
borderColor: '#818181',
borderOpacity: 0.25,
borderWidth: 1,
color: '#f4f3f0',
regionStyle : {
initial : {
fill : '#79e580'
}
},
markerStyle: {
initial: {
r: 9,
'fill': '#fff',
'fill-opacity':1,
'stroke': '#000',
'stroke-width' : 5,
'stroke-opacity': 0.4
},
},
enableZoom: true,
hoverColor: '#79e580',
markers : [{
latLng : [21.00, 78.00],
name : 'I Love My India'
}],
hoverOpacity: null,
normalizeFunction: 'linear',
scaleColors: ['#b6d6ff', '#005ace'],
selectedColor: '#c9dfaf',
selectedRegions: [],
showTooltip: true,
onRegionClick: function(element, code, region)
{
var message = 'You clicked "'
+ region
+ '" which has the code: '
+ code.toUpperCase();
alert(message);
}
});
$('#india').vectorMap({
map : 'in_mill',
backgroundColor : 'transparent',
regionStyle : {
initial : {
fill : '#13dafe'
}
}
});
$('#usa').vectorMap({
map : 'us_aea_en',
backgroundColor : 'transparent',
regionStyle : {
initial : {
fill : '#79e580'
}
}
});
$('#australia').vectorMap({
map : 'au_mill',
backgroundColor : 'transparent',
regionStyle : {
initial : {
fill : '#ffca4a'
}
}
});
$('#uk').vectorMap({
map : 'uk_mill_en',
backgroundColor : 'transparent',
regionStyle : {
initial : {
fill : '#6164c1'
}
}
}); |
% hledger-Sh.tex
\begin{hcarentry}[updated]{hledger}
\label{hledger}
\report{Simon Michael}%14/05
\status{ongoing development; suitable for daily use}
\makeheader
hledger is a library and end-user tool (with command-line, curses and web
interfaces) for converting, recording, and analyzing financial
transactions, using a simple human-editable plain text file format. It is
a haskell port and friendly fork of John Wiegley's Ledger, licensed under
GNU GPLv3+.
%% 2011:
%% hledger aims to be a reliable, practical tool for daily use. It reports
%% charts of accounts or account balances, filters transactions by type,
%% helps you record new transactions, converts CSV data from your bank,
%% publishes your text journal with a rich web interface, generates simple
%% charts, and provides an API for use in your own financial scripts and
%% apps.
%% In the last six months there have been two major releases. 0.15 focussed
%% on features and 0.16 focussed on quality. Changes include:
%% - new modal command-line interface, extensible with hledger-* executables in the path
%% - more useful web interface, with real account registers and basic charts
%% - hledger-web no longer needs to create support files, and uses latest yesod & warp
%% - more ledger compatibility
%% - misc command enhancements, API improvements, bug fixes, documentation updates
%% - lines of code increased by 3k to 8k
%% - project committers increased by 6 to 21
%% Current plans include:
%% - Continue the release rhythm of odd-numbered = features, even-numbered =
%% quality/stability/polish, and releasing on the first of a month
%% - In 0.17, clean up the storage layer, allow rcs integration via
%% filestore, and read (or convert) more formats
%% - Keep working towards wider usefulness, improving the web interface and
%% providing standard financial reports
\FurtherReading
\url{http://hledger.org}
\end{hcarentry} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<TITLE>
StringUtil.StringsIterator (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="StringUtil.StringsIterator (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/StringUtil.StringsIterator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/poi/util/StringUtil.html" title="class in org.apache.poi.util"><B>PREV CLASS</B></A>
<A HREF="../../../../org/apache/poi/util/SuppressForbidden.html" title="annotation in org.apache.poi.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/poi/util/StringUtil.StringsIterator.html" target="_top"><B>FRAMES</B></A>
<A HREF="StringUtil.StringsIterator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.apache.poi.util</FONT>
<BR>
Class StringUtil.StringsIterator</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.util.StringUtil.StringsIterator</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.util.Iterator<java.lang.String></DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../../org/apache/poi/util/StringUtil.html" title="class in org.apache.poi.util">StringUtil</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public static class <B>StringUtil.StringsIterator</B><DT>extends java.lang.Object<DT>implements java.util.Iterator<java.lang.String></DL>
</PRE>
<P>
An Iterator over an array of Strings.
<P>
<P>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/apache/poi/util/StringUtil.StringsIterator.html#StringUtil.StringsIterator(java.lang.String[])">StringUtil.StringsIterator</A></B>(java.lang.String[] strings)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/util/StringUtil.StringsIterator.html#hasNext()">hasNext</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/util/StringUtil.StringsIterator.html#next()">next</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/util/StringUtil.StringsIterator.html#remove()">remove</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="StringUtil.StringsIterator(java.lang.String[])"></A><H3>
StringUtil.StringsIterator</H3>
<PRE>
public <B>StringUtil.StringsIterator</B>(java.lang.String[] strings)</PRE>
<DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="hasNext()"></A><H3>
hasNext</H3>
<PRE>
public boolean <B>hasNext</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>hasNext</CODE> in interface <CODE>java.util.Iterator<java.lang.String></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="next()"></A><H3>
next</H3>
<PRE>
public java.lang.String <B>next</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>next</CODE> in interface <CODE>java.util.Iterator<java.lang.String></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="remove()"></A><H3>
remove</H3>
<PRE>
public void <B>remove</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>remove</CODE> in interface <CODE>java.util.Iterator<java.lang.String></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/StringUtil.StringsIterator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../org/apache/poi/util/StringUtil.html" title="class in org.apache.poi.util"><B>PREV CLASS</B></A>
<A HREF="../../../../org/apache/poi/util/SuppressForbidden.html" title="annotation in org.apache.poi.util"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/poi/util/StringUtil.StringsIterator.html" target="_top"><B>FRAMES</B></A>
<A HREF="StringUtil.StringsIterator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright 2017 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML> |
'use strict';
exports.__esModule = true;
var _root = require('./root');
var Immediate = {
setImmediate: function setImmediate(x) {
return 0;
},
clearImmediate: function clearImmediate(id) {}
};
exports.Immediate = Immediate;
if (_root.root && _root.root.setImmediate) {
Immediate.setImmediate = _root.root.setImmediate;
Immediate.clearImmediate = _root.root.clearImmediate;
} else {
exports.Immediate = Immediate = (function (global, Immediate) {
var nextHandle = 1,
// Spec says greater than zero
tasksByHandle = {},
<API key> = false,
doc = global.document,
setImmediate = undefined;
// Don't get fooled by e.g. browserify environments.
if (({}).toString.call(global.process) === '[object process]') {
// For Node.js before 0.9
setImmediate = <API key>();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
setImmediate = <API key>();
} else if (global.MessageChannel) {
// For web workers, where supported
setImmediate = <API key>();
} else if (doc && 'onreadystatechange' in doc.createElement('script')) {
setImmediate = <API key>();
} else {
// For older browsers
setImmediate = <API key>();
}
Immediate.setImmediate = setImmediate;
Immediate.clearImmediate = clearImmediate;
return Immediate;
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function <API key>(args) {
tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args);
return nextHandle++;
}
// This function accepts the same arguments as setImmediate, but
// returns a function that requires no arguments.
function partiallyApplied(handler) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return function () {
if (typeof handler === 'function') {
handler.apply(undefined, args);
} else {
new Function('' + handler)();
}
};
}
function runIfPresent(handle) {
// From the spec: 'Wait until any invocations of this algorithm started before this one have completed.'
// So if we're currently running a task, we'll need to delay this invocation.
if (<API key>) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// 'too much recursion' error.
setTimeout(partiallyApplied(runIfPresent, handle), 0);
} else {
var task = tasksByHandle[handle];
if (task) {
<API key> = true;
try {
task();
} finally {
clearImmediate(handle);
<API key> = false;
}
}
}
}
function <API key>() {
return function setImmediate() {
var handle = <API key>(arguments);
global.process.nextTick(partiallyApplied(runIfPresent, handle));
return handle;
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var <API key> = true;
var oldOnMessage = global.onmessage;
global.onmessage = function () {
<API key> = false;
};
global.postMessage('', '*');
global.onmessage = oldOnMessage;
return <API key>;
}
}
function <API key>() {
// Installs an event handler on `global` for the `message` event: see
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#<API key>
var messagePrefix = 'setImmediate$' + Math.random() + '$';
var onGlobalMessage = function onGlobalMessage(event) {
if (event.source === global && typeof event.data === 'string' && event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener('message', onGlobalMessage, false);
} else {
global.attachEvent('onmessage', onGlobalMessage);
}
return function setImmediate() {
var handle = <API key>(arguments);
global.postMessage(messagePrefix + handle, '*');
return handle;
};
}
function <API key>() {
var channel = new MessageChannel();
channel.port1.onmessage = function (event) {
var handle = event.data;
runIfPresent(handle);
};
return function setImmediate() {
var handle = <API key>(arguments);
channel.port2.postMessage(handle);
return handle;
};
}
function <API key>() {
var html = doc.documentElement;
return function setImmediate() {
var handle = <API key>(arguments);
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement('script');
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
return handle;
};
}
function <API key>() {
return function setImmediate() {
var handle = <API key>(arguments);
setTimeout(partiallyApplied(runIfPresent, handle), 0);
return handle;
};
}
})(_root.root, Immediate);
} |
#ifndef QGLCOLORMAP_H
#define QGLCOLORMAP_H
#include <QtGui/qcolor.h>
#include <QtCore/qvector.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(OpenGL)
class Q_OPENGL_EXPORT QGLColormap
{
public:
QGLColormap();
QGLColormap(const QGLColormap &);
~QGLColormap();
QGLColormap &operator=(const QGLColormap &);
bool isEmpty() const;
int size() const;
void detach();
void setEntries(int count, const QRgb * colors, int base = 0);
void setEntry(int idx, QRgb color);
void setEntry(int idx, const QColor & color);
QRgb entryRgb(int idx) const;
QColor entryColor(int idx) const;
int find(QRgb color) const;
int findNearest(QRgb color) const;
protected:
Qt::HANDLE handle() { return d ? d->cmapHandle : 0; }
void setHandle(Qt::HANDLE ahandle) { d->cmapHandle = ahandle; }
private:
struct QGLColormapData {
QBasicAtomicInt ref;
QVector<QRgb> *cells;
Qt::HANDLE cmapHandle;
};
QGLColormapData *d;
static struct QGLColormapData shared_null;
static void cleanup(QGLColormapData *x);
void detach_helper();
friend class QGLWidget;
friend class QGLWidgetPrivate;
};
inline void QGLColormap::detach()
{
if (d->ref != 1)
detach_helper();
}
QT_END_NAMESPACE
QT_END_HEADER
#endif // QGLCOLORMAP_H |
<?php
namespace Syw\Front\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Allcountries
*
* @ORM\Table(name="allCountries", indexes={@ORM\Index(name="name", columns={"name"}), @ORM\Index(name="feature_code", columns={"feature_code"}), @ORM\Index(name="country_code", columns={"country_code"})})
* @ORM\Entity
*/
class Allcountries
{
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="asciiname", type="string", length=255, nullable=true)
*/
private $asciiname;
/**
* @var string
*
* @ORM\Column(name="alternatenames", type="string", length=255, nullable=true)
*/
private $alternatenames;
/**
* @var string
*
* @ORM\Column(name="latitude", type="string", length=11, nullable=true)
*/
private $latitude;
/**
* @var string
*
* @ORM\Column(name="longitude", type="string", length=11, nullable=true)
*/
private $longitude;
/**
* @var string
*
* @ORM\Column(name="feature_class", type="string", length=3, nullable=true)
*/
private $featureClass;
/**
* @var string
*
* @ORM\Column(name="feature_code", type="string", length=5, nullable=true)
*/
private $featureCode;
/**
* @var string
*
* @ORM\Column(name="country_code", type="string", length=5, nullable=false)
*/
private $countryCode;
/**
* @var string
*
* @ORM\Column(name="cc2", type="string", length=5, nullable=true)
*/
private $cc2;
/**
* @var string
*
* @ORM\Column(name="admin1_code", type="string", length=5, nullable=true)
*/
private $admin1Code;
/**
* @var string
*
* @ORM\Column(name="admin2_code", type="string", length=5, nullable=true)
*/
private $admin2Code;
/**
* @var string
*
* @ORM\Column(name="admin3_code", type="string", length=5, nullable=true)
*/
private $admin3Code;
/**
* @var string
*
* @ORM\Column(name="admin4_code", type="string", length=5, nullable=true)
*/
private $admin4Code;
/**
* @var integer
*
* @ORM\Column(name="population", type="integer", nullable=true)
*/
private $population;
/**
* @var integer
*
* @ORM\Column(name="elevation", type="integer", nullable=true)
*/
private $elevation;
/**
* @var string
*
* @ORM\Column(name="dem", type="string", length=10, nullable=true)
*/
private $dem;
/**
* @var string
*
* @ORM\Column(name="timezone", type="string", length=40, nullable=true)
*/
private $timezone;
/**
* @var \DateTime
*
* @ORM\Column(name="modification_date", type="datetime", nullable=true)
*/
private $modificationDate;
/**
* @var integer
*
* @ORM\Column(name="geonameid", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $geonameid;
/**
* Set name
*
* @param string $name
* @return Allcountries
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set asciiname
*
* @param string $asciiname
* @return Allcountries
*/
public function setAsciiname($asciiname)
{
$this->asciiname = $asciiname;
return $this;
}
/**
* Get asciiname
*
* @return string
*/
public function getAsciiname()
{
return $this->asciiname;
}
/**
* Set alternatenames
*
* @param string $alternatenames
* @return Allcountries
*/
public function setAlternatenames($alternatenames)
{
$this->alternatenames = $alternatenames;
return $this;
}
/**
* Get alternatenames
*
* @return string
*/
public function getAlternatenames()
{
return $this->alternatenames;
}
/**
* Set latitude
*
* @param string $latitude
* @return Allcountries
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* @return string
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* @param string $longitude
* @return Allcountries
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* @return string
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set featureClass
*
* @param string $featureClass
* @return Allcountries
*/
public function setFeatureClass($featureClass)
{
$this->featureClass = $featureClass;
return $this;
}
/**
* Get featureClass
*
* @return string
*/
public function getFeatureClass()
{
return $this->featureClass;
}
/**
* Set featureCode
*
* @param string $featureCode
* @return Allcountries
*/
public function setFeatureCode($featureCode)
{
$this->featureCode = $featureCode;
return $this;
}
/**
* Get featureCode
*
* @return string
*/
public function getFeatureCode()
{
return $this->featureCode;
}
/**
* Set countryCode
*
* @param string $countryCode
* @return Allcountries
*/
public function setCountryCode($countryCode)
{
$this->countryCode = $countryCode;
return $this;
}
/**
* Get countryCode
*
* @return string
*/
public function getCountryCode()
{
return $this->countryCode;
}
/**
* Set cc2
*
* @param string $cc2
* @return Allcountries
*/
public function setCc2($cc2)
{
$this->cc2 = $cc2;
return $this;
}
/**
* Get cc2
*
* @return string
*/
public function getCc2()
{
return $this->cc2;
}
/**
* Set admin1Code
*
* @param string $admin1Code
* @return Allcountries
*/
public function setAdmin1Code($admin1Code)
{
$this->admin1Code = $admin1Code;
return $this;
}
/**
* Get admin1Code
*
* @return string
*/
public function getAdmin1Code()
{
return $this->admin1Code;
}
/**
* Set admin2Code
*
* @param string $admin2Code
* @return Allcountries
*/
public function setAdmin2Code($admin2Code)
{
$this->admin2Code = $admin2Code;
return $this;
}
/**
* Get admin2Code
*
* @return string
*/
public function getAdmin2Code()
{
return $this->admin2Code;
}
/**
* Set admin3Code
*
* @param string $admin3Code
* @return Allcountries
*/
public function setAdmin3Code($admin3Code)
{
$this->admin3Code = $admin3Code;
return $this;
}
/**
* Get admin3Code
*
* @return string
*/
public function getAdmin3Code()
{
return $this->admin3Code;
}
/**
* Set admin4Code
*
* @param string $admin4Code
* @return Allcountries
*/
public function setAdmin4Code($admin4Code)
{
$this->admin4Code = $admin4Code;
return $this;
}
/**
* Get admin4Code
*
* @return string
*/
public function getAdmin4Code()
{
return $this->admin4Code;
}
/**
* Set population
*
* @param integer $population
* @return Allcountries
*/
public function setPopulation($population)
{
$this->population = $population;
return $this;
}
/**
* Get population
*
* @return integer
*/
public function getPopulation()
{
return $this->population;
}
/**
* Set elevation
*
* @param integer $elevation
* @return Allcountries
*/
public function setElevation($elevation)
{
$this->elevation = $elevation;
return $this;
}
/**
* Get elevation
*
* @return integer
*/
public function getElevation()
{
return $this->elevation;
}
/**
* Set dem
*
* @param string $dem
* @return Allcountries
*/
public function setDem($dem)
{
$this->dem = $dem;
return $this;
}
/**
* Get dem
*
* @return string
*/
public function getDem()
{
return $this->dem;
}
/**
* Set timezone
*
* @param string $timezone
* @return Allcountries
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone;
return $this;
}
/**
* Get timezone
*
* @return string
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* Set modificationDate
*
* @param \DateTime $modificationDate
* @return Allcountries
*/
public function setModificationDate($modificationDate)
{
$this->modificationDate = $modificationDate;
return $this;
}
/**
* Get modificationDate
*
* @return \DateTime
*/
public function getModificationDate()
{
return $this->modificationDate;
}
/**
* Get geonameid
*
* @return integer
*/
public function getGeonameid()
{
return $this->geonameid;
}
} |
<?php
if (! empty($conf->global-><API key>))
{
$sql = "SELECT COUNT(p.rowid) as nb, SUM(p.opp_amount) as opp_amount, p.fk_opp_status as opp_status";
$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
$sql.= " WHERE p.entity = ".$conf->entity;
$sql.= " AND p.fk_statut = 1";
if ($mine || empty($user->rights->projet->all->lire)) $sql.= " AND p.rowid IN (".$projectsListId.")";
if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
$sql.= " GROUP BY p.fk_opp_status";
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
$totalnb=0;
$totalamount=0;
$<API key>=0;
$valsnb=array();
$valsamount=array();
$dataseries=array();
// -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not)
while ($i < $num)
{
$obj = $db->fetch_object($resql);
if ($obj)
{
//if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1))
{
$valsnb[$obj->opp_status]=$obj->nb;
$valsamount[$obj->opp_status]=$obj->opp_amount;
$totalnb+=$obj->nb;
$totalamount+=$obj->opp_amount;
$<API key> = $<API key> + price2num($listofoppstatus[$obj->opp_status] * $obj->opp_amount / 100);
}
$total+=$row[0];
}
$i++;
}
$db->free($resql);
print '<table class="noborder nohover" width="100%">';
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("<API key>").'</td></tr>'."\n";
$var=true;
$listofstatus=array_keys($listofoppstatus);
foreach ($listofstatus as $status)
{
$labelstatus = '';
$code = dol_getIdFromCode($db, $status, 'c_lead_status', 'rowid', 'code');
if ($code) $labelstatus = $langs->trans("OppStatus".$code);
if (empty($labelstatus)) $labelstatus=$listofopplabel[$status];
//$labelstatus .= ' ('.$langs->trans("Coeff").': '.price2num($listofoppstatus[$status]).')';
$labelstatus .= ' - '.price2num($listofoppstatus[$status]).'%';
$dataseries[]=array('label'=>$labelstatus,'data'=>(isset($valsamount[$status])?(float) $valsamount[$status]:0));
if (! $conf->use_javascript_ajax)
{
$var=!$var;
print "<tr ".$bc[$var].">";
print '<td>'.$labelstatus.'</td>';
print '<td align="right"><a href="list.php?statut='.$status.'">'.price((isset($valsamount[$status])?(float) $valsamount[$status]:0), 0, '', 1, -1, -1, $conf->currency).'</a></td>';
print "</tr>\n";
}
}
if ($conf->use_javascript_ajax)
{
print '<tr class="impair"><td align="center" colspan="2">';
$data=array('series'=>$dataseries);
dol_print_graph('stats',400,180,$data,1,'pie',0,'',0);
print '</td></tr>';
}
//if ($totalinprocess != $total)
//print '<tr class="liste_total"><td>'.$langs->trans("Total").' ('.$langs->trans("<API key>").')</td><td align="right">'.$totalinprocess.'</td></tr>';
print '<tr class="liste_total"><td>'.$langs->trans("<API key>").'</td><td align="right">'.price($totalamount, 0, '', 1, -1, -1, $conf->currency).'</td></tr>';
print '<tr class="liste_total"><td>'.$langs->trans("<API key>").'</td><td align="right">'.price($<API key>, 0, '', 1, -1, -1, $conf->currency).'</td></tr>';
print "</table><br>";
}
else
{
dol_print_error($db);
}
} |
try:
import botocore.waiter as core_waiter
except ImportError:
pass # caught by HAS_BOTO3
ec2_data = {
"version": 2,
"waiters": {
"RouteTableExists": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeRouteTables",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "length(RouteTables[]) > `0`",
"state": "success"
},
{
"matcher": "error",
"expected": "InvalidRouteTableID.NotFound",
"state": "retry"
},
]
},
"SecurityGroupExists": {
"delay": 5,
"maxAttempts": 40,
"operation": "<API key>",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "length(SecurityGroups[]) > `0`",
"state": "success"
},
{
"matcher": "error",
"expected": "InvalidGroup.NotFound",
"state": "retry"
},
]
},
"SubnetExists": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "length(Subnets[]) > `0`",
"state": "success"
},
{
"matcher": "error",
"expected": "InvalidSubnetID.NotFound",
"state": "retry"
},
]
},
"SubnetHasMapPublic": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "pathAll",
"expected": True,
"argument": "Subnets[].MapPublicIpOnLaunch",
"state": "success"
},
]
},
"SubnetNoMapPublic": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "pathAll",
"expected": False,
"argument": "Subnets[].MapPublicIpOnLaunch",
"state": "success"
},
]
},
"SubnetHasAssignIpv6": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "pathAll",
"expected": True,
"argument": "Subnets[].<API key>",
"state": "success"
},
]
},
"SubnetNoAssignIpv6": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "pathAll",
"expected": False,
"argument": "Subnets[].<API key>",
"state": "success"
},
]
},
"SubnetDeleted": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeSubnets",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "length(Subnets[]) > `0`",
"state": "retry"
},
{
"matcher": "error",
"expected": "InvalidSubnetID.NotFound",
"state": "success"
},
]
},
"VpnGatewayExists": {
"delay": 5,
"maxAttempts": 40,
"operation": "DescribeVpnGateways",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "length(VpnGateways[]) > `0`",
"state": "success"
},
{
"matcher": "error",
"expected": "InvalidVpnGatewayID.NotFound",
"state": "retry"
},
]
},
}
}
waf_data = {
"version": 2,
"waiters": {
"ChangeTokenInSync": {
"delay": 20,
"maxAttempts": 60,
"operation": "<API key>",
"acceptors": [
{
"matcher": "path",
"expected": True,
"argument": "ChangeTokenStatus == 'INSYNC'",
"state": "success"
},
{
"matcher": "error",
"expected": "<API key>",
"state": "retry"
}
]
}
}
}
eks_data = {
"version": 2,
"waiters": {
"ClusterActive": {
"delay": 20,
"maxAttempts": 60,
"operation": "DescribeCluster",
"acceptors": [
{
"state": "success",
"matcher": "path",
"argument": "cluster.status",
"expected": "ACTIVE"
},
{
"state": "retry",
"matcher": "error",
"expected": "<API key>"
}
]
}
}
}
def ec2_model(name):
ec2_models = core_waiter.WaiterModel(waiter_config=ec2_data)
return ec2_models.get_waiter(name)
def waf_model(name):
waf_models = core_waiter.WaiterModel(waiter_config=waf_data)
return waf_models.get_waiter(name)
def eks_model(name):
eks_models = core_waiter.WaiterModel(waiter_config=eks_data)
return eks_models.get_waiter(name)
waiters_by_name = {
('EC2', 'route_table_exists'): lambda ec2: core_waiter.Waiter(
'route_table_exists',
ec2_model('RouteTableExists'),
core_waiter.<API key>(
ec2.<API key>
)),
('EC2', '<API key>'): lambda ec2: core_waiter.Waiter(
'<API key>',
ec2_model('SecurityGroupExists'),
core_waiter.<API key>(
ec2.<API key>
)),
('EC2', 'subnet_exists'): lambda ec2: core_waiter.Waiter(
'subnet_exists',
ec2_model('SubnetExists'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', '<API key>'): lambda ec2: core_waiter.Waiter(
'<API key>',
ec2_model('SubnetHasMapPublic'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', '<API key>'): lambda ec2: core_waiter.Waiter(
'<API key>',
ec2_model('SubnetNoMapPublic'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', '<API key>'): lambda ec2: core_waiter.Waiter(
'<API key>',
ec2_model('SubnetHasAssignIpv6'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', '<API key>'): lambda ec2: core_waiter.Waiter(
'<API key>',
ec2_model('SubnetNoAssignIpv6'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', 'subnet_deleted'): lambda ec2: core_waiter.Waiter(
'subnet_deleted',
ec2_model('SubnetDeleted'),
core_waiter.<API key>(
ec2.describe_subnets
)),
('EC2', 'vpn_gateway_exists'): lambda ec2: core_waiter.Waiter(
'vpn_gateway_exists',
ec2_model('VpnGatewayExists'),
core_waiter.<API key>(
ec2.<API key>
)),
('WAF', '<API key>'): lambda waf: core_waiter.Waiter(
'<API key>',
waf_model('ChangeTokenInSync'),
core_waiter.<API key>(
waf.<API key>
)),
('EKS', 'cluster_active'): lambda eks: core_waiter.Waiter(
'cluster_active',
eks_model('ClusterActive'),
core_waiter.<API key>(
eks.describe_cluster
)),
}
def get_waiter(client, waiter_name):
try:
return waiters_by_name[(client.__class__.__name__, waiter_name)](client)
except KeyError:
raise NotImplementedError("Waiter {0} could not be found for client {1}. Available waiters: {2}".format(
waiter_name, type(client), ', '.join(repr(k) for k in waiters_by_name.keys()))) |
/** @odoo-module **/
export class Listener {
/**
* Creates a new listener for handling changes in models. This listener
* should be provided to the listening methods of the model manager.
*
* @constructor
* @param {Object} param
* @param {string} param.name name of this listener, useful for debugging
* @param {function} param.onChange function that will be called when this
* listener is notified of change, which is when records or fields that are
* listened to are created/updated/deleted. This function is called with
* 1 param that contains info
* @param {boolean} [param.isLocking=true] whether the model manager should
* be locked while this listener is observing, which means no change of
* state in any model is allowed (preventing to call insert/update/delete).
* @param {boolean} [param.isPartOfUpdateCycle=false] determines at which
* point during the update cycle of the models this `onChange` function
* will be called.
* Note: a function called as part of the update cycle cannot have any side
* effect (such as updating a record), so it is usually necessary to keep
* this value to false. Keeping it to false also improves performance by
* making sure all side effects of update cycle (such as the update of
* computed fields) have been processed before `onChange` is called (it
* could otherwise be called multiple times in quick succession).
*/
constructor({ name, onChange, isLocking = true, isPartOfUpdateCycle = false }) {
this.isLocking = isLocking;
this.isPartOfUpdateCycle = isPartOfUpdateCycle;
this.name = name;
this.onChange = onChange;
/**
* Set of localIds that have been accessed on model manager between the
* last call to `startListening` and `stopListening` with this listener
* as parameter.
* Each localId has its own way to know the listeners that are observing
* it (to be able to notify them if it changes). This set holds the
* inverse of that information, which is useful to be able to remove
* this listener (when the need arises) from those localIds without
* having to verify the presence of this listener on each possible
* localId one by one.
*/
this.<API key> = new Set();
/**
* Map between localIds and a set of fields on those localIds that have
* been accessed on model manager between the last call to
* `startListening` and `stopListening` with this listener as parameter.
* Each field of each localId has its own way to know the listeners that
* are observing it (to be able to notify them if it changes). This map
* holds the inverse of that information, which is useful to be able to
* remove this listener (when the need arises) from those fields without
* having to verify the presence of this listener on each possible field
* one by one.
*/
this.<API key> = new Map();
/**
* Set of Model that have been accessed with `all()` on model manager
* between the last call to `startListening` and `stopListening` with
* this listener as parameter.
* Each Model has its own way to know the listeners that are observing
* it (to be able to notify them if it changes). This set holds the
* inverse of that information, which is useful to be able to remove
* this listener (when the need arises) from those Model without having
* to verify the presence of this listener on each possible Model one by
* one.
*/
this.<API key> = new Set();
}
/**
* @returns {string}
*/
toString() {
return `listener(${this.name})`;
}
} |
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
import os
import unittest
from manifestparser import ManifestParser
here = os.path.dirname(os.path.abspath(__file__))
class TestDefaultSkipif(unittest.TestCase):
"""test applying a skip-if condition in [DEFAULT] and || with the value for the test"""
def test_defaults(self):
default = os.path.join(here, 'default-skipif.ini')
parser = ManifestParser(manifests=(default,))
for test in parser.tests:
if test['name'] == 'test1':
self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (debug)")
elif test['name'] == 'test2':
self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (os == 'linux')")
elif test['name'] == 'test3':
self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (os == 'win')")
elif test['name'] == 'test4':
self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (os == 'win' && debug)")
elif test['name'] == 'test5':
self.assertEqual(test['skip-if'], "os == 'win' && debug # a pesky comment")
elif test['name'] == 'test6':
self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (debug )")
if __name__ == '__main__':
unittest.main() |
require_relative '../../benchmark_helper'
xml = read_big_xml
measure_average do
Oga::XML::Lexer.new(xml).advance { }
end |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package configservice
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)
// ConfigService provides the API operation methods for making requests to
// AWS Config. See this package's package overview docs
// for details on the service.
// ConfigService methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type ConfigService struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "config" // Name of service.
EndpointsID = ServiceName // ID to lookup a service endpoint with.
ServiceID = "Config Service" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the ConfigService client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
// Example:
// mySession := session.Must(session.NewSession())
// // Create a ConfigService client from just a session.
// svc := configservice.New(mySession)
// // Create a ConfigService client with additional configuration
// svc := configservice.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ConfigService {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *ConfigService {
svc := &ConfigService{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-11-12",
JSONVersion: "1.1",
TargetPrefix: "StarlingDoveService",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.<API key>)
svc.Handlers.UnmarshalError.PushBackNamed(
protocol.<API key>(jsonrpc.<API key>(exceptionFromCode)).NamedHandler(),
)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a ConfigService operation and runs any
// custom request initialization.
func (c *ConfigService) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
} |
<!DOCTYPE html>
<html>
<head>
<title>Test for uppercasing of Greek (NFC)</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style type="text/css">
/* Note that this test depends on finding the same "serif" font for the
English- and Greek-tagged elements; on most platforms, our default prefs
provide that, but on Android they currently differ, hence the explicit
Droid Serif setting below. */
div {
font: 150% "Droid Serif", serif; /* explicitly prefer Droid over Charis on Android */
text-transform: uppercase;
margin: 1em;
}
</style>
</head>
<body lang="en">
<div>Πατάτα, Αέρας, Μάιος, άυλος, αϋπνία, Μαΐου, χούι</div>
<div lang="el-GR">Πατάτα, Αέρας, Μάιος, άυλος, αϋπνία, Μαΐου, χούι</div>
</body>
</html> |
#include "ogr_oci.h"
CPL_CVSID("$Id: ogrocidriver.cpp 12396 2007-10-13 10:02:17Z rouault $");
/* ~OGROCIDriver() */
OGROCIDriver::~OGROCIDriver()
{
}
/* GetName() */
const char *OGROCIDriver::GetName()
{
return "OCI";
}
/* Open() */
OGRDataSource *OGROCIDriver::Open( const char * pszFilename,
int bUpdate )
{
OGROCIDataSource *poDS;
poDS = new OGROCIDataSource();
if( !poDS->Open( pszFilename, bUpdate, TRUE ) )
{
delete poDS;
return NULL;
}
else
return poDS;
}
/* CreateDataSource() */
OGRDataSource *OGROCIDriver::CreateDataSource( const char * pszName,
char ** /* papszOptions */ )
{
OGROCIDataSource *poDS;
poDS = new OGROCIDataSource();
if( !poDS->Open( pszName, TRUE, TRUE ) )
{
delete poDS;
CPLError( CE_Failure, CPLE_AppDefined,
"Oracle driver doesn't currently support database creation.\n"
"Please create database with Oracle tools before loading tables." );
return NULL;
}
return poDS;
}
/* TestCapability() */
int OGROCIDriver::TestCapability( const char * pszCap )
{
if( EQUAL(pszCap,<API key>) )
return TRUE;
else
return FALSE;
}
/* RegisterOGROCI() */
void RegisterOGROCI()
{
if (! GDAL_CHECK_VERSION("OCI driver"))
return;
<API key>::GetRegistrar()->RegisterDriver( new OGROCIDriver );
} |
package org.kuali.kra.protocol.notification;
import org.kuali.coeus.common.framework.mail.EmailAttachment;
import org.kuali.coeus.common.notification.impl.<API key>;
import org.kuali.coeus.common.notification.impl.<API key>;
import org.kuali.coeus.common.notification.impl.bo.<API key>;
import org.kuali.coeus.common.notification.impl.exception.<API key>;
import org.kuali.coeus.common.notification.impl.service.<API key>;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.onlinereview.<API key>;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* This class extends the notification context base and provides some helpful functions for
* any IRB specific events.
*/
public abstract class <API key> extends <API key> {
private static final long serialVersionUID = <API key>;
private String documentNumber;
private String actionTypeCode;
private String contextName;
private List<EmailAttachment> emailAttachments;
private String forwardName;
// This is for assign reviewer.
private boolean populateRole;
/**
* Constructs a protocol notification context and sets the necessary services.
* @param protocol
* @param <API key>
* @param actionTypeCode
* @param contextName
*/
public <API key>(ProtocolBase protocol, <API key> <API key>, String actionTypeCode, String contextName, <API key> renderer) {
this(protocol, actionTypeCode, contextName, renderer);
((<API key>) <API key>()).<API key>(<API key>);
}
/**
* Constructs an IRB notification context and sets the necessary services.
* @param protocol
* @param actionTypeCode
* @param contextName
*/
public <API key>(ProtocolBase protocol, String actionTypeCode, String contextName, <API key> renderer) {
super(renderer);
this.documentNumber = protocol.getProtocolDocument().getDocumentNumber();
this.actionTypeCode = actionTypeCode;
this.contextName = contextName;
<API key>(KcServiceLocator.getService(<API key>.class));
}
@Override
public String getDocumentNumber() {
return documentNumber;
}
@Override
public String getActionTypeCode() {
return actionTypeCode;
}
@Override
public String getContextName() {
return contextName;
}
@Override
public List<EmailAttachment> getEmailAttachments() {
return emailAttachments;
}
/**
*
* This method sets a list of email attachments
* @param emailAttachments
*/
public void setEmailAttachments(List<EmailAttachment> emailAttachments) {
this.emailAttachments = emailAttachments;
}
public String getForwardName() {
return forwardName;
}
public void setForwardName(String forwardName) {
this.forwardName = forwardName;
}
public boolean isPopulateRole() {
return populateRole;
}
public void setPopulateRole(boolean populateRole) {
this.populateRole = populateRole;
}
/**
* This is a hook/hack for assign reviewer/submit for review, which has potential of multiple reviewers
* reviewers are supposed to be processed separately, but for 'prompt user', it merged into one prompt.
* 'reviewer role' are the same, but the role qualifiers' are different which is based on context.
* the role qualifier are populated when we merge all recipients in to one list.
* So, when sendnotification, it is just using the last 'context', so at this point, we don't want
* rolequalifiers being populated again. If it is populated again, all reviewer role will retrieve same reviewer because
* the context are the same at the point of 'send'.
* Unless, there is better approach, we'll stick with this hack for now.
* isPopulateRole is only 'true' for this case, so the other cases will stay the same as before this change.
* @see org.kuali.coeus.common.notification.impl.<API key>#<API key>(org.kuali.coeus.common.notification.impl.bo.<API key>)
*/
@Override
public void <API key>(<API key> <API key>) throws <API key> {
if (!isPopulateRole() || CollectionUtils.isEmpty(<API key>.getRoleQualifiers())) {
super.<API key>(<API key>);
}
}
} |
#include "mdef.h"
#include "gdsroot.h"
#include "gdsbt.h"
#include "gtm_facility.h"
#include "fileinfo.h"
#include "gdsfhead.h"
#include "filestruct.h"
#include "jnl.h"
#include "buddy_list.h"
#include "hashtab_int4.h" /* needed for muprec.h */
#include "hashtab_int8.h" /* needed for muprec.h */
#include "hashtab_mname.h" /* needed for muprec.h */
#include "muprec.h"
/* this routine resets new_pini_addr to 0 for all process-vectors in the current rctl->jctl hash-table entries.
* this is usually invoked in case a journal auto switch occurs while backward recover/rollback is playing forward the updates
*/
void mur_pini_addr_reset(sgmnt_addrs *csa)
{
reg_ctl_list *rctl;
jnl_ctl_list *jctl;
pini_list_struct *plst;
ht_ent_int4 *tabent, *topent;
rctl = csa->rctl;
assert(NULL != rctl);
jctl = rctl->jctl;
assert(NULL != jctl);
for (tabent = jctl->pini_list.base, topent = jctl->pini_list.top; tabent < topent; tabent++)
{
if (HTENT_VALID_INT4(tabent, pini_list_struct, plst))
plst->new_pini_addr = 0;
}
} |
#include "<API key>.h"
static asn_TYPE_member_t <API key>[] = {
{ ATF_NOFLAGS, 0, offsetof(struct <API key>, cdma2000_Type),
(<API key> | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&<API key>,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"cdma2000-Type"
},
{ ATF_POINTER, 3, offsetof(struct <API key>, rand),
(<API key> | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&<API key>,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"rand"
},
{ ATF_POINTER, 2, offsetof(struct <API key>, mobilityParameters),
(<API key> | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&<API key>,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"mobilityParameters"
},
{ ATF_POINTER, 1, offsetof(struct <API key>, <API key>),
(<API key> | (3 << 2)),
-1, /* IMPLICIT tag at current level */
&<API key>,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"<API key>"
},
};
static int <API key>[] = { 1, 2, 3 };
static ber_tlv_tag_t <API key>[] = {
(<API key> | (16 << 2))
};
static <API key> <API key>[] = {
{ (<API key> | (0 << 2)), 0, 0, 0 }, /* cdma2000-Type */
{ (<API key> | (1 << 2)), 1, 0, 0 }, /* rand */
{ (<API key> | (2 << 2)), 2, 0, 0 }, /* mobilityParameters */
{ (<API key> | (3 << 2)), 3, 0, 0 } /* <API key> */
};
static <API key> <API key> = {
sizeof(struct <API key>),
offsetof(struct <API key>, _asn_ctx),
<API key>,
4, /* Count of tags in the map */
<API key>, /* Optional members */
3, 0, /* Root/Additions */
-1, /* Start extensions */
-1 /* Stop extensions */
};
<API key> <API key> = {
"<API key>",
"<API key>",
SEQUENCE_free,
SEQUENCE_print,
SEQUENCE_constraint,
SEQUENCE_decode_ber,
SEQUENCE_encode_der,
SEQUENCE_decode_xer,
SEQUENCE_encode_xer,
<API key>,
<API key>,
0, /* Use generic outmost tag fetcher */
<API key>,
sizeof(<API key>)
/sizeof(<API key>[0]),
<API key>, /* Same as above */
sizeof(<API key>)
/sizeof(<API key>[0]),
0, /* No PER visible constraints */
<API key>,
4, /* Elements count */
&<API key> /* Additional specs */
}; |
FullCalendar.globalLocales.push(function () {
'use strict';
var enNz = {
code: "en-nz",
week: {
dow: 1, // Monday is the first day of the week.
doy: 4 // The week that contains Jan 4th is the first week of the year.
}
};
return enNz;
}()); |
from AccessControl import ClassSecurityInfo
from Products.Archetypes.utils import DisplayList
from Products.Archetypes.Registry import registerWidget
from Products.Archetypes.Widget import TypesWidget
from Products.CMFPlone.i18nl10n import ulocalized_time
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import BrowserView
from bika.lims.locales import COUNTRIES,STATES,DISTRICTS
import json
import plone
class AddressWidget(TypesWidget):
_properties = TypesWidget._properties.copy()
_properties.update({
'macro': "bika_widgets/addresswidget",
'helper_js': ("bika_widgets/addresswidget.js",),
'helper_css': ("bika_widgets/addresswidget.css",),
'showLegend': True,
'showDistrict': True,
'showCopyFrom': True,
'showCity': True,
'showPostalCode': True,
'showAddress': True,
})
security = ClassSecurityInfo()
# The values in the form/field are always
# Country Name, State Name, District Name.
def getCountries(self):
items = []
items = [(x['ISO'], x['Country']) for x in COUNTRIES]
items.sort(lambda x,y: cmp(x[1], y[1]))
return items
def getDefaultCountry(self):
portal = getToolByName(self, 'portal_url').getPortalObject()
bs = portal._getOb('bika_setup')
return bs.getDefaultCountry()
def getStates(self, country):
items = []
if not country:
return items
# get ISO code for country
iso = [c for c in COUNTRIES if c['Country'] == country or c['ISO'] == country]
if not iso:
return items
iso = iso[0]['ISO']
items = [x for x in STATES if x[0] == iso]
items.sort(lambda x,y: cmp(x[2], y[2]))
return items
def getDistricts(self, country, state):
items = []
if not country or not state:
return items
# get ISO code for country
iso = [c for c in COUNTRIES if c['Country'] == country or c['ISO'] == country]
if not iso:
return items
iso = iso[0]['ISO']
# get NUMBER of the state for lookup
snr = [s for s in STATES if s[0] == iso and s[2] == state]
if not snr:
return items
snr = snr[0][1]
items = [x for x in DISTRICTS if x[0] == iso and x[1] == snr]
items.sort(lambda x,y: cmp(x[1], y[1]))
return items
registerWidget(AddressWidget,
title = 'Address Widget',
description = ('Simple address widget with country/state lookups'),
) |
# -*- coding: utf-8 -*-
import copy
from lxml import etree, html
from openerp import SUPERUSER_ID, tools
from openerp.addons.website.models import website
from openerp.http import request
from openerp.osv import osv, fields
class view(osv.osv):
_inherit = "ir.ui.view"
_columns = {
'page': fields.boolean("Whether this view is a web page template (complete)"),
'website_meta_title': fields.char("Website meta title", size=70, translate=True),
'<API key>': fields.text("Website meta description", size=160, translate=True),
'<API key>': fields.char("Website meta keywords", translate=True),
'customize_show': fields.boolean("Show As Optional Inherit"),
'website_id': fields.many2one('website',ondelete='cascade', string="Website"),
}
_sql_constraints = [
('key_website_id_uniq', 'unique(key, website_id)',
'Key must be unique per website.'),
]
_defaults = {
'page': False,
'customize_show': False,
}
def _view_obj(self, cr, uid, view_id, context=None):
if isinstance(view_id, basestring):
return self.pool['ir.model.data'].xmlid_to_object(
cr, uid, view_id, raise_if_not_found=True, context=context
)
elif isinstance(view_id, (int, long)):
return self.browse(cr, uid, view_id, context=context)
# assume it's already a view object (WTF?)
return view_id
# Returns all views (called and inherited) related to a view
# Used by translation mechanism, SEO and optional templates
def _views_get(self, cr, uid, view_id, options=True, bundles=False, context=None, root=True):
""" For a given view ``view_id``, should return:
* the view itself
* all views inheriting from it, enabled or not
- but not the optional children of a non-enabled child
* all views called from it (via t-call)
"""
try:
view = self._view_obj(cr, uid, view_id, context=context)
except ValueError:
# Shall we log that ?
return []
while root and view.inherit_id:
view = view.inherit_id
result = [view]
node = etree.fromstring(view.arch)
xpath = "//t[@t-call]"
if bundles:
xpath += "| //t[@t-call-assets]"
for child in node.xpath(xpath):
try:
called_view = self._view_obj(cr, uid, child.get('t-call', child.get('t-call-assets')), context=context)
except ValueError:
continue
if called_view not in result:
result += self._views_get(cr, uid, called_view, options=options, bundles=bundles, context=context)
extensions = view.<API key>
if not options:
# only active children
extensions = (v for v in view.<API key> if v.active)
# Keep options in a deterministic order regardless of their applicability
for extension in sorted(extensions, key=lambda v: v.id):
for r in self._views_get(
cr, uid, extension,
# only return optional grandchildren if this child is enabled
options=extension.active,
context=context, root=False):
if r not in result:
result.append(r)
return result
def <API key>(self, cr, uid, arch, context=None):
""" Update a view section. The view section may embed fields to write
:param str model:
:param int res_id:
:param str xpath: valid xpath to the tag to replace
""" |
// This file is part of MinIO Object Storage stack
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package event
import (
"reflect"
"testing"
)
func TestNewPattern(t *testing.T) {
testCases := []struct {
prefix string
suffix string
expectedResult string
}{
{"", "", ""},
{"*", "", "*"},
{"", "*", "*"},
{"201*/images/", "jpg", "201*/images/*jpg"}, |
package org.kuali.kra.iacuc.committee.service;
import org.kuali.coeus.common.committee.impl.service.<API key>;
import org.kuali.kra.iacuc.committee.bo.IacucCommittee;
import org.kuali.kra.iacuc.committee.bo.<API key>;
public interface <API key> extends <API key><IacucCommittee, <API key>> {
} |
function get_use_values(name){
v = $('.use-value-'+name);
r = [];
$.each(v, function(idx, name){
console.log('use-value?'+$(this).html()+' '+idx+' '+name);
var t = $(this).html();
r.push(t);
});
//console.log(dump(r));
console.log('Inline?'+r.join(','));
return r.join(',')
}
// Go autofill tags
$(document).ready(function(){
$(".to_use_complete").each(function(idx, elt){
var raw_use = $(this).attr('data-use').split(',');
var cls = $(this).attr('data-cls');
var pop = [];
// If we got a '' value, a each will put a void element...
if(raw_use != ''){
$.each(raw_use, function(idx, v){pop.push({id:v, name : v})});
};
/*
Ok, go for the huge part. We want a auto loading of the elements from /lookup/tag,
as a POST (query = value), we don't want duplicate objects (stupid for tag),
and the formater will put a good class to we can get the data back, and put a
picture from the sets. If not available, hide the picture :p.
The ref_id is an hack from original code so in the tokenFormatter we know
what we are refering from...
yes, I said huge :)
*/
$(this).tokenInput("/lookup/"+cls+"/tag",
{'theme' : 'facebook',
prePopulate: pop,
method : 'POST', queryParam:'value',
preventDuplicates: true,
tokenFormatter: function(item) { return "<li><img class='imgsize1' onerror=\"$(this).hide()\" src=\"/static/images/sets/"+item[this.propertyToSearch]+"/tag.png\" /> <p class='use-value-"+this.ref_id+"'>"+item[this.propertyToSearch] + "</p></li>" },ref_id : $(this).attr('id')
});
});
});
/*
Thanks to jquery UI make a sortable is just easy.
*/
$(function() {
$( ".<API key> ).sortable();
$( ".<API key> ).disableSelection();
}); |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/bigtable/v2/data.proto
namespace Google\Cloud\Bigtable\V2;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
class RowFilter extends \Google\Protobuf\Internal\Message
{
protected $filter;
public function __construct() {
\GPBMetadata\Google\Bigtable\V2\Data::initOnce();
parent::__construct();
}
/**
* Applies several RowFilters to the data in sequence, progressively
* narrowing the results.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Chain chain = 1;</code>
* @return \Google\Cloud\Bigtable\V2\RowFilter_Chain
*/
public function getChain()
{
return $this->readOneof(1);
}
/**
* Applies several RowFilters to the data in sequence, progressively
* narrowing the results.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Chain chain = 1;</code>
* @param \Google\Cloud\Bigtable\V2\RowFilter_Chain $var
* @return $this
*/
public function setChain($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\RowFilter_Chain::class);
$this->writeOneof(1, $var);
return $this;
}
/**
* Applies several RowFilters to the data in parallel and combines the
* results.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Interleave interleave = 2;</code>
* @return \Google\Cloud\Bigtable\V2\<API key>
*/
public function getInterleave()
{
return $this->readOneof(2);
}
/**
* Applies several RowFilters to the data in parallel and combines the
* results.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Interleave interleave = 2;</code>
* @param \Google\Cloud\Bigtable\V2\<API key> $var
* @return $this
*/
public function setInterleave($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\<API key>::class);
$this->writeOneof(2, $var);
return $this;
}
/**
* Applies one of two possible RowFilters to the data based on the output of
* a predicate RowFilter.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Condition condition = 3;</code>
* @return \Google\Cloud\Bigtable\V2\RowFilter_Condition
*/
public function getCondition()
{
return $this->readOneof(3);
}
/**
* Applies one of two possible RowFilters to the data based on the output of
* a predicate RowFilter.
*
* Generated from protobuf field <code>.google.bigtable.v2.RowFilter.Condition condition = 3;</code>
* @param \Google\Cloud\Bigtable\V2\RowFilter_Condition $var
* @return $this
*/
public function setCondition($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\RowFilter_Condition::class);
$this->writeOneof(3, $var);
return $this;
}
public function getSink()
{
return $this->readOneof(16);
}
public function setSink($var)
{
GPBUtil::checkBool($var);
$this->writeOneof(16, $var);
return $this;
}
/**
* Matches all cells, regardless of input. Functionally equivalent to
* leaving `filter` unset, but included for completeness.
*
* Generated from protobuf field <code>bool pass_all_filter = 17;</code>
* @return bool
*/
public function getPassAllFilter()
{
return $this->readOneof(17);
}
/**
* Matches all cells, regardless of input. Functionally equivalent to
* leaving `filter` unset, but included for completeness.
*
* Generated from protobuf field <code>bool pass_all_filter = 17;</code>
* @param bool $var
* @return $this
*/
public function setPassAllFilter($var)
{
GPBUtil::checkBool($var);
$this->writeOneof(17, $var);
return $this;
}
/**
* Does not match any cells, regardless of input. Useful for temporarily
* disabling just part of a filter.
*
* Generated from protobuf field <code>bool block_all_filter = 18;</code>
* @return bool
*/
public function getBlockAllFilter()
{
return $this->readOneof(18);
}
/**
* Does not match any cells, regardless of input. Useful for temporarily
* disabling just part of a filter.
*
* Generated from protobuf field <code>bool block_all_filter = 18;</code>
* @param bool $var
* @return $this
*/
public function setBlockAllFilter($var)
{
GPBUtil::checkBool($var);
$this->writeOneof(18, $var);
return $this;
}
/**
* Matches only cells from rows whose keys satisfy the given RE2 regex. In
* other words, passes through the entire row when the key matches, and
* otherwise produces an empty row.
* Note that, since row keys can contain arbitrary bytes, the `\C` escape
* sequence must be used if a true wildcard is desired. The `.` character
* will not match the new line character `\n`, which may be present in a
* binary key.
*
* Generated from protobuf field <code>bytes <API key> = 4;</code>
* @return string
*/
public function <API key>()
{
return $this->readOneof(4);
}
/**
* Matches only cells from rows whose keys satisfy the given RE2 regex. In
* other words, passes through the entire row when the key matches, and
* otherwise produces an empty row.
* Note that, since row keys can contain arbitrary bytes, the `\C` escape
* sequence must be used if a true wildcard is desired. The `.` character
* will not match the new line character `\n`, which may be present in a
* binary key.
*
* Generated from protobuf field <code>bytes <API key> = 4;</code>
* @param string $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkString($var, False);
$this->writeOneof(4, $var);
return $this;
}
/**
* Matches all cells from a row with probability p, and matches no cells
* from the row with probability 1-p.
*
* Generated from protobuf field <code>double row_sample_filter = 14;</code>
* @return float
*/
public function getRowSampleFilter()
{
return $this->readOneof(14);
}
/**
* Matches all cells from a row with probability p, and matches no cells
* from the row with probability 1-p.
*
* Generated from protobuf field <code>double row_sample_filter = 14;</code>
* @param float $var
* @return $this
*/
public function setRowSampleFilter($var)
{
GPBUtil::checkDouble($var);
$this->writeOneof(14, $var);
return $this;
}
/**
* Matches only cells from columns whose families satisfy the given RE2
* regex. For technical reasons, the regex must not contain the `:`
* character, even if it is not being used as a literal.
* Note that, since column families cannot contain the new line character
* `\n`, it is sufficient to use `.` as a full wildcard when matching
* column family names.
*
* Generated from protobuf field <code>string <API key> = 5;</code>
* @return string
*/
public function <API key>()
{
return $this->readOneof(5);
}
/**
* Matches only cells from columns whose families satisfy the given RE2
* regex. For technical reasons, the regex must not contain the `:`
* character, even if it is not being used as a literal.
* Note that, since column families cannot contain the new line character
* `\n`, it is sufficient to use `.` as a full wildcard when matching
* column family names.
*
* Generated from protobuf field <code>string <API key> = 5;</code>
* @param string $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkString($var, True);
$this->writeOneof(5, $var);
return $this;
}
/**
* Matches only cells from columns whose qualifiers satisfy the given RE2
* regex.
* Note that, since column qualifiers can contain arbitrary bytes, the `\C`
* escape sequence must be used if a true wildcard is desired. The `.`
* character will not match the new line character `\n`, which may be
* present in a binary qualifier.
*
* Generated from protobuf field <code>bytes <API key> = 6;</code>
* @return string
*/
public function <API key>()
{
return $this->readOneof(6);
}
/**
* Matches only cells from columns whose qualifiers satisfy the given RE2
* regex.
* Note that, since column qualifiers can contain arbitrary bytes, the `\C`
* escape sequence must be used if a true wildcard is desired. The `.`
* character will not match the new line character `\n`, which may be
* present in a binary qualifier.
*
* Generated from protobuf field <code>bytes <API key> = 6;</code>
* @param string $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkString($var, False);
$this->writeOneof(6, $var);
return $this;
}
/**
* Matches only cells from columns within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.ColumnRange column_range_filter = 7;</code>
* @return \Google\Cloud\Bigtable\V2\ColumnRange
*/
public function <API key>()
{
return $this->readOneof(7);
}
/**
* Matches only cells from columns within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.ColumnRange column_range_filter = 7;</code>
* @param \Google\Cloud\Bigtable\V2\ColumnRange $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\ColumnRange::class);
$this->writeOneof(7, $var);
return $this;
}
/**
* Matches only cells with timestamps within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.TimestampRange <API key> = 8;</code>
* @return \Google\Cloud\Bigtable\V2\TimestampRange
*/
public function <API key>()
{
return $this->readOneof(8);
}
/**
* Matches only cells with timestamps within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.TimestampRange <API key> = 8;</code>
* @param \Google\Cloud\Bigtable\V2\TimestampRange $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\TimestampRange::class);
$this->writeOneof(8, $var);
return $this;
}
/**
* Matches only cells with values that satisfy the given regular expression.
* Note that, since cell values can contain arbitrary bytes, the `\C` escape
* sequence must be used if a true wildcard is desired. The `.` character
* will not match the new line character `\n`, which may be present in a
* binary value.
*
* Generated from protobuf field <code>bytes value_regex_filter = 9;</code>
* @return string
*/
public function getValueRegexFilter()
{
return $this->readOneof(9);
}
/**
* Matches only cells with values that satisfy the given regular expression.
* Note that, since cell values can contain arbitrary bytes, the `\C` escape
* sequence must be used if a true wildcard is desired. The `.` character
* will not match the new line character `\n`, which may be present in a
* binary value.
*
* Generated from protobuf field <code>bytes value_regex_filter = 9;</code>
* @param string $var
* @return $this
*/
public function setValueRegexFilter($var)
{
GPBUtil::checkString($var, False);
$this->writeOneof(9, $var);
return $this;
}
/**
* Matches only cells with values that fall within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.ValueRange value_range_filter = 15;</code>
* @return \Google\Cloud\Bigtable\V2\ValueRange
*/
public function getValueRangeFilter()
{
return $this->readOneof(15);
}
/**
* Matches only cells with values that fall within the given range.
*
* Generated from protobuf field <code>.google.bigtable.v2.ValueRange value_range_filter = 15;</code>
* @param \Google\Cloud\Bigtable\V2\ValueRange $var
* @return $this
*/
public function setValueRangeFilter($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Bigtable\V2\ValueRange::class);
$this->writeOneof(15, $var);
return $this;
}
/**
* Skips the first N cells of each row, matching all subsequent cells.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 10;</code>
* @return int
*/
public function <API key>()
{
return $this->readOneof(10);
}
/**
* Skips the first N cells of each row, matching all subsequent cells.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 10;</code>
* @param int $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkInt32($var);
$this->writeOneof(10, $var);
return $this;
}
/**
* Matches only the first N cells of each row.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 11;</code>
* @return int
*/
public function <API key>()
{
return $this->readOneof(11);
}
/**
* Matches only the first N cells of each row.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 11;</code>
* @param int $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkInt32($var);
$this->writeOneof(11, $var);
return $this;
}
/**
* Matches only the most recent N cells within each column. For example,
* if N=2, this filter would match column `foo:bar` at timestamps 10 and 9,
* skip all earlier cells in `foo:bar`, and then begin matching again in
* column `foo:bar2`.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 12;</code>
* @return int
*/
public function <API key>()
{
return $this->readOneof(12);
}
/**
* Matches only the most recent N cells within each column. For example,
* if N=2, this filter would match column `foo:bar` at timestamps 10 and 9,
* skip all earlier cells in `foo:bar`, and then begin matching again in
* column `foo:bar2`.
* If duplicate cells are present, as is possible when using an Interleave,
* each copy of the cell is counted separately.
*
* Generated from protobuf field <code>int32 <API key> = 12;</code>
* @param int $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkInt32($var);
$this->writeOneof(12, $var);
return $this;
}
/**
* Replaces each cell's value with the empty string.
*
* Generated from protobuf field <code>bool <API key> = 13;</code>
* @return bool
*/
public function <API key>()
{
return $this->readOneof(13);
}
/**
* Replaces each cell's value with the empty string.
*
* Generated from protobuf field <code>bool <API key> = 13;</code>
* @param bool $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkBool($var);
$this->writeOneof(13, $var);
return $this;
}
/**
* Applies the given label to all cells in the output row. This allows
* the client to determine which results were produced from which part of
* the filter.
* Values must be at most 15 characters in length, and match the RE2
* pattern `[a-z0-9\\-]+`
* Due to a technical limitation, it is not currently possible to apply
* multiple labels to a cell. As a result, a Chain may have no more than
* one sub-filter which contains a `<API key>`. It is okay for
* an Interleave to contain multiple `<API key>`, as they
* will be applied to separate copies of the input. This may be relaxed in
* the future.
*
* Generated from protobuf field <code>string <API key> = 19;</code>
* @return string
*/
public function <API key>()
{
return $this->readOneof(19);
}
/**
* Applies the given label to all cells in the output row. This allows
* the client to determine which results were produced from which part of
* the filter.
* Values must be at most 15 characters in length, and match the RE2
* pattern `[a-z0-9\\-]+`
* Due to a technical limitation, it is not currently possible to apply
* multiple labels to a cell. As a result, a Chain may have no more than
* one sub-filter which contains a `<API key>`. It is okay for
* an Interleave to contain multiple `<API key>`, as they
* will be applied to separate copies of the input. This may be relaxed in
* the future.
*
* Generated from protobuf field <code>string <API key> = 19;</code>
* @param string $var
* @return $this
*/
public function <API key>($var)
{
GPBUtil::checkString($var, True);
$this->writeOneof(19, $var);
return $this;
}
/**
* @return string
*/
public function getFilter()
{
return $this->whichOneof("filter");
}
} |
""" Management command to link program enrollments and external student_keys to an LMS user """
from uuid import UUID
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from lms.djangoapps.program_enrollments.api import <API key>
User = get_user_model()
<API key> = (
"incorrectly formatted argument '{}', "
"must be in form <external user key>:<lms username>"
)
<API key> = 'external user key {} provided multiple times'
class Command(BaseCommand):
"""
Management command to manually link ProgramEnrollments without an LMS user to an LMS user by
username.
Usage:
./manage.py lms <API key> <program_uuid> <user_item>*
where a <user_item> is a string formatted as <external_user_key>:<lms_username>
Normally, program enrollments should be linked by the Django Social Auth post_save signal
handler `lms.djangoapps.program_enrollments.signals.matriculate_learner`, but in the case that
a partner does not have an IDP set up for learners to log in through, we need a way to link
enrollments.
Provided a program uuid and a list of external_user_key:lms_username, this command will look up
the matching program enrollments and users, and update the program enrollments with the matching
user. If the program enrollment has course enrollments, we will enroll the user into their
waiting program courses.
If an external user key is specified twice, an exception will be raised and no enrollments will
be modified.
For each external_user_key:lms_username, if:
- The user is not found
- No enrollment is found for the given program and external_user_key
- The enrollment already has a user
An error message will be logged and the input will be skipped. All other inputs will be
processed and enrollments updated.
If there is an error while enrolling a user in a waiting program course enrollment, the error
will be logged, and we will roll back all transactions for that user so that their db state will
be the same as it was before this command was run. This is to allow the re-running of the same
command again to correctly enroll the user once the issue preventing the enrollment has been
resolved.
No other users will be affected, they will be processed normally.
"""
help = 'Manually links ProgramEnrollment records to LMS users'
def add_arguments(self, parser):
parser.add_argument(
'program_uuid',
help='the program in which we are linking enrollments to users',
)
parser.add_argument(
'user_items',
nargs='*',
help='specify the users to link, in the format <<API key>>:<lms_username>*',
)
# pylint: disable=arguments-differ
def handle(self, program_uuid, user_items, *args, **options):
try:
parsed_program_uuid = UUID(program_uuid)
except ValueError:
raise CommandError("supplied program_uuid '{}' is not a valid UUID")
<API key> = self.parse_user_items(user_items)
try:
<API key>(
parsed_program_uuid, <API key>
)
except Exception as e:
raise CommandError(str(e))
def parse_user_items(self, user_items):
"""
Params:
list of strings in the format 'external_user_key:lms_username'
Returns:
dict mapping external user keys to lms usernames
Raises:
CommandError
"""
result = {}
for user_item in user_items:
split_args = user_item.split(':')
if len(split_args) != 2:
message = <API key>.format(user_item)
raise CommandError(message)
external_user_key = split_args[0].strip()
lms_username = split_args[1].strip()
if not (external_user_key and lms_username):
message = <API key>.format(user_item)
raise CommandError(message)
if external_user_key in result:
raise CommandError(<API key>.format(external_user_key))
result[external_user_key] = lms_username
return result |
#include <cstddef>
extern "C" {
// Exceptions are disabled on the STM32 platforms, and default implementations of these functions
// pull malloc() and free() into the bootloader
void* <API key>(size_t) throw() {
return nullptr;
}
void <API key>(void*) throw() {
}
} // extern "C" |
# -*- coding: utf-8 -*-
from openerp import models, api
class ProductProduct(models.Model):
_inherit = 'product.product'
@api.multi
def <API key>(self):
for product in self:
if (product.type == 'service' and len(product.route_ids) == 2 and
self.env.ref('stock.<API key>').id in
product.route_ids.ids and
self.env.ref('purchase.<API key>').id in
product.route_ids.ids):
return True
return False
@api.multi
def need_procurement(self):
for product in self:
if product.<API key>():
return True
return super(ProductProduct, self).need_procurement() |
require 'spec_helper'
module Chingu
describe Parallax do
before :each do
@game = Chingu::Window.new
# Gosu uses the paths based on where rspec is, not where this file is, so we need to do it manually!
Gosu::Image::autoload_dirs.unshift File.join(File.dirname(File.expand_path(__FILE__)), 'images')
end
after :each do
@game.close
end
describe "layers" do
it "should have 3 different ways of adding layers" do
subject << {:image => "rect_20x20.png", :repeat_x => true, :repeat_y => true}
subject.add_layer(:image => "rect_20x20.png", :repeat_x => true, :repeat_y => true)
subject << ParallaxLayer.new(:image => "rect_20x20.png", :repeat_x => true, :repeat_y => true)
subject.layers.count.should equal 3
end
it "should have incrementing zorder" do
3.times do
subject.add_layer(:image => "rect_20x20.png")
end
subject.layers[1].zorder.should equal (subject.layers[0].zorder + 1)
subject.layers[2].zorder.should equal (subject.layers[0].zorder + 2)
end
it "should start incrementing zorder in layers from Parallax-instance zorder if available" do
parallax = Parallax.new(:zorder => 2000)
3.times { parallax.add_layer(:image => "rect_20x20.png") }
parallax.layers[0].zorder.should == 2000
parallax.layers[1].zorder.should == 2001
parallax.layers[2].zorder.should == 2002
end
end
end
end |
<html>
<head>
<meta charset='utf-8'>
<style>
.pass {
font-weight: bold;
color: green;
}
.fail {
font-weight: bold;
color: red;
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function SputnikError(message)
{
this.message = message;
}
SputnikError.prototype.toString = function ()
{
return 'SputnikError: ' + this.message;
};
var sputnikException;
function testPrint(msg)
{
var span = document.createElement("span");
document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
span.innerHTML = msg + '<br />';
}
function escapeHTML(text)
{
return text.toString().replace(/&/g, "&").replace(/</g, "<");
}
function printTestPassed(msg)
{
testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>');
}
function printTestFailed(msg)
{
testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>');
}
function testFailed(msg)
{
throw new SputnikError(msg);
}
var successfullyParsed = false;
</script>
</head>
<body>
<p>S15.10.2.8_A2_T3</p>
<div id='console'></div>
<script>
try {
/**
* @name: S15.10.2.8_A2_T3;
* @section: 15.10.2.8;
* @assertion: The form (?! Disjunction ) specifies a zero-width negative lookahead.
* In order for it to succeed, the pattern inside Disjunction must fail to match at the current position.
* The current position is not advanced before matching the sequel;
* @description: Execute /Java(?!Script)([A-Z]\w*)/.test("using of Java language") and check results;
*/
__executed = /Java(?!Script)([A-Z]\w*)/.test("using of Java language");
//CHECK
if (__executed) {
testFailed('
}
} catch (ex) {
sputnikException = ex;
}
var successfullyParsed = true;
</script>
<script>
if (!successfullyParsed)
printTestFailed('successfullyParsed is not set');
else if (sputnikException)
printTestFailed(sputnikException);
else
printTestPassed("");
testPrint('<br /><span class="pass">TEST COMPLETE</span>');
</script>
</body>
</html> |
package net.minecraftforge.items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.INBTSerializable;
public class ItemStackHandler implements IItemHandler, <API key>, INBTSerializable<NBTTagCompound>
{
protected ItemStack[] stacks;
public ItemStackHandler()
{
this(1);
}
public ItemStackHandler(int size)
{
stacks = new ItemStack[size];
}
public void setSize(int size)
{
stacks = new ItemStack[size];
}
@Override
public void setStackInSlot(int slot, ItemStack stack)
{
validateSlotIndex(slot);
if (ItemStack.areItemStacksEqual(this.stacks[slot], stack))
return;
this.stacks[slot] = stack;
onContentsChanged(slot);
}
@Override
public int getSlots()
{
return stacks.length;
}
@Override
public ItemStack getStackInSlot(int slot)
{
validateSlotIndex(slot);
return this.stacks[slot];
}
@Override
public ItemStack insertItem(int slot, ItemStack stack, boolean simulate)
{
if (stack == null || stack.stackSize == 0)
return null;
validateSlotIndex(slot);
ItemStack existing = this.stacks[slot];
int limit = getStackLimit(slot, stack);
if (existing != null)
{
if (!ItemHandlerHelper.canItemStacksStack(stack, existing))
return stack;
limit -= existing.stackSize;
}
if (limit <= 0)
return stack;
boolean reachedLimit = stack.stackSize > limit;
if (!simulate)
{
if (existing == null)
{
this.stacks[slot] = reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack;
}
else
{
existing.stackSize += reachedLimit ? limit : stack.stackSize;
}
onContentsChanged(slot);
}
return reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, stack.stackSize - limit) : null;
}
public ItemStack extractItem(int slot, int amount, boolean simulate)
{
if (amount == 0)
return null;
validateSlotIndex(slot);
ItemStack existing = this.stacks[slot];
if (existing == null)
return null;
int toExtract = Math.min(amount, existing.getMaxStackSize());
if (existing.stackSize <= toExtract)
{
if (!simulate)
{
this.stacks[slot] = null;
onContentsChanged(slot);
}
return existing;
}
else
{
if (!simulate)
{
this.stacks[slot] = ItemHandlerHelper.copyStackWithSize(existing, existing.stackSize - toExtract);
onContentsChanged(slot);
}
return ItemHandlerHelper.copyStackWithSize(existing, toExtract);
}
}
protected int getStackLimit(int slot, ItemStack stack)
{
return stack.getMaxStackSize();
}
@Override
public NBTTagCompound serializeNBT()
{
NBTTagList nbtTagList = new NBTTagList();
for (int i = 0; i < stacks.length; i++)
{
if (stacks[i] != null)
{
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setInteger("Slot", i);
stacks[i].writeToNBT(itemTag);
nbtTagList.appendTag(itemTag);
}
}
NBTTagCompound nbt = new NBTTagCompound();
nbt.setTag("Items", nbtTagList);
nbt.setInteger("Size", stacks.length);
return nbt;
}
@Override
public void deserializeNBT(NBTTagCompound nbt)
{
setSize(nbt.hasKey("Size", Constants.NBT.TAG_INT) ? nbt.getInteger("Size") : stacks.length);
NBTTagList tagList = nbt.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tagList.tagCount(); i++)
{
NBTTagCompound itemTags = tagList.getCompoundTagAt(i);
int slot = itemTags.getInteger("Slot");
if (slot >= 0 && slot < stacks.length)
{
stacks[slot] = ItemStack.<API key>(itemTags);
}
}
onLoad();
}
protected void validateSlotIndex(int slot)
{
if (slot < 0 || slot >= stacks.length)
throw new RuntimeException("Slot " + slot + " not in valid range - [0," + stacks.length + ")");
}
protected void onLoad()
{
}
protected void onContentsChanged(int slot)
{
}
} |
# -*- coding: utf-8 -*-
# * This program is free software; you can redistribute it and/or modify *
# * as published by the Free Software Foundation; either version 2 of *
# * for detail see the LICENCE text file. *
# * This program is distributed in the hope that it will be useful, *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * You should have received a copy of the GNU Library General Public *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
''' Used for CNC machine Stops for Path module. Create an Optional or Mandatory Stop.'''
import FreeCAD
import FreeCADGui
import Path
from PySide import QtCore, QtGui
# Qt tanslation handling
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def translate(context, text, disambig=None):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def translate(context, text, disambig=None):
return QtGui.QApplication.translate(context, text, disambig)
class Stop:
def __init__(self,obj):
obj.addProperty("App::PropertyEnumeration", "Stop", "Path", QtCore.QT_TRANSLATE_NOOP("App::Property","Add Optional or Mandatory Stop to the program"))
obj.Stop=['Optional', 'Mandatory']
obj.Proxy = self
mode = 2
obj.setEditorMode('Placement', mode)
def __getstate__(self):
return None
def __setstate__(self, state):
return None
def onChanged(self, obj, prop):
pass
# FreeCAD.ActiveDocument.recompute()
def execute(self, obj):
if obj.Stop == 'Optional':
word = 'M1'
else:
word = 'M0'
output = ""
output = word + '\n'
path = Path.Path(output)
obj.Path = path
class _ViewProviderStop:
def __init__(self, vobj): # mandatory
# obj.addProperty("App::PropertyFloat","SomePropertyName","PropertyGroup","Description of this property")
vobj.Proxy = self
mode = 2
vobj.setEditorMode('LineWidth', mode)
vobj.setEditorMode('MarkerColor', mode)
vobj.setEditorMode('NormalColor', mode)
vobj.setEditorMode('ShowFirstRapid', mode)
vobj.setEditorMode('DisplayMode', mode)
vobj.setEditorMode('BoundingBox', mode)
vobj.setEditorMode('Selectable', mode)
vobj.setEditorMode('ShapeColor', mode)
vobj.setEditorMode('Transparency', mode)
vobj.setEditorMode('Visibility', mode)
def __getstate__(self): # mandatory
return None
def __setstate__(self, state): # mandatory
return None
def getIcon(self): # optional
return ":/icons/Path-Stop.svg"
def onChanged(self, vobj, prop): # optional
mode = 2
vobj.setEditorMode('LineWidth', mode)
vobj.setEditorMode('MarkerColor', mode)
vobj.setEditorMode('NormalColor', mode)
vobj.setEditorMode('ShowFirstRapid', mode)
vobj.setEditorMode('DisplayMode', mode)
vobj.setEditorMode('BoundingBox', mode)
vobj.setEditorMode('Selectable', mode)
vobj.setEditorMode('ShapeColor', mode)
vobj.setEditorMode('Transparency', mode)
vobj.setEditorMode('Visibility', mode)
class CommandPathStop:
def GetResources(self):
return {'Pixmap': 'Path-Stop',
'MenuText': QtCore.QT_TRANSLATE_NOOP("Path_Stop", "Stop"),
'Accel': "P, C",
'ToolTip': QtCore.QT_TRANSLATE_NOOP("Path_Stop", "Add Optional or Mandatory Stop to the program")}
def IsActive(self):
if FreeCAD.ActiveDocument is not None:
for o in FreeCAD.ActiveDocument.Objects:
if o.Name[:3] == "Job":
return True
return False
def Activated(self):
FreeCAD.ActiveDocument.openTransaction(
translate("Path_Stop", "Add Optional or Mandatory Stop to the program"))
FreeCADGui.addModule("PathScripts.PathStop")
snippet = '''
import Path
import PathScripts
from PathScripts import PathUtils
prjexists = False
obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython","Stop")
PathScripts.PathStop.Stop(obj)
PathScripts.PathStop._ViewProviderStop(obj.ViewObject)
PathUtils.addToJob(obj)
'''
FreeCADGui.doCommand(snippet)
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
if FreeCAD.GuiUp:
# register the FreeCAD command
FreeCADGui.addCommand('Path_Stop', CommandPathStop())
FreeCAD.Console.PrintLog("Loading PathStop... done\n") |
package org.litesoft.p2pchat;
public interface NewPeersSupport {
void addNewPeer(PeerInfo pInfo);
} |
<html>
<head>
<meta charset='utf-8'>
<style>
.pass {
font-weight: bold;
color: green;
}
.fail {
font-weight: bold;
color: red;
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function SputnikError(message)
{
this.message = message;
}
SputnikError.prototype.toString = function ()
{
return 'SputnikError: ' + this.message;
};
var sputnikException;
function testPrint(msg)
{
var span = document.createElement("span");
document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
span.innerHTML = msg + '<br />';
}
function escapeHTML(text)
{
return text.toString().replace(/&/g, "&").replace(/</g, "<");
}
function printTestPassed(msg)
{
testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>');
}
function printTestFailed(msg)
{
testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>');
}
function testFailed(msg)
{
throw new SputnikError(msg);
}
var successfullyParsed = false;
</script>
</head>
<body>
<p>S15.10.2.5_A1_T1</p>
<div id='console'></div>
<script>
try {
/**
* @name: S15.10.2.5_A1_T1;
* @section: 15.10.2.5;
* @assertion: An Atom followed by a Quantifier is repeated the number of times specified by the Quantifier;
* @description: Execute /a[a-z]{2,4}/.exec("abcdefghi") and check results;
*/
__executed = /a[a-z]{2,4}/.exec("abcdefghi");
__expected = ["abcde"];
__expected.index = 0;
__expected.input = "abcdefghi";
//CHECK
if (__executed.length !== __expected.length) {
testFailed('
}
//CHECK
if (__executed.index !== __expected.index) {
testFailed('
}
//CHECK
if (__executed.input !== __expected.input) {
testFailed('
}
//CHECK
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
testFailed('
}
}
} catch (ex) {
sputnikException = ex;
}
var successfullyParsed = true;
</script>
<script>
if (!successfullyParsed)
printTestFailed('successfullyParsed is not set');
else if (sputnikException)
printTestFailed(sputnikException);
else
printTestPassed("");
testPrint('<br /><span class="pass">TEST COMPLETE</span>');
</script>
</body>
</html> |
package org.wildfly.clustering.ejb.infinispan.group;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.Externalizer;
import org.wildfly.clustering.marshalling.jboss.<API key>;
import org.wildfly.clustering.marshalling.jboss.<API key>;
/**
* @author Paul Ferraro
*/
@MetaInfServices(Externalizer.class)
public class <API key><I, T> implements Externalizer<<API key><I, T>> {
private final Externalizer<<API key><Map<I, T>>> externalizer = new <API key><>();
@Override
public void writeObject(ObjectOutput output, <API key><I, T> entry) throws IOException {
<API key><Map<I, T>> value = (<API key><Map<I, T>>) entry.getBeans();
this.externalizer.writeObject(output, value);
}
@Override
public <API key><I, T> readObject(ObjectInput input) throws IOException, <API key> {
return new <API key><>(this.externalizer.readObject(input));
}
@SuppressWarnings("unchecked")
@Override
public Class<<API key><I, T>> getTargetClass() {
return (Class<<API key><I, T>>) (Class<?>) <API key>.class;
}
} |
package soot.jimple.infoflow.results.xml;
import java.io.<API key>;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import soot.jimple.Stmt;
import soot.jimple.infoflow.data.AccessPath;
import soot.jimple.infoflow.results.InfoflowResults;
import soot.jimple.infoflow.results.ResultSinkInfo;
import soot.jimple.infoflow.results.ResultSourceInfo;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
/**
* Class for serializing FlowDroid results to XML
*
* @author Steven Arzt
*
*/
public class <API key> {
public static final int FILE_FORMAT_VERSION = 100;
private boolean serializeTaintPath = false;
private final IInfoflowCFG icfg;
/**
* Creates a new instance of the <API key> class
*/
public <API key>() {
this(null);
}
/**
* Creates a new instance of the <API key> class
* @param cfg The control flow graph to be used for obtaining additional
* information such as the methods containing source or sink statements
*/
public <API key>(IInfoflowCFG cfg) {
this.icfg = cfg;
}
/**
* Serializes the given FlowDroid result object into the given file
* @param results The result object to serialize
* @param fileName The target file name
* @throws <API key> Thrown if target file cannot be used
* @throws XMLStreamException Thrown if the XML data cannot be written
*/
public void serialize(InfoflowResults results, String fileName)
throws <API key>, XMLStreamException {
OutputStream out = new FileOutputStream(fileName);
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.<API key>(out);
writer.writeStartDocument();
writer.writeStartElement(XmlConstants.Tags.root);
writer.writeAttribute(XmlConstants.Attributes.fileFormatVersion,
FILE_FORMAT_VERSION + "");
writer.writeStartElement(XmlConstants.Tags.results);
writeDataFlows(results, writer);
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
}
/**
* Writes the given data flow results into the given XML stream writer
* @param results The results to write out
* @param writer The stream writer into which to write the results
* @throws XMLStreamException Thrown if the XML data cannot be written
*/
private void writeDataFlows(InfoflowResults results,
XMLStreamWriter writer) throws XMLStreamException {
for (ResultSinkInfo sink : results.getResults().keySet()) {
writer.writeStartElement(XmlConstants.Tags.result);
writeSinkInfo(sink, writer);
// Write out the sources
writer.writeStartElement(XmlConstants.Tags.sources);
for (ResultSourceInfo src : results.getResults().get(sink))
writeSourceInfo(src, writer);
writer.writeEndElement();
writer.writeEndElement();
}
}
/**
* Writes the given source information into the given XML stream writer
* @param source The source information to write out
* @param writer The stream writer into which to write the results
* @throws XMLStreamException Thrown if the XML data cannot be written
*/
private void writeSourceInfo(ResultSourceInfo source, XMLStreamWriter writer)
throws XMLStreamException {
writer.writeStartElement(XmlConstants.Tags.source);
writer.writeAttribute(XmlConstants.Attributes.statement,
source.getSource().toString());
if (icfg != null)
writer.writeAttribute(XmlConstants.Attributes.method,
icfg.getMethodOf(source.getSource()).getSignature());
writeAccessPath(source.getAccessPath(), writer);
if (serializeTaintPath && source.getPath() != null) {
writer.writeStartElement(XmlConstants.Tags.taintPath);
for (int i = 0; i < source.getPath().length; i++) {
writer.writeStartElement(XmlConstants.Tags.pathElement);
Stmt curStmt = source.getPath()[i];
writer.writeAttribute(XmlConstants.Attributes.statement,
curStmt.toString());
if (icfg != null)
writer.writeAttribute(XmlConstants.Attributes.method,
icfg.getMethodOf(curStmt).getSignature());
AccessPath curAP = source.getPathAccessPaths()[i];
writeAccessPath(curAP, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
/**
* Writes the given sink information into the given XML stream writer
* @param sink The sink information to write out
* @param writer The stream writer into which to write the results
* @throws XMLStreamException Thrown if the XML data cannot be written
*/
private void writeSinkInfo(ResultSinkInfo sink, XMLStreamWriter writer)
throws XMLStreamException {
writer.writeStartElement(XmlConstants.Tags.sink);
writer.writeAttribute(XmlConstants.Attributes.statement,
sink.getSink().toString());
if (icfg != null)
writer.writeAttribute(XmlConstants.Attributes.method,
icfg.getMethodOf(sink.getSink()).getSignature());
writeAccessPath(sink.getAccessPath(), writer);
writer.writeEndElement();
}
/**
* Writes the given access path int othe given XML stream writer
* @param accessPath The access path to write out
* @param writer The stream writer into which to write the data
* @throws XMLStreamException Thrown if the XML data cannot be written
*/
private void writeAccessPath(AccessPath accessPath, XMLStreamWriter writer)
throws XMLStreamException {
writer.writeStartElement(XmlConstants.Tags.accessPath);
if (accessPath.getPlainValue() != null)
writer.writeAttribute(XmlConstants.Attributes.value,
accessPath.getPlainValue().toString());
if (accessPath.getBaseType() != null)
writer.writeAttribute(XmlConstants.Attributes.type,
accessPath.getBaseType().toString());
writer.writeAttribute(XmlConstants.Attributes.taintSubFields,
accessPath.getTaintSubFields() ? XmlConstants.Values.TRUE
: XmlConstants.Values.FALSE);
// Write out the fields
if (accessPath.getFieldCount() > 0) {
writer.writeStartElement(XmlConstants.Tags.fields);
for (int i = 0; i < accessPath.getFieldCount(); i++) {
writer.writeStartElement(XmlConstants.Tags.field);
writer.writeAttribute(XmlConstants.Attributes.value,
accessPath.getFields()[i].toString());
writer.writeAttribute(XmlConstants.Attributes.type,
accessPath.getFieldTypes()[i].toString());
writer.writeEndElement();
}
writer.writeEndElement();
}
writer.writeEndElement();
}
/**
* Sets whether the taint propagation path shall be serialized along with
* the respective data flow result
* @param serialize True if taint propagation paths shall be serialized,
* otherwise false
*/
public void <API key>(boolean serialize) {
this.serializeTaintPath = serialize;
}
} |
<!DOCTYPE html>
<!
Create an oscillator with a custom WaveTable and generate a slow exponential tone sweep.
The result can be checked for the correct wave shape and for aliasing artifacts.
See oscillator-testing.js for details.
<html>
<head>
<script type="text/javascript" src="resources/audio-testing.js"></script>
<script type="text/javascript" src="resources/oscillator-testing.js"></script>
</head>
<body>
<script>
window.onload = init;
function init() {
if (!window.testRunner)
return;
<API key>(OSC.CUSTOM);
}
</script>
</body>
</html> |
#ifndef SVGAngle_h
#define SVGAngle_h
#if ENABLE(SVG)
#include "PlatformString.h"
#include "SVGNames.h"
namespace WebCore {
class SVGStyledElement;
class SVGAngle : public RefCounted<SVGAngle> {
public:
static PassRefPtr<SVGAngle> create()
{
return adoptRef(new SVGAngle);
}
virtual ~SVGAngle();
enum SVGAngleType {
<API key> = 0,
<API key> = 1,
SVG_ANGLETYPE_DEG = 2,
SVG_ANGLETYPE_RAD = 3,
SVG_ANGLETYPE_GRAD = 4
};
SVGAngleType unitType() const;
void setValue(float);
float value() const;
void <API key>(float <API key>);
float <API key>() const;
void setValueAsString(const String&);
String valueAsString() const;
void <API key>(unsigned short unitType, float <API key>);
void <API key>(unsigned short unitType);
// Throughout SVG 1.1 'SVGAngle' is only used for 'SVGMarkerElement' (orient-angle)
const QualifiedName& <API key>() const { return SVGNames::orientAttr; }
private:
SVGAngle();
SVGAngleType m_unitType;
float m_value;
float <API key>;
mutable String m_valueAsString;
void calculate();
};
} // namespace WebCore
#endif // ENABLE(SVG)
#endif // SVGAngle_h |
<html>
<head>
<meta charset='utf-8'>
<style>
.pass {
font-weight: bold;
color: green;
}
.fail {
font-weight: bold;
color: red;
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function SputnikError(message)
{
this.message = message;
}
SputnikError.prototype.toString = function ()
{
return 'SputnikError: ' + this.message;
};
var sputnikException;
function testPrint(msg)
{
var span = document.createElement("span");
document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
span.innerHTML = msg + '<br />';
}
function escapeHTML(text)
{
return text.toString().replace(/&/g, "&").replace(/</g, "<");
}
function printTestPassed(msg)
{
testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>');
}
function printTestFailed(msg)
{
testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>');
}
function testFailed(msg)
{
throw new SputnikError(msg);
}
var successfullyParsed = false;
</script>
</head>
<body>
<p>S11.5.1_A4_T7</p>
<div id='console'></div>
<script>
try {
/**
* @name: S11.5.1_A4_T7;
* @section: 11.5.1;
* @assertion: The result of a floating-point multiplication is governed by the rules of IEEE 754 double-precision arithmetics;
* @description: If the magnitude is too small to represent, the result is then a zero of appropriate sign;
*/
//CHECK
if (Number.MIN_VALUE * 0.1 !== 0) {
testFailed('
}
//CHECK
if (-0.1 * Number.MIN_VALUE !== -0) {
testFailed('
} else {
if (1 / (-0.1 * Number.MIN_VALUE) !== Number.NEGATIVE_INFINITY) {
testFailed('
}
}
//CHECK
if (Number.MIN_VALUE * 0.5 !== 0) {
testFailed('
}
//CHECK
if (-0.5 * Number.MIN_VALUE !== -0) {
testFailed('
} else {
if (1 / (-0.5 * Number.MIN_VALUE) !== Number.NEGATIVE_INFINITY) {
testFailed('
}
}
//CHECK
if (Number.MIN_VALUE * 0.51 !== Number.MIN_VALUE) {
testFailed('
}
//CHECK
if (-0.51 * Number.MIN_VALUE !== -Number.MIN_VALUE) {
testFailed('
}
//CHECK
if (Number.MIN_VALUE * 0.9 !== Number.MIN_VALUE) {
testFailed('
}
//CHECK
if (-0.9 * Number.MIN_VALUE !== -Number.MIN_VALUE) {
testFailed('
}
} catch (ex) {
sputnikException = ex;
}
var successfullyParsed = true;
</script>
<script>
if (!successfullyParsed)
printTestFailed('successfullyParsed is not set');
else if (sputnikException)
printTestFailed(sputnikException);
else
printTestPassed("");
testPrint('<br /><span class="pass">TEST COMPLETE</span>');
</script>
</body>
</html> |
# <API key>: (Apache-2.0 OR MIT)
from spack import *
class PerlTestMore(PerlPackage):
"""Test2 is a new testing framework produced by forking Test::Builder,
completely refactoring it, adding many new features and capabilities."""
homepage = "https://github.com/Test-More/test-more"
url = "https://github.com/Test-More/test-more/archive/v1.302183.tar.gz"
version('1.302183', sha256='<SHA256-like>')
version('1.302182', sha256='<SHA256-like>')
version('1.302181', sha256='<SHA256-like>')
version('1.302180', sha256='<SHA256-like>') |
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
#ifndef <API key>
#define <API key>
#include "<API key>.h"
//Forward Declarations
class <API key>;
template<>
InputParameters validParams<<API key>>();
/**
* This Userobject is the base class of Userobjects that generate one
* random number per timestep and quadrature point in a way that the integral
* over all random numbers is zero. It behaves as ConservedNoiseBase but allows
* the user to specify a multiplicator in the form of a MaterialProperty that is
* multiplied on each random number, effectively masking the random number field.
*
* \see <API key>
* \see <API key>
*/
class <API key> : public <API key>
{
public:
<API key>(const std::string & name, InputParameters parameters);
virtual ~<API key>() {}
virtual void initialize();
virtual void execute();
virtual void threadJoin(const UserObject & y);
virtual void finalize();
Real getQpValue(dof_id_type element_id, unsigned int qp) const;
protected:
<API key><dof_id_type, std::vector<std::pair<Real, Real> > > _random_data;
std::string _mask_property_name;
MaterialProperty<Real> & _mask;
};
#endif //<API key> |
# Produced at the Lawrence Livermore National Laboratory.
# This file is part of Spack.
# LLNL-CODE-647188
# This program is free software; you can redistribute it and/or modify
# published by the Free Software Foundation) version 2.1, February 1999.
# This program is distributed in the hope that it will be useful, but
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# You should have received a copy of the GNU Lesser General Public
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from spack import *
class Stc(AutotoolsPackage):
"""STC: The Swift-Turbine Compiler"""
homepage = 'http://swift-lang.org/Swift-T'
url = 'http://swift-lang.github.io/swift-t-downloads/stc-0.7.3.tar.gz'
version('0.7.3', '<API key>')
depends_on('java')
depends_on('ant')
depends_on('turbine')
depends_on('zsh', type='run')
def configure_args(self):
args = ['--with-turbine=' + self.spec['turbine'].prefix]
return args |
#ifndef <API key>
#define <API key>
#if ENABLE(SVG)
#include "SVGResource.h"
#include "Path.h"
namespace WebCore {
struct ClipData {
Path path;
WindRule windRule;
bool bboxUnits : 1;
};
class ClipDataList {
public:
void addPath(const Path& pathData, WindRule windRule, bool bboxUnits)
{
ClipData clipData;
clipData.path = pathData;
clipData.windRule = windRule;
clipData.bboxUnits = bboxUnits;
m_clipData.append(clipData);
}
void clear() { m_clipData.clear(); }
const Vector<ClipData>& clipData() const { return m_clipData; }
bool isEmpty() const { return m_clipData.isEmpty(); }
private:
Vector<ClipData> m_clipData;
};
class GraphicsContext;
class SVGResourceClipper : public SVGResource {
public:
static PassRefPtr<SVGResourceClipper> create() { return adoptRef(new SVGResourceClipper); }
virtual ~SVGResourceClipper();
void resetClipData();
void addClipData(const Path&, WindRule, bool bboxUnits);
const ClipDataList& clipData() const;
virtual SVGResourceType resourceType() const { return ClipperResourceType; }
virtual TextStream& <API key>(TextStream&) const;
// To be implemented by the specific rendering devices
void applyClip(GraphicsContext*, const FloatRect& boundingBox) const;
private:
SVGResourceClipper();
ClipDataList m_clipData;
};
TextStream& operator<<(TextStream&, WindRule);
TextStream& operator<<(TextStream&, const ClipData&);
SVGResourceClipper* getClipperById(Document*, const AtomicString&);
} // namespace WebCore
#endif
#endif // <API key> |
<html>
<head>
<meta charset='utf-8'>
<style>
.pass {
font-weight: bold;
color: green;
}
.fail {
font-weight: bold;
color: red;
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function SputnikError(message)
{
this.message = message;
}
SputnikError.prototype.toString = function ()
{
return 'SputnikError: ' + this.message;
};
var sputnikException;
function testPrint(msg)
{
var span = document.createElement("span");
document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
span.innerHTML = msg + '<br />';
}
function escapeHTML(text)
{
return text.toString().replace(/&/g, "&").replace(/</g, "<");
}
function printTestPassed(msg)
{
testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>');
}
function printTestFailed(msg)
{
testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>');
}
function testFailed(msg)
{
throw new SputnikError(msg);
}
var successfullyParsed = false;
</script>
</head>
<body>
<p>S15.9.4.3_A2_T1</p>
<div id='console'></div>
<script>
try {
/**
* @name: S15.9.4.3_A2_T1;
* @section: 15.9.4.3;
* @assertion: The "length" property of the "UTC" is 7;
* @description: The "length" property of the "UTC" is 7;
*/
if(Date.UTC.hasOwnProperty("length") !== true){
testFailed('#1: The UTC has a "length" property');
}
if(Date.UTC.length !== 7){
testFailed('#2: The "length" property of the UTC is 7');
}
} catch (ex) {
sputnikException = ex;
}
var successfullyParsed = true;
</script>
<script>
if (!successfullyParsed)
printTestFailed('successfullyParsed is not set');
else if (sputnikException)
printTestFailed(sputnikException);
else
printTestPassed("");
testPrint('<br /><span class="pass">TEST COMPLETE</span>');
</script>
</body>
</html> |
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
#include "data_encoder.h"
#include "data_list.h"
#include "text_encoder.h"
#include "src/util/strbuff.h"
#include "src/asn1/phd_types.h"
#include "api_definitions.h"
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <arpa/inet.h>
/**
*
* \addtogroup DataEncoder Data Encoder
* \ingroup API
*
* \brief Data encoder parses types of IEEE layer into data entries for high
* level application usage.
*
* @{
*/
/**
* Fills a simple data entry.
*
* @param simple data entry to be filled.
* @param name to set name field, this value will be deallocated on data-entry destruction.
* @param type to set type field, this value will be deallocated on data-entry destruction.
* @param value to set value field, this value will be deallocated on data-entry destruction.
*/
static void fill_simple(SimpleDataEntry *simple, char *name, char *type,
char *value)
{
if (simple == NULL)
return;
simple->name = name;
simple->type = type;
simple->value = value;
}
/**
* Sets data entry as simple data entry and fill the field values.
*
* @param data entry to be filled.
* @param name to set name field, this value will be deallocated on data-entry destruction.
* @param type to set type field, this value will be deallocated on data-entry destruction.
* @param value to set value field, this value will be deallocated on data-entry destruction.
*/
static void set_simple(DataEntry *data, char *name, char *type, char *value)
{
if (data == NULL)
return;
data->choice = SIMPLE_DATA_ENTRY;
fill_simple(&data->u.simple, name, type, value);
}
/**
* Set data entry as compound data entry.
*
* @param data compound data.
* @param name to set name field, this value will be deallocated on data-entry destruction.
* @param size number of child entries.
*/
static void set_cmp(DataEntry *data, char *name, int size)
{
if (data == NULL)
return;
data->choice = COMPOUND_DATA_ENTRY;
data->u.compound.name = name;
data->u.compound.entries_count = size;
data->u.compound.entries = calloc(size, sizeof(DataEntry));
}
/**
* Allocates a string in a new memory area and initializes its contents with
* the same value as the given string.
*
* @param str the initial value of the string just created.
* @return string a new string with the same value of the parameter.
*/
char *data_strcp(const char *str)
{
int len = strlen(str);
char *result = calloc(len + 1, sizeof(char));
strcpy(result, str);
return result;
}
/**
* Sets meta data attribute of this entry.
*
* @param data the entry to be modified.
* @param name name of meta-data attribute, this value will be deallocated on data-entry destruction.
* @param value value of meta-data attribute, this value will be deallocated on data-entry destruction.
*/
void data_set_meta_att(DataEntry *data, char *name, char *value)
{
if (data == NULL)
return;
// test if there is not elements in the list
if (data->meta_data.size == 0) {
data->meta_data.values = malloc(sizeof(struct MetaAtt));
} else {
// change the list size
data->meta_data.values = realloc(data->meta_data.values,
sizeof(struct MetaAtt) *
(data->meta_data.size + 1));
}
// add element to list
if (data->meta_data.values == NULL)
return;
MetaAtt *meta = &data->meta_data.values[data->meta_data.size];
meta->name = name;
meta->value = value;
data->meta_data.size += 1;
}
/**
* Fills compound child entry.
*
* @param cmp compound data entry.
* @param index of child entry in this compound.
* @param name to set name field, this value will be deallocated on data-entry destruction.
* @param type to set type field, this value will be deallocated on data-entry destruction.
* @param value to set value field, this value will be deallocated on data-entry destruction.
*/
static void fill_cmp_child(DataEntry *cmp, int index, char *name, char *type,
char *value)
{
if (cmp == NULL)
return;
set_simple(&cmp->u.compound.entries[index], name, type, value);
}
/**
* Sets meta attribute HANDLE.
*
* @param data the entry to have \b HANDLE attribute set.
* @param value the new value of entry's \b HANDLE attribute.
*/
void <API key>(DataEntry *data, ASN1_HANDLE value)
{
if (data == NULL)
return;
data_set_meta_att(data, data_strcp("HANDLE"), int2str(value));
}
/**
* Sets meta attribute partition-code.
*
* @param data the entry to have \b partition-code attribute set.
* @param part_code the new value of entry's \b partition-code attribute.
*/
void <API key>(DataEntry *data, int part_code)
{
if (data == NULL)
return;
data_set_meta_att(data, data_strcp("partition-code"), int2str(part_code));
}
/**
* Sets meta attribute attribute-id.
*
* @param data the entry to have \b attribute-id attribute set.
* @param attr_id the new value of entry's \b attribute-id attribute.
*/
void <API key>(DataEntry *data, intu16 attr_id)
{
if (data == NULL)
return;
data_set_meta_att(data, data_strcp("attribute-id"), intu16_2str(attr_id));
}
/**
* Sets meta attribute personal-id.
*
* @param data the entry to have \b personal-id attribute set.
* @param personal_id the new value of entry's \b personal-id attribute.
*/
void <API key>(DataEntry *data, intu16 personal_id)
{
if (data == NULL)
return;
data_set_meta_att(data, data_strcp("personal-id"), intu16_2str(personal_id));
}
/**
* Sets data entry with passed type.
*
* @param data the entry to have its attribute set.
* @param att_name the name of DIM attribute.
* @param value the new value of DIM attribute.
*/
void data_set_float(DataEntry *data, char *att_name,
FLOAT_Type *value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_FLOAT, float2str(*value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
*/
void <API key>(DataEntry *data,
char *att_name, SimpleNuObsValue *value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_FLOAT, float2str(*value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
* @param partition partition code used
* @param metric_id_list list of metric-ids used in the meta-data node
*/
void <API key>(DataEntry *data,
char *att_name, SimpleNuObsValueCmp *value, intu16 partition,
OID_Type *metric_id_list)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), value->count);
int i;
for (i = 0; i < value->count; ++i) {
fill_cmp_child(data, i, int2str(i), APIDEF_TYPE_FLOAT,
float2str(value->value[i]));
data_set_meta_att(&(data->u.compound.entries[i]), data_strcp("partition"),
intu16_2str(partition));
data_set_meta_att(&(data->u.compound.entries[i]), data_strcp("metric-id"),
intu16_2str(metric_id_list[i]));
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param <API key> the TypeVerList value
*/
void <API key>(DataEntry *data, char *att_name, TypeVerList * <API key>)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), <API key>->count);
int i;
for (i = 0; i < <API key>->count; ++i) {
DataEntry *child = &(data->u.compound.entries[i]);
set_cmp(child, int2str(i), 2);
fill_cmp_child(child, 0, data_strcp("version"), APIDEF_TYPE_INTU16,
intu16_2str(<API key>->value[i].version));
data_set_oid_type(&child->u.compound.entries[1], "type",
&<API key>->value[i].type);
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
*/
void <API key>(DataEntry *data, char *att_name,
BasicNuObsValue *value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_FLOAT, float2str(*value));
}
/**
* Set data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
* @param partition partition code used
* @param metric_id_list list of metric-ids used in the meta-data node
*/
void <API key>(DataEntry *data,
char *att_name, BasicNuObsValueCmp *value, intu16 partition,
OID_Type *metric_id_list)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), value->count);
int i;
for (i = 0; i < value->count; ++i) {
fill_cmp_child(data, i, int2str(i), APIDEF_TYPE_FLOAT,
float2str(value->value[i]));
data_set_meta_att(&(data->u.compound.entries[i]), data_strcp("partition"),
intu16_2str(partition));
data_set_meta_att(&(data->u.compound.entries[i]), data_strcp("metric-id"),
intu16_2str(metric_id_list[i]));
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
*/
void data_set_nu_obs_val(DataEntry *data, char *att_name,
NuObsValue *value)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 4);
fill_cmp_child(data, 1, data_strcp("state"), APIDEF_TYPE_INTU16,
intu16_2str(value->state));
fill_cmp_child(data, 2, data_strcp("unit-code"), APIDEF_TYPE_INTU16,
intu16_2str(value->unit_code));
fill_cmp_child(data, 3, data_strcp("value"), APIDEF_TYPE_INTU16, float2str(
value->value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value
* @param partition partition code used
*/
void <API key>(DataEntry *data, char *att_name,
NuObsValueCmp *value, intu16 partition)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), value->count);
DataEntry *nu_obs_entry = NULL;
int i = 0;
for (i = 0; i < value->count; ++i) {
nu_obs_entry = &data->u.compound.entries[i];
NuObsValue *nu_obs = &value->value[i];
data_set_nu_obs_val(nu_obs_entry, data_strcp("Nu-Observed-Value"), nu_obs);
data_set_meta_att(nu_obs_entry, data_strcp("partition"),
intu16_2str(partition));
data_set_meta_att(nu_obs_entry, data_strcp("metric-id"),
intu16_2str(nu_obs->metric_id));
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param time
*/
void <API key>(DataEntry *data, char *att_name,
AbsoluteTime *time)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 8);
fill_cmp_child(data, 0, data_strcp("century"), APIDEF_TYPE_INTU8,
bcdtime2number(time->century));
fill_cmp_child(data, 1, data_strcp("year"), APIDEF_TYPE_INTU8,
bcdtime2number(time->year));
fill_cmp_child(data, 2, data_strcp("month"), APIDEF_TYPE_INTU8,
bcdtime2number(time->month));
fill_cmp_child(data, 3, data_strcp("day"), APIDEF_TYPE_INTU8,
bcdtime2number(time->day));
fill_cmp_child(data, 4, data_strcp("hour"), APIDEF_TYPE_INTU8,
bcdtime2number(time->hour));
fill_cmp_child(data, 5, data_strcp("minute"), APIDEF_TYPE_INTU8,
bcdtime2number(time->minute));
fill_cmp_child(data, 6, data_strcp("second"), APIDEF_TYPE_INTU8,
bcdtime2number(time->second));
fill_cmp_child(data, 7, data_strcp("sec_fractions"), APIDEF_TYPE_INTU8,
bcdtime2number(time->sec_fractions));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param adj AbsoluteTimeAdjust value
*/
void <API key>(DataEntry *data, char *att_name, AbsoluteTimeAdjust *adj)
{
if (data == NULL)
return;
// AbsoluteTimeAdjust is a big-endian 6-octet uint embedded in a
// string of 6 octets because there is no INT-U48 type.
// Since there is no INT-U64 either, we opted by breaking
// the value in two parts than can easily be combined by
// client.
const intu16* phi = (const intu16*) &adj->value[0];
const intu32* plo = (const intu32*) &adj->value[2];
intu16 hi = ntohs(*phi);
intu32 lo = ntohl(*plo);
set_cmp(data, data_strcp(att_name), 2);
fill_cmp_child(data, 0, data_strcp("hi"), APIDEF_TYPE_INTU16, intu16_2str(hi));
fill_cmp_child(data, 1, data_strcp("lo"), APIDEF_TYPE_INTU32, intu32_2str(lo));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param spec
*/
void <API key>(DataEntry *data, char *att_name,
ProductionSpec *spec)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), spec->count);
DataEntry *prod_spec_entry = NULL;
int i = 0;
for (i = 0; i < spec->count; i++) {
prod_spec_entry = &data->u.compound.entries[i];
set_cmp(prod_spec_entry, int2str(i), 3);
fill_cmp_child(prod_spec_entry, 0, data_strcp("component-id"),
APIDEF_TYPE_INTU16, intu16_2str(
spec->value[i].component_id));
fill_cmp_child(prod_spec_entry, 1, data_strcp("prod-spec"),
APIDEF_TYPE_STRING, octet_string2str(
&spec->value[i].prod_spec));
fill_cmp_child(prod_spec_entry, 2, data_strcp("spec-type"),
APIDEF_TYPE_INTU16, intu16_2str(
spec->value[i].spec_type));
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param confid
*/
void <API key>(DataEntry *data, char *att_name,
ConfigId *confid)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16, intu16_2str(
*confid));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param system_model
*/
void <API key>(DataEntry *data, char *att_name,
SystemModel *system_model)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 2);
fill_cmp_child(data, 0, data_strcp("manufacturer"), APIDEF_TYPE_STRING,
octet_string2str(&system_model->manufacturer));
fill_cmp_child(data, 1, data_strcp("model-number"), APIDEF_TYPE_STRING,
octet_string2str(&system_model->model_number));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param system_id
*/
void data_set_system_id(DataEntry *data, char *att_name,
octet_string *system_id)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_HEX, octet_string2hex(
system_id));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param type
*/
void data_set_type(DataEntry *data, char *att_name, TYPE *type)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 2);
fill_cmp_child(data, 0, data_strcp("code"), APIDEF_TYPE_INTU16, intu16_2str(
type->code));
fill_cmp_child(data, 1, data_strcp("partition"), APIDEF_TYPE_INTU16,
intu16_2str(type->partition));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param oid_type
*/
void <API key>(DataEntry *data, char *att_name,
OID_Type oid_type)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(oid_type));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param simple_bit_str
*/
void <API key>(DataEntry *data, char *att_name,
BITS_32 simple_bit_str)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU32,
intu32_2str(simple_bit_str));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param basic_bit_str
*/
void <API key>(DataEntry *data, char *att_name,
BITS_16 basic_bit_str)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(basic_bit_str));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param simple_str
*/
void <API key>(DataEntry *data, char *att_name,
octet_string *simple_str)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_STRING,
octet_string2str(simple_str));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param enum_obs_value
*/
void <API key>(DataEntry *data, char *att_name,
EnumObsValue *enum_obs_value)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 3);
fill_cmp_child(data, 0, data_strcp("metric-id"), APIDEF_TYPE_INTU16,
intu16_2str(enum_obs_value->metric_id));
fill_cmp_child(data, 1, data_strcp("state"), APIDEF_TYPE_INTU16,
intu16_2str(enum_obs_value->state));
switch (enum_obs_value->value.choice) {
case OBJ_ID_CHOSEN:
fill_cmp_child(data, 2, data_strcp("enum_value"), APIDEF_TYPE_INTU16,
intu16_2str(enum_obs_value->value.u.enum_obj_id));
break;
case TEXT_STRING_CHOSEN:
fill_cmp_child(data, 2, data_strcp("enum_value"), APIDEF_TYPE_STRING,
octet_string2str(&(enum_obs_value->value.u.enum_text_string)));
break;
case BIT_STR_CHOSEN:
fill_cmp_child(data, 2, data_strcp("enum_value"), APIDEF_TYPE_INTU32,
intu32_2str(enum_obs_value->value.u.enum_bit_str));
break;
default:
break;
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param part_value
*/
void <API key>(DataEntry *data, char *att_name,
NomPartition part_value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(part_value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param sample_period
*/
void <API key>(DataEntry *data, char *att_name,
RelativeTime sample_period)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INT32,
int32_2str(sample_period));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param <API key>
*/
void <API key>(DataEntry *data, char *att_name,
octet_string *<API key>)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_STRING,
octet_string2str(<API key>));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param <API key>
*/
void <API key>(DataEntry *data, char *att_name,
ScaleRangeSpec8 *<API key>)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 4);
fill_cmp_child(data, 0, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 1, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 2, data_strcp("lower_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->lower_scaled_value));
fill_cmp_child(data, 03, data_strcp("upper_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->upper_scaled_value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param <API key>
*/
void <API key>(DataEntry *data, char *att_name,
ScaleRangeSpec16 *<API key>)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 4);
fill_cmp_child(data, 0, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 1, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 2, data_strcp("lower_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->lower_scaled_value));
fill_cmp_child(data, 03, data_strcp("upper_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->upper_scaled_value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param <API key>
*/
void <API key>(DataEntry *data, char *att_name,
ScaleRangeSpec32 *<API key>)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 4);
fill_cmp_child(data, 0, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 1, data_strcp("<API key>"), APIDEF_TYPE_FLOAT,
float2str(<API key>-><API key>));
fill_cmp_child(data, 2, data_strcp("lower_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->lower_scaled_value));
fill_cmp_child(data, 03, data_strcp("upper_scaled_value"), APIDEF_TYPE_INTU8,
intu8_2str(<API key>->upper_scaled_value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param sa_specification
*/
void <API key>(DataEntry *data, char *att_name,
SaSpec *sa_specification)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 4);
fill_cmp_child(data, 0, data_strcp("array_size"), APIDEF_TYPE_INTU16,
intu16_2str(sa_specification->array_size));
fill_cmp_child(data, 1, data_strcp("sample_size"), APIDEF_TYPE_INTU8,
intu8_2str(sa_specification->sample_type.sample_size));
fill_cmp_child(data, 2, data_strcp("significan_bits"), APIDEF_TYPE_INTU8,
intu8_2str(sa_specification->sample_type.significant_bits));
fill_cmp_child(data, 03, data_strcp("sa_flags"), APIDEF_TYPE_INTU16,
intu16_2str(sa_specification->flags));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param type the oid_type value
*/
void data_set_oid_type(DataEntry *data, char *att_name, OID_Type *type)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(*type));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param str the label value
*/
void <API key>(DataEntry *data, char *att_name, octet_string *str)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_STRING, octet_string2str(str));
}
/**
* Set data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param handle the handle value
*/
void data_set_handle(DataEntry *data, char *att_name, ASN1_HANDLE *handle)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(*handle));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param spec_small the MetricSpecSmall value
*/
void <API key>(DataEntry *data, char *att_name,
MetricSpecSmall *spec_small)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16,
intu16_2str(*spec_small));
}
/**
* Set data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param struct_small the <API key> value
*/
void <API key>(DataEntry *data, char *att_name,
<API key> *struct_small)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), 2);
fill_cmp_child(data, 0, data_strcp("ms-struct"), APIDEF_TYPE_INTU8,
intu8_2str(struct_small->ms_struct));
fill_cmp_child(data, 1, data_strcp("ms-comp-no"), APIDEF_TYPE_INTU8,
intu8_2str(struct_small->ms_comp_no));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param val_map the <API key> value
*/
void <API key>(DataEntry *data, char *att_name, AttrValMap *val_map)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), val_map->count);
int i;
for (i = 0; i < val_map->count; i++) {
set_cmp(&data->u.compound.entries[i], data_strcp("AttrValMapEntry"), 2);
DataEntry *attr_entry = &data->u.compound.entries[i].u.compound.entries[0];
data_set_oid_type(attr_entry, "attribute-id", &val_map->value[i].attribute_id);
attr_entry = &data->u.compound.entries[i].u.compound.entries[1];
set_simple(attr_entry, data_strcp("attribute-len"), APIDEF_TYPE_INTU16,
intu16_2str(val_map->value[i].attribute_len));
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param supp the <API key> value
*/
void <API key>(DataEntry *data, char *att_name, <API key> *supp)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), supp->count);
int i;
for (i = 0; i < supp->count; i++) {
DataEntry *attr_entry = &data->u.compound.entries[i];
data_set_type(attr_entry, "Type", &supp->value[i]);
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param list the MetricIdList value
*/
void <API key>(DataEntry *data, char *att_name, MetricIdList *list)
{
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), list->count);
int i;
for (i = 0; i < list->count; i++) {
data_set_oid_type(&data->u.compound.entries[i], "Metric-Id", &list->value[i]);
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param list the HANDLEList value
*/
void <API key>(DataEntry *data, char *att_name, HANDLEList *list)
{
int i;
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), list->count);
for (i = 0; i < list->count; i++) {
data_set_handle(&data->u.compound.entries[i], "Handle", &list->value[i]);
}
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param map the HandleAttrValMap value
*/
void <API key>(DataEntry *data, char *att_name, HandleAttrValMap *map)
{
int i;
if (data == NULL)
return;
set_cmp(data, data_strcp(att_name), map->count);
for (i = 0; i < map->count; i++) {
set_cmp(&data->u.compound.entries[i], data_strcp("<API key>"), 2);
DataEntry *entry = &data->u.compound.entries[i];
data_set_handle(&entry->u.compound.entries[0], "obj-handle", &map->value[i].obj_handle);
<API key>(&entry->u.compound.entries[1], "attr-val-map",
&map->value[i].attr_val_map);
}
}
/**
* Sets data entry with passed type.
*
* @param entry
* @param att_name
* @param list
*/
static void <API key>(DataEntry *entry, char *att_name, SegmEntryElemList *list)
{
int i;
set_cmp(entry, data_strcp(att_name), list->count);
for (i = 0; i < list->count; ++i) {
SegmEntryElem *elem = &list->value[i];
DataEntry *sub1 = &entry->u.compound.entries[i];
DataEntry *sub2;
set_cmp(sub1, data_strcp("segment-entry"), 4);
sub2 = &sub1->u.compound.entries[0];
data_set_oid_type(sub2, "class-id", &elem->class_id);
sub2 = &sub1->u.compound.entries[1];
data_set_type(sub2, "type", &elem->metric_type);
sub2 = &sub1->u.compound.entries[2];
data_set_handle(sub2, "obj-handle", &elem->handle);
sub2 = &sub1->u.compound.entries[3];
<API key>(sub2, "attr-val-map", &(elem->attr_val_map));
}
}
/**
* Sets data entry with passed type.
*
* @param entry
* @param att_name the name of DIM attribute
* @param map the PM-Segment entry map
*/
void <API key>(DataEntry *entry, char *att_name, PmSegmentEntryMap *map)
{
if (entry == NULL)
return;
set_cmp(entry, data_strcp(att_name), 2);
data_set_intu16(&entry->u.compound.entries[0], "entry-header", &map->segm_entry_header);
<API key>(&entry->u.compound.entries[1], "entry-list",
&map-><API key>);
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value the entry value
*/
void data_set_intu16(DataEntry *data, char *att_name, intu16 *value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU16, intu16_2str(*value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param value the entry value
*/
void data_set_intu32(DataEntry *data, char *att_name, intu32 *value)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_INTU32, intu32_2str(*value));
}
/**
* Sets data entry with passed type.
*
* @param data entry
* @param att_name the name of DIM attribute
* @param time the entry value
*/
void <API key>(DataEntry *data, char *att_name, HighResRelativeTime *time)
{
if (data == NULL)
return;
set_simple(data, data_strcp(att_name), APIDEF_TYPE_HEX, <API key>(
time));
}
/**
* Deletes a simple data entry.
*
* @param pointer the simple data entry to be deleted.
*/
void <API key>(SimpleDataEntry *pointer)
{
if (pointer == NULL)
return;
free(pointer->name);
pointer->name = NULL;
free(pointer->value);
pointer->value = NULL;
}
/**
* Deletes a compound data entry.
*
* @param pointer the compound data entry to be deleted.
*/
void <API key>(CompoundDataEntry *pointer)
{
int i;
if (pointer == NULL)
return;
free(pointer->name);
pointer->name = NULL;
for (i = 0; i < pointer->entries_count; i++) {
data_entry_del(&pointer->entries[i]);
}
free(pointer->entries);
pointer->entries = NULL;
}
/**
* Deletes the data entry.
*
* @param pointer to data entry to be deleted.
*/
void data_entry_del(DataEntry *pointer)
{
if (pointer == NULL)
return;
if (pointer->meta_data.values != NULL && pointer->meta_data.size > 0) {
int i;
for (i = 0; i < pointer->meta_data.size; i++) {
MetaAtt *meta = &pointer->meta_data.values[i];
free(meta->name);
meta->name = NULL;
free(meta->value);
meta->value = NULL;
}
}
free(pointer->meta_data.values);
pointer->meta_data.values = NULL;
if (pointer->choice == SIMPLE_DATA_ENTRY) {
<API key>(&pointer->u.simple);
} else if (pointer->choice == COMPOUND_DATA_ENTRY) {
<API key>(&pointer->u.compound);
}
}
/**
* Creates a new empty list of elements with a given size.
*
* @param size the size of the new list of elements.
* @return a pointer to a new list with \b size elements.
*/
DataList *data_list_new(int size)
{
DataList *list;
list = calloc(1, sizeof(DataList));
list->size = size;
list->values = calloc(size, sizeof(DataEntry));
return list;
}
/**
* Deletes all elements of the list. It also deletes the list.
*
* @param pointer the list of elements to be deleted.
*/
void data_list_del(DataList *pointer)
{
if (pointer) {
int i = 0;
for (i = 0; i < pointer->size; i++) {
data_entry_del(&pointer->values[i]);
}
free(pointer->values);
pointer->values = NULL;
free(pointer);
pointer = NULL;
}
} |
#ifndef BOOKMARKMODEL_H
#define BOOKMARKMODEL_H
#include <QtCore/QAbstractItemModel>
#include <QtGui/QIcon>
QT_BEGIN_NAMESPACE
class BookmarkItem;
class QMimeData;
class QTreeView;
typedef QMap<BookmarkItem*, <API key>> ItemModelIndexCache;
class BookmarkModel : public QAbstractItemModel
{
Q_OBJECT
public:
BookmarkModel();
~BookmarkModel();
QByteArray bookmarks() const;
void setBookmarks(const QByteArray &bookmarks);
void setItemsEditable(bool editable);
void <API key>(QTreeView *treeView);
QModelIndex addItem(const QModelIndex &parent, bool isFolder = false);
bool removeItem(const QModelIndex &index);
int rowCount(const QModelIndex &index = QModelIndex()) const;
int columnCount(const QModelIndex &index = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
QModelIndex index(int row, int column, const QModelIndex &index) const;
Qt::DropActions <API key> () const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant data(const QModelIndex &index, int role) const;
void setData(const QModelIndex &index, const QVector<QVariant> &data);
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex indexFromItem(BookmarkItem *item) const;
BookmarkItem *itemFromIndex(const QModelIndex &index) const;
QList<<API key>> indexListFor(const QString &label) const;
bool insertRows(int position, int rows, const QModelIndex &parent);
bool removeRows(int position, int rows, const QModelIndex &parent);
QStringList mimeTypes() const;
QMimeData* mimeData(const QModelIndexList &indexes) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row,
int column, const QModelIndex &parent);
private:
void setupCache(const QModelIndex &parent);
QModelIndexList collectItems(const QModelIndex &parent) const;
void collectItems(const QModelIndex &parent, qint32 depth,
QDataStream *stream) const;
private:
int columns;
bool m_folder;
bool m_editable;
QIcon folderIcon;
QIcon bookmarkIcon;
QTreeView *treeView;
BookmarkItem *rootItem;
ItemModelIndexCache cache;
};
QT_END_NAMESPACE
#endif // BOOKMARKMODEL_H |
using NHibernate.Dialect;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1250
{
<summary>
http://nhibernate.jira.com/browse/NH-1250
http://nhibernate.jira.com/browse/NH-1340
</summary>
<remarks>Failure occurs in MsSql2005Dialect only</remarks>
[TestFixture]
public class <API key> : BugTestCase
{
public override string BugNumber
{
get { return "NH1250"; }
}
protected override bool AppliesTo(Dialect.Dialect dialect)
{
return dialect is MsSql2000Dialect;
}
[Test]
public void FetchUsingICriteria()
{
using (ISession s = OpenSession())
using (ITransaction tx = s.BeginTransaction())
{
s.CreateCriteria(typeof(Party))
.SetMaxResults(10)
.List();
tx.Commit();
}
}
[Test]
public void FetchUsingIQuery()
{
using (ISession s = OpenSession())
using (ITransaction tx = s.BeginTransaction())
{
s.CreateQuery("from Party")
.SetMaxResults(10)
.List();
tx.Commit();
}
}
}
} |
#ifndef <API key>
#define <API key>
#include <vector>
#include <string>
#include <set>
#include <map>
#include "Exception.h"
namespace PLMD{
class Log;
This class holds the keywords and their documentation
class Keywords{
This class lets me pass keyword types easily
class KeyType{
public:
enum {hidden,compulsory,flag,optional,atoms,vessel} style;
explicit KeyType( const std::string& type );
void setStyle( const std::string& type );
bool isCompulsory() const { return (style==compulsory); }
bool isFlag() const { return (style==flag); }
bool isOptional() const { return (style==optional); }
bool isAtomList() const { return (style==atoms); }
bool isVessel() const { return (style==vessel); }
std::string toString() const {
if(style==compulsory) return "compulsory";
else if(style==optional) return "optional";
else if(style==atoms) return "atoms";
else if(style==flag) return "flag";
else if(style==hidden) return "hidden";
else if(style==vessel) return "vessel";
else plumed_assert(0);
return "";
}
};
friend class Action;
private:
Is this an action or driver (this bool affects what style==atoms does in print)
bool isaction;
The names of the allowed keywords
std::vector<std::string> keys;
The names of the reserved keywords
std::vector<std::string> reserved_keys;
Whether the keyword is compulsory, optional...
std::map<std::string,KeyType> types;
Do we allow stuff like key1, key2 etc
std::map<std::string,bool> allowmultiple;
The documentation for the keywords
std::map<std::string,std::string> documentation;
The default values for the flags (are they on or of)
std::map<std::string,bool> booldefs;
The default values (if there are default values) for compulsory keywords
std::map<std::string,std::string> numdefs;
The tags for atoms - we use this so the manual can differentiate between different ways of specifying atoms
std::map<std::string,std::string> atomtags;
The string that should be printed out to describe how the components work for this particular action
std::string cstring;
The names of all the possible components for an action
std::vector<std::string> cnames;
The keyword that turns on a particular component
std::map<std::string,std::string> ckey;
The documentation for a particular component
std::map<std::string,std::string> cdocs;
Print the documentation for the jth keyword in html
void print_html_item( const std::string& ) const;
Print a particular keyword
void printKeyword( const std::string& j, Log& log ) const ;
Print a particular keyword (copy of the above that works with files)
void printKeyword( const std::string& j, FILE* out ) const ;
public:
Constructor
Keywords() : isaction(true) {}
void isDriver(){ isaction=false; }
find out whether flag key is on or off by default.
bool getLogicalDefault( std::string key, bool& def ) const ;
Get the value of the default for the keyword named key
bool getDefaultValue( std::string key, std::string& def ) const ;
Return the number of defined keywords
unsigned size() const;
Check if numbered keywords are allowed for this action
bool numbered( const std::string & k ) const ;
Return the ith keyword
std::string getKeyword( const unsigned i ) const ;
Print the documentation to the log file (used by PLMD::Action::error)
void print( Log& log ) const ;
Print the documentation to a file (use by PLUMED::CLTool::readCommandLineArgs)
void print( FILE* out ) const ;
Reserve a keyword
void reserve( const std::string & t, const std::string & k, const std::string & d );
Reserve a flag
void reserveFlag( const std::string & k, const bool def, const std::string & d );
Use one of the reserved keywords
void use( const std::string & k );
Get the ith keyword
std::string get( const unsigned k ) const ;
Add a new keyword of type t with name k and description d
void add( const std::string & t, const std::string & k, const std::string & d );
Add a new compulsory keyword (t must equal compulsory) with name k, default value def and description d
void add( const std::string & t, const std::string & k, const std::string & def, const std::string & d );
Add a falg with name k that is by default on if def is true and off if def is false. d should provide a description of the flag
void addFlag( const std::string & k, const bool def, const std::string & d );
Remove the keyword with name k
void remove( const std::string & k );
Check if there is a keyword with name k
bool exists( const std::string & k ) const ;
Check the keyword k has been reserved
bool reserved( const std::string & k ) const ;
Check if the keyword with name k has style t
bool style( const std::string & k, const std::string & t ) const ;
Print an html version of the documentation
void print_html() const ;
Print keywords in form readable by vim
void print_vim() const ;
Print the template version for the documenation
void print_template( const std::string& actionname, bool include_optional) const ;
Change the style of a keyword
void reset_style( const std::string & k, const std::string & style );
Add keywords from one keyword object to another
void add( const Keywords& keys );
Copy the keywords data
void copyData( std::vector<std::string>& kk, std::vector<std::string>& rk, std::map<std::string,KeyType>& tt, std::map<std::string,bool>& am,
std::map<std::string,std::string>& docs, std::map<std::string,bool>& bools, std::map<std::string,std::string>& nums,
std::map<std::string,std::string>& atags, std::vector<std::string>& cnam, std::map<std::string,std::string>& ck,
std::map<std::string,std::string>& cd ) const ;
Clear everything from the keywords object
void destroyData();
Set the text that introduces how the components for this action are introduced
void <API key>( const std::string& instr );
Add a potential component which can be output by this particular action
void addOutputComponent( const std::string& name, const std::string& key, const std::string& descr );
Has a component with this name been added?
bool <API key>( const std::string& name, const bool& custom ) const ;
};
}
#endif |
require File.join(File.dirname(__FILE__), '/../../../test_helper')
class ActiveRecord::BaseTest < ActiveSupport::TestCase
def <API key>
base = HtmlBlock.new
assert_nil base.updated_on_string
base.updated_at = Time.zone.parse("1978-07-06")
assert_equal "Jul 6, 1978", base.updated_on_string
end
end |
package org.fenixedu.academic.util.renderer;
import java.util.List;
import org.fenixedu.academic.util.DayType;
import org.fenixedu.commons.i18n.LocalizedString;
import org.joda.time.Interval;
public interface GanttDiagramEvent {
public List<Interval> <API key>();
public LocalizedString <API key>();
public int <API key>();
public String <API key>();
public String <API key>();
public String <API key>();
public Integer <API key>();
public String <API key>();
public boolean <API key>();
public boolean <API key>();
public DayType <API key>(Interval interval);
} |
/*! \file
\ingroup CCDENSITY
\brief Enter brief description of file here
*/
#include <cstdio>
#include <cstring>
#include "psi4/libdpd/dpd.h"
#include "MOInfo.h"
#include "Params.h"
#include "Frozen.h"
#define EXTERN
#include "globals.h"
namespace psi {
namespace ccdensity {
/* onepdm(): Computes the one-particle density matrix for CC wave functions.
**
** The spin-orbital expressions for the onepdm components are:
**
** D_ij = -1/2 t_im^ef L^jm_ef - t_i^e L^j_e
**
** D_ab = 1/2 L^mn_ae t_mn^be + L^m_a t_m^b
**
** D_ia = t_i^a + (t_im^ae - t_i^e t_m^a) L^m_e
** - 1/2 L^mn_ef (t_in^ef t_m^a + t_i^e t_mn^af)
**
** D_ai = L^i_a
**
** [cf. Gauss and Stanton, JCP 103, 3561-3577 (1995).]
**
** TDC, July 2002
*/
void onepdm(const struct RHO_Params& rho_params) {
dpdfile2 D, D1, T1, L1, Z;
dpdbuf4 T2, L2;
double trace = 0.0, dot_AI, dot_IA, dot_ai, dot_ia;
double factor = 0.0;
bool L2_T2_T_F = true;
// L2 * T2 * T * F is absent for CC2 Lagrangian
if (params.wfn == "CC2" && params.dertype == 1) L2_T2_T_F = false;
if (params.ref == 0 || params.ref == 1) { /** RHF/ROHF **/
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, rho_params.DIJ_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tIJAB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "LIJAB");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tIjAb");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LIjAb");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->contract222(&T1, &L1, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, rho_params.Dij_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tijab");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "Lijab");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tiJaB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LiJaB");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->contract222(&T1, &L1, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, rho_params.DAB_lbl);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "LIJAB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tIJAB");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LiJaB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tiJaB");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&L1, &T1, &D, 1, 1, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, rho_params.Dab_lbl);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "Lijab");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tijab");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tIjAb");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->contract222(&L1, &T1, &D, 1, 1, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
/* add the T3 contributions to CCSD(T) onepdm calculated
in cctriples*/
if (params.wfn == "CCSD_T" && params.ref == 0) {
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, rho_params.DIJ_lbl);
global_dpd_->file2_init(&D1, PSIF_CC_OEI, 0, 0, 0, "DIJ(T)");
global_dpd_->file2_axpy(&D1, &D, 1.0, 0);
global_dpd_->file2_close(&D);
global_dpd_->file2_close(&D1);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, rho_params.Dij_lbl);
global_dpd_->file2_init(&D1, PSIF_CC_OEI, 0, 0, 0, "DIJ(T)");
global_dpd_->file2_axpy(&D1, &D, 1.0, 0);
global_dpd_->file2_close(&D);
global_dpd_->file2_close(&D1);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, rho_params.DAB_lbl);
global_dpd_->file2_init(&D1, PSIF_CC_OEI, 0, 1, 1, "DAB(T)");
global_dpd_->file2_axpy(&D1, &D, 1.0, 0);
global_dpd_->file2_close(&D);
global_dpd_->file2_close(&D1);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, rho_params.Dab_lbl);
global_dpd_->file2_init(&D1, PSIF_CC_OEI, 0, 1, 1, "DAB(T)");
global_dpd_->file2_axpy(&D1, &D, 1.0, 0);
global_dpd_->file2_close(&D);
global_dpd_->file2_close(&D1);
}
/*outfile->Printf( "\n\tTrace of onepdm = %20.15f\n", trace);*/
/* This term is * L0 = 0 for excited states */
if (rho_params.L_ground) {
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_copy(&T1, PSIF_CC_OEI, rho_params.DIA_lbl);
global_dpd_->file2_close(&T1);
}
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 1, rho_params.DIA_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 2, 7, 0, "tIJAB");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tIjAb");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(I,M)");
global_dpd_->contract222(&T1, &L1, &Z, 0, 0, 1.0, 0.0);
global_dpd_->file2_close(&L1);
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
if (L2_T2_T_F) {
/* D(I,A) << L2(MN,EF) T2(IN,EF) T(M,A) + L2(Mn,Ef) T2(In,Ef) T(M,A) */
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(I,M)");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "LIJAB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tIJAB");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tIjAb");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 1.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&T1);
/* T2(MN,AF) L2(MN,EF) T(I,E) + T2(Mn,Af) L2(Mn,Ef) T(I,E) */
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 1, 1, "Z(A,E)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tIJAB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "LIJAB");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tIjAb");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LIjAb");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&T1, &Z, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&D);
}
/* This term is * L0 = 0 for excited states */
if (rho_params.L_ground) {
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->file2_copy(&T1, PSIF_CC_OEI, rho_params.Dia_lbl);
global_dpd_->file2_close(&T1);
}
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 1, rho_params.Dia_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 2, 7, 0, "tijab");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tiJaB");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(i,m)");
global_dpd_->contract222(&T1, &L1, &Z, 0, 0, 1.0, 0.0);
global_dpd_->file2_close(&L1);
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
if (L2_T2_T_F) {
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(i,m)");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "Lijab");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tijab");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LiJaB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tiJaB");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 1.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&T1);
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 1, 1, "Z(a,e)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tijab");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "Lijab");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 0, 5, 0, "tiJaB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 5, 0, 5, 0, "LiJaB");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->contract222(&T1, &Z, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&D);
}
/* Note that these blocks are still stored occ/vir */
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_copy(&L1, PSIF_CC_OEI, rho_params.DAI_lbl);
global_dpd_->file2_close(&L1);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "Lia");
global_dpd_->file2_copy(&L1, PSIF_CC_OEI, rho_params.Dai_lbl);
global_dpd_->file2_close(&L1);
/* Check overlaps */
/*
dpd_file2_init(&D, CC_OEI, 0, 0, 1, rho_params.DIA_lbl);
dot_IA = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 0, 1, rho_params.Dia_lbl);
dot_ia = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 1, 0, rho_params.DAI_lbl);
dot_AI = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 1, 0, rho_params.Dai_lbl);
dot_ai = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
outfile->Printf("\tOverlaps of onepdm after ground-state parts added.\n");
outfile->Printf("\t<DIA|DIA> = %15.10lf <Dia|Dia> = %15.10lf\n", dot_IA, dot_ia);
outfile->Printf("\t<DAI|DAI> = %15.10lf <Dai|Dai> = %15.10lf\n", dot_AI, dot_ai);
outfile->Printf("\t<Dpq|Dqp> = %15.10lf\n", dot_IA+dot_ia+dot_AI+dot_ai);
*/
} else if (params.ref == 2) { /** UHF **/
if (params.wfn == "CCSD_T" && params.dertype == 1) {
/* For CCSD(T) gradients, some density contributions are
calculated in cctriples */
factor = 1.0;
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, "DIJ");
global_dpd_->file2_copy(&D, PSIF_CC_OEI, rho_params.DIJ_lbl);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 2, 2, "Dij");
global_dpd_->file2_copy(&D, PSIF_CC_OEI, rho_params.Dij_lbl);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, "DAB");
global_dpd_->file2_copy(&D, PSIF_CC_OEI, rho_params.DAB_lbl);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 3, 3, "Dab");
global_dpd_->file2_copy(&D, PSIF_CC_OEI, rho_params.Dab_lbl);
global_dpd_->file2_close(&D);
} else
factor = 0.0;
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 0, rho_params.DIJ_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tIJAB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "LIJAB");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, factor);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 22, 28, 22, 28, 0, "tIjAb");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 22, 28, 22, 28, 0, "LIjAb");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->contract222(&T1, &L1, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 2, 2, rho_params.Dij_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 10, 17, 12, 17, 0, "tijab");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 10, 17, 12, 17, 0, "Lijab");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, factor);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 23, 29, 23, 29, 0, "tiJaB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 23, 29, 23, 29, 0, "LiJaB");
global_dpd_->contract442(&T2, &L2, &D, 0, 0, -1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->contract222(&T1, &L1, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 1, 1, rho_params.DAB_lbl);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "LIJAB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tIJAB");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, factor);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 23, 29, 23, 29, 0, "LiJaB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 23, 29, 23, 29, 0, "tiJaB");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&L1, &T1, &D, 1, 1, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 3, 3, rho_params.Dab_lbl);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 12, 15, 12, 17, 0, "Lijab");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 12, 15, 12, 17, 0, "tijab");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, factor);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 22, 28, 22, 28, 0, "LIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 22, 28, 22, 28, 0, "tIjAb");
global_dpd_->contract442(&L2, &T2, &D, 3, 3, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract222(&L1, &T1, &D, 1, 1, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->file2_close(&T1);
trace += global_dpd_->file2_trace(&D);
global_dpd_->file2_close(&D);
/*outfile->Printf( "\n\tTrace of onepdm = %20.15f\n", trace);*/
/* This term is * L0 = 0 for excited states */
if (rho_params.L_ground) {
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_copy(&T1, PSIF_CC_OEI, rho_params.DIA_lbl);
global_dpd_->file2_close(&T1);
}
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 0, 1, rho_params.DIA_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 5, 2, 7, 0, "tIJAB");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 22, 28, 22, 28, 0, "tIjAb");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(I,M)");
global_dpd_->contract222(&T1, &L1, &Z, 0, 0, 1.0, 0.0);
global_dpd_->file2_close(&L1);
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
if (L2_T2_T_F) {
/* D(I,A) << L2(MN,EF) T2(IN,EF) T(M,A) + L2(Mn,Ef) T2(In,Ef) T(M,A) */
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 0, 0, "Z(I,M)");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 0, 7, 2, 7, 0, "LIJAB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 0, 7, 2, 7, 0, "tIJAB");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 22, 28, 22, 28, 0, "LIjAb");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 22, 28, 22, 28, 0, "tIjAb");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 1.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&T1);
/* T2(MN,AF) L2(MN,EF) T(I,E) + T2(Mn,Af) L2(Mn,Ef) T(I,E) */
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 1, 1, "Z(A,E)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 2, 5, 2, 7, 0, "tIJAB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 2, 5, 2, 7, 0, "LIJAB");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 22, 28, 22, 28, 0, "tIjAb");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 22, 28, 22, 28, 0, "LIjAb");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->contract222(&T1, &Z, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&D);
}
/* This term is * L0 = 0 for excited states */
if (rho_params.L_ground) {
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->file2_copy(&T1, PSIF_CC_OEI, rho_params.Dia_lbl);
global_dpd_->file2_close(&T1);
}
global_dpd_->file2_init(&D, PSIF_CC_OEI, 0, 2, 3, rho_params.Dia_lbl);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 10, 15, 12, 17, 0, "tijab");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 23, 29, 23, 29, 0, "tiJaB");
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->dot24(&L1, &T2, &D, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&L1);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 2, 2, "Z(i,m)");
global_dpd_->contract222(&T1, &L1, &Z, 0, 0, 1.0, 0.0);
global_dpd_->file2_close(&L1);
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
if (L2_T2_T_F) {
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 2, 2, "Z(i,m)");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 10, 17, 12, 17, 0, "Lijab");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 10, 17, 12, 17, 0, "tijab");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 0.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 23, 29, 23, 29, 0, "LiJaB");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 23, 29, 23, 29, 0, "tiJaB");
global_dpd_->contract442(&T2, &L2, &Z, 0, 0, 1.0, 1.0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&L2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract222(&Z, &T1, &D, 0, 1, -1.0, 1.0);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&T1);
global_dpd_->file2_init(&Z, PSIF_CC_TMP0, 0, 3, 3, "Z(a,e)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 12, 15, 12, 17, 0, "tijab");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 12, 15, 12, 17, 0, "Lijab");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 0.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 23, 29, 23, 29, 0, "tiJaB");
global_dpd_->buf4_init(&L2, PSIF_CC_GLG, 0, 23, 29, 23, 29, 0, "LiJaB");
global_dpd_->contract442(&T2, &L2, &Z, 2, 2, 1.0, 1.0);
global_dpd_->buf4_close(&L2);
global_dpd_->buf4_close(&T2);
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract222(&T1, &Z, &D, 0, 0, -1.0, 1.0);
global_dpd_->file2_close(&T1);
global_dpd_->file2_close(&Z);
global_dpd_->file2_close(&D);
}
/* Note that these blocks are still stored occ/vir */
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 0, 1, "LIA");
global_dpd_->file2_copy(&L1, PSIF_CC_OEI, rho_params.DAI_lbl);
global_dpd_->file2_close(&L1);
global_dpd_->file2_init(&L1, PSIF_CC_GLG, 0, 2, 3, "Lia");
global_dpd_->file2_copy(&L1, PSIF_CC_OEI, rho_params.Dai_lbl);
global_dpd_->file2_close(&L1);
/* Check overlaps */
/*
dpd_file2_init(&D, CC_OEI, 0, 0, 1, rho_params.DIA_lbl);
dot_IA = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 2, 3, rho_params.Dia_lbl);
dot_ia = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 0, 1, rho_params.DAI_lbl);
dot_AI = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
dpd_file2_init(&D, CC_OEI, 0, 2, 3, rho_params.Dai_lbl);
dot_ai = dpd_file2_dot_self(&D);
dpd_file2_close(&D);
outfile->Printf("\tOverlaps of onepdm after ground-state parts added.\n");
outfile->Printf("\t<DIA|DIA> = %15.10lf <Dia|Dia> = %15.10lf\n", dot_IA, dot_ia);
outfile->Printf("\t<DAI|DAI> = %15.10lf <Dai|Dai> = %15.10lf\n", dot_AI, dot_ai);
outfile->Printf("\t<Dpq|Dqp> = %15.10lf\n", dot_IA+dot_ia+dot_AI+dot_ai);
*/
}
}
} // namespace ccdensity
} // namespace psi |
#!/usr/bin/env python
# vector3 and rotation matrix classes
# This follows the conventions in the ArduPilot code,
# and is essentially a python version of the AP_Math library
# Andrew Tridgell, March 2012
# This library is free software; you can redistribute it and/or modify it
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# for more details.
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''rotation matrix class
'''
from math import sin, cos, sqrt, asin, atan2, pi, radians, acos, degrees
class Vector3:
'''a vector'''
def __init__(self, x=None, y=None, z=None):
if x != None and y != None and z != None:
self.x = float(x)
self.y = float(y)
self.z = float(z)
elif x != None and len(x) == 3:
self.x = float(x[0])
self.y = float(x[1])
self.z = float(x[2])
elif x != None:
raise ValueError('bad initialiser')
else:
self.x = float(0)
self.y = float(0)
self.z = float(0)
def __repr__(self):
return 'Vector3(%.2f, %.2f, %.2f)' % (self.x,
self.y,
self.z)
def __add__(self, v):
return Vector3(self.x + v.x,
self.y + v.y,
self.z + v.z)
__radd__ = __add__
def __sub__(self, v):
return Vector3(self.x - v.x,
self.y - v.y,
self.z - v.z)
def __neg__(self):
return Vector3(-self.x, -self.y, -self.z)
def __rsub__(self, v):
return Vector3(v.x - self.x,
v.y - self.y,
v.z - self.z)
def __mul__(self, v):
if isinstance(v, Vector3):
'''dot product'''
return self.x*v.x + self.y*v.y + self.z*v.z
return Vector3(self.x * v,
self.y * v,
self.z * v)
__rmul__ = __mul__
def __div__(self, v):
return Vector3(self.x / v,
self.y / v,
self.z / v)
def __mod__(self, v):
'''cross product'''
return Vector3(self.y*v.z - self.z*v.y,
self.z*v.x - self.x*v.z,
self.x*v.y - self.y*v.x)
def __copy__(self):
return Vector3(self.x, self.y, self.z)
copy = __copy__
def length(self):
return sqrt(self.x**2 + self.y**2 + self.z**2)
def zero(self):
self.x = self.y = self.z = 0
def angle(self, v):
'''return the angle between this vector and another vector'''
return acos((self * v) / (self.length() * v.length()))
def normalized(self):
return self.__div__(self.length())
def normalize(self):
v = self.normalized()
self.x = v.x
self.y = v.y
self.z = v.z
class Matrix3:
'''a 3x3 matrix, intended as a rotation matrix'''
def __init__(self, a=None, b=None, c=None):
if a is not None and b is not None and c is not None:
self.a = a.copy()
self.b = b.copy()
self.c = c.copy()
else:
self.identity()
def __repr__(self):
return 'Matrix3((%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f), (%.2f, %.2f, %.2f))' % (
self.a.x, self.a.y, self.a.z,
self.b.x, self.b.y, self.b.z,
self.c.x, self.c.y, self.c.z)
def identity(self):
self.a = Vector3(1,0,0)
self.b = Vector3(0,1,0)
self.c = Vector3(0,0,1)
def transposed(self):
return Matrix3(Vector3(self.a.x, self.b.x, self.c.x),
Vector3(self.a.y, self.b.y, self.c.y),
Vector3(self.a.z, self.b.z, self.c.z))
def from_euler(self, roll, pitch, yaw):
'''fill the matrix from Euler angles in radians'''
cp = cos(pitch)
sp = sin(pitch)
sr = sin(roll)
cr = cos(roll)
sy = sin(yaw)
cy = cos(yaw)
self.a.x = cp * cy
self.a.y = (sr * sp * cy) - (cr * sy)
self.a.z = (cr * sp * cy) + (sr * sy)
self.b.x = cp * sy
self.b.y = (sr * sp * sy) + (cr * cy)
self.b.z = (cr * sp * sy) - (sr * cy)
self.c.x = -sp
self.c.y = sr * cp
self.c.z = cr * cp
def to_euler(self):
'''find Euler angles for the matrix'''
if self.c.x >= 1.0:
pitch = pi
elif self.c.x <= -1.0:
pitch = -pi
else:
pitch = -asin(self.c.x)
roll = atan2(self.c.y, self.c.z)
yaw = atan2(self.b.x, self.a.x)
return (roll, pitch, yaw)
def __add__(self, m):
return Matrix3(self.a + m.a, self.b + m.b, self.c + m.c)
__radd__ = __add__
def __sub__(self, m):
return Matrix3(self.a - m.a, self.b - m.b, self.c - m.c)
def __rsub__(self, m):
return Matrix3(m.a - self.a, m.b - self.b, m.c - self.c)
def __mul__(self, other):
if isinstance(other, Vector3):
v = other
return Vector3(self.a.x * v.x + self.a.y * v.y + self.a.z * v.z,
self.b.x * v.x + self.b.y * v.y + self.b.z * v.z,
self.c.x * v.x + self.c.y * v.y + self.c.z * v.z)
elif isinstance(other, Matrix3):
m = other
return Matrix3(Vector3(self.a.x * m.a.x + self.a.y * m.b.x + self.a.z * m.c.x,
self.a.x * m.a.y + self.a.y * m.b.y + self.a.z * m.c.y,
self.a.x * m.a.z + self.a.y * m.b.z + self.a.z * m.c.z),
Vector3(self.b.x * m.a.x + self.b.y * m.b.x + self.b.z * m.c.x,
self.b.x * m.a.y + self.b.y * m.b.y + self.b.z * m.c.y,
self.b.x * m.a.z + self.b.y * m.b.z + self.b.z * m.c.z),
Vector3(self.c.x * m.a.x + self.c.y * m.b.x + self.c.z * m.c.x,
self.c.x * m.a.y + self.c.y * m.b.y + self.c.z * m.c.y,
self.c.x * m.a.z + self.c.y * m.b.z + self.c.z * m.c.z))
v = other
return Matrix3(self.a * v, self.b * v, self.c * v)
def __div__(self, v):
return Matrix3(self.a / v, self.b / v, self.c / v)
def __neg__(self):
return Matrix3(-self.a, -self.b, -self.c)
def __copy__(self):
return Matrix3(self.a, self.b, self.c)
copy = __copy__
def rotate(self, g):
'''rotate the matrix by a given amount on 3 axes'''
temp_matrix = Matrix3()
a = self.a
b = self.b
c = self.c
temp_matrix.a.x = a.y * g.z - a.z * g.y
temp_matrix.a.y = a.z * g.x - a.x * g.z
temp_matrix.a.z = a.x * g.y - a.y * g.x
temp_matrix.b.x = b.y * g.z - b.z * g.y
temp_matrix.b.y = b.z * g.x - b.x * g.z
temp_matrix.b.z = b.x * g.y - b.y * g.x
temp_matrix.c.x = c.y * g.z - c.z * g.y
temp_matrix.c.y = c.z * g.x - c.x * g.z
temp_matrix.c.z = c.x * g.y - c.y * g.x
self.a += temp_matrix.a
self.b += temp_matrix.b
self.c += temp_matrix.c
def normalize(self):
'''re-normalise a rotation matrix'''
error = self.a * self.b
t0 = self.a - (self.b * (0.5 * error))
t1 = self.b - (self.a * (0.5 * error))
t2 = t0 % t1
self.a = t0 * (1.0 / t0.length())
self.b = t1 * (1.0 / t1.length())
self.c = t2 * (1.0 / t2.length())
def trace(self):
'''the trace of the matrix'''
return self.a.x + self.b.y + self.c.z
def from_axis_angle(self, axis, angle):
'''create a rotation matrix from axis and angle'''
ux = axis.x
uy = axis.y
uz = axis.z
ct = cos(angle)
st = sin(angle)
self.a.x = ct + (1-ct) * ux**2
self.a.y = ux*uy*(1-ct) - uz*st
self.a.z = ux*uz*(1-ct) + uy*st
self.b.x = uy*ux*(1-ct) + uz*st
self.b.y = ct + (1-ct) * uy**2
self.b.z = uy*uz*(1-ct) - ux*st
self.c.x = uz*ux*(1-ct) - uy*st
self.c.y = uz*uy*(1-ct) + ux*st
self.c.z = ct + (1-ct) * uz**2
def from_two_vectors(self, vec1, vec2):
'''get a rotation matrix from two vectors.
This returns a rotation matrix which when applied to vec1
will produce a vector pointing in the same direction as vec2'''
angle = vec1.angle(vec2)
cross = vec1 % vec2
if cross.length() == 0:
# the two vectors are colinear
return self.from_euler(0,0,angle)
cross.normalize()
return self.from_axis_angle(cross, angle)
class Plane:
'''a plane in 3 space, defined by a point and a vector normal'''
def __init__(self, point=None, normal=None):
if point is None:
point = Vector3(0,0,0)
if normal is None:
normal = Vector3(0, 0, 1)
self.point = point
self.normal = normal
class Line:
'''a line in 3 space, defined by a point and a vector'''
def __init__(self, point=None, vector=None):
if point is None:
point = Vector3(0,0,0)
if vector is None:
vector = Vector3(0, 0, 1)
self.point = point
self.vector = vector
def plane_intersection(self, plane, forward_only=False):
'''return point where line intersects with a plane'''
l_dot_n = self.vector * plane.normal
if l_dot_n == 0.0:
# line is parallel to the plane
return None
d = ((plane.point - self.point) * plane.normal) / l_dot_n
if forward_only and d < 0:
return None
return (self.vector * d) + self.point
def test_euler():
'''check that from_euler() and to_euler() are consistent'''
m = Matrix3()
from math import radians, degrees
for r in range(-179, 179, 3):
for p in range(-89, 89, 3):
for y in range(-179, 179, 3):
m.from_euler(radians(r), radians(p), radians(y))
(r2, p2, y2) = m.to_euler()
v1 = Vector3(r,p,y)
v2 = Vector3(degrees(r2),degrees(p2),degrees(y2))
diff = v1 - v2
if diff.length() > 1.0e-12:
print('EULER ERROR:', v1, v2, diff.length())
def test_two_vectors():
'''test the from_two_vectors() method'''
import random
for i in range(1000):
v1 = Vector3(1, 0.2, -3)
v2 = Vector3(random.uniform(-5,5), random.uniform(-5,5), random.uniform(-5,5))
m = Matrix3()
m.from_two_vectors(v1, v2)
v3 = m * v1
diff = v3.normalized() - v2.normalized()
(r, p, y) = m.to_euler()
if diff.length() > 0.001:
print('err=%f' % diff.length())
print("r/p/y = %.1f %.1f %.1f" % (
degrees(r), degrees(p), degrees(y)))
print(v1.normalized(), v2.normalized(), v3.normalized())
def test_plane():
'''testing line/plane intersection'''
print("testing plane/line maths")
plane = Plane(Vector3(0,0,0), Vector3(0,0,1))
line = Line(Vector3(0,0,100), Vector3(10, 10, -90))
p = line.plane_intersection(plane)
print(p)
if __name__ == "__main__":
import doctest
doctest.testmod()
test_euler()
test_two_vectors() |
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="Start" href="index.html">
<link title="Index of types" rel=Appendix href="index_types.html">
<link title="Index of exceptions" rel=Appendix href="index_exceptions.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of class methods" rel=Appendix href="index_methods.html">
<link title="Index of classes" rel=Appendix href="index_classes.html">
<link title="Index of class types" rel=Appendix href="index_class_types.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Index of module types" rel=Appendix href="index_module_types.html">
<link title="Pretty" rel="Chapter" href="Pretty.html">
<link title="Errormsg" rel="Chapter" href="Errormsg.html">
<link title="Clist" rel="Chapter" href="Clist.html">
<link title="Stats" rel="Chapter" href="Stats.html">
<link title="Cil" rel="Chapter" href="Cil.html">
<link title="Formatcil" rel="Chapter" href="Formatcil.html">
<link title="Alpha" rel="Chapter" href="Alpha.html">
<link title="Cillower" rel="Chapter" href="Cillower.html">
<link title="Cfg" rel="Chapter" href="Cfg.html">
<link title="Dataflow" rel="Chapter" href="Dataflow.html">
<link title="Dominators" rel="Chapter" href="Dominators.html"><title>CIL API Documentation (version 1.3.7) : Index of class methods</title>
</head>
<body>
<center><h1>Index of class methods</h1></center>
<table>
<tr><td align="left"><br>D</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODdBlock">dBlock</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Dump a control-flow block to a file with a given indentation.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODdGlobal">dGlobal</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Dump a global to a file with a given indentation.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODdInit">dInit</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Dump a global to a file with a given indentation.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODdStmt">dStmt</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Dump a control-flow statement to a file with a given indentation.
</div>
</td></tr>
<tr><td align="left"><br>G</td></tr>
<tr><td><a href="Cil.cilPrinter.html#<API key>"><API key></a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td></td></tr>
<tr><td align="left"><br>P</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpAttr">pAttr</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Attribute.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpAttrParam">pAttrParam</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Attribute parameter
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpAttrs">pAttrs</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Attribute lists
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpBlock">pBlock</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print a block.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpExp">pExp</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print expressions
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpFieldDecl">pFieldDecl</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
A field declaration
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpGlobal">pGlobal</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Global (vars, types, etc.).
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpInit">pInit</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print initializers.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpInstr">pInstr</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Invoked on each instruction occurrence.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpLabel">pLabel</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print a label.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#<API key>">pLineDirective</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print a line-number.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpLval">pLval</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Invoked on each lvalue occurrence
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpOffset">pOffset</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Invoked on each offset occurrence.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpStmt">pStmt</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Control-flow statement.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpStmtKind">pStmtKind</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Print a statement kind.
</div>
</td></tr>
<tr><td><a href="Cil.<API key>.html#METHODpTemps">pTemps</a> [<a href="Cil.<API key>.html">Cil.<API key></a>]</td>
<td></td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpType">pType</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Use of some type in some declaration.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpVDecl">pVDecl</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Invoked for each variable declaration.
</div>
</td></tr>
<tr><td><a href="Cil.cilPrinter.html#METHODpVar">pVar</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td><div class="info">
Invoked on each variable use.
</div>
</td></tr>
<tr><td align="left"><br>Q</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODqueueInstr">queueInstr</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Add here instructions while visiting to queue them to preceede the
current statement or instruction being processed.
</div>
</td></tr>
<tr><td align="left"><br>S</td></tr>
<tr><td><a href="Cil.cilPrinter.html#<API key>">setCurrentFormals</a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td></td></tr>
<tr><td><a href="Cil.cilPrinter.html#<API key>"><API key></a> [<a href="Cil.cilPrinter.html">Cil.cilPrinter</a>]</td>
<td></td></tr>
<tr><td><a href="Cil.<API key>.html#METHODstartTemps">startTemps</a> [<a href="Cil.<API key>.html">Cil.<API key></a>]</td>
<td></td></tr>
<tr><td><a href="Cil.<API key>.html#METHODstopTemps">stopTemps</a> [<a href="Cil.<API key>.html">Cil.<API key></a>]</td>
<td></td></tr>
<tr><td align="left"><br>U</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODunqueueInstr">unqueueInstr</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Gets the queue of instructions and resets the queue.
</div>
</td></tr>
<tr><td align="left"><br>V</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvattr">vattr</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Attribute.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvattrparam">vattrparam</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Attribute parameters.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvblock">vblock</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Block.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvexpr">vexpr</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each expression occurrence.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvfunc">vfunc</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Function definition.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvglob">vglob</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Global (vars, types,
etc.)
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvinit">vinit</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Initializers for globals,
pass the global where this
occurs, and the offset
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvinitoffs">vinitoffs</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each offset appearing in the list of a
CompoundInit initializer.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvinst">vinst</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each instruction occurrence.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvlval">vlval</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each lvalue occurrence
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvoffs">voffs</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each offset occurrence that is *not* as part
of an initializer list specification, i.e.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvstmt">vstmt</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Control-flow statement.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvtype">vtype</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Use of some type.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvvdec">vvdec</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked for each variable declaration.
</div>
</td></tr>
<tr><td><a href="Cil.cilVisitor.html#METHODvvrbl">vvrbl</a> [<a href="Cil.cilVisitor.html">Cil.cilVisitor</a>]</td>
<td><div class="info">
Invoked on each variable use.
</div>
</td></tr>
</table><br>
</body>
</html> |
// -*- Mode:C++ -*-
#include "FloatFieldAdapter.h"
#include <avango/StandardFields.h>
#include "../../core/include/shade/types/FloatAccessor.h"
#include "../../core/include/shade/types/float.h"
namespace
{
class FloatGetter
{
public:
FloatGetter(shade::types::FloatAccessor* accessor) :
mAccessor(accessor)
{
}
void operator()(const av::SFFloat::GetValueEvent& event)
{
mAccessor->get(*event.getValuePtr());
}
private:
shade::types::FloatAccessor* mAccessor;
};
class FloatSetter
{
public:
FloatSetter(shade::types::FloatAccessor* accessor) :
mAccessor(accessor)
{
}
void operator()(const av::SFFloat::SetValueEvent& event)
{
mAccessor->set(event.getValue());
}
private:
shade::types::FloatAccessor* mAccessor;
};
}
::shade::types::TypeAccessor::HashType
av::shade::FloatFieldAdapter::hash(void) const
{
static ::shade::float_<> value;
return value.hash();
}
void
av::shade::FloatFieldAdapter::bindField(::shade::Type* type, const std::string& name, av::FieldContainer* container) const
{
::shade::types::FloatAccessor* float_accessor(dynamic_cast< ::shade::types::FloatAccessor*>(type));
if (float_accessor == 0)
return;
av::SFFloat* field= new av::SFFloat;
field->bind(container, name, true, FloatGetter(float_accessor), FloatSetter(float_accessor));
} |
package org.alfresco.repo.virtual.ref;
import java.util.HashMap;
import java.util.Map;
/**
* Common {@link Reference} protocols.
*/
public enum Protocols
{
NODE(new NodeProtocol()), VIRTUAL(new VirtualProtocol()), VANILLA(new VanillaProtocol());
private static volatile Map<String, Protocol> protocolsMap;
public static synchronized Protocol fromName(String name)
{
return protocolsMap.get(name);
}
private synchronized static void register(Protocol protocol)
{
if (protocolsMap == null)
{
protocolsMap = new HashMap<>();
}
protocolsMap.put(protocol.name,
protocol);
}
public final Protocol protocol;
Protocols(Protocol protocol)
{
this.protocol = protocol;
register(protocol);
}
} |
# This is yui/yui
# do NOT require this file, but do a simple
# require 'yui'
# instead
require 'yui/version'
# this loads the binary .so file
require '_yui' |
package org.alfresco.repo.policy;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.namespace.QName;
/**
* Policy scope.
* <p>
* Helper often used by policies which require information
* about a node to be gathered, for example onCopy or onCreateVersion.
*
* @author Roy Wetherall
*/
public class PolicyScope extends AspectDetails
{
/**
* The aspects
*/
protected Map<QName, AspectDetails> aspectCopyDetails = new HashMap<QName, AspectDetails>();
/**
* Constructor
*
* @param classRef the class reference
*/
public PolicyScope(QName classRef)
{
super(classRef);
}
/**
* Add a property
*
* @param classRef the class reference
* @param qName the qualified name of the property
* @param value the value of the property
*/
public void addProperty(QName classRef, QName qName, Serializable value)
{
if (classRef.equals(this.classRef) == true)
{
addProperty(qName, value);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails == null)
{
// Add the aspect
aspectDetails = addAspect(classRef);
}
aspectDetails.addProperty(qName, value);
}
}
/**
* Removes a property from the list
*
* @param classRef the class reference
* @param qName the qualified name
*/
public void removeProperty(QName classRef, QName qName)
{
if (classRef.equals(this.classRef) == true)
{
removeProperty(qName);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails != null)
{
aspectDetails.removeProperty(qName);
}
}
}
/**
* Get the properties
*
* @param classRef the class ref
* @return the properties that should be copied
*/
public Map<QName, Serializable> getProperties(QName classRef)
{
Map<QName, Serializable> result = null;
if (classRef.equals(this.classRef) == true)
{
result = getProperties();
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails != null)
{
result = aspectDetails.getProperties();
}
}
return result;
}
/**
* Adds a child association
*
* @param classRef QName
* @param childAssocRef ChildAssociationRef
*/
public void addChildAssociation(QName classRef, ChildAssociationRef childAssocRef)
{
if (classRef.equals(this.classRef) == true)
{
addChildAssociation(childAssocRef);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails == null)
{
// Add the aspect
aspectDetails = addAspect(classRef);
}
aspectDetails.addChildAssociation(childAssocRef);
}
}
/**
*
* @param classRef QName
* @param childAssocRef ChildAssociationRef
* @param <API key> boolean
*/
public void addChildAssociation(QName classRef, ChildAssociationRef childAssocRef, boolean <API key>)
{
if (classRef.equals(this.classRef) == true)
{
addChildAssociation(childAssocRef, <API key>);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails == null)
{
// Add the aspect
aspectDetails = addAspect(classRef);
}
aspectDetails.addChildAssociation(childAssocRef, <API key>);
}
}
/**
* Get a child association
*
* @param classRef QName
* @return List<ChildAssociationRef>
*/
public List<ChildAssociationRef> <API key>(QName classRef)
{
List<ChildAssociationRef> result = null;
if (classRef.equals(this.classRef) == true)
{
result = <API key>();
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails != null)
{
result = aspectDetails.<API key>();
}
}
return result;
}
public boolean <API key>(QName classRef, ChildAssociationRef childAssocRef)
{
boolean result = false;
if (classRef.equals(this.classRef) == true)
{
result = <API key>(childAssocRef);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails != null)
{
result = aspectDetails.<API key>(childAssocRef);
}
}
return result;
}
/**
* Add an association
*
* @param classRef QName
* @param nodeAssocRef AssociationRef
*/
public void addAssociation(QName classRef, AssociationRef nodeAssocRef)
{
if (classRef.equals(this.classRef) == true)
{
addAssociation(nodeAssocRef);
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails == null)
{
// Add the aspect
aspectDetails = addAspect(classRef);
}
aspectDetails.addAssociation(nodeAssocRef);
}
}
/**
* Get associations
*
* @param classRef QName
* @return List<AssociationRef>
*/
public List<AssociationRef> getAssociations(QName classRef)
{
List<AssociationRef> result = null;
if (classRef.equals(this.classRef) == true)
{
result = getAssociations();
}
else
{
AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
if (aspectDetails != null)
{
result = aspectDetails.getAssociations();
}
}
return result;
}
/**
* Add an aspect
*
* @param aspect the aspect class reference
* @return the apsect copy details (returned as a helper)
*/
public AspectDetails addAspect(QName aspect)
{
AspectDetails result = new AspectDetails(aspect);
this.aspectCopyDetails.put(aspect, result);
return result;
}
/**
* Removes an aspect from the list
*
* @param aspect the aspect class reference
*/
public void removeAspect(QName aspect)
{
this.aspectCopyDetails.remove(aspect);
}
/**
* Gets a list of the aspects
*
* @return a list of aspect to copy
*/
public Set<QName> getAspects()
{
return this.aspectCopyDetails.keySet();
}
}
/**
* Aspect details class.
* <p>
* Contains the details of an aspect this can be used for copying or versioning.
*
* @author Roy Wetherall
*/
/*package*/ class AspectDetails
{
/**
* The properties
*/
protected Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
/**
* The child associations
*/
protected List<ChildAssociationRef> childAssocs = new ArrayList<ChildAssociationRef>();
/**
* The target associations
*/
protected List<AssociationRef> targetAssocs = new ArrayList<AssociationRef>();
/**
* The class ref of the aspect
*/
protected QName classRef;
/**
* Map of assocs that will always be traversed
*/
protected Map<ChildAssociationRef, ChildAssociationRef> alwaysTraverseMap = new HashMap<ChildAssociationRef, ChildAssociationRef>();
/**
* Constructor
*
* @param classRef the class ref
*/
public AspectDetails(QName classRef)
{
this.classRef = classRef;
}
/**
* Add a property to the list
*
* @param qName the qualified name of the property
* @param value the value of the property
*/
public void addProperty(QName qName, Serializable value)
{
this.properties.put(qName, value);
}
/**
* Remove a property from the list
*
* @param qName the qualified name of the property
*/
public void removeProperty(QName qName)
{
this.properties.remove(qName);
}
/**
* Gets the map of properties
*
* @return map of property names and values
*/
public Map<QName, Serializable> getProperties()
{
return properties;
}
/**
* Add a child association
*
* @param childAssocRef the child association reference
*/
protected void addChildAssociation(ChildAssociationRef childAssocRef)
{
this.childAssocs.add(childAssocRef);
}
/**
* Add a child association
*
* @param childAssocRef the child assoc reference
* @param <API key> indicates whether the assoc should always be traversed
*/
protected void addChildAssociation(ChildAssociationRef childAssocRef, boolean <API key>)
{
addChildAssociation(childAssocRef);
if (<API key> == true)
{
// Add to the list of deep copy child associations
this.alwaysTraverseMap.put(childAssocRef, childAssocRef);
}
}
/**
* Indicates whether a child association ref is always traversed or not
*
* @param childAssocRef the child association reference
* @return true if the assoc is always traversed, false otherwise
*/
protected boolean <API key>(ChildAssociationRef childAssocRef)
{
return this.alwaysTraverseMap.containsKey(childAssocRef);
}
/**
* Gets the child associations to be copied
*
* @return map containing the child associations to be copied
*/
public List<ChildAssociationRef> <API key>()
{
return this.childAssocs;
}
/**
* Adds an association to be copied
*
* @param nodeAssocRef the association reference
*/
protected void addAssociation(AssociationRef nodeAssocRef)
{
this.targetAssocs.add(nodeAssocRef);
}
/**
* Gets the map of associations to be copied
*
* @return a map conatining the associations to be copied
*/
public List<AssociationRef> getAssociations()
{
return this.targetAssocs;
}
} |
To install the latest version, execute `npm install -g brunch`
## Brunch 2.10 (Jan 13, 2017)
* Added [yarn](https://yarnpkg.com/) support.
* CLI improvements:
* Undeprecated `--config` for specifying Brunch config file. Thanks @stelmakh.
* Fixed `--debug` option. Thanks @denysdovhan.
* `bower install` runs automatically now.
* Improved error messages. Thanks @lydell.
* Fixed double error logging. Thanks @stelmakh.
* Fixed persistent errors in static files compilers.
* Fixed infinite compilation caused by file writes in `preCompile`.
* Plugins now can change file path.
* New API for changing file extension: `.targetExtension`.
* Brunch now respects `NODE_ENV` variable.
* Other code refactorings and fixes.
## Brunch 2.9 (Oct 23, 2016)
* Added new CLI option `--network`: sets server's hostname to `0.0.0.0`. Thanks @shreeve.
* Reduced installation size of Brunch by 5Mb.
* Fixed Brunch not quitting immediately after compilation finished.
* Improved performance of loading configs and writing source maps to disk.
* Improved config handling:
* Trailing slashes from `config.path` are now removed. Thanks @herenow.
* Fixed warning on `hot` option set in config.
* Added `"inline"` option to `config.sourceMaps`.
* Allow specifying watched globs in `getDependencies`.
* Allow specifying `teardown` in `config.hooks`.
* If `templates.joinTo` is empty, `javascripts.joinTo` will be used.
* Added `bower.enabled: false` option to ignore [bower](https://github.com/bower/bower).
* `lint` and `getDependencies` now support new promise-based single-parameter plugin API.
* `include` supports returning Promise that resolves to an Array. Thanks @jacksonrayhamilton.
* Various performance improvements and refactorings.
## Brunch 2.8 (May 21, 2016)
* Added plugin API for asset compilation e.g. jade to html.
* Watcher improvements:
* Brunch will not try to `npm install` if only the config was changed.
* NPM: improved handling of added & removed files during `watch`. Adding a new file will now try to re-check files that previously failed due to module resolution errors. Removing a file will now cause the files that depended on it to be re-checked.
* Fixed a memory leak issue after watcher reload (due to config change or update in `package.json`).
* Small API improvements:
* Changed back to `destinationPath` (instead of `destPath` since 2.6) in `Asset` that is received in `onCompile`
* Moved `config.plugins.npm` to `config.npm.compilers`
* Print a warning if a plugin from `devDependencies` fails to load.
* NPM: `require.alias` will now be inserted only in the bundles which contain the aliased file. Previous behavior was that all output file contained all possible aliases.
## Brunch 2.7 (Apr 21, 2016)
* Introduced support for Hot Module Replacement API with [hmr-brunch](https://github.com/brunch/hmr-brunch).
* Added config file validation of format and types.
* Allow JavaScript files from NPM packages to get processed with plugins (`config.plugins.npm`).
* Fixed `entryPoint`-related warnings on Windows.
* Brunch will now try to recover from `MODULE_NOT_FOUND` errors caused by the config, by trying to `npm install`.
* The slashes in file paths are now normalized early. The plugins will always receive paths with UNIX-style slashes even on Windows (`/`).
## Brunch 2.6 (Apr 2, 2016)
* Non-JS files can now output JS modules.
* You are now able to import stylesheets from Sass, Less, CSS in JS.
* For this to work, don't forget to enable proper config option for each plugin.
* Added experimental support for `entryPoints`, a smarter alternative to `joinTo`:
* `joinTo` concatenates all files that match the pattern into one
* `entryPoints` allow you to specify first input file. Then Brunch
automatically calculates which modules and dependencies will be used
in the output. This way, unused files would not get compiled.
* Add support for `BRUNCH_JOBS` environment variable to be able to specify number of jobs to process your build.
* Fixed an issue when Brunch was forking processes even if `-j` flag was not passed which caused some extreme CPU and memory issues.
* Deprecated `onCompile` config option in favor of new `hooks.onCompile`.
* Fix a type error when checkin if a file was written.
* Don't categorize node_modules as 'assets' even if they match the regexp
* Fixed brokenness of some plugins like `static-jade-brunch`.
* Fixes parent recompilation when a dependency changes.
* Improved `npm install` behavior while Brunch is watching:
* Make sure Brunch waits for it before proceeding.
* Make it aware of `production` env flag for Heroku.
* Small bugfix for dependency parser.
## Brunch 2.5 (Mar 22, 2016)
* **Improved NPM support:**
* Added support for scoped npm packages, like `@cycle/dom`.
* Brunch will now try to `npm install` if you try to require a package that is present in `package.json` but was not installed.
* `<API key>` are now correctly ignored when not present.
* `peerDepdenencides` are treated as required ones.
* Improperly-cased requires (like `React` instead of `react`) will now throw compile errors.
* Fixed npm mail file resolving which was not working before in some cases (`rx`).
* **Support for file extensions:**
* Brunch will now register CommonJS modules using full names of the files, and create aliases without extensions to allow you to use both styles of requires.
* Basically these cases are possible & different now: `require('file.json')` and `require('file.js')`
* **Parallel builds:** Bringing up to 50% performance improvement with just one simple flag.
* You can use the `-j 2 / 4` flag with `build` / `watch` to parallelize CPU-bould tasks in your build. See [docs](http://brunch.io/docs/commands.html) for more details.
* **React hot load support:**
* Bumped `<API key>` to allow resetting modules, which can be used for live JS reloading with the updated `auto-reload-brunch`
* **Improved output** for JavaScript files.
* Allow to specify again `conventions.vendor` as an anymatch set.
* Fixed double inclusion of some files on Windows.
* Fixed an issue when `joinTo` production override did not have any effect.
* Fixed JSON file loading.
## Brunch 2.4 (Feb 23, 2016)
* You can now simply set `config.modules = false` to disable module wrapping.
* Brunch would now correctly include file-based aliases for NPM packages. For example, this means you would be able to load `require('moment/locales/en')` even though the file is not declared in moment's `package.json`.
* Fixed auto-expanding of GH URLs in skeletons: `brunch new --skeleton paulmillr/brunch-with-chaplin`
* Removed `component.js` support, which was barely supported since v2.0.
* Added warning for versions of NPM <3, because Brunch does not work on those.
* Improved error handling.
## Brunch 2.3 (Feb 17, 2016)
* Small fix for `xBrowserResolve is not a function` error.
* Fixed handling of custom web-servers for `brunch watch -s`.
* Improved exposure of `process.env.NODE_ENV` when used in Brunch apps.
* NPM: Fixed support for different versions of the same package.
* Enabled NPM support by default
* NPM: Added aliases support
* NPM: Added support for including static files.
* NPM: Added support for different versions of the same package.
* NPM: Watcher would detect removed packages from users source code and
then do a corresponding recompilation.
* NPM: Added support for `json` files.
* `onCompile` config option now receives modified `assets` as a second argument.
* `server` config option now allows to specify custom `hostname`s
* New warning: When `brunch w -s -p 3334` is used (instead of `-P`)
* New warning: When `defaultExtension` option is used.
It has been removed in Brunch 1.1, but many configs still have it.
## Brunch 2.2 (Jan 22, 2016)
* Massively improved NPM integration:
1. Brunch would now automatically detect and extract all npm packages.
2. Because of this, `whitelist` property is no longer required.
3. Windows implementation should now work correctly.
* `brunch new` launched with old syntax would now throw a descriptive error.
* Improved progress indicator. It would not allow plugins to write output on top of it.
* Added support for promises in plugins.
* Improve compatibility with Brunch 1.x.
* Built-in node.js modules can now be loaded in your client-side apps.
## Brunch 2.1 (Jan 1, 2016)
* Brunch would now indicate progress for long builds, like that:
`(4s) Compiling => Compiling. => Compiling..`
* Massively improved debug output (`-d`) readability.
* Now throwing correct import errors ([gh-1053](https:
* NPM integration was hugely reworked. Disabled by default for now.
1. With `config.npm.enabled = true`, all non-brunch NPM packages
would be loaded automatically.
2. To exclude packages, specify the blacklist:
`config.npm = {blacklist: ['express']}`
3. To include packages manually, specify the whitelist:
`config.npm = {whitelist: ['react', 'react-dom', 'pikaday']}`
* Fixes an issue when NPM packages were included incorrectly on Windows.
* `brunch build -d` is now able to receive an optional `filterer` argument
* `brunch new` and `brunch build` hangup fixes.
* NPM integration fixes
* Fixes an issue when sass-brunch or similar plugins weren't compiling files correctly.
## Brunch 2.0 (Nov 19, 2015)
Brunch v2 **requires node 4.0 / npm 3.0 or higher**.
* `brunch new` reworked, simplified and receives new syntax:
* `brunch new .` to create a new project in current directory from dead-simple skeleton
* `brunch new path` to create the project in `path`
* `brunch new . --skeleton react` to create the project from `React` skeleton
* Now allowing to clone skeletons to dirs with `.git` directory.
* General speed & stability improvements.
* Rewritten in JavaScript (ES6 + Promises).
* Switched `-p` and `-P`. `-p` now specifies `--production` build and `-P` now specifies watch server port.
* `modules.autoRequire` should now work correctly on Windows.
* Fixes using production flag (`-p`) with multiple optimizers [(gh-1056)](https://github.com/brunch/brunch/issues/1056).
* Brunch would now auto-expand the following syntax to a full GitHub user / repo URL:
`brunch new --skeleton paulmillr/brunch-with-chaplin`
* Fix: Post `onCompile` string replaces not working.
* Fix: Linters now get the correct `linter` context.
* Compilation log would now use seconds instead of milliseconds for long compilations.
* Launching Brunch on node v4< would now throw an explicit error.
## Brunch 1.8.5 (Aug 5, 2015)
* Only listen to stdin (and exit when stdin is closed) when the `--stdin` CLI switch is passed
## Brunch 1.8.4 (Jul 31, 2015)
* Add `modules.autoRequire` option that would automatically append `require('module')` to your javascript outputs.
## Brunch 1.8.3 (May 19, 2015)
* Fix restarting watcher upon config change
* Fix issue with npm includes that have no dependencies
## Brunch 1.8.2 (Apr 21, 2015)
* Fix regression with `-d`/`--debug` CLI switch
## Brunch 1.8.1 (Apr 20, 2015)
* Enabled NPM support by default. Just load any installed npm package in your code
via `require('package')`.
## Brunch 1.8.0 (Apr 8, 2015)
* Added experimental **NPM support** for client-side libraries.
Just specify dependencies in `package.json` and load them within your app
with `require('package')`. Brunch would do all the hard job for you.
Behind config option for now (`config.npm = {enabled: true}`).
* Ultra-simple custom webservers.
Brunch will now consume file `brunch-server.{js,coffee}` if it exists
and it would be used to launch a custom webserver that launches with `brunch watch --server`.
Also, no more need to write `startServer` — just export the function with `module.exports`
* Added `preCompile` plugins ([gh-873](https://github.com/brunch/brunch/issues/873)).
* Compilers can now return dependencies:
`{data: 'file-data', dependencies: ['a.js', 'b.js']}`
* Fixed env handling for optimizers ([gh-903](https://github.com/brunch/brunch/issues/903))
* Only listen to stdin if in persistent mode ([gh-920](https://github.com/brunch/brunch/issues/920))
* Added **fcache** - a simple way to speed-up your plugins like sass or jade.
fcache is a simple filesystem wrapper that allows to read files and
to update them in cache.
Brunch would usually update them on every change, after that your plugin
will pull the data from RAM and would be super fast.
* Massive improvements to file watcher.
## Brunch 1.7.20 (Dec 8, 2014)
* Bump chokidar to 0.12.0
## Brunch 1.7.19 (Nov 17, 2014)
* Bump chokidar to 0.11.0
* Fix issue with undetected changes when using vim on Linux
* Ensure `build` does not complete prematurely on slow file systems
## Brunch 1.7.18 (Oct 20, 2014)
* File watching improvements via chokidar 0.10.1
## Brunch 1.7.17 (Sep 26, 2014)
* Fix warnings about files joined only under default config settings
* Warning when custom server fails to callback
* Add `-d`/`--debug` CLI switch to easily enable debug output
## Brunch 1.7.16 (Sep 13, 2014)
* Suppress warnings about unjoined filed meant for only specific envs
## Brunch 1.7.15 (Sep 10, 2014)
* Fix race condition that aborted build cycle on some systems
* Better error/warning messages for source files that do not get concatenated
(no `joinTo` match)
* Improved handling of `plugins.on` and `plugins.off` when used with `overrides`
* New [config](https://github.com/brunch/brunch/blob/stable/docs/config.md) options
* `server.command` for setting non-node.js custom server
* Pass `server.config` settings to custom server
* Create `absoluteUrl` option for source maps
* Support for array of files in `pluginHelpers` config setting
* IMPORTANT NOTE: If providing a custom node server for `brunch watch`, ensure it
invokes the callback when ready, as brunch now waits for that before proceeding
with build steps.
## Brunch 1.7.14 (May 21, 2014)
* [component](https://github.com/component/component) integration
* [anysort](https:
integration, providing much more flexible ways to define source files in
config such as in `joinTo` and `order`
* [New config options](https://github.com/brunch/brunch/blob/stable/docs/config.md#plugins)
to control which plugins are used (can be env-specific)
* Allow `onCompile` method to be defined in Brunch config file for triggering
custom project-specific functionality after every compile cycle
* Default settings updates:
* Ignore directories that start with underscore (to match filename handling)
* Fix heroku issues
## Brunch 1.7.13 (Dec 9, 2013)
* Fixed optimizers not actually optimizing the code.
## Brunch 1.7.12 (Nov 30, 2013)
* Fixed syntax error in source code.
## Brunch 1.7.11 (Nov 29, 2013)
* If you remove some file and create a file with the same name,
it will be handled correctly.
* Linter warnings are now handled correctly.
## Brunch 1.7.10 (Oct 19, 2013)
* Fixed optimizers.
## Brunch 1.7.9 (Oct 16, 2013)
* Re-release of 1.7.8 because of npm code publishing bug.
## Brunch 1.7.8 (Oct 10, 2013)
*NOTE:* Re-published on 16 October 2013 due to npm bug.
If installed prior to this date, it will actually run as if it is 1.7.6.
* Switched source maps format to new (`//
Old format is still available via `config.sourceMaps = 'old'`
* Assets dotfile ignore exception to enable copying of `.rewrite` files.
## Brunch 1.7.7 (Sep 28, 2013)
*NOTE:* Re-published on 16 October 2013 due to npm bug.
If installed prior to this date, it will actually run as if it is 1.7.6.
* Fixed absolute paths exposal for plugin includes in source maps.
* Workers are now shut down on brunch re-watch.
## Brunch 1.7.6 (Sep 20, 2013)
* Fixed overriding `config.files` in custom environments.
* Fixed issues with old compiler plugin versions.
* Adopted `brunch-config` as the standard config file name.
* Config files named `config` still work, but will be deprecated starting
with 1.8.
## Brunch 1.7.5 (Sep 17, 2013)
* Added experimental workers support.
* Fixed custom enviroment bug.
## Brunch 1.7.4 (Aug 29, 2013)
* Quick fix for `--optimize`d building.
## Brunch 1.7.3 (Aug 28, 2013)
* Added `-e, --env` param to `build` and `watch`
that will replace --config in 1.8.
`env` is a dead-simple way of specifying your work environment.
You can use `--env production` and then specify
`config.overrides.production`, all properties of which will
override default config. You may use more than one --env.
* Source maps for languages which don't support source maps
(“identity source maps”) now generated from
compiled source (js) instead of original source (coffee)
* Deprecated `--optimize` (use `--env production` or `--production`)
and `--config` options.
## Brunch 1.7.2 (Aug 19, 2013)
* Fixed windows issues with compilation.
* Auto-watching `bower.json` for changes now.
* Concatenate JS files in main property of bower component in valid order
(how they were specified in `bower.json`).
* Respect config.order.before in brunch config for bower files.
## Brunch 1.7.1 (Aug 11, 2013)
* Local brunch package now takes precedence over global and
will be auto-loaded on global `brunch` command.
* Added `pluginHelpers` directive to `joinTo` configs. It allows to
specify to which file you want stuff from plugins to be added
(`handlebars-runtime.js`, for example).
* `.htaccess` is now properly copied from assets.
* Fixed issues on windows with copying many assets.
## Brunch 1.7.0 (Jul 23, 2013)
* Added **source maps** support! Big thanks to
[Pierre Lepers](https://github.com/plepers) and
[Elan Shanker](https://github.com/es128).
* Added **Twitter Bower** package manager support.
The support is very different from modern builders.
You don’t need to specify concat order or list all files, brunch will do that
for you automatically.
**But**, some packages don’t specify which files they include and
on which packages they depend.
You may specify `overrides` property in root `bower.json`, see
[read-components docs](http://github.com/paulmillr/read-components)
* Added proper **AMD support**. Just include almond.js with your AMD app
and brunch will do require.js optimizer job for you.
* Added ability to use multiple compilator plugins for one file.
* Added `require.list` support to default require definition of app. This allows
you to automatically load tests and stuff. See new [how-to-run-tests guide](https://github.com/brunch/brunch/blob/master/docs/faq.md#<API key>)
* Added `config.paths.watched` which replaces
`config.paths.{app,test,vendor,assets}`.
* Added `config.modules.nameCleaner`, which allows you to set
filterer function for module names, for example, change all
definitions of app/file to file (as done by default).
* Added `config.fileListInterval` config prop that allows to set an
interval in ms which determines how often brunch file list
should be checked for new files (internal property).
* Added detailed messages of what was done to `compiled in` logs.
* Removed files are now actually removed from compiled output.
* Removed `config.modules.addSourceURLs` directive. Use source maps instead.
* Improved compilation performance.
* Improved error messages when there’s a need in `npm install`.
* Changed syntax of `brunch new` to `brunch new <uri> [dir]`
* Fixed advanced `conventions.assets` issues (e.g. `/styles\/img/`).
## Brunch 1.6.7 (May 8, 2013)
* Fixed `brunch new --skeleton`.
## Brunch 1.6.6 (May 7, 2013)
* Added `plugin#teardown` API support. With it you can stop servers in your
plugins and stuff. It will be called after each brunch stop.
* Added `config.notificationsTitle`.
* Fixed double requiring of some plugins.
* Fixed reloading of `package.json` data.
## Brunch 1.6.5 (May 6, 2013)
* Fixed `--config` option of build / watch commands.
* Fixed `watch` command description.
## Brunch 1.6.4 (May 5, 2013)
* Don’t throw on missing devdependencies. Closes [gh-541](https://github.com/brunch/brunch/issues/541).
* Reload config correctly on change. Closes [gh-540](https://github.com/brunch/brunch/issues/540).
## Brunch 1.6.3 (Apr 7, 2013)
* Fixed watching after `npm install`.
* `config.optimize` is taken into account if it was set manually.
## Brunch 1.6.2 (Apr 1, 2013)
* Fixed watching of config files.
## Brunch 1.6.1 (Mar 25, 2013)
* Fixed `brunch new`.
## Brunch 1.6.0 (Mar 24, 2013)
* Removed `brunch generate` and `brunch destroy`.
[scaffolt](https://github.com/paulmillr/scaffolt) is its simpler successor.
* Removed `brunch test`.
[Mocha-phantomjs](http://metaskills.net/mocha-phantomjs/) is its simpler
successor.
* Adjust config settings, if you have been using those:
* Rename `config` file itself to `brunch-config`
* Rename `config.minify` setting to `config.optimize`
* Rename `config.paths.{app,test,vendor,assets}` to `config.paths.watched`
* Rename `config.paths.ignored` to `config.conventions.ignored`
* Rename `buildPath` to `paths.public`
* Remove `defaultExtension` and `framework` settings
* Use `--production` instead of `--optimize` flag, which has been deprecated.
## Brunch 1.5.4 (Mar 19, 2013)
* Fixed `brunch generate`, switched to standalone modules for some features.
* Added node 0.10 support.
## Brunch 1.5.3 (Feb 2, 2013)
* When using `brunch generate`, generator will no longer overwrite
existing files.
* Preserved context of `include` method of plugins.
## Brunch 1.5.2 (Jan 13, 2013)
* Improved installation process.
## Brunch 1.5.1 (Jan 11, 2013)
* Tester no longer runs watcher by default.
* Changed `brunch test -f REGEX` option to `-g / --grep` for consistency with
Mocha.
## Brunch 1.5.0 (Jan 2, 2013)
* Added ability to wrap files in sourceURLs which simplifies debugging a lot.
Disabled by default in non-production mode, but can be disabled with
`config.modules.addSourceURLs = false`.
* Added `-f REGEX, --filter REGEX` option to `brunch test`.
* `--minify` (`-m`) command line option was changed to `--optimize` (`-o`).
The previous version is deprecated and will be removed in the future.
This is made for plugins that will do optimizations of you application
that are not minifications.
* `config.modules.wrapper` now accepts full file path as first argument, instead
of sanitized.
* Debugging mode syntax was changed to standardized
`DEBUG=brunch:* brunch <command>`.
* Fixed bug when process didn’t return code "1" on compilation errors.
* Brunch will now work only with brunch plugins that have `brunch` in their
name.
* Improved error handling of running brunch in non-brunch app dirs.
## Brunch 1.4.5 (Dec 14, 2012)
* Updated base brunch with chaplin skeleton to the latest libs.
## Brunch 1.4.4 (Oct 1, 2012)
* All errors are now deferred to the compilation end.
Also, if you have added one error on previous compilation and one error on
current, brunch will show both of them until they will be fixed.
* Fixed terminal-notifier.app integration.
* Fixed test passing.
* Fixed `config.notifications` on ubuntu.
## Brunch 1.4.3 (Sep 2, 2012)
* Added support of binary files to generators.
* Improved error logging.
* Updated built-in webserver to express.js 3.0.
## Brunch 1.4.2 (Aug 18, 2012)
* Fixed incorrect scaffolding on windows.
* `.git` directories are now discarded when using `brunch new` with git URL.
## Brunch 1.4.1 (Aug 8, 2012)
* `brunch new` now allowed to take current working directory (`.`) or any
existing directory as first argument.
* Assets are now affected by `conventions.ignored` too.
* Fixed linting bug.
## Brunch 1.4.0 (Aug 4, 2012)
* Added new phenomenally simplified scaffolder:
1. Create `generators/` directory in your brunch application
(directory name is customizable by `config.paths.generators`).
2. Create generator directory there with `generator.json` and
files that will be generated.
* Added conventions:
* Conventions are configurable via `config.conventions[name]`.
Convention can be a RegExp or Function.
* `assets` convention: all files in directories that named as `assets`
(default value) will be copied to public path directly.
* `vendor` All files in directories that named as `vendor`
(default value) won't be wrapped in modules.
* `tests` convention: all files that end with `_test.<extension>`
(default value) are considered as test files and will be loaded
automatically with `brunch test`.
* `ignored` convention: all files that start with `_` (default value)
are considered as partial files and won't be compiled. Useful for
Stylus / Sass languages. This replaces functionality of
`config.paths.ignored`.
* Added AMD support by allowing more flexibility with file wrapping:
* `config.modules` can be an object of:
* `config.modules.wrapper` - string, boolean or function, defines how to
wrap files in app directory in modules.
* `config.modules.definition` - string, boolean or function, defines
what to add on top of every file.
* Added linting support. Linting is a static analysis of code. Example
tools for this are JSHint, CSSLint etc. The lint API is
`plugin.lint(data, path, callback)`. One file can use more than one linter.
* Added config option that disables growl / libnotify notifications.
Usage: `config.notifications = false`.
* Added support for Mac OS X Mountain Lion notification center.
You'll need to place
[terminal-notifier.app](https://github.com/alloy/terminal-notifier/downloads)
to `/Applications/` to get it work.
* Removed support for:
* `config.files[lang].defaultExtension`.
Brunch will automatically detect extension from your generator file name.
* `config.framework`, `config.generators`. It's not needed because all
generators are local to your application and because brunch now has
`generators/` directory.
* Array type of `paths.vendor` / `paths.assets`. They're replaced by
conventions.
* If any error happened in `brunch build`, it will exit with error code `1`
instead of `0`.
* Fixed commonjs `require_definition` in <IE9.
## Brunch 1.3.4 (Jul 7, 2012)
* Fixed bug with too fast compilations.
## Brunch 1.3.3 (Jun 29, 2012)
* Added node.js 0.8 and 0.9 support.
* `jsdom`, required for `brunch test` can now be installed once for all apps via
`npm install -g jsdom`. You'll need to have its parent dir in `NODE_MODULES`
env variable.
* Fixed `compiled in` timer and `brunch generate` bugs.
## Brunch 1.3.2 (Jun 27, 2012)
* Fixed `brunch test` on new projects.
## Brunch 1.3.1 (Jun 22, 2012)
* Config can now be in any language you use in app (e.g. livescript).
* Added `--reporter` (`-r`) option to `brunch test` which allows to choose
Mocha reporter.
* Made require definition much easier for debugging.
## Brunch 1.3.0 (Jun 19, 2012)
* Brunch with Chaplin is now the default application skeleton, that will be
created on `brunch new <app>`. Old one is still available with
`brunch new <app> -s github://brunch/<API key>`.
Chaplin is an awesome set of classes on top of Backbone.js that makes making
big webapps very simple.
* Added testing support (thanks to Andreas Gerstmayr):
* [Mocha](http://visionmedia.github.com/mocha/) is used as test engine.
It's a feature-rich, flexible and fun.
* `brunch test` (or `brunch t`) is used to run all tests in CLI env.
* `test` directory is now watched. Add `'javascripts/tests.js': /^test/`
to `config.javascripts.joinTo` in `config.coffee` to compile them.
* Improved command line API:
* Added `github://user/repo` skeleton address schema support to
`brunch new`.
* Debug mode now has logger namespaces. Usage:
`BRUNCH_DEBUG=<ns> brunch <command>` where `<ns>` is:
`watcher`, `writer`, `*`.
* Improved file watcher:
* Vim backup files are now ignored by watcher.
* Fixed watching of non-compiled files in `app`.
* Improved config API:
* Added support for `config.server.base`, which determines base URL from
which to serve the app. The default value is empty string.
* `config.paths.ignored` now doesn't need to check versus if file is
`config.coffee` or `package.json`, it does it automatically in brunch
code.
* Fixed `config.paths.ignored` on windows.
* `config.paths.vendor` is now an array, but it will be soon deprecated.
* Changed `onCompile` plugin API. Now it receives an array of
`fs_utils.GeneratedFile`. This makes it very rich and allows to build smarter
reloaders. For example, the ones that reload browser tabs only on stylesheet
change.
* Semicolon is now added after every compiled vendor library because of some
libs that break with brunch. Hello, Zepto!
* Styles in `vendor` directory are now sorted correctly, before `app` files.
* Only generated files that depend on changed in current compilation files are
written now. Before, brunch was writing all files each time.
## Brunch 1.2.2 (May 24, 2012)
* Brunch now outputs compilation time.
* Assets are copied one-by-one on change, instead of copying the whole assets
directory. This improves watcher performance by about 25%+.
* Disabled caching in built-in webserver.
* Improved `brunch generate`:
* Added `--plural` option to `brunch generate`. Plural version of generator
name is used in controllers and collections. By default, brunch does
pluralizing instead of you.
* Added `collection` generator to `brunch generate`. It is not included in
`brunch g scaffold`, because it's not needed most of the time.
* Added `collectionView` generator to `brunch generate` for Chaplin users.
It doesn't generate corresponding `template`.
* If `package.json` or `config.coffee` were removed during the watching, brunch
process will exit.
* Maximum time between changes of two files that will be considered as a one
compilation changed from 100ms to 65ms.
## Brunch 1.2.1 (May 12, 2012)
* Fixed persistence of process with `brunch watch` (without server).
* Fixed watching of files on windows.
## Brunch 1.2.0 (May 12, 2012)
* Greatly improved `brunch generate`:
* User can now define his own generators in `config.generators`.
* Default generators are now:
* `controllerTest`, `modelTest`, `viewTest`, `template`, `style`
* `controller` (generates `controllerTest` too)
* `model` (generates `modelTest` too)
* `view` (generates `template`, `style` & `viewTest` too)
* `scaffold` (generates `controller`, `model`, `view` and their
generators)
* Improved config API:
* Added `paths.ignored` param that redefines paths ignored by brunch.
* `paths.assets` can now be an array of paths.
* Improved plugin API:
* Added support for `onCompile` method.
It allows great & simple live browser reloaders.
* Added pushState support to the built-in webserver.
* Files that end with two underscores (e.g. `a.js__`) are now ignored by
watcher and compiler because they're created by some IDEs.
* Files in `vendor` directory are now sorted correctly, before `app` files.
## Brunch 1.1.2 (Apr 20, 2012)
* Fixed `buildPath is deprecated` warning on new configs.
* Fixed compiling of invalid files (`.rb`, `.png` etc).
## Brunch 1.1.1 (Apr 19, 2012)
* Fixed compiling of `package.json`, `config` and watching of assets.
* Fixed incorrect date in brunch logger.
* Fixed an error when requiring custom server script.
## Brunch 1.1.0 (Apr 15, 2012)
* Added windows support.
* Added node.js 0.7 / 0.8 support.
* Added support for chain compilation. For example, if `_user.styl` changes and
`main.styl` depends on it, `main.styl` will be recompiled too.
* `brunch watch` now also watches config & `package.json`.
* Improved command line API:
* Added optional `--config` param to all commands expect `brunch new`.
Usage: `brunch build --config ios_config`.
* Brought back `--minify` param in `brunch build` and `brunch watch`.
* Deprecated `--output` param in `brunch build` and `brunch watch`.
* Param `--template` in `brunch new` has been renamed to `--skeleton`.
`--skeleton` supports relative / absolute path and git repo URLs.
Also, git metadata is automatically removed in cloned / copied projects.
* Improved config API:
* `buildPath` is now deprecated, `paths.public` is used instead of it.
* Added `paths.app`, `paths.root`, `paths.assets`, `paths.test`,
`paths.vendor`.
* Scripts that are not in the config[lang].order are now compiled in
alphabetical order instead of random.
* Made optional presence of almost all config params.
* Improved module loader:
* Real exceptions are now thrown instead of strings when module wasn't
found.
* Fixed an issue when loader cached same modules more than once.
* Fixed an issue when loader loaded non-existing modules.
* Greatly improved default coffee skeleton architecture:
* Moved all collections to `models`.
* Replaced `routers` with `lib/router`.
* No more global variable for application bootstrapper, it can be loaded
with `require 'application'`.
* Switched default templates to Handlebars. Handlebars.js is a nice
mustache-compatible template engine that supports helpers
(`lib/view_helper`).
* Fixed loading of non-coffeescript configs.
* Made optional existence of `app` & `vendor` directories.
* Node.js API now mirrors command line api.
## Brunch 1.0.3 (Apr 3, 2012)
* Dotfiles from assets dir are prevented to be copied to build dir.
## Brunch 1.0.2 (Mar 28, 2012)
* Removed `Cakefile` from default template.
* Changed recommended framework in `test/spec` to Mocha.
## Brunch 1.0.1 (Mar 26, 2012)
* Updated dependencies.
* Fixed permissions issue with `app/assets` folder.
## Brunch 1.0.0 (Mar 14, 2012)
* Simplified config files.
* Default app now uses two separate files to simplify debugging: `app.js` and
`vendor.js`.
* Changed default naming of build directory & its subdirs. Now the style matches
expressjs and rails.
* `build` directory is now `public`.
* `scripts` has been renamed to `javascripts`.
* `styles` has been renamed to `stylesheets`.
* Rewritten API for plugins to be framework-agnostic & much more simple:
* All `brunch-extensions` plugins have been split into separate repos.
* Added support for generator templates.
* Added support for different extensions in brunch generators.
* Added support for including files with plugins.
* Improved command line API:
* Added `--template` / `-t` option to `brunch new`.
* Added `--path` `-p` option to `brunch generate`.
* Added support for custom webservers to `brunch watch --server`.
* Files, whose names start with `_` and files in `app/assets` are now ignored by
compiler (but not by watcher).
* Update backbone to 0.9.1, underscore to 1.3.1 and jquery to 1.7.1.
* Added IcedCoffeeScript plugin.
* Fixed Jade templates. See [jade-brunch](https://github.com/brunch/jade-brunch)
for more info.
* Added support for javascript config files.
* Added debugging mode. You can enable it by prepending `BRUNCH_DEBUG=1 ` to
brunch command.
## Brunch 0.9.1 (Feb 21, 2012)
* Updated brunch-extensions to 0.2.2.
## Brunch 0.9.0 (Jan 10, 2012)
* Added new API for plugins.
* Added support for Jade, LESS and Roy. All language compilers / plugins are now
located in separate repo,
[brunch-extensions](https://github.com/brunch/brunch-extensions).
* Added JS & CSS minifier.
* CoffeeScript (instead of YAML) is now used for application configs.
* Improved file watcher speed by 5-fold.
* Implemented new directory structure:
* The build directory is now generated automatically.
* All assets (index.html, images etc.) are placed in app/assets/.
* `main.coffee` was renamed to `initialize.coffee` for clarity.
* `src/vendor` and `src/app` moved to `vendor` and `app`.
* All scripts from `src/vendor` are moved to `app/vendor/scripts`.
* Added support for CoffeeScript in `vendor/scripts`.
* Added support for Stylus / LESS in `vendor/styles`.
* Templates have moved from `app/templates` to `app/views/templates`.
* Updated command line API:
* `brunch build` and `brunch watch` now compile files in current working
directory (instead of in `./brunch/` subdir).
* Added `brunch generate` command. It's basically a shortcut for creating
new model / view / router. Example usage: `brunch generate view user`.
* Added `brunch watch --server` flag that would run http server on build
directory. It has an optional `--port` setting.
* Added support for node 0.6.
* Added growl support.
* Changed reset.styl to normalize.css & helpers.css from html5boilerplate.
* Improvements for vendor data: support CSS in vendor/styles directory,
support CoffeeScript (in addition to js) in vendor/scripts directory.
* Add firebug support to stylus compiler.
* Improved time formatting in console logs. |
/* Use, modification and distribution is subject to the Boost Software */
/* Authors: Jeremiah Willcock */
/* Andrew Lumsdaine */
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef <API key>
#define <API key>
#endif
#include <inttypes.h>
#include <stdio.h>
#include <mpi.h>
#include "make_graph.h"
int main(int argc, char* argv[]) {
int log_numverts;
int size, rank;
unsigned long my_edges;
unsigned long global_edges;
double start, stop;
size_t i;
MPI_Init(&argc, &argv);
log_numverts = 16; /* In base <API key> */
if (argc >= 2) log_numverts = atoi(argv[1]);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) fprintf(stderr, "Graph size is %" PRIu64 " vertices and %" PRIu64 " edges\n", (uint64_t)pow(2., log_numverts), (uint64_t)(pow(2., log_numverts) * 8.));
/* Start of graph generation timing */
MPI_Barrier(MPI_COMM_WORLD);
start = MPI_Wtime();
int64_t nedges;
int64_t* result;
double initiator[] = {.57, .19, .19, .05};
make_graph(log_numverts, 8. * pow(2., log_numverts), 1, 2, initiator, &nedges, &result);
MPI_Barrier(MPI_COMM_WORLD);
stop = MPI_Wtime();
/* End of graph generation timing */
my_edges = 0;
for (i = 0; i < nedges; ++i) {
if (result[2 * i] != (uint64_t)(-1)) {
++my_edges;
}
}
free(result);
MPI_Reduce(&my_edges, &global_edges, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
fprintf(stderr, "%lu edge%s generated and permuted in %fs (%f Medges/s on %d processor%s)\n", global_edges, (global_edges == 1 ? "" : "s"), (stop - start), global_edges / (stop - start) * 1.e-6, size, (size == 1 ? "" : "s"));
}
MPI_Finalize();
return 0;
} |
// <API key>: Apache-2.0 WITH LLVM-exception
#include "lldb/Symbol/<API key>.h"
// Clang headers like to use NDEBUG inside of them to enable/disable debug
// related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
// or another. This is bad because it means that if clang was built in release
// mode, it assumes that you are building in release mode which is not always
// the case. You can end up with functions that are defined as empty in header
// files when NDEBUG is not defined, and this can cause link errors with the
// clang .a files that you have since you might be missing functions in the .a
// file. So we have to define NDEBUG when including clang headers to avoid any
// mismatches. This is covered by rdar://problem/8691220
#if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
#define <API key>
#define NDEBUG
// Need to include assert.h so it is as clang would expect it to be (disabled)
#include <assert.h>
#endif
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclarationName.h"
#ifdef <API key>
#undef NDEBUG
#undef <API key>
// Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
#include <assert.h>
#endif
#include "lldb/Utility/Log.h"
#include "clang/AST/Decl.h"
using namespace clang;
using namespace lldb_private;
bool <API key>::<API key>(
const clang::DeclContext *decl_ctx,
clang::DeclarationName clang_decl_name) {
if (<API key>) {
llvm::SmallVector<clang::NamedDecl *, 3> results;
<API key>(m_callback_baton, decl_ctx, clang_decl_name,
&results);
<API key>(decl_ctx, clang_decl_name, results);
return (results.size() != 0);
}
std::string decl_name(clang_decl_name.getAsString());
<API key>(decl_ctx, clang_decl_name);
return false;
}
void <API key>::CompleteType(TagDecl *tag_decl) {
if (m_callback_tag_decl)
m_callback_tag_decl(m_callback_baton, tag_decl);
}
void <API key>::CompleteType(
ObjCInterfaceDecl *objc_decl) {
if (<API key>)
<API key>(m_callback_baton, objc_decl);
}
bool <API key>::layoutRecordType(
const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets,
llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &BaseOffsets,
llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
&VirtualBaseOffsets) {
if (<API key>)
return <API key>(m_callback_baton, Record, Size,
Alignment, FieldOffsets, BaseOffsets,
VirtualBaseOffsets);
return false;
}
void <API key>::<API key>(
const clang::DeclContext *decl_ctx,
llvm::function_ref<bool(clang::Decl::Kind)> IsKindWeWant,
llvm::SmallVectorImpl<clang::Decl *> &decls) {
if (m_callback_tag_decl && decl_ctx) {
clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(
const_cast<clang::DeclContext *>(decl_ctx));
if (tag_decl)
CompleteType(tag_decl);
}
} |
"use strict";
var <API key> = require("@babel/runtime/helpers/<API key>");
exports.__esModule = true;
exports.getGatsbyVersion = void 0;
var _path = <API key>(require("path"));
const getGatsbyVersion = () => {
try {
return require(_path.default.join(process.cwd(), `node_modules`, `gatsby`, `package.json`)).version;
} catch (e) {
return ``;
}
};
exports.getGatsbyVersion = getGatsbyVersion; |
// <API key>.h
// SDProgressView
#import "SDBaseProgressView.h"
@interface <API key> : SDBaseProgressView
@end |
package com.quinn.githubknife.ui.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.quinn.githubknife.presenter.<API key>;
import com.quinn.githubknife.ui.activity.EventAdapter;
import com.quinn.githubknife.ui.activity.UserInfoActivity;
import com.quinn.githubknife.ui.widget.<API key>;
import com.quinn.httpknife.github.Event;
import com.quinn.httpknife.github.GithubImpl;
import com.quinn.httpknife.github.User;
import java.util.ArrayList;
import java.util.List;
public class <API key> extends BaseFragment implements <API key> {
private EventAdapter adapter;
public static <API key> getInstance(String user){
<API key> <API key> = new <API key>();
Bundle bundle = new Bundle();
bundle.putString("user", user);
<API key>.setArguments(bundle);
return <API key>;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new <API key>(this.getActivity(),this);
dataItems = new ArrayList<Event>();
adapter = new EventAdapter(dataItems);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater,container,savedInstanceState);
recyclerView.setAdapter(adapter);
adapter.<API key>(this);
return view;
}
@Override
public void setItems(List<?> items) {
super.setItems(items);
for(Object repo:items){
dataItems.add((Event) repo);
}
loading = false;
if(items.size() < GithubImpl.DEFAULT_PAGE_SIZE)
haveMore = false;
adapter.<API key>();
}
@Override
public void onItemClick(View view, int position) {
intoItem(position);
}
@Override
public void intoItem(final int position) {
Event event = (Event)dataItems.get(position);
User user = (User)event.getActor();
Bundle bundle = new Bundle();
bundle.putSerializable("user",user);
UserInfoActivity.launch(<API key>.this.getActivity(),bundle);
}
} |
# This makefile is mainly intended for use on the CI server (Travis). It
# requires xcpretty to be installed.
# If you are trying to build a release locally consider using the build.rb
# script in the Tools directory instead.
BUILD_DIR = OBJROOT="$(CURDIR)/build" SYMROOT="$(CURDIR)/build"
SHELL = /bin/bash -e -o pipefail
IPHONE = -scheme OCMockLib -sdk iphonesimulator -destination 'name=iPhone 4S' $(BUILD_DIR)
MACOSX = -scheme OCMock -sdk macosx $(BUILD_DIR)
XCODEBUILD = xcodebuild -project "$(CURDIR)/Source/OCMock.xcodeproj"
ci: clean test
clean:
$(XCODEBUILD) clean
rm -rf "$(CURDIR)/build"
test: test-iphone test-macosx
test-iphone:
@echo "Running iPhone tests..."
$(XCODEBUILD) $(IPHONE) test | xcpretty -c
test-macosx:
@echo "Running OS X tests..."
$(XCODEBUILD) $(MACOSX) test | xcpretty -c |
#include <paddle/capi.h>
#include <time.h>
#include "../common/common.h"
#define CONFIG_BIN "./trainer_config.bin"
int main() {
// Initalize Paddle
char* argv[] = {"--use_gpu=False"};
CHECK(paddle_init(1, (char**)argv));
// Reading config binary file. It is generated by `convert_protobin.sh`
long size;
void* buf = read_config(CONFIG_BIN, &size);
// Create a gradient machine for inference.
<API key> machine;
CHECK(<API key>(&machine, buf, (int)size));
CHECK(<API key>(machine));
// Loading parameter. Uncomment the following line and change the directory.
// CHECK(<API key>(machine,
// "./<API key>"));
paddle_arguments in_args = <API key>();
// There is only one input of this network.
CHECK(<API key>(in_args, 1));
// Create input ids.
int sentence_ids[] = {83, 48, 20, 84, 394, 853, 64, 53, 64};
paddle_ivector sentence = <API key>(
sentence_ids, sizeof(sentence_ids) / sizeof(int), false, false);
CHECK(<API key>(in_args, 0, sentence));
int seq_pos_array[] = {0, sizeof(sentence_ids) / sizeof(int)};
paddle_ivector seq_pos = <API key>(
seq_pos_array, sizeof(seq_pos_array) / sizeof(int), false, false);
CHECK(<API key>(in_args, 0, 0, seq_pos));
paddle_arguments out_args = <API key>();
CHECK(<API key>(machine,
in_args,
out_args,
/* isTrain */ false));
paddle_matrix prob = <API key>();
CHECK(<API key>(out_args, 0, prob));
paddle_real* array;
CHECK(<API key>(prob, 0, &array));
printf("Prob: ");
for (int i = 0; i < 2; ++i) {
printf("%.2f ", array[i]);
}
printf("\n");
CHECK(<API key>(prob));
CHECK(<API key>(out_args));
CHECK(<API key>(seq_pos));
CHECK(<API key>(sentence));
CHECK(<API key>(in_args));
CHECK(<API key>(machine));
return 0;
} |
# Motivation
Web browsers generally do not allow audio to be played by media elements, unless they were explicitly played by a user gesture. [iOS Safari](https://webkit.org/blog/6784/<API key>/), [Google Chrome](https://developers.google.com/web/updates/2017/09/<API key>), etc. This behavior causes the problem outlined by #11856 where, since stories sometimes automatically (without user input) advance to new pages with media, some stories can fail to play media on some pages.
# High-Level Design
Every story always starts muted. Because muted autoplay of video is allowed by browsers, all videos are allowed to play. We offer an audio control to users where tapping the control unmutes ALL of the media present in the story. It then subsequently re-mutes all of the media, except for any media on the current page that should have otherwise been unmuted. We herein refer to this operation of umuting and immediately (conditionally) re-muting a media element in response to user gesture as "blessing" said media element. Blessing a media element leverages the user gesture to unmute that media element, so that future unmute operations do not require a user gesture.
# Detailed Design
Some browsers (notably, iOS Safari) place an explicit maximum on the number of media elements allowed to be kept in memory at once (as we last tested it in November 2017, this limit was 16). To ensure that all media elements get blessed, even when more than 16 are present, we maintain a pool of a fixed number of media elements, where the maximum number of media elements allowed is less than 16 (currently a maximum of 8 `<video>` tags and 4 `audio` tags, for a total of 12 elements). We refer to this pool as `MediaPool`, and it handles recycling the media elements it controls by swapping them in and out of the DOM as the user navigates through a story.
By default, these `<audio>` and `<video>` elements are set to blank audio and video files. Notably, they are _not_ set to the empty string, but rather data URIs that represent an MP3 and an MP4 (respectively) that have no audio or video. This is because invoking media playback functions like `play()`, `pause()`, `mute()`, and `unmute()` does not work if the media element's source is unset.
## Lifecycle

Each media element present in the document should be registered into the media pool as soon as possible. Once registered, a media element can be blessed, and that blessed state will be honored regardless of whether the source of that media element is subsequently changed.
We preload media elements based on what we refer to as the element's "distance": how far the element is away from the user's current position in the document. For stories, we measure this distance in pages; an element on the page the user is currently viewing has a distance of 0, an element on the page immediately before or after the page the user is currently viewing has a distance of 1, an element on the page two pages before or two pages after has a distance of 2, etc. Stories currently preload elements on pages that have a distance of 2 or less. If there are more elements in the story than can fit in the `MediaPool`, then media elements are evicted based on their distance; elements with the highest distance are evicted first, until all elements that are loaded have been allocated a resource from the pool.
Once a media element has been loaded, one can call `play()`, `pause()`, `mute()`, or `unmute()`.
## Queueing
Some browsers can also have problems with the underlying media element methods interrupting one another, depending on the order in which they are invoked. For example, calling `load()` on a media element after calling `play()` can cause the promise returned by `play()` to be rejected. An example of the problems caused by this is outlined in #13232.
To resolve this, we create a task queue, stored as a property on each media element. The `MediaPool` queues all media-element-bound tasks and executes them only upon completion of the previous tasks. This eliminates the race conditions that come with invoking many of the functions on a media element, as well as from swapping the elements into (and out of) the DOM.
# Code
- MediaPool: https://github.com/ampproject/amphtml/blob/master/extensions/amp-story/1.0/media-pool.js
- Tasks for queue: https://github.com/ampproject/amphtml/blob/master/extensions/amp-story/1.0/media-tasks.js |
package com.mxgraph.shape;
import java.awt.Rectangle;
import java.util.Map;
import com.mxgraph.canvas.mxGraphics2DCanvas;
import com.mxgraph.swing.util.mxSwingConstants;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxCellState;
public class mxRectangleShape extends mxBasicShape
{
public void paintShape(mxGraphics2DCanvas canvas, mxCellState state)
{
Map<String, Object> style = state.getStyle();
if (mxUtils.isTrue(style, mxConstants.STYLE_ROUNDED, false))
{
Rectangle tmp = state.getRectangle();
int x = tmp.x;
int y = tmp.y;
int w = tmp.width;
int h = tmp.height;
int radius = getArcSize(state, w, h);
boolean shadow = hasShadow(canvas, state);
int shadowOffsetX = (shadow) ? mxConstants.SHADOW_OFFSETX : 0;
int shadowOffsetY = (shadow) ? mxConstants.SHADOW_OFFSETY : 0;
if (canvas.getGraphics().hitClip(x, y, w + shadowOffsetX,
h + shadowOffsetY))
{
// Paints the optional shadow
if (shadow)
{
canvas.getGraphics().setColor(mxSwingConstants.SHADOW_COLOR);
canvas.getGraphics().fillRoundRect(
x + mxConstants.SHADOW_OFFSETX,
y + mxConstants.SHADOW_OFFSETY, w, h, radius,
radius);
}
// Paints the background
if (configureGraphics(canvas, state, true))
{
canvas.getGraphics().fillRoundRect(x, y, w, h, radius,
radius);
}
// Paints the foreground
if (configureGraphics(canvas, state, false))
{
canvas.getGraphics().drawRoundRect(x, y, w, h, radius,
radius);
}
}
}
else
{
Rectangle rect = state.getRectangle();
// Paints the background
if (configureGraphics(canvas, state, true))
{
canvas.fillShape(rect, hasShadow(canvas, state));
}
// Paints the foreground
if (configureGraphics(canvas, state, false))
{
canvas.getGraphics().drawRect(rect.x, rect.y, rect.width,
rect.height);
}
}
}
/**
* Helper method to configure the given wrapper canvas.
*/
protected int getArcSize(mxCellState state, double w, double h)
{
double f = mxUtils.getDouble(state.getStyle(),
mxConstants.STYLE_ARCSIZE,
mxConstants.<API key> * 100) / 100;
return (int) (Math.min(w, h) * f * 2);
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Mon Dec 20 13:46:16 EST 2010 -->
<TITLE>
DescriptorHandler (Apache Ant API)
</TITLE>
<META NAME="keywords" CONTENT="org.apache.tools.ant.taskdefs.optional.ejb.DescriptorHandler class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="DescriptorHandler (Apache Ant API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/<API key>.html" title="class in org.apache.tools.ant.taskdefs.optional.ejb"><B>PREV CLASS</B></A>
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.html" title="interface in org.apache.tools.ant.taskdefs.optional.ejb"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html" target="_top"><B>FRAMES</B></A>
<A HREF="DescriptorHandler.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
org.apache.tools.ant.taskdefs.optional.ejb</FONT>
<BR>
Class DescriptorHandler</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by ">org.xml.sax.HandlerBase
<IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.tools.ant.taskdefs.optional.ejb.DescriptorHandler</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>org.xml.sax.DocumentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>DescriptorHandler</B><DT>extends org.xml.sax.HandlerBase</DL>
</PRE>
<P>
Inner class used by EjbJar to facilitate the parsing of deployment
descriptors and the capture of appropriate information. Extends
HandlerBase so it only implements the methods needed. During parsing
creates a hashtable consisting of entries mapping the name it should be
inserted into an EJB jar as to a File representing the file on disk. This
list can then be accessed through the getFiles() method.
<P>
<P>
<HR>
<P>
<A NAME="field_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#currentElement">currentElement</A></B></CODE>
<BR>
Instance variable used to store the name of the current element being
processed by the SAX parser.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#currentText">currentText</A></B></CODE>
<BR>
The text of the current element</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.util.Hashtable</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#ejbFiles">ejbFiles</A></B></CODE>
<BR>
Instance variable that stores the names of the files as they will be
put into the jar file, mapped to File objects Accessed by the SAX
parser call-back method characters().</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#ejbName">ejbName</A></B></CODE>
<BR>
Instance variable that stores the value found in the <ejb-name> element</TD>
</TR>
</TABLE>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#DescriptorHandler(org.apache.tools.ant.Task, java.io.File)">DescriptorHandler</A></B>(<A HREF="../../../../../../../org/apache/tools/ant/Task.html" title="class in org.apache.tools.ant">Task</A> task,
java.io.File srcDir)</CODE>
<BR>
Constructor for DescriptorHandler.</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#characters(char[], int, int)">characters</A></B>(char[] ch,
int start,
int length)</CODE>
<BR>
SAX parser call-back method invoked whenever characters are located within
an element.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#endElement(java.lang.String)">endElement</A></B>(java.lang.String name)</CODE>
<BR>
SAX parser call-back method that is invoked when an element is exited.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#getEjbName()">getEjbName</A></B>()</CODE>
<BR>
Getter method that returns the value of the <ejb-name> element.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.Hashtable</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#getFiles()">getFiles</A></B>()</CODE>
<BR>
Getter method that returns the set of files to include in the EJB jar.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#getPublicId()">getPublicId</A></B>()</CODE>
<BR>
Get the publicId of the DTD</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#processElement()">processElement</A></B>()</CODE>
<BR>
Called when an endelement is seen.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#registerDTD(java.lang.String, java.lang.String)">registerDTD</A></B>(java.lang.String publicId,
java.lang.String location)</CODE>
<BR>
Register a dtd with a location.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> org.xml.sax.InputSource</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#resolveEntity(java.lang.String, java.lang.String)">resolveEntity</A></B>(java.lang.String publicId,
java.lang.String systemId)</CODE>
<BR>
Resolve the entity.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#startDocument()">startDocument</A></B>()</CODE>
<BR>
SAX parser call-back method that is used to initialize the values of some
instance variables to ensure safe operation.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html#startElement(java.lang.String, org.xml.sax.AttributeList)">startElement</A></B>(java.lang.String name,
org.xml.sax.AttributeList attrs)</CODE>
<BR>
SAX parser call-back method that is invoked when a new element is entered
into.</TD>
</TR>
</TABLE>
<A NAME="<API key>.xml.sax.HandlerBase"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class org.xml.sax.HandlerBase</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>endDocument, error, fatalError, ignorableWhitespace, notationDecl, <API key>, setDocumentLocator, unparsedEntityDecl, warning</CODE></TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="field_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="currentElement"></A><H3>
currentElement</H3>
<PRE>
protected java.lang.String <B>currentElement</B></PRE>
<DL>
<DD>Instance variable used to store the name of the current element being
processed by the SAX parser. Accessed by the SAX parser call-back methods
startElement() and endElement().
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="currentText"></A><H3>
currentText</H3>
<PRE>
protected java.lang.String <B>currentText</B></PRE>
<DL>
<DD>The text of the current element
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="ejbFiles"></A><H3>
ejbFiles</H3>
<PRE>
protected java.util.Hashtable <B>ejbFiles</B></PRE>
<DL>
<DD>Instance variable that stores the names of the files as they will be
put into the jar file, mapped to File objects Accessed by the SAX
parser call-back method characters().
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="ejbName"></A><H3>
ejbName</H3>
<PRE>
protected java.lang.String <B>ejbName</B></PRE>
<DL>
<DD>Instance variable that stores the value found in the <ejb-name> element
<P>
<DL>
</DL>
</DL>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="DescriptorHandler(org.apache.tools.ant.Task, java.io.File)"></A><H3>
DescriptorHandler</H3>
<PRE>
public <B>DescriptorHandler</B>(<A HREF="../../../../../../../org/apache/tools/ant/Task.html" title="class in org.apache.tools.ant">Task</A> task,
java.io.File srcDir)</PRE>
<DL>
<DD>Constructor for DescriptorHandler.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>task</CODE> - the task that owns this desciptor<DD><CODE>srcDir</CODE> - the source directory</DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="registerDTD(java.lang.String, java.lang.String)"></A><H3>
registerDTD</H3>
<PRE>
public void <B>registerDTD</B>(java.lang.String publicId,
java.lang.String location)</PRE>
<DL>
<DD>Register a dtd with a location.
The location is one of a filename, a resource name in the classpath, or
a URL.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>publicId</CODE> - the public identity of the dtd<DD><CODE>location</CODE> - the location of the dtd</DL>
</DD>
</DL>
<HR>
<A NAME="resolveEntity(java.lang.String, java.lang.String)"></A><H3>
resolveEntity</H3>
<PRE>
public org.xml.sax.InputSource <B>resolveEntity</B>(java.lang.String publicId,
java.lang.String systemId)
throws org.xml.sax.SAXException</PRE>
<DL>
<DD>Resolve the entity.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>resolveEntity</CODE> in interface <CODE>org.xml.sax.EntityResolver</CODE><DT><B>Overrides:</B><DD><CODE>resolveEntity</CODE> in class <CODE>org.xml.sax.HandlerBase</CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>publicId</CODE> - The public identifier, or <code>null</code>
if none is available.<DD><CODE>systemId</CODE> - The system identifier provided in the XML
document. Will not be <code>null</code>.
<DT><B>Returns:</B><DD>an inputsource for this identifier
<DT><B>Throws:</B>
<DD><CODE>org.xml.sax.SAXException</CODE> - if there is a problem.<DT><B>See Also:</B><DD><CODE>EntityResolver.resolveEntity(String, String).</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getFiles()"></A><H3>
getFiles</H3>
<PRE>
public java.util.Hashtable <B>getFiles</B>()</PRE>
<DL>
<DD>Getter method that returns the set of files to include in the EJB jar.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the map of files</DL>
</DD>
</DL>
<HR>
<A NAME="getPublicId()"></A><H3>
getPublicId</H3>
<PRE>
public java.lang.String <B>getPublicId</B>()</PRE>
<DL>
<DD>Get the publicId of the DTD
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the public id</DL>
</DD>
</DL>
<HR>
<A NAME="getEjbName()"></A><H3>
getEjbName</H3>
<PRE>
public java.lang.String <B>getEjbName</B>()</PRE>
<DL>
<DD>Getter method that returns the value of the <ejb-name> element.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the ejb name</DL>
</DD>
</DL>
<HR>
<A NAME="startDocument()"></A><H3>
startDocument</H3>
<PRE>
public void <B>startDocument</B>()
throws org.xml.sax.SAXException</PRE>
<DL>
<DD>SAX parser call-back method that is used to initialize the values of some
instance variables to ensure safe operation.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>startDocument</CODE> in interface <CODE>org.xml.sax.DocumentHandler</CODE><DT><B>Overrides:</B><DD><CODE>startDocument</CODE> in class <CODE>org.xml.sax.HandlerBase</CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>org.xml.sax.SAXException</CODE> - on error</DL>
</DD>
</DL>
<HR>
<A NAME="startElement(java.lang.String, org.xml.sax.AttributeList)"></A><H3>
startElement</H3>
<PRE>
public void <B>startElement</B>(java.lang.String name,
org.xml.sax.AttributeList attrs)
throws org.xml.sax.SAXException</PRE>
<DL>
<DD>SAX parser call-back method that is invoked when a new element is entered
into. Used to store the context (attribute name) in the currentAttribute
instance variable.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>startElement</CODE> in interface <CODE>org.xml.sax.DocumentHandler</CODE><DT><B>Overrides:</B><DD><CODE>startElement</CODE> in class <CODE>org.xml.sax.HandlerBase</CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>name</CODE> - The name of the element being entered.<DD><CODE>attrs</CODE> - Attributes associated to the element.
<DT><B>Throws:</B>
<DD><CODE>org.xml.sax.SAXException</CODE> - on error</DL>
</DD>
</DL>
<HR>
<A NAME="endElement(java.lang.String)"></A><H3>
endElement</H3>
<PRE>
public void <B>endElement</B>(java.lang.String name)
throws org.xml.sax.SAXException</PRE>
<DL>
<DD>SAX parser call-back method that is invoked when an element is exited.
Used to blank out (set to the empty string, not nullify) the name of
the currentAttribute. A better method would be to use a stack as an
instance variable, however since we are only interested in leaf-node
data this is a simpler and workable solution.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>endElement</CODE> in interface <CODE>org.xml.sax.DocumentHandler</CODE><DT><B>Overrides:</B><DD><CODE>endElement</CODE> in class <CODE>org.xml.sax.HandlerBase</CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>name</CODE> - The name of the attribute being exited. Ignored
in this implementation.
<DT><B>Throws:</B>
<DD><CODE>org.xml.sax.SAXException</CODE> - on error</DL>
</DD>
</DL>
<HR>
<A NAME="characters(char[], int, int)"></A><H3>
characters</H3>
<PRE>
public void <B>characters</B>(char[] ch,
int start,
int length)
throws org.xml.sax.SAXException</PRE>
<DL>
<DD>SAX parser call-back method invoked whenever characters are located within
an element. currentAttribute (modified by startElement and endElement)
tells us whether we are in an interesting element (one of the up to four
classes of an EJB). If so then converts the classname from the format
org.apache.tools.ant.Parser to the convention for storing such a class,
org/apache/tools/ant/Parser.class. This is then resolved into a file
object under the srcdir which is stored in a Hashtable.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE>characters</CODE> in interface <CODE>org.xml.sax.DocumentHandler</CODE><DT><B>Overrides:</B><DD><CODE>characters</CODE> in class <CODE>org.xml.sax.HandlerBase</CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>ch</CODE> - A character array containing all the characters in
the element, and maybe others that should be ignored.<DD><CODE>start</CODE> - An integer marking the position in the char
array to start reading from.<DD><CODE>length</CODE> - An integer representing an offset into the
char array where the current data terminates.
<DT><B>Throws:</B>
<DD><CODE>org.xml.sax.SAXException</CODE> - on error</DL>
</DD>
</DL>
<HR>
<A NAME="processElement()"></A><H3>
processElement</H3>
<PRE>
protected void <B>processElement</B>()</PRE>
<DL>
<DD>Called when an endelement is seen.
This may be overridden in derived classes.
This updates the ejbfiles if the element is an interface or a bean class.
This updates the ejbname if the element is an ejb name.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/<API key>.html" title="class in org.apache.tools.ant.taskdefs.optional.ejb"><B>PREV CLASS</B></A>
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ejb/EJBDeploymentTool.html" title="interface in org.apache.tools.ant.taskdefs.optional.ejb"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/tools/ant/taskdefs/optional/ejb/DescriptorHandler.html" target="_top"><B>FRAMES</B></A>
<A HREF="DescriptorHandler.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML> |
package edu.harvard.iq.dataverse.engine.command.impl;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.Dataverse;
import edu.harvard.iq.dataverse.authorization.DataverseRole;
import edu.harvard.iq.dataverse.DvObject;
import edu.harvard.iq.dataverse.RoleAssignment;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.engine.command.AbstractCommand;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.DataverseRequest;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* Assign a in a dataverse to a user.
*
* @author michael
*/
public class AssignRoleCommand extends AbstractCommand<RoleAssignment> {
private final DataverseRole role;
private final RoleAssignee grantee;
private final DvObject defPoint;
private final String privateUrlToken;
/**
* @param anAssignee The user being granted the role
* @param aRole the role being granted to the user
* @param assignmentPoint the dataverse on which the role is granted.
* @param aRequest
* @param privateUrlToken An optional token used by the Private Url feature.
*/
public AssignRoleCommand(RoleAssignee anAssignee, DataverseRole aRole, DvObject assignmentPoint, DataverseRequest aRequest, String privateUrlToken) {
super(aRequest, assignmentPoint instanceof DataFile ? assignmentPoint.getOwner() : assignmentPoint);
role = aRole;
grantee = anAssignee;
defPoint = assignmentPoint;
this.privateUrlToken = privateUrlToken;
}
@Override
public RoleAssignment execute(CommandContext ctxt) throws CommandException {
// TODO make sure the role is defined on the dataverse.
RoleAssignment roleAssignment = new RoleAssignment(role, grantee, defPoint, privateUrlToken);
return ctxt.roles().save(roleAssignment);
}
@Override
public Map<String, Set<Permission>> <API key>() {
return Collections.singletonMap("",
defPoint instanceof Dataverse ? Collections.singleton(Permission.<API key>)
: Collections.singleton(Permission.<API key>));
}
} |
// Use of this source code is governed by a BSD-style
//go:generate go run gen.go gen_index.go -output tables.go
package compact
// TODO: Remove above NOTE after:
// - verifying that tables are dropped correctly (most notably matcher tables).
import (
"strings"
"golang.org/x/text/internal/language"
)
// Tag represents a BCP 47 language tag. It is used to specify an instance of a
// specific language or locale. All language tag values are guaranteed to be
// well-formed.
type Tag struct {
language ID
locale ID
full fullTag // always a language.Tag for now.
}
const _und = 0
type fullTag interface {
IsRoot() bool
Parent() language.Tag
}
// Make a compact Tag from a fully specified internal language Tag.
func Make(t language.Tag) (tag Tag) {
if region := t.TypeForKey("rg"); len(region) == 6 && region[2:] == "zzzz" {
if r, err := language.ParseRegion(region[:2]); err == nil {
tFull := t
t, _ = t.SetTypeForKey("rg", "")
// TODO: should we not consider "va" for the language tag?
var exact1, exact2 bool
tag.language, exact1 = FromTag(t)
t.RegionID = r
tag.locale, exact2 = FromTag(t)
if !exact1 || !exact2 {
tag.full = tFull
}
return tag
}
}
lang, ok := FromTag(t)
tag.language = lang
tag.locale = lang
if !ok {
tag.full = t
}
return tag
}
// Tag returns an internal language Tag version of this tag.
func (t Tag) Tag() language.Tag {
if t.full != nil {
return t.full.(language.Tag)
}
tag := t.language.Tag()
if t.language != t.locale {
loc := t.locale.Tag()
tag, _ = tag.SetTypeForKey("rg", strings.ToLower(loc.RegionID.String())+"zzzz")
}
return tag
}
// IsCompact reports whether this tag is fully defined in terms of ID.
func (t *Tag) IsCompact() bool {
return t.full == nil
}
// MayHaveVariants reports whether a tag may have variants. If it returns false
// it is guaranteed the tag does not have variants.
func (t Tag) MayHaveVariants() bool {
return t.full != nil || int(t.language) >= len(coreTags)
}
// MayHaveExtensions reports whether a tag may have extensions. If it returns
// false it is guaranteed the tag does not have them.
func (t Tag) MayHaveExtensions() bool {
return t.full != nil ||
int(t.language) >= len(coreTags) ||
t.language != t.locale
}
// IsRoot returns true if t is equal to language "und".
func (t Tag) IsRoot() bool {
if t.full != nil {
return t.full.IsRoot()
}
return t.language == _und
}
// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a
// specific language are substituted with fields from the parent language.
// The parent for a language may change for newer versions of CLDR.
func (t Tag) Parent() Tag {
if t.full != nil {
return Make(t.full.Parent())
}
if t.language != t.locale {
// Simulate stripping -u-rg-xxxxxx
return Tag{language: t.language, locale: t.language}
}
// TODO: use parent lookup table once cycle from internal package is
// removed. Probably by internalizing the table and declaring this fast
// enough.
// lang := compactID(internal.Parent(uint16(t.language)))
lang, _ := FromTag(t.language.Tag().Parent())
return Tag{language: lang, locale: lang}
}
// returns token t and the rest of the string.
func nextToken(s string) (t, tail string) {
p := strings.Index(s[1:], "-")
if p == -1 {
return s[1:], ""
}
p++
return s[1:p], s[p:]
}
// LanguageID returns an index, where 0 <= index < NumCompactTags, for tags
// for which data exists in the text repository.The index will change over time
// and should not be stored in persistent storage. If t does not match a compact
// index, exact will be false and the compact index will be returned for the
// first match after repeatedly taking the Parent of t.
func LanguageID(t Tag) (id ID, exact bool) {
return t.language, t.full == nil
}
// TODO: make these functions and methods public once we settle on the API and
// RegionalID returns the ID for the regional variant of this tag. This index is
// used to indicate region-specific overrides, such as default currency, default
// calendar and week data, default time cycle, and default measurement system
// and unit preferences.
// For instance, the tag en-GB-u-rg-uszzzz specifies British English with US
// settings for currency, number formatting, etc. The CompactIndex for this tag
// will be that for en-GB, while the RegionalID will be the one corresponding to
// en-US.
func RegionalID(t Tag) (id ID, exact bool) {
return t.locale, t.full == nil
}
// LanguageTag returns t stripped of regional variant indicators.
// At the moment this means it is stripped of a regional and variant subtag "rg"
// and "va" in the "u" extension.
func (t Tag) LanguageTag() Tag {
if t.full == nil {
return Tag{language: t.language, locale: t.language}
}
tt := t.Tag()
tt.SetTypeForKey("rg", "")
tt.SetTypeForKey("va", "")
return Make(tt)
}
// RegionalTag returns the regional variant of the tag.
// At the moment this means that the region is set from the regional subtag
// "rg" in the "u" extension.
func (t Tag) RegionalTag() Tag {
rt := Tag{language: t.locale, locale: t.locale}
if t.full == nil {
return rt
}
b := language.Builder{}
tag := t.Tag()
// tag, _ = tag.SetTypeForKey("rg", "")
b.SetTag(t.locale.Tag())
if v := tag.Variants(); v != "" {
for _, v := range strings.Split(v, "-") {
b.AddVariant(v)
}
}
for _, e := range tag.Extensions() {
b.AddExt(e)
}
return t
}
// FromTag reports closest matching ID for an internal language Tag.
func FromTag(t language.Tag) (id ID, exact bool) {
// TODO: perhaps give more frequent tags a lower index.
// TODO: we could make the indexes stable. This will excluded some
// possibilities for optimization, so don't do this quite yet.
exact = true
b, s, r := t.Raw()
if t.HasString() {
if t.IsPrivateUse() {
// We have no entries for user-defined tags.
return 0, false
}
hasExtra := false
if t.HasVariants() {
if t.HasExtensions() {
build := language.Builder{}
build.SetTag(language.Tag{LangID: b, ScriptID: s, RegionID: r})
build.AddVariant(t.Variants())
exact = false
t = build.Make()
}
hasExtra = true
} else if _, ok := t.Extension('u'); ok {
// TODO: va may mean something else. Consider not considering it.
// Strip all but the 'va' entry.
old := t
variant := t.TypeForKey("va")
t = language.Tag{LangID: b, ScriptID: s, RegionID: r}
if variant != "" {
t, _ = t.SetTypeForKey("va", variant)
hasExtra = true
}
exact = old == t
} else {
exact = false
}
if hasExtra {
// We have some variants.
for i, s := range specialTags {
if s == t {
return ID(i + len(coreTags)), exact
}
}
exact = false
}
}
if x, ok := getCoreIndex(t); ok {
return x, exact
}
exact = false
if r != 0 && s == 0 {
// Deal with cases where an extra script is inserted for the region.
t, _ := t.Maximize()
if x, ok := getCoreIndex(t); ok {
return x, exact
}
}
for t = t.Parent(); t != root; t = t.Parent() {
// No variants specified: just compare core components.
// The key has the form lllssrrr, where l, s, and r are nibbles for
// respectively the langID, scriptID, and regionID.
if x, ok := getCoreIndex(t); ok {
return x, exact
}
}
return 0, exact
}
var root = language.Tag{} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cindy JS</title>
<script type="text/javascript" src="../../build/js/Cindy.js"></script>
<script type="text/javascript" src="../../build/js/CindyGL.js"></script>
<link rel="stylesheet" href="../../css/cindy.css">
</head>
<body style="font-family:Arial;">
<h1>CindyJS: Moiré pattern</h1>
<script id="csmove" type="text/x-cindyscript">
t = seconds()-t0;
l = exp(4+im(complex(mouse())));
x = exp(re(complex(mouse())));
colorplot([-l,-l],[l,-l], "plot", .5+.5*sin((x*(
drawimage([0,0], "plot");
</script>
<script id="csinit" type="text/x-cindyscript">
use("CindyGL");
t0 = seconds();
createimage("plot",500,500);
</script>
<div id="CSCanvas"></div>
<script type="text/javascript">
var gslp=[
];
CindyJS({canvasname:"CSCanvas",
scripts: "cs*",
geometry:gslp,
animation: {autoplay: true},
ports: [{
id: "CSCanvas",
width: 500,
height: 500,
transform: [ { visibleRect: [-1,-1,1,1] } ]
}]
});
</script>
</body>
</html> |
{% extends "screen/base.html" %}
{%block title%}{{screen.name}}{%endblock%}
{% block container %}
{% block screen_nav %}
<div class="row">
<div class="col-md-12">
<ul class="breadcrumb">
<li> {{screen_layout.screen_main_menu(pscreen, top_screens)}} </li>
<li> {{screen_layout.screen_sub_menu(pscreen, screen, sub_screens)}} </li>
{%if screen%}
<li><a href="/screen/{{screen.id}}/edit"><i class="icon-edit"></i></a></li>
<li><a href="javascript:;" class="icon-muledit"><i></i></a></li>
<li><a href="/screen/{{screen.id}}/delete" onclick="return confirm('screen?');"><i class="icon-trash"></i></a></li>
<li><a href="/screen/{{screen.id}}/clone" onclick="return confirm('screen?');"></a></li>
<li><a href="/screen/{{screen.id}}/graph"><i class="icon-plus"></i>+graph</a></li>
{%if g.legend == "on"%}
<li><a href="#" onclick="fn_query({legend: 'off'})"><i class="icon-plus"></i>legend</a></li>
{%else%}
<li><a href="#" onclick="fn_query({legend: 'on'})"><i class="icon-plus"></i>legend</a></li>
{%endif%}
<li>
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" onclick="fn_query({cols: '1'})"><small>1</small></a></li>
<li><a href="#" onclick="fn_query({cols: '2'})"><small>2</small></a></li>
<li><a href="#" onclick="fn_query({cols: '3'})"><small>3</small></a></li>
<li><a href="#" onclick="fn_query({cols: '4'})"><small>4</small></a></li>
</ul>
</div>
</li>
<li>
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" onclick="fn_query({start: -3600})"><small>1h</small></a></li>
<li><a href="#" onclick="fn_query({start: -10800})"><small>3h</small></a></li>
<li><a href="#" onclick="fn_query({start: -21600})"><small>6h</small></a></li>
<li><a href="#" onclick="fn_query({ start: -43200})"><small>12h</small></a></li>
<li><a href="#" onclick="fn_query({start: -86400})"><small>1d</small></a></li>
<li><a href="#" onclick="fn_query({start: -259200})"><small>3d</small></a></li>
<li><a href="#" onclick="fn_query({start: -604800})"><small>7d</small></a></li>
<li><a href="#" onclick="fn_query({start: -2592000})"><small>1m</small></a></li>
<li><a href="#" onclick="fn_query({start: -31536000})"><small>1y</small></a></li>
</ul>
</div>
</li>
{%endif%}
</ul>
</div>
</div>
{%endblock%}
{% block graphs %}
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
{{screen_layout.layout_block(g.cols, all_graphs)}}
</div>
</div>
</div>
{%endblock%}
<script>
$(function(){
// screen id,
window.sid = {{ sid }};
});
</script>
{%endblock%} |
package com.google.bitcoin.bouncycastle.asn1.cms;
import com.google.bitcoin.bouncycastle.asn1.ASN1SequenceParser;
import com.google.bitcoin.bouncycastle.asn1.DERInteger;
import com.google.bitcoin.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.io.IOException;
/**
* RFC 3274 - CMS Compressed Data.
* <pre>
* CompressedData ::= SEQUENCE {
* version CMSVersion,
* <API key> <API key>,
* encapContentInfo <API key>
* }
* </pre>
*/
public class <API key>
{
private DERInteger _version;
private AlgorithmIdentifier <API key>;
private ContentInfoParser _encapContentInfo;
public <API key>(
ASN1SequenceParser seq)
throws IOException
{
this._version = (DERInteger)seq.readObject();
this.<API key> = AlgorithmIdentifier.getInstance(seq.readObject().getDERObject());
this._encapContentInfo = new ContentInfoParser((ASN1SequenceParser)seq.readObject());
}
public DERInteger getVersion()
{
return _version;
}
public AlgorithmIdentifier <API key>()
{
return <API key>;
}
public ContentInfoParser getEncapContentInfo()
{
return _encapContentInfo;
}
} |
--TEST
Javascript Code: code string is not null-terminated
--DESCRIPTION
Generated by scripts/<API key>.php
DO NOT EDIT THIS FILE
--FILE
<?php
require_once __DIR__ . '/../utils/tools.php';
$bson = hex2bin('<API key>');
throws(function() use ($bson) {
var_dump(toPHP($bson));
}, 'MongoDB\Driver\Exception\<API key>');
?>
DONE===
<?php exit(0); ?>
--EXPECT
OK: Got MongoDB\Driver\Exception\<API key>
DONE=== |
Copyright (c) 2012 Ecma International. All rights reserved.
Ecma International makes this code available under the terms and conditions set
forth on http:
"Use Terms"). Any redistribution of this code must retain the above
copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-82-16.js
* @description Object.defineProperty - Update [[Configurable]] attribute of 'name' property to false successfully when [[Enumerable]] and [[Configurable]] attributes of 'name' property are true, the 'desc' is a generic descriptor which contains [[Enumerable]] attribute as true and [[Configurable]] attribute as false, 'name' property is an index data property (8.12.9 step 8)
*/
function testcase() {
var obj = {};
Object.defineProperty(obj, "0", {
value: 1001,
writable: true,
enumerable: true,
configurable: true
});
Object.defineProperty(obj, "0", {
enumerable: true,
configurable: false
});
return <API key>(obj, "0", 1001, true, true, false);
}
runTestCase(testcase); |
select l_linenumber, l_orderkey from lineitem order by l_orderkey desc; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.