answer stringlengths 15 1.25M |
|---|
from django.conf.urls import url, patterns
from django.views.generic import TemplateView
urlpatterns = patterns('librehatti.voucher.views',
url(r'^voucher_generate/','voucher_generate'),
url(r'^voucher_show/','voucher_show'),
url(r'^voucher_print/','voucher_print'),
) |
#ifndef __PNX4008_IRQS_h__
#define __PNX4008_IRQS_h__
#define NR_IRQS 96
#define SIC2_BASE_INT 64
#define CLK_SWITCH_ARM_INT 95
#define CLK_SWITCH_DSP_INT 94
#define CLK_SWITCH_AUD_INT 93
#define GPI_06_INT 92
#define GPI_05_INT 91
#define GPI_04_INT 90
#define GPI_03_INT 89
#define GPI_02_INT 88
#define GPI_01_INT 87
#define GPI_00_INT 86
#define BT_CLKREQ_INT 85
#define SPI1_DATIN_INT 84
#define U5_RX_INT 83
#define SDIO_INT_N 82
#define CAM_HS_INT 81
#define CAM_VS_INT 80
#define GPI_07_INT 79
#define DISP_SYNC_INT 78
#define DSP_INT8 77
#define U7_HCTS_INT 76
#define GPI_10_INT 75
#define GPI_09_INT 74
#define GPI_08_INT 73
#define DSP_INT7 72
#define U2_HCTS_INT 71
#define SPI2_DATIN_INT 70
#define GPIO_05_INT 69
#define GPIO_04_INT 68
#define GPIO_03_INT 67
#define GPIO_02_INT 66
#define GPIO_01_INT 65
#define GPIO_00_INT 64
#define SIC1_BASE_INT 32
#define USB_I2C_INT 63
#define USB_DEV_HP_INT 62
#define USB_DEV_LP_INT 61
#define USB_DEV_DMA_INT 60
#define USB_HOST_INT 59
#define USB_OTG_ATX_INT_N 58
#define USB_OTG_TIMER_INT 57
#define SW_INT 56
#define SPI1_INT 55
#define KEY_IRQ 54
#define DSP_M_INT 53
#define RTC_INT 52
#define I2C_1_INT 51
#define I2C_2_INT 50
#define PLL1_LOCK_INT 49
#define PLL2_LOCK_INT 48
#define PLL3_LOCK_INT 47
#define PLL4_LOCK_INT 46
#define PLL5_LOCK_INT 45
#define SPI2_INT 44
#define DSP_INT1 43
#define DSP_INT2 42
#define DSP_TDM_INT2 41
#define TS_AUX_INT 40
#define TS_IRQ 39
#define TS_P_INT 38
#define UOUT1_TO_PAD_INT 37
#define GPI_11_INT 36
#define DSP_INT4 35
#define JTAG_COMM_RX_INT 34
#define JTAG_COMM_TX_INT 33
#define DSP_INT3 32
#define MAIN_BASE_INT 0
#define SUB2_FIQ_N 31
#define SUB1_FIQ_N 30
#define JPEG_INT 29
#define DMA_INT 28
#define MSTIMER_INT 27
#define IIR1_INT 26
#define IIR2_INT 25
#define IIR7_INT 24
#define DSP_TDM_INT0 23
#define DSP_TDM_INT1 22
#define DSP_P_INT 21
#define DSP_INT0 20
#define DUM_INT 19
#define UOUT0_TO_PAD_INT 18
#define MP4_ENC_INT 17
#define MP4_DEC_INT 16
#define SD0_INT 15
#define MBX_INT 14
#define SD1_INT 13
#define MS_INT_N 12
#define FLASH_INT 11
#define IIR6_INT 10
#define IIR5_INT 9
#define IIR4_INT 8
#define IIR3_INT 7
#define WATCH_INT 6
#define HSTIMER_INT 5
#define ARCH_TIMER_IRQ HSTIMER_INT
#define CAM_INT 4
#define PRNG_INT 3
#define CRYPTO_INT 2
#define SUB2_IRQ_N 1
#define SUB1_IRQ_N 0
#define PNX4008_IRQ_TYPES \
{ \
IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_LOW, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, <API key>, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_LOW, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_LOW, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, IRQ_TYPE_LEVEL_HIGH, \
}
#define SE_PIN_BASE_INT 32
#define SE_U7_RX_INT 63
#define SE_U7_HCTS_INT 62
#define SE_BT_CLKREQ_INT 61
#define SE_U6_IRRX_INT 60
#define SE_U5_RX_INT 58
#define SE_GPI_11_INT 57
#define SE_U3_RX_INT 56
#define SE_U2_HCTS_INT 55
#define SE_U2_RX_INT 54
#define SE_U1_RX_INT 53
#define SE_DISP_SYNC_INT 52
#define SE_SDIO_INT_N 50
#define SE_MSDIO_START_INT 49
#define SE_GPI_06_INT 48
#define SE_GPI_05_INT 47
#define SE_GPI_04_INT 46
#define SE_GPI_03_INT 45
#define SE_GPI_02_INT 44
#define SE_GPI_01_INT 43
#define SE_GPI_00_INT 42
#define SE_SYSCLKEN_PIN_INT 41
#define SE_SPI1_DATAIN_INT 40
#define SE_GPI_07_INT 39
#define SE_SPI2_DATAIN_INT 38
#define SE_GPI_10_INT 37
#define SE_GPI_09_INT 36
#define SE_GPI_08_INT 35
#define SE_INT_BASE_INT 0
#define SE_TS_IRQ 31
#define SE_TS_P_INT 30
#define SE_TS_AUX_INT 29
#define <API key> 26
#define SE_MSTIMER_INT 25
#define SE_RTC_INT 24
#define SE_USB_NEED_CLK_INT 23
#define SE_USB_INT 22
#define SE_USB_I2C_INT 21
#define <API key> 20
#endif |
/*
Data in big-endian format.
*/
#define float4store(T,A) do { *(T)= ((uchar *) &A)[3];\
*((T)+1)=(char) ((uchar *) &A)[2];\
*((T)+2)=(char) ((uchar *) &A)[1];\
*((T)+3)=(char) ((uchar *) &A)[0]; } while(0)
#define float4get(V,M) do { float def_temp;\
((uchar*) &def_temp)[0]=(M)[3];\
((uchar*) &def_temp)[1]=(M)[2];\
((uchar*) &def_temp)[2]=(M)[1];\
((uchar*) &def_temp)[3]=(M)[0];\
(V)=def_temp; } while(0)
#define float8store(T,V) do { *(T)= ((uchar *) &V)[7];\
*((T)+1)=(char) ((uchar *) &V)[6];\
*((T)+2)=(char) ((uchar *) &V)[5];\
*((T)+3)=(char) ((uchar *) &V)[4];\
*((T)+4)=(char) ((uchar *) &V)[3];\
*((T)+5)=(char) ((uchar *) &V)[2];\
*((T)+6)=(char) ((uchar *) &V)[1];\
*((T)+7)=(char) ((uchar *) &V)[0]; } while(0)
#define float8get(V,M) do { double def_temp;\
((uchar*) &def_temp)[0]=(M)[7];\
((uchar*) &def_temp)[1]=(M)[6];\
((uchar*) &def_temp)[2]=(M)[5];\
((uchar*) &def_temp)[3]=(M)[4];\
((uchar*) &def_temp)[4]=(M)[3];\
((uchar*) &def_temp)[5]=(M)[2];\
((uchar*) &def_temp)[6]=(M)[1];\
((uchar*) &def_temp)[7]=(M)[0];\
(V) = def_temp; } while(0)
#define ushortget(V,M) do { V = (uint16) (((uint16) ((uchar) (M)[1]))+\
((uint16) ((uint16) (M)[0]) << 8)); } while(0)
#define shortget(V,M) do { V = (short) (((short) ((uchar) (M)[1]))+\
((short) ((short) (M)[0]) << 8)); } while(0)
#define longget(V,M) do { int32 def_temp;\
((uchar*) &def_temp)[0]=(M)[0];\
((uchar*) &def_temp)[1]=(M)[1];\
((uchar*) &def_temp)[2]=(M)[2];\
((uchar*) &def_temp)[3]=(M)[3];\
(V)=def_temp; } while(0)
#define ulongget(V,M) do { uint32 def_temp;\
((uchar*) &def_temp)[0]=(M)[0];\
((uchar*) &def_temp)[1]=(M)[1];\
((uchar*) &def_temp)[2]=(M)[2];\
((uchar*) &def_temp)[3]=(M)[3];\
(V)=def_temp; } while(0)
#define shortstore(T,A) do { uint def_temp=(uint) (A) ;\
*(((char*)T)+1)=(char)(def_temp); \
*(((char*)T)+0)=(char)(def_temp >> 8); } while(0)
#define longstore(T,A) do { *(((char*)T)+3)=((A));\
*(((char*)T)+2)=(((A) >> 8));\
*(((char*)T)+1)=(((A) >> 16));\
*(((char*)T)+0)=(((A) >> 24)); } while(0)
#define floatget(V,M) memcpy(&V, (M), sizeof(float))
/* Cast away type qualifiers (necessary as macro takes argument by value). */
#define floatstore(T,V) memcpy((T), (void*) (&V), sizeof(float))
#define doubleget(V,M) memcpy(&V, (M), sizeof(double))
/* Cast away type qualifiers (necessary as macro takes argument by value). */
#define doublestore(T,V) memcpy((T), (void*) &V, sizeof(double))
#define longlongget(V,M) memcpy(&V, (M), sizeof(ulonglong))
#define longlongstore(T,V) memcpy((T), &V, sizeof(ulonglong)) |
#ifdef __KERNEL__
#ifndef _ASM_M32R_IRQ_H
#define _ASM_M32R_IRQ_H
#if defined(CONFIG_PLAT_USRV)
#define <API key> (64)
#define <API key> (32)
#define M32700UT_IRQ_BASE 0
#define <API key> M32700UT_IRQ_BASE
#define <API key> (<API key> + <API key>)
#define NR_IRQS (<API key> + <API key>)
#elif defined(<API key>)
#define <API key> (64)
#define <API key> (32)
#define <API key> (32)
#define <API key> (32)
#define M32700UT_IRQ_BASE 0
#define <API key> (M32700UT_IRQ_BASE)
#define <API key> \
(<API key> + <API key>)
#define <API key> \
(<API key> + <API key>)
#define <API key> \
(<API key> + <API key>)
#define NR_IRQS \
(<API key> + <API key> \
+ <API key> + <API key>)
#elif defined(CONFIG_PLAT_OPSPUT)
#define OPSPUT_NUM_CPU_IRQ (64)
#define OPSPUT_NUM_PLD_IRQ (32)
#define <API key> (32)
#define <API key> (32)
#define OPSPUT_IRQ_BASE 0
#define OPSPUT_CPU_IRQ_BASE (OPSPUT_IRQ_BASE)
#define OPSPUT_PLD_IRQ_BASE \
(OPSPUT_CPU_IRQ_BASE + OPSPUT_NUM_CPU_IRQ)
#define <API key> \
(OPSPUT_PLD_IRQ_BASE + OPSPUT_NUM_PLD_IRQ)
#define <API key> \
(<API key> + <API key>)
#define NR_IRQS \
(OPSPUT_NUM_CPU_IRQ + OPSPUT_NUM_PLD_IRQ \
+ <API key> + <API key>)
#elif defined(<API key>)
#define <API key> (64)
#define <API key> (32)
#define M32104UT_IRQ_BASE 0
#define <API key> M32104UT_IRQ_BASE
#define <API key> (<API key> + <API key>)
#define NR_IRQS \
(<API key> + <API key>)
#else
#define NR_IRQS 64
#endif
#define irq_canonicalize(irq) (irq)
#endif
#endif |
/*
* Modified for uClibc by Erik Andersen <andersen@codepoet.org>
* These make no attempt to use nifty things like mmx/3dnow/etc.
* These are not inline, and will therefore not be as fast as
* modifying the headers to use inlines (and cannot therefore
* do tricky things when dealing with const memory). But they
* should (I hope!) be faster than their generic equivalents....
*
* More importantly, these should provide a good example for
* others to follow when adding arch specific optimizations.
* -Erik
*/
#include <string.h>
libc_hidden_proto(memchr)
void *memchr(const void *cs, int c, size_t count)
{
int d0;
register void * __res;
if (!count)
return NULL;
__asm__ __volatile__(
"repne\n\t"
"scasb\n\t"
"je 1f\n\t"
"movl $1,%0\n"
"1:\tdecl %0"
:"=D" (__res), "=&c" (d0) : "a" (c),"0" (cs),"1" (count));
return __res;
}
libc_hidden_def(memchr) |
#!/bin/bash
test_info()
{
cat <<EOF
Verify that an interface is deleted when all IPs on it are deleted.
EOF
}
. "${TEST_SCRIPTS_DIR}/integration.bash"
ctdb_test_init "$@"
set -e
cluster_is_healthy
# Reset configuration
<API key>
echo "Getting public IPs information..."
try_command_on_node -v any "$CTDB ip -v all -X | tail -n +2"
ip_info="$out"
# Select the first node and find out its interfaces
test_node=$(awk -F'|' 'NR == 1 { print $3}' <<<"$ip_info")
ifaces=$(awk -F'|' -v tn=$test_node '$3 == tn { print $6 }' <<<"$ip_info" | sed 's@, @ @g' | xargs -n 1 | sort -u)
echo "Selected test node ${test_node} with interfaces: ${ifaces}"
# Delete all IPs on each interface... deleting IPs from one interface
# can cause other interfaces to disappear, so we need to be careful...
for i in $ifaces ; do
try_command_on_node $test_node "$CTDB ifaces -X"
info=$(awk -F'|' -v iface="$i" '$2 == iface { print $0 }' <<<"$out")
if [ -z "$info" ] ; then
echo "Interface ${i} missing... assuming already deleted!"
continue
fi
echo "Deleting IPs on interface ${i}, with this information:"
echo " $info"
try_command_on_node $test_node "$CTDB ip -v -X | tail -n +2"
awk -F'|' -v i="$i" \
'$6 == i { print $2 }' <<<"$out" |
while read ip ; do
echo " $ip"
try_command_on_node $test_node "$CTDB delip $ip"
done
try_command_on_node $test_node "$CTDB ipreallocate"
try_command_on_node $test_node "$CTDB ifaces -X"
info=$(awk -F'|' -v iface="$i" '$2 == iface { print $0 }' <<<"$out")
if [ -z "$info" ] ; then
echo "GOOD: Interface ${i} has been garbage collected"
else
echo "BAD: Interface ${i} still exists"
echo "$out"
exit 1
fi
done |
#include "curl_setup.h"
#include "strtoofft.h"
#include "strequal.h"
#include "rawstr.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#ifndef HAVE_SOCKET
#error "We can't compile without socket() support!"
#endif
#include "urldata.h"
#include <curl/curl.h>
#include "netrc.h"
#include "content_encoding.h"
#include "hostip.h"
#include "transfer.h"
#include "sendf.h"
#include "speedcheck.h"
#include "progress.h"
#include "http.h"
#include "url.h"
#include "getinfo.h"
#include "vtls/vtls.h"
#include "http_digest.h"
#include "curl_ntlm.h"
#include "http_negotiate.h"
#include "share.h"
#include "select.h"
#include "multiif.h"
#include "connect.h"
#include "non-ascii.h"
#include "curl_printf.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/*
* This function will call the read callback to fill our buffer with data
* to upload.
*/
CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
{
struct SessionHandle *data = conn->data;
size_t buffersize = (size_t)bytes;
int nread;
#ifdef <API key>
bool <API key> = FALSE;
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
const struct HTTP *http = data->req.protop;
if(http->sending == HTTPSEND_REQUEST)
/* We're sending the HTTP request headers, not the data.
Remember that so we don't re-translate them into garbage. */
<API key> = TRUE;
}
#endif
if(data->req.upload_chunky) {
/* if chunked Transfer-Encoding */
buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
}
/* this function returns a size_t, so we typecast to int to prevent warnings
with picky compilers */
nread = (int)data->set.fread_func(data->req.upload_fromhere, 1,
buffersize, data->set.in);
if(nread == CURL_READFUNC_ABORT) {
failf(data, "operation aborted by callback");
*nreadp = 0;
return <API key>;
}
else if(nread == CURL_READFUNC_PAUSE) {
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* protocols that work without network cannot be paused. This is
actually only FILE:// just now, and it can't pause since the transfer
isn't done using the "normal" procedure. */
failf(data, "Read callback asked for PAUSE when not supported!");
return CURLE_READ_ERROR;
}
else {
struct SingleRequest *k = &data->req;
/* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
if(data->req.upload_chunky) {
/* Back out the preallocation done above */
data->req.upload_fromhere -= (8 + 2);
}
*nreadp = 0;
}
return CURLE_OK; /* nothing was read */
}
else if((size_t)nread > buffersize) {
/* the read function returned a too large value */
*nreadp = 0;
failf(data, "read function returned funny value");
return CURLE_READ_ERROR;
}
if(!data->req.forbidchunk && data->req.upload_chunky) {
/* if chunked Transfer-Encoding
* build chunk:
*
* <HEX SIZE> CRLF
* <DATA> CRLF
*/
/* On non-ASCII platforms the <DATA> may or may not be
translated based on set.prefer_ascii while the protocol
portion must always be translated to the network encoding.
To further complicate matters, line end conversion might be
done later on, so we need to prevent CRLFs from becoming
CRCRLFs if that's the case. To do this we use bare LFs
here, knowing they'll become CRLFs later on.
*/
char hexbuffer[11];
const char *endofline_native;
const char *endofline_network;
int hexlen;
if(
#ifdef <API key>
(data->set.prefer_ascii) ||
#endif
(data->set.crlf)) {
/* \n will become \r\n later on */
endofline_native = "\n";
endofline_network = "\x0a";
}
else {
endofline_native = "\r\n";
endofline_network = "\x0d\x0a";
}
hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
"%x%s", nread, endofline_native);
/* move buffer pointer */
data->req.upload_fromhere -= hexlen;
nread += hexlen;
/* copy the prefix to the buffer, leaving out the NUL */
memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
/* always append ASCII CRLF to the data */
memcpy(data->req.upload_fromhere + nread,
endofline_network,
strlen(endofline_network));
#ifdef <API key>
CURLcode result;
int length;
if(data->set.prefer_ascii) {
/* translate the protocol and data */
length = nread;
}
else {
/* just translate the protocol portion */
length = strlen(hexbuffer);
}
result = <API key>(data, data->req.upload_fromhere, length);
/* <API key> calls failf if unsuccessful */
if(result)
return result;
#endif /* <API key> */
if((nread - hexlen) == 0)
/* mark this as done once this chunk is transferred */
data->req.upload_done = TRUE;
nread+=(int)strlen(endofline_native); /* for the added end of line */
}
#ifdef <API key>
else if((data->set.prefer_ascii) && (!<API key>)) {
CURLcode result;
result = <API key>(data, data->req.upload_fromhere, nread);
/* <API key> calls failf if unsuccessful */
if(result)
return result;
}
#endif /* <API key> */
*nreadp = nread;
return CURLE_OK;
}
/*
* Curl_readrewind() rewinds the read stream. This is typically used for HTTP
* POST/PUT with multi-pass authentication when a sending was denied and a
* resend is necessary.
*/
CURLcode Curl_readrewind(struct connectdata *conn)
{
struct SessionHandle *data = conn->data;
conn->bits.rewindaftersend = FALSE; /* we rewind now */
/* explicitly switch off sending data on this connection now since we are
about to restart a new transfer and thus we want to avoid inadvertently
sending more data on the existing connection until the next transfer
starts */
data->req.keepon &= ~KEEP_SEND;
/* We have sent away data. If not using CURLOPT_POSTFIELDS or
CURLOPT_HTTPPOST, call app to rewind
*/
if(data->set.postfields ||
(data->set.httpreq == HTTPREQ_POST_FORM))
; /* do nothing */
else {
if(data->set.seek_func) {
int err;
err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
if(err) {
failf(data, "seek callback returned error %d", (int)err);
return <API key>;
}
}
else if(data->set.ioctl_func) {
curlioerr err;
err = (data->set.ioctl_func)(data, <API key>,
data->set.ioctl_client);
infof(data, "the ioctl callback returned %d\n", (int)err);
if(err) {
/* FIXME: convert to a human readable error message */
failf(data, "ioctl callback returned error %d", (int)err);
return <API key>;
}
}
else {
/* If no <API key> is used, we know that we operate on a
given FILE * stream and we can actually attempt to rewind that
ourselves with fseek() */
if(data->set.fread_func == (curl_read_callback)fread) {
if(-1 != fseek(data->set.in, 0, SEEK_SET))
/* successful rewind */
return CURLE_OK;
}
/* no callback set or failure above, makes us fail at once */
failf(data, "necessary data rewind wasn't possible");
return <API key>;
}
}
return CURLE_OK;
}
static int data_pending(const struct connectdata *conn)
{
/* in the case of libssh2, we can never be really sure that we have emptied
its internal buffers so we MUST always try until we get EAGAIN back */
return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
#if defined(USE_NGHTTP2)
<API key>(conn, FIRSTSOCKET) ||
/* For HTTP/2, we may read up everything including responde body
with header fields in <API key>. If no
content-length is provided, curl waits for the connection
close, which we emulate it using conn->proto.httpc.closed =
TRUE. The thing is if we read everything, then http2_recv won't
be called and we cannot signal the HTTP/2 stream has closed. As
a workaround, we return nonzero here to call http2_recv. */
((conn->handler->protocol&PROTO_FAMILY_HTTP) && conn->httpversion == 20);
#else
<API key>(conn, FIRSTSOCKET);
#endif
}
static void read_rewind(struct connectdata *conn,
size_t thismuch)
{
DEBUGASSERT(conn->read_pos >= thismuch);
conn->read_pos -= thismuch;
conn->bits.stream_was_rewound = TRUE;
#ifdef DEBUGBUILD
{
char buf[512 + 1];
size_t show;
show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
if(conn->master_buffer) {
memcpy(buf, conn->master_buffer + conn->read_pos, show);
buf[show] = '\0';
}
else {
buf[0] = '\0';
}
DEBUGF(infof(conn->data,
"Buffer after stream rewind (read_pos = %zu): [%s]\n",
conn->read_pos, buf));
}
#endif
}
/*
* Check to see if <API key> was met by comparing the time of the
* remote document with the time provided by CURLOPT_TIMEVAL
*/
bool <API key>(struct SessionHandle *data, time_t timeofdoc)
{
if((timeofdoc == 0) || (data->set.timevalue == 0))
return TRUE;
switch(data->set.timecondition) {
case <API key>:
default:
if(timeofdoc <= data->set.timevalue) {
infof(data,
"The requested document is not new enough\n");
data->info.timecond = TRUE;
return FALSE;
}
break;
case <API key>:
if(timeofdoc >= data->set.timevalue) {
infof(data,
"The requested document is not old enough\n");
data->info.timecond = TRUE;
return FALSE;
}
break;
}
return TRUE;
}
/*
* Go ahead and do a read if we have a readable socket or if
* the stream was rewound (in which case we have data in a
* buffer)
*/
static CURLcode readwrite_data(struct SessionHandle *data,
struct connectdata *conn,
struct SingleRequest *k,
int *didwhat, bool *done)
{
CURLcode result = CURLE_OK;
ssize_t nread; /* number of bytes read */
size_t excess = 0; /* excess bytes read */
bool is_empty_data = FALSE;
bool readmore = FALSE; /* used by RTP to signal for more data */
*done = FALSE;
/* This is where we loop until we have read everything there is to
read or we get a CURLE_AGAIN */
do {
size_t buffersize = data->set.buffer_size?
data->set.buffer_size : BUFSIZE;
size_t bytestoread = buffersize;
if(k->size != -1 && !k->header) {
/* make sure we don't read "too much" if we can help it since we
might be pipelining and then someone else might want to read what
follows! */
curl_off_t totalleft = k->size - k->bytecount;
if(totalleft < (curl_off_t)bytestoread)
bytestoread = (size_t)totalleft;
}
if(bytestoread) {
/* receive data from the network! */
result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
/* read would've blocked */
if(CURLE_AGAIN == result)
break; /* get out of loop */
if(result>0)
return result;
}
else {
/* read nothing but since we wanted nothing we consider this an OK
situation to proceed from */
DEBUGF(infof(data, "readwrite_data: we're done!\n"));
nread = 0;
}
if((k->bytecount == 0) && (k->writebytecount == 0)) {
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
if(k->exp100 > EXP100_SEND_DATA)
/* set time stamp to compare with when waiting for the 100 */
k->start100 = Curl_tvnow();
}
*didwhat |= KEEP_RECV;
/* indicates data of zero size, i.e. empty file */
is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
/* NUL terminate, allowing string ops to be used */
if(0 < nread || is_empty_data) {
k->buf[nread] = 0;
}
else if(0 >= nread) {
/* if we receive 0 or less here, the server closed the connection
and we bail out from this! */
DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
k->keepon &= ~KEEP_RECV;
break;
}
/* Default buffer to use when we write the buffer, it may be changed
in the flow below before the actual storing is done. */
k->str = k->buf;
if(conn->handler->readwrite) {
result = conn->handler->readwrite(data, conn, &nread, &readmore);
if(result)
return result;
if(readmore)
break;
}
#ifndef CURL_DISABLE_HTTP
/* Since this is a two-state thing, we check if we are parsing
headers at the moment or not. */
if(k->header) {
/* we are in <API key> */
bool stop_reading = FALSE;
result = <API key>(data, conn, &nread, &stop_reading);
if(result)
return result;
if(conn->handler->readwrite &&
(k->maxdownload <= 0 && nread > 0)) {
result = conn->handler->readwrite(data, conn, &nread, &readmore);
if(result)
return result;
if(readmore)
break;
}
if(stop_reading) {
/* We've stopped dealing with input, get out of the do-while loop */
if(nread > 0) {
if(<API key>(conn->data->multi, CURLPIPE_HTTP1)) {
infof(data,
"Rewinding stream by : %zd"
" bytes on url %s (zero-length body)\n",
nread, data->state.path);
read_rewind(conn, (size_t)nread);
}
else {
infof(data,
"Excess found in a non pipelined read:"
" excess = %zd"
" url = %s (zero-length body)\n",
nread, data->state.path);
}
}
break;
}
}
#endif /* CURL_DISABLE_HTTP */
/* This is not an 'else if' since it may be a rest from the header
parsing, where the beginning of the buffer is headers and the end
is non-headers. */
if(k->str && !k->header && (nread > 0 || is_empty_data)) {
#ifndef CURL_DISABLE_HTTP
if(0 == k->bodywrites && !is_empty_data) {
/* These checks are only made the first time we are about to
write a piece of the body */
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
/* HTTP-only checks */
if(data->req.newurl) {
if(conn->bits.close) {
/* Abort after the headers if "follow Location" is set
and we're set to close anyway. */
k->keepon &= ~KEEP_RECV;
*done = TRUE;
return CURLE_OK;
}
/* We have a new url to load, but since we want to be able
to re-use this connection properly, we read the full
response in "ignore more" */
k->ignorebody = TRUE;
infof(data, "Ignoring the response-body\n");
}
if(data->state.resume_from && !k->content_range &&
(data->set.httpreq==HTTPREQ_GET) &&
!k->ignorebody) {
if(k->size == data->state.resume_from) {
/* The resume point is at the end of file, consider this fine
even if it doesn't allow resume from here. */
infof(data, "The entire document is already downloaded");
connclose(conn, "already downloaded");
/* Abort download */
k->keepon &= ~KEEP_RECV;
*done = TRUE;
return CURLE_OK;
}
/* we wanted to resume a download, although the server doesn't
* seem to support this and we did this with a GET (if it
* wasn't a GET we did a POST or PUT resume) */
failf(data, "HTTP server doesn't seem to support "
"byte ranges. Cannot resume.");
return CURLE_RANGE_ERROR;
}
if(data->set.timecondition && !data->state.range) {
/* A time condition has been set AND no ranges have been
requested. This seems to be what chapter 13.3.4 of
RFC 2616 defines to be the correct action for a
HTTP/1.1 client */
if(!<API key>(data, k->timeofdoc)) {
*done = TRUE;
/* We're simulating a http 304 from server so we return
what should have been returned from the server */
data->info.httpcode = 304;
infof(data, "Simulate a HTTP 304 response!\n");
/* we abort the transfer before it is completed == we ruin the
re-use ability. Close the connection */
connclose(conn, "Simulated 304 handling");
return CURLE_OK;
}
} /* we have a time condition */
} /* this is HTTP or RTSP */
} /* this is the first time we write a body part */
#endif /* CURL_DISABLE_HTTP */
k->bodywrites++;
/* pass data to the debug function before it gets "dechunked" */
if(data->set.verbose) {
if(k->badheader) {
Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
(size_t)k->hbuflen, conn);
if(k->badheader == HEADER_PARTHEADER)
Curl_debug(data, CURLINFO_DATA_IN,
k->str, (size_t)nread, conn);
}
else
Curl_debug(data, CURLINFO_DATA_IN,
k->str, (size_t)nread, conn);
}
#ifndef CURL_DISABLE_HTTP
if(k->chunk) {
/*
* Here comes a chunked transfer flying and we need to decode this
* properly. While the name says read, this function both reads
* and writes away the data. The returned 'nread' holds the number
* of actual data it wrote to the client.
*/
CHUNKcode res =
Curl_httpchunk_read(conn, k->str, nread, &nread);
if(CHUNKE_OK < res) {
if(CHUNKE_WRITE_ERROR == res) {
failf(data, "Failed writing data");
return CURLE_WRITE_ERROR;
}
failf(data, "%s in chunked-encoding", <API key>(res));
return CURLE_RECV_ERROR;
}
else if(CHUNKE_STOP == res) {
size_t dataleft;
/* we're done reading chunks! */
k->keepon &= ~KEEP_RECV; /* read no more */
/* There are now possibly N number of bytes at the end of the
str buffer that weren't written to the client.
We DO care about this data if we are pipelining.
Push it back to be read on the next pass. */
dataleft = conn->chunk.dataleft;
if(dataleft != 0) {
infof(conn->data, "Leftovers after chunking: %zu bytes\n",
dataleft);
if(<API key>(conn->data->multi, CURLPIPE_HTTP1)) {
/* only attempt the rewind if we truly are pipelining */
infof(conn->data, "Rewinding %zu bytes\n",dataleft);
read_rewind(conn, dataleft);
}
}
}
/* If it returned OK, we just keep going */
}
#endif /* CURL_DISABLE_HTTP */
/* Account for body content stored in the header buffer */
if(k->badheader && !k->ignorebody) {
DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
k->hbuflen));
k->bytecount += k->hbuflen;
}
if((-1 != k->maxdownload) &&
(k->bytecount + nread >= k->maxdownload)) {
excess = (size_t)(k->bytecount + nread - k->maxdownload);
if(excess > 0 && !k->ignorebody) {
if(<API key>(conn->data->multi, CURLPIPE_HTTP1)) {
/* The 'excess' amount below can't be more than BUFSIZE which
always will fit in a size_t */
infof(data,
"Rewinding stream by : %zu"
" bytes on url %s (size = %" <API key>
", maxdownload = %" <API key>
", bytecount = %" <API key> ", nread = %zd)\n",
excess, data->state.path,
k->size, k->maxdownload, k->bytecount, nread);
read_rewind(conn, excess);
}
else {
infof(data,
"Excess found in a non pipelined read:"
" excess = %zu"
", size = %" <API key>
", maxdownload = %" <API key>
", bytecount = %" <API key> "\n",
excess, k->size, k->maxdownload, k->bytecount);
}
}
nread = (ssize_t) (k->maxdownload - k->bytecount);
if(nread < 0 ) /* this should be unusual */
nread = 0;
k->keepon &= ~KEEP_RECV; /* we're done reading */
}
k->bytecount += nread;
<API key>(data, k->bytecount);
if(!k->chunk && (nread || k->badheader || is_empty_data)) {
/* If this is chunky transfer, it was already written */
if(k->badheader && !k->ignorebody) {
/* we parsed a piece of data wrongly assuming it was a header
and now we output it as body instead */
/* Don't let excess data pollute body writes */
if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
result = Curl_client_write(conn, CLIENTWRITE_BODY,
data->state.headerbuff,
k->hbuflen);
else
result = Curl_client_write(conn, CLIENTWRITE_BODY,
data->state.headerbuff,
(size_t)k->maxdownload);
if(result)
return result;
}
if(k->badheader < HEADER_ALLBAD) {
/* This switch handles various content encodings. If there's an
error here, be sure to check over the almost identical code
in http_chunks.c.
Make sure that <API key> contains all the
encodings handled here. */
#ifdef HAVE_LIBZ
switch (conn->data->set.http_ce_skip ?
IDENTITY : k->auto_decoding) {
case IDENTITY:
#endif
/* This is the default when the server sends no
Content-Encoding header. See Curl_readwrite_init; the
memset() call initializes k->auto_decoding to zero. */
if(!k->ignorebody) {
#ifndef CURL_DISABLE_POP3
if(conn->handler->protocol&PROTO_FAMILY_POP3)
result = Curl_pop3_write(conn, k->str, nread);
else
#endif /* CURL_DISABLE_POP3 */
result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
nread);
}
#ifdef HAVE_LIBZ
break;
case DEFLATE:
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
if(!k->ignorebody)
result = <API key>(conn, k, nread);
break;
case GZIP:
/* Assume CLIENTWRITE_BODY; headers are not encoded. */
if(!k->ignorebody)
result = <API key>(conn, k, nread);
break;
case COMPRESS:
default:
failf (data, "Unrecognized content encoding type. "
"libcurl understands `identity', `deflate' and `gzip' "
"content encodings.");
result = <API key>;
break;
}
#endif
}
k->badheader = HEADER_NORMAL; /* taken care of now */
if(result)
return result;
}
} /* if(! header and data to read ) */
if(conn->handler->readwrite &&
(excess > 0 && !conn->bits.stream_was_rewound)) {
/* Parse the excess data */
k->str += nread;
nread = (ssize_t)excess;
result = conn->handler->readwrite(data, conn, &nread, &readmore);
if(result)
return result;
if(readmore)
k->keepon |= KEEP_RECV; /* we're not done reading */
break;
}
if(is_empty_data) {
/* if we received nothing, the server closed the connection and we
are done */
k->keepon &= ~KEEP_RECV;
}
} while(data_pending(conn));
if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
conn->bits.close ) {
/* When we've read the entire thing and the close bit is set, the server
may now close the connection. If there's now any kind of sending going
on from our side, we need to stop that immediately. */
infof(data, "we are done reading and this is set to close, stop send\n");
k->keepon &= ~KEEP_SEND; /* no writing anymore either */
}
return CURLE_OK;
}
/*
* Send data to upload to the server, when the socket is writable.
*/
static CURLcode readwrite_upload(struct SessionHandle *data,
struct connectdata *conn,
struct SingleRequest *k,
int *didwhat)
{
ssize_t i, si;
ssize_t bytes_written;
CURLcode result;
ssize_t nread; /* number of bytes read */
bool <API key> = FALSE;
if((k->bytecount == 0) && (k->writebytecount == 0))
Curl_pgrsTime(data, TIMER_STARTTRANSFER);
*didwhat |= KEEP_SEND;
do {
/* only read more data if there's no upload data already
present in the upload buffer */
if(0 == data->req.upload_present) {
/* init the "upload from here" pointer */
data->req.upload_fromhere = k->uploadbuf;
if(!k->upload_done) {
/* HTTP pollution, this should be written nicer to become more
protocol agnostic. */
int fillcount;
struct HTTP *http = data->req.protop;
if((k->exp100 == <API key>) &&
(http->sending == HTTPSEND_BODY)) {
/* If this call is to send body data, we must take some action:
We have sent off the full HTTP 1.1 request, and we shall now
go into the Expect: 100 state and await such a header */
k->exp100 = <API key>; /* wait for the header */
k->keepon &= ~KEEP_SEND; /* disable writing */
k->start100 = Curl_tvnow(); /* timeout count starts now */
*didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
/* set a timeout for the multi interface */
Curl_expire(data, data->set.expect_100_timeout);
break;
}
if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
if(http->sending == HTTPSEND_REQUEST)
/* We're sending the HTTP request headers, not the data.
Remember that so we don't change the line endings. */
<API key> = TRUE;
else
<API key> = FALSE;
}
result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
if(result)
return result;
nread = (ssize_t)fillcount;
}
else
nread = 0; /* we're done uploading/reading */
if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
/* this is a paused transfer */
break;
}
else if(nread<=0) {
/* done */
k->keepon &= ~KEEP_SEND; /* we're done writing */
if(conn->bits.rewindaftersend) {
result = Curl_readrewind(conn);
if(result)
return result;
}
break;
}
/* store number of bytes available for upload */
data->req.upload_present = nread;
/* convert LF to CRLF if so asked */
if((!<API key>) && (
#ifdef <API key>
/* always convert if we're FTPing in ASCII mode */
(data->set.prefer_ascii) ||
#endif
(data->set.crlf))) {
/* Do we need to allocate a scratch buffer? */
if(!data->state.scratch) {
data->state.scratch = malloc(2 * BUFSIZE);
if(!data->state.scratch) {
failf(data, "Failed to alloc scratch buffer!");
return CURLE_OUT_OF_MEMORY;
}
}
/*
* ASCII/EBCDIC Note: This is presumably a text (not binary)
* transfer so the data should already be in ASCII.
* That means the hex values for ASCII CR (0x0d) & LF (0x0a)
* must be used instead of the escape sequences \r & \n.
*/
for(i = 0, si = 0; i < nread; i++, si++) {
if(data->req.upload_fromhere[i] == 0x0a) {
data->state.scratch[si++] = 0x0d;
data->state.scratch[si] = 0x0a;
if(!data->set.crlf) {
/* we're here only because FTP is in ASCII mode...
bump infilesize for the LF we just added */
data->state.infilesize++;
}
}
else
data->state.scratch[si] = data->req.upload_fromhere[i];
}
if(si != nread) {
/* only perform the special operation if we really did replace
anything */
nread = si;
/* upload from the new (replaced) buffer instead */
data->req.upload_fromhere = data->state.scratch;
/* set the new amount too */
data->req.upload_present = nread;
}
}
#ifndef CURL_DISABLE_SMTP
if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
result = <API key>(conn, nread);
if(result)
return result;
}
#endif /* CURL_DISABLE_SMTP */
} /* if 0 == data->req.upload_present */
else {
/* We have a partial buffer left from a previous "round". Use
that instead of reading more data */
}
/* write to socket (send away data) */
result = Curl_write(conn,
conn->writesockfd, /* socket to send to */
data->req.upload_fromhere, /* buffer pointer */
data->req.upload_present, /* buffer size */
&bytes_written); /* actually sent */
if(result)
return result;
if(data->set.verbose)
/* show the data before we change the pointer upload_fromhere */
Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
(size_t)bytes_written, conn);
k->writebytecount += bytes_written;
if(k->writebytecount == data->state.infilesize) {
/* we have sent all data we were supposed to */
k->upload_done = TRUE;
infof(data, "We are completely uploaded and fine\n");
}
if(data->req.upload_present != bytes_written) {
/* we only wrote a part of the buffer (if anything), deal with it! */
/* store the amount of bytes left in the buffer to write */
data->req.upload_present -= bytes_written;
/* advance the pointer where to find the buffer when the next send
is to happen */
data->req.upload_fromhere += bytes_written;
}
else {
/* we've uploaded that buffer now */
data->req.upload_fromhere = k->uploadbuf;
data->req.upload_present = 0; /* no more bytes left */
if(k->upload_done) {
/* switch off writing, we're done! */
k->keepon &= ~KEEP_SEND; /* we're done writing */
}
}
<API key>(data, k->writebytecount);
} WHILE_FALSE; /* just to break out from! */
return CURLE_OK;
}
/*
* Curl_readwrite() is the low-level function to be called when data is to
* be read and written to/from the connection.
*/
CURLcode Curl_readwrite(struct connectdata *conn,
struct SessionHandle *data,
bool *done)
{
struct SingleRequest *k = &data->req;
CURLcode result;
int didwhat=0;
curl_socket_t fd_read;
curl_socket_t fd_write;
int select_res = conn->cselect_bits;
conn->cselect_bits = 0;
/* only use the proper socket if the *_HOLD bit is not set simultaneously as
then we are in rate limiting state in that transfer direction */
if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
fd_read = conn->sockfd;
else
fd_read = CURL_SOCKET_BAD;
if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
fd_write = conn->writesockfd;
else
fd_write = CURL_SOCKET_BAD;
if(conn->data->state.drain) {
select_res |= CURL_CSELECT_IN;
DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data\n"));
}
if(!select_res) /* Call for select()/poll() only, if read/write/error
status is not known. */
select_res = Curl_socket_ready(fd_read, fd_write, 0);
if(select_res == CURL_CSELECT_ERR) {
failf(data, "select/poll returned error");
return CURLE_SEND_ERROR;
}
/* We go ahead and do a read if we have a readable socket or if
the stream was rewound (in which case we have data in a
buffer) */
if((k->keepon & KEEP_RECV) &&
((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
result = readwrite_data(data, conn, k, &didwhat, done);
if(result || *done)
return result;
}
/* If we still have writing to do, we check if we have a writable socket. */
if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
/* write */
result = readwrite_upload(data, conn, k, &didwhat);
if(result)
return result;
}
k->now = Curl_tvnow();
if(didwhat) {
/* Update read/write counters */
if(k->bytecountp)
*k->bytecountp = k->bytecount; /* read count */
if(k->writebytecountp)
*k->writebytecountp = k->writebytecount; /* write count */
}
else {
/* no read no write, this is a timeout? */
if(k->exp100 == <API key>) {
/* This should allow some time for the header to arrive, but only a
very short time as otherwise it'll be too much wasted time too
often. */
/* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
Therefore, when a client sends this header field to an origin server
(possibly via a proxy) from which it has never seen a 100 (Continue)
status, the client SHOULD NOT wait for an indefinite period before
sending the request body.
*/
long ms = Curl_tvdiff(k->now, k->start100);
if(ms >= data->set.expect_100_timeout) {
/* we've waited long enough, continue anyway */
k->exp100 = EXP100_SEND_DATA;
k->keepon |= KEEP_SEND;
infof(data, "Done waiting for 100-continue\n");
}
}
}
if(Curl_pgrsUpdate(conn))
result = <API key>;
else
result = Curl_speedcheck(data, k->now);
if(result)
return result;
if(k->keepon) {
if(0 > Curl_timeleft(data, &k->now, FALSE)) {
if(k->size != -1) {
failf(data, "Operation timed out after %ld milliseconds with %"
<API key> " out of %"
<API key> " bytes received",
Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount,
k->size);
}
else {
failf(data, "Operation timed out after %ld milliseconds with %"
<API key> " bytes received",
Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount);
}
return <API key>;
}
}
else {
/*
* The transfer has been performed. Just make some general checks before
* returning.
*/
if(!(data->set.opt_no_body) && (k->size != -1) &&
(k->bytecount != k->size) &&
#ifdef <API key>
/* Most FTP servers don't adjust their file SIZE response for CRLFs,
so we'll check to see if the discrepancy can be explained
by the number of CRLFs we've changed to LFs.
*/
(k->bytecount != (k->size + data->state.crlf_conversions)) &&
#endif /* <API key> */
!data->req.newurl) {
failf(data, "transfer closed with %" <API key>
" bytes remaining to read",
k->size - k->bytecount);
return CURLE_PARTIAL_FILE;
}
else if(!(data->set.opt_no_body) &&
k->chunk &&
(conn->chunk.state != CHUNK_STOP)) {
/*
* In chunked mode, return an error if the connection is closed prior to
* the empty (terminating) chunk is read.
*
* The condition above used to check for
* conn->proto.http->chunk.datasize != 0 which is true after reading
* *any* chunk, not just the empty chunk.
*
*/
failf(data, "transfer closed with outstanding read data remaining");
return CURLE_PARTIAL_FILE;
}
if(Curl_pgrsUpdate(conn))
return <API key>;
}
/* Now update the "done" boolean we return */
*done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
return CURLE_OK;
}
/*
* Curl_single_getsock() gets called by the multi interface code when the app
* has requested to get the sockets for the current connection. This function
* will then be called once for every connection that the multi interface
* keeps track of. This function will only be called for connections that are
* in the proper state to have this information available.
*/
int Curl_single_getsock(const struct connectdata *conn,
curl_socket_t *sock, /* points to numsocks number
of sockets */
int numsocks)
{
const struct SessionHandle *data = conn->data;
int bitmap = GETSOCK_BLANK;
unsigned sockindex = 0;
if(conn->handler->perform_getsock)
return conn->handler->perform_getsock(conn, sock, numsocks);
if(numsocks < 2)
/* simple check but we might need two slots */
return GETSOCK_BLANK;
/* don't include HOLD and PAUSE connections */
if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
bitmap |= GETSOCK_READSOCK(sockindex);
sock[sockindex] = conn->sockfd;
}
/* don't include HOLD and PAUSE connections */
if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
if((conn->sockfd != conn->writesockfd) ||
bitmap == GETSOCK_BLANK) {
/* only if they are not the same socket and we have a readable
one, we increase index */
if(bitmap != GETSOCK_BLANK)
sockindex++; /* increase index if we need two entries */
DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
sock[sockindex] = conn->writesockfd;
}
bitmap |= GETSOCK_WRITESOCK(sockindex);
}
return bitmap;
}
/*
* Determine optimum sleep time based on configured rate, current rate,
* and packet size.
* Returns value in milliseconds.
*
* The basic idea is to adjust the desired rate up/down in this method
* based on whether we are running too slow or too fast. Then, calculate
* how many milliseconds to wait for the next packet to achieve this new
* rate.
*/
long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
int pkt_size)
{
curl_off_t min_sleep = 0;
curl_off_t rv = 0;
if(rate_bps == 0)
return 0;
/* If running faster than about .1% of the desired speed, slow
* us down a bit. Use shift instead of division as the 0.1%
* cutoff is arbitrary anyway.
*/
if(cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
/* running too fast, decrease target rate by 1/64th of rate */
rate_bps -= rate_bps >> 6;
min_sleep = 1;
}
else if(cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
/* running too slow, increase target rate by 1/64th of rate */
rate_bps += rate_bps >> 6;
}
/* Determine number of milliseconds to wait until we do
* the next packet at the adjusted rate. We should wait
* longer when using larger packets, for instance.
*/
rv = ((curl_off_t)(pkt_size * 1000) / rate_bps);
/* Catch rounding errors and always slow down at least 1ms if
* we are running too fast.
*/
if(rv < min_sleep)
rv = min_sleep;
/* Bound value to fit in 'long' on 32-bit platform. That's
* plenty long enough anyway!
*/
if(rv > 0x7fffffff)
rv = 0x7fffffff;
return (long)rv;
}
/*
* Curl_pretransfer() is called immediately before a transfer starts.
*/
CURLcode Curl_pretransfer(struct SessionHandle *data)
{
CURLcode result;
if(!data->change.url) {
/* we can't do anything without URL */
failf(data, "No URL set!");
return CURLE_URL_MALFORMAT;
}
/* Init the SSL session ID cache here. We do it here since we want to do it
after the *_setopt() calls (that could specify the size of the cache) but
before any transfer takes place. */
result = <API key>(data, data->set.ssl.max_ssl_sessions);
if(result)
return result;
data->set.followlocation=0; /* reset the location-follow counter */
data->state.this_is_a_follow = FALSE; /* reset this */
data->state.errorbuf = FALSE; /* no error has occurred */
data->state.httpversion = 0; /* don't assume any particular server version */
data->state.authproblem = FALSE;
data->state.authhost.want = data->set.httpauth;
data->state.authproxy.want = data->set.proxyauth;
Curl_safefree(data->info.wouldredirect);
data->info.wouldredirect = NULL;
/* If there is a list of cookie files to read, do it now! */
if(data->change.cookielist)
<API key>(data);
/* If there is a list of host pairs to deal with */
if(data->change.resolve)
result = Curl_loadhostpairs(data);
if(!result) {
/* Allow data->set.use_port to set which port to use. This needs to be
* disabled for example when we follow Location: headers to URLs using
* different ports! */
data->state.allow_port = TRUE;
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
if(!data->set.no_signal)
data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
#endif
Curl_initinfo(data); /* reset session-specific information "variables" */
<API key>(data);
Curl_pgrsStartNow(data);
if(data->set.timeout)
Curl_expire(data, data->set.timeout);
if(data->set.connecttimeout)
Curl_expire(data, data->set.connecttimeout);
/* In case the handle is re-used and an authentication method was picked
in the session we need to make sure we only use the one(s) we now
consider to be fine */
data->state.authhost.picked &= data->state.authhost.want;
data->state.authproxy.picked &= data->state.authproxy.want;
}
return result;
}
/*
* Curl_posttransfer() is called immediately after a transfer ends
*/
CURLcode Curl_posttransfer(struct SessionHandle *data)
{
#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
/* restore the signal handler for SIGPIPE before we get back */
if(!data->set.no_signal)
signal(SIGPIPE, data->state.prev_signal);
#else
(void)data; /* unused parameter */
#endif
return CURLE_OK;
}
#ifndef CURL_DISABLE_HTTP
/*
* strlen_url() returns the length of the given URL if the spaces within the
* URL were properly URL encoded.
*/
static size_t strlen_url(const char *url)
{
const char *ptr;
size_t newlen=0;
bool left=TRUE; /* left side of the ? */
for(ptr=url; *ptr; ptr++) {
switch(*ptr) {
case '?':
left=FALSE;
/* fall through */
default:
newlen++;
break;
case ' ':
if(left)
newlen+=3;
else
newlen++;
break;
}
}
return newlen;
}
/* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
* the source URL accordingly.
*/
static void strcpy_url(char *output, const char *url)
{
/* we must add this with <API key> */
bool left=TRUE;
const char *iptr;
char *optr = output;
for(iptr = url; /* read from here */
*iptr; /* until zero byte */
iptr++) {
switch(*iptr) {
case '?':
left=FALSE;
/* fall through */
default:
*optr++=*iptr;
break;
case ' ':
if(left) {
*optr++='%'; /* add a '%' */
*optr++='2'; /* add a '2' */
*optr++='0'; /* add a '0' */
}
else
*optr++='+'; /* add a '+' here */
break;
}
}
*optr=0; /* zero terminate output buffer */
}
/*
* Returns true if the given URL is absolute (as opposed to relative)
*/
static bool is_absolute_url(const char *url)
{
char prot[16]; /* URL protocol string storage */
char letter; /* used for a silly sscanf */
return (2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter)) ? TRUE : FALSE;
}
/*
* Concatenate a relative URL to a base URL making it absolute.
* URL-encodes any spaces.
* The returned pointer must be freed by the caller unless NULL
* (returns NULL on out of memory).
*/
static char *concat_url(const char *base, const char *relurl)
{
/***
TRY to append this new path to the old URL
to the right of the host part. Oh crap, this is doomed to cause
problems in the future...
*/
char *newest;
char *protsep;
char *pathsep;
size_t newlen;
const char *useurl = relurl;
size_t urllen;
/* we must make our own copy of the URL to play with, as it may
point to read-only data */
char *url_clone=strdup(base);
if(!url_clone)
return NULL; /* skip out of this NOW */
/* protsep points to the start of the host name */
protsep=strstr(url_clone, "
if(!protsep)
protsep=url_clone;
else
protsep+=2; /* pass the slashes */
if('/' != relurl[0]) {
int level=0;
/* First we need to find out if there's a ?-letter in the URL,
and cut it and the right-side of that off */
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep=0;
/* we have a relative path to append to the last slash if there's one
available, or if the new URL is just a query string (starts with a
'?') we append the new one at the end of the entire currently worked
out URL */
if(useurl[0] != '?') {
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep=0;
}
/* Check if there's any slash after the host name, and if so, remember
that position instead */
pathsep = strchr(protsep, '/');
if(pathsep)
protsep = pathsep+1;
else
protsep = NULL;
/* now deal with one "./" or any amount of "../" in the newurl
and act accordingly */
if((useurl[0] == '.') && (useurl[1] == '/'))
useurl+=2; /* just skip the "./" */
while((useurl[0] == '.') &&
(useurl[1] == '.') &&
(useurl[2] == '/')) {
level++;
useurl+=3; /* pass the "../" */
}
if(protsep) {
while(level
/* cut off one more level from the right of the original URL */
pathsep = strrchr(protsep, '/');
if(pathsep)
*pathsep=0;
else {
*protsep=0;
break;
}
}
}
}
else {
/* We got a new absolute path for this server */
if((relurl[0] == '/') && (relurl[1] == '/')) {
/* the new URL starts with //, just keep the protocol part from the
original one */
*protsep=0;
useurl = &relurl[2]; /* we keep the slashes from the original, so we
skip the new ones */
}
else {
/* cut off the original URL from the first slash, or deal with URLs
without slash */
pathsep = strchr(protsep, '/');
if(pathsep) {
char *sep = strchr(protsep, '?');
if(sep && (sep < pathsep))
pathsep = sep;
*pathsep=0;
}
else {
pathsep = strchr(protsep, '?');
if(pathsep)
*pathsep=0;
}
}
}
/* If the new part contains a space, this is a mighty stupid redirect
but we still make an effort to do "right". To the left of a '?'
letter we replace each space with %20 while it is replaced with '+'
on the right side of the '?' letter.
*/
newlen = strlen_url(useurl);
urllen = strlen(url_clone);
newest = malloc(urllen + 1 + /* possible slash */
newlen + 1 /* zero byte */);
if(!newest) {
free(url_clone); /* don't leak this */
return NULL;
}
/* copy over the root url part */
memcpy(newest, url_clone, urllen);
/* check if we need to append a slash */
if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
;
else
newest[urllen++]='/';
/* then append the new piece on the right side */
strcpy_url(&newest[urllen], useurl);
free(url_clone);
return newest;
}
#endif /* CURL_DISABLE_HTTP */
/*
* Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
* as given by the remote server and set up the new URL to request.
*/
CURLcode Curl_follow(struct SessionHandle *data,
char *newurl, /* this 'newurl' is the Location: string,
and it must be malloc()ed before passed
here */
followtype type) /* see transfer.h */
{
#ifdef CURL_DISABLE_HTTP
(void)data;
(void)newurl;
(void)type;
/* Location: following will not happen when HTTP is disabled */
return <API key>;
#else
/* Location: redirect */
bool disallowport = FALSE;
if(type == FOLLOW_REDIR) {
if((data->set.maxredirs != -1) &&
(data->set.followlocation >= data->set.maxredirs)) {
failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
return <API key>;
}
/* mark the next request as a followed location: */
data->state.this_is_a_follow = TRUE;
data->set.followlocation++; /* count location-followers */
if(data->set.http_auto_referer) {
/* We are asked to automatically set the previous URL as the referer
when we get the next URL. We pick the ->url field, which may or may
not be 100% correct */
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = strdup(data->change.url);
if(!data->change.referer)
return CURLE_OUT_OF_MEMORY;
data->change.referer_alloc = TRUE; /* yes, free this later */
}
}
if(!is_absolute_url(newurl)) {
/***
*DANG* this is an RFC 2068 violation. The URL is supposed
to be absolute and this doesn't seem to be that!
*/
char *absolute = concat_url(data->change.url, newurl);
if(!absolute)
return CURLE_OUT_OF_MEMORY;
free(newurl);
newurl = absolute;
}
else {
/* This is an absolute URL, don't allow the custom port number */
disallowport = TRUE;
if(strchr(newurl, ' ')) {
/* This new URL contains at least one space, this is a mighty stupid
redirect but we still make an effort to do "right". */
char *newest;
size_t newlen = strlen_url(newurl);
newest = malloc(newlen+1); /* get memory for this */
if(!newest)
return CURLE_OUT_OF_MEMORY;
strcpy_url(newest, newurl); /* create a space-free URL */
free(newurl); /* that was no good */
newurl = newest; /* use this instead now */
}
}
if(type == FOLLOW_FAKE) {
/* we're only figuring out the new url if we would've followed locations
but now we're done so we can get out! */
data->info.wouldredirect = newurl;
return CURLE_OK;
}
if(disallowport)
data->state.allow_port = FALSE;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = newurl;
data->change.url_alloc = TRUE;
newurl = NULL; /* don't free! */
infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
/*
* We get here when the HTTP code is 300-399 (and 401). We need to perform
* differently based on exactly what return code there was.
*
* News from 7.10.6: we can also get here on a 401 or 407, in case we act on
* a HTTP (proxy-) authentication scheme other than Basic.
*/
switch(data->info.httpcode) {
/* 401 - Act on a WWW-Authenticate, we keep on moving and do the
Authorization: XXXX header in the HTTP request code snippet */
/* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
Proxy-Authorization: XXXX header in the HTTP request code snippet */
/* 300 - Multiple Choices */
/* 306 - Not used */
/* 307 - Temporary Redirect */
default: /* for all above (and the unknown ones) */
/* Some codes are explicitly mentioned since I've checked RFC2616 and they
* seem to be OK to POST to.
*/
break;
case 301: /* Moved Permanently */
if((data->set.httpreq == HTTPREQ_POST
|| data->set.httpreq == HTTPREQ_POST_FORM)
&& !(data->set.keep_post & CURL_REDIR_POST_301)) {
infof(data, "Switch from POST to GET\n");
data->set.httpreq = HTTPREQ_GET;
}
break;
case 302: /* Found */
if((data->set.httpreq == HTTPREQ_POST
|| data->set.httpreq == HTTPREQ_POST_FORM)
&& !(data->set.keep_post & CURL_REDIR_POST_302)) {
infof(data, "Switch from POST to GET\n");
data->set.httpreq = HTTPREQ_GET;
}
break;
case 303: /* See Other */
/* Disable both types of POSTs, unless the user explicitely
asks for POST after POST */
if(data->set.httpreq != HTTPREQ_GET
&& !(data->set.keep_post & CURL_REDIR_POST_303)) {
data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
infof(data, "Disables POST, goes with %s\n",
data->set.opt_no_body?"HEAD":"GET");
}
break;
case 304: /* Not Modified */
/* 304 means we did a conditional request and it was "Not modified".
* We shouldn't get any Location: header in this response!
*/
break;
case 305: /* Use Proxy */
/* (quote from RFC2616, section 10.3.6):
* "The requested resource MUST be accessed through the proxy given
* by the Location field. The Location field gives the URI of the
* proxy. The recipient is expected to repeat this single request
* via the proxy. 305 responses MUST only be generated by origin
* servers."
*/
break;
}
Curl_pgrsTime(data, TIMER_REDIRECT);
<API key>(data);
return CURLE_OK;
#endif /* CURL_DISABLE_HTTP */
}
CURLcode
<API key>(struct connectdata **connp)
{
CURLcode result = CURLE_OK;
struct connectdata *conn = *connp;
struct SessionHandle *data = conn->data;
/* This was a re-use of a connection and we got a write error in the
* DO-phase. Then we DISCONNECT this connection and have another attempt to
* CONNECT and then DO again! The retry cannot possibly find another
* connection to re-use, since we only keep one possible connection for
* each. */
infof(data, "Re-used connection seems dead, get a new one\n");
connclose(conn, "Reconnect dead connection"); /* enforce close */
result = Curl_done(&conn, result, FALSE); /* we are so done with this */
/* conn may no longer be a good pointer, clear it to avoid mistakes by
parent functions */
*connp = NULL;
/*
* According to bug report #1330310. We need to check for CURLE_SEND_ERROR
* here as well. I figure this could happen when the request failed on a FTP
* connection and thus Curl_done() itself tried to use the connection
* (again). Slight Lack of feedback in the report, but I don't think this
* extra check can do much harm.
*/
if(!result || (CURLE_SEND_ERROR == result)) {
bool async;
bool protocol_done = TRUE;
/* Now, redo the connect and get a new connection */
result = Curl_connect(data, connp, &async, &protocol_done);
if(!result) {
/* We have connected or sent away a name resolve query fine */
conn = *connp; /* setup conn to again point to something nice */
if(async) {
/* Now, if async is TRUE here, we need to wait for the name
to resolve */
result = <API key>(conn, NULL);
if(result)
return result;
/* Resolved, continue with the connection */
result = Curl_async_resolved(conn, &protocol_done);
if(result)
return result;
}
}
}
return result;
}
/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
NOTE: that the *url is malloc()ed. */
CURLcode Curl_retry_request(struct connectdata *conn,
char **url)
{
struct SessionHandle *data = conn->data;
*url = NULL;
/* if we're talking upload, we can't do the checks below, unless the protocol
is HTTP as when uploading over HTTP we will still get a response */
if(data->set.upload &&
!(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
return CURLE_OK;
if((data->req.bytecount + data->req.headerbytecount == 0) &&
conn->bits.reuse &&
!data->set.opt_no_body &&
(data->set.rtspreq != RTSPREQ_RECEIVE)) {
/* We got no data, we attempted to re-use a connection and yet we want a
"body". This might happen if the connection was left alive when we were
done using it before, but that was closed when we wanted to read from
it again. Bad luck. Retry the same request on a fresh connect! */
infof(conn->data, "Connection died, retrying a fresh connect\n");
*url = strdup(conn->data->change.url);
if(!*url)
return CURLE_OUT_OF_MEMORY;
connclose(conn, "retry"); /* close this connection */
conn->bits.retry = TRUE; /* mark this as a connection we're about
to retry. Marking it this way should
prevent i.e HTTP transfers to return
error just because nothing has been
transferred! */
if(conn->handler->protocol&PROTO_FAMILY_HTTP) {
struct HTTP *http = data->req.protop;
if(http->writebytecount)
return Curl_readrewind(conn);
}
}
return CURLE_OK;
}
/*
* Curl_setup_transfer() is called to setup some basic properties for the
* upcoming transfer.
*/
void
Curl_setup_transfer(
struct connectdata *conn, /* connection data */
int sockindex, /* socket index to read from or -1 */
curl_off_t size, /* -1 if unknown at this point */
bool getheader, /* TRUE if header parsing is wanted */
curl_off_t *bytecountp, /* return number of bytes read or NULL */
int writesockindex, /* socket index to write to, it may very well be
the same we read from. -1 disables */
curl_off_t *writecountp /* return number of bytes written or NULL */
)
{
struct SessionHandle *data;
struct SingleRequest *k;
DEBUGASSERT(conn != NULL);
data = conn->data;
k = &data->req;
DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
/* now copy all input parameters */
conn->sockfd = sockindex == -1 ?
CURL_SOCKET_BAD : conn->sock[sockindex];
conn->writesockfd = writesockindex == -1 ?
CURL_SOCKET_BAD:conn->sock[writesockindex];
k->getheader = getheader;
k->size = size;
k->bytecountp = bytecountp;
k->writebytecountp = writecountp;
/* The code sequence below is placed in this function just because all
necessary input is not always known in do_complete() as this function may
be called after that */
if(!k->getheader) {
k->header = FALSE;
if(size > 0)
<API key>(data, size);
}
/* we want header and/or body, if neither then don't do this! */
if(k->getheader || !data->set.opt_no_body) {
if(conn->sockfd != CURL_SOCKET_BAD)
k->keepon |= KEEP_RECV;
if(conn->writesockfd != CURL_SOCKET_BAD) {
struct HTTP *http = data->req.protop;
/* HTTP 1.1 magic:
Even if we require a 100-return code before uploading data, we might
need to write data before that since the REQUEST may not have been
finished sent off just yet.
Thus, we must check if the request has been sent before we set the
state info where we wait for the 100-return code
*/
if((data->state.expect100header) &&
(conn->handler->protocol&PROTO_FAMILY_HTTP) &&
(http->sending == HTTPSEND_BODY)) {
/* wait with write until we either got 100-continue or a timeout */
k->exp100 = <API key>;
k->start100 = Curl_tvnow();
/* Set a timeout for the multi interface. Add the inaccuracy margin so
that we don't fire slightly too early and get denied to run. */
Curl_expire(data, data->set.expect_100_timeout);
}
else {
if(data->state.expect100header)
/* when we've sent off the rest of the headers, we must await a
100-continue but first finish sending the request */
k->exp100 = <API key>;
/* enable the write bit when we're not waiting for continue */
k->keepon |= KEEP_SEND;
}
} /* if(conn->writesockfd != CURL_SOCKET_BAD) */
} /* if(k->getheader || !data->set.opt_no_body) */
} |
package nsk.jdi.PlugConnectors.LaunchConnector.<API key>;
import nsk.jdi.PlugConnectors.LaunchConnector.<API key>.connectors.*;
import nsk.share.*;
import nsk.share.jdi.*;
import com.sun.jdi.*;
import com.sun.jdi.connect.*;
import java.util.*;
import java.io.*;
public class <API key> {
static final int STATUS_PASSED = 0;
static final int STATUS_FAILED = 2;
static final int STATUS_TEMP = 95;
static final String errorLogPrefixHead = "<API key>: ";
static final String errorLogPrefix = " ";
static final String infoLogPrefixNead = "--> <API key>: ";
static final String infoLogPrefix = "
static ArgumentHandler argsHandler;
static Log logHandler;
private static void logOnVerbose(String message) {
logHandler.display(message);
}
private static void logOnError(String message) {
logHandler.complain(message);
}
private static void logAlways(String message) {
logHandler.println(message);
}
public static void main (String argv[]) {
int result = run(argv, System.out);
System.exit(result + STATUS_TEMP);
}
public static int run (String argv[], PrintStream out) {
int result = new <API key>().runThis(argv, out);
if ( result == STATUS_FAILED ) {
logAlways("\n##> nsk/jdi/PlugConnectors/LaunchConnector/<API key> test FAILED");
}
else {
logAlways("\n==> nsk/jdi/PlugConnectors/LaunchConnector/<API key> test PASSED");
}
return result;
}
private int runThis (String argv[], PrintStream out) {
int testResult = STATUS_PASSED;
argsHandler = new ArgumentHandler(argv);
logHandler = new Log(out, argsHandler);
logHandler.enableErrorsSummary(false);
logAlways("==> nsk/jdi/PlugConnectors/LaunchConnector/<API key> test...");
logOnVerbose
("==> Test checks that pluggable launching connector is NOT created.");
logOnVerbose
(" for LaunchingConnector implementation for which instance can not be created.");
<API key> <API key> = null;
try {
<API key> = Bootstrap.<API key>();
} catch (Throwable thrown) {
// OK: Bootstrap.<API key>() may throw an unspecified error
// if initialization of the <API key> fails or if the virtual
// machine manager is unable to locate or create any Connectors.
logOnVerbose
(infoLogPrefixNead + "Bootstrap.<API key>() throws:\n" + thrown);
return STATUS_PASSED;
}
if (<API key> == null) {
logOnError(errorLogPrefixHead + "Bootstrap.<API key>() returns null.");
return STATUS_FAILED;
}
// implementation (<API key> class) for which instance can not be created
List <API key> = <API key>.launchingConnectors();
int <API key> = <API key>.size();
LaunchingConnector <API key> = null;
for (int i=0; i < <API key>; i++ ) {
LaunchingConnector launchingConnector = (LaunchingConnector)<API key>.get(i);
if ( launchingConnector instanceof <API key> ) {
<API key> = launchingConnector;
break;
}
}
if ( <API key> != null ) {
logOnError(errorLogPrefixHead + "Pluggable launching connector is created on base of LaunchingConnector");
logOnError(errorLogPrefix + "implementation for which instance can not be created.");
logOnError(errorLogPrefix + "This connector is found out in launchingConnectors() list");
logOnError(errorLogPrefix + "Connector instance = '" + <API key> + "'");
logOnError(errorLogPrefix + "Connector name = '" + <API key>.name() + "'");
testResult = STATUS_FAILED;
}
// check that pluggable connectors are NOT contained in allConnectors() List too
List allConnectorsList = <API key>.allConnectors();
int allConnectorsNumber = allConnectorsList.size();
Connector <API key> = null;
for (int i=0; i < allConnectorsNumber; i++ ){
Connector connector = (Connector)allConnectorsList.get(i);
if ( connector instanceof <API key> ) {
<API key> = connector;
break;
}
}
if ( <API key> != null ) {
logOnError(errorLogPrefixHead + "Pluggable launching connector is created on base of LaunchingConnector");
logOnError(errorLogPrefix + "implementation for which instance can not be created.");
logOnError(errorLogPrefix + "This connector is found out in allConnectors() list");
logOnError(errorLogPrefix + "Connector instance = '" + <API key> + "'");
logOnError(errorLogPrefix + "Connector name = '" + <API key>.name() + "'");
testResult = STATUS_FAILED;
}
return testResult;
}
} // end of <API key> class |
#include <cmath>
#include <fstream>
#include <vector>
#include "Common/CommonPaths.h"
#include "Common/FileUtil.h"
#include "Common/Hash.h"
#include "Common/MemoryUtil.h"
#include "Common/StringUtil.h"
#include "Core/HW/Memmap.h"
#include "VideoBackends/OGL/FramebufferManager.h"
#include "VideoBackends/OGL/GLInterfaceBase.h"
#include "VideoBackends/OGL/ProgramShaderCache.h"
#include "VideoBackends/OGL/Render.h"
#include "VideoBackends/OGL/SamplerCache.h"
#include "VideoBackends/OGL/StreamBuffer.h"
#include "VideoBackends/OGL/TextureCache.h"
#include "VideoBackends/OGL/TextureConverter.h"
#include "VideoCommon/BPStructs.h"
#include "VideoCommon/HiresTextures.h"
#include "VideoCommon/ImageWrite.h"
#include "VideoCommon/Statistics.h"
#include "VideoCommon/TextureDecoder.h"
#include "VideoCommon/VideoConfig.h"
namespace OGL
{
static SHADER s_ColorCopyProgram;
static SHADER <API key>;
static SHADER <API key>;
static GLuint <API key>;
static GLuint <API key>;
static GLuint <API key>;
static GLuint <API key>;
static GLuint <API key>;
static u32 s_ColorCbufid;
static u32 s_DepthCbufid;
static u32 s_Textures[8];
static u32 s_ActiveTexture;
static SHADER <API key>[3];
static StreamBuffer* <API key> = nullptr;
static GLuint <API key>;
static GLuint <API key>[3];
static GLuint <API key>[3];
static GLuint <API key>[3];
bool SaveTexture(const std::string& filename, u32 textarget, u32 tex, int virtual_width, int virtual_height, unsigned int level)
{
if (GLInterface->GetMode() != GLInterfaceMode::MODE_OPENGL)
return false;
int width = std::max(virtual_width >> level, 1);
int height = std::max(virtual_height >> level, 1);
std::vector<u8> data(width * height * 4);
glActiveTexture(GL_TEXTURE9);
glBindTexture(textarget, tex);
glGetTexImage(textarget, level, GL_RGBA, GL_UNSIGNED_BYTE, data.data());
TextureCache::SetStage();
return TextureToPng(data.data(), width * 4, filename, width, height, true);
}
TextureCache::TCacheEntry::~TCacheEntry()
{
if (texture)
{
for (auto& gtex : s_Textures)
if (gtex == texture)
gtex = 0;
glDeleteTextures(1, &texture);
texture = 0;
}
if (framebuffer)
{
<API key>(1, &framebuffer);
framebuffer = 0;
}
}
TextureCache::TCacheEntry::TCacheEntry(const TCacheEntryConfig& _config)
: TCacheEntryBase(_config)
{
glGenTextures(1, &texture);
framebuffer = 0;
}
void TextureCache::TCacheEntry::Bind(unsigned int stage)
{
if (s_Textures[stage] != texture)
{
if (s_ActiveTexture != stage)
{
glActiveTexture(GL_TEXTURE0 + stage);
s_ActiveTexture = stage;
}
glBindTexture(GL_TEXTURE_2D_ARRAY, texture);
s_Textures[stage] = texture;
}
}
bool TextureCache::TCacheEntry::Save(const std::string& filename, unsigned int level)
{
return SaveTexture(filename, GL_TEXTURE_2D_ARRAY, texture, config.width, config.height, level);
}
TextureCache::TCacheEntryBase* TextureCache::CreateTexture(const TCacheEntryConfig& config)
{
TCacheEntry* entry = new TCacheEntry(config);
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D_ARRAY, entry->texture);
glTexParameteri(GL_TEXTURE_2D_ARRAY, <API key>, config.levels - 1);
if (config.rendertarget)
{
for (u32 level = 0; level <= config.levels; level++)
{
glTexImage3D(GL_TEXTURE_2D_ARRAY, level, GL_RGBA, config.width, config.height, config.layers, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}
glGenFramebuffers(1, &entry->framebuffer);
FramebufferManager::SetFramebuffer(entry->framebuffer);
FramebufferManager::FramebufferTexture(GL_FRAMEBUFFER, <API key>, GL_TEXTURE_2D_ARRAY, entry->texture, 0);
}
TextureCache::SetStage();
return entry;
}
void TextureCache::TCacheEntry::<API key>(
const TCacheEntryBase* source,
const MathUtil::Rectangle<int> &srcrect,
const MathUtil::Rectangle<int> &dstrect)
{
TCacheEntry* srcentry = (TCacheEntry*)source;
if (srcrect.GetWidth() == dstrect.GetWidth()
&& srcrect.GetHeight() == dstrect.GetHeight()
&& g_ogl_config.<API key>)
{
glCopyImageSubData(
srcentry->texture,
GL_TEXTURE_2D_ARRAY,
0,
srcrect.left,
srcrect.top,
0,
texture,
GL_TEXTURE_2D_ARRAY,
0,
dstrect.left,
dstrect.top,
0,
dstrect.GetWidth(),
dstrect.GetHeight(),
1);
return;
}
else if (!framebuffer)
{
glGenFramebuffers(1, &framebuffer);
FramebufferManager::SetFramebuffer(framebuffer);
FramebufferManager::FramebufferTexture(GL_FRAMEBUFFER, <API key>, GL_TEXTURE_2D_ARRAY, texture, 0);
}
g_renderer->ResetAPIState();
FramebufferManager::SetFramebuffer(framebuffer);
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D_ARRAY, srcentry->texture);
g_sampler_cache->BindLinearSampler(9);
glViewport(dstrect.left, dstrect.top, dstrect.GetWidth(), dstrect.GetHeight());
s_ColorCopyProgram.Bind();
glUniform4f(<API key>,
float(srcrect.left),
float(srcrect.top),
float(srcrect.GetWidth()),
float(srcrect.GetHeight()));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
FramebufferManager::SetFramebuffer(0);
g_renderer->RestoreAPIState();
}
void TextureCache::TCacheEntry::Load(unsigned int width, unsigned int height,
unsigned int expanded_width, unsigned int level)
{
if (level >= config.levels)
PanicAlert("Texture only has %d levels, can't update level %d", config.levels, level);
if (width != std::max(1u, config.width >> level) || height != std::max(1u, config.height >> level))
PanicAlert("size of level %d must be %dx%d, but %dx%d requested",
level, std::max(1u, config.width >> level), std::max(1u, config.height >> level), width, height);
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D_ARRAY, texture);
if (expanded_width != width)
glPixelStorei(<API key>, expanded_width);
glTexImage3D(GL_TEXTURE_2D_ARRAY, level, GL_RGBA, width, height, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp);
if (expanded_width != width)
glPixelStorei(<API key>, 0);
TextureCache::SetStage();
}
void TextureCache::TCacheEntry::FromRenderTarget(u8* dstPointer, unsigned int dstFormat, u32 dstStride,
PEControl::PixelFormat srcFormat, const EFBRectangle& srcRect,
bool isIntensity, bool scaleByHalf, unsigned int cbufid,
const float *colmat)
{
g_renderer->ResetAPIState(); // reset any game specific settings
// Make sure to resolve anything we need to read from.
const GLuint read_texture = (srcFormat == PEControl::Z24) ?
FramebufferManager::<API key>(srcRect) :
FramebufferManager::<API key>(srcRect);
FramebufferManager::SetFramebuffer(framebuffer);
<API key>();
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D_ARRAY, read_texture);
if (scaleByHalf)
g_sampler_cache->BindLinearSampler(9);
else
g_sampler_cache->BindNearestSampler(9);
glViewport(0, 0, config.width, config.height);
GLuint uniform_location;
if (srcFormat == PEControl::Z24)
{
<API key>.Bind();
if (s_DepthCbufid != cbufid)
glUniform4fv(<API key>, 5, colmat);
s_DepthCbufid = cbufid;
uniform_location = <API key>;
}
else
{
<API key>.Bind();
if (s_ColorCbufid != cbufid)
glUniform4fv(<API key>, 7, colmat);
s_ColorCbufid = cbufid;
uniform_location = <API key>;
}
TargetRectangle R = g_renderer->ConvertEFBRectangle(srcRect);
glUniform4f(uniform_location, static_cast<float>(R.left), static_cast<float>(R.top),
static_cast<float>(R.right), static_cast<float>(R.bottom));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
if (g_ActiveConfig.bSkipEFBCopyToRam)
{
this->Zero(dstPointer);
}
else
{
TextureConverter::<API key>(
dstPointer,
this,
read_texture,
srcFormat == PEControl::Z24,
isIntensity,
scaleByHalf,
srcRect);
}
FramebufferManager::SetFramebuffer(0);
g_renderer->RestoreAPIState();
}
TextureCache::TextureCache()
{
CompileShaders();
s_ActiveTexture = -1;
for (auto& gtex : s_Textures)
gtex = -1;
if (g_ActiveConfig.backend_info.<API key>)
{
<API key> = StreamBuffer::Create(GL_TEXTURE_BUFFER, 1024*1024);
glGenTextures(1, &<API key>);
glBindTexture(GL_TEXTURE_BUFFER, <API key>);
glTexBuffer(GL_TEXTURE_BUFFER, GL_R16UI, <API key>->m_buffer);
}
}
TextureCache::~TextureCache()
{
DeleteShaders();
if (g_ActiveConfig.backend_info.<API key>)
{
delete <API key>;
<API key> = nullptr;
glDeleteTextures(1, &<API key>);
}
}
void TextureCache::DisableStage(unsigned int stage)
{
}
void TextureCache::SetStage()
{
// -1 is the initial value as we don't know which texture should be bound
if (s_ActiveTexture != (u32)-1)
glActiveTexture(GL_TEXTURE0 + s_ActiveTexture);
}
void TextureCache::CompileShaders()
{
const char *pColorCopyProg =
"SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n"
"in vec3 f_uv0;\n"
"out vec4 ocol0;\n"
"\n"
"void main(){\n"
" vec4 texcol = texture(samp9, f_uv0);\n"
" ocol0 = texcol;\n"
"}\n";
const char *pColorMatrixProg =
"SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n"
"uniform vec4 colmat[7];\n"
"in vec3 f_uv0;\n"
"out vec4 ocol0;\n"
"\n"
"void main(){\n"
" vec4 texcol = texture(samp9, f_uv0);\n"
" texcol = round(texcol * colmat[5]) * colmat[6];\n"
" ocol0 = texcol * mat4(colmat[0], colmat[1], colmat[2], colmat[3]) + colmat[4];\n"
"}\n";
const char *pDepthMatrixProg =
"SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n"
"uniform vec4 colmat[5];\n"
"in vec3 f_uv0;\n"
"out vec4 ocol0;\n"
"\n"
"void main(){\n"
" vec4 texcol = texture(samp9, vec3(f_uv0.xy, %s));\n"
" int depth = int(texcol.x * 16777216.0);\n"
// Convert to Z24 format
" ivec4 workspace;\n"
" workspace.r = (depth >> 16) & 255;\n"
" workspace.g = (depth >> 8) & 255;\n"
" workspace.b = depth & 255;\n"
// Convert to Z4 format
" workspace.a = (depth >> 16) & 0xF0;\n"
// Normalize components to [0.0..1.0]
" texcol = vec4(workspace) / 255.0;\n"
" ocol0 = texcol * mat4(colmat[0], colmat[1], colmat[2], colmat[3]) + colmat[4];\n"
"}\n";
const char *VProgram =
"out vec3 %s_uv0;\n"
"SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n"
"uniform vec4 copy_position;\n" // left, top, right, bottom
"void main()\n"
"{\n"
" vec2 rawpos = vec2(gl_VertexID&1, gl_VertexID&2);\n"
" %s_uv0 = vec3(mix(copy_position.xy, copy_position.zw, rawpos) / vec2(textureSize(samp9, 0).xy), 0.0);\n"
" gl_Position = vec4(rawpos*2.0-1.0, 0.0, 1.0);\n"
"}\n";
const char *GProgram = g_ActiveConfig.iStereoMode > 0 ?
"layout(triangles) in;\n"
"layout(triangle_strip, max_vertices = 6) out;\n"
"in vec3 v_uv0[3];\n"
"out vec3 f_uv0;\n"
"SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n"
"void main()\n"
"{\n"
" int layers = textureSize(samp9, 0).z;\n"
" for (int layer = 0; layer < layers; ++layer) {\n"
" for (int i = 0; i < 3; ++i) {\n"
" f_uv0 = vec3(v_uv0[i].xy, layer);\n"
" gl_Position = gl_in[i].gl_Position;\n"
" gl_Layer = layer;\n"
" EmitVertex();\n"
" }\n"
" EndPrimitive();\n"
" }\n"
"}\n" : nullptr;
const char* prefix = (GProgram == nullptr) ? "f" : "v";
const char* depth_layer = (g_ActiveConfig.bStereoEFBMonoDepth) ? "0.0" : "f_uv0.z";
ProgramShaderCache::CompileShader(s_ColorCopyProgram, StringFromFormat(VProgram, prefix, prefix).c_str(), pColorCopyProg, GProgram);
ProgramShaderCache::CompileShader(<API key>, StringFromFormat(VProgram, prefix, prefix).c_str(), pColorMatrixProg, GProgram);
ProgramShaderCache::CompileShader(<API key>, StringFromFormat(VProgram, prefix, prefix).c_str(), StringFromFormat(pDepthMatrixProg, depth_layer).c_str(), GProgram);
<API key> = <API key>(<API key>.glprogid, "colmat");
<API key> = <API key>(<API key>.glprogid, "colmat");
s_ColorCbufid = -1;
s_DepthCbufid = -1;
<API key> = <API key>(s_ColorCopyProgram.glprogid, "copy_position");
<API key> = <API key>(<API key>.glprogid, "copy_position");
<API key> = <API key>(<API key>.glprogid, "copy_position");
std::string palette_shader =
R"GLSL(
uniform int <API key>;
uniform float multiplier;
SAMPLER_BINDING(9) uniform sampler2DArray samp9;
SAMPLER_BINDING(10) uniform usamplerBuffer samp10;
in vec3 f_uv0;
out vec4 ocol0;
int Convert3To8(int v)
{
// Swizzle bits: 00000123 -> 12312312
return (v << 5) | (v << 2) | (v >> 1);
}
int Convert4To8(int v)
{
// Swizzle bits: 00001234 -> 12341234
return (v << 4) | v;
}
int Convert5To8(int v)
{
// Swizzle bits: 00012345 -> 12345123
return (v << 3) | (v >> 2);
}
int Convert6To8(int v)
{
// Swizzle bits: 00123456 -> 12345612
return (v << 2) | (v >> 4);
}
float4 DecodePixel_RGB5A3(int val)
{
int r,g,b,a;
if ((val&0x8000) > 0)
{
r=Convert5To8((val>>10) & 0x1f);
g=Convert5To8((val>>5 ) & 0x1f);
b=Convert5To8((val ) & 0x1f);
a=0xFF;
}
else
{
a=Convert3To8((val>>12) & 0x7);
r=Convert4To8((val>>8 ) & 0xf);
g=Convert4To8((val>>4 ) & 0xf);
b=Convert4To8((val ) & 0xf);
}
return float4(r, g, b, a) / 255.0;
}
float4 DecodePixel_RGB565(int val)
{
int r, g, b, a;
r = Convert5To8((val >> 11) & 0x1f);
g = Convert6To8((val >> 5) & 0x3f);
b = Convert5To8((val) & 0x1f);
a = 0xFF;
return float4(r, g, b, a) / 255.0;
}
float4 DecodePixel_IA8(int val)
{
int i = val & 0xFF;
int a = val >> 8;
return float4(i, i, i, a) / 255.0;
}
void main()
{
int src = int(round(texture(samp9, f_uv0).r * multiplier));
src = int(texelFetch(samp10, src + <API key>).r);
src = ((src << 8) & 0xFF00) | (src >> 8);
ocol0 = DECODE(src);
}
)GLSL";
if (g_ActiveConfig.backend_info.<API key>)
{
ProgramShaderCache::CompileShader(
<API key>[GX_TL_IA8],
StringFromFormat(VProgram, prefix, prefix).c_str(),
("#define DECODE DecodePixel_IA8" + palette_shader).c_str(),
GProgram);
<API key>[GX_TL_IA8] = <API key>(<API key>[GX_TL_IA8].glprogid, "<API key>");
<API key>[GX_TL_IA8] = <API key>(<API key>[GX_TL_IA8].glprogid, "multiplier");
<API key>[GX_TL_IA8] = <API key>(<API key>[GX_TL_IA8].glprogid, "copy_position");
ProgramShaderCache::CompileShader(
<API key>[GX_TL_RGB565],
StringFromFormat(VProgram, prefix, prefix).c_str(),
("#define DECODE DecodePixel_RGB565" + palette_shader).c_str(),
GProgram);
<API key>[GX_TL_RGB565] = <API key>(<API key>[GX_TL_RGB565].glprogid, "<API key>");
<API key>[GX_TL_RGB565] = <API key>(<API key>[GX_TL_RGB565].glprogid, "multiplier");
<API key>[GX_TL_RGB565] = <API key>(<API key>[GX_TL_RGB565].glprogid, "copy_position");
ProgramShaderCache::CompileShader(
<API key>[GX_TL_RGB5A3],
StringFromFormat(VProgram, prefix, prefix).c_str(),
("#define DECODE DecodePixel_RGB5A3" + palette_shader).c_str(),
GProgram);
<API key>[GX_TL_RGB5A3] = <API key>(<API key>[GX_TL_RGB5A3].glprogid, "<API key>");
<API key>[GX_TL_RGB5A3] = <API key>(<API key>[GX_TL_RGB5A3].glprogid, "multiplier");
<API key>[GX_TL_RGB5A3] = <API key>(<API key>[GX_TL_RGB5A3].glprogid, "copy_position");
}
}
void TextureCache::DeleteShaders()
{
<API key>.Destroy();
<API key>.Destroy();
if (g_ActiveConfig.backend_info.<API key>)
for (auto& shader : <API key>)
shader.Destroy();
}
void TextureCache::ConvertTexture(TCacheEntryBase* _entry, TCacheEntryBase* _unconverted, void* palette, TlutFormat format)
{
if (!g_ActiveConfig.backend_info.<API key>)
return;
g_renderer->ResetAPIState();
TCacheEntry* entry = (TCacheEntry*) _entry;
TCacheEntry* unconverted = (TCacheEntry*) _unconverted;
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D_ARRAY, unconverted->texture);
g_sampler_cache->BindNearestSampler(9);
FramebufferManager::SetFramebuffer(entry->framebuffer);
glViewport(0, 0, entry->config.width, entry->config.height);
<API key>[format].Bind();
int size = unconverted->format == 0 ? 32 : 512;
auto buffer = <API key>->Map(size);
memcpy(buffer.first, palette, size);
<API key>->Unmap(size);
glUniform1i(<API key>[format], buffer.second / 2);
glUniform1f(<API key>[format], (unconverted->format & 0xf) == 0 ? 15.0f : 255.0f);
glUniform4f(<API key>[format], 0.0f, 0.0f, (float)unconverted->config.width, (float)unconverted->config.height);
glActiveTexture(GL_TEXTURE10);
glBindTexture(GL_TEXTURE_BUFFER, <API key>);
g_sampler_cache->BindNearestSampler(10);
<API key>();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
FramebufferManager::SetFramebuffer(0);
g_renderer->RestoreAPIState();
}
} |
#include <cstdlib>
#include <cstring>
#include <config.h>
// tuxbox
#if HAVE_LCD
#include <driver/lcdd.h>
#endif
#include <global.h>
#include <neutrino.h>
#include <system/settings.h>
#if HAVE_LCD
#include <lcddisplay/lcddisplay.h>
#endif
#include <fcntl.h>
#include <unistd.h>
// nhttpd
//#include "ylogging.h"
#include "lcdapi.h"
#if HAVE_LCD
static char font_name[3][10]={"Micron","Micron","Pakenham"};
#endif
void CLCDAPI::Clear(void)
{
#if HAVE_LCD
display.draw_fill_rect(-1, -1, 120, 64, CLCDDisplay::PIXEL_OFF); // clear lcd
#endif
}
void CLCDAPI::Update(void)
{
#if HAVE_LCD
display.update();
#endif
}
void CLCDAPI::LockDisplay(int plock)
{
if (plock)
{
FILE *lfh=fopen("/tmp/lcd.locked","w");
if(lfh)
{
fprintf(lfh,"lcdlock");
fclose(lfh);
usleep(100000L);
}
}
else
{
remove("/tmp/lcd.locked");
}
}
void CLCDAPI::DrawLine(int x1, int y1, int x2, int y2, int col)
{
#if HAVE_LCD
int color=(col==0)?(CLCDDisplay::PIXEL_OFF):((col==2)?(CLCDDisplay::PIXEL_INV):(CLCDDisplay::PIXEL_ON));
display.draw_line(x1,y1,x2,y2,color);
#endif
}
void CLCDAPI::DrawRect(int x1, int y1, int x2, int y2, int coll, int colf)
{
#if HAVE_LCD
int colorl=(coll==0)?(CLCDDisplay::PIXEL_OFF):((coll==2)?(CLCDDisplay::PIXEL_INV):(CLCDDisplay::PIXEL_ON));
int colorf=(colf==0)?(CLCDDisplay::PIXEL_OFF):((colf==2)?(CLCDDisplay::PIXEL_INV):(CLCDDisplay::PIXEL_ON));
display.draw_rectangle(x1,y1,x2,y2,colorl,colorf);
#endif
}
void CLCDAPI::DrawText(int px, int py, int psize, int pcolor, int pfont, char *pmsg)
{
#if HAVE_LCD
int color=(pcolor==0)?(CLCDDisplay::PIXEL_OFF):((pcolor==2)?(CLCDDisplay::PIXEL_INV):(CLCDDisplay::PIXEL_ON));
if(!(font = fontRenderer->getFont(font_name[pfont], style_name[pfont], psize)))
{
printf("[nhttpd] Kein Font gefunden.\n");
return;
}
font->RenderString(px, py, 130, pmsg, color, 0, true); // UTF-8
#endif
}
bool CLCDAPI::ShowPng(char *filename)
{
#if HAVE_LCD
return display.load_png(filename);
#endif
return 0;
}
void CLCDAPI::ShowRaw(int xpos, int ypos, int xsize, int ysize, char *ascreen)
{
#if HAVE_LCD
int sbyte,dbit,dxpos,dypos,wasinc=0,gotval;
char *sptr=ascreen;
raw_display_t rscreen;
display.dump_screen(&rscreen);
gotval=sscanf(sptr,"%d",&sbyte);
for(dypos=ypos; gotval && (dypos<(ypos+ysize)); dypos++)
{
dbit=7;
for(dxpos=xpos; gotval && (dxpos<(xpos+xsize)); dxpos++)
{
wasinc=0;
if((dypos<LCD_ROWS*8) && (dxpos<LCD_COLS))
{
rscreen[dypos][dxpos]=(sbyte & (1<<dbit))?1:0;
}
if(--dbit<0)
{
dbit=7;
if((sptr=strchr(sptr,','))!=NULL)
{
gotval=sscanf(++sptr,"%d",&sbyte);
}
else
{
gotval=0;
}
wasinc=1;
}
}
if(!wasinc)
{
if((sptr=strchr(sptr,','))!=NULL)
{
gotval=sscanf(++sptr,"%d",&sbyte);
}
else
{
gotval=0;
}
}
}
display.load_screen(&rscreen);
#endif
}
// Konstruktor und destruktor
CLCDAPI::CLCDAPI()
{
#if HAVE_LCD
// int i;
// display = new CLCDDisplay();
fontRenderer = new LcdFontRenderClass(&display);
style_name[0] = fontRenderer->AddFont("/share/fonts/micron.ttf");
style_name[1] = fontRenderer->AddFont("/share/fonts/micron_bold.ttf");
style_name[2] = fontRenderer->AddFont("/share/fonts/pakenham.ttf");
fontRenderer->InitFontCache();
/* for(i=0; i<3; i++)
{
if(font=fontRenderer->getFont(font_name[i], style_name[i], 14))
{
font->RenderString(10, 10, 30, "X", CLCDDisplay::PIXEL_OFF, 0, true);
}
}
*/
#endif
}
CLCDAPI::~CLCDAPI(void)
{
#if HAVE_LCD
if(fontRenderer)
{
delete fontRenderer;
}
/* if(display)
{
delete display;
}
*/
#endif
} |
#define IN_LIBXML
#include "xmlenglibxml.h"
#include <stdlib.h>
#include <string.h>
#include <<API key>.h>
#include "libxml2_xmlerror2.h"
#ifdef <API key>
#include "libxml2_debugxml.h"
#endif
#include <libxml2_uri.h>
#include <libxml2_globals.h>
#ifdef LIBXML_HTML_ENABLED
#include "libxml2_htmltree.h"
#endif
/* #define DEBUG_SAX2 */
/* #define DEBUG_SAX2_TREE */
/**
*
*
* macro to flag unimplemented blocks
* XML_CATALOG_PREFER user env to select between system/public prefered
* option. C.f. Richard Tobin <richard@cogsci.ed.ac.uk>
*> Just FYI, I am using an environment variable XML_CATALOG_PREFER with
*> values "system" and "public". I have made the default be "system" to
*> match yours.
*/
#define _TODO_ \
xmlGenericError(<API key>, \
EMBED_ERRTXT("Unimplemented block at %s:%d\n"), \
__FILE__, __LINE__);
/**
* xmlValidError:
* @param ctxt an XML validation parser context
* @param error the error number
* @param msg the error message
* @param str1 extra data
* @param str2 extra data
*
* Handle a validation error
*/
static void
xmlErrValid(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg, const char *str1, const char *str2)
{
<API key> schannel = NULL;
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
ctxt->errNo = error;
if ((ctxt->sax != NULL) && (ctxt->sax->initialized == XML_SAX2_MAGIC))
schannel = ctxt->sax->serror;
__xmlRaiseError(schannel,
ctxt->vctxt.error, ctxt->vctxt.userData,
ctxt, NULL, XML_FROM_DTD, error,
XML_ERR_ERROR, NULL, 0, (const char *) str1,
(const char *) str2, NULL, 0, 0,
msg, (const char *) str1, (const char *) str2);
ctxt->valid = 0;
}
/**
* xmlSAX2GetPublicId:
* @param ctx the user data (XML parser context)
*
* Provides the public ID e.g. "-//SGMLSOURCE//DTD DEMO//EN"
*
* Returns a xmlChar *
*/
XMLPUBFUNEXPORT const xmlChar *
xmlSAX2GetPublicId(void *ctx ATTRIBUTE_UNUSED)
{
/* xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; */
if(ctx)
return NULL; // just to use ctx
return(NULL);
}
XMLPUBFUNEXPORT const xmlChar *
xmlSAX2GetSystemId(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return((const xmlChar *) ctxt->input->filename);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
*
* Provide the line number of the current parsing point.
*
* Returns an int
*/
XMLPUBFUNEXPORT int
<API key>(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return(ctxt->input->line);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
*
* Provide the column number of the current parsing point.
*
* Returns an int
*/
XMLPUBFUNEXPORT int
<API key>(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return(ctxt->input->col);
}
/**
* xmlSAX2IsStandalone:
* @param ctx the user data (XML parser context)
*
* Is this document tagged standalone ?
*
* Returns 1 if true
*/
XMLPUBFUNEXPORT int
xmlSAX2IsStandalone(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return(ctxt->myDoc->standalone == 1);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
*
* Does this document has an internal subset
*
* Returns 1 if true
*/
XMLPUBFUNEXPORT int
<API key>(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return(ctxt->myDoc->intSubset != NULL);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
*
* Does this document has an external subset
*
* Returns 1 if true
*/
XMLPUBFUNEXPORT int
<API key>(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
return(ctxt->myDoc->extSubset != NULL);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param name the root element name
* @param ExternalID the external ID
* @param SystemID the SYSTEM ID (e.g. filename or URL)
*
* Callback on internal subset declaration.
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *SystemID)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlDtdPtr dtd;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s, %s)\n",
name, ExternalID, SystemID);
#endif
if (ctxt->myDoc == NULL)
return;
dtd = xmlGetIntSubset(ctxt->myDoc);
if (dtd != NULL) {
if (ctxt->html)
return;
xmlUnlinkNode((xmlNodePtr) dtd);
xmlFreeDtd(dtd);
ctxt->myDoc->intSubset = NULL;
}
ctxt->myDoc->intSubset = xmlCreateIntSubset(ctxt->myDoc, name, ExternalID, SystemID);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param name the root element name
* @param ExternalID the external ID
* @param SystemID the SYSTEM ID (e.g. filename or URL)
*
* Callback on external subset declaration.
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *SystemID)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s, %s)\n",
name, ExternalID, SystemID);
#endif
if (((ExternalID != NULL) || (SystemID != NULL)) &&
(((ctxt->validate) || (ctxt->loadsubset != 0)) &&
(ctxt->wellFormed && ctxt->myDoc))) {
/*
* Try to fetch and parse the external subset.
*/
xmlParserInputPtr oldinput;
int oldinputNr;
int oldinputMax;
xmlParserInputPtr *oldinputTab;
xmlParserInputPtr input = NULL;
xmlCharEncoding enc;
int oldcharset;
/*
* Ask the Entity resolver to load the damn thing
*/
if ((ctxt->sax != NULL) && (ctxt->sax->resolveEntity != NULL))
input = ctxt->sax->resolveEntity(ctxt->userData, ExternalID,
SystemID);
if (input == NULL) {
return;
}
xmlNewDtd(ctxt->myDoc, name, ExternalID, SystemID);
/*
* make sure we won't destroy the main document context
*/
oldinput = ctxt->input;
oldinputNr = ctxt->inputNr;
oldinputMax = ctxt->inputMax;
oldinputTab = ctxt->inputTab;
oldcharset = ctxt->charset;
ctxt->inputTab = (xmlParserInputPtr *)
xmlMalloc(5 * sizeof(xmlParserInputPtr));
if (ctxt->inputTab == NULL) {
ctxt->errNo = XML_ERR_NO_MEMORY;
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("<API key>: out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
ctxt->input = oldinput;
ctxt->inputNr = oldinputNr;
ctxt->inputMax = oldinputMax;
ctxt->inputTab = oldinputTab;
ctxt->charset = oldcharset;
return;
}
ctxt->inputNr = 0;
ctxt->inputMax = 5;
ctxt->input = NULL;
xmlPushInput(ctxt, input);
/*
* On the fly encoding conversion if needed
*/
if (ctxt->input->length >= 4) {
enc = <API key>(ctxt->input->cur, 4);
xmlSwitchEncoding(ctxt, enc);
}
if (input->filename == NULL)
input->filename = (char *) xmlCanonicPath(SystemID);
input->line = 1;
input->col = 1;
input->base = ctxt->input->cur;
input->cur = ctxt->input->cur;
input->free = NULL;
/*
* let's parse that entity knowing it's an external subset.
*/
<API key>(ctxt, ExternalID, SystemID);
/*
* Free up the external entities
*/
while (ctxt->inputNr > 1)
xmlPopInput(ctxt);
xmlFreeInputStream(ctxt->input);
xmlFree(ctxt->inputTab);
/*
* Restore the parsing context of the main entity
*/
ctxt->input = oldinput;
ctxt->inputNr = oldinputNr;
ctxt->inputMax = oldinputMax;
ctxt->inputTab = oldinputTab;
ctxt->charset = oldcharset;
/* ctxt->wellFormed = oldwellFormed; */
}
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param publicId The public ID of the entity
* @param systemId The system ID of the entity
*
* The entity loader, to control the loading of external entities,
* the application can either:
* - override this <API key>() callback in the SAX block
* - or better use the <API key>() function to
* set up it's own entity resolution routine
*
* Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour.
*/
XMLPUBFUNEXPORT xmlParserInputPtr
<API key>(void *ctx, const xmlChar *publicId, const xmlChar *systemId)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlParserInputPtr ret;
xmlChar* URI;
const char* base = NULL;
if (ctxt->input)
base = ctxt->input->filename;
if (!base)
base = ctxt->directory;
URI = xmlBuildURI(systemId, (const xmlChar *) base);
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s)\n", publicId, systemId);
#endif
ret = <API key>((const char *) URI,
(const char *) publicId, ctxt);
if (URI)
xmlFree(URI);
return(ret);
}
/**
* xmlSAX2GetEntity:
* @param ctx the user data (XML parser context)
* @param name The entity name
*
* Get an entity by name
*
* Returns the xmlEntityPtr if found.
*/
XMLPUBFUNEXPORT xmlEntityPtr
xmlSAX2GetEntity(void *ctx, const xmlChar *name)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlEntityPtr ret = NULL;
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.xmlSAX2GetEntity(%s)\n", name);
#endif
if (ctxt->inSubset == 0) {
ret = <API key>(name);
if (ret != NULL)
return(ret);
}
if ((ctxt->myDoc != NULL) && (ctxt->myDoc->standalone == 1))
{
if (ctxt->inSubset == 2) {
ctxt->myDoc->standalone = 0;
ret = xmlGetDocEntity(ctxt->myDoc, name);
ctxt->myDoc->standalone = 1;
} else {
ret = xmlGetDocEntity(ctxt->myDoc, name);
if (ret == NULL) {
ctxt->myDoc->standalone = 0;
ret = xmlGetDocEntity(ctxt->myDoc, name);
if (ret != NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("Entity(%s) document marked standalone but requires external subset\n"),
name);
ctxt->valid = 0;
ctxt->wellFormed = 0;
}
ctxt->myDoc->standalone = 1;
}
}
} else {
ret = xmlGetDocEntity(ctxt->myDoc, name);
}
if (ret &&
((ctxt->validate) || (ctxt->replaceEntities)) &&
!ret->children &&
(ret->etype == <API key>))
{
int val;
/*
* for validation purposes we really need to fetch and
* parse the external entity
*/
xmlNodePtr children;
val = <API key>(ctxt, ret->URI, ret->ExternalID, &children);
if (val == 0) {
xmlAddChildList((xmlNodePtr) ret, children);
} else {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("Failure to process entity %s\n"), name);
ctxt->wellFormed = 0;
ctxt->valid = 0;
ctxt->validate = 0;
return(NULL);
}
ret->owner = 1;
}
return(ret);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param name The entity name
*
* Get a parameter entity by name
*
* Returns the xmlEntityPtr if found.
*/
XMLPUBFUNEXPORT xmlEntityPtr
<API key>(void *ctx, const xmlChar *name)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlEntityPtr ret;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s)\n", name);
#endif
ret = <API key>(ctxt->myDoc, name);
return(ret);
}
/**
* xmlSAX2EntityDecl:
* @param ctx the user data (XML parser context)
* @param name the entity name
* @param type the entity type
* @param publicId The public ID of the entity
* @param systemId The system ID of the entity
* @param content the entity value (without processing).
*
* An entity definition has been parsed
*/
XMLPUBFUNEXPORT void
xmlSAX2EntityDecl(void *ctx, const xmlChar *name, int type,
const xmlChar *publicId, const xmlChar *systemId, xmlChar *content)
{
xmlEntityPtr ent;
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.xmlSAX2EntityDecl(%s, %d, %s, %s, %s)\n",
name, type, publicId, systemId, content);
#endif
if (ctxt->inSubset == 1)
{
ent = xmlAddDocEntity(ctxt->myDoc, name, type, publicId,
systemId, content);
if (!ent &&
ctxt->pedantic &&
ctxt->sax && ctxt->sax->warning)
{
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Entity(%s) already defined in the internal subset\n"), name);
}
if (ent && !ent->URI && systemId)
{
xmlChar *URI;
const char *base = NULL;
if (ctxt->input)
base = ctxt->input->filename;
if (!base)
base = ctxt->directory;
URI = xmlBuildURI(systemId, (const xmlChar *) base);
ent->URI = URI;
}
}
else if (ctxt->inSubset == 2)
{
ent = xmlAddDtdEntity(ctxt->myDoc, name, type, publicId,
systemId, content);
if (!ent &&
ctxt->pedantic &&
ctxt->sax &&
ctxt->sax->warning)
{
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Entity(%s) already defined in the external subset\n"), name);
}
if (ent && !ent->URI && systemId)
{
xmlChar *URI;
const char* base = NULL;
if (ctxt->input != NULL)
base = ctxt->input->filename;
if (!base)
base = ctxt->directory;
URI = xmlBuildURI(systemId, (const xmlChar*) base);
ent->URI = URI;
}
}
else if (ctxt->sax && ctxt->sax->error)
{
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.xmlSAX2EntityDecl(%s) called while not in subset\n"),
name);
}
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param elem the name of the element
* @param fullname the attribute name
* @param type the attribute type
* @param def the type of default value
* @param defaultValue the attribute default value
* @param tree the tree of enumerated value set
*
* An attribute definition has been parsed
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx, const xmlChar *elem, const xmlChar *fullname,
int type, int def, const xmlChar *defaultValue,
xmlEnumerationPtr tree)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef <API key>
xmlAttributePtr attr;
#endif
xmlChar *name = NULL, *prefix = NULL;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s, %d, %d, %s, ...)\n",
elem, fullname, type, def, defaultValue);
#endif
if ((xmlStrEqual(fullname, BAD_CAST "xml:id")) &&
(type != XML_ATTRIBUTE_ID)) {
/*
* Raise the error but keep the validity flag
*/
int tmp = ctxt->valid;
xmlErrValid(ctxt, XML_DTD_XMLID_TYPE,
EMBED_ERRTXT("xml:id : attribute type should be ID\n"), NULL, NULL);
ctxt->valid = tmp;
}
name = xmlSplitQName(ctxt, fullname, &prefix);
ctxt->vctxt.valid = 1;
if (ctxt->inSubset == 1)
{
#ifdef <API key>
attr =
#endif
xmlAddAttributeDecl(&ctxt->vctxt, ctxt->myDoc->intSubset, elem,
name, prefix, (xmlAttributeType) type,
(xmlAttributeDefault) def, defaultValue, tree);
}
else if (ctxt->inSubset == 2)
{
#ifdef <API key>
attr =
#endif
xmlAddAttributeDecl(&ctxt->vctxt, ctxt->myDoc->extSubset, elem,
name, prefix, (xmlAttributeType) type,
(xmlAttributeDefault) def, defaultValue, tree);
}
else
{
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.<API key>(%s) called while not in subset\n"), name);
xmlFreeEnumeration(tree);
return;
}
#ifdef <API key>
if (ctxt->vctxt.valid == 0)
ctxt->valid = 0;
if ((attr != NULL) && (ctxt->validate) && (ctxt->wellFormed) &&
(ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset != NULL))
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
attr);
#endif /* <API key> */
if (prefix != NULL)
xmlFree(prefix);
if (name != NULL)
xmlFree(name);
}
/**
* xmlSAX2ElementDecl:
* @param ctx the user data (XML parser context)
* @param name the element name
* @param type the element type
* @param content the element value tree
*
* An element definition has been parsed
*/
XMLPUBFUNEXPORT void
xmlSAX2ElementDecl(void *ctx, const xmlChar * name, int type,
<API key> content)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef <API key>
xmlElementPtr elem = NULL;
#endif
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.xmlSAX2ElementDecl(%s, %d, ...)\n", name, type);
#endif
if (ctxt->inSubset == 1){
#ifdef <API key>
elem =
#endif
xmlAddElementDecl(&ctxt->vctxt, ctxt->myDoc->intSubset,
name, (xmlElementTypeVal) type, content);
}
else if (ctxt->inSubset == 2)
{
#ifdef <API key>
elem =
#endif
xmlAddElementDecl(&ctxt->vctxt, ctxt->myDoc->extSubset,
name, (xmlElementTypeVal) type, content);
}
else
{
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.xmlSAX2ElementDecl(%s) called while not in subset\n"),
name);
return;
}
#ifdef <API key>
if (elem == NULL)
ctxt->valid = 0;
if (ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &=
<API key>(&ctxt->vctxt, ctxt->myDoc, elem);
#endif /* <API key> */
}
/**
* xmlSAX2NotationDecl:
* @param ctx the user data (XML parser context)
* @param name The name of the notation
* @param publicId The public ID of the entity
* @param systemId The system ID of the entity
*
* What to do when a notation declaration has been parsed.
*/
XMLPUBFUNEXPORT void
xmlSAX2NotationDecl(void *ctx, const xmlChar *name,
const xmlChar *publicId, const xmlChar *systemId)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef <API key>
xmlNotationPtr nota = NULL;
#endif
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.xmlSAX2NotationDecl(%s, %s, %s)\n", name, publicId, systemId);
#endif
if ((publicId == NULL) && (systemId == NULL)) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.xmlSAX2NotationDecl(%s) externalID or PublicID missing\n"), name);
ctxt->valid = 0;
ctxt->wellFormed = 0;
return;
}
else if (ctxt->inSubset == 1)
{
#ifdef <API key>
nota =
#endif
xmlAddNotationDecl(&ctxt->vctxt, ctxt->myDoc->intSubset, name,
publicId, systemId);
}
else if (ctxt->inSubset == 2)
{
#ifdef <API key>
nota =
#endif
xmlAddNotationDecl(&ctxt->vctxt, ctxt->myDoc->extSubset, name,
publicId, systemId);
}
else
{
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.xmlSAX2NotationDecl(%s) called while not in subset\n"), name);
return;
}
#ifdef <API key>
if (nota == NULL)
ctxt->valid = 0;
if (ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
nota);
#endif /* <API key> */
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param name The name of the entity
* @param publicId The public ID of the entity
* @param systemId The system ID of the entity
* @param notationName the name of the notation
*
* What to do when an unparsed entity declaration is parsed
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx, const xmlChar *name,
const xmlChar *publicId, const xmlChar *systemId,
const xmlChar *notationName)
{
xmlEntityPtr ent;
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s, %s, %s)\n",
name, publicId, systemId, notationName);
#endif
if (ctxt->inSubset == 1)
{
ent = xmlAddDocEntity(ctxt->myDoc, name,
<API key>,
publicId, systemId, notationName);
if (!ent && ctxt->pedantic &&
ctxt->sax && ctxt->sax->warning)
{
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Entity(%s) already defined in the internal subset\n"), name);
}
if (ent && !ent->URI && systemId)
{
xmlChar *URI;
const char* base = NULL;
if (ctxt->input)
base = ctxt->input->filename;
if (!base)
base = ctxt->directory;
URI = xmlBuildURI(systemId, (const xmlChar *) base);
ent->URI = URI;
}
}
else if (ctxt->inSubset == 2)
{
ent = xmlAddDtdEntity(ctxt->myDoc, name,
<API key>,
publicId, systemId, notationName);
if (!ent && ctxt->pedantic &&
ctxt->sax && ctxt->sax->warning)
{
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Entity(%s) already defined in the external subset\n"), name);
}
if (ent && !ent->URI && systemId)
{
xmlChar *URI;
const char* base = NULL;
if (ctxt->input)
base = ctxt->input->filename;
if (!base)
base = ctxt->directory;
URI = xmlBuildURI(systemId, (const xmlChar*) base);
ent->URI = URI;
}
}
else if (ctxt->sax && ctxt->sax->error)
{
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.<API key>(%s) called while not in subset\n"), name);
}
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param loc A SAX Locator
*
* Receive the document locator at startup, actually <API key>
* Everything is available on the context, so this is useless in our case.
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx ATTRIBUTE_UNUSED, xmlSAXLocatorPtr loc ATTRIBUTE_UNUSED)
{
/* xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; */
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.<API key>()\n");
#endif
if(ctx) return; // just to use ctx
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
*
* called when the document start being processed.
*
* OOM: possible --> check OOM flag
*/
XMLPUBFUNEXPORT void <API key>(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlDocPtr doc = NULL;
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.<API key>()\n");
#endif
if (ctxt->html) {
#ifdef LIBXML_HTML_ENABLED
if (ctxt->myDoc == NULL)
doc = ctxt->myDoc = htmlNewDocNoDtD(NULL, NULL);
if (!ctxt->myDoc)
goto OOM;
#else
xmlGenericError(<API key>, EMBED_ERRTXT("libxml2 built without HTML support\n"));
ctxt->errNo = <API key>;
goto ERR;
#endif
} else { // not HTML
doc = ctxt->myDoc = xmlNewDoc(ctxt->version);
if (!doc)
goto OOM;
if (ctxt->encoding != NULL){
doc->encoding = xmlStrdup(ctxt->encoding);
if(! doc->encoding)
goto OOM;
}
//else
// doc->encoding = NULL; // it is NULL after xmlNewDoc
doc->standalone = ctxt->standalone;
if (ctxt->dictNames && doc) {
doc->dict = ctxt->dict;
xmlDictReference(doc->dict);
}
}
if ( /* (ctxt->myDoc != NULL) && : it's NOT NULL here */
!doc->URL &&
ctxt->input &&
ctxt->input->filename)
{
doc->URL = xmlCanonicPath((const xmlChar *) ctxt->input->filename);
if (!doc->URL)
doc->URL = xmlStrdup((const xmlChar *) ctxt->input->filename);
}
return;
OOM:
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("SAX.<API key>(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ERR:
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
/**
* xmlSAX2EndDocument:
* @param ctx the user data (XML parser context)
*
* called when the document end has been detected.
*/
XMLPUBFUNEXPORT void
xmlSAX2EndDocument(void *ctx)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.xmlSAX2EndDocument()\n");
#endif
#ifdef <API key>
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc);
#endif /* <API key> */
/*
* Grab the encoding if it was added on-the-fly
*/
if (ctxt->encoding &&
ctxt->myDoc &&
!ctxt->myDoc->encoding)
{
ctxt->myDoc->encoding = ctxt->encoding;
ctxt->encoding = NULL;
}
if (ctxt->inputTab[0]->encoding &&
ctxt->myDoc &&
!ctxt->myDoc->encoding)
{
ctxt->myDoc->encoding = xmlStrdup(ctxt->inputTab[0]->encoding);
}
if ((ctxt->charset != <API key>) &&
ctxt->myDoc &&
(ctxt->myDoc->charset == <API key>))
{
ctxt->myDoc->charset = ctxt->charset;
}
}
// Note: old (SAX1) handlers -- name is misleading
#if defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED)
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param fullname The attribute name, including namespace prefix
* @param value The attribute value
* @param prefix the prefix on the element node
*
* Handle an attribute that has been read by the parser.
* The default handling is to convert the attribute into an
* DOM subtree and past it in a new xmlAttr element added to
* the element.
*/
static void
<API key>(void *ctx, const xmlChar *fullname,
const xmlChar *value, const xmlChar *prefix ATTRIBUTE_UNUSED)
{
// DONE: Find and refactor all "namespace" variables to not match C++ keyword
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlAttrPtr ret;
xmlChar *name;
xmlChar *ns;
xmlChar *nval;
xmlNsPtr nameSpace;
/*
* Split the full name into a namespace prefix and the tag name
*/
name = xmlSplitQName(ctxt, fullname, &ns);
if ((name != NULL) && (name[0] == 0)) {
if (xmlStrEqual(ns, BAD_CAST "xmlns")) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("invalid namespace declaration '%s'\n"), fullname);
} else {
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Avoid attribute ending with ':' like '%s'\n"), fullname);
}
if (ns != NULL)
xmlFree(ns);
ns = NULL;
xmlFree(name);
name = xmlStrdup(fullname);
}
if (name == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,EMBED_ERRTXT("SAX.xmlSAX2StartElement(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
if (ns != NULL)
xmlFree(ns);
return;
}
#ifdef <API key>
ctxt->vctxt.valid = 1;
nval = <API key>(&ctxt->vctxt,
ctxt->myDoc, ctxt->node,
fullname, value);
if (ctxt->vctxt.valid != 1) {
ctxt->valid = 0;
}
if (nval != NULL)
value = nval;
#else
nval = NULL;
#endif /* <API key> */
/*
* Check whether it's a namespace definition
*/
if ((!ctxt->html) && (ns == NULL) &&
(name[0] == 'x') && (name[1] == 'm') && (name[2] == 'l') &&
(name[3] == 'n') && (name[4] == 's') && (name[5] == 0))
{
xmlNsPtr nsret;
xmlChar *val;
if (!ctxt->replaceEntities) {
ctxt->depth++;
val = <API key>(ctxt, value, XML_SUBSTITUTE_REF,0,0,0);
ctxt->depth
} else {
val = (xmlChar *) value;
}
if (val[0] != 0) {
xmlURIPtr uri;
uri = xmlParseURI((const char *)val);
if (uri == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("xmlns: %s not a valid URI\n"), val);
} else {
if (uri->scheme == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("xmlns: URI %s is not absolute\n"), val);
}
xmlFreeURI(uri);
}
}
/* a default namespace definition */
nsret = xmlNewNs(ctxt->node, val, NULL);
#ifdef <API key>
/*
* Validate also for namespace decls, they are attributes from
* an XML-1.0 perspective
*/
if (nsret != NULL &&
ctxt->validate &&
ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
{
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
ctxt->node, prefix, nsret, val);
}
#endif /* <API key> */
if (name != NULL)
xmlFree(name);
if (nval != NULL)
xmlFree(nval);
if (val != value)
xmlFree(val);
return;
}
if ((!ctxt->html) &&
(ns != NULL) &&
(ns[0] == 'x') && (ns[1] == 'm') && (ns[2] == 'l') &&
(ns[3] == 'n') && (ns[4] == 's') && (ns[5] == 0))
{
xmlNsPtr nsret;
xmlChar *val;
if (!ctxt->replaceEntities) {
ctxt->depth++;
val = <API key>(ctxt, value, XML_SUBSTITUTE_REF,
0,0,0);
ctxt->depth
if (val == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("SAX.xmlSAX2StartElement(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
xmlFree(ns);
if (name != NULL)
xmlFree(name);
return;
}
} else {
val = (xmlChar *) value;
}
if (val[0] == 0) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("Empty namespace name for prefix %s\n"), name);
}
if ((ctxt->pedantic != 0) && (val[0] != 0)) {
xmlURIPtr uri;
uri = xmlParseURI((const char *)val);
if (uri == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("xmlns:%s: %s not a valid URI\n"), name, value);
} else {
if (uri->scheme == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("xmlns:%s: URI %s is not absolute\n"), name, value);
}
xmlFreeURI(uri);
}
}
/* a standard namespace definition */
nsret = xmlNewNs(ctxt->node, val, name);
xmlFree(ns);
#ifdef <API key>
/*
* Validate also for namespace decls, they are attributes from
* an XML-1.0 perspective
*/
if (nsret != NULL && ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
ctxt->node, prefix, nsret, value);
#endif /* <API key> */
if (name != NULL)
xmlFree(name);
if (nval != NULL)
xmlFree(nval);
if (val != value)
xmlFree(val);
return;
}
if (ns != NULL) {
xmlAttrPtr prop;
nameSpace = xmlSearchNs(ctxt->myDoc, ctxt->node, ns);
if (nameSpace == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("Namespace prefix %s of attribute %s is not defined\n"),
ns, name);
}
prop = ctxt->node->properties;
while (prop != NULL) {
if (prop->ns != NULL) {
if ((xmlStrEqual(name, prop->name)) &&
((nameSpace == prop->ns) ||
(xmlStrEqual(nameSpace->href, prop->ns->href)))) {
ctxt->errNo = <API key>;
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("Attribute %s in %s redefined\n"),
name, nameSpace->href);
ctxt->wellFormed = 0;
if (ctxt->recovery == 0) ctxt->disableSAX = 1;
goto error;
}
}
prop = prop->next;
}
} else {
nameSpace = NULL;
}
ret = xmlNewNsPropEatName(ctxt->node, nameSpace, name, NULL);
if (ret != NULL) {
if ((ctxt->replaceEntities == 0) && (!ctxt->html)) {
xmlNodePtr tmp;
ret->children = <API key>(ctxt->myDoc, value);
tmp = ret->children;
while (tmp != NULL) {
tmp->parent = (xmlNodePtr) ret;
if (tmp->next == NULL)
ret->last = tmp;
tmp = tmp->next;
}
} else if (value != NULL) {
ret->children = xmlNewDocText(ctxt->myDoc, value);
ret->last = ret->children;
if (ret->children != NULL)
ret->children->parent = (xmlNodePtr) ret;
}
}
#ifdef <API key>
if ((!ctxt->html) && ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
{
/*
* If we don't substitute entities, the validation should be
* done on a value with replaced entities anyway.
*/
if (!ctxt->replaceEntities) {
xmlChar *val;
ctxt->depth++;
val = <API key>(ctxt, value, XML_SUBSTITUTE_REF,0,0,0);
ctxt->depth
if (val == NULL)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc, ctxt->node, ret, value);
else {
xmlChar *nvalnorm;
/*
* Do the last stage of the attribute normalization
* It need to be done twice ... it's an extra burden related
* to the ability to keep xmlSAX2References in attributes
*/
nvalnorm = <API key>(ctxt->myDoc, ctxt->node, fullname, val);
if (nvalnorm != NULL) {
xmlFree(val);
val = nvalnorm;
}
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc, ctxt->node, ret, val);
xmlFree(val);
}
} else {
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc, ctxt->node, ret, value);
}
} else
#endif /* <API key> */
if (((ctxt->loadsubset & XML_SKIP_IDS) == 0) &&
(((ctxt->replaceEntities == 0) && (ctxt->external != 2)) ||
((ctxt->replaceEntities != 0) && (ctxt->inSubset == 0)))) {
/*
* when validating, the ID registration is done at the attribute
* validation level. Otherwise we have to do specific handling here.
*/
if (xmlIsID(ctxt->myDoc, ctxt->node, ret))
xmlAddID(&ctxt->vctxt, ctxt->myDoc, value, ret);
else if (xmlIsRef(ctxt->myDoc, ctxt->node, ret))
xmlAddRef(&ctxt->vctxt, ctxt->myDoc, value, ret);
else if (xmlStrEqual(fullname, BAD_CAST "xml:id")) {
/*
* Add the xml:id value
*
* Open issue: normalization of the value.
*/
if (xmlValidateNCName(value, 1) != 0) {
xmlErrValid(ctxt, XML_DTD_XMLID_VALUE,
EMBED_ERRTXT("xml:id : attribute value %s is not an NCName\n"),
(const char *) value, NULL);
}
xmlAddID(&ctxt->vctxt, ctxt->myDoc, value, ret);
}
}
error:
if (nval != NULL)
xmlFree(nval);
if (ns != NULL)
xmlFree(ns);
}
/*
* <API key>:
*
* Check defaulted attributes from the DTD
*/
static void
<API key>(xmlParserCtxtPtr ctxt, const xmlChar *name,
const xmlChar *prefix, const xmlChar **atts) {
xmlElementPtr elemDecl;
const xmlChar *att;
int internal = 1;
int i;
elemDecl = <API key>(ctxt->myDoc->intSubset, name, prefix);
if (elemDecl == NULL) {
elemDecl = <API key>(ctxt->myDoc->extSubset, name, prefix);
internal = 0;
}
<API key>:
if (elemDecl != NULL) {
xmlAttributePtr attr = elemDecl->attributes;
/*
* Check against defaulted attributes from the external subset
* if the document is stamped as standalone
*/
if ((ctxt->myDoc->standalone == 1) &&
(ctxt->myDoc->extSubset != NULL) &&
(ctxt->validate)) {
while (attr != NULL) {
if ((attr->defaultValue != NULL) &&
(xmlGetDtdQAttrDesc(ctxt->myDoc->extSubset,
attr->elem, attr->name,
attr->prefix) == attr) &&
(xmlGetDtdQAttrDesc(ctxt->myDoc->intSubset,
attr->elem, attr->name,
attr->prefix) == NULL)) {
xmlChar *fulln;
if (attr->prefix != NULL) {
fulln = xmlStrdup(attr->prefix);
fulln = xmlStrcat(fulln, BAD_CAST ":");
fulln = xmlStrcat(fulln, attr->name);
} else {
fulln = xmlStrdup(attr->name);
}
/*
* Check that the attribute is not declared in the
* serialization
*/
att = NULL;
if (atts != NULL) {
i = 0;
att = atts[i];
while (att != NULL) {
if (xmlStrEqual(att, fulln))
break;
i += 2;
att = atts[i];
}
}
if (att == NULL) {
xmlErrValid(ctxt, <API key>,
EMBED_ERRTXT("standalone: attribute %s on %s defaulted from external subset\n"),
(const char *)fulln,
(const char *)attr->elem);
}
}
attr = attr->nexth;
}
}
/*
* Actually insert defaulted values when needed
*/
attr = elemDecl->attributes;
while (attr != NULL) {
/*
* Make sure that attributes redefinition occuring in the
* internal subset are not overriden by definitions in the
* external subset.
*/
if (attr->defaultValue != NULL) {
/*
* the element should be instantiated in the tree if:
* - this is a namespace prefix
* - the user required for completion in the tree
* like XSLT
* - there isn't already an attribute definition
* in the internal subset overriding it.
*/
if (((attr->prefix != NULL) &&
(xmlStrEqual(attr->prefix, BAD_CAST "xmlns"))) ||
((attr->prefix == NULL) &&
(xmlStrEqual(attr->name, BAD_CAST "xmlns"))) ||
(ctxt->loadsubset & XML_COMPLETE_ATTRS)) {
xmlAttributePtr tst;
tst = xmlGetDtdQAttrDesc(ctxt->myDoc->intSubset,
attr->elem, attr->name,
attr->prefix);
if ((tst == attr) || (tst == NULL)) {
xmlChar fn[50];
xmlChar *fulln;
fulln = xmlBuildQName(attr->name, attr->prefix, fn, 50);
if (fulln == NULL) {
if ((ctxt->sax != NULL) &&
(ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData,
EMBED_ERRTXT("SAX.xmlSAX2StartElement(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
/*
* Check that the attribute is not declared in the
* serialization
*/
att = NULL;
if (atts != NULL) {
i = 0;
att = atts[i];
while (att != NULL) {
if (xmlStrEqual(att, fulln))
break;
i += 2;
att = atts[i];
}
}
if (att == NULL) {
<API key>(ctxt, fulln,
attr->defaultValue, prefix);
}
if ((fulln != fn) && (fulln != attr->name))
xmlFree(fulln);
}
}
}
attr = attr->nexth;
}
if (internal == 1) {
elemDecl = <API key>(ctxt->myDoc->extSubset,
name, prefix);
internal = 0;
goto <API key>;
}
}
}
/**
* xmlSAX2StartElement:
* @param ctx the user data (XML parser context)
* @param fullname The element name, including namespace prefix
* @param atts An array of name/value attributes pairs, NULL terminated
*
* called when an opening tag has been processed.
*/
XMLPUBFUNEXPORT void
xmlSAX2StartElement(void *ctx, const xmlChar *fullname, const xmlChar **atts)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret;
xmlNodePtr parent = ctxt->node;
xmlNsPtr ns;
xmlChar *name;
xmlChar *prefix;
const xmlChar *att;
const xmlChar *value;
int i;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.xmlSAX2StartElement(%s)\n", fullname);
#endif
/*
* First check on validity:
*/
if (ctxt->validate && (ctxt->myDoc->extSubset == NULL) &&
((ctxt->myDoc->intSubset == NULL) ||
((ctxt->myDoc->intSubset->notations == NULL) &&
(ctxt->myDoc->intSubset->elements == NULL) &&
(ctxt->myDoc->intSubset->attributes == NULL) &&
(ctxt->myDoc->intSubset->entities == NULL)))) {
xmlErrValid(ctxt, XML_ERR_NO_DTD,
EMBED_ERRTXT("Validation failed: no DTD found !"), NULL, NULL);
ctxt->validate = 0;
}
/*
* Split the full name into a namespace prefix and the tag name
*/
name = xmlSplitQName(ctxt, fullname, &prefix);
/*
* Note : the namespace resolution is deferred until the end of the
* attributes parsing, since local namespace can be defined as
* an attribute at this level.
*/
ret = <API key>(ctxt->myDoc, NULL, name, NULL);
if (ret == NULL) {
if (prefix != NULL)
xmlFree(prefix);
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
if (ctxt->myDoc->children == NULL) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "Setting %s as root\n", name);
#endif
xmlAddChild((xmlNodePtr) ctxt->myDoc, (xmlNodePtr) ret);
} else if (parent == NULL) {
parent = ctxt->myDoc->children;
}
ctxt->nodemem = -1;
#ifdef <API key>
if (ctxt->linenumbers) {
if (ctxt->input != NULL) {
if (ctxt->input->line < 65535)
ret->line = (short) ctxt->input->line;
else
ret->line = 65535;
}
}
#endif
/*
* We are parsing a new node.
*/
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "pushing(%s)\n", name);
#endif
nodePush(ctxt, ret);
/*
* Link the child element
*/
if (parent != NULL) {
if (parent->type == XML_ELEMENT_NODE) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,"adding child %s to %s\n", name, parent->name);
#endif
xmlAddChild(parent, ret);
} else {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,"adding sibling %s to ", name);
xmlDebugDumpOneNode(stderr, parent, 0);
#endif
xmlAddSibling(parent, ret);
}
}
/*
* Insert all the defaulted attributes from the DTD especially namespaces
*/
if ((!ctxt->html) &&
((ctxt->myDoc->intSubset != NULL) || (ctxt->myDoc->extSubset != NULL)))
{
<API key>(ctxt, name, prefix, atts);
}
/*
* process all the attributes whose name start with "xmlns"
*/
if (atts != NULL) {
i = 0;
att = atts[i++];
value = atts[i++];
if (!ctxt->html) {
while ((att != NULL) && (value != NULL)) {
if ((att[0] == 'x') && (att[1] == 'm') && (att[2] == 'l') &&
(att[3] == 'n') && (att[4] == 's'))
<API key>(ctxt, att, value, prefix);
att = atts[i++];
value = atts[i++];
}
}
}
/*
* Search the namespace, note that since the attributes have been
* processed, the local namespaces are available.
*/
ns = xmlSearchNs(ctxt->myDoc, ret, prefix);
if ((ns == NULL) && (parent != NULL))
ns = xmlSearchNs(ctxt->myDoc, parent, prefix);
if ((prefix != NULL) && (ns == NULL)) {
ns = xmlNewNs(ret, NULL, prefix);
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,EMBED_ERRTXT("Namespace prefix %s is not defined\n"), prefix);
}
/*
* set the namespace node, making sure that if the default namspace
* is unbound on a parent we simply kee it NULL
*/
if ((ns != NULL) && (ns->href != NULL) &&
((ns->href[0] != 0) || (ns->prefix != NULL)))
xmlSetNs(ret, ns);
/*
* process all the other attributes
*/
if (atts != NULL) {
i = 0;
att = atts[i++];
value = atts[i++];
if (ctxt->html) {
while (att != NULL) {
<API key>(ctxt, att, value, NULL);
att = atts[i++];
value = atts[i++];
}
} else {
while ((att != NULL) && (value != NULL)) {
if ((att[0] != 'x') || (att[1] != 'm') || (att[2] != 'l') ||
(att[3] != 'n') || (att[4] != 's'))
<API key>(ctxt, att, value, NULL);
/*
* Next ones
*/
att = atts[i++];
value = atts[i++];
}
}
}
#ifdef <API key>
/*
* If it's the Document root, finish the DTD validation and
* check the document root element for validity
*/
if ((ctxt->validate) && (ctxt->vctxt.finishDtd == 0)) {
int chk;
chk = xmlValidateDtdFinal(&ctxt->vctxt, ctxt->myDoc);
if (chk <= 0)
ctxt->valid = 0;
if (chk < 0)
ctxt->wellFormed = 0;
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
ctxt->vctxt.finishDtd = 1;
}
#endif /* <API key> */
if (prefix != NULL)
xmlFree(prefix);
}
/**
* xmlSAX2EndElement:
* @param ctx the user data (XML parser context)
* @param name The element name
*
* called when the end of an element has been detected.
*/
XMLPUBFUNEXPORT void
xmlSAX2EndElement(void *ctx, const xmlChar *name ATTRIBUTE_UNUSED)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
//xmlParserNodeInfo node_info;
xmlNodePtr cur = ctxt->node;
#ifdef DEBUG_SAX
if (name == NULL)
xmlGenericError(<API key>, "SAX.xmlSAX2EndElement(NULL)\n");
else
xmlGenericError(<API key>, "SAX.xmlSAX2EndElement(%s)\n", name);
#endif
#ifdef <API key>
/* Capture end position and add node */
if (cur != NULL && ctxt->record_info) {
node_info.end_pos = ctxt->input->cur - ctxt->input->base;
node_info.end_line = ctxt->input->line;
node_info.node = cur;
<API key>(ctxt, &node_info);
}
#endif // <API key>
ctxt->nodemem = -1;
#ifdef <API key>
if (ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
cur);
#endif /* <API key> */
/*
* end of parsing of this node.
*/
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "popping(%s)\n", cur->name);
#endif
nodePop(ctxt);
}
#endif /* LIBXML_SAX1_ENABLED || LIBXML_HTML_ENABLE */
/*
* xmlSAX2TextNode:
* @param ctxt the parser context
* @param str the input string
* @param len the string length
*
* Remove the entities from an attribute value
*
* Returns the newly allocated string or NULL if not needed or error
*/
static xmlNodePtr
xmlSAX2TextNode(xmlParserCtxtPtr ctxt, const xmlChar *str, int len) {
LOAD_GS(ctxt)
xmlNodePtr ret;
const xmlChar *intern = NULL;
/*
* Allocate
*/
if (ctxt->freeElems != NULL) {
ret = ctxt->freeElems;
ctxt->freeElems = ret->next;
ctxt->freeElemsNr
} else {
ret = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
}
if (ret == NULL) {
OOM:
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("SAX.xmlSAX2Characters(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return(NULL);
}
/*
* intern the formatting blanks found between tags, or the
* very short strings
*/
if (ctxt->dictNames) {
xmlChar cur = str[len];
if ((len <= 3) && ((cur == '"') || (cur == '\'') ||
((cur == '<') && (str[len + 1] != '!'))))
{
intern = xmlDictLookup(ctxt->dict, str, len);
}
else if (IS_BLANK_CH(*str) && (len < 60) && (cur == '<') &&
(str[len + 1] != '!'))
{
int i;
for (i = 1;i < len;i++) {
if (!IS_BLANK_CH(str[i])) goto skip;
}
intern = xmlDictLookup(ctxt->dict, str, len);
}
}
skip:
memset(ret, 0, sizeof(xmlNode));
ret->type = XML_TEXT_NODE;
ret->name = xmlStringText;
if (intern == NULL)
{
ret->content = xmlStrndup(str, len);
{
if(OOM_FLAG)
{
if (ctxt->freeElems != NULL)
{
ctxt->freeElemsNr++;
ret->next = ctxt->freeElems;
ctxt->freeElems = ret;
}
else
{
xmlFreeNode(ret);
}
goto OOM;
}
}
}
else
ret->content = (xmlChar *) intern;
if ((<API key>) && (<API key>))
<API key>(ret);
return(ret);
}
#ifdef <API key>
/*
* <API key>:
* @param ctxt the parser context
* @param str the input string
* @param len the string length
*
* Remove the entities from an attribute value
*
* Returns the newly allocated string or NULL if not needed or error
*/
static xmlChar *
<API key>(xmlParserCtxtPtr ctxt, const xmlChar *str,
const xmlChar *end) {
const xmlChar *in;
xmlChar *ret;
in = str;
while (in < end)
if (*in++ == '&')
goto decode;
return(NULL);
decode:
ctxt->depth++;
ret = <API key>(ctxt, str, end - str,
XML_SUBSTITUTE_REF, 0,0,0);
ctxt->depth
return(ret);
}
#endif /* <API key> */
/**
* xmlSAX2AttributeNs:
* @param ctx the user data (XML parser context)
* @param localname the local name of the attribute
* @param prefix the attribute namespace prefix if available
* @param URI the attribute namespace name if available
* @param value Start of the attribute value
* @param valueend end of the attribute value
*
* Handle an attribute that has been read by the parser.
* The default handling is to convert the attribute into an
* DOM subtree and past it in a new xmlAttr element added to
* the element.
*/
static void
xmlSAX2AttributeNs(xmlParserCtxtPtr ctxt,
const xmlChar* localname,
const xmlChar* prefix,
const xmlChar* value,
const xmlChar* valueend)
{
LOAD_GS(ctxt)
xmlAttrPtr ret;
xmlNsPtr nameSpace = NULL;
xmlChar *dup = NULL;
/*
* Note: if prefix == NULL, the attribute is not in the default namespace
*/
if (prefix != NULL)
nameSpace = xmlSearchNs(ctxt->myDoc, ctxt->node, prefix);
/*
* allocate the node
*/
if (ctxt->freeAttrs != NULL)
{
ret = ctxt->freeAttrs;
ctxt->freeAttrs = ret->next;
ctxt->freeAttrsNr
memset(ret, 0, sizeof(xmlAttr));
ret->type = XML_ATTRIBUTE_NODE;
ret->parent = ctxt->node;
ret->doc = ctxt->myDoc;
ret->ns = nameSpace;
if (ctxt->dictNames)
ret->name = localname;
else
ret->name = xmlStrdup(localname);
if (ctxt->node->properties == NULL) {
ctxt->node->properties = ret;
} else {
xmlAttrPtr prev = ctxt->node->properties;
while (prev->next != NULL) prev = prev->next;
prev->next = ret;
ret->prev = prev;
}
if ((<API key>) && (<API key>))
<API key>((xmlNodePtr)ret);
} else {
if (ctxt->dictNames)
ret = xmlNewNsPropEatName(ctxt->node, nameSpace,
(xmlChar *) localname, NULL);
else
ret = xmlNewNsProp(ctxt->node, nameSpace, localname, NULL);
if (ret == NULL) {
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
}
if ((ctxt->replaceEntities == 0) && (!ctxt->html))
{
xmlNodePtr tmp;
/*
* We know that if there is an entity reference, then
* the string has been dup'ed and terminates with 0
* otherwise with ' or "
*/
if (*valueend != 0) {
tmp = xmlSAX2TextNode(ctxt, value, valueend - value);
if(OOM_FLAG)
{
xmlFree(dup);
return;
}
ret->children = tmp;
ret->last = tmp;
if (tmp != NULL) {
tmp->doc = ret->doc;
tmp->parent = (xmlNodePtr) ret;
}
} else {
ret->children = <API key>(ctxt->myDoc, value, valueend - value);
tmp = ret->children;
while (tmp != NULL) {
tmp->parent = (xmlNodePtr) ret;
if (tmp->next == NULL)
ret->last = tmp;
tmp = tmp->next;
}
}
} else if (value != NULL) {
xmlNodePtr tmp;
tmp = xmlSAX2TextNode(ctxt, value, valueend - value);
ret->children = tmp;
ret->last = tmp;
if (tmp != NULL) {
tmp->doc = ret->doc;
tmp->parent = (xmlNodePtr) ret;
}
}
#ifdef <API key>
if ((!ctxt->html) && ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset) {
/*
* If we don't substitute entities, the validation should be
* done on a value with replaced entities anyway.
*/
if (!ctxt->replaceEntities) {
dup = <API key>(ctxt, value, valueend);
if (dup == NULL) {
if (*valueend == 0) {
ctxt->valid &= <API key>(&ctxt->vctxt,
ctxt->myDoc, ctxt->node, ret, value);
} else {
/*
* That should already be normalized.
* cheaper to finally allocate here than duplicate
* entry points in the full validation code
*/
dup = xmlStrndup(value, valueend - value);
ctxt->valid &= <API key>(&ctxt->vctxt,
ctxt->myDoc, ctxt->node, ret, dup);
}
} else {
/*
* dup now contains a string of the flattened attribute
* content with entities substitued. Check if we need to
* apply an extra layer of normalization.
* It need to be done twice ... it's an extra burden related
* to the ability to keep references in attributes
*/
if (ctxt->attsSpecial != NULL) {
xmlChar *nvalnorm;
xmlChar fn[50];
xmlChar *fullname;
fullname = xmlBuildQName(localname, prefix, fn, 50);
if (fullname != NULL) {
ctxt->vctxt.valid = 1;
nvalnorm = <API key>(
&ctxt->vctxt, ctxt->myDoc,
ctxt->node, fullname, dup);
if (ctxt->vctxt.valid != 1)
ctxt->valid = 0;
if ((fullname != fn) && (fullname != localname))
xmlFree(fullname);
if (nvalnorm != NULL) {
xmlFree(dup);
dup = nvalnorm;
}
}
}
ctxt->valid &= <API key>(&ctxt->vctxt,
ctxt->myDoc, ctxt->node, ret, dup);
}
} else {
/*
* if entities already have been substitued, then
* the attribute as passed is already normalized
*/
dup = xmlStrndup(value, valueend - value);
ctxt->valid &= <API key>(&ctxt->vctxt,
ctxt->myDoc, ctxt->node, ret, dup);
}
} else
#endif /* <API key> */
if (((ctxt->loadsubset & XML_SKIP_IDS) == 0) &&
(((ctxt->replaceEntities == 0) && (ctxt->external != 2)) ||
((ctxt->replaceEntities != 0) && (ctxt->inSubset == 0)))) {
/*
* when validating, the ID registration is done at the attribute
* validation level. Otherwise we have to do specific handling here.
*/
if (xmlIsID(ctxt->myDoc, ctxt->node, ret)) {
/* might be worth duplicate entry points and not copy */
if (dup == NULL)
dup = xmlStrndup(value, valueend - value);
xmlAddID(&ctxt->vctxt, ctxt->myDoc, dup, ret);
} else if (xmlIsRef(ctxt->myDoc, ctxt->node, ret)) {
if (dup == NULL)
dup = xmlStrndup(value, valueend - value);
xmlAddRef(&ctxt->vctxt, ctxt->myDoc, dup, ret);
} else if ((prefix == ctxt->str_xml) &&
(localname[0] == 'i') && (localname[1] == 'd') &&
(localname[2] == 0)) {
/*
* Add the xml:id value
*
* Open issue: normalization of the value.
*/
if (dup == NULL)
dup = xmlStrndup(value, valueend - value);
if (xmlValidateNCName(dup, 1) != 0) {
xmlErrValid(ctxt, XML_DTD_XMLID_VALUE,
EMBED_ERRTXT("xml:id : attribute value %s is not an NCName\n"),
(const char *) dup, NULL);
}
xmlAddID(&ctxt->vctxt, ctxt->myDoc, dup, ret);
}
}
if (dup != NULL)
xmlFree(dup);
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param localname the local name of the element
* @param prefix the element namespace prefix if available
* @param URI the element namespace name if available
* @param nb_namespaces number of namespace definitions on that node
* @param namespaces pointer to the array of prefix/URI pairs namespace definitions
* @param nb_attributes the number of attributes on that node
* @param nb_defaulted the number of defaulted attributes.
* @param attributes pointer to the array of (localname/prefix/URI/value/end)
* attribute values.
*
* SAX2 callback when an element start has been detected by the parser.
* It provides the namespace informations for the element, as well as
* the new namespace declarations on the element.
*/
XMLPUBFUNEXPORT void
<API key>(void* ctx,
const xmlChar *localname,
const xmlChar *prefix,
const xmlChar *URI,
int nb_namespaces,
const xmlChar **namespaces,
int nb_attributes,
int nb_defaulted,
const xmlChar **attributes)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret;
xmlNodePtr parent = ctxt->node;
xmlNsPtr last = NULL, ns;
const xmlChar *uri, *pref;
int i, j;
LOAD_GS_SAFE_CTXT(ctxt)
/*
* First check on validity:
*/
if (ctxt->validate &&
(ctxt->myDoc->extSubset == NULL) &&
((ctxt->myDoc->intSubset == NULL)
||
((ctxt->myDoc->intSubset->notations == NULL) &&
(ctxt->myDoc->intSubset->elements == NULL) &&
(ctxt->myDoc->intSubset->attributes == NULL)&&
(ctxt->myDoc->intSubset->entities == NULL)
)
)
)
{
xmlErrValid(ctxt, XML_ERR_NO_DTD, EMBED_ERRTXT("Validation failed: no DTD found !"), NULL, NULL);
ctxt->validate = 0;
}
/*
* allocate the node
*/
if (ctxt->freeElems != NULL) {
ret = ctxt->freeElems;
ctxt->freeElems = ret->next;
ctxt->freeElemsNr
memset(ret, 0, sizeof(xmlNode));
ret->type = XML_ELEMENT_NODE;
if (ctxt->dictNames)
ret->name = localname;
else
ret->name = xmlStrdup(localname);
if ((<API key>) && (<API key>))
<API key>(ret);
} else {
if (ctxt->dictNames)
ret = <API key>(ctxt->myDoc, NULL,
(xmlChar *) localname, NULL);
else
ret = xmlNewDocNode(ctxt->myDoc, NULL, localname, NULL);
if (ret == NULL) {
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
}
#ifdef <API key>
if (ctxt->linenumbers) {
if (ctxt->input != NULL) {
if (ctxt->input->line < 65535)
ret->line = (short) ctxt->input->line;
else
ret->line = 65535;
}
}
#endif
if (ctxt->myDoc->children == NULL) {
xmlAddChild((xmlNodePtr) ctxt->myDoc, (xmlNodePtr) ret);
} else if (parent == NULL) {
parent = ctxt->myDoc->children;
}
/*
* Build the namespace list
*/
for (i = 0,j = 0;j < nb_namespaces;j++)
{
pref = namespaces[i++];
uri = namespaces[i++];
// NULL passed in order to avoid uniqueness check in xmlNewNs(),
ns = xmlNewNs(NULL, uri, pref);
// ... but then we need to link new Ns node manually
if (ns != NULL) {
if (last == NULL) {
ret->nsDef = last = ns;
} else {
last->next = ns;
last = ns;
}
if ((URI != NULL) && (prefix == pref))
ret->ns = ns;
} else {
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
//DONE: OOM: cleanup:
if(ctxt->myDoc->children != ret)
xmlFreeNode(ret); // it was not yet inserted in myDoc
return;
}
#ifdef <API key>
if (ctxt->validate && (!ctxt->html) && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
{
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc,
ret, prefix, ns, uri);
}
#endif /* <API key> */
} // for (i = 0,j = 0;j < nb_namespaces;j++)
ctxt->nodemem = -1;
/*
* We are parsing a new node.
*/
nodePush(ctxt, ret);
/*
* Link the child element
*/
if (parent != NULL) {
if (parent->type == XML_ELEMENT_NODE) {
xmlAddChild(parent, ret);
} else {
xmlAddSibling(parent, ret);
}
}
/*
* Insert the defaulted attributes from the DTD only if requested:
*/
if ((nb_defaulted != 0) &&
((ctxt->loadsubset & XML_COMPLETE_ATTRS) == 0))
{
nb_attributes -= nb_defaulted;
}
/*
* Search the namespace if it wasn't already found
*/
if ((URI != NULL) && (ret->ns == NULL)) {
ret->ns = xmlSearchNs(ctxt->myDoc, parent, prefix);
if (ret->ns == NULL) {
ns = xmlNewNs(ret, NULL, prefix);
if ((ctxt->sax != NULL) && (ctxt->sax->warning != NULL))
ctxt->sax->warning(ctxt->userData,
EMBED_ERRTXT("Namespace prefix %s was not found\n"), prefix);
}
}
/*
* process all the other attributes
*/
if (nb_attributes > 0) {
for (j = 0,i = 0;i < nb_attributes;i++,j+=5) {
xmlSAX2AttributeNs(ctxt, attributes[j], attributes[j+1],
attributes[j+3], attributes[j+4]);
if(OOM_FLAG)
{
return;
}
}
}
#ifdef <API key>
/*
* If it's the Document root, finish the DTD validation and
* check the document root element for validity
*/
if ((ctxt->validate) && (ctxt->vctxt.finishDtd == 0)) {
int chk;
chk = xmlValidateDtdFinal(&ctxt->vctxt, ctxt->myDoc);
if (chk <= 0)
ctxt->valid = 0;
if (chk < 0)
ctxt->wellFormed = 0;
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
ctxt->vctxt.finishDtd = 1;
}
#endif /* <API key> */
}
/**
* xmlSAX2EndElementNs:
* @param ctx the user data (XML parser context)
* @param localname the local name of the element
* @param prefix the element namespace prefix if available
* @param URI the element namespace name if available
*
* SAX2 callback when an element end has been detected by the parser.
* It provides the namespace informations for the element.
*/
XMLPUBFUNEXPORT void
xmlSAX2EndElementNs(void *ctx,
const xmlChar * localname ATTRIBUTE_UNUSED,
const xmlChar * prefix ATTRIBUTE_UNUSED,
const xmlChar * URI ATTRIBUTE_UNUSED)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
#if defined(<API key>) || defined(<API key>)
xmlNodePtr cur = ctxt->node;
#endif
#ifdef <API key>
{
xmlParserNodeInfo node_info;
/* Capture end position and add node */
if ((ctxt->record_info) && (cur != NULL)) {
node_info.end_pos = ctxt->input->cur - ctxt->input->base;
node_info.end_line = ctxt->input->line;
node_info.node = cur;
<API key>(ctxt, &node_info);
}
}
#endif
ctxt->nodemem = -1;
#ifdef <API key>
if (ctxt->validate && ctxt->wellFormed &&
ctxt->myDoc && ctxt->myDoc->intSubset)
ctxt->valid &= <API key>(&ctxt->vctxt, ctxt->myDoc, cur);
#endif /* <API key> */
/*
* end of parsing of this node.
*/
nodePop(ctxt);
}
/**
* xmlSAX2Reference:
* @param ctx the user data (XML parser context)
* @param name The entity name
*
* called when an entity xmlSAX2Reference is detected.
*/
XMLPUBFUNEXPORT void
xmlSAX2Reference(void *ctx, const xmlChar *name)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.xmlSAX2Reference(%s)\n", name);
#endif
if (name[0] == '
ret = xmlNewCharRef(ctxt->myDoc, name);
else
ret = xmlNewReference(ctxt->myDoc, name);
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,
"add xmlSAX2Reference %s to %s \n", name, ctxt->node->name);
#endif
xmlAddChild(ctxt->node, ret);
}
/**
* xmlSAX2Characters:
* @param ctx the user data (XML parser context)
* @param ch a xmlChar string
* @param len the number of xmlChar
*
* receiving some chars from the parser.
*/
XMLPUBFUNEXPORT void
xmlSAX2Characters(void *ctx, const xmlChar *ch, int len)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr lastChild;
/*
* SYMBIAN DEF130695 FIX : Ensuring that CTX(xml buffer context) is valid or not. The CTX is being considered
* here while receiving parsed characters using SAX parsing mechanism.
*/
if(ctx == NULL)
return;
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.xmlSAX2Characters(%.30s, %d)\n", ch, len);
#endif
/*
* Handle the data if any. If there is no child
* add it as content, otherwise if the last child is text,
* concatenate it, else create a new node of type text.
*/
if (ctxt->node == NULL) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "add chars: ctxt->node == NULL !\n");
#endif
return;
}
lastChild = ctxt->node->last;
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "add chars to %s \n", ctxt->node->name);
#endif
/*
* Here we needed an accelerator mechanism in case of very large
* elements. Use an attribute in the structure !!!
*/
if (lastChild == NULL) {
lastChild = xmlSAX2TextNode(ctxt, ch, len);
if (lastChild != NULL) {
ctxt->node->children = lastChild;
ctxt->node->last = lastChild;
lastChild->parent = ctxt->node;
lastChild->doc = ctxt->node->doc;
ctxt->nodelen = len;
ctxt->nodemem = len + 1;
}
} else {
int coalesceText = (lastChild != NULL) &&
(lastChild->type == XML_TEXT_NODE) &&
(lastChild->name == xmlStringText);
if ((coalesceText) && (ctxt->nodemem != 0)) {
/*
* The whole point of maintaining nodelen and nodemem,
* xmlTextConcat is too costly, i.e. compute length,
* reallocate a new buffer, move data, append ch. Here
* We try to minimaze realloc() uses and avoid copying
* and recomputing length over and over.
*/
if ((ctxt->nodemem == ctxt->nodelen + 1) &&
(xmlDictOwns(ctxt->dict, lastChild->content)))
{
lastChild->content = xmlStrdup(lastChild->content);
}
if (ctxt->nodelen + len >= ctxt->nodemem) {
xmlChar *newbuf;
int size;
size = ctxt->nodemem + len;
size *= 2;
newbuf = (xmlChar *) xmlRealloc(lastChild->content,size);
if (newbuf == NULL) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("SAX.xmlSAX2Characters(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return;
}
ctxt->nodemem = size;
lastChild->content = newbuf;
}
memcpy(&lastChild->content[ctxt->nodelen], ch, len);
ctxt->nodelen += len;
lastChild->content[ctxt->nodelen] = 0;
} else if (coalesceText) {
if (xmlTextConcat(lastChild, ch, len)) {
if ((ctxt->sax != NULL) && (ctxt->sax->error != NULL))
ctxt->sax->error(ctxt->userData, EMBED_ERRTXT("SAX.xmlSAX2Characters(): out of memory\n"));
ctxt->errNo = XML_ERR_NO_MEMORY;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
}
if (ctxt->node->children != NULL) {
ctxt->nodelen = xmlStrlen(lastChild->content);
ctxt->nodemem = ctxt->nodelen + 1;
}
} else {
/* Mixed content, first time */
lastChild = xmlSAX2TextNode(ctxt, ch, len);
if (lastChild != NULL) {
xmlAddChild(ctxt->node, lastChild);
if (ctxt->node->children != NULL) {
ctxt->nodelen = len;
ctxt->nodemem = len + 1;
}
}
}
}
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param ch a xmlChar string
* @param len the number of xmlChar
*
* receiving some ignorable whitespaces from the parser.
* UNUSED: by default the DOM building will use xmlSAX2Characters
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx ATTRIBUTE_UNUSED, const xmlChar *ch ATTRIBUTE_UNUSED, int len ATTRIBUTE_UNUSED)
{
/* xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx; */
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.<API key>(%.30s, %d)\n", ch, len);
#endif
if(ctx) return; // just to use ctx
}
/**
* <API key>:
* @param ctx the user data (XML parser context)
* @param target the target name
* @param data the PI data's
*
* A processing instruction has been parsed.
*/
XMLPUBFUNEXPORT void
<API key>(void *ctx,
const xmlChar *target,
const xmlChar *data)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret;
xmlNodePtr parent = ctxt->node;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,
"SAX.<API key>(%s, %s)\n", target, data);
#endif
ret = xmlNewPI(target, data);
if (!ret)
return;
parent = ctxt->node;
if (ctxt->inSubset == 1) {
xmlAddChild((xmlNodePtr) ctxt->myDoc->intSubset, ret);
return;
} else
if (ctxt->inSubset == 2) {
xmlAddChild((xmlNodePtr) ctxt->myDoc->extSubset, ret);
return;
}
if ((ctxt->myDoc->children == NULL) || (parent == NULL)) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,"Setting PI %s as root\n", target);
#endif
xmlAddChild((xmlNodePtr) ctxt->myDoc, (xmlNodePtr) ret);
return;
}
if (parent->type == XML_ELEMENT_NODE) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,
"adding PI %s child to %s\n", target, parent->name);
#endif
xmlAddChild(parent, ret);
} else {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>, "adding PI %s sibling to ", target);
xmlDebugDumpOneNode(stderr, parent, 0);
#endif
xmlAddSibling(parent, ret);
}
}
/**
* xmlSAX2Comment:
* @param ctx the user data (XML parser context)
* @param value the xmlSAX2Comment content
*
* A xmlSAX2Comment has been parsed.
*/
XMLPUBFUNEXPORT void
xmlSAX2Comment(void *ctx, const xmlChar *value)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret;
xmlNodePtr parent = ctxt->node;
#ifdef DEBUG_SAX
xmlGenericError(<API key>, "SAX.xmlSAX2Comment(%s)\n", value);
#endif
ret = xmlNewDocComment(ctxt->myDoc, value);
if (ret == NULL) return;
if (ctxt->inSubset == 1) {
xmlAddChild((xmlNodePtr) ctxt->myDoc->intSubset, ret);
return;
} else if (ctxt->inSubset == 2) {
xmlAddChild((xmlNodePtr) ctxt->myDoc->extSubset, ret);
return;
}
if ((ctxt->myDoc->children == NULL) || (parent == NULL)) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,
"Setting xmlSAX2Comment as root\n");
#endif
xmlAddChild((xmlNodePtr) ctxt->myDoc, (xmlNodePtr) ret);
return;
}
if (parent->type == XML_ELEMENT_NODE) {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,
"adding xmlSAX2Comment child to %s\n", parent->name);
#endif
xmlAddChild(parent, ret);
} else {
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,
"adding xmlSAX2Comment sibling to ");
xmlDebugDumpOneNode(stderr, parent, 0);
#endif
xmlAddSibling(parent, ret);
}
}
/**
* xmlSAX2CDataBlock:
* @param ctx the user data (XML parser context)
* @param value The pcdata content
* @param len the block length
*
* called when a pcdata block has been parsed
*/
XMLPUBFUNEXPORT void
xmlSAX2CDataBlock(void *ctx, const xmlChar *value, int len)
{
xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;
xmlNodePtr ret, lastChild;
#ifdef DEBUG_SAX
xmlGenericError(<API key>,"SAX.pcdata(%.10s, %d)\n", value, len);
#endif
lastChild = xmlGetLastChild(ctxt->node);
#ifdef DEBUG_SAX_TREE
xmlGenericError(<API key>,"add chars to %s \n", ctxt->node->name);
#endif
if ((lastChild != NULL) &&
(lastChild->type == <API key>))
{
xmlTextConcat(lastChild, value, len);
} else {
ret = xmlNewCDataBlock(ctxt->myDoc, value, len);
xmlAddChild(ctxt->node, ret);
}
}
#ifdef LIBXML_SAX1_ENABLED
/**
* <API key>:
* @param version the version, 1 or 2
*
* Set the default version of SAX used globally by the library.
* Note that this may not be a good thing to do from a library
* it is better to use xmlSAXVersion() to set up specifically the
* version for a given parsing context.
*
* Returns the previous value in case of success and -1 in case of error.
*/
XMLPUBFUNEXPORT int
<API key>(int version)
{
LOAD_GS_DIRECT
int ret = <API key>;
if ((version != 1) && (version != 2))
return(-1);
<API key> = version;
return(ret);
}
#endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUNEXPORT int
xmlSAXVersion(xmlSAXHandler *hdlr, int version)
{
if (hdlr == NULL) return(-1);
if (version == 2) {
hdlr->startElement = NULL;
hdlr->endElement = NULL;
hdlr->startElementNs = <API key>;
hdlr->endElementNs = xmlSAX2EndElementNs;
hdlr->serror = NULL;
hdlr->initialized = XML_SAX2_MAGIC;
#ifdef LIBXML_SAX1_ENABLED
} else if (version == 1) {
hdlr->startElement = xmlSAX2StartElement;
hdlr->endElement = xmlSAX2EndElement;
hdlr->initialized = 1;
#endif /* LIBXML_SAX1_ENABLED */
} else
return(-1);
hdlr->internalSubset = <API key>;
hdlr->externalSubset = <API key>;
hdlr->isStandalone = xmlSAX2IsStandalone;
hdlr->hasInternalSubset = <API key>;
hdlr->hasExternalSubset = <API key>;
hdlr->resolveEntity = <API key>;
hdlr->getEntity = xmlSAX2GetEntity;
hdlr->getParameterEntity = <API key>;
hdlr->entityDecl = xmlSAX2EntityDecl;
hdlr->attributeDecl = <API key>;
hdlr->elementDecl = xmlSAX2ElementDecl;
hdlr->notationDecl = xmlSAX2NotationDecl;
hdlr->unparsedEntityDecl = <API key>;
hdlr->setDocumentLocator = <API key>;
hdlr->startDocument = <API key>;
hdlr->endDocument = xmlSAX2EndDocument;
hdlr->reference = xmlSAX2Reference;
hdlr->characters = xmlSAX2Characters;
hdlr->cdataBlock = xmlSAX2CDataBlock;
hdlr->ignorableWhitespace = xmlSAX2Characters;
hdlr-><API key> = <API key>;
hdlr->comment = xmlSAX2Comment;
// XMLENGINE: MODIFIED CODE
// preprocessor directive is used for managing error callbacks
#ifdef _DEBUG_LIBXML
hdlr->warning = xmlParserWarning;
hdlr->error = xmlParserError;
hdlr->fatalError = xmlParserError;
#else
hdlr->warning = NULL;
hdlr->error = NULL;
hdlr->fatalError = NULL;
#endif
// XMLENGINE: BEGINE NEW CODE
// These should be nullified for DOMParser
hdlr->startPrefixMapping = NULL;
hdlr->endPrefixMapping = NULL;
// XMLENGINE: END NEW CODE
return(0);
}
#ifdef LIBXML_HTML_ENABLED
/**
* <API key>:
* @param hdlr the SAX handler
*
* Initialize the default HTML SAX2 handler
*/
void
<API key>(xmlSAXHandler *hdlr)
{
if(hdlr->initialized != 0)
return;
hdlr->internalSubset = <API key>;
hdlr->externalSubset = NULL;
hdlr->isStandalone = NULL;
hdlr->hasInternalSubset = NULL;
hdlr->hasExternalSubset = NULL;
hdlr->resolveEntity = NULL;
hdlr->getEntity = xmlSAX2GetEntity;
hdlr->getParameterEntity = NULL;
hdlr->entityDecl = NULL;
hdlr->attributeDecl = NULL;
hdlr->elementDecl = NULL;
hdlr->notationDecl = NULL;
hdlr->unparsedEntityDecl = NULL;
hdlr->setDocumentLocator = <API key>;
hdlr->startDocument = <API key>;
hdlr->endDocument = xmlSAX2EndDocument;
hdlr->startElement = xmlSAX2StartElement;
hdlr->endElement = xmlSAX2EndElement;
hdlr->reference = NULL;
hdlr->characters = xmlSAX2Characters;
hdlr->cdataBlock = xmlSAX2CDataBlock;
hdlr->ignorableWhitespace = <API key>;
hdlr-><API key> = NULL;
hdlr->comment = xmlSAX2Comment;
hdlr->warning = xmlParserWarning;
hdlr->error = xmlParserError;
hdlr->fatalError = xmlParserError;
hdlr->initialized = 1;
}
/**
* <API key>:
*
* Initialize the default SAX handler
*/
void
<API key>(void)
{
// XMLENGINE: disabled: HTML is never parsed
// <API key>((xmlSAXHandlerPtr) &<API key>);
}
#endif
/**
* <API key>:
* @param hdlr the SAX handler
* @param warning flag if non-zero sets the handler warning procedure
*
* Initialize the default XML SAX2 handler
*/
XMLPUBFUNEXPORT void
<API key>(xmlSAXHandler* hdlr, int warning)
{
LOAD_GS_DIRECT
if ((hdlr == NULL) || (hdlr->initialized != 0))
return;
xmlSAXVersion(hdlr, <API key>);
// Note: hdlr->warning is NULL after previous line
if(warning)
hdlr->warning = xmlParserWarning;
}
/**
* <API key>:
*
* Initialize the default SAX2 handler
*
* OOM: never
*/
XMLPUBFUNEXPORT void
<API key>(void)
{
#ifdef XMLENGINE_SAX1
#ifdef LIBXML_SAX1_ENABLED
xmlSAXVersion((xmlSAXHandlerPtr) &<API key>, 1);
#endif /* LIBXML_SAX1_ENABLED */
#endif
}
#ifdef LIBXML_DOCB_ENABLED
/**
* <API key>:
* @param hdlr the SAX handler
*
* Initialize the default DocBook SAX2 handler
*/
void
<API key>(xmlSAXHandler *hdlr)
{
if(hdlr->initialized != 0)
return;
hdlr->internalSubset = <API key>;
hdlr->externalSubset = NULL;
hdlr->isStandalone = xmlSAX2IsStandalone;
hdlr->hasInternalSubset = <API key>;
hdlr->hasExternalSubset = <API key>;
hdlr->resolveEntity = <API key>;
hdlr->getEntity = xmlSAX2GetEntity;
hdlr->getParameterEntity = NULL;
hdlr->entityDecl = xmlSAX2EntityDecl;
hdlr->attributeDecl = NULL;
hdlr->elementDecl = NULL;
hdlr->notationDecl = NULL;
hdlr->unparsedEntityDecl = NULL;
hdlr->setDocumentLocator = <API key>;
hdlr->startDocument = <API key>;
hdlr->endDocument = xmlSAX2EndDocument;
hdlr->startElement = xmlSAX2StartElement;
hdlr->endElement = xmlSAX2EndElement;
hdlr->reference = xmlSAX2Reference;
hdlr->characters = xmlSAX2Characters;
hdlr->cdataBlock = NULL;
hdlr->ignorableWhitespace = <API key>;
hdlr-><API key> = NULL;
hdlr->comment = xmlSAX2Comment;
hdlr->warning = xmlParserWarning;
hdlr->error = xmlParserError;
hdlr->fatalError = xmlParserError;
hdlr->initialized = 1;
}
/**
* <API key>:
*
* Initialize the default SAX handler
*/
void
<API key>(void)
{
<API key>((xmlSAXHandlerPtr) &<API key>);
}
#endif /* LIBXML_DOCB_ENABLED */ |
--TEST
mysqli fetch (bind_param + bind_result)
--SKIPIF
<?php
require_once('skipif.inc');
require_once('<API key>.inc');
?>
--FILE
<?php
require_once("connect.inc");
/*** test mysqli_connect 127.0.0.1 ***/
$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket);
if (!mysqli_query($link, "DROP TABLE IF EXISTS insert_read"))
printf("[001] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
$rc = mysqli_query($link,"CREATE TABLE insert_read(col1 tinyint, col2 smallint,
col3 int, col4 bigint,
col5 float, col6 double,
col7 date, col8 time,
col9 varbinary(10),
col10 varchar(50),
col11 char(20)) ENGINE=" . $engine);
if (!$rc)
printf("[002] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
if (!$stmt = mysqli_prepare($link, "INSERT INTO insert_read(col1,col10, col11, col6) VALUES (?,?,?,?)"))
printf("[003] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
<API key>($stmt, "issd", $c1, $c2, $c3, $c4);
$c1 = 1;
$c2 = "foo";
$c3 = "foobar";
$c4 = 3.14;
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
if (!$stmt = mysqli_prepare($link, "SELECT col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11 FROM insert_read"))
printf("[004] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
<API key>($stmt, $c1, $c2, $c3, $c4, $c5, $c6, $c7, $c8, $c9, $c10, $c11);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
$test = array($c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$c10,$c11);
var_dump($test);
mysqli_stmt_close($stmt);
mysqli_query($link, "DROP TABLE IF EXISTS insert_read");
mysqli_close($link);
print "done!";
?>
--CLEAN
<?php
require_once("connect.inc");
if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket))
printf("[c001] [%d] %s\n", <API key>(), <API key>());
if (!mysqli_query($link, "DROP TABLE IF EXISTS insert_read"))
printf("[c002] Cannot drop table, [%d] %s\n", mysqli_errno($link), mysqli_error($link));
mysqli_close($link);
?>
--EXPECTF
array(11) {
[0]=>
int(1)
[1]=>
NULL
[2]=>
NULL
[3]=>
NULL
[4]=>
NULL
[5]=>
float(3.14)
[6]=>
NULL
[7]=>
NULL
[8]=>
NULL
[9]=>
%unicode|string%(3) "foo"
[10]=>
%unicode|string%(6) "foobar"
}
done! |
import LodashWrapper from './_LodashWrapper';
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
export default wrapperCommit; |
#include "RCOutputRGBLed.h"
#include <AP_Math/AP_Math.h>
#include <SRV_Channel/SRV_Channel.h>
static const AP_HAL::HAL& hal = AP_HAL::get_HAL();
#define LED_OFF 0
#define LED_FULL_BRIGHT 255
#define LED_MEDIUM ((LED_FULL_BRIGHT / 5) * 4)
#define LED_DIM ((LED_FULL_BRIGHT / 5) * 2)
RCOutputRGBLed::RCOutputRGBLed(uint8_t red_channel, uint8_t green_channel, uint8_t blue_channel)
: RCOutputRGBLed(red_channel, green_channel, blue_channel, LED_OFF,
LED_FULL_BRIGHT, LED_MEDIUM, LED_DIM)
{
}
RCOutputRGBLed::RCOutputRGBLed(uint8_t red_channel, uint8_t green_channel,
uint8_t blue_channel, uint8_t led_off,
uint8_t led_full, uint8_t led_medium,
uint8_t led_dim)
: RGBLed(led_off, led_full, led_medium, led_dim)
, _red_channel(red_channel)
, _green_channel(green_channel)
, _blue_channel(blue_channel)
{
}
bool RCOutputRGBLed::hw_init()
{
hal.rcout->enable_ch(_red_channel);
hal.rcout->enable_ch(_green_channel);
hal.rcout->enable_ch(_blue_channel);
return true;
}
bool RCOutputRGBLed::hw_set_rgb(uint8_t red, uint8_t green, uint8_t blue)
{
const uint16_t freq_motor = hal.rcout->get_freq(0);
const uint16_t freq = hal.rcout->get_freq(_red_channel);
const uint16_t usec_period = hz_to_usec(freq);
if (freq_motor != freq) {
/*
* keep at same frequency as the first RCOutput channel, some RCOutput
* drivers can not operate in different frequency between channels
*/
const uint32_t mask = 1 << _red_channel | 1 << _green_channel
| 1 << _blue_channel;
hal.rcout->set_freq(mask, freq_motor);
}
uint16_t usec_duty = usec_period * red / _led_bright;
SRV_Channels::set_output_pwm_chan(_red_channel, usec_duty);
usec_duty = usec_period * green / _led_bright;
SRV_Channels::set_output_pwm_chan(_green_channel, usec_duty);
usec_duty = usec_period * blue / _led_bright;
SRV_Channels::set_output_pwm_chan(_blue_channel, usec_duty);
return true;
} |
/** @file WhisperHost.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <mutex>
#include <array>
#include <set>
#include <memory>
#include <utility>
#include <libdevcore/RLP.h>
#include <libdevcore/Worker.h>
#include <libdevcore/Guards.h>
#include <libdevcore/SHA3.h>
#include "Common.h"
#include "WhisperPeer.h"
#include "Interface.h"
#include "BloomFilter.h"
namespace dev
{
namespace shh
{
static const Topics EmptyTopics;
class WhisperHost: public HostCapability<WhisperPeer>, public Interface, public Worker
{
friend class WhisperPeer;
public:
WhisperHost(bool _storeMessagesInDB = false);
virtual ~WhisperHost();
unsigned protocolVersion() const { return <API key>; }
void cleanup(); ///< remove old messages
std::map<h256, Envelope> all() const { dev::ReadGuard l(x_messages); return m_messages; }
<API key> bloom() const { dev::Guard l(m_filterLock); return m_bloom; }
virtual void inject(Envelope const& _e, WhisperPeer* _from = nullptr) override;
virtual Topics const& fullTopics(unsigned _id) const override { try { return m_filters.at(m_watches.at(_id).id).full; } catch (...) { return EmptyTopics; } }
virtual unsigned installWatch(Topics const& _filter) override;
virtual void uninstallWatch(unsigned _watchId) override;
virtual h256s peekWatch(unsigned _watchId) const override { dev::Guard l(m_filterLock); try { return m_watches.at(_watchId).changes; } catch (...) { return h256s(); } }
virtual h256s checkWatch(unsigned _watchId) override;
virtual h256s watchMessages(unsigned _watchId) override; ///< returns IDs of messages, which match specific watch criteria
virtual Envelope envelope(h256 _m) const override { try { dev::ReadGuard l(x_messages); return m_messages.at(_m); } catch (...) { return Envelope(); } }
protected:
virtual void doWork() override;
void <API key>();
bool isWatched(Envelope const& _e) const;
private:
virtual void onStarting() override { startWorking(); }
virtual void onStopping() override { stopWorking(); }
void streamMessage(h256 _m, RLPStream& _s) const;
void saveMessagesToBD();
void loadMessagesFromBD();
mutable dev::SharedMutex x_messages;
std::map<h256, Envelope> m_messages;
std::multimap<unsigned, h256> m_expiryQueue;
mutable dev::Mutex m_filterLock;
std::map<h256, InstalledFilter> m_filters;
std::map<unsigned, ClientWatch> m_watches;
TopicBloomFilter m_bloom;
bool m_storeMessagesInDB; ///< needed for tests and other special cases
};
}
} |
class CreateSysSettings < ActiveRecord::Migration
def up
create_table :sys_settings do |t|
t.string :name
t.text :value
t.integer :sort_no
t.text :extra_value
t.timestamps
end
end
def down
drop_table :sys_settings
end
end |
package org.dvb.dsmcc;
public class StreamEvent extends java.util.EventObject {
public StreamEvent(DSMCCStreamEvent source, long npt, String name,
int eventId, byte[] eventData)
{
super(source);
this.source = source;
this.npt = npt;
this.name = name;
this.eventId = eventId;
this.eventData = eventData;
}
public Object getSource()
{
return source;
}
public String getEventName()
{
return name;
}
public int getEventId()
{
return eventId;
}
public long getEventNPT()
{
return npt;
}
public byte[] getEventData()
{
return eventData;
}
private DSMCCStreamEvent source;
private long npt;
private String name;
private int eventId;
private byte[] eventData;
private static final long serialVersionUID = -<API key>;
} |
@echo off
set CLASSPATH=build
for %%f in (lib\*.jar) do call add_to_classpath.bat %%f
for %%f in (p:\jonathan\jdbc\*.jar) do call add_to_classpath.bat %%f
echo %CLASSPATH% |
#include "testutil.hpp"
#include "../include/zmq_utils.h"
// Asynchronous client-to-server (DEALER to ROUTER) - pure libzmq
// While this example runs in a single process, that is to make
// it easier to start and stop the example. Each task may have its own
// context and conceptually acts as a separate process. To have this
// behaviour, it is necessary to replace the inproc transport of the
// control socket by a tcp transport.
// This is our client task
// It connects to the server, and then sends a request once per second
// It collects responses as they arrive, and it prints them out. We will
// run several client tasks in parallel, each with a different random ID.
#define CONTENT_SIZE 13
#define CONTENT_SIZE_MAX 32
#define ID_SIZE 10
#define ID_SIZE_MAX 32
#define QT_WORKERS 5
#define QT_CLIENTS 3
#define is_verbose 0
static void
client_task (void *ctx)
{
void *client = zmq_socket (ctx, ZMQ_DEALER);
assert (client);
// Control socket receives terminate command from main over inproc
void *control = zmq_socket (ctx, ZMQ_SUB);
assert (control);
int rc = zmq_setsockopt (control, ZMQ_SUBSCRIBE, "", 0);
assert (rc == 0);
int linger = 0;
rc = zmq_setsockopt (control, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_connect (control, "inproc://control");
assert (rc == 0);
char content [CONTENT_SIZE_MAX];
// Set random identity to make tracing easier
char identity [ID_SIZE];
sprintf (identity, "%04X-%04X", rand() % 0xFFFF, rand() % 0xFFFF);
rc = zmq_setsockopt (client, ZMQ_IDENTITY, identity, ID_SIZE); // includes '\0' as an helper for printf
assert (rc == 0);
linger = 0;
rc = zmq_setsockopt (client, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_connect (client, "tcp://127.0.0.1:5563");
assert (rc == 0);
zmq_pollitem_t items [] = { { client, 0, ZMQ_POLLIN, 0 }, { control, 0, ZMQ_POLLIN, 0 } };
int request_nbr = 0;
bool run = true;
while (run) {
// Tick once per 200 ms, pulling in arriving messages
int centitick;
for (centitick = 0; centitick < 20; centitick++) {
zmq_poll (items, 2, 10);
if (items [0].revents & ZMQ_POLLIN) {
int rcvmore;
size_t sz = sizeof (rcvmore);
rc = zmq_recv (client, content, CONTENT_SIZE_MAX, 0);
assert (rc == CONTENT_SIZE);
if (is_verbose) printf("client receive - identity = %s content = %s\n", identity, content);
// Check that message is still the same
assert (memcmp (content, "request #", 9) == 0);
rc = zmq_getsockopt (client, ZMQ_RCVMORE, &rcvmore, &sz);
assert (rc == 0);
assert (!rcvmore);
}
if (items [1].revents & ZMQ_POLLIN) {
rc = zmq_recv (control, content, CONTENT_SIZE_MAX, 0);
if (is_verbose) printf("client receive - identity = %s command = %s\n", identity, content);
if (memcmp (content, "TERMINATE", 9) == 0) {
run = false;
break;
}
}
}
sprintf(content, "request #%03d", ++request_nbr); // CONTENT_SIZE
rc = zmq_send (client, content, CONTENT_SIZE, 0);
assert (rc == CONTENT_SIZE);
}
rc = zmq_close (client);
assert (rc == 0);
rc = zmq_close (control);
assert (rc == 0);
}
// This is our server task.
// It uses the multithreaded server model to deal requests out to a pool
// of workers and route replies back to clients. One worker can handle
// one request at a time but one client can talk to multiple workers at
// once.
static void server_worker (void *ctx);
void
server_task (void *ctx)
{
// Frontend socket talks to clients over TCP
void *frontend = zmq_socket (ctx, ZMQ_ROUTER);
assert (frontend);
int linger = 0;
int rc = zmq_setsockopt (frontend, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_bind (frontend, "tcp://127.0.0.1:5563");
assert (rc == 0);
// Backend socket talks to workers over inproc
void *backend = zmq_socket (ctx, ZMQ_DEALER);
assert (backend);
rc = zmq_setsockopt (backend, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_bind (backend, "inproc://backend");
assert (rc == 0);
// Control socket receives terminate command from main over inproc
void *control = zmq_socket (ctx, ZMQ_SUB);
assert (control);
rc = zmq_setsockopt (control, ZMQ_SUBSCRIBE, "", 0);
assert (rc == 0);
rc = zmq_setsockopt (control, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_connect (control, "inproc://control");
assert (rc == 0);
// Launch pool of worker threads, precise number is not critical
int thread_nbr;
void* threads [5];
for (thread_nbr = 0; thread_nbr < QT_WORKERS; thread_nbr++)
threads[thread_nbr] = zmq_threadstart (&server_worker, ctx);
// Connect backend to frontend via a proxy
zmq_proxy_steerable (frontend, backend, NULL, control);
for (thread_nbr = 0; thread_nbr < QT_WORKERS; thread_nbr++)
zmq_threadclose (threads[thread_nbr]);
rc = zmq_close (frontend);
assert (rc == 0);
rc = zmq_close (backend);
assert (rc == 0);
rc = zmq_close (control);
assert (rc == 0);
}
// Each worker task works on one request at a time and sends a random number
// of replies back, with random delays between replies:
// The comments in the first column, if suppressed, makes it a poller version
static void
server_worker (void *ctx)
{
void *worker = zmq_socket (ctx, ZMQ_DEALER);
assert (worker);
int linger = 0;
int rc = zmq_setsockopt (worker, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_connect (worker, "inproc://backend");
assert (rc == 0);
// Control socket receives terminate command from main over inproc
void *control = zmq_socket (ctx, ZMQ_SUB);
assert (control);
rc = zmq_setsockopt (control, ZMQ_SUBSCRIBE, "", 0);
assert (rc == 0);
rc = zmq_setsockopt (control, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_connect (control, "inproc://control");
assert (rc == 0);
char content [CONTENT_SIZE_MAX]; // bigger than what we need to check that
char identity [ID_SIZE_MAX]; // the size received is the size sent
bool run = true;
while (run) {
rc = zmq_recv (control, content, CONTENT_SIZE_MAX, ZMQ_DONTWAIT); // usually, rc == -1 (no message)
if (rc > 0) {
if (is_verbose)
printf("server_worker receives command = %s\n", content);
if (memcmp (content, "TERMINATE", 9) == 0)
run = false;
}
// The DEALER socket gives us the reply envelope and message
// if we don't poll, we have to use ZMQ_DONTWAIT, if we poll, we can block-receive with 0
rc = zmq_recv (worker, identity, ID_SIZE_MAX, ZMQ_DONTWAIT);
if (rc == ID_SIZE) {
rc = zmq_recv (worker, content, CONTENT_SIZE_MAX, 0);
assert (rc == CONTENT_SIZE);
if (is_verbose)
printf ("server receive - identity = %s content = %s\n", identity, content);
// Send 0..4 replies back
int reply, replies = rand() % 5;
for (reply = 0; reply < replies; reply++) {
// Sleep for some fraction of a second
msleep (rand () % 10 + 1);
// Send message from server to client
rc = zmq_send (worker, identity, ID_SIZE, ZMQ_SNDMORE);
assert (rc == ID_SIZE);
rc = zmq_send (worker, content, CONTENT_SIZE, 0);
assert (rc == CONTENT_SIZE);
}
}
}
rc = zmq_close (worker);
assert (rc == 0);
rc = zmq_close (control);
assert (rc == 0);
}
// The main thread simply starts several clients and a server, and then
// waits for the server to finish.
int main (void)
{
<API key> ();
void *ctx = zmq_ctx_new ();
assert (ctx);
// Control socket receives terminate command from main over inproc
void *control = zmq_socket (ctx, ZMQ_PUB);
assert (control);
int linger = 0;
int rc = zmq_setsockopt (control, ZMQ_LINGER, &linger, sizeof (linger));
assert (rc == 0);
rc = zmq_bind (control, "inproc://control");
assert (rc == 0);
void *threads [QT_CLIENTS + 1];
for (int i = 0; i < QT_CLIENTS; i++)
threads[i] = zmq_threadstart (&client_task, ctx);
threads[QT_CLIENTS] = zmq_threadstart (&server_task, ctx);
msleep (500); // Run for 500 ms then quit
rc = zmq_send (control, "TERMINATE", 9, 0);
assert (rc == 9);
rc = zmq_close (control);
assert (rc == 0);
for (int i = 0; i < QT_CLIENTS + 1; i++)
zmq_threadclose (threads[i]);
rc = zmq_ctx_term (ctx);
assert (rc == 0);
return 0;
} |
#ifndef KHELPMENU_H
#define KHELPMENU_H
#include <kdeui_export.h>
#include <QtCore/QObject>
#include <QtCore/QString>
class KActionCollection;
class KMenu;
class QWidget;
class QAction;
class KAboutData;
class KHelpMenuPrivate;
class KDEUI_EXPORT KHelpMenu : public QObject
{
Q_OBJECT
public:
/**
* Constructor.
*
* @param parent The parent of the dialog boxes. The boxes are modeless
* and will be centered with respect to the parent.
* @param aboutAppText User definable string that is used in the
* default application dialog box.
* @param showWhatsThis Decides whether a "Whats this" entry will be
* added to the dialog.
*
*/
explicit KHelpMenu( QWidget *parent=0, const QString &aboutAppText=QString(),
bool showWhatsThis=true );
/**
* Constructor.
*
* This alternative constructor is mainly useful if you want to
* overide the standard actions (aboutApplication(), aboutKDE(),
* helpContents(), reportBug, and optionally whatsThis).
*
* @param parent The parent of the dialog boxes. The boxes are modeless
* and will be centered with respect to the parent.
* @param aboutData User and app data used in the About app dialog
* @param showWhatsThis Decides whether a "Whats this" entry will be
* added to the dialog.
* @param actions KActionCollection that is used instead of the
* standard actions.
*
*/
KHelpMenu( QWidget *parent, const KAboutData *aboutData,
bool showWhatsThis=true, KActionCollection *actions = 0 );
/**
* Destructor
*
* Destroys dialogs and the menu pointer retuned by menu
*/
~KHelpMenu();
/**
* Returns a popup menu you can use in the menu bar or where you
* need it.
*
* The returned menu is configured with an icon, a title and
* menu entries. Therefore adding the returned pointer to your menu
* is enougth to have access to the help menu.
*
* Note: This method will only create one instance of the menu. If
* you call this method twice or more the same pointer is returned.
*/
KMenu *menu();
enum MenuId
{
menuHelpContents = 0,
menuWhatsThis = 1,
menuAboutApp = 2,
menuAboutKDE = 3,
menuReportBug = 4,
menuSwitchLanguage = 5
};
/**
* Returns the QAction * associated with the given parameter
* Will return NULL pointers if menu() has not been called
*
* @param id The id of the action of which you want to get QAction *
*/
QAction *action( MenuId id ) const;
public Q_SLOTS:
/**
* Opens the help page for the application. The application name is
* used as a key to determine what to display and the system will attempt
* to open \<appName\>/index.html.
*/
void appHelpActivated();
/**
* Activates What's This help for the application.
*/
void <API key>();
/**
* Opens an application specific dialog box.
*
* The method will try to open the about box using the following steps:
* - If the <API key>() signal is connected, then it will be called.
* This means there is an application defined aboutBox.
* - If the aboutData was set in the constructor a <API key> will be created.
* - Else a default about box using the aboutAppText from the constructor will be created.
*/
void aboutApplication();
/**
* Opens the standard "About KDE" dialog box.
*/
void aboutKDE();
/**
* Opens the standard "Report Bugs" dialog box.
*/
void reportBug();
/**
* Opens the changing default application language dialog box.
*/
void <API key>();
private Q_SLOTS:
/**
* Connected to the menu pointer (if created) to detect a delete
* operation on the pointer. You should not delete the pointer in your
* code yourself. Let the KHelpMenu destructor do the job.
*/
void menuDestroyed();
/**
* Connected to the dialogs (about kde and bug report) to detect
* when they are finished.
*/
void dialogFinished();
/**
* This slot will delete a dialog (about kde or bug report) if the
* dialog pointer is not zero and the dialog is not visible. This
* slot is activated by a one shot timer started in dialogHidden
*/
void timerExpired();
Q_SIGNALS:
/**
* This signal is emitted from aboutApplication() if no
* "about application" string has been defined. The standard
* application specific dialog box that is normally activated in
* aboutApplication() will not be displayed when this signal
* is emitted.
*/
void <API key>();
private:
KHelpMenuPrivate *const d;
};
#endif |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _simpleAssign = require('simple-assign');
var _simpleAssign2 = <API key>(_simpleAssign);
var _react = require('react');
var _react2 = <API key>(_react);
var _propTypes = require('../utils/propTypes');
var _propTypes2 = <API key>(_propTypes);
var _transitions = require('../styles/transitions');
var _transitions2 = <API key>(_transitions);
function <API key>(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function <API key>(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function <API key>(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function getStyles(props, context) {
var circle = props.circle;
var rounded = props.rounded;
var transitionEnabled = props.transitionEnabled;
var zDepth = props.zDepth;
var _context$muiTheme = context.muiTheme;
var baseTheme = _context$muiTheme.baseTheme;
var paper = _context$muiTheme.paper;
return {
root: {
color: paper.color,
backgroundColor: paper.backgroundColor,
transition: transitionEnabled && _transitions2.default.easeOut(),
boxSizing: 'border-box',
fontFamily: baseTheme.fontFamily,
<API key>: 'rgba(0,0,0,0)', // Remove mobile color flashing (deprecated)
boxShadow: paper.zDepthShadows[zDepth - 1], // No shadow for 0 depth papers
borderRadius: circle ? '50%' : rounded ? '2px' : '0px'
}
};
}
var Paper = function (_Component) {
_inherits(Paper, _Component);
function Paper() {
_classCallCheck(this, Paper);
return <API key>(this, Object.getPrototypeOf(Paper).apply(this, arguments));
}
_createClass(Paper, [{
key: 'render',
value: function render() {
var _props = this.props;
var children = _props.children;
var style = _props.style;
var other = <API key>(_props, ['children', 'style']);
var prepareStyles = this.context.muiTheme.prepareStyles;
var styles = getStyles(this.props, this.context);
return _react2.default.createElement(
'div',
_extends({}, other, { style: prepareStyles((0, _simpleAssign2.default)(styles.root, style)) }),
children
);
}
}]);
return Paper;
}(_react.Component);
Paper.propTypes = {
/**
* Children passed into the paper element.
*/
children: _react.PropTypes.node,
/**
* Set to true to generate a circlular paper container.
*/
circle: _react.PropTypes.bool,
/**
* By default, the paper container will have a border radius.
* Set this to false to generate a container with sharp corners.
*/
rounded: _react.PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: _react.PropTypes.object,
/**
* Set to false to disable CSS transitions for the paper element.
*/
transitionEnabled: _react.PropTypes.bool,
/**
* This number represents the zDepth of the paper shadow.
*/
zDepth: _propTypes2.default.zDepth
};
Paper.defaultProps = {
circle: false,
rounded: true,
transitionEnabled: true,
zDepth: 1
};
Paper.contextTypes = {
muiTheme: _react.PropTypes.object.isRequired
};
exports.default = Paper; |
// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited -triple x86_64-apple-darwin -std=c++11 %s -o - | FileCheck %s
enum class A { A1=1 }; // underlying type is int by default
enum class B: unsigned long { B1=1 }; // underlying type is unsigned long
enum C { C1 = 1 };
enum D : short; // enum forward declaration
enum Z : int;
A a;
B b;
C c;
D d;
// CHECK: !DICompositeType(tag: <API key>, name: "A"
// CHECK-SAME: line: 3
// CHECK-SAME: baseType: ![[INT:[0-9]+]]
// CHECK-SAME: size: 32
// CHECK-NOT: offset:
// CHECK-NOT: flags:
// CHECK-SAME: ){{$}}
// CHECK: ![[INT]] = !DIBasicType(name: "int"
// CHECK: !DICompositeType(tag: <API key>, name: "B"
// CHECK-SAME: line: 4
// CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
// CHECK-SAME: size: 64
// CHECK-NOT: offset:
// CHECK-NOT: flags:
// CHECK-SAME: ){{$}}
// CHECK: ![[ULONG]] = !DIBasicType(name: "long unsigned int"
// CHECK: !DICompositeType(tag: <API key>, name: "C"
// CHECK-SAME: line: 5
// CHECK-NOT: baseType:
// CHECK-SAME: size: 32
// CHECK-NOT: offset:
// CHECK-NOT: flags:
// CHECK-SAME: ){{$}}
namespace PR14029 {
// Make sure this doesn't crash/assert.
template <typename T> struct Test {
enum class Tag {
test = 0
};
Test() {
auto t = Tag::test;
}
Tag tag() const { return static_cast<Tag>(1); }
};
Test<int> t;
}
namespace test2 {
// FIXME: this should just be a declaration under -<API key>
// CHECK: !DICompositeType(tag: <API key>, name: "E"
// CHECK-SAME: scope: [[TEST2:![0-9]+]]
// CHECK-SAME: elements: [[TEST_ENUMS:![0-9]+]]
// CHECK-SAME: identifier: "_ZTSN5test21EE"
// CHECK: [[TEST2]] = !DINamespace(name: "test2"
// CHECK: [[TEST_ENUMS]] = !{[[TEST_E:![0-9]*]]}
// CHECK: [[TEST_E]] = !DIEnumerator(name: "e", value: 0)
enum E : int;
void func(E *) {
}
enum E : int { e };
}
namespace test3 {
// FIXME: this should just be a declaration under -<API key>
// CHECK: !DICompositeType(tag: <API key>, name: "E"
// CHECK-SAME: scope: [[TEST3:![0-9]+]]
// CHECK-SAME: elements: [[TEST_ENUMS]]
// CHECK-SAME: identifier: "_ZTSN5test31EE"
// CHECK: [[TEST3]] = !DINamespace(name: "test3"
enum E : int { e };
void func(E *) {
}
}
namespace test4 {
// CHECK: !DICompositeType(tag: <API key>, name: "E"
// CHECK-SAME: scope: [[TEST4:![0-9]+]]
// CHECK-SAME: elements: [[TEST_ENUMS]]
// CHECK-SAME: identifier: "_ZTSN5test41EE"
// CHECK: [[TEST4]] = !DINamespace(name: "test4"
enum E : int;
void f1(E *) {
}
enum E : int { e };
void f2(E) {
}
}
// CHECK: !DICompositeType(tag: <API key>, name: "D"
// CHECK-SAME: line: 6
// CHECK-SAME: size: 16
// CHECK-NOT: offset:
// CHECK-SAME: flags: DIFlagFwdDecl
// CHECK: !DICompositeType(tag: <API key>, name: "Z"
// CHECK-NOT: scope:
// CHECK-SAME: flags: DIFlagFwdDecl
void fz() { Z z; }
namespace test5 {
// CHECK: [[TEST5:![0-9]+]] = !DINamespace(name: "test5"
// CHECK: !DICompositeType(tag: <API key>, name: "E"
// CHECK-SAME: scope: [[TEST5]]
// CHECK-SAME: flags: DIFlagFwdDecl
// CHECK-SAME: identifier: "_ZTSN5test51EE"
enum E : int;
void f1(E *) {
}
}
namespace test6 {
// Ensure typedef'd enums aren't manifest by debug info generation.
// This could cause "typedef changes linkage of anonymous type, but linkage was
// already computed" errors.
// CHECK-NOT: test6
typedef enum {
} E;
} |
#!/usr/bin/python
# This file is part of Ansible
# Ansible is free software: you can redistribute it and/or modify
# (at your option) any later version.
# Ansible is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: always
type: dict
sample: {"addr": "20.20.20.20", "interface": "ethernet1/32", "mask": "24"}
existing:
description: k/v pairs of existing IP attributes on the interface
type: dict
sample: {"addresses": [{"addr": "11.11.11.11", "mask": 17}],
"interface": "ethernet1/32", "prefix": "11.11.0.0",
"type": "ethernet", "vrf": "default"}
end_state:
description: k/v pairs of IP attributes after module execution
returned: always
type: dict
sample: {"addresses": [{"addr": "20.20.20.20", "mask": 24}],
"interface": "ethernet1/32", "prefix": "20.20.20.0",
"type": "ethernet", "vrf": "default"}
updates:
description: commands sent to the device
returned: always
type: list
sample: ["interface ethernet1/32", "ip address 20.20.20.20/24"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
import json
import collections
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.module_utils.shell import ShellError
try:
from ansible.module_utils.nxos import get_module
except ImportError:
from ansible.module_utils.nxos import NetworkModule
def to_list(val):
if isinstance(val, (list, tuple)):
return list(val)
elif val is not None:
return [val]
else:
return list()
class CustomNetworkConfig(NetworkConfig):
def expand_section(self, configobj, S=None):
if S is None:
S = list()
S.append(configobj)
for child in configobj.children:
if child in S:
continue
self.expand_section(child, S)
return S
def get_object(self, path):
for item in self.items:
if item.text == path[-1]:
parents = [p.text for p in item.parents]
if parents == path[:-1]:
return item
def to_block(self, section):
return '\n'.join([item.raw for item in section])
def get_section(self, path):
try:
section = self.get_section_objects(path)
return self.to_block(section)
except ValueError:
return list()
def get_section_objects(self, path):
if not isinstance(path, list):
path = [path]
obj = self.get_object(path)
if not obj:
raise ValueError('path does not exist in config')
return self.expand_section(obj)
def add(self, lines, parents=None):
"""Adds one or lines of configuration
"""
ancestors = list()
offset = 0
obj = None
## global config command
if not parents:
for line in to_list(lines):
item = ConfigLine(line)
item.raw = line
if item not in self.items:
self.items.append(item)
else:
for index, p in enumerate(parents):
try:
i = index + 1
obj = self.get_section_objects(parents[:i])[0]
ancestors.append(obj)
except ValueError:
# add parent to config
offset = index * self.indent
obj = ConfigLine(p)
obj.raw = p.rjust(len(p) + offset)
if ancestors:
obj.parents = list(ancestors)
ancestors[-1].children.append(obj)
self.items.append(obj)
ancestors.append(obj)
# add child objects
for line in to_list(lines):
# check if child already exists
for child in ancestors[-1].children:
if child.text == line:
break
else:
offset = len(parents) * self.indent
item = ConfigLine(line)
item.raw = line.rjust(len(line) + offset)
item.parents = ancestors
ancestors[-1].children.append(item)
self.items.append(item)
def get_network_module(**kwargs):
try:
return get_module(**kwargs)
except NameError:
return NetworkModule(**kwargs)
def get_config(module, include_defaults=False):
config = module.params['config']
if not config:
try:
config = module.get_config()
except AttributeError:
defaults = module.params['include_defaults']
config = module.config.get_config(include_defaults=defaults)
return CustomNetworkConfig(indent=2, contents=config)
def load_config(module, candidate):
config = get_config(module)
commands = candidate.difference(config)
commands = [str(c).strip() for c in commands]
save_config = module.params['save']
result = dict(changed=False)
if commands:
if not module.check_mode:
try:
module.configure(commands)
except AttributeError:
module.config(commands)
if save_config:
try:
module.config.save_config()
except AttributeError:
module.execute(['copy running-config startup-config'])
result['changed'] = True
result['updates'] = commands
return result
# END OF COMMON CODE
def <API key>(commands, module):
try:
module.configure(commands)
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending CLI commands',
error=str(clie), commands=commands)
except AttributeError:
try:
commands.insert(0, 'configure')
module.cli.add_commands(commands, output='config')
module.cli.run_commands()
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending CLI commands',
error=str(clie), commands=commands)
def get_cli_body_ssh(command, response, module):
"""Get response for when transport=cli. This is kind of a hack and mainly
needed because these modules were originally written for NX-API. And
not every command supports "| json" when using cli/ssh. As such, we assume
if | json returns an XML string, it is a valid command, but that the
resource doesn't exist yet. Instead, we assume if '^' is found in response,
it is an invalid command.
"""
if 'xml' in response[0]:
body = []
elif '^' in response[0] or 'show run' in response[0] or response[0] == '\n':
body = response
else:
try:
body = [json.loads(response[0])]
except ValueError:
module.fail_json(msg='Command does not support JSON output',
command=command)
return body
def execute_show(cmds, module, command_type=None):
command_type_map = {
'cli_show': 'json',
'cli_show_ascii': 'text'
}
try:
if command_type:
response = module.execute(cmds, command_type=command_type)
else:
response = module.execute(cmds)
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending {0}'.format(cmds),
error=str(clie))
except AttributeError:
try:
if command_type:
command_type = command_type_map.get(command_type)
module.cli.add_commands(cmds, output=command_type)
response = module.cli.run_commands()
else:
module.cli.add_commands(cmds, raw=True)
response = module.cli.run_commands()
except ShellError:
clie = get_exception()
module.fail_json(msg='Error sending {0}'.format(cmds),
error=str(clie))
return response
def <API key>(command, module, command_type='cli_show'):
if module.params['transport'] == 'cli':
command += ' | json'
cmds = [command]
response = execute_show(cmds, module)
body = get_cli_body_ssh(command, response, module)
elif module.params['transport'] == 'nxapi':
cmds = [command]
body = execute_show(cmds, module, command_type=command_type)
return body
def apply_key_map(key_map, table):
new_dict = {}
for key, value in table.items():
new_key = key_map.get(key)
if new_key:
value = table.get(key)
if value:
new_dict[new_key] = str(value)
else:
new_dict[new_key] = value
return new_dict
def get_interface_type(interface):
if interface.upper().startswith('ET'):
return 'ethernet'
elif interface.upper().startswith('VL'):
return 'svi'
elif interface.upper().startswith('LO'):
return 'loopback'
elif interface.upper().startswith('MG'):
return 'management'
elif interface.upper().startswith('MA'):
return 'management'
elif interface.upper().startswith('PO'):
return 'portchannel'
else:
return 'unknown'
def is_default(interface, module):
command = 'show run interface {0}'.format(interface)
try:
body = <API key>(command, module)[0]
if 'invalid' in body.lower():
return 'DNE'
else:
raw_list = body.split('\n')
if raw_list[-1].startswith('interface'):
return True
else:
return False
except (KeyError):
return 'DNE'
def get_interface_mode(interface, intf_type, module):
command = 'show interface {0}'.format(interface)
mode = 'unknown'
if intf_type in ['ethernet', 'portchannel']:
body = <API key>(command, module)[0]
if isinstance(body, str):
if 'invalid interface format' in body.lower():
module.fail_json(msg='Invalid interface name. Please check '
'its format.', interface=interface)
interface_table = body['TABLE_interface']['ROW_interface']
mode = str(interface_table.get('eth_mode', 'layer3'))
if mode == 'access' or mode == 'trunk':
mode = 'layer2'
elif intf_type == 'svi':
mode = 'layer3'
return mode
def send_show_command(interface_name, version, module):
if version == 'v4':
command = 'show ip interface {0}'.format(interface_name)
elif version == 'v6':
command = 'show ipv6 interface {0}'.format(interface_name)
if module.params['transport'] == 'nxapi' and version == 'v6':
body = <API key>(command, module,
command_type='cli_show_ascii')
else:
body = <API key>(command, module)
return body
def <API key>(body, interface_name, version, module):
address_list = []
interface_key = {
'subnet': 'prefix',
'prefix': 'prefix'
}
try:
interface_table = body[0]['TABLE_intf']['ROW_intf']
try:
vrf_table = body[0]['TABLE_vrf']['ROW_vrf']
vrf = vrf_table['vrf-name-out']
except KeyError:
vrf = None
except (KeyError, AttributeError):
return {}
interface = apply_key_map(interface_key, interface_table)
interface['interface'] = interface_name
interface['type'] = get_interface_type(interface_name)
interface['vrf'] = vrf
if version == 'v4':
address = {}
address['addr'] = interface_table.get('prefix', None)
if address['addr'] is not None:
address['mask'] = str(interface_table.get('masklen', None))
interface['addresses'] = [address]
prefix = "{0}/{1}".format(address['addr'], address['mask'])
address_list.append(prefix)
else:
interface['addresses'] = []
elif version == 'v6':
address_list = interface_table.get('addr', [])
interface['addresses'] = []
if address_list:
if not isinstance(address_list, list):
address_list = [address_list]
for ipv6 in address_list:
address = {}
splitted_address = ipv6.split('/')
address['addr'] = splitted_address[0]
address['mask'] = splitted_address[1]
interface['addresses'].append(address)
else:
interface['addresses'] = []
return interface, address_list
def <API key>(body, interface_name, module):
interface = {}
address_list = []
vrf = None
body = body[0]
if "ipv6 is disabled" not in body.lower():
splitted_body = body.split('\n')
# We can have multiple IPv6 on the same interface.
# We need to parse them manually from raw output.
for index in range(0, len(splitted_body) - 1):
if "IPv6 address:" in splitted_body[index]:
<API key> = index + 1
elif "IPv6 subnet:" in splitted_body[index]:
<API key> = index
prefix_line = splitted_body[<API key>]
prefix = prefix_line.split('IPv6 subnet:')[1].strip()
interface['prefix'] = prefix
<API key> = splitted_body[
<API key>:<API key>]
for each_line in <API key>:
address = each_line.strip().split(' ')[0]
if address not in address_list:
address_list.append(address)
interface['addresses'] = []
if address_list:
for ipv6 in address_list:
address = {}
splitted_address = ipv6.split('/')
address['addr'] = splitted_address[0]
address['mask'] = splitted_address[1]
interface['addresses'].append(address)
try:
vrf_regex = '.*VRF\s+(?P<vrf>\S+).*'
match_vrf = re.match(vrf_regex, body, re.DOTALL)
group_vrf = match_vrf.groupdict()
vrf = group_vrf["vrf"]
except AttributeError:
vrf = None
else:
# IPv6's not been configured on this interface yet.
interface['addresses'] = []
interface['interface'] = interface_name
interface['type'] = get_interface_type(interface_name)
interface['vrf'] = vrf
return interface, address_list
def get_ip_interface(interface_name, version, module):
body = send_show_command(interface_name, version, module)
# nxapi default response doesn't reflect the actual interface state
# when dealing with IPv6. That's why we need to get raw output instead
# and manually parse it.
if module.params['transport'] == 'nxapi' and version == 'v6':
interface, address_list = <API key>(
body, interface_name, module)
else:
interface, address_list = <API key>(
body, interface_name, version, module)
return interface, address_list
def <API key>(interface, addr, mask, version):
commands = []
commands.append('interface {0}'.format(interface))
if version == 'v4':
commands.append('no ip address')
else:
commands.append('no ipv6 address {0}/{1}'.format(addr, mask))
return commands
def <API key>(delta, interface, existing, version):
commands = []
delta = dict(delta)
# loop used in the situation that just an IP address or just a
# mask is changing, not both.
for each in ['addr', 'mask']:
if each not in delta:
delta[each] = existing[each]
if version == 'v4':
command = 'ip address {addr}/{mask}'.format(**delta)
else:
command = 'ipv6 address {addr}/{mask}'.format(**delta)
commands.append(command)
commands.insert(0, 'interface {0}'.format(interface))
return commands
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def validate_params(addr, interface, mask, version, state, intf_type, module):
if state == "present":
if addr is None or mask is None:
module.fail_json(msg="An IP address AND a mask must be provided "
"when state=present.")
elif state == "absent" and version == "v6":
if addr is None or mask is None:
module.fail_json(msg="IPv6 address and mask must be provided when "
"state=absent.")
if (intf_type != "ethernet" and module.params["transport"] == "cli"):
if is_default(interface, module) == "DNE":
module.fail_json(msg="That interface does not exist yet. Create "
"it first.", interface=interface)
if mask is not None:
try:
if (int(mask) < 1 or int(mask) > 32) and version == "v4":
raise ValueError
elif int(mask) < 1 or int(mask) > 128:
raise ValueError
except ValueError:
module.fail_json(msg="Warning! 'mask' must be an integer between"
" 1 and 32 when version v4 and up to 128 "
"when version v6.", version=version,
mask=mask)
def main():
argument_spec = dict(
interface=dict(required=True),
addr=dict(required=False),
version=dict(required=False, choices=['v4', 'v6'],
default='v4'),
mask=dict(type='str', required=False),
state=dict(required=False, default='present',
choices=['present', 'absent']),
include_defaults=dict(default=True),
config=dict(),
save=dict(type='bool', default=False)
)
module = get_network_module(argument_spec=argument_spec,
supports_check_mode=True)
addr = module.params['addr']
version = module.params['version']
mask = module.params['mask']
interface = module.params['interface'].lower()
state = module.params['state']
intf_type = get_interface_type(interface)
validate_params(addr, interface, mask, version, state, intf_type, module)
mode = get_interface_mode(interface, intf_type, module)
if mode == 'layer2':
module.fail_json(msg='That interface is a layer2 port.\nMake it '
'a layer 3 port first.', interface=interface)
existing, address_list = get_ip_interface(interface, version, module)
args = dict(addr=addr, mask=mask, interface=interface)
proposed = dict((k, v) for k, v in args.items() if v is not None)
commands = []
changed = False
end_state = existing
if state == 'absent' and existing['addresses']:
if version == 'v6':
for address in existing['addresses']:
if address['addr'] == addr and address['mask'] == mask:
command = <API key>(interface, addr,
mask, version)
commands.append(command)
else:
command = <API key>(interface, addr,
mask, version)
commands.append(command)
elif state == 'present':
if not existing['addresses']:
command = <API key>(proposed, interface,
existing, version)
commands.append(command)
else:
prefix = "{0}/{1}".format(addr, mask)
if prefix not in address_list:
command = <API key>(proposed, interface,
existing, version)
commands.append(command)
else:
for address in existing['addresses']:
if (address['addr'] == addr and
int(address['mask']) != int(mask)):
command = <API key>(proposed, interface,
existing, version)
commands.append(command)
cmds = flatten_list(commands)
if cmds:
if module.check_mode:
module.exit_json(changed=True, commands=cmds)
else:
<API key>(cmds, module)
changed = True
end_state, address_list = get_ip_interface(interface, version,
module)
if 'configure' in cmds:
cmds.pop(0)
results = {}
results['proposed'] = proposed
results['existing'] = existing
results['end_state'] = end_state
results['updates'] = cmds
results['changed'] = changed
module.exit_json(**results)
if __name__ == '__main__':
main() |
#ifndef <API key>
#define <API key>
// PURPOSE: This module contains all the libc code that is entirely
// standalone (other than the VG_() macro and some types defined
// elsewhere): string functions, char functions, and a few other things.
#include "pub_tool_libcbase.h"
#endif // <API key> |
{
volScalarField rUA = 1.0/UEqn.A();
surfaceScalarField rUAf = fvc::interpolate(rUA);
U = rUA*UEqn.H();
surfaceScalarField phiU
(
"phiU",
(fvc::interpolate(U) & mesh.Sf())
+ fvc::ddtPhiCorr(rUA, rho, U, phi)
);
adjustPhi(phiU, U, pd);
phi = phiU +
(
fvc::interpolate(interface.sigmaK())*fvc::snGrad(alpha1)
- ghf*fvc::snGrad(rho)
)*rUAf*mesh.magSf();
Pair<tmp<volScalarField> > vDotP = twoPhaseProperties->vDotP();
const volScalarField& vDotcP = vDotP[0]();
const volScalarField& vDotvP = vDotP[1]();
for(int nonOrth=0; nonOrth<=nNonOrthCorr; nonOrth++)
{
fvScalarMatrix pdEqn
(
fvc::div(phi) - fvm::laplacian(rUAf, pd)
+ (vDotvP - vDotcP)*(rho*gh - pSat) + fvm::Sp(vDotvP - vDotcP, pd)
);
pdEqn.setReference(pdRefCell, pdRefValue);
if (corr == nCorr - 1 && nonOrth == nNonOrthCorr)
{
pdEqn.solve(mesh.solutionDict().solver(pd.name() + "Final"));
}
else
{
pdEqn.solve(mesh.solutionDict().solver(pd.name()));
}
if (nonOrth == nNonOrthCorr)
{
phi += pdEqn.flux();
}
}
p = pd + rho*gh;
U += rUA*fvc::reconstruct((phi - phiU)/rUAf);
U.<API key>();
} |
#!/usr/bin/env perl
use File::Temp qw/ tempfile tempdir /;
$ICONWIDTH = 50;
$ICONHEIGHT = 30;
$BORDER = 4;
$FONTSIZE = 12;
$ALIGNMENT_CROSS = false;
my $srcdir = $ARGV[0];
my $argc = @ARGV;
if($argc != 1){
print "Usage: <API key>.pl <src dir>\n";
exit 1;
}
# create a temporary directory
my $tempdir = tempdir(CLEANUP => 1);
# find all the icons listed in paint.h
open(PAINTH, "<$srcdir/dtgtk/paint.h");
my $comment;
my $lastlinewasacomment = false;
my $code;
my $numberoficons = 0;
my $longeststring;
my @codelines;
while(<PAINTH>){
chomp;
next if $_ eq '';
if($_ =~ /^\/\*\* (.*) \*\//){ # this should be the description of a paint function
$comment = $1;
$lastlinewasacomment = true;
}
else{
if($lastlinewasacomment eq true){ # this is the next non-empty line after a comment, so it should be a paint function
$_ =~ /(dtgtk_cairo_[^(]*)/;
$code = $1;
my $description = "$comment ($code)";
$longeststring = $description if length($longeststring) < length($description);
$codelines[$numberoficons][0] = $description;
$codelines[$numberoficons][1] = $code;
$numberoficons++;
}
$lastlinewasacomment = false;
}
}
close(PAINTH);
# write the .c file
open(TESTC, ">$tempdir/test.c");
print TESTC <<EOF;
#include <cairo.h>
#include "dtgtk/paint.h"
int main(){
cairo_surface_t *surface;
cairo_t *cr;
<API key> ext;
int width, height, textwidth;
surface = <API key>(CAIRO_FORMAT_ARGB32, 10, 10);
cr = cairo_create(surface);
<API key> (cr, "mono", <API key>, <API key>);
cairo_set_font_size (cr, $FONTSIZE);
cairo_text_extents (cr, "$longeststring", &ext);
textwidth = ext.width; width = textwidth+4*$ICONWIDTH+6*$BORDER; height = $numberoficons*($ICONHEIGHT+$BORDER)+$BORDER;
cairo_destroy(cr);
<API key>(surface);
surface = <API key>(CAIRO_FORMAT_ARGB32, width, height);
cr = cairo_create(surface);
<API key> (cr, "mono", <API key>, <API key>);
cairo_set_font_size (cr, $FONTSIZE);
cairo_rectangle(cr, 0.0, 0.0, width, height);
<API key>(cr, .15, .15, .15);
cairo_fill(cr);
EOF
# add all the calls to the individual paint functions
my $row = 0;
foreach my $line (@codelines){
my $description = @$line[0];
$description =~ s/"/\\"/g;
my $code = @$line[1];
# add description text
print TESTC <<EOF;
cairo_save(cr);
<API key>(cr, .79, .79, .79);
cairo_move_to (cr, $BORDER, $BORDER+$row*($ICONHEIGHT+$BORDER)+0.8*$ICONHEIGHT);
cairo_show_text(cr, "$description");
cairo_restore(cr);
EOF
# add icons for all four directions
my $column = 0;
foreach my $direction ("CPF_DIRECTION_UP", "CPF_DIRECTION_DOWN", "CPF_DIRECTION_LEFT", "CPF_DIRECTION_RIGHT"){
print TESTC <<EOF;
cairo_save(cr);
cairo_rectangle(cr, textwidth+2*$BORDER+$column*($ICONWIDTH+$BORDER), $BORDER+$row*($ICONHEIGHT+$BORDER), $ICONWIDTH, $ICONHEIGHT);
<API key>(cr, .17, .17, .17);
cairo_fill(cr);
EOF
if($ALIGNMENT_CROSS eq true){
print TESTC <<EOF;
<API key>(cr, .7, 0, 0);
<API key>(cr, 1);
cairo_move_to(cr, textwidth+2*$BORDER+$column*($ICONWIDTH+$BORDER)+0.5*$ICONWIDTH, $BORDER+$row*($ICONHEIGHT+$BORDER));
cairo_line_to(cr, textwidth+2*$BORDER+$column*($ICONWIDTH+$BORDER)+0.5*$ICONWIDTH, $BORDER+$row*($ICONHEIGHT+$BORDER)+$ICONHEIGHT);
cairo_stroke(cr);
EOF
}
print TESTC <<EOF;
cairo_move_to(cr, textwidth+2*$BORDER+$column*($ICONWIDTH+$BORDER), $BORDER+$row*($ICONHEIGHT+$BORDER)+0.5*$ICONHEIGHT);
cairo_line_to(cr, textwidth+2*$BORDER+$column*($ICONWIDTH+$BORDER)+$ICONWIDTH, $BORDER+$row*($ICONHEIGHT+$BORDER)+0.5*$ICONHEIGHT);
cairo_stroke(cr);
<API key>(cr, .79, .79, .79);
$code(cr, textwidth+3*$BORDER+$column*($ICONWIDTH+$BORDER), 2*$BORDER+$row*($ICONHEIGHT+$BORDER), $ICONWIDTH-2*$BORDER, $ICONHEIGHT-2*$BORDER, $direction, NULL);
cairo_restore(cr);
EOF
$column++;
}
$row++;
}
# rest of the .c file
print TESTC <<EOF;
cairo_destroy(cr);
<API key>(surface, "<API key>.png");
<API key>(surface);
return 0;
}
EOF
# compile & run the .c file
system("gcc `pkg-config --cflags --libs gtk+-3.0 json-glib-1.0` -lm -std=c99 -I$srcdir -o $tempdir/test $tempdir/test.c $srcdir/dtgtk/paint.c");
system("$tempdir/test");
print "<API key>.png created in the current directory\n"; |
#include <common.h>
#include <regs.h>
#define M_MDIV 0x03c
#define M_PDIV 0x02
#define M_SDIV 0x0
#define U_M_MDIV 0x030
#define U_M_PDIV 0x2
#define U_M_SDIV 0x1
static inline void delay(unsigned long loops)
{
__asm__ volatile ("1:\n" "subs %0, %1, #1\n" "bne 1b":"=r" (loops):"0"(loops));
}
/*
* Miscellaneous platform dependent initialisations
*/
int board_init(void)
{
<API key>;
SROM_BW_REG &= ~0x1c0;
SROM_BW_REG |= 0x1c0;
SROM_BC2_REG = 0x25a0;
gd->bd->bi_arch_number = MACH_TYPE;
gd->bd->bi_boot_params = 0x10000100;
#if 0
icache_enable();
dcache_enable();
#endif
return 0;
}
int dram_init(void)
{
<API key>;
#if defined (CONFIG_PKGTYPE_416) && defined (<API key>)
gd->bd->bi_dram[0].start = PHYS_SDRAM_1;
gd->bd->bi_dram[0].size = PHYS_SDRAM_1_SIZE;
#else /* CONFIG_PKGTYPE_496 or (416 and mDDR) */
gd->bd->bi_dram[0].start = PHYS_SDRAM_1;
gd->bd->bi_dram[0].size = PHYS_SDRAM_1_SIZE;
gd->bd->bi_dram[1].start = PHYS_SDRAM_2;
gd->bd->bi_dram[1].size = PHYS_SDRAM_2_SIZE;
#endif
return 0;
}
#ifdef BOARD_LATE_INIT
int board_late_init (void)
{
uint *magic = (uint*)(PHYS_SDRAM_1);
char boot_cmd[30];
if ((0x24564236 == magic[0]) && (0x20764316 == magic[1])) {
sprintf(boot_cmd, "nandw 0 0x38000 0x%08x", PHYS_SDRAM_1+0x8000);
magic[0] = 0;
magic[1] = 0;
printf("\n\nready for self-burning U-Boot image\n\n");
setenv("bootdelay", "0");
setenv("bootcmd", boot_cmd);
}
}
#endif
#ifdef <API key>
int checkboard(void)
{
printf("Board: SMDK2460\n");
return (0);
}
#endif
#ifdef CONFIG_ENABLE_MMU
ulong <API key>(ulong addr)
{
#ifdef CONFIG_PKGTYPE_416
#ifdef <API key>
if ((0xc0000000 <= addr) && (addr < 0xc2000000))
return (addr - 0xc0000000 + 0x20000000);
else if ((0xc2000000 <= addr) && (addr < 0xc4000000))
return (addr - 0xc2000000 + 0x30000000);
else
printf("do not support this address : %08lx\n", addr);
#else /* <API key> */
if ((0xc0000000 <= addr) && (addr < 0xc4000000))
return (addr - 0xc0000000 + 0x20000000);
else
printf("do not support this address : %08lx\n", addr);
#endif
#else /* CONFIG_PKGTYPE_496 */
if ((0xc0000000 <= addr) && (addr < 0xc2000000))
return (addr - 0xc0000000 + 0x10000000);
else if ((0xc2000000 <= addr) && (addr < 0xc4000000))
return (addr - 0xc2000000 + 0x20000000);
else
printf("do not support this address : %08lx\n", addr);
#endif
return addr;
}
#endif
#if (CONFIG_COMMANDS & CFG_CMD_NAND) && defined(CFG_NAND_LEGACY)
#include <linux/mtd/nand.h>
extern struct nand_chip nand_dev_desc[CFG_MAX_NAND_DEVICE];
void nand_init(void)
{
nand_probe(CFG_NAND_BASE);
if (nand_dev_desc[0].ChipID != NAND_ChipID_UNKNOWN) {
print_size(nand_dev_desc[0].totlen, "\n");
}
}
#endif |
--TEST
MySQL PDO->errorCode()
--SKIPIF
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'skipif.inc');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc');
MySQLPDOTest::skip();
$db = MySQLPDOTest::factory();
?>
--FILE
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc');
$db = MySQLPDOTest::factory();
MySQLPDOTest::createTestTable($db);
function check_error($offset, &$obj, $expected = '00000') {
$code = $obj->errorCode();
if (($code != $expected) && (($expected != '00000') && ($code != ''))) {
printf("[%03d] Expecting error code '%s' got code '%s'\n",
$offset, $expected, $code);
}
}
try {
/*
If you create a PDOStatement object through PDO->prepare()
or PDO->query() and invoke an error on the statement handle,
PDO->errorCode() will not reflect that error. You must call
PDOStatement->errorCode() to return the error code for an
operation performed on a particular statement handle.
*/
$code = $db->errorCode();
check_error(2, $db);
$stmt = $db->query('SELECT id, label FROM test');
$stmt2 = &$stmt;
check_error(3, $db);
check_error(4, $stmt);
$db->exec('DROP TABLE IF EXISTS test');
@$stmt->execute();
check_error(4, $db);
check_error(5, $stmt, '42S02');
check_error(6, $stmt2, '42S02');
$db->exec('DROP TABLE IF EXISTS unknown');
@$stmt = $db->query('SELECT id, label FROM unknown');
check_error(7, $db, '42S02');
MySQLPDOTest::createTestTable($db);
$stmt = $db->query('SELECT id, label FROM test');
check_error(8, $db);
check_error(9, $stmt);
$db2 = &$db;
@$db->query('SELECT id, label FROM unknown');
check_error(10, $db, '42S02');
check_error(11, $db2, '42S02');
check_error(12, $stmt);
check_error(13, $stmt2);
// lets hope this is an invalid attribute code
$invalid_attr = -1 * PHP_INT_MAX + 3;
$tmp = @$db->getAttribute($invalid_attr);
check_error(14, $db, 'IM001');
check_error(15, $db2, 'IM001');
check_error(16, $stmt);
check_error(17, $stmt2);
} catch (PDOException $e) {
printf("[001] %s [%s] %s\n",
$e->getMessage(), $db->errorCode(), implode(' ', $db->errorInfo()));
}
print "done!";
?>
--CLEAN
<?php
require dirname(__FILE__) . '/mysql_pdo_test.inc';
MySQLPDOTest::dropTestTable();
?>
--EXPECTF
done! |
<?php
/**
* Contains \jamesiarmes\PhpEws\Type\NotType.
*/
namespace jamesiarmes\PhpEws\Type;
/**
* Represents a search expression that negates the Boolean value of the search
* expression that it contains.
*
* @package php-ews\Type
*/
class NotType extends <API key>
{
} |
#include <stdint.h>
#include <stdio.h>
#include "keywords.h"
#include "podefs.h"
#include "pinsn32.h"
#include "pfdefs.h"
#include "pxdefs.h"
#include "paslib.h"
#include "pinsn.h"
/* These are all the format codes that apply to opcodes with an argument */
enum {
SIMPLE = 0, /* No argument */
HEX, /* Hexadecimal argument */
DECIMAL, /* Signed Decimal argument (w/shift) */
UDECIMAL, /* Unsigned Decimal argument (w/shift) */
LABEL_DEC, /* Label number */
xOP, lbOP, fpOP, /* Sub opcode */
FILENO, LINENO /* File number, line number */
};
/* The following table defines everything that is needed to disassemble
* a P-Code. NOTE: The order of definition in this table must exactly
* match the declaration sequence in pinsn.h. */
static const char invOp[] = "Invalid Opcode";
struct optab_s
{
const char *opName; /* Opcode mnemonics */
uint8_t format; /* arg16 format */
};
static const struct optab_s g_sNoArgOpTable[64] =
{
/* Program control (No stack arguments) */
/* 0x00 */ { "NOP ", SIMPLE },
/* Arithmetic & logical & and integer conversions (One stack argument) */
/* 0x01 */ { "NEG ", SIMPLE },
/* 0x02 */ { "ABS ", SIMPLE },
/* 0x03 */ { "INC ", SIMPLE },
/* 0x04 */ { "DEC ", SIMPLE },
/* 0x05 */ { "NOT ", SIMPLE },
/* Arithmetic & logical (Two stack arguments) */
/* 0x06 */ { "ADD ", SIMPLE },
/* 0x07 */ { "SUB ", SIMPLE },
/* 0x08 */ { "MUL ", SIMPLE },
/* 0x09 */ { "DIV ", SIMPLE },
/* 0x0a */ { "MOD ", SIMPLE },
/* 0x0b */ { "SLL ", SIMPLE },
/* 0x0c */ { "SRL ", SIMPLE },
/* 0x0d */ { "SRA ", SIMPLE },
/* 0x0e */ { "OR ", SIMPLE },
/* 0x0f */ { "AND ", SIMPLE },
/* Comparisons (One stack argument) */
/* 0x10 */ { "EQUZ ", SIMPLE },
/* 0x11 */ { "NEQZ ", SIMPLE },
/* 0x12 */ { "LTZ ", SIMPLE },
/* 0x13 */ { "GTEZ ", SIMPLE },
/* 0x14 */ { "GTZ ", SIMPLE },
/* 0x15 */ { "LTEZ ", SIMPLE },
/* 0x16 */ { invOp, SIMPLE },
/* 0x17 */ { invOp, SIMPLE },
/* Comparisons (Two stack arguments) */
/* 0x18 */ { "EQU ", SIMPLE },
/* 0x19 */ { "NEQ ", SIMPLE },
/* 0x1a */ { "LT ", SIMPLE },
/* 0x1b */ { "GTE ", SIMPLE },
/* 0x1c */ { "GT ", SIMPLE },
/* 0x1d */ { "LTE ", SIMPLE },
/* 0x1e */ { invOp, SIMPLE },
/* 0x1f */ { "BIT ", SIMPLE },
/* Load (One) or Store (Two stack argument) */
/* 0x20 */ { "LDI ", SIMPLE },
/* 0x21 */ { "LDIH", SIMPLE },
/* 0x22 */ { "LDIB", SIMPLE },
/* 0x23 */ { "LDIM", SIMPLE },
/* 0x24 */ { "STI ", SIMPLE },
/* 0x25 */ { "STIH", SIMPLE },
/* 0x26 */ { "STIB", SIMPLE },
/* 0x27 */ { "STIM", SIMPLE },
/* Data stack operations */
/* 0x28 */ { "DUP ", SIMPLE },
/* 0x29 */ { "DUPH ", SIMPLE },
/* 0x2a */ { "PUSHS", SIMPLE },
/* 0x2b */ { "POPS", SIMPLE },
/* 0x2c */ { invOp, SIMPLE },
/* 0x2d */ { invOp, SIMPLE },
/* 0x2e */ { invOp, SIMPLE },
/* 0x2f */ { "RET ", SIMPLE },
/* 0x30 */ { invOp, SIMPLE },
/* 0x31 */ { invOp, SIMPLE },
/* 0x32 */ { invOp, SIMPLE },
/* 0x33 */ { invOp, SIMPLE },
/* 0x34 */ { invOp, SIMPLE },
/* 0x35 */ { invOp, SIMPLE },
/* 0x36 */ { invOp, SIMPLE },
/* 0x37 */ { invOp, SIMPLE },
/* System Functions (No stack arguments) */
/* 0x38 */ { invOp, SIMPLE },
/* 0x39 */ { invOp, SIMPLE },
/* 0x3a */ { invOp, SIMPLE },
/* 0x3b */ { invOp, SIMPLE },
/* 0x3c */ { invOp, SIMPLE },
/* 0x3d */ { invOp, SIMPLE },
/* 0x3e */ { invOp, SIMPLE },
/* 0x3f */ { "EXIT ", SIMPLE }
};
static const struct optab_s g_sArg32OpTable[64] =
{
/* Load: arg = unsigned base offset */
/* 0x80 */ { "LD ", UDECIMAL }, /* No stack arguments */
/* 0x81 */ { "LDH ", UDECIMAL }, /* No stack arguments */
/* 0x82 */ { "LDB ", UDECIMAL }, /* No stack arguments */
/* 0x83 */ { "LDM ", UDECIMAL }, /* One 32-bit stack argument */
/* Store: arg = unsigned base offset (One stack arguments) */
/* 0x84 */ { "ST ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x85 */ { "STH ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x86 */ { "STB ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x87 */ { "STM ", UDECIMAL }, /* One+n 32-bit stack argument */
/* Load Indexed: arg = unsigned base offset */
/* 0x88 */ { "LDX ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x89 */ { "LDXH ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x8a */ { "LDXB ", UDECIMAL }, /* One 32-bit stack argument */
/* 0x8b */ { "LDXM ", UDECIMAL }, /* Two 32-bit stack argument */
/* Store Indexed: arg = unsigned base offset */
/* 0x8c */ { "STX ", UDECIMAL }, /* Two 32-bit stack argument */
/* 0x8d */ { "STXH ", UDECIMAL }, /* Two 32-bit stack argument */
/* 0x8e */ { "STXB ", UDECIMAL }, /* Two 32-bit stack argument */
/* 0x8f */ { "STXM ", UDECIMAL }, /* Two+n 32-bit stack argument */
/* Program control: arg = unsigned label (One stack argument) */
/* 0x90 */ { "JEQUZ", HEX },
/* 0x91 */ { "JNEQZ", HEX },
/* 0x92 */ { "JLTZ ", HEX },
/* 0x93 */ { "JGTEZ", HEX },
/* 0x94 */ { "JGTZ ", HEX },
/* 0x95 */ { "JLTEZ", HEX },
/* Program control: arg = unsigned label (no stack arguments) */
/* 0x96 */ { "JMP ", HEX },
/* 0x97 */ { "PUSH ", DECIMAL },
/* Program control: arg = unsigned label (One stack argument) */
/* 0x98 */ { "JEQU ", HEX },
/* 0x99 */ { "JNEQ ", HEX },
/* 0x9a */ { "JLT ", HEX },
/* 0x9b */ { "JGTE ", HEX },
/* 0x9c */ { "JGT ", HEX },
/* 0x9d */ { "JLTE ", HEX },
/* 0x9e */ { invOp, SIMPLE },
/* 0x9f */ { "INDS ", DECIMAL },
/* Load: Uses LSP; arg = signed frame offset */
/* 0xa0 */ { "LDS ", DECIMAL }, /* No stack arguments */
/* 0xa1 */ { "LDSH ", DECIMAL }, /* No stack arguments */
/* 0xa2 */ { "LDSB ", DECIMAL }, /* No stack arguments */
/* 0xa3 */ { "LDSM ", DECIMAL }, /* One 32-bit stack argument */
/* Store: Uses LSP; arg = signed frame offset */
/* 0xa4 */ { "STS ", DECIMAL }, /* One 32-bit stack argument */
/* 0xa5 */ { "STSH ", DECIMAL }, /* One 32-bit stack argument */
/* 0xa6 */ { "STSB ", DECIMAL }, /* One 32-bit stack argument */
/* 0xa7 */ { "STSM ", DECIMAL }, /* One+n 32-bit stack argument */
/* Load Indexed: Uses LSP; arg = signed frame offset */
/* 0xa8 */ { "LDSX ", DECIMAL }, /* One 32-bit stack argument */
/* 0xa9 */ { "LDSXH", DECIMAL }, /* One 32-bit stack argument */
/* 0xaa */ { "LDSXB", DECIMAL }, /* One 32-bit stack argument */
/* 0xab */ { "LDSXM", DECIMAL }, /* Two 32-bit stack argument */
/* Store Indexed: Uses LSP; arg = signed frame offset */
/* 0xac */ { "STSX ", DECIMAL }, /* Two 32-bit stack argument */
/* 0xad */ { "STSXH", DECIMAL }, /* Two 32-bit stack argument */
/* 0xae */ { "STSXB", DECIMAL }, /* Two 32-bit stack argument */
/* 0xaf */ { "STSXM", DECIMAL }, /* Two+n 32-bit stack argument */
/* Load address relative to stack base: arg = unsigned offset */
/* 0xb0 */ { "LA ", UDECIMAL },
/* Load address: Uses SLP, arg = signed frame offset */
/* 0xb1 */ { "LAS ", DECIMAL },
/* Load absolute stack address: arg = RODATA offset (No stack arguments) */
/* 0xb2 */ { "LAC ", HEX, },
/* 0xb3 */ { invOp, SIMPLE },
/* Load address relative to stack base: arg = unsigned offset, TOS=index */
/* 0xb4 */ { "LAX ", UDECIMAL },
/* Load address indexed: Uses SLP, arg = signed frame offset */
/* 0xb5 */ { "LASX ", DECIMAL },
/* Set LSP: arg = new level that evaluates to LSP value */
/* 0xb6 */ { "SLSP ", UDECIMAL },
/* 0xb7 */ { "SDC ", UDECIMAL },
/* 0xb8 */ { invOp, SIMPLE },
/* Program Control: Uses LSP; arg = unsigned label (No stack arguments) */
/* 0xb9 */ { "PCAL ", HEX },
/* System calls: arg = file number | sub-function code */
/* 0xba */ { "SYSIO", xOP },
/* System functions: arg = 32-bit library call identifier */
/* 0xbb */ { "LIB ", lbOP },
/* Floating point operations: arg = FP op-code */
/* 0xbc */ { "FLOAT", fpOP },
/* Program control: arg = unsigned label (no stack arguments) */
/* 0xbd */ { NULL, LABEL_DEC },
/* Pseudo-operations: arg = file number OR line number */
/* 0xbe */ { "INCLUDE ", FILENO },
/* 0xbf */ { "LINE ", LINENO },
};
static const char invXOp[] = "Invalid SYSIO";
static const char *xName[MAX_XOP] = { /* SYSIO opcode mnemonics */
/* 0x00 */ invXOp, "EOF", "EOLN", "RESET",
/* 0x04 */ "REWRITE", invXOp, invXOp, invXOp,
/* 0x08 */ invXOp, invXOp, invXOp, invXOp,
/* 0x0c */ invXOp, invXOp, invXOp, invXOp,
/* 0x10 */ "READLN", "READPG", "READBIN", "READINT",
/* 0x14 */ "READCHR", "READSTR", "READRL", invXOp,
/* 0x18 */ invXOp, invXOp, invXOp, invXOp,
/* 0x1c */ invXOp, invXOp, invXOp, invXOp,
/* 0x20 */ "WRITELN", "WRITEPG", "WRITEBIN", "WRITEINT",
/* 0x24 */ "WRITECHR", "WRITESTR", "WRITERL" };
static const char invLbOp[] = "Invalid runtime code";
static const char *lbName[MAX_LBOP] = { /* LIB opcode mnemonics */
/* 0x00 */ "GETENV", "STR2STR", "CSTR2STR", "STR2RSTR",
/* 0x04 */ "CSTR2RSTR", "VAL", "MKSTK", "MKSTKSTR",
/* 0x08 */ "MKSTKC", "STRCAT", "STRCATC", "STRCMP" };
#define MAX_FOP 16
static const char invFpOp[] = "Invalid FP Operation";
static const char *fpName[MAX_FOP] = {
/* 0x00 */ invFpOp, "FLOAT", "TRUNC", "ROUND",
/* 0x04 */ "NEG", "ADD", "SUB", "MUL",
/* 0x08 */ "DIV", "MOD", "EQU", "NEQ",
/* 0x0c */ "LT", "GTE", "GT", "LTE" };
void <API key>(FILE* lfile, OPTYPE *pop)
{
const struct optab_s *opTable;
int idx;
/* Select table based upon whether an opcode is included or not */
if (pop->op & o32)
{
opTable = g_sArg32OpTable;
idx = pop->op & ~o32;
}
else
{
opTable = g_sNoArgOpTable;
idx = pop->op;
}
/* Indent, comment or label as appropriate */
switch (opTable[idx].format)
{
case LABEL_DEC :
fprintf(lfile, "L%08lx:\n", pop->arg);
return;
case FILENO :
case LINENO :
fprintf(lfile, "; ");
break;
default :
fprintf(lfile, " ");
} /* end switch */
/* Print the opcode mnemonic */
fprintf(lfile, "%s ", opTable[idx].opName);
/* Print the argument (if present) */
if (pop->op & o32)
{
switch (opTable[idx].format)
{
case HEX :
fprintf(lfile, "0x%08lx", pop->arg);
break;
case FILENO :
case LINENO :
case DECIMAL :
fprintf(lfile, "%ld", (int32_t)pop->arg);
break;
case UDECIMAL :
fprintf(lfile, "%1lu", pop->arg);
break;
case fpOP :
if ((pop->arg & 0x3f) < MAX_FOP)
fprintf(lfile, "%s", fpName[(pop->arg & 0x3f)]);
else
fprintf(lfile, "%s", invFpOp);
break;
case xOP :
{
unsigned fileno = pop->arg >> 16;
unsigned xop = pop->arg & 0xffff;
fprintf(lfile, "%d, ", fileno);
if (xop < MAX_XOP)
fprintf(lfile, "%s", xName[xop]);
else
fprintf(lfile, "%s", invXOp);
}
break;
case lbOP :
if (pop->arg < MAX_LBOP)
fprintf(lfile, "%s", lbName[pop->arg]);
else
fprintf(lfile, "%s", invLbOp);
break;
case LABEL_DEC :
default :
break;
}
}
/* Don't forget the newline! */
fputc('\n', lfile);
} /* end dissassemblePcode */ |
<!DOCTYPE html>
<html>
<head>
<title>jsProject Examples</title>
<meta charset="UTF-8">
<meta name="description" content="How to jsProject">
<meta name="keywords" content="jsProject, explanation, function, example">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge"><link href="https://fonts.googleapis.com/css?family=Raleway" media="screen" rel="stylesheet" type="text/css">
<script>
// add onload event
window.onload = function(){
// set language
sharesoft.urlLanguage = '<?php
// lang in url
if( isset( $_GET['lang'] ) ){
// echo lang
echo $_GET['lang'];
}
// lang in url
?>';
// start the application
sharesoft.start();
};
// done add onload event
</script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script type="text/javascript" src="../../main.js"></script>
<script type="text/javascript" src="settingsModule.js"></script>
<script type="text/javascript" src="../../valuesModule.js"></script>
<?php
echo ' <script type="text/javascript" src="translationsModule';
// lang in url
if( isset( $_GET['lang'] ) ){
// echo lang
echo '_' . $_GET['lang'];
}
// lang in url
echo '.js"></script>';
?>
<script type="text/javascript" src="../../layoutModule.js"></script>
<script type="text/javascript" src="../../headerModule.js"></script>
<script type="text/javascript" src="../../<API key>.js"></script>
<script type="text/javascript" src="../../githubButtonModule.js"></script>
<script type="text/javascript" src="../../<API key>.js"></script>
<script type="text/javascript" src="../../<API key>.js"></script>
<script type="text/javascript" src="contentModule.js"></script>
<script type="text/javascript" src="../../src/jsProject/jsProject-min.js"></script>
</head>
<body>
</body>
</html> |
'use strict';
const test_desc = 'Wrong Service name. Reject with TypeError.';
const expected = new DOMException(
"Failed to execute 'FUNCTION_NAME' on " +
"'<API key>': Invalid Service name: " +
"'wrong_name'. It must be a valid UUID alias (e.g. 0x1234), " +
"UUID (lowercase hex characters e.g. " +
"'<API key>'), " +
"or recognized standard name from " +
"https:
" e.g. 'alert_notification'.",
'TypeError');
bluetooth_test(() => <API key>()
.then(({device}) => <API key>(
device.gatt.CALLS([
getPrimaryService('wrong_name')|
getPrimaryServices('wrong_name')
]),
expected,
'Wrong Service name passed.')),
test_desc); |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
var BUGNUMBER = 71107;
var summary = 'Propagate heavyweightness back up the function-nesting chain.';
test();
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var actual = outer()()(); //call the return of calling the return of outer()
var expect = 5;
reportCompare(expect, actual, summary);
exitFunc ('test');
}
function outer () {
var outer_var = 5;
function inner() {
function way_inner() {
return outer_var;
}
return way_inner;
}
return inner;
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "types.h"
#include "readline.h"
#include "reader.h"
// Declarations
MalVal *EVAL(MalVal *ast, GHashTable *env);
// read
MalVal *READ(char prompt[], char *str) {
char *line;
MalVal *ast;
if (str) {
line = str;
} else {
line = _readline(prompt);
if (!line) {
_error("EOF");
return NULL;
}
}
ast = read_str(line);
if (!str) { MAL_GC_FREE(line); }
return ast;
}
// eval
MalVal *eval_ast(MalVal *ast, GHashTable *env) {
if (!ast || mal_error) return NULL;
if (ast->type == MAL_SYMBOL) {
//g_print("EVAL symbol: %s\n", ast->val.string);
// TODO: check if not found
MalVal *res = g_hash_table_lookup(env, ast->val.string);
assert(res, "'%s' not found", ast->val.string);
return res;
} else if ((ast->type == MAL_LIST) || (ast->type == MAL_VECTOR)) {
//g_print("EVAL sequential: %s\n", _pr_str(ast,1));
MalVal *el = _map2((MalVal *(*)(void*, void*))EVAL, ast, env);
if (!el || mal_error) return NULL;
el->type = ast->type;
return el;
} else if (ast->type == MAL_HASH_MAP) {
//g_print("EVAL hash_map: %s\n", _pr_str(ast,1));
GHashTableIter iter;
gpointer key, value;
MalVal *seq = malval_new_list(MAL_LIST,
g_array_sized_new(TRUE, TRUE, sizeof(MalVal*),
_count(ast)));
<API key> (&iter, ast->val.hash_table);
while (<API key> (&iter, &key, &value)) {
MalVal *kname = malval_new_string((char *)key);
g_array_append_val(seq->val.array, kname);
MalVal *new_val = EVAL((MalVal *)value, env);
g_array_append_val(seq->val.array, new_val);
}
return _hash_map(seq);
} else {
//g_print("EVAL scalar: %s\n", _pr_str(ast,1));
return ast;
}
}
MalVal *EVAL(MalVal *ast, GHashTable *env) {
if (!ast || mal_error) return NULL;
//g_print("EVAL: %s\n", _pr_str(ast,1));
if (ast->type != MAL_LIST) {
return eval_ast(ast, env);
}
if (!ast || mal_error) return NULL;
// apply list
//g_print("EVAL apply list: %s\n", _pr_str(ast,1));
if (_count(ast) == 0) { return ast; }
MalVal *a0 = _nth(ast, 0);
assert_type(a0, MAL_SYMBOL, "Cannot invoke %s", _pr_str(a0,1));
MalVal *el = eval_ast(ast, env);
if (!el || mal_error) { return NULL; }
MalVal *(*f)(void *, void*) = (MalVal *(*)(void*, void*))_first(el);
//g_print("eval_invoke el: %s\n", _pr_str(el,1));
return f(_nth(el, 1), _nth(el, 2));
}
// print
char *PRINT(MalVal *exp) {
if (mal_error) {
return NULL;
}
return _pr_str(exp,1);
}
// repl
// read and eval
MalVal *RE(GHashTable *env, char *prompt, char *str) {
MalVal *ast, *exp;
ast = READ(prompt, str);
if (!ast || mal_error) return NULL;
exp = EVAL(ast, env);
if (ast != exp) {
malval_free(ast); // Free input structure
}
return exp;
}
// Setup the initial REPL environment
GHashTable *repl_env;
WRAP_INTEGER_OP(plus,+)
WRAP_INTEGER_OP(minus,-)
WRAP_INTEGER_OP(multiply,*)
WRAP_INTEGER_OP(divide,/)
void init_repl_env() {
repl_env = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(repl_env, "+", int_plus);
g_hash_table_insert(repl_env, "-", int_minus);
g_hash_table_insert(repl_env, "*", int_multiply);
g_hash_table_insert(repl_env, "/", int_divide);
}
int main()
{
MalVal *exp;
char *output;
char prompt[100];
MAL_GC_SETUP();
// Set the initial prompt and environment
snprintf(prompt, sizeof(prompt), "user> ");
init_repl_env();
// repl loop
for(;;) {
exp = RE(repl_env, prompt, NULL);
if (mal_error && strcmp("EOF", mal_error->val.string) == 0) {
return 0;
}
output = PRINT(exp);
if (mal_error) {
fprintf(stderr, "Error: %s\n", _pr_str(mal_error,1));
malval_free(mal_error);
mal_error = NULL;
} else if (output) {
puts(output);
MAL_GC_FREE(output); // Free output string
}
//malval_free(exp); // Free evaluated expression
}
} |
package org.opennms.features.topology.api;
public interface <API key>{
public void boundingBoxChanged(MapViewManager viewManager);
} |
require File.dirname(__FILE__) + File::SEPARATOR + 'test_helper'
class AdvancedErrorsTest < Test::Unit::TestCase
include ErrorHelper
def <API key>
@user = User.new({:login => 'blah'})
assert !@user.valid?, 'User should be invalid'
assert @user.errors.size == 1, 'There should only be one error.'
assert !@user.errors.on(:password).blank?, 'They should be a failed validations on :password'
assert @user.errors.full_messages.first == "Password can't be blank", "The message is wrong."
<API key> = %Q{
<div class="errorExplanation" id="errorExplanation">
<h2>1 error prohibited this user from being saved</h2>
<p>There were problems with the following fields:</p>
<ul>
<li>Password can't be blank</li>
</ul>
</div>
}.normalize_html
<API key> = error_messages_for(:user).normalize_html
assert <API key> == <API key>, 'Expected and actual messages should be the same'
@user = nil
end
def <API key>
@user = User.new({:password => 'blah'})
assert !@user.valid?, 'User should be invalid'
assert @user.errors.size == 1, 'There should only be one error.'
assert !@user.errors.on(:login).blank?, 'They should be a failed validations on :login'
assert @user.errors.full_messages.first == 'You really should have a login.', "The message is wrong."
<API key> = %Q{
<div class="errorExplanation" id="errorExplanation">
<h2>1 error prohibited this user from being saved</h2>
<p>There were problems with the following fields:</p>
<ul>
<li>You really should have a login.</li>
</ul>
</div>
}.normalize_html
<API key> = error_messages_for(:user).normalize_html
assert <API key> == <API key>, 'Expected and actual messages should be the same'
@user = nil
end
end |
<?php
namespace Test\Files;
use OC\Files\Filesystem;
use OCP\Share;
/**
* Class EtagTest
*
* @group DB
*
* @package Test\Files
*/
class EtagTest extends \Test\TestCase {
private $datadir;
private $tmpDir;
/**
* @var \Test\Util\User\Dummy $userBackend
*/
private $userBackend;
protected function setUp() {
parent::setUp();
\OC_Hook::clear('OC_Filesystem', 'setup');
$application = new \OCA\Files_Sharing\AppInfo\Application();
$application-><API key>();
\OCP\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File');
\OCP\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file');
$config = \OC::$server->getConfig();
$this->datadir = $config->getSystemValue('datadirectory');
$this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
$config->setSystemValue('datadirectory', $this->tmpDir);
$this->userBackend = new \Test\Util\User\Dummy();
\OC_User::useBackend($this->userBackend);
}
protected function tearDown() {
\OC::$server->getConfig()->setSystemValue('datadirectory', $this->datadir);
$this->logout();
parent::tearDown();
}
public function testNewUser() {
$user1 = $this->getUniqueID('user_');
$this->userBackend->createUser($user1, '');
$this->loginAsUser($user1);
Filesystem::mkdir('/folder');
Filesystem::mkdir('/folder/subfolder');
Filesystem::file_put_contents('/foo.txt', 'asd');
Filesystem::file_put_contents('/folder/bar.txt', 'fgh');
Filesystem::file_put_contents('/folder/subfolder/qwerty.txt', 'jkl');
$files = array('/foo.txt', '/folder/bar.txt', '/folder/subfolder', '/folder/subfolder/qwerty.txt');
$originalEtags = $this->getEtags($files);
$scanner = new \OC\Files\Utils\Scanner($user1, \OC::$server-><API key>(), \OC::$server->getLogger());
$scanner->backgroundScan('/');
$newEtags = $this->getEtags($files);
// loop over array and use assertSame over assertEquals to prevent false positives
foreach ($originalEtags as $file => $originalEtag) {
$this->assertSame($originalEtag, $newEtags[$file]);
}
}
/**
* @param string[] $files
*/
private function getEtags($files) {
$etags = array();
foreach ($files as $file) {
$info = Filesystem::getFileInfo($file);
$etags[$file] = $info['etag'];
}
return $etags;
}
} |
"""
Browser set up for acceptance tests.
"""
# pylint: disable=no-member
# pylint: disable=unused-argument
from base64 import encodestring
from json import dumps
from logging import getLogger
import requests
from django.conf import settings
from django.core.management import call_command
from lettuce import after, before, world
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.<API key> import DesiredCapabilities
from splinter.browser import Browser
import xmodule.modulestore.django
from xmodule.contentstore.django import _CONTENTSTORE
LOGGER = getLogger(__name__)
LOGGER.info("Loading the lettuce acceptance testing terrain file...")
<API key> = 20
<API key> = 60
def <API key>():
"""
Returns the Sauce Labs username and access ID as set by environment variables
"""
return {"username": settings.SAUCE.get('USERNAME'), "access-key": settings.SAUCE.get('ACCESS_ID')}
def <API key>(jobid, passed=True):
"""
Sets the job status on sauce labs
"""
config = <API key>()
url = 'http://saucelabs.com/rest/v1/{}/jobs/{}'.format(config['username'], world.jobid)
body_content = dumps({"passed": passed})
base64string = encodestring('{}:{}'.format(config['username'], config['access-key']))[:-1]
headers = {"Authorization": "Basic {}".format(base64string)}
result = requests.put(url, data=body_content, headers=headers)
return result.status_code == 200
def <API key>():
"""
Returns a DesiredCapabilities object corresponding to the environment sauce parameters
"""
<API key> = settings.SAUCE.get('BROWSER', DesiredCapabilities.CHROME)
<API key>['platform'] = settings.SAUCE.get('PLATFORM')
<API key>['version'] = settings.SAUCE.get('VERSION')
<API key>['device-type'] = settings.SAUCE.get('DEVICE')
<API key>['name'] = settings.SAUCE.get('SESSION')
<API key>['build'] = settings.SAUCE.get('BUILD')
<API key>['<API key>'] = False
<API key>['sauce-advisor'] = False
<API key>['capture-html'] = True
<API key>['record-screenshots'] = True
<API key>['selenium-version'] = "2.34.0"
<API key>['max-duration'] = 3600
<API key>['public'] = 'public restricted'
return <API key>
@before.harvest
def initial_setup(server):
"""
Launch the browser once before executing the tests.
"""
world.absorb(settings.<API key>, '<API key>')
if world.<API key> == 'local':
browser_driver = getattr(settings, 'LETTUCE_BROWSER', 'chrome')
if browser_driver == 'chrome':
<API key> = DesiredCapabilities.CHROME
<API key>['loggingPrefs'] = {
'browser': 'ALL',
}
else:
<API key> = {}
# There is an issue with ChromeDriver2 r195627 on Ubuntu
# in which we sometimes get an invalid browser session.
# This is a work-around to ensure that we get a valid session.
success = False
num_attempts = 0
while (not success) and num_attempts < <API key>:
# Load the browser and try to visit the main page
# If the browser couldn't be reached or
# the browser session is invalid, this will
# raise a WebDriverException
try:
if browser_driver == 'firefox':
# Lettuce initializes differently for firefox, and sending
# <API key> will not work. So initialize without
# sending <API key>.
world.browser = Browser(browser_driver)
else:
world.browser = Browser(browser_driver, <API key>=<API key>)
world.browser.driver.set_script_timeout(<API key>)
world.visit('/')
except WebDriverException:
LOGGER.warn("Error acquiring %s browser, retrying", browser_driver, exc_info=True)
if hasattr(world, 'browser'):
world.browser.quit()
num_attempts += 1
else:
success = True
# If we were unable to get a valid session within the limit of attempts,
# then we cannot run the tests.
if not success:
raise IOError("Could not acquire valid {driver} browser session.".format(driver=browser_driver))
world.absorb(0, 'IMPLICIT_WAIT')
world.browser.driver.set_window_size(1280, 1024)
elif world.<API key> == 'saucelabs':
config = <API key>()
world.browser = Browser(
'remote',
url="http://{}:{}@ondemand.saucelabs.com:80/wd/hub".format(config['username'], config['access-key']),
**<API key>()
)
world.absorb(30, 'IMPLICIT_WAIT')
world.browser.set_script_timeout(<API key>)
elif world.<API key> == 'grid':
world.browser = Browser(
'remote',
url=settings.SELENIUM_GRID.get('URL'),
browser=settings.SELENIUM_GRID.get('BROWSER'),
)
world.absorb(30, 'IMPLICIT_WAIT')
world.browser.driver.set_script_timeout(<API key>)
else:
raise Exception("Unknown selenium client '{}'".format(world.<API key>))
world.browser.driver.implicitly_wait(world.IMPLICIT_WAIT)
world.absorb(world.browser.driver.session_id, 'jobid')
@before.each_scenario
def reset_data(scenario):
"""
Clean out the django test database defined in the
envs/acceptance.py file: edx-platform/db/test_edx.db
"""
LOGGER.debug("Flushing the test database...")
call_command('flush', interactive=False, verbosity=0)
world.absorb({}, 'scenario_dict')
@before.each_scenario
def <API key>(scenario):
"""
Before each scenario, turn off automatic screenshots.
Args: str, scenario. Name of current scenario.
"""
world.<API key> = False
@after.each_scenario
def clear_data(scenario):
world.spew('scenario_dict')
@after.each_scenario
def reset_databases(scenario):
'''
After each scenario, all databases are cleared/dropped. Contentstore data are stored in unique databases
whereas modulestore data is in unique collection names. This data is created implicitly during the scenarios.
If no data is created during the test, these lines equivilently do nothing.
'''
xmodule.modulestore.django.modulestore()._drop_database() # pylint: disable=protected-access
xmodule.modulestore.django.<API key>()
_CONTENTSTORE.clear()
@world.absorb
def capture_screenshot(image_name):
"""
Capture a screenshot outputting it to a defined directory.
This function expects only the name of the file. It will generate
the full path of the output screenshot.
If the name contains spaces, they ill be converted to underscores.
"""
output_dir = '{}/log/auto_screenshots'.format(settings.TEST_ROOT)
image_name = '{}/{}.png'.format(output_dir, image_name.replace(' ', '_'))
try:
world.browser.driver.save_screenshot(image_name)
except WebDriverException:
LOGGER.error("Could not capture a screenshot '{}'".format(image_name))
@after.each_scenario
def screenshot_on_error(scenario):
"""
Save a screenshot to help with debugging.
"""
if scenario.failed:
try:
output_dir = '{}/log'.format(settings.TEST_ROOT)
image_name = '{}/{}.png'.format(output_dir, scenario.name.replace(' ', '_'))
world.browser.driver.save_screenshot(image_name)
except WebDriverException:
LOGGER.error('Could not capture a screenshot')
@after.each_scenario
def capture_console_log(scenario):
"""
Save the console log to help with debugging.
"""
if scenario.failed:
log = world.browser.driver.get_log('browser')
try:
output_dir = '{}/log'.format(settings.TEST_ROOT)
file_name = '{}/{}.log'.format(output_dir, scenario.name.replace(' ', '_'))
with open(file_name, 'w') as output_file:
for line in log:
output_file.write("{}{}".format(dumps(line), '\n'))
except WebDriverException:
LOGGER.error('Could not capture the console log')
def <API key>(step, when):
"""
Useful method for debugging acceptance tests that are run in Vagrant.
This method runs automatically before and after each step of an acceptance
test scenario. The variable:
world.<API key>
either enables or disabled the taking of screenshots. To change the
variable there is a convenient step defined:
I (enable|disable) auto screenshots
If you just want to capture a single screenshot at a desired point in code,
you should use the method:
world.capture_screenshot("image_name")
"""
if world.<API key>:
scenario_num = step.scenario.feature.scenarios.index(step.scenario) + 1
step_num = step.scenario.steps.index(step) + 1
step_func_name = step.defined_at.function.func_name
image_name = "{prefix:03d}__{num:03d}__{name}__{postfix}".format(
prefix=scenario_num,
num=step_num,
name=step_func_name,
postfix=when
)
world.capture_screenshot(image_name)
@before.each_step
def before_each_step(step):
<API key>(step, '1_before')
@after.each_step
def after_each_step(step):
<API key>(step, '2_after')
@after.harvest
def saucelabs_status(total):
"""
Collect data for saucelabs.
"""
if world.<API key> == 'saucelabs':
<API key>(world.jobid, total.scenarios_ran == total.scenarios_passed) |
<?php
namespace DI\Definition\Dumper;
use DI\Definition\Definition;
/**
* Dispatch a definition to the appropriate dumper.
*
* @since 4.1
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class <API key> implements DefinitionDumper
{
/**
* Definition dumpers, indexed by the class of the definition they can dump.
*
* @var DefinitionDumper[]|null
*/
private $dumpers = array();
public function __construct($dumpers = null)
{
$this->dumpers = $dumpers;
}
/**
* {@inheritdoc}
*/
public function dump(Definition $definition)
{
$this->initialize();
$class = get_class($definition);
if (! array_key_exists($class, $this->dumpers)) {
throw new \RuntimeException(sprintf(
'There is no DefinitionDumper capable of dumping this definition of type %s',
$class
));
}
$dumper = $this->dumpers[$class];
return $dumper->dump($definition);
}
private function initialize()
{
if ($this->dumpers === null) {
$this->dumpers = array(
'DI\Definition\ValueDefinition' => new <API key>(),
'DI\Definition\FactoryDefinition' => new <API key>(),
'DI\Definition\DecoratorDefinition' => new <API key>(),
'DI\Definition\AliasDefinition' => new <API key>(),
'DI\Definition\ObjectDefinition' => new <API key>(),
'DI\Definition\<API key>' => new <API key>(),
);
}
}
} |
# This file is part of Canvas.
# Canvas is free software: you can redistribute it and/or modify it under
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# details.
class ErrorsController < <API key>
PER_PAGE = 20
before_filter :<API key>
def <API key>
<API key>(:view_error_reports)
end
def index
params[:page] = params[:page].to_i > 0 ? params[:page].to_i : 1
@reports = ErrorReport.scoped(:include => :user)
@message = params[:message]
if <API key>? && @message.present?
@reports = @reports.scoped(:conditions => ["message LIKE ?", '%' + @message + '%'])
elsif params[:category].blank?
@reports = @reports.scoped(:conditions => "category != '404'")
end
if params[:category].present?
@reports = @reports.scoped(:conditions => { :category => params[:category] })
end
@reports = @reports.paginate(:per_page => PER_PAGE, :page => params[:page], :order => 'id DESC', :without_count => true)
end
def show
@reports = [ErrorReport.find(params[:id])]
render :action => 'index'
end
def <API key>?
Setting.get_cached("<API key>", "true") == "true"
end
helper_method :<API key>?
end |
FROM edxops/xenial-common:latest
MAINTAINER edxops
ADD . /edx/app/edx_ansible/edx_ansible
COPY docker/build/mongo/ansible_overrides.yml /
WORKDIR /edx/app/edx_ansible/edx_ansible/docker/plays
RUN /edx/app/edx_ansible/venvs/edx_ansible/bin/ansible-playbook mongo.yml \
-i '127.0.0.1,' -c local \
-t 'install' \
-e@/ansible_overrides.yml
WORKDIR /edx/app
EXPOSE 27017 |
# -*- coding: utf-8 -*-
# OpenERP, Open Source Management Solution
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import time
from collections import defaultdict
from openerp.osv import fields
from openerp import pooler
from openerp.report import report_sxw
class report_rappel(report_sxw.rml_parse):
_name = "account_followup.report.rappel"
def __init__(self, cr, uid, name, context=None):
super(report_rappel, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
'ids_to_objects': self._ids_to_objects,
'getLines': self._lines_get,
'get_text': self._get_text
})
def _ids_to_objects(self, ids):
pool = pooler.get_pool(self.cr.dbname)
all_lines = []
for line in pool.get('account_followup.stat.by.partner').browse(self.cr, self.uid, ids):
if line not in all_lines:
all_lines.append(line)
return all_lines
def _lines_get(self, <API key>):
return self.<API key>(<API key>.partner_id, <API key>.company_id.id)
def <API key>(self, partner, company_id):
pool = pooler.get_pool(self.cr.dbname)
moveline_obj = pool.get('account.move.line')
moveline_ids = moveline_obj.search(self.cr, self.uid, [
('partner_id', '=', partner.id),
('account_id.type', '=', 'receivable'),
('reconcile_id', '=', False),
('state', '!=', 'draft'),
('company_id', '=', company_id),
'|', ('date_maturity', '=', False), ('date_maturity', '<=', fields.date.context_today(self, self.cr, self.uid)),
])
# lines_per_currency = {currency: [line data, ...], ...}
lines_per_currency = defaultdict(list)
for line in moveline_obj.browse(self.cr, self.uid, moveline_ids):
currency = line.currency_id or line.company_id.currency_id
line_data = {
'name': line.move_id.name,
'ref': line.ref,
'date': line.date,
'date_maturity': line.date_maturity,
'balance': line.amount_currency if currency != line.company_id.currency_id else line.debit - line.credit,
'blocked': line.blocked,
'currency_id': currency,
}
lines_per_currency[currency].append(line_data)
return [{'line': lines} for lines in lines_per_currency.values()]
def _get_text(self, stat_line, followup_id, context=None):
if context is None:
context = {}
context.update({'lang': stat_line.partner_id.lang})
fp_obj = pooler.get_pool(self.cr.dbname).get('account_followup.followup')
fp_line = fp_obj.browse(self.cr, self.uid, followup_id, context=context).followup_line
if not fp_line:
raise osv.except_osv(_('Error!'),_("The followup plan defined for the current company does not have any followup action."))
#the default text will be the first fp_line in the sequence with a description.
default_text = ''
li_delay = []
for line in fp_line:
if not default_text and line.description:
default_text = line.description
li_delay.append(line.delay)
li_delay.sort(reverse=True)
a = {}
#look into the lines of the partner that already have a followup level, and take the description of the higher level for which it is available
partner_line_ids = pooler.get_pool(self.cr.dbname).get('account.move.line').search(self.cr, self.uid, [('partner_id','=',stat_line.partner_id.id),('reconcile_id','=',False),('company_id','=',stat_line.company_id.id),('blocked','=',False),('state','!=','draft'),('debit','!=',False),('account_id.type','=','receivable'),('followup_line_id','!=',False)])
partner_max_delay = 0
partner_max_text = ''
for i in pooler.get_pool(self.cr.dbname).get('account.move.line').browse(self.cr, self.uid, partner_line_ids, context=context):
if i.followup_line_id.delay > partner_max_delay and i.followup_line_id.description:
partner_max_delay = i.followup_line_id.delay
partner_max_text = i.followup_line_id.description
text = partner_max_delay and partner_max_text or default_text
if text:
lang_obj = self.pool['res.lang']
lang_ids = lang_obj.search(self.cr, self.uid, [('code', '=', stat_line.partner_id.lang)], context=context)
date_format = lang_ids and lang_obj.browse(self.cr, self.uid, lang_ids[0], context=context).date_format or '%Y-%m-%d'
text = text % {
'partner_name': stat_line.partner_id.name,
'date': time.strftime(date_format),
'company_name': stat_line.company_id.name,
'user_signature': pooler.get_pool(self.cr.dbname).get('res.users').browse(self.cr, self.uid, self.uid, context).signature or '',
}
return text
report_sxw.report_sxw('report.account_followup.followup.print',
'account_followup.stat.by.partner', 'addons/account_followup/report/<API key>.rml',
parser=report_rappel)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
@echo off
echo.
echo
SETLOCAL <API key>
IF NOT DEFINED PROACTIVE set PROACTIVE=%CD%\..\..
call "..\init.bat"
set JAVA_CMD=%JAVA_CMD% -Dgcm.provider=org.objectweb.proactive.core.component.Fractive
%JAVA_CMD% org.objectweb.proactive.examples.components.userguide.Main %*
ENDLOCAL
pause
echo.
echo |
package android.os.storage;
class StorageVolume {
int CREATOR;
int <API key>;
int mMaxFileSize;
int mStorageId;
int mAllowMassStorage;
int mMtpReserveSpace;
int mEmulated;
int mRemovable;
int mDescriptionId;
int mPath;
}
class StorageResultCode {
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int OperationSucceeded;
}
class <API key> {
int mFile;
int LOG_TAG;
}
class <API key> {
class ObbListener {
int mState;
int mDone;
int mOfficialPath;
int LOG_TAG;
}
class MountingObbThread {
int <API key>;
int mPathToContentsFile;
int mObbFilePath;
int mFileOpenOnObb;
int mStop;
}
int SAMPLE2_TEXT;
int SAMPLE1_TEXT;
int DONT_FORCE;
int FORCE;
int <API key>;
int <API key>;
int OBB_FILE_3_PASSWORD;
int OBB_FILE_2_UNSIGNED;
int <API key>;
int OBB_FILE_1_PASSWORD;
int OBB_FILE_3;
int OBB_FILE_2;
int <API key>;
int OBB_FILE_1;
int WAIT_TIME_INCR;
int MAX_WAIT_TIME;
int LOG_TAG;
int mSm;
int mContext;
}
class StorageManager {
class ListenerDelegate {
int mHandler;
int <API key>;
}
class <API key> {
int newState;
int oldState;
int path;
}
class <API key> {
int available;
}
class StorageEvent {
int mMessage;
int <API key>;
int <API key>;
int <API key>;
}
class <API key> {
int state;
int path;
}
class ObbListenerDelegate {
int nonce;
int mHandler;
int <API key>;
}
class ObbActionListener {
int mListeners;
}
int mObbActionListener;
class <API key> {
}
int mNextNonce;
int mListeners;
int mBinderListener;
int mTgtLooper;
int mMountService;
int TAG;
}
class StorageListener {
int doneFlag;
int mTargetState;
int TAG;
int localLOGV;
}
class <API key> {
}
class <API key> {
int <API key>;
int <API key>;
int ERROR_NOT_MOUNTED;
int <API key>;
int <API key>;
int ERROR_INTERNAL;
int UNMOUNTED;
int MOUNTED;
}
class <API key> {
}
class IObbActionListener {
class Stub {
int <API key>;
class Proxy {
int mRemote;
}
int DESCRIPTOR;
}
}
class <API key> {
class Stub {
int <API key>;
class Proxy {
int mRemote;
}
int DESCRIPTOR;
}
}
class <API key> {
class Stub {
int <API key>;
int <API key>;
class Proxy {
int mRemote;
}
int DESCRIPTOR;
}
}
class IMountService {
int <API key>;
int <API key>;
int ENCRYPTION_STATE_OK;
int <API key>;
class Stub {
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int <API key>;
int DESCRIPTOR;
class Proxy {
int mRemote;
}
}
}
class AsecTests {
class ShutdownObserver {
int statusCode;
int doneFlag;
}
class MultipleStorageLis {
int count;
}
class StorageListener {
int doneFlag;
int path;
int newState;
int oldState;
}
int WAIT_TIME_INCR;
int MAX_WAIT_TIME;
int FS_EXT4;
int FS_FAT;
int TAG;
int localLOGV;
int <API key>;
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/compiler/plugin.proto
#ifndef <API key>
#define <API key>
#include <string>
#include <google/protobuf/stubs/common.h>
#if <API key> < 3005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3005001 < <API key>
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/<API key>.h>
#include <google/protobuf/<API key>.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
// @@<API key>(includes)
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
namespace <API key> {
// Internal implementation detail -- do not use these members.
struct LIBPROTOC_EXPORT TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::<API key> aux[];
static const ::google::protobuf::internal::ParseTable schema[4];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOC_EXPORT AddDescriptors();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT InitDefaultsVersion();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT <API key>();
void LIBPROTOC_EXPORT <API key>();
inline void LIBPROTOC_EXPORT InitDefaults() {
InitDefaultsVersion();
<API key>();
<API key>();
<API key>();
}
} // namespace <API key>
namespace google {
namespace protobuf {
namespace compiler {
class <API key>;
class <API key>;
LIBPROTOC_EXPORT extern <API key> <API key>;
class <API key>;
class <API key>;
LIBPROTOC_EXPORT extern <API key> <API key>;
class <API key>;
class <API key>;
LIBPROTOC_EXPORT extern <API key> <API key>;
class Version;
class <API key>;
LIBPROTOC_EXPORT extern <API key> <API key>;
} // namespace compiler
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
namespace compiler {
class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@<API key>(class_definition:google.protobuf.compiler.Version) */ {
public:
Version();
virtual ~Version();
Version(const Version& from);
inline Version& operator=(const Version& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Version(Version&& from) noexcept
: Version() {
*this = ::std::move(from);
}
inline Version& operator=(Version&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* <API key>() {
return _internal_metadata_.<API key>();
}
static const ::google::protobuf::Descriptor* descriptor();
static const Version& default_instance();
static void <API key>(); // FOR INTERNAL USE ONLY
static inline const Version* <API key>() {
return reinterpret_cast<const Version*>(
&<API key>);
}
static PROTOBUF_CONSTEXPR int const <API key> =
0;
void Swap(Version* other);
friend void swap(Version& a, Version& b) {
a.Swap(&b);
}
inline Version* New() const PROTOBUF_FINAL { return New(NULL); }
Version* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const Version& from);
void MergeFrom(const Version& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool <API key>(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void <API key>(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* <API key>(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(Version* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// optional string suffix = 4;
bool has_suffix() const;
void clear_suffix();
static const int kSuffixFieldNumber = 4;
const ::std::string& suffix() const;
void set_suffix(const ::std::string& value);
#if LANG_CXX11
void set_suffix(::std::string&& value);
#endif
void set_suffix(const char* value);
void set_suffix(const char* value, size_t size);
::std::string* mutable_suffix();
::std::string* release_suffix();
void <API key>(::std::string* suffix);
// optional int32 major = 1;
bool has_major() const;
void clear_major();
static const int kMajorFieldNumber = 1;
::google::protobuf::int32 major() const;
void set_major(::google::protobuf::int32 value);
// optional int32 minor = 2;
bool has_minor() const;
void clear_minor();
static const int kMinorFieldNumber = 2;
::google::protobuf::int32 minor() const;
void set_minor(::google::protobuf::int32 value);
// optional int32 patch = 3;
bool has_patch() const;
void clear_patch();
static const int kPatchFieldNumber = 3;
::google::protobuf::int32 patch() const;
void set_patch(::google::protobuf::int32 value);
// @@<API key>(class_scope:google.protobuf.compiler.Version)
private:
void set_has_major();
void clear_has_major();
void set_has_minor();
void clear_has_minor();
void set_has_patch();
void clear_has_patch();
void set_has_suffix();
void clear_has_suffix();
::google::protobuf::internal::<API key> _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr suffix_;
::google::protobuf::int32 major_;
::google::protobuf::int32 minor_;
::google::protobuf::int32 patch_;
friend struct ::<API key>::TableStruct;
friend void ::<API key>::<API key>();
};
class LIBPROTOC_EXPORT <API key> : public ::google::protobuf::Message /* @@<API key>(class_definition:google.protobuf.compiler.<API key>) */ {
public:
<API key>();
virtual ~<API key>();
<API key>(const <API key>& from);
inline <API key>& operator=(const <API key>& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
<API key>(<API key>&& from) noexcept
: <API key>() {
*this = ::std::move(from);
}
inline <API key>& operator=(<API key>&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* <API key>() {
return _internal_metadata_.<API key>();
}
static const ::google::protobuf::Descriptor* descriptor();
static const <API key>& default_instance();
static void <API key>(); // FOR INTERNAL USE ONLY
static inline const <API key>* <API key>() {
return reinterpret_cast<const <API key>*>(
&<API key>);
}
static PROTOBUF_CONSTEXPR int const <API key> =
1;
void Swap(<API key>* other);
friend void swap(<API key>& a, <API key>& b) {
a.Swap(&b);
}
inline <API key>* New() const PROTOBUF_FINAL { return New(NULL); }
<API key>* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const <API key>& from);
void MergeFrom(const <API key>& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool <API key>(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void <API key>(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* <API key>(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(<API key>* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// repeated string file_to_generate = 1;
int <API key>() const;
void <API key>();
static const int <API key> = 1;
const ::std::string& file_to_generate(int index) const;
::std::string* <API key>(int index);
void <API key>(int index, const ::std::string& value);
#if LANG_CXX11
void <API key>(int index, ::std::string&& value);
#endif
void <API key>(int index, const char* value);
void <API key>(int index, const char* value, size_t size);
::std::string* <API key>();
void <API key>(const ::std::string& value);
#if LANG_CXX11
void <API key>(::std::string&& value);
#endif
void <API key>(const char* value);
void <API key>(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& file_to_generate() const;
::google::protobuf::RepeatedPtrField< ::std::string>* <API key>();
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
int proto_file_size() const;
void clear_proto_file();
static const int <API key> = 15;
const ::google::protobuf::FileDescriptorProto& proto_file(int index) const;
::google::protobuf::FileDescriptorProto* mutable_proto_file(int index);
::google::protobuf::FileDescriptorProto* add_proto_file();
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
mutable_proto_file();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
proto_file() const;
// optional string parameter = 2;
bool has_parameter() const;
void clear_parameter();
static const int <API key> = 2;
const ::std::string& parameter() const;
void set_parameter(const ::std::string& value);
#if LANG_CXX11
void set_parameter(::std::string&& value);
#endif
void set_parameter(const char* value);
void set_parameter(const char* value, size_t size);
::std::string* mutable_parameter();
::std::string* release_parameter();
void <API key>(::std::string* parameter);
// optional .google.protobuf.compiler.Version compiler_version = 3;
bool <API key>() const;
void <API key>();
static const int <API key> = 3;
const ::google::protobuf::compiler::Version& compiler_version() const;
::google::protobuf::compiler::Version* <API key>();
::google::protobuf::compiler::Version* <API key>();
void <API key>(::google::protobuf::compiler::Version* compiler_version);
// @@<API key>(class_scope:google.protobuf.compiler.<API key>)
private:
void set_has_parameter();
void clear_has_parameter();
void <API key>();
void <API key>();
::google::protobuf::internal::<API key> _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_;
::google::protobuf::internal::ArenaStringPtr parameter_;
::google::protobuf::compiler::Version* compiler_version_;
friend struct ::<API key>::TableStruct;
friend void ::<API key>::<API key>();
};
class LIBPROTOC_EXPORT <API key> : public ::google::protobuf::Message /* @@<API key>(class_definition:google.protobuf.compiler.<API key>.File) */ {
public:
<API key>();
virtual ~<API key>();
<API key>(const <API key>& from);
inline <API key>& operator=(const <API key>& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
<API key>(<API key>&& from) noexcept
: <API key>() {
*this = ::std::move(from);
}
inline <API key>& operator=(<API key>&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* <API key>() {
return _internal_metadata_.<API key>();
}
static const ::google::protobuf::Descriptor* descriptor();
static const <API key>& default_instance();
static void <API key>(); // FOR INTERNAL USE ONLY
static inline const <API key>* <API key>() {
return reinterpret_cast<const <API key>*>(
&<API key>);
}
static PROTOBUF_CONSTEXPR int const <API key> =
2;
void Swap(<API key>* other);
friend void swap(<API key>& a, <API key>& b) {
a.Swap(&b);
}
inline <API key>* New() const PROTOBUF_FINAL { return New(NULL); }
<API key>* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const <API key>& from);
void MergeFrom(const <API key>& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool <API key>(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void <API key>(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* <API key>(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(<API key>* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// optional string name = 1;
bool has_name() const;
void clear_name();
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
#if LANG_CXX11
void set_name(::std::string&& value);
#endif
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
// optional string insertion_point = 2;
bool has_insertion_point() const;
void <API key>();
static const int <API key> = 2;
const ::std::string& insertion_point() const;
void set_insertion_point(const ::std::string& value);
#if LANG_CXX11
void set_insertion_point(::std::string&& value);
#endif
void set_insertion_point(const char* value);
void set_insertion_point(const char* value, size_t size);
::std::string* <API key>();
::std::string* <API key>();
void <API key>(::std::string* insertion_point);
// optional string content = 15;
bool has_content() const;
void clear_content();
static const int kContentFieldNumber = 15;
const ::std::string& content() const;
void set_content(const ::std::string& value);
#if LANG_CXX11
void set_content(::std::string&& value);
#endif
void set_content(const char* value);
void set_content(const char* value, size_t size);
::std::string* mutable_content();
::std::string* release_content();
void <API key>(::std::string* content);
// @@<API key>(class_scope:google.protobuf.compiler.<API key>.File)
private:
void set_has_name();
void clear_has_name();
void <API key>();
void <API key>();
void set_has_content();
void clear_has_content();
::google::protobuf::internal::<API key> _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr insertion_point_;
::google::protobuf::internal::ArenaStringPtr content_;
friend struct ::<API key>::TableStruct;
friend void ::<API key>::<API key>();
};
class LIBPROTOC_EXPORT <API key> : public ::google::protobuf::Message /* @@<API key>(class_definition:google.protobuf.compiler.<API key>) */ {
public:
<API key>();
virtual ~<API key>();
<API key>(const <API key>& from);
inline <API key>& operator=(const <API key>& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
<API key>(<API key>&& from) noexcept
: <API key>() {
*this = ::std::move(from);
}
inline <API key>& operator=(<API key>&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* <API key>() {
return _internal_metadata_.<API key>();
}
static const ::google::protobuf::Descriptor* descriptor();
static const <API key>& default_instance();
static void <API key>(); // FOR INTERNAL USE ONLY
static inline const <API key>* <API key>() {
return reinterpret_cast<const <API key>*>(
&<API key>);
}
static PROTOBUF_CONSTEXPR int const <API key> =
3;
void Swap(<API key>* other);
friend void swap(<API key>& a, <API key>& b) {
a.Swap(&b);
}
inline <API key>* New() const PROTOBUF_FINAL { return New(NULL); }
<API key>* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const <API key>& from);
void MergeFrom(const <API key>& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool <API key>(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void <API key>(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* <API key>(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(<API key>* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
typedef <API key> File;
// repeated .google.protobuf.compiler.<API key>.File file = 15;
int file_size() const;
void clear_file();
static const int kFileFieldNumber = 15;
const ::google::protobuf::compiler::<API key>& file(int index) const;
::google::protobuf::compiler::<API key>* mutable_file(int index);
::google::protobuf::compiler::<API key>* add_file();
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::<API key> >*
mutable_file();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::<API key> >&
file() const;
// optional string error = 1;
bool has_error() const;
void clear_error();
static const int kErrorFieldNumber = 1;
const ::std::string& error() const;
void set_error(const ::std::string& value);
#if LANG_CXX11
void set_error(::std::string&& value);
#endif
void set_error(const char* value);
void set_error(const char* value, size_t size);
::std::string* mutable_error();
::std::string* release_error();
void set_allocated_error(::std::string* error);
// @@<API key>(class_scope:google.protobuf.compiler.<API key>)
private:
void set_has_error();
void clear_has_error();
::google::protobuf::internal::<API key> _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::<API key> > file_;
::google::protobuf::internal::ArenaStringPtr error_;
friend struct ::<API key>::TableStruct;
friend void ::<API key>::<API key>();
};
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Version
// optional int32 major = 1;
inline bool Version::has_major() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void Version::set_has_major() {
_has_bits_[0] |= 0x00000002u;
}
inline void Version::clear_has_major() {
_has_bits_[0] &= ~0x00000002u;
}
inline void Version::clear_major() {
major_ = 0;
clear_has_major();
}
inline ::google::protobuf::int32 Version::major() const {
// @@<API key>(field_get:google.protobuf.compiler.Version.major)
return major_;
}
inline void Version::set_major(::google::protobuf::int32 value) {
set_has_major();
major_ = value;
// @@<API key>(field_set:google.protobuf.compiler.Version.major)
}
// optional int32 minor = 2;
inline bool Version::has_minor() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void Version::set_has_minor() {
_has_bits_[0] |= 0x00000004u;
}
inline void Version::clear_has_minor() {
_has_bits_[0] &= ~0x00000004u;
}
inline void Version::clear_minor() {
minor_ = 0;
clear_has_minor();
}
inline ::google::protobuf::int32 Version::minor() const {
// @@<API key>(field_get:google.protobuf.compiler.Version.minor)
return minor_;
}
inline void Version::set_minor(::google::protobuf::int32 value) {
set_has_minor();
minor_ = value;
// @@<API key>(field_set:google.protobuf.compiler.Version.minor)
}
// optional int32 patch = 3;
inline bool Version::has_patch() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void Version::set_has_patch() {
_has_bits_[0] |= 0x00000008u;
}
inline void Version::clear_has_patch() {
_has_bits_[0] &= ~0x00000008u;
}
inline void Version::clear_patch() {
patch_ = 0;
clear_has_patch();
}
inline ::google::protobuf::int32 Version::patch() const {
// @@<API key>(field_get:google.protobuf.compiler.Version.patch)
return patch_;
}
inline void Version::set_patch(::google::protobuf::int32 value) {
set_has_patch();
patch_ = value;
// @@<API key>(field_set:google.protobuf.compiler.Version.patch)
}
// optional string suffix = 4;
inline bool Version::has_suffix() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void Version::set_has_suffix() {
_has_bits_[0] |= 0x00000001u;
}
inline void Version::clear_has_suffix() {
_has_bits_[0] &= ~0x00000001u;
}
inline void Version::clear_suffix() {
suffix_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
clear_has_suffix();
}
inline const ::std::string& Version::suffix() const {
// @@<API key>(field_get:google.protobuf.compiler.Version.suffix)
return suffix_.GetNoArena();
}
inline void Version::set_suffix(const ::std::string& value) {
set_has_suffix();
suffix_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.Version.suffix)
}
#if LANG_CXX11
inline void Version::set_suffix(::std::string&& value) {
set_has_suffix();
suffix_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.Version.suffix)
}
#endif
inline void Version::set_suffix(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_suffix();
suffix_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.Version.suffix)
}
inline void Version::set_suffix(const char* value, size_t size) {
set_has_suffix();
suffix_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.Version.suffix)
}
inline ::std::string* Version::mutable_suffix() {
set_has_suffix();
// @@<API key>(field_mutable:google.protobuf.compiler.Version.suffix)
return suffix_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* Version::release_suffix() {
// @@<API key>(field_release:google.protobuf.compiler.Version.suffix)
clear_has_suffix();
return suffix_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void Version::<API key>(::std::string* suffix) {
if (suffix != NULL) {
set_has_suffix();
} else {
clear_has_suffix();
}
suffix_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), suffix);
// @@<API key>(field_set_allocated:google.protobuf.compiler.Version.suffix)
}
// <API key>
// repeated string file_to_generate = 1;
inline int <API key>::<API key>() const {
return file_to_generate_.size();
}
inline void <API key>::<API key>() {
file_to_generate_.Clear();
}
inline const ::std::string& <API key>::file_to_generate(int index) const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.file_to_generate)
return file_to_generate_.Get(index);
}
inline ::std::string* <API key>::<API key>(int index) {
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.file_to_generate)
return file_to_generate_.Mutable(index);
}
inline void <API key>::<API key>(int index, const ::std::string& value) {
// @@<API key>(field_set:google.protobuf.compiler.<API key>.file_to_generate)
file_to_generate_.Mutable(index)->assign(value);
}
#if LANG_CXX11
inline void <API key>::<API key>(int index, ::std::string&& value) {
// @@<API key>(field_set:google.protobuf.compiler.<API key>.file_to_generate)
file_to_generate_.Mutable(index)->assign(std::move(value));
}
#endif
inline void <API key>::<API key>(int index, const char* value) {
GOOGLE_DCHECK(value != NULL);
file_to_generate_.Mutable(index)->assign(value);
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.file_to_generate)
}
inline void <API key>::<API key>(int index, const char* value, size_t size) {
file_to_generate_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.file_to_generate)
}
inline ::std::string* <API key>::<API key>() {
// @@<API key>(field_add_mutable:google.protobuf.compiler.<API key>.file_to_generate)
return file_to_generate_.Add();
}
inline void <API key>::<API key>(const ::std::string& value) {
file_to_generate_.Add()->assign(value);
// @@<API key>(field_add:google.protobuf.compiler.<API key>.file_to_generate)
}
#if LANG_CXX11
inline void <API key>::<API key>(::std::string&& value) {
file_to_generate_.Add(std::move(value));
// @@<API key>(field_add:google.protobuf.compiler.<API key>.file_to_generate)
}
#endif
inline void <API key>::<API key>(const char* value) {
GOOGLE_DCHECK(value != NULL);
file_to_generate_.Add()->assign(value);
// @@<API key>(field_add_char:google.protobuf.compiler.<API key>.file_to_generate)
}
inline void <API key>::<API key>(const char* value, size_t size) {
file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@<API key>(field_add_pointer:google.protobuf.compiler.<API key>.file_to_generate)
}
inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
<API key>::file_to_generate() const {
// @@<API key>(field_list:google.protobuf.compiler.<API key>.file_to_generate)
return file_to_generate_;
}
inline ::google::protobuf::RepeatedPtrField< ::std::string>*
<API key>::<API key>() {
// @@<API key>(field_mutable_list:google.protobuf.compiler.<API key>.file_to_generate)
return &file_to_generate_;
}
// optional string parameter = 2;
inline bool <API key>::has_parameter() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void <API key>::set_has_parameter() {
_has_bits_[0] |= 0x00000001u;
}
inline void <API key>::clear_has_parameter() {
_has_bits_[0] &= ~0x00000001u;
}
inline void <API key>::clear_parameter() {
parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
clear_has_parameter();
}
inline const ::std::string& <API key>::parameter() const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.parameter)
return parameter_.GetNoArena();
}
inline void <API key>::set_parameter(const ::std::string& value) {
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.<API key>.parameter)
}
#if LANG_CXX11
inline void <API key>::set_parameter(::std::string&& value) {
set_has_parameter();
parameter_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.<API key>.parameter)
}
#endif
inline void <API key>::set_parameter(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.parameter)
}
inline void <API key>::set_parameter(const char* value, size_t size) {
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.parameter)
}
inline ::std::string* <API key>::mutable_parameter() {
set_has_parameter();
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.parameter)
return parameter_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* <API key>::release_parameter() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.parameter)
clear_has_parameter();
return parameter_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void <API key>::<API key>(::std::string* parameter) {
if (parameter != NULL) {
set_has_parameter();
} else {
clear_has_parameter();
}
parameter_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), parameter);
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.parameter)
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
inline int <API key>::proto_file_size() const {
return proto_file_.size();
}
inline const ::google::protobuf::FileDescriptorProto& <API key>::proto_file(int index) const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.proto_file)
return proto_file_.Get(index);
}
inline ::google::protobuf::FileDescriptorProto* <API key>::mutable_proto_file(int index) {
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.proto_file)
return proto_file_.Mutable(index);
}
inline ::google::protobuf::FileDescriptorProto* <API key>::add_proto_file() {
// @@<API key>(field_add:google.protobuf.compiler.<API key>.proto_file)
return proto_file_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >*
<API key>::mutable_proto_file() {
// @@<API key>(field_mutable_list:google.protobuf.compiler.<API key>.proto_file)
return &proto_file_;
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >&
<API key>::proto_file() const {
// @@<API key>(field_list:google.protobuf.compiler.<API key>.proto_file)
return proto_file_;
}
// optional .google.protobuf.compiler.Version compiler_version = 3;
inline bool <API key>::<API key>() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void <API key>::<API key>() {
_has_bits_[0] |= 0x00000002u;
}
inline void <API key>::<API key>() {
_has_bits_[0] &= ~0x00000002u;
}
inline void <API key>::<API key>() {
if (compiler_version_ != NULL) compiler_version_->Clear();
<API key>();
}
inline const ::google::protobuf::compiler::Version& <API key>::compiler_version() const {
const ::google::protobuf::compiler::Version* p = compiler_version_;
// @@<API key>(field_get:google.protobuf.compiler.<API key>.compiler_version)
return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::compiler::Version*>(
&::google::protobuf::compiler::<API key>);
}
inline ::google::protobuf::compiler::Version* <API key>::<API key>() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.compiler_version)
<API key>();
::google::protobuf::compiler::Version* temp = compiler_version_;
compiler_version_ = NULL;
return temp;
}
inline ::google::protobuf::compiler::Version* <API key>::<API key>() {
<API key>();
if (compiler_version_ == NULL) {
compiler_version_ = new ::google::protobuf::compiler::Version;
}
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.compiler_version)
return compiler_version_;
}
inline void <API key>::<API key>(::google::protobuf::compiler::Version* compiler_version) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete compiler_version_;
}
if (compiler_version) {
::google::protobuf::Arena* submessage_arena = NULL;
if (message_arena != submessage_arena) {
compiler_version = ::google::protobuf::internal::GetOwnedMessage(
message_arena, compiler_version, submessage_arena);
}
<API key>();
} else {
<API key>();
}
compiler_version_ = compiler_version;
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.compiler_version)
}
// <API key>
// optional string name = 1;
inline bool <API key>::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void <API key>::set_has_name() {
_has_bits_[0] |= 0x00000001u;
}
inline void <API key>::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void <API key>::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
clear_has_name();
}
inline const ::std::string& <API key>::name() const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.File.name)
return name_.GetNoArena();
}
inline void <API key>::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.<API key>.File.name)
}
#if LANG_CXX11
inline void <API key>::set_name(::std::string&& value) {
set_has_name();
name_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.<API key>.File.name)
}
#endif
inline void <API key>::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.File.name)
}
inline void <API key>::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.File.name)
}
inline ::std::string* <API key>::mutable_name() {
set_has_name();
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.File.name)
return name_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* <API key>::release_name() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.File.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void <API key>::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
clear_has_name();
}
name_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), name);
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.File.name)
}
// optional string insertion_point = 2;
inline bool <API key>::has_insertion_point() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void <API key>::<API key>() {
_has_bits_[0] |= 0x00000002u;
}
inline void <API key>::<API key>() {
_has_bits_[0] &= ~0x00000002u;
}
inline void <API key>::<API key>() {
insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
<API key>();
}
inline const ::std::string& <API key>::insertion_point() const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.File.insertion_point)
return insertion_point_.GetNoArena();
}
inline void <API key>::set_insertion_point(const ::std::string& value) {
<API key>();
insertion_point_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.<API key>.File.insertion_point)
}
#if LANG_CXX11
inline void <API key>::set_insertion_point(::std::string&& value) {
<API key>();
insertion_point_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.<API key>.File.insertion_point)
}
#endif
inline void <API key>::set_insertion_point(const char* value) {
GOOGLE_DCHECK(value != NULL);
<API key>();
insertion_point_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.File.insertion_point)
}
inline void <API key>::set_insertion_point(const char* value, size_t size) {
<API key>();
insertion_point_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.File.insertion_point)
}
inline ::std::string* <API key>::<API key>() {
<API key>();
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.File.insertion_point)
return insertion_point_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* <API key>::<API key>() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.File.insertion_point)
<API key>();
return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void <API key>::<API key>(::std::string* insertion_point) {
if (insertion_point != NULL) {
<API key>();
} else {
<API key>();
}
insertion_point_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), insertion_point);
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.File.insertion_point)
}
// optional string content = 15;
inline bool <API key>::has_content() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void <API key>::set_has_content() {
_has_bits_[0] |= 0x00000004u;
}
inline void <API key>::clear_has_content() {
_has_bits_[0] &= ~0x00000004u;
}
inline void <API key>::clear_content() {
content_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
clear_has_content();
}
inline const ::std::string& <API key>::content() const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.File.content)
return content_.GetNoArena();
}
inline void <API key>::set_content(const ::std::string& value) {
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.<API key>.File.content)
}
#if LANG_CXX11
inline void <API key>::set_content(::std::string&& value) {
set_has_content();
content_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.<API key>.File.content)
}
#endif
inline void <API key>::set_content(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.File.content)
}
inline void <API key>::set_content(const char* value, size_t size) {
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.File.content)
}
inline ::std::string* <API key>::mutable_content() {
set_has_content();
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.File.content)
return content_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* <API key>::release_content() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.File.content)
clear_has_content();
return content_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void <API key>::<API key>(::std::string* content) {
if (content != NULL) {
set_has_content();
} else {
clear_has_content();
}
content_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), content);
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.File.content)
}
// <API key>
// optional string error = 1;
inline bool <API key>::has_error() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void <API key>::set_has_error() {
_has_bits_[0] |= 0x00000001u;
}
inline void <API key>::clear_has_error() {
_has_bits_[0] &= ~0x00000001u;
}
inline void <API key>::clear_error() {
error_.ClearToEmptyNoArena(&::google::protobuf::internal::<API key>());
clear_has_error();
}
inline const ::std::string& <API key>::error() const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.error)
return error_.GetNoArena();
}
inline void <API key>::set_error(const ::std::string& value) {
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::<API key>(), value);
// @@<API key>(field_set:google.protobuf.compiler.<API key>.error)
}
#if LANG_CXX11
inline void <API key>::set_error(::std::string&& value) {
set_has_error();
error_.SetNoArena(
&::google::protobuf::internal::<API key>(), ::std::move(value));
// @@<API key>(field_set_rvalue:google.protobuf.compiler.<API key>.error)
}
#endif
inline void <API key>::set_error(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::<API key>(), ::std::string(value));
// @@<API key>(field_set_char:google.protobuf.compiler.<API key>.error)
}
inline void <API key>::set_error(const char* value, size_t size) {
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::<API key>(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@<API key>(field_set_pointer:google.protobuf.compiler.<API key>.error)
}
inline ::std::string* <API key>::mutable_error() {
set_has_error();
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.error)
return error_.MutableNoArena(&::google::protobuf::internal::<API key>());
}
inline ::std::string* <API key>::release_error() {
// @@<API key>(field_release:google.protobuf.compiler.<API key>.error)
clear_has_error();
return error_.ReleaseNoArena(&::google::protobuf::internal::<API key>());
}
inline void <API key>::set_allocated_error(::std::string* error) {
if (error != NULL) {
set_has_error();
} else {
clear_has_error();
}
error_.SetAllocatedNoArena(&::google::protobuf::internal::<API key>(), error);
// @@<API key>(field_set_allocated:google.protobuf.compiler.<API key>.error)
}
// repeated .google.protobuf.compiler.<API key>.File file = 15;
inline int <API key>::file_size() const {
return file_.size();
}
inline void <API key>::clear_file() {
file_.Clear();
}
inline const ::google::protobuf::compiler::<API key>& <API key>::file(int index) const {
// @@<API key>(field_get:google.protobuf.compiler.<API key>.file)
return file_.Get(index);
}
inline ::google::protobuf::compiler::<API key>* <API key>::mutable_file(int index) {
// @@<API key>(field_mutable:google.protobuf.compiler.<API key>.file)
return file_.Mutable(index);
}
inline ::google::protobuf::compiler::<API key>* <API key>::add_file() {
// @@<API key>(field_add:google.protobuf.compiler.<API key>.file)
return file_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::<API key> >*
<API key>::mutable_file() {
// @@<API key>(field_mutable_list:google.protobuf.compiler.<API key>.file)
return &file_;
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::<API key> >&
<API key>::file() const {
// @@<API key>(field_list:google.protobuf.compiler.<API key>.file)
return file_;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@<API key>(namespace_scope)
} // namespace compiler
} // namespace protobuf
} // namespace google
// @@<API key>(global_scope)
#endif // <API key> |
package jade.tools.logging.ontology;
//#J2ME_EXCLUDE_FILE
import jade.content.AgentAction;
public class SetFile implements AgentAction {
private String file;
private String logger;
public SetFile() {
}
public SetFile(String logger, String file) {
this.logger = logger;
this.file = file;
}
public SetFile(String file) {
setFile(file);
}
public void setFile(String file) {
this.file = file;
}
public String getFile() {
return file;
}
public String getLogger() {
return logger;
}
public void setLogger(String logger) {
this.logger = logger;
}
} |
module Cms
module WebApi
attr_accessor :current_user
# Log in to the CMS admin.
def login_as(username, password, path=cms.login_path)
logout
visit path
fill_in 'Login', :with => username
fill_in 'Password', :with => password
click_button 'Sign in'
end
def fill_in_password(pw)
fill_in "user_password", with: pw
fill_in "<API key>", with: pw
end
def acceptable_password
"atleast8chars"
end
def <API key>
login_as(Cms::Authentication::<API key>::EXPECTED_LOGIN, Cms::Authentication::<API key>::EXPECTED_PASSWORD)
end
def <API key>
assert_equal 1, Cms::ExternalUser.count
end
def logout
visit cms.logout_path
end
def <API key>
Cms::Page.order("created_at DESC").first
end
# For inspecting content of a page. Will follow the 'editing' frame if it exists.
# Works around lack of within_frame for rack test.
# WARNING: Does not 'return' to previous page, so don't expect tests like this to work:
# <pre>
# <API key> do
# assert some_content_exists
# end
# assert <API key>
# </pre>
def <API key>
if <API key>?
<API key>
end
yield
end
# View the content iframe as a top level page.
def <API key>
visit find(<API key>)['src']
end
def <API key>?
page.has_selector?(<API key>)
end
def <API key>
"iframe[id='page_content']"
end
def top_form_buttons
find(".top-buttons")
end
def <API key>
find("button[data-purpose=subheader]")
end
def click_save_button
top_form_buttons.click_on('Save')
end
def <API key>
top_form_buttons.click_on('Publish')
end
def click_user_search
click_on 'user_search_submit'
end
end
end
World(Cms::WebApi) |
<div id="brjs.dashboard.app.footer-right">
<div class="footer-logo">
<a href="http:
</div>
</div> |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Module: Selenium::WebDriver::HTML5::SharedWebStorage
— Documentation by YARD 0.8.1
</title>
<link rel="stylesheet" href="../../../css/style.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="../../../css/common.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
hasFrames = window.top.frames.main ? true : false;
relpath = '../../../';
framesUrl = "../../../frames.html#!" + escape(window.location.href);
</script>
<script type="text/javascript" charset="utf-8" src="../../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../../js/app.js"></script>
</head>
<body>
<div id="header">
<div id="menu">
<a href="../../../_index.html">Index (S)</a> »
<span class='title'><span class='object_link'><a href="../../../Selenium.html" title="Selenium (module)">Selenium</a></span></span> » <span class='title'><span class='object_link'><a href="../../WebDriver.html" title="Selenium::WebDriver (module)">WebDriver</a></span></span> » <span class='title'><span class='object_link'><a href="../HTML5.html" title="Selenium::WebDriver::HTML5 (module)">HTML5</a></span></span>
»
<span class="title">SharedWebStorage</span>
<div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div>
</div>
<div id="search">
<a class="full_list_link" id="class_list_link"
href="../../../class_list.html">
Class List
</a>
<a class="full_list_link" id="method_list_link"
href="../../../method_list.html">
Method List
</a>
<a class="full_list_link" id="file_list_link"
href="../../../file_list.html">
File List
</a>
</div>
<div class="clear"></div>
</div>
<iframe id="search_frame"></iframe>
<div id="content"><h1>Module: Selenium::WebDriver::HTML5::SharedWebStorage
</h1>
<dl class="box">
<dt class="r1">Includes:</dt>
<dd class="r1">Enumerable</dd>
<dt class="r2">Included in:</dt>
<dd class="r2"><span class='object_link'><a href="LocalStorage.html" title="Selenium::WebDriver::HTML5::LocalStorage (class)">LocalStorage</a></span>, <span class='object_link'><a href="SessionStorage.html" title="Selenium::WebDriver::HTML5::SessionStorage (class)">SessionStorage</a></span></dd>
<dt class="r1 last">Defined in:</dt>
<dd class="r1 last">rb/lib/selenium/webdriver/common/html5/shared_web_storage.rb</dd>
</dl>
<div class="clear"></div>
<h2>
Instance Method Summary
<small>(<a href="#" class="summary_toggle">collapse</a>)</small>
</h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#<API key>" title="#each (instance method)">- (Object) <strong>each</strong>(&blk) </a>
</span>
<span class="summary_desc"><div class='inline'></div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#empty%3F-instance_method" title="#empty? (instance method)">- (Boolean) <strong>empty?</strong> </a>
</span>
<span class="summary_desc"><div class='inline'></div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#<API key>" title="#fetch (instance method)">- (Object) <strong>fetch</strong>(key, &blk) </a>
</span>
<span class="summary_desc"><div class='inline'></div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#key%3F-instance_method" title="#key? (instance method)">- (Boolean) <strong>key?</strong>(key) </a>
(also: #member?, #has_key?)
</span>
<span class="summary_desc"><div class='inline'></div></span>
</li>
</ul>
<div id="<API key>" class="method_details_list">
<h2>Instance Method Details</h2>
<div class="method_details first">
<h3 class="signature first" id="<API key>">
- (<tt>Object</tt>) <strong>each</strong>(&blk)
</h3><table class="source_code">
<tr>
<td>
<pre class="lines">
31
32
33
34
35
36
37</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/webdriver/common/html5/shared_web_storage.rb', line 31</span>
<span class='kw'>def</span> <span class='id identifier rubyid_each'>each</span><span class='lparen'>(</span><span class='op'>&</span><span class='id identifier rubyid_blk'>blk</span><span class='rparen'>)</span>
<span class='kw'>return</span> <span class='id identifier rubyid_enum_for'>enum_for</span><span class='lparen'>(</span><span class='symbol'>:each</span><span class='rparen'>)</span> <span class='kw'>unless</span> <span class='id identifier rubyid_block_given?'>block_given?</span>
<span class='id identifier rubyid_keys'>keys</span><span class='period'>.</span><span class='id identifier rubyid_each'>each</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_k'>k</span><span class='op'>|</span>
<span class='kw'>yield</span> <span class='id identifier rubyid_k'>k</span><span class='comma'>,</span> <span class='kw'>self</span><span class='lbracket'>[</span><span class='id identifier rubyid_k'>k</span><span class='rbracket'>]</span>
<span class='kw'>end</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="empty?-instance_method">
- (<tt>Boolean</tt>) <strong>empty?</strong>
</h3><div class="docstring">
<div class="discussion">
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
27
28
29</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/webdriver/common/html5/shared_web_storage.rb', line 27</span>
<span class='kw'>def</span> <span class='id identifier rubyid_empty?'>empty?</span>
<span class='id identifier rubyid_size'>size</span> <span class='op'>==</span> <span class='int'>0</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="<API key>">
- (<tt>Object</tt>) <strong>fetch</strong>(key, &blk)
</h3><table class="source_code">
<tr>
<td>
<pre class="lines">
14
15
16
17
18
19
20
21
22
23
24
25</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/webdriver/common/html5/shared_web_storage.rb', line 14</span>
<span class='kw'>def</span> <span class='id identifier rubyid_fetch'>fetch</span><span class='lparen'>(</span><span class='id identifier rubyid_key'>key</span><span class='comma'>,</span> <span class='op'>&</span><span class='id identifier rubyid_blk'>blk</span><span class='rparen'>)</span>
<span class='kw'>if</span> <span class='kw'>self</span><span class='period'>.</span><span class='id identifier rubyid_key?'>key?</span> <span class='id identifier rubyid_key'>key</span>
<span class='kw'>return</span> <span class='kw'>self</span><span class='lbracket'>[</span><span class='id identifier rubyid_key'>key</span><span class='rbracket'>]</span>
<span class='kw'>end</span>
<span class='kw'>if</span> <span class='id identifier rubyid_block_given?'>block_given?</span>
<span class='kw'>yield</span> <span class='id identifier rubyid_key'>key</span>
<span class='kw'>else</span>
<span class='comment'># should be KeyError, but it's 1.9-specific
</span> <span class='id identifier rubyid_raise'>raise</span> <span class='const'>IndexError</span><span class='comma'>,</span> <span class='tstring'><span class='tstring_beg'>"</span><span class='tstring_content'>missing key </span><span class='embexpr_beg'>#{</span><span class='id identifier rubyid_key'>key</span><span class='period'>.</span><span class='id identifier rubyid_inspect'>inspect</span><span class='rbrace'>}</span><span class='tstring_end'>"</span></span>
<span class='kw'>end</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<div class="method_details ">
<h3 class="signature " id="key?-instance_method">
- (<tt>Boolean</tt>) <strong>key?</strong>(key)
<span class="aliases">Also known as:
<span class="names"><span id='member?-instance_method'>member?</span>, <span id='has_key?-instance_method'>has_key?</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
</div>
</div>
<div class="tags">
<p class="tag_title">Returns:</p>
<ul class="return">
<li>
<span class='type'>(<tt>Boolean</tt>)</span>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
8
9
10</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/webdriver/common/html5/shared_web_storage.rb', line 8</span>
<span class='kw'>def</span> <span class='id identifier rubyid_key?'>key?</span><span class='lparen'>(</span><span class='id identifier rubyid_key'>key</span><span class='rparen'>)</span>
<span class='id identifier rubyid_keys'>keys</span><span class='period'>.</span><span class='id identifier rubyid_include?'>include?</span> <span class='id identifier rubyid_key'>key</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated on Thu Jul 19 12:32:24 2012 by
<a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a>
0.8.1 (ruby-1.9.3).
</div>
</body>
</html> |
class <API key> < ActiveRecord::Migration
def up
remove_column :datasets, :import_schedule_id
add_column :import_schedules, :<API key>, :integer
end
def down
add_column :datasets, :import_schedule_id, :integer
remove_column :import_schedules, :<API key>
end
end |
/**
* This entity represents a project which is a container for tickets.
*/
Ext.define('Ticket.model.Project', {
extend: 'Ticket.model.Base',
fields: [
'name',
{ name: 'organizationId', reference: 'Organization' }, {
name: 'leadId',
unique: true,
reference: 'User'
}
]
}); |
package com.querydsl.jpa.codegen;
public class MyEntity {
private String pk1, pk2, prop1;
public String getPk1() {
return pk1;
}
public void setPk1(String pk1) {
this.pk1 = pk1;
}
public String getPk2() {
return pk2;
}
public void setPk2(String pk2) {
this.pk2 = pk2;
}
public String getProp1() {
return prop1;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
} |
object Test {
def main(args: Array[String]): Unit = {
Lib.track {
Lib.printStack("main1")
Lib.printStack("main2")
}
Lib.track {
Lib.track {
Lib.printStack("main3")
Lib.printStack("main4")
}
}
Lib.fact(0) {
Lib.fact(2) {
Lib.printStack("main1", -1)
Lib.printStack("main2", -1)
}
}
}
} |
class <API key> < ActiveRecord::Migration
def change
add_column :users, :subject_limit, :integer
end
end |
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Adapter | node', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let adapter = this.owner.lookup('adapter:node');
assert.ok(adapter);
});
}); |
#ifndef _INC_STRING_
#define STR_LEN 40
char * strcat(s, append);
char * strcpy(to, from);
uint strlen(str);
char * strchr(s, c);
uint strcmp(s1, s2);
char * strncat(dst, src, n);
int strncmp(s1, s2, n);
char * strncpy(dst, src, n);
char * strpbrk(s, c);
char * strtok(s, delim);
char * strlwr(s);
char * strupr(s);
int strcasecmp(s1, s2);
int strncasecmp(s1, s2, n);
char * strsep(stringp, delim);
/*
size_t strcspn(const char *_s1, const char *_s2);
char * strrchr(const char *_s, int _c);
size_t strspn(const char *_s1, const char *_s2);
char * strstr(const char *_s1, const char *_s2);
size_t strxfrm(char *_s1, const char *_s2, size_t _n);
char * stpcpy(char *_dest, const char *_src);
*/
/*** impossible or unnecessary to define ***/
/*
char * strerror(int _errcode);
void * memchr(const void *_s, int _c, size_t _n);
int memcmp(const void *_s1, const void *_s2, size_t _n);
void * memcpy(void *_dest, const void *_src, size_t _n);
void * memmove(void *_s1, const void *_s2, size_t _n);
void * memset(void *_s, int _c, size_t _n);
int strcoll(const char *_s1, const char *_s2);
void * memccpy(void *_to, const void *_from, int c, size_t n);
char * rindex(const char *_string, int _c);
int stricmp(const char *_s1, const char *_s2);
int strnicmp(const char *_s1, const char *_s2, size_t _n);
int bcmp(const void *_ptr1, const void *_ptr2, int _length);
void * bcopy(const void *_a, void *_b, size_t _len);
void * bzero(void *ptr, size_t _len);
int ffs(int _mask);
char * index(const char *_string, int _c);
char * strdup(const char *_s);
*/
#define _INC_STRING_
#endif |
require "vertx"
include Vertx
EventBus.register_handler('ping-address') do |msg|
msg.reply 'pong!'
puts 'sent back pong ruby'
end |
#include "clar_libgit2.h"
static const char* tagger_name = "Vicent Marti";
static const char* tagger_email = "vicent@github.com";
static const char* tagger_message = "This is my tag.\n\nThere are many tags, but this one is mine\n";
static const char *tag2_id = "<SHA1-like>";
static const char *tagged_commit = "<SHA1-like>";
static git_repository *g_repo;
/* Fixture setup and teardown */
void <API key>(void)
{
g_repo = cl_git_sandbox_init("testrepo");
}
void <API key>(void)
{
<API key>();
}
void <API key>(void)
{
/* write a tag to the repository and read it again */
git_tag *tag;
git_oid target_id, tag_id;
git_signature *tagger;
const git_signature *tagger1;
git_reference *ref_tag;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
/* create signature */
cl_git_pass(git_signature_new(&tagger, tagger_name, tagger_email, 123456789, 60));
cl_git_pass(
git_tag_create(&tag_id, g_repo,
"the-tag", target, tagger, tagger_message, 0)
);
git_object_free(target);
git_signature_free(tagger);
cl_git_pass(git_tag_lookup(&tag, g_repo, &tag_id));
cl_assert(git_oid_cmp(git_tag_target_id(tag), &target_id) == 0);
/* Check attributes were set correctly */
tagger1 = git_tag_tagger(tag);
cl_assert(tagger1 != NULL);
cl_assert_equal_s(tagger1->name, tagger_name);
cl_assert_equal_s(tagger1->email, tagger_email);
cl_assert(tagger1->when.time == 123456789);
cl_assert(tagger1->when.offset == 60);
cl_assert_equal_s(git_tag_message(tag), tagger_message);
cl_git_pass(<API key>(&ref_tag, g_repo, "refs/tags/the-tag"));
cl_assert(git_oid_cmp(<API key>(ref_tag), &tag_id) == 0);
cl_git_pass(<API key>(ref_tag));
git_reference_free(ref_tag);
git_tag_free(tag);
}
void <API key>(void)
{
/* Attempt to write a tag bearing the same name than an already existing tag */
git_oid target_id, tag_id;
git_signature *tagger;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
/* create signature */
cl_git_pass(git_signature_new(&tagger, tagger_name, tagger_email, 123456789, 60));
cl_assert_equal_i(GIT_EEXISTS, git_tag_create(
&tag_id, /* out id */
g_repo,
"e90810b",
target,
tagger,
tagger_message,
0));
git_object_free(target);
git_signature_free(tagger);
}
void <API key>(void)
{
/* Replace an already existing tag */
git_oid target_id, tag_id, old_tag_id;
git_signature *tagger;
git_reference *ref_tag;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
cl_git_pass(<API key>(&ref_tag, g_repo, "refs/tags/e90810b"));
git_oid_cpy(&old_tag_id, <API key>(ref_tag));
git_reference_free(ref_tag);
/* create signature */
cl_git_pass(git_signature_new(&tagger, tagger_name, tagger_email, 123456789, 60));
cl_git_pass(git_tag_create(
&tag_id, /* out id */
g_repo,
"e90810b",
target,
tagger,
tagger_message,
1));
git_object_free(target);
git_signature_free(tagger);
cl_git_pass(<API key>(&ref_tag, g_repo, "refs/tags/e90810b"));
cl_assert(git_oid_cmp(<API key>(ref_tag), &tag_id) == 0);
cl_assert(git_oid_cmp(<API key>(ref_tag), &old_tag_id) != 0);
git_reference_free(ref_tag);
}
void <API key>(void)
{
/* write a lightweight tag to the repository and read it again */
git_oid target_id, object_id;
git_reference *ref_tag;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
cl_git_pass(<API key>(
&object_id,
g_repo,
"light-tag",
target,
0));
git_object_free(target);
cl_assert(git_oid_cmp(&object_id, &target_id) == 0);
cl_git_pass(<API key>(&ref_tag, g_repo, "refs/tags/light-tag"));
cl_assert(git_oid_cmp(<API key>(ref_tag), &target_id) == 0);
cl_git_pass(git_tag_delete(g_repo, "light-tag"));
git_reference_free(ref_tag);
}
void <API key>(void)
{
/* Attempt to write a lightweight tag bearing the same name than an already existing tag */
git_oid target_id, object_id, existing_object_id;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
cl_assert_equal_i(GIT_EEXISTS, <API key>(
&object_id,
g_repo,
"e90810b",
target,
0));
git_oid_fromstr(&existing_object_id, tag2_id);
cl_assert(git_oid_cmp(&object_id, &existing_object_id) == 0);
git_object_free(target);
}
void <API key>(void)
{
/* Delete an already existing tag */
git_reference *ref_tag;
cl_git_pass(git_tag_delete(g_repo, "e90810b"));
cl_git_fail(<API key>(&ref_tag, g_repo, "refs/tags/e90810b"));
git_reference_free(ref_tag);
}
void <API key>(void)
{
git_oid target_id, tag_id;
git_signature *tagger;
git_object *target;
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
cl_git_pass(git_signature_new(&tagger, tagger_name, tagger_email, 123456789, 60));
cl_assert_equal_i(GIT_EINVALIDSPEC,
git_tag_create(&tag_id, g_repo,
"Inv@{id", target, tagger, tagger_message, 0)
);
cl_assert_equal_i(GIT_EINVALIDSPEC,
<API key>(&tag_id, g_repo,
"Inv@{id", target, 0)
);
git_object_free(target);
git_signature_free(tagger);
}
void <API key>(void)
{
cl_assert_equal_i(GIT_EINVALIDSPEC, git_tag_delete(g_repo, "Inv@{id"));
}
void create_annotation(git_oid *tag_id, const char *name)
{
git_object *target;
git_oid target_id;
git_signature *tagger;
cl_git_pass(git_signature_new(&tagger, tagger_name, tagger_email, 123456789, 60));
git_oid_fromstr(&target_id, tagged_commit);
cl_git_pass(git_object_lookup(&target, g_repo, &target_id, GIT_OBJECT_COMMIT));
cl_git_pass(<API key>(tag_id, g_repo, name, target, tagger, "boom!"));
git_object_free(target);
git_signature_free(tagger);
}
void <API key>(void)
{
git_oid tag_id;
git_tag *tag;
create_annotation(&tag_id, "new_tag");
cl_git_pass(git_tag_lookup(&tag, g_repo, &tag_id));
cl_assert_equal_s("new_tag", git_tag_name(tag));
git_tag_free(tag);
}
void <API key>(void)
{
git_oid tag_id;
git_reference *tag_ref;
create_annotation(&tag_id, "new_tag");
cl_git_fail_with(<API key>(&tag_ref, g_repo, "refs/tags/new_tag"), GIT_ENOTFOUND);
} |
package play.db;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Similar to java.util.concurrent.Callable with a Connection as argument.
* Provides a functional interface for use with Java 8+.
* If no result needs to be returned, ConnectionRunnable can be used instead.
*
* Vanilla Java:
* <code>
* new ConnectionCallable<A>() {
* public A call(Connection c) { return ...; }
* }
* </code>
*
* Java Lambda:
* <code>(Connection c) -> ...</code>
*/
public interface ConnectionCallable<A> {
public A call(Connection connection) throws SQLException;
} |
#ifndef PACKETPP_ICMP_LAYER
#define PACKETPP_ICMP_LAYER
#include <Layer.h>
#include <IPv4Layer.h>
#ifdef _MSC_VER
#include <Winsock2.h>
#else
#include <sys/time.h>
#endif
#include <vector>
@file
/**
* \namespace pcpp
* \brief The main namespace for the PcapPlusPlus lib
*/
namespace pcpp
{
/**
* @struct icmphdr
* Represents ICMP basic protocol header (common for all ICMP message types)
*/
#pragma pack(push, 1)
typedef struct
{
/** message type */
uint8_t type;
/** message code */
uint8_t code;
/** message checksum */
uint16_t checksum;
} icmphdr;
#pragma pack(pop)
/**
* An enum of all supported ICMP message types
*/
enum IcmpMessageType
{
/** ICMP echo (ping) reply message */
ICMP_ECHO_REPLY = 0,
/** ICMP destination unreachable message */
<API key> = 3,
/** ICMP source quench message */
ICMP_SOURCE_QUENCH = 4,
/** ICMP redirect message */
ICMP_REDIRECT = 5,
/** ICMP echo (ping) request message */
ICMP_ECHO_REQUEST = 8,
/** ICMP router advertisement message */
ICMP_ROUTER_ADV = 9,
/** ICMP router soliciatation message */
ICMP_ROUTER_SOL = 10,
/** ICMP time-to-live excceded message */
ICMP_TIME_EXCEEDED = 11,
/** ICMP parameter problem message */
ICMP_PARAM_PROBLEM = 12,
/** ICMP timestamp request message */
<API key> = 13,
/** ICMP timestamp reply message */
<API key> = 14,
/** ICMP information request message */
ICMP_INFO_REQUEST = 15,
/** ICMP information reply message */
ICMP_INFO_REPLY = 16,
/** ICMP address mask request message */
<API key> = 17,
/** ICMP address mask reply message */
<API key> = 18,
/** ICMP message type unsupported by PcapPlusPlus */
ICMP_UNSUPPORTED = 255
};
enum <API key>
{
/** Network unreachable error */
<API key> = 0,
/** Host unreachable error */
IcmpHostUnreachable = 1,
/** Protocol unreachable error (the designated transport protocol is not supported) */
<API key> = 2,
/** Port unreachable error (the designated protocol is unable to inform the host of the incoming message) */
IcmpPortUnreachable = 3,
/** The datagram is too big. Packet fragmentation is required but the 'don't fragment' (DF) flag is on */
IcmpDatagramTooBig = 4,
/** Source route failed error */
<API key> = 5,
/** Destination network unknown error */
<API key> = 6,
/** Destination host unknown error */
<API key> = 7,
/** Source host isolated error */
<API key> = 8,
/** The destination network is administratively prohibited */
<API key> = 9,
/** The destination host is administratively prohibited */
<API key> = 10,
/** The network is unreachable for Type Of Service */
<API key> = 11,
/** The host is unreachable for Type Of Service */
<API key> = 12,
/** Communication administratively prohibited (administrative filtering prevents
* packet from being forwarded)
*/
<API key> = 13,
/** Host precedence violation (indicates the requested precedence is not permitted for
* the combination of host or network and port)
*/
<API key> = 14,
/** Precedence cutoff in effect (precedence of datagram is below the level set by
* the network administrators)
*/
<API key> = 15
};
/**
* @struct icmp_echo_hdr
* ICMP echo (ping) request/reply message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** the echo (ping) request identifier */
uint16_t id;
/** the echo (ping) request sequence number */
uint16_t sequence;
/** a timestamp of when the message was sent */
uint64_t timestamp;
} icmp_echo_hdr;
#pragma pack(pop)
/**
* @struct icmp_echo_request
* ICMP echo (ping) request/reply message structure
*/
typedef struct
{
/** a pointer to the header data */
icmp_echo_hdr* header;
/** most echo requests/replies contain some payload data. This is the data length */
size_t dataLength;
/** most echo requests/replies contain some payload data. This is a pointer to this data */
uint8_t* data;
} icmp_echo_request;
/**
* @typedef icmp_echo_reply
* ICMP echo (ping) reply message structure, same as icmp_echo_request
*/
typedef icmp_echo_request icmp_echo_reply;
/**
* @struct <API key>
* ICMP timestamp request message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** the timestamp request identifier */
uint16_t id;
/** the timestamp request sequence number */
uint16_t sequence;
/** the time (in milliseconds since midnight) the sender last touched the packet */
uint32_t originateTimestamp;
/** relevant for timestamp reply only - the time the echoer first touched it on receipt */
uint32_t receiveTimestamp;
/** relevant for timestamp reply only - the time the echoer last touched the message on sending it */
uint32_t transmitTimestamp;
} <API key>;
#pragma pack(pop)
/**
* @typedef <API key>
* ICMP timestamp reply message structure, same as <API key>
*/
typedef <API key> <API key>;
/**
* @struct <API key>
* ICMP destination unreachable message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** unused 2 bytes */
uint16_t unused;
/** contains the MTU of the next-hop network if a code 4 error occurs */
uint16_t nextHopMTU;
} <API key>;
#pragma pack(pop)
/**
* @struct icmp_time_exceeded
* ICMP time-to-live exceeded message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** unused 4 bytes */
uint32_t unused;
} icmp_time_exceeded;
#pragma pack(pop)
/**
* @typedef icmp_source_quench
* ICMP source quence message structure, same as icmp_time_exceeded
*/
typedef icmp_time_exceeded icmp_source_quench;
/**
* @struct icmp_param_problem
* ICMP parameter problem message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** in the case of an invalid IP header (Code 0), this field indicates the byte offset of the error in the header */
uint8_t pointer;
/** unused 1 byte */
uint8_t unused1;
/** unused 2 bytes */
uint16_t unused2;
} icmp_param_problem;
#pragma pack(pop)
/**
* @typedef <API key>
* ICMP router solicitation message structure, same as icmphdr
*/
typedef icmphdr <API key>;
/**
* @struct icmp_redirect
* ICMP redirect message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** an IPv4 address of the gateway to which the redirection should be sent */
uint32_t gatewayAddress;
} icmp_redirect;
#pragma pack(pop)
/**
* @struct <API key>
* Router address structure, relevant for ICMP router advertisement message type (<API key>)
*/
#pragma pack(push, 1)
struct <API key>
{
/** the IPv4 address of the advertised router */
uint32_t routerAddress;
/** The preferability of the router address as a default router address, relative to other router addresses
* on the same subnet. This is a twos-complement value where higher values indicate that the route is
* more preferable */
uint32_t preferenceLevel;
/**
* Set router address structure from a given IPv4 address and preference level
* @param[in] addr IPv4 address to set
* @param[in] preference Preference level to set
*/
void setRouterAddress(IPv4Address addr, uint32_t preference);
/**
* @return The IPv4 address extracted from <API key>#routerAddress field
*/
IPv4Address getAddress();
};
#pragma pack(pop)
/**
* @struct <API key>
* ICMP router advertisement message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** the number of router advertisements in this message. Each advertisement contains one router address/preference level pair */
uint8_t advertisementCount;
/** the number of 32-bit words of information for each router address entry in the list. The value is normally set to 2
* (router address + preference level) */
uint8_t addressEntrySize;
/** the maximum number of seconds that the router addresses in this list may be considered valid */
uint16_t lifetime;
} <API key>;
#pragma pack(pop)
/**
* @struct <API key>
* ICMP router advertisement message structure
*/
struct <API key>
{
/** a pointer to the header data on the packet */
<API key>* header;
/**
* Extract router advertisement at a given index
* @param[in] index The index of the router advertisement
* @return A pointer to the router advertisement on the packet or null if index is out of range (less than zero or
* greater than the number of router advertisement records on this message, determined by advertisementCount field)
*/
<API key>* getRouterAddress(int index);
};
/**
* @struct <API key>
* ICMP address mask request message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** the address mask request identifier */
uint16_t id;
/** the address mask request sequence */
uint16_t sequence;
/** the subnet mask of the requesting host */
uint32_t addressMask;
} <API key>;
#pragma pack(pop)
/**
* @typedef <API key>
* ICMP address mask reply message structure, same as <API key>
*/
typedef <API key> <API key>;
/**
* @struct icmp_info_request
* ICMP information request message structure
*/
#pragma pack(push, 1)
typedef struct : icmphdr
{
/** the information request identifier */
uint16_t id;
/** the information request sequence */
uint16_t sequence;
} icmp_info_request;
#pragma pack(pop)
/**
* @typedef icmp_info_reply
* ICMP information reply message structure, same as icmp_info_request
*/
typedef icmp_info_request icmp_info_reply;
/**
* @class IcmpLayer
* Represents an ICMP protocol layer (for IPv4 only)
*/
class IcmpLayer : public Layer
{
private:
icmp_echo_request m_EchoData;
<API key> m_RouterAdvData;
bool cleanIcmpLayer();
bool setEchoData(IcmpMessageType echoType, uint16_t id, uint16_t sequence, uint64_t timestamp, const uint8_t* data, size_t dataLen);
bool setIpAndL4Layers(IPv4Layer* ipLayer, Layer* l4Layer);
public:
/**
* A constructor that creates the layer from an existing packet raw data
* @param[in] data A pointer to the raw data (will be casted to @ref arphdr)
* @param[in] dataLen Size of the data in bytes
* @param[in] prevLayer A pointer to the previous layer
* @param[in] packet A pointer to the Packet instance where layer will be stored in
*/
IcmpLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet) : Layer(data, dataLen, prevLayer, packet) { m_Protocol = ICMP; }
/**
* An empty constructor that creates a new layer with an empty ICMP header without setting the ICMP type or ICMP data.
* Call the set*Data() methods to set ICMP type and data
*/
IcmpLayer();
virtual ~IcmpLayer() {}
/**
* Get a pointer to the basic ICMP header. Notice this points directly to the data, so every change will change the actual packet data
* @return A pointer to the @ref icmphdr
*/
inline icmphdr* getIcmpHeader() { return (icmphdr*)m_Data; };
/**
* @return The ICMP message type
*/
IcmpMessageType getMessageType();
/**
* @param[in] type Type to check
* @return True if the layer if of the given type, false otherwise
*/
bool isMessageOfType(IcmpMessageType type);
/**
* @return ICMP echo (ping) request data. If the layer isn't of type ICMP echo request NULL is returned
*/
icmp_echo_request* getEchoRequestData();
/**
* Set echo (ping) request message data
* @param[in] id Echo (ping) request identifier
* @param[in] sequence Echo (ping) request sequence
* @param[in] timestamp Echo (ping) request timestamp
* @param[in] data A pointer to echo (ping) request payload to set
* @param[in] dataLen The length of the echo (ping) request payload
* @return A pointer to the echo (ping) request data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
icmp_echo_request* setEchoRequestData(uint16_t id, uint16_t sequence, uint64_t timestamp, const uint8_t* data, size_t dataLen);
/**
* @return ICMP echo reply data. If the layer isn't of type ICMP echo reply NULL is returned
*/
icmp_echo_reply* getEchoReplyData();
/**
* Set echo (ping) reply message data
* @param[in] id Echo (ping) reply identifier
* @param[in] sequence Echo (ping) reply sequence
* @param[in] timestamp Echo (ping) reply timestamp
* @param[in] data A pointer to echo (ping) reply payload to set
* @param[in] dataLen The length of the echo (ping) reply payload
* @return A pointer to the echo (ping) reply data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
icmp_echo_reply* setEchoReplyData(uint16_t id, uint16_t sequence, uint64_t timestamp, const uint8_t* data, size_t dataLen);
/**
* @return ICMP timestamp request data. If the layer isn't of type ICMP timestamp request NULL is returned
*/
<API key>* <API key>();
/**
* Set timestamp request message data
* @param[in] id Timestamp request identifier
* @param[in] sequence Timestamp request sequence
* @param[in] originateTimestamp Time (in milliseconds since midnight) the sender last touched the packet
* @return A pointer to the timestamp request data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>(uint16_t id, uint16_t sequence, timeval originateTimestamp);
/**
* @return ICMP timestamp reply data. If the layer isn't of type ICMP timestamp reply NULL is returned
*/
<API key>* <API key>();
/**
* Set timestamp reply message data
* @param[in] id Timestamp reply identifier
* @param[in] sequence Timestamp reply sequence
* @param[in] originateTimestamp Time (in milliseconds since midnight) the sender last touched the packet
* @param[in] receiveTimestamp The time the echoer first touched it on receipt
* @param[in] transmitTimestamp The time the echoer last touched the message on sending it
* @return A pointer to the timestamp reply data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>(uint16_t id, uint16_t sequence,
timeval originateTimestamp, timeval receiveTimestamp, timeval transmitTimestamp);
/**
* @return ICMP destination unreachable data. If the layer isn't of type ICMP destination unreachable NULL is returned.
* The IP and L4 (ICMP/TCP/UDP) headers of the destination unreachable data are parsed as separate layers and can be
* retrieved via this->getNextLayer()
*/
<API key>* <API key>();
/**
* Set destination unreachable message data. This method only works if IcmpLayer is already part of a packet (not
* a standalone layer). The reason is the Internet and L4 headers given as parameters are added as separate layers
* and need a packet to be added to
* @param[in] code Destination unreachable code
* @param[in] nextHopMTU The MTU of the next-hop network if a code 4 error occurs
* @param[in] ipHeader The Internet header of the original data. This layer is added as a separate layer on the packet
* @param[in] l4Header The L4 header of the original data. This layer is added as a separate layer on the packet
* @return A pointer to the destination unreachable data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>(<API key> code, uint16_t nextHopMTU, IPv4Layer* ipHeader, Layer* l4Header);
/**
* @return ICMP source quench data. If the layer isn't of type ICMP source quench NULL is returned.
* The IP and L4 (ICMP/TCP/UDP) headers of the source quench data are parsed as separate layers and can be
* retrieved via this->getNextLayer()
*/
icmp_source_quench* getSourceQuenchdata();
/**
* Set source quench message data. This method only works if IcmpLayer is already part of a packet (not
* a standalone layer). The reason is the Internet and L4 headers given as parameters are added as separate layers
* and need a packet to be added to
* @param[in] ipHeader The Internet header of the original data. This layer is added as a separate layer on the packet
* @param[in] l4Header The L4 header of the original data. This layer is added as a separate layer on the packet
* @return A pointer to the source quench data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
icmp_source_quench* setSourceQuenchdata(IPv4Layer* ipHeader, Layer* l4Header);
/**
* @return ICMP redirect data. If the layer isn't of type ICMP redirect NULL is returned.
* The IP and L4 (ICMP/TCP/UDP) headers of the redirect data are parsed as separate layers and can be
* retrieved via this->getNextLayer()
*/
icmp_redirect* getRedirectData();
icmp_redirect* setRedirectData(uint8_t code, IPv4Address gatewayAddress, IPv4Layer* ipHeader, Layer* l4Header);
/**
* @return ICMP router advertisement data. If the layer isn't of type ICMP router advertisement NULL is returned
*/
<API key>* <API key>();
<API key>* <API key>(uint8_t code, uint16_t lifetimeInSeconds, const std::vector<<API key>>& routerAddresses);
/**
* @return ICMP router solicitation data. If the layer isn't of type ICMP router solicitation NULL is returned
*/
<API key>* <API key>();
/**
* Set router solicitation message data. This message accepts no parameters as there are no parameters to this
* type of message (code is always zero)
* @return A pointer to the router solicitation data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>();
/**
* @return ICMP time-to-live exceeded data. If the layer isn't of type ICMP time-to-live exceeded NULL is returned.
* The IP and L4 (ICMP/TCP/UDP) headers of the time exceeded data are parsed as separate layers and can be
* retrieved via this->getNextLayer()
*/
icmp_time_exceeded* getTimeExceededData();
icmp_time_exceeded* setTimeExceededData(uint8_t code, IPv4Layer* ipHeader, Layer* l4Header);
/**
* @return ICMP parameter problem data. If the layer isn't of type ICMP parameter problem NULL is returned
*/
icmp_param_problem* getParamProblemData();
icmp_param_problem* setParamProblemData(uint8_t code, uint8_t errorOctetPointer, IPv4Layer* ipHeader, Layer* l4Header);
/**
* @return ICMP address mask request data. If the layer isn't of type ICMP address mask request NULL is returned
*/
<API key>* <API key>();
/**
* Set address mask request message data
* @param[in] id Address mask request identifier
* @param[in] sequence Address mask request sequence
* @param[in] mask The subnet mask of the requesting host
* @return A pointer to the address mask request data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>(uint16_t id, uint16_t sequence, IPv4Address mask);
/**
* @return ICMP address mask reply data. If the layer isn't of type ICMP address mask reply NULL is returned
*/
<API key>* <API key>();
/**
* Set address mask reply message data
* @param[in] id Address mask reply identifier
* @param[in] sequence Address mask reply sequence
* @param[in] mask The subnet mask of the requesting host
* @return A pointer to the address mask reply data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
<API key>* <API key>(uint16_t id, uint16_t sequence, IPv4Address mask);
/**
* @return ICMP address information request data. If the layer isn't of type ICMP information request NULL is returned
*/
icmp_info_request* getInfoRequestData();
/**
* Set information request message data
* @param[in] id Information request identifier
* @param[in] sequence Information request sequence
* @return A pointer to the information request data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
icmp_info_request* setInfoRequestData(uint16_t id, uint16_t sequence);
/**
* @return ICMP address information reply data. If the layer isn't of type ICMP information reply NULL is returned
*/
icmp_info_reply* getInfoReplyData();
/**
* Set information reply message data
* @param[in] id Information reply identifier
* @param[in] sequence Information reply sequence
* @return A pointer to the information reply data that have been set or NULL if something went wrong
* (an appropriate error log is printed in such cases)
*/
icmp_info_reply* setInfoReplyData(uint16_t id, uint16_t sequence);
// implement abstract methods
/**
* ICMP messages of types: <API key>, ICMP_SOURCE_QUENCH, ICMP_TIME_EXCEEDED, ICMP_REDIRECT, ICMP_PARAM_PROBLEM
* have data that contains IPv4 header and some L4 header (TCP/UDP/ICMP). This method parses these headers as separate
* layers on top of the ICMP layer
*/
void parseNextLayer();
/**
* @return The ICMP header length. This length varies according to the ICMP message type. This length doesn't include
* IPv4 and L4 headers in case ICMP message type are: <API key>, ICMP_SOURCE_QUENCH, ICMP_TIME_EXCEEDED,
* ICMP_REDIRECT, ICMP_PARAM_PROBLEM
*/
size_t getHeaderLen();
/**
* Calculate ICMP checksum field
*/
void <API key>();
std::string toString();
OsiModelLayer getOsiModelLayer() { return <API key>; }
};
} // namespace pcpp
#endif /* PACKETPP_ICMP_LAYER */ |
package com.arjuna.ats.internal.jta.transaction.jts;
import javax.transaction.<API key>;
import org.omg.CORBA.<API key>;
import org.omg.CosTransactions.Control;
import org.omg.CosTransactions.Coordinator;
import com.arjuna.ats.internal.jta.utils.jtaxLogger;
import com.arjuna.ats.internal.jts.OTSImpleManager;
import com.arjuna.ats.jta.common.jtaPropertyManager;
import com.arjuna.ats.jts.OTSManager;
/**
* Some common methods for UserTransaction and TransactionManager.
*
* @author Mark Little (mark_little@hp.com)
* @version $Id: BaseTransaction.java 2342 2006-03-30 13:06:17Z $
* @since JTS 2.1.
*/
public class BaseTransaction
{
public void begin () throws javax.transaction.<API key>,
javax.transaction.SystemException
{
if (jtaxLogger.logger.isTraceEnabled()) {
jtaxLogger.logger.trace("BaseTransaction.begin");
}
/*
* We can supported subtransactions, so should have the option to let
* programmer use them. Strict conformance will always say no.
*/
if (!<API key>)
{
try
{
<API key>();
}
catch (<API key> e1)
{
<API key> <API key> = new <API key>(e1.getMessage());
<API key>.initCause(e1);
throw <API key>;
}
catch (org.omg.CORBA.SystemException e2)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e2.toString());
systemException.initCause(e2);
throw systemException;
}
}
try
{
TransactionImple.putTransaction(new TransactionImple());
}
catch (org.omg.CosTransactions.<API key> e3)
{
// shouldn't happen if we get here from the previous checks!
<API key> <API key> = new <API key>(e3.getMessage());
<API key>.initCause(e3);
throw <API key>;
}
catch (org.omg.CORBA.SystemException e4)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e4.toString());
systemException.initCause(e4);
throw systemException;
}
}
/**
* We will never throw a <API key> because if we get a
* HeuristicRollback from a resource, and can successfully rollback the
* other resources, this is then the same as having simply been forced to
* rollback the transaction during phase 1. The OTS interfaces do not allow
* a differentiation.
*/
public void commit () throws javax.transaction.RollbackException,
javax.transaction.<API key>,
javax.transaction.<API key>,
java.lang.SecurityException, java.lang.<API key>,
javax.transaction.SystemException
{
if (jtaxLogger.logger.isTraceEnabled()) {
jtaxLogger.logger.trace("BaseTransaction.commit");
}
TransactionImple theTransaction = TransactionImple.getTransaction();
try
{
theTransaction.<API key>();
}
catch (<API key> ex)
{
ex.printStackTrace();
throw new <API key>(
"BaseTransaction.commit - "
+ jtaxLogger.i18NLogger.<API key>()
+ ex, ex);
}
<API key>();
}
public void rollback () throws java.lang.<API key>,
java.lang.SecurityException, javax.transaction.SystemException
{
if (jtaxLogger.logger.isTraceEnabled()) {
jtaxLogger.logger.trace("BaseTransaction.rollback");
}
TransactionImple theTransaction = TransactionImple.getTransaction();
try
{
theTransaction.<API key>();
}
catch (<API key> ex)
{
throw new <API key>(ex);
}
<API key>();
}
public void setRollbackOnly () throws java.lang.<API key>,
javax.transaction.SystemException
{
if (jtaxLogger.logger.isTraceEnabled()) {
jtaxLogger.logger.trace("BaseTransaction.setRollbackOnly");
}
TransactionImple theTransaction = TransactionImple.getTransaction();
try
{
theTransaction.setRollbackOnly();
}
catch (<API key> ex)
{
throw new <API key>(
jtaxLogger.i18NLogger.<API key>(), ex);
}
}
public int getStatus () throws javax.transaction.SystemException
{
if (jtaxLogger.logger.isTraceEnabled()) {
jtaxLogger.logger.trace("BaseTransaction.getStatus");
}
TransactionImple theTransaction = null;
try {
theTransaction = TransactionImple.getTransaction();
} catch (<API key> e) {
if (e.minor == 1) {
return javax.transaction.Status.<API key>;
}
}
if (theTransaction == null) {
return javax.transaction.Status.<API key>;
}
try
{
return theTransaction.getStatus();
}
catch (<API key> ex)
{
return javax.transaction.Status.<API key>;
}
catch (Exception e)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e.toString());
systemException.initCause(e);
throw systemException;
}
}
public void <API key> (int seconds)
throws javax.transaction.SystemException
{
try
{
OTSImpleManager.current().set_timeout(seconds);
}
catch (Exception e)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e.toString());
systemException.initCause(e);
throw systemException;
}
}
public int getTimeout () throws javax.transaction.SystemException
{
try
{
return OTSImpleManager.current().get_timeout();
}
catch (Exception e)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e.toString());
systemException.initCause(e);
throw systemException;
}
}
protected BaseTransaction ()
{
}
/**
* Called when we want to make sure this thread does not already have a
* transaction associated with it.
*/
final void <API key> () throws <API key>,
javax.transaction.SystemException
{
try
{
Control cont = OTSManager.get_current().get_control();
/*
* Control may not be null, but its coordinator may be.
*/
if (cont != null)
{
Coordinator coord = cont.get_coordinator();
if (coord != null)
{
if ((coord.get_status() == org.omg.CosTransactions.Status.StatusActive)
&& (!<API key>))
{
throw new <API key>(
"BaseTransaction.<API key> - "
+ jtaxLogger.i18NLogger.<API key>());
}
}
cont = null;
}
}
catch (org.omg.CORBA.SystemException e1)
{
javax.transaction.SystemException systemException = new javax.transaction.SystemException(e1.toString());
systemException.initCause(e1);
throw systemException;
}
catch (org.omg.CosTransactions.Unavailable e2)
{
// ok, no transaction currently associated with thread.
}
catch (<API key> ex)
{
// ok, no transaction currently associated with thread.
}
}
private static boolean <API key> = jtaPropertyManager.<API key>()
.<API key>();
} |
#top-header {
margin-top: 26px;
margin-bottom: 10px;
}
#top-header .header2 {
font-weight: 400;
}
#usernav > ul {
margin-top: 10px;
z-index: 99999;
}
.menu-caption {
padding-bottom: 10px;
}
#toc_table {
margin-top: 10px;
}
#leftnav {
height: 100%;
overflow: hidden;
}
#leftnav .nav ul {
line-height: 1;
margin: 10px 10px 0px 16px;
padding: 0;
list-style: none;
}
#leftnav .nav li ul a,
#leftnav .nav li ul a:hover {
margin: 0 !important;
padding: 0 !important;
font-size: 13px;
font-weight: 400;
color: #394d54;
}
#leftnav .nav li ul a:hover {
color: #24b8eb;
}
#leftnav .nav.nav-tabs li a,
#leftnav .nav.nav-tabs li li {
line-height: 1.1 !important;
}
#leftnav li {
margin-top: 20px;
// text-indent: -16px;
padding-left: 10px;
}
#leftnav .nav-tabs.nav ul li {
margin-top: 5px;
}
.content-body {
padding: 0px 0px 0px 20px;
}
ol {
padding-left: 22px;
}
ol li {
margin: 8px;
}
pre {
font-size: 12px;
line-height: 1.5;
}
/* Main Navigation */
#nav_menu > #docsnav {
max-width: 940px;
width: 940px;
margin: 0 auto;
}
#nav_menu > #docsnav > #nav_search {
margin-top: 10px;
}
.search_input:focus {
background: #fff;
outline: none;
}
#nav_menu > #docsnav > #main-nav {
height: 50px;
margin: 0px;
padding: 0em;
}
#nav_menu > #docsnav > #main-nav > li > a {
color: #253237;
}
#nav_menu > #docsnav > #main-nav > li.dd_on_hover {
background: #d3f1fb;
color: #253237;
}
#nav_menu > #docsnav > #main-nav > li > span > b {
border-top-color: #b1d5df !important;
}
#nav_menu > #docsnav > #main-nav > li.dd_on_hover > span > b {
border-top-color: #71afc0 !important;
}
#nav_menu > #docsnav > #main-nav > li form {
margin-top: -12px;
}
#nav_menu > #docsnav > #main-nav > li.home > a {
color: #fff;
}
#nav_menu > #docsnav > #main-nav > li.home:hover {
background: #b1d5df;
}
#nav_menu > #docsnav > #main-nav > li.home:hover > a {
color: #5992a3;
}
#nav_menu {
background: #E8E8E8;
position: relative;
width: 100%;
height: 54px;
z-index: 1000;
top: auto;
padding: 0px 15px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#nav_menu #docsnav #main-nav > li {
font-size: 15px;
font-weight: 400;
color: #253237;
line-height: 2em;
display: block;
padding: 0 12px 0 12px;
line-height: 54px;
height: 54px;
}
#nav_menu #docsnav #main-nav > li.active {
background: #ade5f9; /* url("../img/nav/<API key>.svg") no-repeat 87% 50%;*/
}
#nav_menu #docsnav #main-nav > li.dd_on_hover {
/*background: #ade5f9 url("../img/nav/<API key>.svg") no-repeat 87% 50%;*/
}
#nav_search {
padding-top: 2px;
}
#nav_search input[type="text"] {
width: 220px;
height: 30px;
margin: 0;
background: #ffffff url("../img/nav/search-icon.svg") no-repeat 95% 50%;
}
/* Navigation Submenu */
.dd_menu {
cursor: pointer;
}
.dd_menu .dd_submenu {
display: none;
position: absolute;
top: 54px;
list-style: none;
margin: 0px;
margin-left: -12px;
overflow: hidden;
overflow-y: auto;
background: #fff;
border: 1px solid #ccc;
border-top: none;
border-bottom: 3px solid #ccc;
-<API key>: 0px 0px 4px 4px;
-moz-border-radius: 0px 0px 4px 4px;
border-radius: 0px 0px 4px 4px;
padding: 0px;
}
.dd_menu.dd_on_hover .dd_submenu {
display: block;
}
.dd_menu.dd_on_hover .dd_submenu > li:first-child {
border: none;
}
.dd_menu.dd_on_hover .dd_submenu > li {
border-top: 1px solid #ddd;
}
.dd_menu.dd_on_hover .dd_submenu > li.active > a {
border-color: #b1d5df;
color: #FF8100 !important;
}
.dd_menu.dd_on_hover .dd_submenu > li > a {
padding: 0.6em 0.8em 0.4em 0.8em;
width: 100%;
display: block;
}
.dd_menu li a {
font-size: 15px;
font-weight: 400;
color: #005976;
}
.dd_menu li a:hover {
text-decoration: none;
font-size: 15px;
font-weight: 400;
color: #24b8eb;
}
/* Search Page */
#tipue_search_input {
height: 30px;
margin: 0;
background: #ffffff url("../img/nav/search-icon.svg") no-repeat 95% 50%;
}
.alert-red-block {
margin: 10px 0px;
background: #edd3d7;
border: none;
margin-bottom: 20px;
}
.content-body ul {
padding: 10px 0px 10px 20px;
list-style-position: inherit;
list-style: circle;
}
.content-body ul li {
padding-bottom: 5px;
}
.content-body ul ul {
padding: 10px 0px 10px 40px;
}
.content-body h1 {
display: block !important;
font-size: 27px;
font-weight: 400;
color: #394d54;
line-height: 1.33;
margin-bottom: 8px;
margin-top: 6px;
}
.content-body h2 {
font-size: 21px;
font-weight: 400;
color: #394d54;
line-height: 1.7;
margin-bottom: 4px;
margin-top: 10px;
}
.content-body h3 {
font-size: 18px;
font-weight: 400;
color: #394d54;
line-height: 1.7;
margin-bottom: 4px;
margin-top: 10px;
}
.content-body h4 {
font-size: 16px;
font-weight: 400;
color: #394d54;
line-height: 1.7;
margin-bottom: 4px;
margin-top: 10px;
}
.content-body p {
font-size: 14px;
font-weight: 400;
color: #394d54;
line-height: 1.7;
}
.content-body p code {
background-color: #FCFCFC;
border-radius: 4px;
-<API key>: 4px;
-moz-border-radius: 4px;
border: 1px solid #dbdde0;
color: #394d54;
padding-left: 6px;
padding-right: 6px;
margin-bottom: 2px;
}
.content-body blockquote {
margin: 0px !important;
margin-bottom: 20px !important;
margin-top: 20px !important;
font-size: 14px;
font-weight: 400;
color: #394d54;
line-height: 1.7;
font-style: italic;
border: none;
border-left: 4px solid #ade5f9;
padding: 10px;
padding-left: 15px;
}
.content-body ul {
margin-top: 0px !important;
}
.content-body blockquote a {
color: #24b8eb;
}
.content-body blockquote a:hover {
color: #008bb8;
}
.content-body ul {
margin-top: 0px !important;
}
.content-body pre {
font-family: Monaco, Consolas, "Lucida Console", monospace;
background-color: #FCFCFC;
margin-bottom: 20px;
border-radius: 4px;
-<API key>: 4px;
-moz-border-radius: 4px;
overflow-x: auto;
}
.content-body pre code {
overflow-wrap: normal;
white-space: pre;
}
.content-body strong {
font-weight: bold;
}
/* Logged-in/out header */
.topmostnav_loggedin {
display: none;
}
#topmostnav.public .brand {
padding-left: 0px !important;
}
.navbar #usernav .nav li {
padding-top: 0px !important;
}
table.table tr td img {
width:100%;
}
#versionnav ul {
list-style: none outside none;
}
#versionnav ul ul {
padding: 0;
}
/* over-ride the prettyPrint colouring */
.str, .atv { color: #48484C; } |
trait x0 {
class x1 (x1:x0
{
type x1 <: List[x1 <: // error
// error |
#ifndef GCC_CR16_H
#define GCC_CR16_H
#define OBJECT_FORMAT_ELF
/* Controlling the driver. */
/* The GNU C++ standard library requires that these macros be defined. */
#undef CPLUSPLUS_CPP_SPEC
#define CPLUSPLUS_CPP_SPEC "-D_GNU_SOURCE %(cpp)"
#undef STARTFILE_SPEC
#define STARTFILE_SPEC "crt1.o%s crti.o%s crtbegin.o%s crtlibid.o%s"
#undef ENDFILE_SPEC
#define ENDFILE_SPEC "crtend.o%s crtn.o%s"
#undef MATH_LIBRARY
#define MATH_LIBRARY ""
#undef LIB_SPEC
#define LIB_SPEC "-( -lc %{msim*:-lsim}%{!msim*:-lnosys} -) \
%{msim*:%{!T*:-Tsim.ld}} \
%{!T*:%{!msim*: %{-Telf32cr16.x}}}"
/* Run-time target specification. */
#ifndef <API key>
#define <API key>() \
do \
{ \
builtin_define ("__CR__"); \
builtin_define ("__CR16__"); \
builtin_define ("__CR16C__"); \
if (TARGET_CR16CP) \
builtin_define ("__CR16CP__"); \
else \
builtin_define ("__CR16CSTD__"); \
if (<API key>) \
builtin_define ("__DATA_NEAR__"); \
if (<API key>) \
builtin_define ("__DATA_MEDIUM__"); \
if (<API key>) \
builtin_define ("__DATA_FAR__"); \
if (TARGET_INT32) \
builtin_define ("__INT32__"); \
} \
while (0)
#endif
/* Force the generation of dwarf .debug_frame sections even if not
compiling -g. This guarantees that we can unwind the stack. */
#define DWARF2_FRAME_INFO 1
#define <API key> DWARF2_DEBUG
/* Generate .file/.loc directives, so that the assembler generates the
line table. */
#define <API key> 1
#define <API key> cr16_is_data_model (DM_NEAR)
#define <API key> cr16_is_data_model (DM_DEFAULT)
#define <API key> cr16_is_data_model (DM_FAR)
/* Storage layout. */
#define BITS_BIG_ENDIAN 0
#define BYTES_BIG_ENDIAN 0
#define WORDS_BIG_ENDIAN 0
#define UNITS_PER_WORD 2
/* Units per 32-bit (DWORD). */
#define <API key> 4
#define POINTER_SIZE 32
#define PARM_BOUNDARY 16
#define STACK_BOUNDARY (MAX (BIGGEST_ALIGNMENT, PARM_BOUNDARY))
#define FUNCTION_BOUNDARY BIGGEST_ALIGNMENT
#define BIGGEST_ALIGNMENT ((TARGET_CR16CP) ? 32 : 16)
#define MAX_FIXED_MODE_SIZE 64
/* In CR16 arrays of chars are word-aligned, so strcpy () will be faster. */
#define DATA_ALIGNMENT(TYPE, ALIGN) \
(((TREE_CODE (TYPE) == ARRAY_TYPE) \
&& (TYPE_MODE (TREE_TYPE (TYPE)) == QImode) \
&& ((ALIGN) < BITS_PER_WORD)) \
? (BITS_PER_WORD) : (ALIGN))
/* In CR16 strings are word-aligne; strcpy from constants will be faster. */
#define CONSTANT_ALIGNMENT(CONSTANT, ALIGN) \
(((TREE_CODE (CONSTANT) == STRING_CST) && ((ALIGN) < BITS_PER_WORD)) \
? (BITS_PER_WORD) : (ALIGN))
#define STRICT_ALIGNMENT 0
#define <API key> 1
/* Layout of source language data types. */
#define INT_TYPE_SIZE (TARGET_INT32 ? 32 : 16)
#define SHORT_TYPE_SIZE 16
#define LONG_TYPE_SIZE 32
#define LONG_LONG_TYPE_SIZE 64
#define FLOAT_TYPE_SIZE 32
#define DOUBLE_TYPE_SIZE 64
#define <API key> 64
#define DEFAULT_SIGNED_CHAR 1
#define SIZE_TYPE "long unsigned int"
#define PTRDIFF_TYPE "long int"
#define WCHAR_TYPE "short unsigned int"
#define WCHAR_TYPE_SIZE 16
/* By default, the C++ compiler will use the lowest bit of the pointer
to function to indicate a <API key> points to a
virtual member function. However, in CR architecture FUNCTION_BOUNDARY
indicates function addresses are always even, but function pointers can be
odd (after right-shifting them when loading them into a register), and the
default doesn't work. In that case, the lowest bit of the delta
field will be used (the remainder of the field is shifted to the left). */
#define <API key> <API key>
/* Define <API key> to 1 if all structure and union return
values must be in memory. */
#define <API key> 0
/* Register usage. */
/* First 32-bit register is R12. */
#define <API key> 12
#define <API key> 16
/* 1 for registers that have pervasive standard uses
and are not available for the register allocator.
On the CR16, only the stack pointer (r15) is such. */
#define FIXED_REGISTERS \
{ \
/* r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10. */ \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
/* r11 r12 r13 ra sp. */ \
0, 0, 0, 0, 1 \
}
/* 1 for registers not available across function calls.
These must include the FIXED_REGISTERS and also any
registers that can be used without being saved.
The latter must include the registers where values are returned
and the register where structure-value addresses are passed.
On the CR16, calls clobbers r0-r6 (scratch registers),
ra (the return address) and sp (the stack pointer). */
#define CALL_USED_REGISTERS \
{ \
/* r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10. */ \
1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, \
/* r11 r12 r13 ra sp. */ \
0, 0, 0, 1, 1 \
}
/* Returns 1 if the register is longer than word size, 0 otherwise. */
#define LONG_REG_P(REGNO) \
(HARD_REGNO_NREGS (REGNO, \
GET_MODE_WIDER_MODE (<API key> \
(BITS_PER_WORD, MODE_INT))) == 1)
#define HARD_REGNO_NREGS(REGNO, MODE) \
((REGNO >= <API key>) \
? ((GET_MODE_SIZE (MODE) + <API key> - 1) / <API key>)\
: ((GET_MODE_SIZE (MODE) + UNITS_PER_WORD - 1) / UNITS_PER_WORD))
/* Nonzero if it is permissible to store a value of mode @var{mode} in hard
register number @var{regno} (or in several registers starting with that
one). On the CR16 architecture, all registers can hold all modes,
except that double precision floats (and double ints) must fall on
even-register boundaries. */
#define HARD_REGNO_MODE_OK(REGNO, MODE) <API key> (REGNO, MODE)
#define NOTICE_UPDATE_CC(EXP, INSN) \
notice_update_cc ((EXP))
/* Interrupt functions can only use registers that have already been
saved by the prologue, even if they would normally be call-clobbered
Check if sizes are same and then check if it is possible to rename. */
#define <API key>(SRC, DEST) \
(!<API key> () || (df_regs_ever_live_p (DEST)))
/* Exception handling stuff. */
/*To ensure correct dwarf unwinding. */
#define <API key> __attribute__((optimize ("no-gcse","no-dse")))
#define gen_rtx_RA gen_rtx_REG (Pmode, <API key>)
/* Use (r8,r7) and (r10,r9) to pass exception handling information. */
#define <API key>(N) (((N) < 2) ? (N*2 + 7) : INVALID_REGNUM)
#define DWARF2_UNWIND_INFO 1
/* (r5,r4) holds a stack adjustment for returning to a handler. */
#define <API key> gen_rtx_REG (Pmode, 4)
#define <API key> \
gen_rtx_MEM (Pmode, plus_constant (arg_pointer_rtx, -4))
#define <API key> gen_rtx_RA
#define <API key> \
DWARF_FRAME_REGNUM (<API key>)
#define <API key> 0
#define <API key>(FNDECL) 0
/* A C expression whose value is RTL representing the value of the return
address for the frame COUNT steps up from the current frame. */
#define RETURN_ADDR_RTX(COUNT, FRAME) \
(0 == COUNT) ? gen_rtx_PLUS (Pmode, gen_rtx_RA, gen_rtx_RA) \
: const0_rtx
#define MODES_TIEABLE_P(MODE1, MODE2) \
(GET_MODE_CLASS (MODE1) == GET_MODE_CLASS (MODE2))
enum reg_class
{
NO_REGS,
SHORT_REGS,
LONG_REGS,
NOSP_REGS,
DOUBLE_BASE_REGS,
GENERAL_REGS,
ALL_REGS,
LIM_REG_CLASSES
};
#define N_REG_CLASSES (int) LIM_REG_CLASSES
#define REG_CLASS_NAMES \
{ \
"NO_REGS", \
"SHORT_REGS", \
"LONG_REGS", \
"NOSP_REGS", \
"DOUBLE_BASE_REGS", \
"GENERAL_REGS", \
"ALL_REGS" \
}
#define REG_CLASS_CONTENTS \
{ \
{0x00000000}, /* NO_REGS */ \
{0x00000FFF}, /* SHORT_REGS : 0 - 11 */ \
{0x0000F000}, /* LONG_REGS : 12 - 15 */ \
{0x00007FFF}, /* NOSP_REGS : 0 - 14 */ \
{0x0000F555}, /* DOUBLE_BASE_REGS : 2,4,6,8,10 */ \
{0x0000FFFF}, /* GENERAL_REGS : 0 - 15 */ \
{0x0000FFFF} /* ALL_REGS : 0 - 15 */ \
}
#define <API key> hook_bool_mode_true
#define REGNO_REG_CLASS(REGNO) <API key> (REGNO)
#define BASE_REG_CLASS GENERAL_REGS
#define MODE_BASE_REG_CLASS(MODE) \
(GET_MODE_SIZE (MODE) <= 4 ? (BASE_REG_CLASS) : (DOUBLE_BASE_REGS))
#define INDEX_REG_CLASS LONG_REGS
#define <API key>(REGNO) \
(((REGNO) < <API key>) \
|| (reg_renumber && ((unsigned) reg_renumber[REGNO] \
< <API key>)))
/* Use even-numbered reg for 64-bit accesses. */
#define <API key>(REGNO, MODE) \
(<API key>(REGNO) && \
((GET_MODE_SIZE (MODE) > 4 && \
(REGNO) < <API key>) \
? (0 == ((REGNO) & 1)) \
: 1))
/* TODO: For now lets not support index addressing mode. */
#define <API key>(REGNO) \
(((REGNO >= <API key>) \
&& ((REGNO) < <API key>)) \
|| (reg_renumber \
&& (((unsigned) reg_renumber[REGNO] >= <API key>) \
&& ((unsigned) reg_renumber[REGNO] < <API key>))) \
)
#define <API key>(X, CLASS) CLASS
/* The maximum number of consecutive registers of class CLASS needed to
hold a value of mode MODE.
On the CompactRISC architecture, the size of MODE in words.
The size of MODE in double words for the class LONG_REGS.
The following check assumes if the class is not LONG_REGS, then
all (NO_REGS, SHORT_REGS, NOSP_REGS and GENERAL_REGS) other classes are
short. We may have to check if this can cause any degradation in
performance. */
#define CLASS_MAX_NREGS(CLASS, MODE) \
(CLASS == LONG_REGS \
? (GET_MODE_SIZE (MODE) + <API key> - 1) / <API key>\
: (GET_MODE_SIZE (MODE) + UNITS_PER_WORD - 1) / UNITS_PER_WORD)
/* Macros to check the range of integers . These macros were used across
the port, majorly in constraints.md, predicates.md files. */
#define <API key>(imm, N) \
((((imm) < ((HOST_WIDE_INT) 1 << ((N) - 1))) \
&& ((imm) >= -((HOST_WIDE_INT) 1 << ((N) - 1)))) ? 1 : 0)
#define <API key>(imm, N) \
(((imm) < ((HOST_WIDE_INT) 1 << (N)) && (imm) >= (HOST_WIDE_INT) 0) ? 1 : 0)
#define IN_RANGE_P(VALUE, LOW, HIGH) \
((((HOST_WIDE_INT)(VALUE)) >= (HOST_WIDE_INT)(LOW)) \
&& (((HOST_WIDE_INT)(VALUE)) <= ((HOST_WIDE_INT)(HIGH))))
#define IN_RAN(VALUE, LOW, HIGH) \
(((((HOST_WIDE_INT)(VALUE)) >= (HOST_WIDE_INT)(LOW)) \
&& (((HOST_WIDE_INT)(VALUE)) <= ((HOST_WIDE_INT)(HIGH)))) ? 1 : 0)
/* This check is for sbit/cbit instruction. */
#define OK_FOR_Z(OP) \
((GET_CODE (OP) == MEM && GET_CODE (XEXP (OP, 0)) == CONST_INT) \
|| (GET_CODE (OP) == MEM && GET_CODE (XEXP (OP, 0)) == REG) \
|| (GET_CODE (OP) == MEM && GET_CODE (XEXP (OP, 0)) == PLUS \
&& GET_CODE (XEXP ((XEXP (OP, 0)), 0)) == REG \
&& GET_CODE (XEXP ((XEXP (OP, 0)), 1)) == CONST_INT))
/* Stack layout and calling conventions. */
#define <API key>
#define <API key> 0
#define <API key> 15
#define <API key> 13
#define ARG_POINTER_REGNUM 12
#define STATIC_CHAIN_REGNUM 1
#define <API key> 14
#define FIRST_PARM_OFFSET(FNDECL) 0
#define ELIMINABLE_REGS \
{ \
{ ARG_POINTER_REGNUM, <API key>}, \
{ ARG_POINTER_REGNUM, <API key>}, \
{ <API key>, <API key>} \
}
#define <API key>(FROM, TO, OFFSET) \
do \
{ \
(OFFSET) = <API key> ((FROM), (TO)); \
} \
while (0)
/* Passing function arguments. */
#define <API key> 0
#define PUSH_ARGS 1
#define PUSH_ROUNDING(BYTES) (((BYTES) + 1) & ~1)
#ifndef CUMULATIVE_ARGS
struct cumulative_args
{
int ints;
int last_parm_in_reg;
};
#define CUMULATIVE_ARGS struct cumulative_args
#endif
/* On the CR16 architecture, Varargs routines should receive their parameters
on the stack. */
#define <API key>(CUM, FNTYPE, LIBNAME, FNDECL, N_NAMED_ARGS) \
<API key> (&(CUM), (FNTYPE), (LIBNAME))
#define <API key>(REGNO) <API key> (REGNO)
/* Generating code for profiling - NOT IMPLEMENTED. */
#undef FUNCTION_PROFILER
#define FUNCTION_PROFILER(STREAM, LABELNO) \
{ \
sorry ("profiler support for CR16"); \
}
/* Trampolines for nested functions - NOT SUPPORTED. */
#define TRAMPOLINE_SIZE 16
/* ADDRESSING MODES. */
#define CONSTANT_ADDRESS_P(X) \
(GET_CODE (X) == LABEL_REF \
|| GET_CODE (X) == SYMBOL_REF \
|| GET_CODE (X) == CONST \
|| GET_CODE (X) == CONST_INT)
#define <API key> 2
#define HAVE_POST_INCREMENT 0
#define HAVE_POST_DECREMENT 0
#define <API key> 0
#define <API key> 0
#ifdef REG_OK_STRICT
#define <API key>(X) <API key> (REGNO (X))
#define <API key>(X, MODE) \
<API key> (REGNO(X), MODE)
#define REG_OK_FOR_INDEX_P(X) <API key> (REGNO (X))
#else /* not REG_OK_STRICT. */
#define <API key>(X) 1
#define <API key>(X, MODE) 1
#define REG_OK_FOR_INDEX_P(X) 1
#endif /* not REG_OK_STRICT. */
/* Go to LABEL if ADDR (a legitimate address expression) has
an effect that depends on the machine mode it is used for. */
#define <API key>(ADDR, LABEL)
/* Assume best case (branch predicted). */
#define BRANCH_COST(speed_p, predictable_p) 2
#define SLOW_BYTE_ACCESS 1
/* It is as good or better to call a constant function address than to
call an address kept in a register. */
#define NO_FUNCTION_CSE
/* Dividing the output into sections. */
#define TEXT_SECTION_ASM_OP "\t.section\t.text"
#define DATA_SECTION_ASM_OP "\t.section\t.data"
#define BSS_SECTION_ASM_OP "\t.section\t.bss"
/* Position independent code (PIC). */
/* NEAR_PIC for -fpic option. */
#define NEAR_PIC 1
/* FAR_PIC for -fPIC option. */
#define FAR_PIC 2
#define <API key> 12
#define <API key>(X) <API key> (X)
/* Assembler format. */
/* Character to start a comment. */
#define ASM_COMMENT_START "
#define GLOBAL_ASM_OP "\t.globl\t"
#undef USER_LABEL_PREFIX
#define USER_LABEL_PREFIX "_"
#undef ASM_OUTPUT_LABELREF
#define ASM_OUTPUT_LABELREF(STREAM, NAME) \
asm_fprintf (STREAM, "%U%s", (*targetm.strip_name_encoding) (NAME));
#define <API key>(STREAM, SYMBOL) \
do \
{ \
const char *rn = XSTR (SYMBOL, 0); \
assemble_name (STREAM, rn); \
if (<API key> (SYMBOL)) \
{ \
fprintf ((STREAM), "@c"); \
} \
} \
while (0)
#undef ASM_APP_ON
#define ASM_APP_ON "#APP\n"
#undef ASM_APP_OFF
#define ASM_APP_OFF "#NO_APP\n"
/* Switch into a generic section. */
#define <API key> <API key>
#undef INIT_SECTION_ASM_OP
#define INIT_SECTION_ASM_OP "\t.section\t.init"
#undef FINI_SECTION_ASM_OP
#define FINI_SECTION_ASM_OP "\t.section\t.fini"
/* Instruction output. */
#define REGISTER_NAMES \
{ \
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", \
"r8", "r9", "r10", "r11", "r12", "r13", "ra", "sp" \
}
/* Output of dispatch tables. */
/* Revisit. No PC relative case as label expressions are not
properly supported in binutils else we could have done this:
#define <API key> (optimize_size ? 1 : 0). */
#define <API key> 0
#define <API key>(FILE, BODY, VALUE, REL) \
((GET_MODE (BODY) == QImode) \
? fprintf ((FILE), "\t.byte (.L%d-.L%d) >> 1\n", \
VALUE, REL) \
: fprintf ((FILE), "\t.word (.L%d-.L%d) >> 1\n", \
VALUE, REL))
#define <API key>(STREAM, VALUE) \
asm_fprintf ((STREAM), "\t.long\t.L%d@c\n", (VALUE))
/* Alignment in assembler file. */
#define ASM_OUTPUT_ALIGN(STREAM, POWER) \
asm_fprintf ((STREAM), "\t.align\t%d\n", 1 << (POWER))
/* Miscellaneous parameters. */
#define CASE_VECTOR_MODE Pmode
#define MOVE_MAX 4
#define <API key>(OUTPREC, INPREC) 1
#define STORE_FLAG_VALUE 1
#define Pmode SImode
#define FUNCTION_MODE QImode
/* Define this boolean macro(s) to indicate whether or not your architecture
has (un)conditional branches that can span all of memory. It is used in
conjunction with an optimization that partitions hot and cold basic blocks
into separate sections of the executable.
CR16 contains branch instructions that span whole address space. */
#define <API key> 1
#define <API key> 1
#endif /* End of GCC_CR16_H. */ |
/*#define USE_SBRK (0) */
/*#define USE_MMAP (0) */
#ifndef USE_PRINTF
#define USE_PRINTF (1)
#endif
#include <string.h>
#ifndef TLSF_USE_LOCKS
#define TLSF_USE_LOCKS (0)
#endif
#ifndef TLSF_STATISTIC
#define TLSF_STATISTIC (0)
#endif
#ifndef USE_MMAP
#define USE_MMAP (0)
#endif
#ifndef USE_SBRK
#define USE_SBRK (0)
#endif
#if TLSF_USE_LOCKS
#include "target.h"
#else
#define TLSF_CREATE_LOCK(_unused_) do{}while(0)
#define TLSF_DESTROY_LOCK(_unused_) do{}while(0)
#define TLSF_ACQUIRE_LOCK(_unused_) do{}while(0)
#define TLSF_RELEASE_LOCK(_unused_) do{}while(0)
#endif
#if TLSF_STATISTIC
#define TLSF_ADD_SIZE(tlsf, b) do { \
tlsf->used_size += (b->size & BLOCK_SIZE) + BHDR_OVERHEAD; \
if (tlsf->used_size > tlsf->max_size) \
tlsf->max_size = tlsf->used_size; \
} while(0)
#define TLSF_REMOVE_SIZE(tlsf, b) do { \
tlsf->used_size -= (b->size & BLOCK_SIZE) + BHDR_OVERHEAD; \
} while(0)
#else
#define TLSF_ADD_SIZE(tlsf, b) do{}while(0)
#define TLSF_REMOVE_SIZE(tlsf, b) do{}while(0)
#endif
#if USE_MMAP || USE_SBRK
#include <unistd.h>
#endif
#if USE_MMAP
#include <sys/mman.h>
#endif
#include "tlsf.h"
#if !defined(__GNUC__)
#ifndef __inline__
#define __inline__
#endif
#endif
/* The debug functions only can be used when _DEBUG_TLSF_ is set. */
#ifndef _DEBUG_TLSF_
#define _DEBUG_TLSF_ (0)
#endif
/* Definition of the structures used by TLSF */
/* Some IMPORTANT TLSF parameters */
/* Unlike the preview TLSF versions, now they are statics */
#define BLOCK_ALIGN (sizeof(void *) * 2)
#define MAX_FLI (30)
#define MAX_LOG2_SLI (5)
#define MAX_SLI (1 << MAX_LOG2_SLI) /* MAX_SLI = 2^MAX_LOG2_SLI */
#define FLI_OFFSET (6) /* tlsf structure just will manage blocks bigger */
/* than 128 bytes */
#define SMALL_BLOCK (128)
#define REAL_FLI (MAX_FLI - FLI_OFFSET)
#define MIN_BLOCK_SIZE (sizeof (free_ptr_t))
#define BHDR_OVERHEAD (sizeof (bhdr_t) - MIN_BLOCK_SIZE)
#define TLSF_SIGNATURE (0x2A59FA59)
#define PTR_MASK (sizeof(void *) - 1)
#define BLOCK_SIZE (0xFFFFFFFF - PTR_MASK)
#define GET_NEXT_BLOCK(_addr, _r) ((bhdr_t *) ((char *) (_addr) + (_r)))
#define MEM_ALIGN ((BLOCK_ALIGN) - 1)
#define ROUNDUP_SIZE(_r) (((_r) + MEM_ALIGN) & ~MEM_ALIGN)
#define ROUNDDOWN_SIZE(_r) ((_r) & ~MEM_ALIGN)
#define ROUNDUP(_x, _v) ((((~(_x)) + 1) & ((_v)-1)) + (_x))
#define BLOCK_STATE (0x1)
#define PREV_STATE (0x2)
/* bit 0 of the block size */
#define FREE_BLOCK (0x1)
#define USED_BLOCK (0x0)
/* bit 1 of the block size */
#define PREV_FREE (0x2)
#define PREV_USED (0x0)
#define DEFAULT_AREA_SIZE (1024*10)
#ifdef USE_MMAP
#define PAGE_SIZE (getpagesize())
#endif
#ifdef USE_PRINTF
#include <stdio.h>
# define PRINT_MSG(fmt, args...) printf(fmt, ## args)
# define ERROR_MSG(fmt, args...) printf(fmt, ## args)
#else
# if !defined(PRINT_MSG)
# define PRINT_MSG(fmt, args...)
# endif
# if !defined(ERROR_MSG)
# define ERROR_MSG(fmt, args...)
# endif
#endif
typedef unsigned int u32_t; /* NOTE: Make sure that this type is 4 bytes long on your computer */
typedef unsigned char u8_t; /* NOTE: Make sure that this type is 1 byte on your computer */
typedef struct free_ptr_struct {
struct bhdr_struct *prev;
struct bhdr_struct *next;
} free_ptr_t;
typedef struct bhdr_struct {
/* This pointer is just valid if the first bit of size is set */
struct bhdr_struct *prev_hdr;
/* The size is stored in bytes */
size_t size; /* bit 0 indicates whether the block is used and */
/* bit 1 allows to know whether the previous block is free */
union {
struct free_ptr_struct free_ptr;
u8_t buffer[1]; /*sizeof(struct free_ptr_struct)]; */
} ptr;
} bhdr_t;
/* This structure is embedded at the beginning of each area, giving us
* enough information to cope with a set of areas */
typedef struct area_info_struct {
bhdr_t *end;
struct area_info_struct *next;
} area_info_t;
typedef struct TLSF_struct {
/* the TLSF's structure signature */
u32_t tlsf_signature;
#if TLSF_USE_LOCKS
TLSF_MLOCK_T lock;
#endif
#if TLSF_STATISTIC
/* These can not be calculated outside tlsf because we
* do not know the sizes when freeing/reallocing memory. */
size_t used_size;
size_t max_size;
#endif
/* A linked list holding all the existing areas */
area_info_t *area_head;
/* the first-level bitmap */
/* This array should have a size of REAL_FLI bits */
u32_t fl_bitmap;
/* the second-level bitmap */
u32_t sl_bitmap[REAL_FLI];
bhdr_t *matrix[REAL_FLI][MAX_SLI];
} tlsf_t;
static __inline__ void set_bit(int nr, u32_t * addr);
static __inline__ void clear_bit(int nr, u32_t * addr);
static __inline__ int ls_bit(int x);
static __inline__ int ms_bit(int x);
static __inline__ void MAPPING_SEARCH(size_t * _r, int *_fl, int *_sl);
static __inline__ void MAPPING_INSERT(size_t _r, int *_fl, int *_sl);
static __inline__ bhdr_t *FIND_SUITABLE_BLOCK(tlsf_t * _tlsf, int *_fl, int *_sl);
static __inline__ bhdr_t *process_area(void *area, size_t size);
#if USE_SBRK || USE_MMAP
static __inline__ void *get_new_area(size_t * size);
#endif
static const int table[] = {
-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4,
4, 4,
4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5,
5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6,
6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6,
6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7,
7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7,
7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7,
7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7,
7, 7, 7, 7, 7, 7, 7
};
static __inline__ int ls_bit(int i)
{
unsigned int a;
unsigned int x = i & -i;
a = x <= 0xffff ? (x <= 0xff ? 0 : 8) : (x <= 0xffffff ? 16 : 24);
return table[x >> a] + a;
}
static __inline__ int ms_bit(int i)
{
unsigned int a;
unsigned int x = (unsigned int) i;
a = x <= 0xffff ? (x <= 0xff ? 0 : 8) : (x <= 0xffffff ? 16 : 24);
return table[x >> a] + a;
}
static __inline__ void set_bit(int nr, u32_t * addr)
{
addr[nr >> 5] |= 1 << (nr & 0x1f);
}
static __inline__ void clear_bit(int nr, u32_t * addr)
{
addr[nr >> 5] &= ~(1 << (nr & 0x1f));
}
static __inline__ void MAPPING_SEARCH(size_t * _r, int *_fl, int *_sl)
{
int _t;
if (*_r < SMALL_BLOCK) {
*_fl = 0;
*_sl = *_r / (SMALL_BLOCK / MAX_SLI);
} else {
_t = (1 << (ms_bit(*_r) - MAX_LOG2_SLI)) - 1;
*_r = *_r + _t;
*_fl = ms_bit(*_r);
*_sl = (*_r >> (*_fl - MAX_LOG2_SLI)) - MAX_SLI;
*_fl -= FLI_OFFSET;
/*if ((*_fl -= FLI_OFFSET) < 0) // FL wil be always >0!
*_fl = *_sl = 0;
*/
*_r &= ~_t;
}
}
static __inline__ void MAPPING_INSERT(size_t _r, int *_fl, int *_sl)
{
if (_r < SMALL_BLOCK) {
*_fl = 0;
*_sl = _r / (SMALL_BLOCK / MAX_SLI);
} else {
*_fl = ms_bit(_r);
*_sl = (_r >> (*_fl - MAX_LOG2_SLI)) - MAX_SLI;
*_fl -= FLI_OFFSET;
}
}
static __inline__ bhdr_t *FIND_SUITABLE_BLOCK(tlsf_t * _tlsf, int *_fl, int *_sl)
{
u32_t _tmp = _tlsf->sl_bitmap[*_fl] & (~0 << *_sl);
bhdr_t *_b = NULL;
if (_tmp) {
*_sl = ls_bit(_tmp);
_b = _tlsf->matrix[*_fl][*_sl];
} else {
*_fl = ls_bit(_tlsf->fl_bitmap & (~0 << (*_fl + 1)));
if (*_fl > 0) { /* likely */
*_sl = ls_bit(_tlsf->sl_bitmap[*_fl]);
_b = _tlsf->matrix[*_fl][*_sl];
}
}
return _b;
}
#define EXTRACT_BLOCK_HDR(_b, _tlsf, _fl, _sl) do { \
_tlsf -> matrix [_fl] [_sl] = _b -> ptr.free_ptr.next; \
if (_tlsf -> matrix[_fl][_sl]) \
_tlsf -> matrix[_fl][_sl] -> ptr.free_ptr.prev = NULL; \
else { \
clear_bit (_sl, &_tlsf -> sl_bitmap [_fl]); \
if (!_tlsf -> sl_bitmap [_fl]) \
clear_bit (_fl, &_tlsf -> fl_bitmap); \
} \
_b -> ptr.free_ptr.prev = NULL; \
_b -> ptr.free_ptr.next = NULL; \
}while(0)
#define EXTRACT_BLOCK(_b, _tlsf, _fl, _sl) do { \
if (_b -> ptr.free_ptr.next) \
_b -> ptr.free_ptr.next -> ptr.free_ptr.prev = _b -> ptr.free_ptr.prev; \
if (_b -> ptr.free_ptr.prev) \
_b -> ptr.free_ptr.prev -> ptr.free_ptr.next = _b -> ptr.free_ptr.next; \
if (_tlsf -> matrix [_fl][_sl] == _b) { \
_tlsf -> matrix [_fl][_sl] = _b -> ptr.free_ptr.next; \
if (!_tlsf -> matrix [_fl][_sl]) { \
clear_bit (_sl, &_tlsf -> sl_bitmap[_fl]); \
if (!_tlsf -> sl_bitmap [_fl]) \
clear_bit (_fl, &_tlsf -> fl_bitmap); \
} \
} \
_b -> ptr.free_ptr.prev = NULL; \
_b -> ptr.free_ptr.next = NULL; \
} while(0)
#define INSERT_BLOCK(_b, _tlsf, _fl, _sl) do { \
_b -> ptr.free_ptr.prev = NULL; \
_b -> ptr.free_ptr.next = _tlsf -> matrix [_fl][_sl]; \
if (_tlsf -> matrix [_fl][_sl]) \
_tlsf -> matrix [_fl][_sl] -> ptr.free_ptr.prev = _b; \
_tlsf -> matrix [_fl][_sl] = _b; \
set_bit (_sl, &_tlsf -> sl_bitmap [_fl]); \
set_bit (_fl, &_tlsf -> fl_bitmap); \
} while(0)
#if USE_SBRK || USE_MMAP
static __inline__ void *get_new_area(size_t * size)
{
void *area;
#if USE_SBRK
area = (void *)sbrk(0);
if (((void *)sbrk(*size)) != ((void *) -1))
return area;
#endif
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
#if USE_MMAP
*size = ROUNDUP(*size, PAGE_SIZE);
if ((area = mmap(0, *size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)) != MAP_FAILED)
return area;
#endif
return ((void *) ~0);
}
#endif
static __inline__ bhdr_t *process_area(void *area, size_t size)
{
bhdr_t *b, *lb, *ib;
area_info_t *ai;
ib = (bhdr_t *) area;
ib->size =
(sizeof(area_info_t) <
MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : ROUNDUP_SIZE(sizeof(area_info_t)) | USED_BLOCK | PREV_USED;
b = (bhdr_t *) GET_NEXT_BLOCK(ib->ptr.buffer, ib->size & BLOCK_SIZE);
b->size = ROUNDDOWN_SIZE(size - 3 * BHDR_OVERHEAD - (ib->size & BLOCK_SIZE)) | USED_BLOCK | PREV_USED;
b->ptr.free_ptr.prev = b->ptr.free_ptr.next = 0;
lb = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
lb->prev_hdr = b;
lb->size = 0 | USED_BLOCK | PREV_FREE;
ai = (area_info_t *) ib->ptr.buffer;
ai->next = 0;
ai->end = lb;
return ib;
}
static char *mp = NULL; /* Default memory pool. */
size_t init_memory_pool(size_t mem_pool_size, void *mem_pool)
{
tlsf_t *tlsf;
bhdr_t *b, *ib;
if (!mem_pool || !mem_pool_size || mem_pool_size < sizeof(tlsf_t) + BHDR_OVERHEAD * 8) {
ERROR_MSG("init_memory_pool (): memory_pool invalid\n");
return -1;
}
if (((unsigned long) mem_pool & PTR_MASK)) {
ERROR_MSG("init_memory_pool (): mem_pool must be aligned to a word\n");
return -1;
}
tlsf = (tlsf_t *) mem_pool;
/* Check if already initialised */
if (tlsf->tlsf_signature == TLSF_SIGNATURE) {
mp = mem_pool;
b = GET_NEXT_BLOCK(mp, ROUNDUP_SIZE(sizeof(tlsf_t)));
return b->size & BLOCK_SIZE;
}
mp = mem_pool;
/* Zeroing the memory pool */
memset(mem_pool, 0, sizeof(tlsf_t));
tlsf->tlsf_signature = TLSF_SIGNATURE;
TLSF_CREATE_LOCK(&tlsf->lock);
ib = process_area(GET_NEXT_BLOCK
(mem_pool, ROUNDUP_SIZE(sizeof(tlsf_t))), ROUNDDOWN_SIZE(mem_pool_size - sizeof(tlsf_t)));
b = GET_NEXT_BLOCK(ib->ptr.buffer, ib->size & BLOCK_SIZE);
free_ex(b->ptr.buffer, tlsf);
tlsf->area_head = (area_info_t *) ib->ptr.buffer;
#if TLSF_STATISTIC
tlsf->used_size = mem_pool_size - (b->size & BLOCK_SIZE);
tlsf->max_size = tlsf->used_size;
#endif
return (b->size & BLOCK_SIZE);
}
size_t add_new_area(void *area, size_t area_size, void *mem_pool)
{
tlsf_t *tlsf = (tlsf_t *) mem_pool;
area_info_t *ptr, *ptr_prev, *ai;
bhdr_t *ib0, *b0, *lb0, *ib1, *b1, *lb1, *next_b;
memset(area, 0, area_size);
ptr = tlsf->area_head;
ptr_prev = 0;
ib0 = process_area(area, area_size);
b0 = GET_NEXT_BLOCK(ib0->ptr.buffer, ib0->size & BLOCK_SIZE);
lb0 = GET_NEXT_BLOCK(b0->ptr.buffer, b0->size & BLOCK_SIZE);
/* Before inserting the new area, we have to merge this area with the
already existing ones */
while (ptr) {
ib1 = (bhdr_t *) ((char *) ptr - BHDR_OVERHEAD);
b1 = GET_NEXT_BLOCK(ib1->ptr.buffer, ib1->size & BLOCK_SIZE);
lb1 = ptr->end;
/* Merging the new area with the next physically contigous one */
if ((unsigned long) ib1 == (unsigned long) lb0 + BHDR_OVERHEAD) {
if (tlsf->area_head == ptr) {
tlsf->area_head = ptr->next;
ptr = ptr->next;
} else {
ptr_prev->next = ptr->next;
ptr = ptr->next;
}
b0->size =
ROUNDDOWN_SIZE((b0->size & BLOCK_SIZE) +
(ib1->size & BLOCK_SIZE) + 2 * BHDR_OVERHEAD) | USED_BLOCK | PREV_USED;
b1->prev_hdr = b0;
lb0 = lb1;
continue;
}
/* Merging the new area with the previous physically contigous
one */
if ((unsigned long) lb1->ptr.buffer == (unsigned long) ib0) {
if (tlsf->area_head == ptr) {
tlsf->area_head = ptr->next;
ptr = ptr->next;
} else {
ptr_prev->next = ptr->next;
ptr = ptr->next;
}
lb1->size =
ROUNDDOWN_SIZE((b0->size & BLOCK_SIZE) +
(ib0->size & BLOCK_SIZE) + 2 * BHDR_OVERHEAD) | USED_BLOCK | (lb1->size & PREV_STATE);
next_b = GET_NEXT_BLOCK(lb1->ptr.buffer, lb1->size & BLOCK_SIZE);
next_b->prev_hdr = lb1;
b0 = lb1;
ib0 = ib1;
continue;
}
ptr_prev = ptr;
ptr = ptr->next;
}
/* Inserting the area in the list of linked areas */
ai = (area_info_t *) ib0->ptr.buffer;
ai->next = tlsf->area_head;
ai->end = lb0;
tlsf->area_head = ai;
free_ex(b0->ptr.buffer, mem_pool);
return (b0->size & BLOCK_SIZE);
}
size_t get_used_size(void *mem_pool)
{
#if TLSF_STATISTIC
return ((tlsf_t *) mem_pool)->used_size;
#else
return 0;
#endif
}
size_t get_max_size(void *mem_pool)
{
#if TLSF_STATISTIC
return ((tlsf_t *) mem_pool)->max_size;
#else
return 0;
#endif
}
void destroy_memory_pool(void *mem_pool)
{
tlsf_t *tlsf = (tlsf_t *) mem_pool;
tlsf->tlsf_signature = 0;
TLSF_DESTROY_LOCK(&tlsf->lock);
}
void *tlsf_malloc(size_t size)
{
void *ret;
#if USE_MMAP || USE_SBRK
if (!mp) {
size_t area_size;
void *area;
area_size = sizeof(tlsf_t) + BHDR_OVERHEAD * 8; /* Just a safety constant */
area_size = (area_size > DEFAULT_AREA_SIZE) ? area_size : DEFAULT_AREA_SIZE;
area = get_new_area(&area_size);
if (area == ((void *) ~0))
return NULL; /* Not enough system memory */
init_memory_pool(area_size, area);
}
#endif
TLSF_ACQUIRE_LOCK(&((tlsf_t *)mp)->lock);
ret = malloc_ex(size, mp);
TLSF_RELEASE_LOCK(&((tlsf_t *)mp)->lock);
return ret;
}
void tlsf_free(void *ptr)
{
TLSF_ACQUIRE_LOCK(&((tlsf_t *)mp)->lock);
free_ex(ptr, mp);
TLSF_RELEASE_LOCK(&((tlsf_t *)mp)->lock);
}
void *tlsf_realloc(void *ptr, size_t size)
{
void *ret;
#if USE_MMAP || USE_SBRK
if (!mp) {
return tlsf_malloc(size);
}
#endif
TLSF_ACQUIRE_LOCK(&((tlsf_t *)mp)->lock);
ret = realloc_ex(ptr, size, mp);
TLSF_RELEASE_LOCK(&((tlsf_t *)mp)->lock);
return ret;
}
void *tlsf_calloc(size_t nelem, size_t elem_size)
{
void *ret;
TLSF_ACQUIRE_LOCK(&((tlsf_t *)mp)->lock);
ret = calloc_ex(nelem, elem_size, mp);
TLSF_RELEASE_LOCK(&((tlsf_t *)mp)->lock);
return ret;
}
void *malloc_ex(size_t size, void *mem_pool)
{
tlsf_t *tlsf = (tlsf_t *) mem_pool;
bhdr_t *b, *b2, *next_b;
int fl, sl;
size_t tmp_size;
size = (size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : ROUNDUP_SIZE(size);
/* Rounding up the requested size and calculating fl and sl */
MAPPING_SEARCH(&size, &fl, &sl);
/* Searching a free block, recall that this function changes the values of fl and sl,
so they are not longer valid when the function fails */
b = FIND_SUITABLE_BLOCK(tlsf, &fl, &sl);
#if USE_MMAP || USE_SBRK
if (!b) {
size_t area_size;
void *area;
/* Growing the pool size when needed */
area_size = size + BHDR_OVERHEAD * 8; /* size plus enough room for the requered headers. */
area_size = (area_size > DEFAULT_AREA_SIZE) ? area_size : DEFAULT_AREA_SIZE;
area = get_new_area(&area_size); /* Call sbrk or mmap */
if (area == ((void *) ~0))
return NULL; /* Not enough system memory */
add_new_area(area, area_size, mem_pool);
/* Rounding up the requested size and calculating fl and sl */
MAPPING_SEARCH(&size, &fl, &sl);
/* Searching a free block */
b = FIND_SUITABLE_BLOCK(tlsf, &fl, &sl);
}
#endif
if (!b)
return NULL; /* Not found */
EXTRACT_BLOCK_HDR(b, tlsf, fl, sl);
/*-- found: */
next_b = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
/* Should the block be split? */
tmp_size = (b->size & BLOCK_SIZE) - size;
if (tmp_size >= sizeof(bhdr_t)) {
tmp_size -= BHDR_OVERHEAD;
b2 = GET_NEXT_BLOCK(b->ptr.buffer, size);
b2->size = tmp_size | FREE_BLOCK | PREV_USED;
next_b->prev_hdr = b2;
MAPPING_INSERT(tmp_size, &fl, &sl);
INSERT_BLOCK(b2, tlsf, fl, sl);
b->size = size | (b->size & PREV_STATE);
} else {
next_b->size &= (~PREV_FREE);
b->size &= (~FREE_BLOCK); /* Now it's used */
}
TLSF_ADD_SIZE(tlsf, b);
return (void *) b->ptr.buffer;
}
void free_ex(void *ptr, void *mem_pool)
{
tlsf_t *tlsf = (tlsf_t *) mem_pool;
bhdr_t *b, *tmp_b;
int fl = 0, sl = 0;
if (!ptr) {
return;
}
b = (bhdr_t *) ((char *) ptr - BHDR_OVERHEAD);
b->size |= FREE_BLOCK;
TLSF_REMOVE_SIZE(tlsf, b);
b->ptr.free_ptr.prev = NULL;
b->ptr.free_ptr.next = NULL;
tmp_b = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
if (tmp_b->size & FREE_BLOCK) {
MAPPING_INSERT(tmp_b->size & BLOCK_SIZE, &fl, &sl);
EXTRACT_BLOCK(tmp_b, tlsf, fl, sl);
b->size += (tmp_b->size & BLOCK_SIZE) + BHDR_OVERHEAD;
}
if (b->size & PREV_FREE) {
tmp_b = b->prev_hdr;
MAPPING_INSERT(tmp_b->size & BLOCK_SIZE, &fl, &sl);
EXTRACT_BLOCK(tmp_b, tlsf, fl, sl);
tmp_b->size += (b->size & BLOCK_SIZE) + BHDR_OVERHEAD;
b = tmp_b;
}
MAPPING_INSERT(b->size & BLOCK_SIZE, &fl, &sl);
INSERT_BLOCK(b, tlsf, fl, sl);
tmp_b = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
tmp_b->size |= PREV_FREE;
tmp_b->prev_hdr = b;
}
void *realloc_ex(void *ptr, size_t new_size, void *mem_pool)
{
tlsf_t *tlsf = (tlsf_t *) mem_pool;
void *ptr_aux;
unsigned int cpsize;
bhdr_t *b, *tmp_b, *next_b;
int fl, sl;
size_t tmp_size;
if (!ptr) {
if (new_size)
return (void *) malloc_ex(new_size, mem_pool);
if (!new_size)
return NULL;
} else if (!new_size) {
free_ex(ptr, mem_pool);
return NULL;
}
b = (bhdr_t *) ((char *) ptr - BHDR_OVERHEAD);
next_b = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
new_size = (new_size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : ROUNDUP_SIZE(new_size);
tmp_size = (b->size & BLOCK_SIZE);
if (new_size <= tmp_size) {
TLSF_REMOVE_SIZE(tlsf, b);
if (next_b->size & FREE_BLOCK) {
MAPPING_INSERT(next_b->size & BLOCK_SIZE, &fl, &sl);
EXTRACT_BLOCK(next_b, tlsf, fl, sl);
tmp_size += (next_b->size & BLOCK_SIZE) + BHDR_OVERHEAD;
next_b = GET_NEXT_BLOCK(next_b->ptr.buffer, next_b->size & BLOCK_SIZE);
/* We allways reenter this free block because tmp_size will
be greater then sizeof (bhdr_t) */
}
tmp_size -= new_size;
if (tmp_size >= sizeof(bhdr_t)) {
tmp_size -= BHDR_OVERHEAD;
tmp_b = GET_NEXT_BLOCK(b->ptr.buffer, new_size);
tmp_b->size = tmp_size | FREE_BLOCK | PREV_USED;
next_b->prev_hdr = tmp_b;
next_b->size |= PREV_FREE;
MAPPING_INSERT(tmp_size, &fl, &sl);
INSERT_BLOCK(tmp_b, tlsf, fl, sl);
b->size = new_size | (b->size & PREV_STATE);
}
TLSF_ADD_SIZE(tlsf, b);
return (void *) b->ptr.buffer;
}
if ((next_b->size & FREE_BLOCK)) {
if (new_size <= (tmp_size + (next_b->size & BLOCK_SIZE))) {
TLSF_REMOVE_SIZE(tlsf, b);
MAPPING_INSERT(next_b->size & BLOCK_SIZE, &fl, &sl);
EXTRACT_BLOCK(next_b, tlsf, fl, sl);
b->size += (next_b->size & BLOCK_SIZE) + BHDR_OVERHEAD;
next_b = GET_NEXT_BLOCK(b->ptr.buffer, b->size & BLOCK_SIZE);
next_b->prev_hdr = b;
next_b->size &= ~PREV_FREE;
tmp_size = (b->size & BLOCK_SIZE) - new_size;
if (tmp_size >= sizeof(bhdr_t)) {
tmp_size -= BHDR_OVERHEAD;
tmp_b = GET_NEXT_BLOCK(b->ptr.buffer, new_size);
tmp_b->size = tmp_size | FREE_BLOCK | PREV_USED;
next_b->prev_hdr = tmp_b;
next_b->size |= PREV_FREE;
MAPPING_INSERT(tmp_size, &fl, &sl);
INSERT_BLOCK(tmp_b, tlsf, fl, sl);
b->size = new_size | (b->size & PREV_STATE);
}
TLSF_ADD_SIZE(tlsf, b);
return (void *) b->ptr.buffer;
}
}
if (!(ptr_aux = malloc_ex(new_size, mem_pool))){
return NULL;
}
cpsize = ((b->size & BLOCK_SIZE) > new_size) ? new_size : (b->size & BLOCK_SIZE);
memcpy(ptr_aux, ptr, cpsize);
free_ex(ptr, mem_pool);
return ptr_aux;
}
void *calloc_ex(size_t nelem, size_t elem_size, void *mem_pool)
{
void *ptr;
if (nelem <= 0 || elem_size <= 0)
return NULL;
if (!(ptr = malloc_ex(nelem * elem_size, mem_pool)))
return NULL;
memset(ptr, 0, nelem * elem_size);
return ptr;
}
#if _DEBUG_TLSF_
/* The following functions have been designed to ease the debugging of */
/* the TLSF structure. For non-developing purposes, it may be they */
/* haven't too much worth. To enable them, _DEBUG_TLSF_ must be set. */
extern void dump_memory_region(unsigned char *mem_ptr, unsigned int size);
extern void print_block(bhdr_t * b);
extern void print_tlsf(tlsf_t * tlsf);
void print_all_blocks(tlsf_t * tlsf);
void dump_memory_region(unsigned char *mem_ptr, unsigned int size)
{
unsigned long begin = (unsigned long) mem_ptr;
unsigned long end = (unsigned long) mem_ptr + size;
int column = 0;
begin >>= 2;
begin <<= 2;
end >>= 2;
end++;
end <<= 2;
PRINT_MSG("\nMemory region dumped: 0x%lx - 0x%lx\n\n", begin, end);
column = 0;
PRINT_MSG("0x%lx ", begin);
while (begin < end) {
if (((unsigned char *) begin)[0] == 0)
PRINT_MSG("00");
else
PRINT_MSG("%02x", ((unsigned char *) begin)[0]);
if (((unsigned char *) begin)[1] == 0)
PRINT_MSG("00 ");
else
PRINT_MSG("%02x ", ((unsigned char *) begin)[1]);
begin += 2;
column++;
if (column == 8) {
PRINT_MSG("\n0x%lx ", begin);
column = 0;
}
}
PRINT_MSG("\n\n");
}
void print_block(bhdr_t * b)
{
if (!b)
return;
PRINT_MSG(">> [%p] (", b);
if ((b->size & BLOCK_SIZE))
PRINT_MSG("%lu bytes, ", (unsigned long) (b->size & BLOCK_SIZE));
else
PRINT_MSG("sentinel, ");
if ((b->size & BLOCK_STATE) == FREE_BLOCK)
PRINT_MSG("free [%p, %p], ", b->ptr.free_ptr.prev, b->ptr.free_ptr.next);
else
PRINT_MSG("used, ");
if ((b->size & PREV_STATE) == PREV_FREE)
PRINT_MSG("prev. free [%p])\n", b->prev_hdr);
else
PRINT_MSG("prev used)\n");
}
void print_tlsf(tlsf_t * tlsf)
{
bhdr_t *next;
int i, j;
PRINT_MSG("\nTLSF at %p\n", tlsf);
PRINT_MSG("FL bitmap: 0x%x\n\n", (unsigned) tlsf->fl_bitmap);
for (i = 0; i < REAL_FLI; i++) {
if (tlsf->sl_bitmap[i])
PRINT_MSG("SL bitmap 0x%x\n", (unsigned) tlsf->sl_bitmap[i]);
for (j = 0; j < MAX_SLI; j++) {
next = tlsf->matrix[i][j];
if (next)
PRINT_MSG("-> [%d][%d]\n", i, j);
while (next) {
print_block(next);
next = next->ptr.free_ptr.next;
}
}
}
}
void print_all_blocks(tlsf_t * tlsf)
{
area_info_t *ai;
bhdr_t *next;
PRINT_MSG("\nTLSF at %p\nALL BLOCKS\n\n", tlsf);
ai = tlsf->area_head;
while (ai) {
next = (bhdr_t *) ((char *) ai - BHDR_OVERHEAD);
while (next) {
print_block(next);
if ((next->size & BLOCK_SIZE))
next = GET_NEXT_BLOCK(next->ptr.buffer, next->size & BLOCK_SIZE);
else
next = NULL;
}
ai = ai->next;
}
}
#endif |
package cz.metacentrum.perun.cabinet.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import cz.metacentrum.perun.cabinet.model.Author;
import cz.metacentrum.perun.cabinet.model.Publication;
import cz.metacentrum.perun.cabinet.model.PublicationSystem;
import cz.metacentrum.perun.cabinet.strategy.<API key>;
public class PubSysTestStrategy implements <API key> {
public final static HttpGet httpGet = new HttpGet("www.metacentrum.cz");
public HttpUriRequest getHttpRequest(String authorId, int yearSince, int yearTill, PublicationSystem ps) {
return httpGet;
}
public List<Publication> parseHttpResponse(HttpResponse response) {
List<Publication> publications = new ArrayList<Publication>();
Publication p = new Publication();
Author a = new Author();
a.setFirstName("Pepa");
a.setLastName("Becher");
List<Author> authors = new ArrayList<Author>();
authors.add(a);
p.setAuthors(authors);
publications.add(p); // we have one publication in list..
return publications;
}
} |
CREATE TABLE IF NOT EXISTS `<API key>` (
`id` int(10) unsigned NOT NULL auto_increment,
`gender` enum('','female','male') NOT NULL,
`title` varchar(255) NOT NULL,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`format` enum('','html','text') NOT NULL,
`subscribe_date` datetime NOT NULL,
`unsubscribed` tinyint(1) NOT NULL,
`activated` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `<API key>` (
`id` int(10) unsigned NOT NULL auto_increment,
`subscriber_id` int(10) unsigned NOT NULL,
`pool_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `subscriber_id` (`subscriber_id`),
KEY `pool_id` (`pool_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
# Tests for XlsxWriter.
import unittest
from ...compatibility import StringIO
from ...styles import Styles
from ...format import Format
class TestWriteCellXfs(unittest.TestCase):
"""
Test the Styles _write_cell_xfs() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_cell_xfs(self):
"""Test the _write_cell_xfs() method"""
xf_format = Format()
xf_format.has_font = 1
self.styles.<API key>([[xf_format], None, 1, 0, 0, 0, [], []])
self.styles._write_cell_xfs()
exp = """<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs>"""
got = self.fh.getvalue()
self.assertEqual(got, exp) |
<?php
class Kwf_Component_Generator_DbIdRecursiveChildComponents_Detail_Cards_Card_Page_Component extends Kwc_Abstract
{
public static function getSettings()
{
$ret = parent::getSettings();
return $ret;
}
} |
<?php
class <API key> extends <API key>
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['ownModel'] = '<API key>';
$ret['generators']['child']['component'] = array(
'empty' => '<API key>',
'extern' => '<API key>'
);
return $ret;
}
} |
<html>
<head>
<script>
function closeWindow()
{
if (window.testRunner) {
testRunner.abortModal();
}
close();
}
</script>
</head>
<body onload="closeWindow()">
This is a modal dialog.
</body>
</html> |
# -*- coding: utf-8 -*-
import warnings
from django.core.exceptions import <API key>
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from .models import Customer
<API key> = (
"The <API key> decorator requires the user"
"be authenticated before use. Please use django.contrib.auth's"
"login_required decorator."
"Please read the warning at"
"http://dj-stripe.readthedocs.org/en/latest/usage.html#<API key>"
)
def <API key>(user):
warnings.warn("Deprecated - Use ``<API key>`` instead. This method will be removed in dj-stripe 1.0.", DeprecationWarning)
return <API key>(user)
def <API key>(subscriber):
"""
Helper function to check if a subscriber has an active subscription.
Throws <API key> if the subscriber is an instance of AUTH_USER_MODEL
and get_user_model().is_anonymous == True.
Activate subscription rules (or):
* customer has active subscription
If the subscriber is an instance of AUTH_USER_MODEL, active subscription rules (or):
* customer has active subscription
* user.is_superuser
* user.is_staff
"""
if isinstance(subscriber, AnonymousUser):
raise <API key>(<API key>)
if isinstance(subscriber, get_user_model()):
if subscriber.is_superuser or subscriber.is_staff:
return True
customer, created = Customer.get_or_create(subscriber)
if created or not customer.<API key>():
return False
return True
def <API key>(api_key):
"""
Pulls a stripe account's supported currencies and returns a choices tuple of
those supported currencies.
:param api_key: The api key associated with the account from which to pull data.
:type api_key: str
"""
import stripe
stripe.api_key = api_key
account = stripe.Account.retrieve()
return [(currency, currency.upper()) for currency in account["<API key>"]] |
# modification, are permitted provided that the following conditions are
# met:
# the distribution.
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# 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.
import IECore
import GafferUI
from Qt import QtCore
from Qt import QtGui
from Qt import QtWidgets
class ScrolledContainer( GafferUI.ContainerWidget ) :
ScrollMode = GafferUI.Enums.ScrollMode
def __init__( self, horizontalMode=GafferUI.ScrollMode.Automatic, verticalMode=GafferUI.ScrollMode.Automatic, borderWidth=0, **kw ) :
GafferUI.ContainerWidget.__init__( self, _ScrollArea(), **kw )
self._qtWidget().setViewportMargins( borderWidth, borderWidth, borderWidth, borderWidth )
self._qtWidget().setWidgetResizable( True )
self.setHorizontalMode( horizontalMode )
self.setVerticalMode( verticalMode )
self.__child = None
def addChild( self, child ) :
if self.getChild() is not None :
raise Exception( "ScrolledContainer can only hold one child" )
self.setChild( child )
def removeChild( self, child ) :
assert( child is self.__child )
child._qtWidget().setParent( None )
child._applyVisibility()
self.__child = None
def setChild( self, child ) :
if self.__child :
self.removeChild( self.__child )
if child is not None :
oldParent = child.parent()
if oldParent is not None :
oldParent.removeChild( child )
self._qtWidget().setWidget( child._qtWidget() )
child._applyVisibility()
self.__child = child
def getChild( self ) :
return self.__child
def setHorizontalMode( self, mode ) :
self._qtWidget().<API key>( GafferUI.ScrollMode._toQt( mode ) )
def getHorizontalMode( self ) :
p = self._qtWidget().<API key>()
return GafferUI.ScrollMode._fromQt( p[0] )
def setVerticalMode( self, mode ) :
self._qtWidget().<API key>( GafferUI.ScrollMode._toQt( mode ) )
def getVerticalMode( self ) :
p = self._qtWidget().<API key>()
return GafferUI.ScrollMode._fromQt( p[1] )
def _revealDescendant( self, descendant ) :
self._qtWidget().ensureWidgetVisible( descendant._qtWidget() )
# Private implementation - a QScrollArea derived class which is a bit more
# forceful about claiming size - it always asks for enough to completely show
# the contained widget.
class _ScrollArea( QtWidgets.QScrollArea ) :
def __init__( self ) :
QtWidgets.QScrollArea.__init__( self )
self.__marginLeft = 0
self.__marginRight = 0
self.__marginTop = 0
self.__marginBottom = 0
def setWidget( self, widget ) :
QtWidgets.QScrollArea.setWidget( self, widget )
widget.installEventFilter( self )
def setViewportMargins( self, left, top, right, bottom ) :
QtWidgets.QScrollArea.setViewportMargins( self, left, top, right, bottom )
self.__marginLeft = left
self.__marginRight = right
self.__marginTop = top
self.__marginBottom = bottom
def sizeHint( self ) :
w = self.widget()
if not w :
return QtWidgets.QScrollArea.sizeHint( self )
wSize = w.sizeHint()
width = self.__marginLeft + self.__marginRight + wSize.width()
if self.<API key>()==QtCore.Qt.ScrollBarAlwaysOn :
width += self.verticalScrollBar().sizeHint().width()
height = self.__marginTop + self.__marginBottom + wSize.height()
if self.<API key>()==QtCore.Qt.ScrollBarAlwaysOn :
height += self.horizontalScrollBar().sizeHint().height()
return QtCore.QSize( width, height )
def eventFilter( self, widget, event ) :
if widget is self.widget() and isinstance( event, QtGui.QResizeEvent ) :
# Ask for our geometry to be recalculated if possible. This allows
# us to expand and contract with our child.
self.updateGeometry()
# I don't know why this is necessary. If it's removed then when the
# child widget resizes and the ScrolledContainer is resized up to fit,
# the scroll bar flickers on and off briefly. This can be seen in the
# OpDialogue with any op with collapsible parameter sections. Ideally
# we would find a better fix, or at least understand this one.
while widget is not None :
if widget.layout() is not None :
widget.layout().invalidate()
widget = widget.parent()
return False |
FROM python:3.8-buster
RUN apt-get update
RUN apt-get install libpq-dev python3-dev -y
ADD ./requirements.txt /flask/requirements.txt
RUN pip3 install -r /flask/requirements.txt
ADD ./ /flask
WORKDIR /flask
EXPOSE 8080
CMD gunicorn app_raw:app -c gunicorn_conf.py -k egg:meinheld#gunicorn_worker |
// A complete set of unit tests for O<API key>.
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/common/net/gaia/<API key>.h"
#include "chrome/common/net/gaia/o<API key>.h"
#include "chrome/common/net/gaia/o<API key>.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/common/url_fetcher.h"
#include "content/public/common/<API key>.h"
#include "content/public/common/url_fetcher_factory.h"
#include "content/test/test_browser_thread.h"
#include "content/test/<API key>.h"
#include "googleurl/src/gurl.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_status.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
using content::URLFetcher;
using content::URLFetcherDelegate;
using content::URLFetcherFactory;
using net::ResponseCookies;
using net::URLRequestStatus;
using testing::_;
using testing::Return;
namespace {
class <API key> : public <API key>,
public URLFetcherFactory {
public:
<API key>()
: <API key>(<API key>(this)) {
}
virtual ~<API key>() {}
MOCK_METHOD4(
CreateURLFetcher,
URLFetcher* (int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcherDelegate* d));
};
class MockO<API key> : public O<API key> {
public:
MockO<API key>() {}
~MockO<API key>() {}
MOCK_METHOD0(OnRevocationSuccess, void());
MOCK_METHOD1(OnRevocationFailure,
void(const <API key>& error));
};
}
class O<API key> : public testing::Test {
public:
O<API key>()
: ui_thread_(BrowserThread::UI, &message_loop_),
fetcher_(&consumer_, profile_.GetRequestContext()) {
}
virtual ~O<API key>() { }
virtual TestURLFetcher* SetupRevocation(
bool fetch_succeeds, int response_code) {
GURL url = O<API key>::MakeRevocationUrl();
TestURLFetcher* url_fetcher = new TestURLFetcher(0, url, &fetcher_);
URLRequestStatus::Status status =
fetch_succeeds ? URLRequestStatus::SUCCESS : URLRequestStatus::FAILED;
url_fetcher->set_status(URLRequestStatus(status, 0));
if (response_code != 0)
url_fetcher->set_response_code(response_code);
EXPECT_CALL(factory_, CreateURLFetcher(_, url, _, _))
.WillOnce(Return(url_fetcher));
return url_fetcher;
}
protected:
MessageLoop message_loop_;
content::TestBrowserThread ui_thread_;
<API key> factory_;
MockO<API key> consumer_;
TestingProfile profile_;
O<API key> fetcher_;
};
TEST_F(O<API key>, RequestFailure) {
TestURLFetcher* url_fetcher = SetupRevocation(false, 0);
EXPECT_CALL(consumer_, OnRevocationFailure(_)).Times(1);
fetcher_.Start("access_token", "client_id", "origin");
fetcher_.OnURLFetchComplete(url_fetcher);
}
TEST_F(O<API key>, ResponseCodeFailure) {
TestURLFetcher* url_fetcher = SetupRevocation(true, net::HTTP_FORBIDDEN);
EXPECT_CALL(consumer_, OnRevocationFailure(_)).Times(1);
fetcher_.Start("access_token", "client_id", "origin");
fetcher_.OnURLFetchComplete(url_fetcher);
}
TEST_F(O<API key>, Success) {
TestURLFetcher* url_fetcher = SetupRevocation(true, net::HTTP_NO_CONTENT);
EXPECT_CALL(consumer_, OnRevocationSuccess()).Times(1);
fetcher_.Start("access_token", "client_id", "origin");
fetcher_.OnURLFetchComplete(url_fetcher);
} |
// The LLVM Compiler Infrastructure
// <tuple>
// template <class... Types> class tuple;
// template <class Alloc, class U1, class U2>
// tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&);
// UNSUPPORTED: c++98, c++03
#include <tuple>
#include <utility>
#include <cassert>
#include "allocators.h"
#include "../alloc_first.h"
#include "../alloc_last.h"
int main()
{
{
typedef std::pair<long, int> T0;
typedef std::tuple<long long, double> T1;
T0 t0(2, 3);
T1 t1(std::allocator_arg, A1<int>(5), t0);
assert(std::get<0>(t1) == 2);
assert(std::get<1>(t1) == 3);
}
{
typedef std::pair<int, int> T0;
typedef std::tuple<alloc_first, double> T1;
T0 t0(2, 3);
alloc_first::<API key> = false;
T1 t1(std::allocator_arg, A1<int>(5), t0);
assert(alloc_first::<API key>);
assert(std::get<0>(t1) == 2);
assert(std::get<1>(t1) == 3);
}
{
typedef std::pair<int, int> T0;
typedef std::tuple<alloc_first, alloc_last> T1;
T0 t0(2, 3);
alloc_first::<API key> = false;
alloc_last::<API key> = false;
T1 t1(std::allocator_arg, A1<int>(5), t0);
assert(alloc_first::<API key>);
assert(alloc_last::<API key>);
assert(std::get<0>(t1) == 2);
assert(std::get<1>(t1) == 3);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.Hardware2.Network.Devices.RTL8139
{
<summary>
The packethead consists of two bytes (i.e. 16 bits).
A PacketHead contains information about a network Packet, and its transfer.
</summary>
[Obsolete("Use Ethernet2Frame instead.")]
public class PacketHeader
{
private UInt16 head;
public PacketHeader(UInt16 data)
{
head = data;
}
public ushort PacketLength
{
get {return 2048;} //TODO: Get from packet?
//private set;
}
public bool IsReceiveOk()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.ROK);
}
public bool <API key>()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.FAE);
}
public bool IsCRCError()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.CRC);
}
public bool IsLongPacket()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.LONG);
}
public bool IsRuntPacket()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.RUNT);
}
public bool <API key>()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.ISE);
}
public bool IsBroadcastAddress()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.BAR);
}
public bool <API key>()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.PAM);
}
public bool IsMulticastAddress()
{
return BinaryHelper.CheckBit(head, (ushort)PacketHeadBit.MAR);
}
private enum PacketHeadBit : ushort
{
ROK = 0x00, //Receive OK
FAE = 0x01, //Frame Alignment Error
CRC = 0x02, //CRC Error
LONG = 0x03,//Long packet - set to 1 when packet over 4k bytes
RUNT = 0x04,//Runt packet received (smaller than 64 bytes)
ISE = 0x05, //Invalid Symbol Error (Only 100BASE-TX).
BAR = 0x0D, //Broadcast Address Received
PAM = 0x0E, //Physical Address Matched
MAR = 0x0F //Multicast Address Received
}
}
} |
package net.sourceforge.pebble.plugins;
import junit.framework.TestCase;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author James Roper
*/
public class TestPluginLocator extends TestCase {
private Map<String, List<Plugin>> plugins;
private URL testPlugins = this.getClass().getResource("/test-plugins.xml");
@Override
protected void setUp() throws Exception {
plugins = new HashMap<String, List<Plugin>>();
}
public void testUnweighted() {
PluginLocator.installPlugins(plugins, testPlugins);
List<Plugin> ps = plugins.get("plugin-type");
assertEquals(2, ps.size());
Plugin plugin = ps.get(0);
assertEquals("Unweighted", plugin.getName());
assertEquals(100, plugin.getWeight());
assertEquals("java.util.ArrayList", plugin.getPluginClass());
assertNull(plugin.getDescription());
assertFalse(plugin.isConfigurable());
assertEquals(0, plugin.getPluginConfig().size());
}
public void testWeighted() {
PluginLocator.installPlugins(plugins, testPlugins);
List<Plugin> ps = plugins.get("plugin-type");
assertEquals(2, ps.size());
Plugin plugin = ps.get(1);
assertEquals("Weighted", plugin.getName());
assertEquals(20, plugin.getWeight());
}
public void testDescription() {
PluginLocator.installPlugins(plugins, testPlugins);
assertEquals("My description", plugins.get("<API key>").get(0).getDescription());
}
private PluginConfig getConfig(int index) {
PluginLocator.installPlugins(plugins, testPlugins);
Plugin plugin = plugins.get("<API key>").get(0);
assertTrue(plugin.isConfigurable());
return ((List<PluginConfig>) plugin.getPluginConfig()).get(index);
}
public void testNoType() {
PluginConfig config = getConfig(0);
assertEquals("No type", config.getName());
assertEquals("notype", config.getKey());
assertSame(<API key>.INSTANCE, config.getType());
assertTrue(config.getProperties().isEmpty());
assertFalse(config.isRequried());
}
public void testStringType() {
assertSame(<API key>.INSTANCE, getConfig(1).getType());
}
public void testPasswordType() {
assertSame(<API key>.INSTANCE, getConfig(2).getType());
}
public void testTextAreaType() {
assertSame(<API key>.INSTANCE, getConfig(3).getType());
}
public void testRequired() {
assertTrue(getConfig(4).isRequried());
}
public void testProperty() {
assertEquals("value", getConfig(5).getProperties().get("property"));
}
} |
#include "Accumulator.h"
#include <vector>
#include <glog/logging.h>
#include <folly/io/async/EventBase.h>
#include <folly/MPMCQueue.h>
#include <folly/Random.h>
#include <folly/ThreadLocal.h>
namespace facebook { namespace memcache { namespace cycles { namespace detail {
// Interval between data aggregations in milliseconds (must be strictly less
// than <API key>).
constexpr size_t <API key> = 1000;
namespace {
// Accumulated stats queue.
folly::MPMCQueue<CycleStats> gStatsQueue{100};
} // anonymous namespace
void Accumulator::add(const Interval& interval) {
auto reqId = interval.label().requestId();
auto idx = reqId % kMaxInflightSamples;
if (inflightSamples_[idx].label == interval.label()) {
// This interval is a part of an existing sample.
inflightSamples_[idx].length += interval.length();
inflightSamples_[idx].numIntervals++;
} else {
if (inflightSamples_[idx].numIntervals != 0 &&
inflightSamples_[idx].contextSwitches == 0) {
// Save previous sample
if (numSamples_ < kMaxSamples) {
samples_[numSamples_] = std::move(inflightSamples_[idx]);
} else {
// reservoir sampling.
auto r = folly::Random::rand32(numSamples_ + 1);
if (r < kMaxSamples) {
samples_[r] = std::move(inflightSamples_[idx]);
}
}
++numSamples_;
}
inflightSamples_[idx].label = interval.label();
inflightSamples_[idx].length = interval.length();
inflightSamples_[idx].numIntervals = 1;
}
}
void Accumulator::attachEventBase(folly::EventBase& eventBase) {
if (eventBase_ != nullptr) {
LOG(ERROR) << "Attempt to reattach EventBase to cycles Accumulator";
return;
}
eventBase_ = &eventBase;
<API key>();
}
CycleStats Accumulator::aggregate() {
CycleStats stats;
if (numSamples_ == 0) {
return stats;
}
// Compute valid intervals and discard invalid.
int lo = 0;
int hi = kMaxSamples - 1;
while (lo <= hi) {
// Verify if sample is valid. We are using a heuristic where a valid
// sample is composed by 2 intervals. Will want to change it in next version
if (samples_[lo].numIntervals >= 2) {
stats.avg += samples_[lo].length;
++lo;
} else {
std::swap(samples_[lo], samples_[hi]);
--hi;
}
}
stats.numSamples = lo;
// Calculate percentils
if (stats.numSamples > 0) {
std::sort(samples_.begin(), samples_.begin() + stats.numSamples,
[](const Sample& lhr, const Sample& rhs) {
return lhr.length < rhs.length;
});
stats.min = samples_[0].length;
stats.p01 = samples_[stats.numSamples * 0.01].length;
stats.p05 = samples_[stats.numSamples * 0.05].length;
stats.p50 = samples_[stats.numSamples * 0.50].length;
stats.p95 = samples_[stats.numSamples * 0.95].length;
stats.p99 = samples_[stats.numSamples * 0.99].length;
stats.max = samples_[stats.numSamples - 1].length;
stats.avg /= stats.numSamples;
}
// Reset and schedule next one.
numSamples_ = 0;
return stats;
}
void Accumulator::<API key>() {
this->eventBase_->runAfterDelay([&] {
CycleStats stats = this->aggregate();
if (stats.numSamples > 0) {
gStatsQueue.write(stats);
}
this-><API key>();
}, <API key>);
}
Accumulator& currentAccumulator() {
static folly::ThreadLocal<Accumulator> accumulator_;
return *accumulator_;
}
CycleStats extract() {
CycleStats stats;
stats.min = std::numeric_limits<uint64_t>::max();
CycleStats tmp;
while (gStatsQueue.read(tmp)) {
stats.min = std::min(stats.min, tmp.min);
stats.max = std::max(stats.max, tmp.max);
stats.avg += (tmp.avg * tmp.numSamples);
stats.p01 += (tmp.p01 * tmp.numSamples);
stats.p05 += (tmp.p05 * tmp.numSamples);
stats.p50 += (tmp.p50 * tmp.numSamples);
stats.p95 += (tmp.p95 * tmp.numSamples);
stats.p99 += (tmp.p99 * tmp.numSamples);
stats.numSamples += tmp.numSamples;
}
if (stats.numSamples > 0) {
stats.avg /= stats.numSamples;
stats.p01 /= stats.numSamples;
stats.p05 /= stats.numSamples;
stats.p50 /= stats.numSamples;
stats.p95 /= stats.numSamples;
stats.p99 /= stats.numSamples;
} else {
stats.min = 0;
}
return stats;
}
}}}} // namespace facebook::memcache::cycles::detail |
/* This is the master header for all device drivers. It includes some other
* files and defines the principal constants.
*/
#define _POSIX_SOURCE 1 /* tell headers to include POSIX stuff */
#define _MINIX 1 /* tell headers to include MINIX stuff */
#define _SYSTEM 1 /* get negative error number in <errno.h> */
/* The following are so basic, all the *.c files get them automatically. */
#include <minix/config.h> /* MUST be first */
#include <ansi.h> /* MUST be second */
#include <minix/type.h>
#include <minix/com.h>
#include <minix/dmap.h>
#include <minix/callnr.h>
#include <sys/types.h>
#include <minix/const.h>
#include <minix/devio.h>
#include <minix/syslib.h>
#include <minix/sysutil.h>
#include <minix/bitmap.h>
#include <ibm/interrupt.h> /* IRQ vectors and miscellaneous ports */
#include <ibm/bios.h> /* BIOS index numbers */
#include <ibm/ports.h> /* Well-known ports */
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <stddef.h>
#include <errno.h>
#include <unistd.h> |
// RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp %s
// RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp-simd %s
struct B {
static int ib[20]; // expected-note 0 {{'B::ib' declared here}}
static constexpr int bfoo() { return 8; }
};
namespace X {
B x; // expected-note {{'x' defined here}}
};
constexpr int bfoo() { return 4; }
int **z;
const int C1 = 1;
const int C2 = 2;
void test_aligned_colons(int *&rp)
{
int *B = 0;
#pragma omp target
#pragma omp teams distribute simd aligned(B:bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B::ib:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'}}
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(z:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}}
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(X::x : ::z) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'int **'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'B'}}
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B,rp,::z: X::x) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'B'}}
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(::z)
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B::bfoo()) // expected-error {{expected variable name}}
for (int i = 0; i < 10; ++i) ;
#pragma omp target
#pragma omp teams distribute simd aligned(B::ib,B:C1+C2) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}}
for (int i = 0; i < 10; ++i) ;
}
// expected-note@+1 {{'num' defined here}}
template<int L, class T, class N> T test_template(T* arr, N num) {
N i;
T sum = (T)0;
T ind2 = - num * L;
// Negative number is passed as L.
#pragma omp target
#pragma omp teams distribute simd aligned(arr:L) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}}
for (i = 0; i < num; ++i) {
T cur = arr[(int)ind2];
ind2 += L;
sum += cur;
}
#pragma omp target
#pragma omp teams distribute simd aligned(num:4) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
for (i = 0; i < num; ++i);
return T();
}
template<int LEN> int test_warn() {
int *ind2 = 0;
#pragma omp target
#pragma omp teams distribute simd aligned(ind2:LEN) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}}
for (int i = 0; i < 100; i++) {
ind2 += LEN;
}
return 0;
}
struct S1; // expected-note 2 {{declared here}}
extern S1 a; // expected-note {{'a' declared here}}
class S2 {
mutable int a;
public:
S2():a(0) { }
};
const S2 b; // expected-note 1 {{'b' defined here}}
const S2 ba[5];
class S3 {
int a;
public:
S3():a(0) { }
};
const S3 ca[5];
class S4 {
int a;
S4();
public:
S4(int v):a(v) { }
};
class S5 {
int a;
S5():a(0) {}
public:
S5(int v):a(v) { }
};
S3 h; // expected-note 2 {{'h' defined here}}
#pragma omp threadprivate(h)
template<class I, class C> int foomain(I argc, C **argv) {
I e(argc);
I g(argc);
int i; // expected-note {{'i' defined here}}
// expected-note@+1 {{declared here}}
int &j = i;
#pragma omp target
#pragma omp teams distribute simd aligned // expected-error {{expected '(' after 'aligned'}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned () // expected-error {{expected expression}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (I k = 0; k < argc; ++k) ++k;
// FIXME: Should argc really be a pointer?
#pragma omp target
#pragma omp teams distribute simd aligned (*argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argc : 5) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (S1) // expected-error {{'S1' does not refer to a value}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argv[1]) // expected-error {{expected variable name}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned(e, g)
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned(i) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
for (I k = 0; k < argc; ++k) ++k;
#pragma omp parallel
{
int *v = 0;
I i;
#pragma omp target
#pragma omp teams distribute simd aligned(v:16)
for (I k = 0; k < argc; ++k) { i = k; v += 2; }
}
float *f;
#pragma omp target
#pragma omp teams distribute simd aligned(f)
for (I k = 0; k < argc; ++k) ++k;
int v = 0;
#pragma omp target
#pragma omp teams distribute simd aligned(f:j) // expected-note {{initializer of 'j' is not a constant expression}} expected-error {{expression is not an integral constant expression}}
for (I k = 0; k < argc; ++k) { ++k; v += j; }
#pragma omp target
#pragma omp teams distribute simd aligned(f)
for (I k = 0; k < argc; ++k) ++k;
return 0;
}
// expected-note@+1 2 {{'argc' defined here}}
int main(int argc, char **argv) {
double darr[100];
// expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}}
test_template<-4>(darr, 4);
test_warn<4>();
// expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}}
test_warn<0>();
int i;
int &j = i;
#pragma omp target
#pragma omp teams distribute simd aligned // expected-error {{expected '(' after 'aligned'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argv // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams
#pragma omp distribute simd aligned (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams
#pragma omp distribute simd aligned (argc) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (a, b) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S1'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S2'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target
#pragma omp teams distribute simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}}
for (int k = 0; k < argc; ++k) ++k;
int *pargc = &argc;
// expected-note@+1 {{in instantiation of function template specialization 'foomain<int *, char>' requested here}}
foomain<int*,char>(pargc,argv);
return 0;
} |
let deviceId = null;
const onDeviceChanged = (response) => {
chrome.hid.getDevices({}, devices => {
for (let device of devices) {
if (device.deviceId == deviceId && device.collections.length == 2) {
chrome.test.sendMessage("changed");
return;
}
}
console.error("Device not found");
chrome.test.sendMessage("failure");
});
};
chrome.hid.onDeviceAdded.addListener(function (device) {
if (device.collections.length == 1) {
deviceId = device.deviceId;
chrome.test.sendMessage("added", onDeviceChanged);
} else {
console.error("Got unexpected device with " + device.collections.length +
" collections");
chrome.test.sendMessage("failure");
}
});
chrome.hid.onDeviceRemoved.addListener(function (removedId) {
if (deviceId == removedId) {
chrome.test.sendMessage("success");
} else {
console.error("Received removed event for wrong device");
chrome.test.sendMessage("failure");
}
});
chrome.test.sendMessage("loaded"); |
/*
* NaCl Simple/secure ELF loader (NaCl SEL).
*/
#ifndef <API key>
#define <API key> 1
#include "native_client/src/include/nacl_base.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/trusted/service_runtime/nacl_error_code.h"
struct NaClApp; /* fwd */
EXTERN_C_BEGIN
#if NACL_LINUX
extern size_t <API key>;
#endif
enum NaClAslrMode {
NACL_DISABLE_ASLR,
NACL_ENABLE_ASLR
};
/*
* Try to find prereserved sandbox memory. Sets *p to the start of the
* sandbox.
*
* Returns a non-zero value if prereserved sandbox memory was found and the
* memory is the same size as the requested size. Returns zero otherwise.
*/
int <API key>(void **p, size_t num_bytes);
void <API key>(size_t guarded_addrsp_size);
/*
* Allocate the NaCl module's address space. The |aslr_mode|
* argument is passed to <API key> and may be ignored on
* platforms where the sandbox requires a zero-base, e.g., ARM.
*/
NaClErrorCode <API key>(struct NaClApp *nap,
enum NaClAslrMode aslr_mode) NACL_WUR;
/*
* Old interface. Invokes <API key> with aslr_mode =
* NACL_ENABLE_ASLR.
*/
NaClErrorCode NaClAllocAddrSpace(struct NaClApp *nap) NACL_WUR;
/*
* Apply memory protection to memory regions.
*/
NaClErrorCode <API key>(struct NaClApp *nap) NACL_WUR;
/*
* Platform-specific routine to allocate memory space for the NaCl
* module. mem is an out argument; addrsp_size is the requested
* address space size, currently always ((size_t) 1) <<
* nap->addr_bits. On x86-64, there's a further requirement that this
* is 4G.
*
* If |aslr_mode| is NACL_ENABLE_ASLR, this routine will attempt to
* pick a random address for the address space. If we are running on
* a platform where a zero-based address space is pre-reserved (for
* Atom performance issues), then |aslr_mode| may be ignored.
*
* The actual amount of memory allocated is larger than requested on
* x86-64 and on the ARM, since guard pages are also allocated to be
* contiguous with the allocated address space.
*
* If successful, the guard pages are also mapped as inaccessible (PROT_NONE).
*
* Returns LOAD_OK on success.
*/
NaClErrorCode <API key>(void **mem, size_t addrsp_size,
enum NaClAslrMode aslr_mode) NACL_WUR;
/*
* Old interface. Invokes <API key> with aslr_mode =
* NACL_ENABLE_ASLR.
*/
NaClErrorCode NaClAllocateSpace(void **mem, size_t addrsp_size) NACL_WUR;
/*
* NaClAddrSpaceFree() unmaps all of untrusted address space. This is
* only safe if no untrusted threads are running.
*
* Note that this does not free any other data structures associated
* with the NaClApp. In particular, it does not free mem_map.
*/
void NaClAddrSpaceFree(struct NaClApp *nap);
EXTERN_C_END
#endif |
#pragma once
namespace stm32plus {
/**
* Base feature class to enable polling communication in master mode. This class manages
* the actual I2C protocol interaction. It makes the assumption that the exchange with a
* peripheral consists of sending N bytes as an "address" and then either reading or
* writing some data. The address size (N) can be 1..255. That size can be found in
* the I2C Parameters class.
*/
class <API key> : public I2CIoFeature {
protected:
uint8_t _slaveAddress;
protected:
bool checkEvent(uint32_t eventId) const;
public:
<API key>(I2C& i2c);
bool prepareRead(const uint8_t *address) const;
bool readBytes(const uint8_t *address,uint8_t *output,uint32_t count) const;
bool prepareWrite(const uint8_t *address) const;
bool writeBytes(const uint8_t *address,const uint8_t *input,uint32_t count) const;
void setSlaveAddress(uint8_t address);
};
/**
* Constructor
* @param i2c The i2c feature base reference
*/
inline <API key>::<API key>(I2C& i2c)
: I2CIoFeature(i2c) {
}
/**
* Set the slave peripheral address
* @param address The 7-bit slave address is left aligned within the byte. i.e. the MSB
* of the slave address is bit 7 (the 8th bit) in this parameter.
*/
inline void <API key>::setSlaveAddress(uint8_t address) {
_slaveAddress=address;
}
} |
#include "ui/gl/trace_util.h"
#include "base/format_macros.h"
#include "base/strings/stringprintf.h"
namespace gl {
base::trace_event::<API key> <API key>(
uint64_t share_group_guid,
uint32_t texture_id) {
return base::trace_event::<API key>(
base::StringPrintf("<API key>/%" PRIx64 "/%d",
share_group_guid, texture_id));
}
base::trace_event::<API key> <API key>(
uint64_t share_group_guid,
uint32_t texture_id) {
return base::trace_event::<API key>(
base::StringPrintf("<API key>/%" PRIx64 "/%d",
share_group_guid, texture_id));
}
base::trace_event::<API key> <API key>(
uint64_t share_group_guid,
uint32_t buffer_id) {
return base::trace_event::<API key>(base::StringPrintf(
"gl-buffer-x-process/%" PRIx64 "/%d", share_group_guid, buffer_id));
}
base::trace_event::<API key> <API key>(
uint64_t share_group_guid,
uint32_t renderbuffer_id) {
return base::trace_event::<API key>(
base::StringPrintf("<API key>/%" PRIx64 "/%d",
share_group_guid, renderbuffer_id));
}
} // namespace gl |
#ifndef <API key>
#define <API key>
#pragma once
#include "base/debug/trace_event.h"
#define SK_TRACE_EVENT0(name) \
TRACE_EVENT0("skia", name)
#define SK_TRACE_EVENT1(name, arg1_name, arg1_val) \
TRACE_EVENT1("skia", name, arg1_name, arg1_val)
#define SK_TRACE_EVENT2(name, arg1_name, arg1_val, arg2_name, arg2_val) \
TRACE_EVENT1("skia", name, arg1_name, arg1_val, arg2_name, arg2_val)
#endif |
package org.bouncycastle.jcajce.provider.symmetric;
import org.bouncycastle.jcajce.provider.config.<API key>;
import org.bouncycastle.jcajce.provider.util.AlgorithmProvider;
abstract class <API key>
extends AlgorithmProvider
{
protected void addGMacAlgorithm(
<API key> provider,
String algorithm,
String algorithmClassName,
String <API key>)
{
provider.addAlgorithm("Mac." + algorithm + "-GMAC", algorithmClassName);
provider.addAlgorithm("Alg.Alias.Mac." + algorithm + "GMAC", algorithm + "-GMAC");
provider.addAlgorithm("KeyGenerator." + algorithm + "-GMAC", <API key>);
provider.addAlgorithm("Alg.Alias.KeyGenerator." + algorithm + "GMAC", algorithm + "-GMAC");
}
protected void <API key>(<API key> provider,
String algorithm,
String algorithmClassName,
String <API key>)
{
provider.addAlgorithm("Mac.POLY1305-" + algorithm, algorithmClassName);
provider.addAlgorithm("Alg.Alias.Mac.POLY1305" + algorithm, "POLY1305-" + algorithm);
provider.addAlgorithm("KeyGenerator.POLY1305-" + algorithm, <API key>);
provider.addAlgorithm("Alg.Alias.KeyGenerator.POLY1305" + algorithm, "POLY1305-" + algorithm);
}
} |
// <API key>.h
// APCAppCore
// are permitted provided that the following conditions are met:
// other materials provided with the distribution.
// may be used to endorse or promote products derived from this software without
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// 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.
#import <UIKit/UIKit.h>
@interface <API key> : <API key>
//Abstract Implementations
- (void) next;
- (BOOL) isContentValid;
@end |
#ifndef <API key>
#define <API key>
#include <stddef.h>
#include "base/types/pass_key.h"
#include "chrome/browser/ui/tabs/<API key>.h"
class Browser;
class TabStripModel;
class <API key>;
namespace chromeos {
class DesksHelper;
// <API key> implementation for chromeos specific code.
class <API key> : public <API key> {
public:
<API key>(
base::PassKey<<API key>> passkey,
ui::SimpleMenuModel::Delegate* parent_delegate,
<API key>* <API key>,
TabStripModel* model,
int context_index);
<API key>(
const <API key>&) = delete;
<API key>& operator=(
const <API key>&) = delete;
~<API key>() override;
private:
// Builds the submenu, grouping browsers from |existing_browsers| by desks.
// Browsers within desk groupings maintain the originally provided order. I.e.
// if browsers were provided in MRU order, then within desk groupings browsers
// will be in MRU order.
void <API key>(const std::vector<Browser*>& existing_browsers);
};
} // namespace chromeos
#endif // <API key> |
#ifndef <API key>
#define <API key>
#include <asm/arch/chip-features.h>
#include <asm/arch/portmux.h>
#ifdef CONFIG_PLL
#define PLL0_RATE ((CONFIG_SYS_OSC0_HZ / CONFIG_SYS_PLL0_DIV) \
* CONFIG_SYS_PLL0_MUL)
#define MAIN_CLK_RATE PLL0_RATE
#else
#define MAIN_CLK_RATE (CONFIG_SYS_OSC0_HZ)
#endif
static inline unsigned long get_cpu_clk_rate(void)
{
return MAIN_CLK_RATE >> <API key>;
}
static inline unsigned long get_hsb_clk_rate(void)
{
return MAIN_CLK_RATE >> <API key>;
}
static inline unsigned long get_pba_clk_rate(void)
{
return MAIN_CLK_RATE >> <API key>;
}
static inline unsigned long get_pbb_clk_rate(void)
{
return MAIN_CLK_RATE >> <API key>;
}
/* Accessors for specific devices. More will be added as needed. */
static inline unsigned long get_sdram_clk_rate(void)
{
return get_hsb_clk_rate();
}
#ifdef <API key>
static inline unsigned long get_usart_clk_rate(unsigned int dev_id)
{
return get_pba_clk_rate();
}
#endif
#ifdef <API key>
static inline unsigned long get_macb_pclk_rate(unsigned int dev_id)
{
return get_pbb_clk_rate();
}
static inline unsigned long get_macb_hclk_rate(unsigned int dev_id)
{
return get_hsb_clk_rate();
}
#endif
#ifdef <API key>
static inline unsigned long get_mci_clk_rate(void)
{
return get_pbb_clk_rate();
}
#endif
#ifdef <API key>
static inline unsigned long get_spi_clk_rate(unsigned int dev_id)
{
return get_pba_clk_rate();
}
#endif
#ifdef <API key>
static inline unsigned long get_lcdc_clk_rate(unsigned int dev_id)
{
return get_hsb_clk_rate();
}
#endif
extern void clk_init(void);
/* Board code may need the SDRAM base clock as a compile-time constant */
#define SDRAMC_BUS_HZ (MAIN_CLK_RATE >> <API key>)
/* Generic clock control */
enum gclk_parent {
GCLK_PARENT_OSC0 = 0,
GCLK_PARENT_OSC1 = 1,
GCLK_PARENT_PLL0 = 2,
GCLK_PARENT_PLL1 = 3,
};
/* Some generic clocks have specific roles */
#define GCLK_DAC_SAMPLE_CLK 6
#define GCLK_LCDC_PIXCLK 7
extern unsigned long __gclk_set_rate(unsigned int id, enum gclk_parent parent,
unsigned long rate, unsigned long parent_rate);
/**
* gclk_set_rate - configure and enable a generic clock
* @id: Which GCLK[id] to enable
* @parent: Parent clock feeding the GCLK
* @rate: Target rate of the GCLK in Hz
*
* Returns the actual GCLK rate in Hz, after rounding to the nearest
* supported rate.
*
* All three parameters are usually constant, hence the inline.
*/
static inline unsigned long gclk_set_rate(unsigned int id,
enum gclk_parent parent, unsigned long rate)
{
unsigned long parent_rate;
if (id > 7)
return 0;
switch (parent) {
case GCLK_PARENT_OSC0:
parent_rate = CONFIG_SYS_OSC0_HZ;
break;
#ifdef CONFIG_SYS_OSC1_HZ
case GCLK_PARENT_OSC1:
parent_rate = CONFIG_SYS_OSC1_HZ;
break;
#endif
#ifdef PLL0_RATE
case GCLK_PARENT_PLL0:
parent_rate = PLL0_RATE;
break;
#endif
#ifdef PLL1_RATE
case GCLK_PARENT_PLL1:
parent_rate = PLL1_RATE;
break;
#endif
default:
parent_rate = 0;
break;
}
return __gclk_set_rate(id, parent, rate, parent_rate);
}
/**
* gclk_enable_output - enable output on a GCLK pin
* @id: Which GCLK[id] pin to enable
* @drive_strength: Drive strength of external GCLK pin, if applicable
*/
static inline void gclk_enable_output(unsigned int id,
unsigned long drive_strength)
{
switch (id) {
case 0:
<API key>(PORTMUX_PORT_A, 1 << 30,
PORTMUX_FUNC_A, drive_strength);
break;
case 1:
<API key>(PORTMUX_PORT_A, 1 << 31,
PORTMUX_FUNC_A, drive_strength);
break;
case 2:
<API key>(PORTMUX_PORT_B, 1 << 19,
PORTMUX_FUNC_A, drive_strength);
break;
case 3:
<API key>(PORTMUX_PORT_B, 1 << 29,
PORTMUX_FUNC_A, drive_strength);
break;
case 4:
<API key>(PORTMUX_PORT_B, 1 << 30,
PORTMUX_FUNC_A, drive_strength);
break;
}
}
#endif /* <API key> */ |
#ifndef <API key>
#define <API key>
#define REG_SPI_BASE(i) (0x60000200-i*0x100)
#define SPI_CMD(i) (REG_SPI_BASE(i) + 0x0)
#define SPI_FLASH_READ (BIT(31)) //From previous SDK
#define SPI_FLASH_WREN (BIT(30)) //From previous SDK
#define SPI_FLASH_WRDI (BIT(29)) //From previous SDK
#define SPI_FLASH_RDID (BIT(28)) //From previous SDK
#define SPI_FLASH_RDSR (BIT(27)) //From previous SDK
#define SPI_FLASH_WRSR (BIT(26)) //From previous SDK
#define SPI_FLASH_PP (BIT(25)) //From previous SDK
#define SPI_FLASH_SE (BIT(24)) //From previous SDK
#define SPI_FLASH_BE (BIT(23)) //From previous SDK
#define SPI_FLASH_CE (BIT(22)) //From previous SDK
#define SPI_FLASH_DP (BIT(21)) //From previous SDK
#define SPI_FLASH_RES (BIT(20)) //From previous SDK
#define SPI_FLASH_HPM (BIT(19)) //From previous SDK
#define SPI_USR (BIT(18))
#define SPI_ADDR(i) (REG_SPI_BASE(i) + 0x4)
#define SPI_CTRL(i) (REG_SPI_BASE(i) + 0x8)
#define SPI_WR_BIT_ORDER (BIT(26))
#define SPI_RD_BIT_ORDER (BIT(25))
#define SPI_QIO_MODE (BIT(24))
#define SPI_DIO_MODE (BIT(23))
#define <API key> (BIT(22)) //From previous SDK
#define SPI_WP_REG (BIT(21)) //From previous SDK
#define SPI_QOUT_MODE (BIT(20))
#define SPI_SHARE_BUS (BIT(19)) //From previous SDK
#define SPI_HOLD_MODE (BIT(18)) //From previous SDK
#define SPI_ENABLE_AHB (BIT(17)) //From previous SDK
#define SPI_SST_AAI (BIT(16)) //From previous SDK
#define SPI_RESANDRES (BIT(15)) //From previous SDK
#define SPI_DOUT_MODE (BIT(14))
#define SPI_FASTRD_MODE (BIT(13))
#define SPI_CTRL1(i) (REG_SPI_BASE (i) + 0xC) //From previous SDK. Removed _FLASH_ from name to match other registers.
#define SPI_CS_HOLD_DELAY 0x0000000F //Espressif BBS
#define SPI_CS_HOLD_DELAY_S 28 //Espressif BBS
#define <API key> 0x00000FFF //Espressif BBS
#define <API key> 16 //Espressif BBS
#define SPI_BUS_TIMER_LIMIT 0x0000FFFF //From previous SDK
#define <API key> 0 //From previous SDK
#define SPI_RD_STATUS(i) (REG_SPI_BASE(i) + 0x10)
#define SPI_STATUS_EXT 0x000000FF //From previous SDK
#define SPI_STATUS_EXT_S 24 //From previous SDK
#define SPI_WB_MODE 0x000000FF //From previous SDK
#define SPI_WB_MODE_S 16 //From previous SDK
#define <API key> (BIT(7)) //From previous SDK
#define <API key> (BIT(5)) //From previous SDK
#define SPI_FLASH_BP2 (BIT(4)) //From previous SDK
#define SPI_FLASH_BP1 (BIT(3)) //From previous SDK
#define SPI_FLASH_BP0 (BIT(2)) //From previous SDK
#define <API key> (BIT(1)) //From previous SDK
#define SPI_FLASH_BUSY_FLAG (BIT(0)) //From previous SDK
#define SPI_CTRL2(i) (REG_SPI_BASE(i) + 0x14)
#define SPI_CS_DELAY_NUM 0x0000000F
#define SPI_CS_DELAY_NUM_S 28
#define SPI_CS_DELAY_MODE 0x00000003
#define SPI_CS_DELAY_MODE_S 26
#define SPI_MOSI_DELAY_NUM 0x00000007
#define <API key> 23
#define SPI_MOSI_DELAY_MODE 0x00000003 //mode 0 : posedge; data set at positive edge of clk
//mode 1 : negedge + 1 cycle delay, only if freq<10MHz ; data set at negitive edge of clk
//mode 2 : Do not use this mode.
#define <API key> 21
#define SPI_MISO_DELAY_NUM 0x00000007
#define <API key> 18
#define SPI_MISO_DELAY_MODE 0x00000003
#define <API key> 16
#define <API key> 0x0000000F
#define <API key> 12
#define SPI_CK_OUT_LOW_MODE 0x0000000F
#define <API key> 8
#define SPI_HOLD_TIME 0x0000000F
#define SPI_HOLD_TIME_S 4
#define SPI_SETUP_TIME 0x0000000F
#define SPI_SETUP_TIME_S 0
#define SPI_CLOCK(i) (REG_SPI_BASE(i) + 0x18)
#define SPI_CLK_EQU_SYSCLK (BIT(31))
#define SPI_CLKDIV_PRE 0x00001FFF
#define SPI_CLKDIV_PRE_S 18
#define SPI_CLKCNT_N 0x0000003F
#define SPI_CLKCNT_N_S 12
#define SPI_CLKCNT_H 0x0000003F
#define SPI_CLKCNT_H_S 6
#define SPI_CLKCNT_L 0x0000003F
#define SPI_CLKCNT_L_S 0
#define SPI_USER(i) (REG_SPI_BASE(i) + 0x1C)
#define SPI_USR_COMMAND (BIT(31))
#define SPI_USR_ADDR (BIT(30))
#define SPI_USR_DUMMY (BIT(29))
#define SPI_USR_MISO (BIT(28))
#define SPI_USR_MOSI (BIT(27))
#define SPI_USR_DUMMY_IDLE (BIT(26)) //From previous SDK
#define <API key> (BIT(25))
#define <API key> (BIT(24))
#define SPI_USR_PREP_HOLD (BIT(23)) //From previous SDK
#define SPI_USR_CMD_HOLD (BIT(22)) //From previous SDK
#define SPI_USR_ADDR_HOLD (BIT(21)) //From previous SDK
#define SPI_USR_DUMMY_HOLD (BIT(20)) //From previous SDK
#define SPI_USR_DIN_HOLD (BIT(19)) //From previous SDK
#define SPI_USR_DOUT_HOLD (BIT(18)) //From previous SDK
#define SPI_USR_HOLD_POL (BIT(17)) //From previous SDK
#define SPI_SIO (BIT(16))
#define SPI_FWRITE_QIO (BIT(15))
#define SPI_FWRITE_DIO (BIT(14))
#define SPI_FWRITE_QUAD (BIT(13))
#define SPI_FWRITE_DUAL (BIT(12))
#define SPI_WR_BYTE_ORDER (BIT(11))
#define SPI_RD_BYTE_ORDER (BIT(10))
#define SPI_AHB_ENDIAN_MODE 0x00000003 //From previous SDK
#define <API key> 8 //From previous SDK
#define SPI_CK_OUT_EDGE (BIT(7))
#define SPI_CK_I_EDGE (BIT(6))
#define SPI_CS_SETUP (BIT(5))
#define SPI_CS_HOLD (BIT(4))
#define SPI_AHB_USR_COMMAND (BIT(3)) //From previous SDK
#define SPI_FLASH_MODE (BIT(2))
#define <API key> (BIT(1)) //From previous SDK
#define SPI_DOUTDIN (BIT(0)) //From previous SDK
#define SPI_USER1(i) (REG_SPI_BASE(i) + 0x20)
#define SPI_USR_ADDR_BITLEN 0x0000003F
#define <API key> 26
#define SPI_USR_MOSI_BITLEN 0x000001FF
#define <API key> 17
#define SPI_USR_MISO_BITLEN 0x000001FF
#define <API key> 8
#define <API key> 0x000000FF
#define <API key> 0
#define SPI_USER2(i) (REG_SPI_BASE(i) + 0x24)
#define <API key> 0x0000000F
#define <API key> 28
#define <API key> 0x0000FFFF
#define <API key> 0
#define SPI_WR_STATUS(i) (REG_SPI_BASE(i) + 0x28)
//previously defined as SPI_FLASH_USER3. No further info available.
#define SPI_PIN(i) (REG_SPI_BASE(i) + 0x2C)
#define SPI_IDLE_EDGE (BIT(29))
#define SPI_CS2_DIS (BIT(2))
#define SPI_CS1_DIS (BIT(1))
#define SPI_CS0_DIS (BIT(0))
#define SPI_SLAVE(i) (REG_SPI_BASE(i) + 0x30)
#define SPI_SYNC_RESET (BIT(31))
#define SPI_SLAVE_MODE (BIT(30))
#define <API key> (BIT(29))
#define <API key> (BIT(28))
#define SPI_SLV_CMD_DEFINE (BIT(27))
#define SPI_TRANS_CNT 0x0000000F
#define SPI_TRANS_CNT_S 23
#define SPI_SLV_LAST_STATE 0x00000007 //From previous SDK
#define <API key> 20 //From previous SDK
#define <API key> 0x00000007 //From previous SDK
#define <API key> 17 //From previous SDK
#define SPI_CS_I_MODE 0x00000003 //From previous SDK
#define SPI_CS_I_MODE_S 10 //From previous SDK
#define SPI_TRANS_DONE_EN (BIT(9))
#define <API key> (BIT(8))
#define <API key> (BIT(7))
#define <API key> (BIT(6))
#define <API key> (BIT(5))
#define SLV_SPI_INT_EN 0x0000001f
#define SLV_SPI_INT_EN_S 5
#define SPI_TRANS_DONE (BIT(4))
#define SPI_SLV_WR_STA_DONE (BIT(3))
#define SPI_SLV_RD_STA_DONE (BIT(2))
#define SPI_SLV_WR_BUF_DONE (BIT(1))
#define SPI_SLV_RD_BUF_DONE (BIT(0))
#define SPI_SLAVE1(i) (REG_SPI_BASE(i) + 0x34)
#define <API key> 0x0000001F
#define <API key> 27
#define <API key> (BIT(26)) //From previous SDK
#define <API key> (BIT(25)) //From previous SDK
#define SPI_SLV_BUF_BITLEN 0x000001FF
#define <API key> 16
#define <API key> 0x0000003F
#define <API key> 10
#define <API key> 0x0000003F
#define <API key> 4
#define <API key> (BIT(3))
#define <API key> (BIT(2))
#define <API key> (BIT(1))
#define <API key> (BIT(0))
#define SPI_SLAVE2(i) (REG_SPI_BASE(i) + 0x38)
#define <API key> 0X000000FF
#define <API key> 24
#define <API key> 0X000000FF
#define <API key> 16
#define <API key> 0X000000FF
#define <API key> 8
#define <API key> 0x000000FF
#define <API key> 0
#define SPI_SLAVE3(i) (REG_SPI_BASE(i) + 0x3C)
#define <API key> 0x000000FF
#define <API key> 24
#define <API key> 0x000000FF
#define <API key> 16
#define <API key> 0x000000FF
#define <API key> 8
#define <API key> 0x000000FF
#define <API key> 0
//Previous SDKs referred to these following registers as SPI_C0 etc.
#define SPI_W0(i) (REG_SPI_BASE(i) +0x40)
#define SPI_W1(i) (REG_SPI_BASE(i) +0x44)
#define SPI_W2(i) (REG_SPI_BASE(i) +0x48)
#define SPI_W3(i) (REG_SPI_BASE(i) +0x4C)
#define SPI_W4(i) (REG_SPI_BASE(i) +0x50)
#define SPI_W5(i) (REG_SPI_BASE(i) +0x54)
#define SPI_W6(i) (REG_SPI_BASE(i) +0x58)
#define SPI_W7(i) (REG_SPI_BASE(i) +0x5C)
#define SPI_W8(i) (REG_SPI_BASE(i) +0x60)
#define SPI_W9(i) (REG_SPI_BASE(i) +0x64)
#define SPI_W10(i) (REG_SPI_BASE(i) +0x68)
#define SPI_W11(i) (REG_SPI_BASE(i) +0x6C)
#define SPI_W12(i) (REG_SPI_BASE(i) +0x70)
#define SPI_W13(i) (REG_SPI_BASE(i) +0x74)
#define SPI_W14(i) (REG_SPI_BASE(i) +0x78)
#define SPI_W15(i) (REG_SPI_BASE(i) +0x7C)
// +0x80 to +0xBC could be SPI_W16 through SPI_W31?
// +0xC0 to +0xEC not currently defined.
#define SPI_EXT0(i) (REG_SPI_BASE(i) + 0xF0) //From previous SDK. Removed _FLASH_ from name to match other registers.
#define SPI_T_PP_ENA (BIT(31)) //From previous SDK
#define SPI_T_PP_SHIFT 0x0000000F //From previous SDK
#define SPI_T_PP_SHIFT_S 16 //From previous SDK
#define SPI_T_PP_TIME 0x00000FFF //From previous SDK
#define SPI_T_PP_TIME_S 0 //From previous SDK
#define SPI_EXT1(i) (REG_SPI_BASE(i) + 0xF4) //From previous SDK. Removed _FLASH_ from name to match other registers.
#define SPI_T_ERASE_ENA (BIT(31)) //From previous SDK
#define SPI_T_ERASE_SHIFT 0x0000000F //From previous SDK
#define SPI_T_ERASE_SHIFT_S 16 //From previous SDK
#define SPI_T_ERASE_TIME 0x00000FFF //From previous SDK
#define SPI_T_ERASE_TIME_S 0 //From previous SDK
#define SPI_EXT2(i) (REG_SPI_BASE(i) + 0xF8) //From previous SDK. Removed _FLASH_ from name to match other registers.
#define SPI_ST 0x00000007 //From previous SDK
#define SPI_ST_S 0 //From previous SDK
#define SPI_EXT3(i) (REG_SPI_BASE(i) + 0xFC)
#define SPI_INT_HOLD_ENA 0x00000003
#define SPI_INT_HOLD_ENA_S 0
#endif // <API key> |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ResourceManager.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
<summary>
Tag details.
</summary>
public partial class TagDetails : IResource
{
<summary>
Initializes a new instance of the TagDetails class.
</summary>
public TagDetails()
{
CustomInit();
}
<summary>
Initializes a new instance of the TagDetails class.
</summary>
<param name="id">The tag name ID.</param>
<param name="tagName">The tag name.</param>
<param name="count">The total number of resources that use the
resource tag. When a tag is initially created and has no associated
resources, the value is 0.</param>
<param name="values">The list of tag values.</param>
public TagDetails(string id = default(string), string tagName = default(string), TagCount count = default(TagCount), IList<TagValue> values = default(IList<TagValue>))
{
Id = id;
TagName = tagName;
Count = count;
Values = values;
CustomInit();
}
<summary>
An initialization method that performs custom operations like setting defaults
</summary>
partial void CustomInit();
<summary>
Gets the tag name ID.
</summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
<summary>
Gets or sets the tag name.
</summary>
[JsonProperty(PropertyName = "tagName")]
public string TagName { get; set; }
<summary>
Gets or sets the total number of resources that use the resource
tag. When a tag is initially created and has no associated
resources, the value is 0.
</summary>
[JsonProperty(PropertyName = "count")]
public TagCount Count { get; set; }
<summary>
Gets or sets the list of tag values.
</summary>
[JsonProperty(PropertyName = "values")]
public IList<TagValue> Values { get; set; }
}
} |
# <API key>: true
module ActiveRecord
module Associations
class SingularAssociation < Association # :nodoc:
# Implements the reader method, e.g. foo.bar for Foo.has_one :bar
def reader
ensure_klass_exists!
if !loaded? || stale_target?
reload
end
target
end
# Implements the writer method, e.g. foo.bar= for Foo.belongs_to :bar
def writer(record)
replace(record)
end
def build(attributes = nil, &block)
record = build_record(attributes, &block)
set_new_record(record)
record
end
# Implements the reload reader method, e.g. foo.reload_bar for
# Foo.has_one :bar
def force_reload_reader
reload(true)
target
end
private
def scope_for_create
super.except!(klass.primary_key)
end
def find_target
if disable_joins
scope.first
else
super.first
end
end
def replace(record)
raise NotImplementedError, "Subclasses must implement a replace(record) method"
end
def set_new_record(record)
replace(record)
end
def _create_record(attributes, raise_error = false, &block)
record = build_record(attributes, &block)
saved = record.save
set_new_record(record)
raise RecordInvalid.new(record) if !saved && raise_error
record
end
end
end
end |
CKEDITOR.plugins.setLang( 'btquicktable', 'sk', {
more: 'Viac...'
} ); |
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <cassert>
#include <stdexcept>
#include <univalue.h>
#define <API key>(a, b)
#define <API key>(funcName) void funcName()
#define <API key>()
#define BOOST_CHECK(expr) assert(expr)
#define BOOST_CHECK_EQUAL(v1, v2) assert((v1) == (v2))
#define BOOST_CHECK_THROW(stmt, excMatch) { \
try { \
(stmt); \
} catch (excMatch & e) { \
} catch (...) { \
assert(0); \
} \
}
#define <API key>(stmt) { \
try { \
(stmt); \
} catch (...) { \
assert(0); \
} \
}
<API key>(univalue_tests, BasicTestingSetup)
<API key>(<API key>)
{
UniValue v1;
BOOST_CHECK(v1.isNull());
UniValue v2(UniValue::VSTR);
BOOST_CHECK(v2.isStr());
UniValue v3(UniValue::VSTR, "foo");
BOOST_CHECK(v3.isStr());
BOOST_CHECK_EQUAL(v3.getValStr(), "foo");
UniValue numTest;
BOOST_CHECK(numTest.setNumStr("82"));
BOOST_CHECK(numTest.isNum());
BOOST_CHECK_EQUAL(numTest.getValStr(), "82");
uint64_t vu64 = 82;
UniValue v4(vu64);
BOOST_CHECK(v4.isNum());
BOOST_CHECK_EQUAL(v4.getValStr(), "82");
int64_t vi64 = -82;
UniValue v5(vi64);
BOOST_CHECK(v5.isNum());
BOOST_CHECK_EQUAL(v5.getValStr(), "-82");
int vi = -688;
UniValue v6(vi);
BOOST_CHECK(v6.isNum());
BOOST_CHECK_EQUAL(v6.getValStr(), "-688");
double vd = -7.21;
UniValue v7(vd);
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
std::string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
const char *vcs = "zappa";
UniValue v9(vcs);
BOOST_CHECK(v9.isStr());
BOOST_CHECK_EQUAL(v9.getValStr(), "zappa");
}
<API key>(univalue_typecheck)
{
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
BOOST_CHECK_THROW(v1.get_bool(), std::runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
BOOST_CHECK_THROW(v2.get_int(), std::runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("<API key>"));
BOOST_CHECK_THROW(v3.get_int64(), std::runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648);
BOOST_CHECK_THROW(v4.get_int(), std::runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
BOOST_CHECK_THROW(v4.get_str(), std::runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
BOOST_CHECK_THROW(v4.get_array(), std::runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error);
BOOST_CHECK_THROW(v4.getValues(), std::runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
<API key>(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
BOOST_CHECK_THROW(vals[0].get_int(), std::runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
BOOST_CHECK_THROW(vals[1].get_bool(), std::runtime_error);
}
<API key>(univalue_set)
{
UniValue v(UniValue::VSTR, "foo");
v.clear();
BOOST_CHECK(v.isNull());
BOOST_CHECK_EQUAL(v.getValStr(), "");
BOOST_CHECK(v.setObject());
BOOST_CHECK(v.isObject());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ);
BOOST_CHECK(v.empty());
BOOST_CHECK(v.setArray());
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK(v.setStr("zum"));
BOOST_CHECK(v.isStr());
BOOST_CHECK_EQUAL(v.getValStr(), "zum");
BOOST_CHECK(v.setFloat(-1.01));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1.01");
BOOST_CHECK(v.setInt((int)1023));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setInt((int64_t)-1023LL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1023");
BOOST_CHECK(v.setInt((uint64_t)1023ULL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setNumStr("-688"));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-688");
BOOST_CHECK(v.setBool(false));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), false);
BOOST_CHECK_EQUAL(v.isFalse(), true);
BOOST_CHECK_EQUAL(v.getBool(), false);
BOOST_CHECK(v.setBool(true));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), true);
BOOST_CHECK_EQUAL(v.isFalse(), false);
BOOST_CHECK_EQUAL(v.getBool(), true);
BOOST_CHECK(!v.setNumStr("zombocom"));
BOOST_CHECK(v.setNull());
BOOST_CHECK(v.isNull());
}
<API key>(univalue_array)
{
UniValue arr(UniValue::VARR);
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
std::string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
std::vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
v.setStr("going");
vec.push_back(v);
BOOST_CHECK(arr.push_backV(vec));
BOOST_CHECK_EQUAL(arr.empty(), false);
BOOST_CHECK_EQUAL(arr.size(), 5);
BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023");
BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy");
BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy");
BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing");
BOOST_CHECK_EQUAL(arr[4].getValStr(), "going");
BOOST_CHECK_EQUAL(arr[999].getValStr(), "");
arr.clear();
BOOST_CHECK(arr.empty());
BOOST_CHECK_EQUAL(arr.size(), 0);
}
<API key>(univalue_object)
{
UniValue obj(UniValue::VOBJ);
std::string strKey, strVal;
UniValue v;
strKey = "age";
v.setInt(100);
BOOST_CHECK(obj.pushKV(strKey, v));
strKey = "first";
strVal = "John";
BOOST_CHECK(obj.pushKV(strKey, strVal));
strKey = "last";
const char *cVal = "Smith";
BOOST_CHECK(obj.pushKV(strKey, cVal));
strKey = "distance";
BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25));
strKey = "time";
BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600));
strKey = "calories";
BOOST_CHECK(obj.pushKV(strKey, (int) 12));
strKey = "temperature";
BOOST_CHECK(obj.pushKV(strKey, (double) 90.012));
UniValue obj2(UniValue::VOBJ);
BOOST_CHECK(obj2.pushKV("cat1", 9000));
BOOST_CHECK(obj2.pushKV("cat2", 12345));
BOOST_CHECK(obj.pushKVs(obj2));
BOOST_CHECK_EQUAL(obj.empty(), false);
BOOST_CHECK_EQUAL(obj.size(), 9);
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100");
BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John");
BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith");
BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25");
BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600");
BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12");
BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012");
BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000");
BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345");
BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), "");
BOOST_CHECK(obj.exists("age"));
BOOST_CHECK(obj.exists("first"));
BOOST_CHECK(obj.exists("last"));
BOOST_CHECK(obj.exists("distance"));
BOOST_CHECK(obj.exists("time"));
BOOST_CHECK(obj.exists("calories"));
BOOST_CHECK(obj.exists("temperature"));
BOOST_CHECK(obj.exists("cat1"));
BOOST_CHECK(obj.exists("cat2"));
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
std::map<std::string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
objTypes["distance"] = UniValue::VNUM;
objTypes["time"] = UniValue::VNUM;
objTypes["calories"] = UniValue::VNUM;
objTypes["temperature"] = UniValue::VNUM;
objTypes["cat1"] = UniValue::VNUM;
objTypes["cat2"] = UniValue::VNUM;
BOOST_CHECK(obj.checkObject(objTypes));
objTypes["cat2"] = UniValue::VSTR;
BOOST_CHECK(!obj.checkObject(objTypes));
obj.clear();
BOOST_CHECK(obj.empty());
BOOST_CHECK_EQUAL(obj.size(), 0);
}
static const char *json1 =
"[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]";
<API key>(univalue_readwrite)
{
UniValue v;
BOOST_CHECK(v.read(json1));
std::string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 2);
BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000");
UniValue obj = v[1];
BOOST_CHECK(obj.isObject());
BOOST_CHECK_EQUAL(obj.size(), 3);
BOOST_CHECK(obj["key1"].isStr());
std::string correctValue("str");
correctValue.push_back('\0');
BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue);
BOOST_CHECK(obj["key2"].isNum());
BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800");
BOOST_CHECK(obj["key3"].isObject());
BOOST_CHECK_EQUAL(strJson1, v.write());
/* Check for (correctly reporting) a parsing error if the initial
JSON construct is followed by more stuff. Note that whitespace
is, of course, exempt. */
BOOST_CHECK(v.read(" {}\n "));
BOOST_CHECK(v.isObject());
BOOST_CHECK(v.read(" []\n "));
BOOST_CHECK(v.isArray());
BOOST_CHECK(!v.read("@{}"));
BOOST_CHECK(!v.read("{} garbage"));
BOOST_CHECK(!v.read("[]{}"));
BOOST_CHECK(!v.read("{}[]"));
BOOST_CHECK(!v.read("{} 42"));
}
<API key>()
int main (int argc, char *argv[])
{
<API key>();
univalue_typecheck();
univalue_set();
univalue_array();
univalue_object();
univalue_readwrite();
return 0;
} |
#import <Foundation/Foundation.h>
@interface NSInvocation (Cedar)
- (void)<API key>;
- (void)<API key>:(id)block;
- (NSArray *)cdr_arguments;
@end |
odoo.define('web_editor.rte', function (require) {
'use strict';
var ajax = require('web.ajax');
var core = require('web.core');
var utils = require('web.utils');
var Widget = require('web.Widget');
var summernote = require('web_editor.summernote');
var base = require('web_editor.base');
var _t = core._t;
/* Summernote Lib (neek change to make accessible: method and object) */
var dom = summernote.core.dom;
var range = summernote.core.range;
/* Change History to have a global History for all summernote instances */
var History = function History ($editable) {
var aUndo = [];
var pos = 0;
this.makeSnap = function (event, rng) {
rng = rng || range.create();
var elEditable = $(rng && rng.sc).closest('.o_editable')[0];
if (!elEditable) {
return false;
}
return {
event: event,
editable: elEditable,
contents: elEditable.innerHTML,
bookmark: rng && rng.bookmark(elEditable),
scrollTop: $(elEditable).scrollTop()
};
};
this.applySnap = function (oSnap) {
var $editable = $(oSnap.editable);
if (!!document.documentMode) {
$editable.removeAttr("contentEditable").removeProp("contentEditable");
}
$editable.html(oSnap.contents).scrollTop(oSnap.scrollTop);
$(".oe_overlay").remove();
$(".<API key>").hide();
$editable.trigger("content_changed");
try {
var r = oSnap.editable.innerHTML === "" ? range.create(oSnap.editable, 0) : range.createFromBookmark(oSnap.editable, oSnap.bookmark);
r.select();
} catch(e) {
console.error(e);
return;
}
$(document).trigger("click");
$(".o_editable *").filter(function () {
var $el = $(this);
if($el.data('snippet-editor')) {
$el.removeData();
}
});
setTimeout(function () {
var target = dom.isBR(r.sc) ? r.sc.parentNode : dom.node(r.sc);
if (!target) {
return;
}
$editable.trigger("applySnap");
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, target);
target.dispatchEvent(evt);
$editable.trigger("keyup");
},0);
};
this.undo = function () {
if (!pos) { return; }
var _toSnap = toSnap;
if (_toSnap) {
this.saveSnap();
}
if (!aUndo[pos] && (!aUndo[pos] || aUndo[pos].event !== 'undo')) {
var temp = this.makeSnap('undo');
if (temp && (!pos || temp.contents !== aUndo[pos-1].contents)) {
aUndo[pos] = temp;
} else {
pos
}
} else if (_toSnap) {
pos
}
this.applySnap(aUndo[Math.max(--pos,0)]);
while (pos && (aUndo[pos].event === "blur" || (aUndo[pos+1].editable === aUndo[pos].editable && aUndo[pos+1].contents === aUndo[pos].contents))) {
this.applySnap(aUndo[--pos]);
}
};
this.hasUndo = function () {
return (toSnap && (toSnap.event !== "blur" && toSnap.event !== "activate" && toSnap.event !== "undo")) ||
!!_.find(aUndo.slice(0, pos+1), function (undo) {
return undo.event !== "blur" && undo.event !== "activate" && undo.event !== "undo";
});
};
this.getEditableHasUndo = function () {
var editable = [];
if ((toSnap && (toSnap.event !== "blur" && toSnap.event !== "activate" && toSnap.event !== "undo"))) {
editable.push(toSnap.editable);
}
_.each(aUndo.slice(0, pos+1), function (undo) {
if (undo.event !== "blur" && undo.event !== "activate" && undo.event !== "undo") {
editable.push(undo.editable);
}
});
return _.uniq(editable);
};
this.redo = function () {
if (!aUndo[pos+1]) { return; }
this.applySnap(aUndo[++pos]);
while (aUndo[pos+1] && aUndo[pos].event === "active") {
this.applySnap(aUndo[pos++]);
}
};
this.hasRedo = function () {
return aUndo.length > pos+1;
};
var toSnap, split;
this.recordUndo = function ($editable, event, internal_history) {
var self = this;
if (!$editable) {
var rng = range.create();
if(!rng) return;
$editable = $(rng.sc).closest(".o_editable");
}
if (aUndo[pos] && (event === "applySnap" || event === "activate")) {
return;
}
if (!internal_history) {
if (!event || !toSnap || !aUndo[pos-1] || toSnap.event === "activate") { // don't trigger change for all keypress
setTimeout(function () {
$editable.trigger("content_changed");
},0);
}
}
if (aUndo[pos]) {
pos = Math.min(pos, aUndo.length);
aUndo.splice(Math.max(pos,1), aUndo.length);
}
// => make a snap when the user change editable zone (because: don't make snap for each keydown)
if (toSnap && (toSnap.split || !event || toSnap.event !== event || toSnap.editable !== $editable[0])) {
this.saveSnap();
}
if (pos && aUndo[pos-1].editable !== $editable[0]) {
var snap = this.makeSnap('blur', range.create(aUndo[pos-1].editable, 0));
pos++;
aUndo.push(snap);
}
if (range.create()) {
toSnap = self.makeSnap(event);
} else {
toSnap = false;
}
};
this.splitNext = function () {
if (toSnap) {
toSnap.split = true;
}
};
this.saveSnap = function () {
if (toSnap) {
if (!aUndo[pos]) {
pos++;
}
aUndo.push(toSnap);
delete toSnap.split;
toSnap = null;
}
};
};
var history = new History();
// add focusIn to jQuery to allow to move caret into a div of a contentEditable area
$.extend($.expr[':'],{
o_editable: function(node,i,m){
while (node) {
if (node.className && _.isString(node.className)) {
if (node.className.indexOf('o_not_editable')!==-1 ) {
return false;
}
if (node.className.indexOf('o_editable')!==-1 ) {
return true;
}
}
node = node.parentNode;
}
return false;
}
});
$.fn.extend({
focusIn: function () {
if (this.length) {
range.create(dom.firstChild(this[0]), 0).select();
}
return this;
},
focusInEnd: function () {
if (this.length) {
var last = dom.lastChild(this[0]);
range.create(last, dom.nodeLength(last)).select();
}
return this;
},
selectContent: function () {
if (this.length) {
var next = dom.lastChild(this[0]);
range.create(dom.firstChild(this[0]), 0, next, next.textContent.length).select();
}
return this;
}
});
var RTE = Widget.extend({
init: function (EditorBar, config) {
var self = this;
this.EditorBar = EditorBar;
data.rte = this;
this._super.apply(this, arguments);
this.<API key> = $.fn.carousel;
this.<API key> = function () {
var res = self.<API key>.apply(this, arguments);
// off bootstrap keydown event to remove event.preventDefault()
// and allow to change cursor position
$(this).off('keydown.bs.carousel');
return res;
};
if (config) {
this.config = config;
}
},
/**
* Add a record undo to history
* @param {DOM} target where the dom is changed is editable zone
*/
historyRecordUndo: function ($target, event, internal_history) {
var rng = range.create();
var $editable = $(rng && rng.sc).closest(".o_editable");
if (!rng || !$editable.length) {
$editable = $($target).closest(".o_editable");
rng = range.create($target.closest("*")[0],0);
} else {
rng = $editable.data('range') || rng;
}
rng.select();
history.recordUndo($editable, event, internal_history);
},
/**
* Makes the page editable
*
* @param {Boolean} [restart=false] in case the edition was already set
* up once and is being re-enabled.
* @returns {$.Deferred} deferred indicating when the RTE is ready
*/
start: function () {
var self = this;
this.saving_mutex = new utils.Mutex();
$.fn.carousel = this.<API key>;
this._onKeydown = _.bind(this.onKeydown, this);
$(document).on('keydown', this, this._onKeydown);
this._onMousedown = _.bind(this.onMousedown, this);
$(document).on('mousedown activate', this, this._onMousedown);
this._onMouseup = _.bind(this.onMouseup, this);
$(document).on('mouseup', this, this._onMouseup);
$('.o_not_editable').attr("contentEditable", false);
var $editable = this.editable();
$editable.addClass('o_editable').data('rte', self);
$editable.each(function () {
var $node = $(this);
// add class to display inline-block for empty t-field
if(window.getComputedStyle(this).display === "inline" && $node.data('oe-type') !== "image") {
$node.addClass('<API key>');
}
$node.data('initInnerHTML', $node.html());
});
// start element observation
$(document).on('content_changed', '.o_editable', function (event) {
self.trigger('change', this);
if(!$(this).hasClass('o_dirty')) {
$(this).addClass('o_dirty');
}
});
this._onClick = _.bind(this.onClick, this);
$('#wrapwrap, .o_editable').on('click', '*', this, this._onClick);
$('body').addClass("editor_enable");
$(document)
.tooltip({
selector: '[data-oe-readonly]',
container: 'body',
trigger: 'hover',
delay: { "show": 1000, "hide": 100 },
placement: 'bottom',
title: _t("Readonly field")
})
.on('click', function () {
$(this).tooltip('hide');
});
$(document).trigger('mousedown');
self.trigger('rte:start');
},
save: function (context) {
var self = this;
this.__saved = {}; // list of allready saved views and data
var editables = history.getEditableHasUndo();
var defs = $('.o_dirty')
.removeAttr('contentEditable')
.removeClass('o_dirty oe_carlos_danger <API key>')
.map(function () {
var $el = $(this);
$el.find('[class]').filter(function () {
if (!this.className.match(/\S/)) {
this.removeAttribute("class");
}
});
// TODO: Add a queue with concurrency limit in webclient
return self.saving_mutex.exec(function () {
return self.saveElement($el, context)
.then(undefined, function (thing, response) {
// because ckeditor regenerates all the dom,
// we can't just setup the popover here as
// everything will be destroyed by the DOM
// regeneration. Add markings instead, and
// returns a new rejection with all relevant
// info
var id = _.uniqueId('carlos_danger_');
$el.addClass('o_dirty oe_carlos_danger ' + id);
return $.Deferred().reject({
id: id,
error: response.data,
});
});
});
}).get();
return $.when.apply(null, defs).then(function () {
window.onbeforeunload = null;
}, function (failed) {
// If there were errors, re-enable edition
self.stop();
self.start();
// jquery's deferred being a pain in the ass
if (!_.isArray(failed)) { failed = [failed]; }
_(failed).each(function (failure) {
var html = failure.error.exception_type === "except_osv";
if (html) {
var msg = $("<div/>").text(failure.error.message).html();
var data = msg.substring(3,msg.length-2).split(/', u'/);
failure.error.message = '<b>' + data[0] + '</b>' + data[1];
}
$('.o_editable.' + failure.id)
.removeClass(failure.id)
.popover({
html: html,
trigger: 'hover',
content: failure.error.message,
placement: 'auto top',
})
// Force-show popovers so users will notice them.
.popover('show');
});
});
},
/**
* Get HTML cloned element with text nodes escaped for XML storage
*/
getEscapedElement: function($el) {
var escaped_el = $el.clone();
var to_escape = escaped_el.find('*').addBack();
to_escape = to_escape.not(to_escape.filter('object,iframe,script,style,[data-oe-model][data-oe-model!="ir.ui.view"]').find('*').addBack());
to_escape.contents().each(function(){
if(this.nodeType == 3) {
this.nodeValue = $('<div />').text(this.nodeValue).html();
}
});
return escaped_el;
},
saveElement: function ($el, context) {
// remove multi edition
if ($el.data('oe-model')) {
var key = $el.data('oe-model')+":"+$el.data('oe-id')+":"+$el.data('oe-field')+":"+$el.data('oe-type')+":"+$el.data('oe-expression');
if (this.__saved[key]) return true;
this.__saved[key] = true;
}
var markup = this.getEscapedElement($el).prop('outerHTML');
return ajax.jsonRpc('/web/dataset/call', 'call', {
model: 'ir.ui.view',
method: 'save',
args: [
$el.data('oe-id'),
markup,
$el.data('oe-xpath') || null,
_.omit(context || base.get_context(), 'lang')
],
});
},
stop: function () {
if (this.$last) {
this.$last.destroy();
this.$last = null;
}
$.fn.carousel = this.<API key>;
$(document).off('keydown', this._onKeydown);
$(document).off('mousedown applySnap', this._onMousedown);
$(document).off('mouseup', this._onMouseup);
$('.o_not_editable').removeAttr("contentEditable");
$(document).off('content_changed').removeClass('<API key>').removeData('rte');
$('#wrapwrap, .o_editable').off('click', this._onClick);
$(document).tooltip('destroy');
$('body').removeClass("editor_enable");
this.trigger('rte:stop');
},
cancel: function () {
$('.o_editable').each(function () {
var $node = $(this);
$node.data('initInnerHTML', $node.html());
});
this.stop();
},
onClick: function (event) {
event.preventDefault();
},
// handler for cancel editor
onKeydown: function (event) {
if (event.keyCode === 27 && !$('.modal-content:visible').length) {
setTimeout(function () {
$('#editor-top-navbar [data-action="cancel"]').click();
var $modal = $('.modal-content > .modal-body').parents(".modal:first");
$modal.off('keyup.dismiss.bs.modal');
setTimeout(function () {
$modal.on('keyup.dismiss.bs.modal', function () {
$(this).modal('hide');
});
},500);
},0);
}
},
// activate editor
onMousedown: function (event) {
var $target = $(event.target);
var $editable = $target.closest('.o_editable');
if (!$editable.size()) {
return;
}
if ($target.is('a')) {
// add contenteditable on link to improve its editing behaviour
$target.attr('contenteditable', true);
setTimeout(function () {
$editable.attr('contenteditable', false);
});
// once clicked outside, remove contenteditable on link
var reactive_editable = function(e){
if($target.is(e.target)) {
return;
}
$target.removeAttr('contenteditable');
$editable.attr('contenteditable', true);
$(document).off('mousedown', reactive_editable);
}
$(document).on('mousedown', reactive_editable);
}
if (this && this.$last && (!$editable.size() || this.$last[0] != $editable[0])) {
var $destroy = this.$last;
history.splitNext();
setTimeout(function () {
var id = $destroy.data('note-id');
$destroy.destroy().removeData('note-id').removeAttr('data-note-id');
$('#note-popover-'+id+', #note-handle-'+id+', #note-dialog-'+id+'').remove();
},150); // setTimeout to remove flickering when change to editable zone (re-create an editor)
this.$last = null;
}
if ($editable.size() && (!this.$last || this.$last[0] != $editable[0]) &&
($target.closest('[contenteditable]').attr('contenteditable') || "").toLowerCase() !== 'false') {
$editable.summernote(this.config($editable));
$editable.data('NoteHistory', history);
this.$last = $editable;
// firefox & IE fix
try {
document.execCommand('<API key>', false, false);
document.execCommand('<API key>', false, false);
document.execCommand( '2D-position', false, false);
} catch (e) {}
document.body.addEventListener('resizestart', function (evt) {evt.preventDefault(); return false;});
document.body.addEventListener('movestart', function (evt) {evt.preventDefault(); return false;});
document.body.addEventListener('dragstart', function (evt) {evt.preventDefault(); return false;});
if (!range.create()) {
$editable.focusIn();
}
if (dom.isImg($target[0])) {
$target.trigger('mousedown'); // for activate selection on picture
}
this.<API key>($editable);
}
},
<API key>: function ($editable) {
},
onMouseup: function (event) {
var $target = $(event.target);
var $editable = $target.closest('.o_editable');
if (!$editable.size()) {
return;
}
var self = this;
setTimeout(function () {
self.historyRecordUndo($target, 'activate', true);
},0);
},
editable: function () {
return $('#wrapwrap [data-oe-model]')
.not('.o_not_editable')
.filter(function () {
return !$(this).closest('.o_not_editable').length;
})
.not('link, script')
.not('[data-oe-readonly]')
.not('img[data-oe-field="arch"], br[data-oe-field="arch"], input[data-oe-field="arch"]')
.not('.oe_snippet_editor')
.add('.o_editable');
},
config: function ($editable) {
return {
'airMode' : true,
'focus': false,
'airPopover': [
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture']],
['history', ['undo', 'redo']],
],
'styleWithSpan': false,
'inlinemedia' : ['p'],
'lang': "odoo",
'onChange': function (html, $editable) {
$editable.trigger("content_changed");
}
};
},
});
var data = {
'history': history,
'Class': RTE
};
return data;
}); |
export * from './src/api';
export {NOOP_PERF_RECORDER} from './src/noop';
export {ActivePerfRecorder, <API key>} from './src/recorder'; |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\Post */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="post-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'content', [
'template' => '{input}{error}{hint}'
])->widget('shiyang\umeditor\UMeditor', [
'clientOptions' => [
'initialFrameHeight' => 100,
'toolbar' => [
'source | undo redo | bold |',
'link unlink | emotion image video |',
'justifyleft justifycenter justifyright justifyjustify |',
'insertorderedlist insertunorderedlist |' ,
'horizontal preview fullscreen',
],
]
])->label(false) ?>
<?= $form->field($model, 'tags')->textarea(['rows' => 2]) ?>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'created_at')->textInput() ?>
<?= $form->field($model, 'updated_at')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div> |
'use strict';
var $interpolateMinErr = minErr('$interpolate');
/**
* @ngdoc provider
* @name $interpolateProvider
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<example module="<API key>">
<file name="index.html">
<script>
var <API key> = angular.module('<API key>', []);
<API key>.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
<API key>.controller('DemoController', function() {
this.label = "This binding is brought you by // interpolation symbols.";
});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
//demo.label//
</div>
</file>
<file name="protractor.js" type="protractor">
it('should interpolate binding with custom symbols', function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
});
</file>
</example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name $interpolateProvider#startSymbol
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value) {
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name $interpolateProvider#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value) {
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length,
escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
function escape(ch) {
return '\\\\\\' + ch;
}
function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
allOrNothing = !!allOrNothing;
var startIndex,
endIndex,
index = 0,
expressions = [],
parseFns = [],
textLength = text.length,
exp,
concat = [],
expressionPositions = [];
while (index < textLength) {
if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
if (index !== startIndex) {
concat.push(unescapeText(text.substring(index, startIndex)));
}
exp = text.substring(startIndex + startSymbolLength, endIndex);
expressions.push(exp);
parseFns.push($parse(exp, <API key>));
index = endIndex + endSymbolLength;
expressionPositions.push(concat.length);
concat.push('');
} else {
// we did not find an interpolation, so we have to add the remainder to the separators array
if (index !== textLength) {
concat.push(unescapeText(text.substring(index)));
}
break;
}
}
// Concatenating expressions makes it hard to reason about whether some combination of
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
// single expression be used for iframe[src], object[src], etc., we ensure that the value
// that's used is assigned or constructed by some JS code somewhere that is more testable or
// make it obvious that you bound the value to some user controlled value. This helps reduce
// the load when auditing for XSS issues.
if (trustedContext && concat.length > 1) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
}
if (!mustHaveExpression || expressions.length) {
var compute = function(values) {
for (var i = 0, ii = expressions.length; i < ii; i++) {
if (allOrNothing && isUndefined(values[i])) return;
concat[expressionPositions[i]] = values[i];
}
return concat.join('');
};
var getValue = function(value) {
return trustedContext ?
$sce.getTrusted(trustedContext, value) :
$sce.valueOf(value);
};
var stringify = function(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
value = toJson(value);
}
return value;
};
return extend(function interpolationFn(context) {
var i = 0;
var ii = expressions.length;
var values = new Array(ii);
try {
for (; i < ii; i++) {
values[i] = parseFns[i](context);
}
return compute(values);
} catch (err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
err.toString());
$exceptionHandler(newErr);
}
}, {
// all of these properties are undocumented for now
exp: text, //just for compatibility with regular watchers created via $watch
expressions: expressions,
$$watchDelegate: function(scope, listener, objectEquality) {
var lastValue;
return scope.$watchGroup(parseFns, function <API key>(values, oldValues) {
var currValue = compute(values);
if (isFunction(listener)) {
listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
}
lastValue = currValue;
}, objectEquality);
}
});
}
function unescapeText(text) {
return text.replace(escapedStartRegexp, startSymbol).
replace(escapedEndRegexp, endSymbol);
}
function <API key>(value) {
try {
return stringify(getValue(value));
} catch (err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
err.toString());
$exceptionHandler(newErr);
}
}
}
/**
* @ngdoc method
* @name $interpolate#startSymbol
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
};
/**
* @ngdoc method
* @name $interpolate#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
* the symbol.
*
* @returns {string} end symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
};
return $interpolate;
}];
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.