answer
stringlengths 15
1.25M
|
|---|
package com.github.dandelion.gua.core.field;
public enum EventTrackingField implements AnalyticsField, <API key> {
@<API key>(<API key>.Policy.TEXT) eventCategory,
@<API key>(<API key>.Policy.TEXT) eventAction,
@<API key>(<API key>.Policy.TEXT) eventLabel,
@<API key>(<API key>.Policy.INTEGER) eventValue,
}
|
package edu.wustl.cab2b.server.analyticalservice;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.common.analyticalservice.<API key>;
import edu.wustl.cab2b.common.exception.RuntimeException;
/**
* This is a singleton class which parses the <API key>.xml file and stores the mapping information into an internal map.
* This class provieds the methods to get the service interface and the service invoker interface.
* @author chetan_patil
*/
public class <API key> {
/**
* Self reference
*/
private static <API key> entityServiceMapper = null;
/**
* Map to store the entity to service mapping
*/
private Map<String, List<String>> <API key> = new HashMap<String, List<String>>();
/**
* Map to store the service to method mapping
*/
private Map<String, List<String>> <API key> = new HashMap<String, List<String>>();
/**
* Map to store the service detail class and the corresponding service invoker class.
*/
private Map<String, String> <API key> = new HashMap<String, String>();
/**
* Name of the Entity Service Mapper file
*/
private static final String <API key> = "<API key>.xml";
/**
* Entity tag
*/
private static final String ENTITY = "entity";
/**
* Service tag
*/
private static final String SERVICE = "service";
/**
* Method tag
*/
private static final String METHOD = "method";
/**
* Name attribute
*/
private static final String ATTRIBUTE_NAME = "name";
/**
* Service Detail Class attribute
*/
private static final String <API key> = "serviceDetailClass";
/**
* Service Invoker Class attribute
*/
private static final String <API key> = "serviceInvokerClass";
/**
* Service name attribute
*/
private static final String <API key> = "serviceName";
/**
* Private constructor
*/
private <API key>() {
<API key>();
}
/**
* This method returns an instance of this class
* @return an instance of this class
*/
public static synchronized <API key> getInstance() {
if (entityServiceMapper == null) {
entityServiceMapper = new <API key>();
}
return entityServiceMapper;
}
/**
* This method parses the EntityServiceMapper.XML file and stores the parsed data into an internally maintained Maps.
*/
private void <API key>() {
//Read the xml file
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(
<API key>);
if (inputStream == null) {
throw new RuntimeException("File not found: " + <API key>);
}
//Parse xml into the Document
Document document = null;
try {
document = new SAXReader().read(inputStream);
} catch (DocumentException e) {
throw new RuntimeException("Unable to parse XML file: " + <API key>, e);
}
//Traverse and fetch the data from the Document
Element <API key> = document.getRootElement();
if (<API key> != null) {
List<Element> serviceElementList = <API key>.elements(SERVICE);
if (serviceElementList == null || serviceElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Service entries not found.");
}
<API key>(serviceElementList);
List<Element> entityElementList = <API key>.elements(ENTITY);
if (entityElementList == null || entityElementList.isEmpty()) {
throw new RuntimeException("Invalid XML file: Entity entries not found.");
}
<API key>(entityElementList);
} else {
throw new RuntimeException("Invalid XML file: Root element not found.");
}
}
/**
* This method stores the data of all the service tags into serviceMethodMap
* @param serviceElementList the root element of the XML document
*/
private void <API key>(List<Element> serviceElementList) {
for (Element serviceElement : serviceElementList) {
List<String> <API key> = new ArrayList<String>();
List<Element> methodElementList = serviceElement.elements(METHOD);
for (Element methodElement : methodElementList) {
String <API key> = methodElement.attributeValue(<API key>);
String <API key> = methodElement.attributeValue(<API key>);
if (!<API key>.contains(<API key>)) {
<API key>.add(<API key>);
}
if (<API key>.get(<API key>) == null) {
<API key>.put(<API key>, <API key>);
}
}
String serviceName = serviceElement.attributeValue(ATTRIBUTE_NAME);
if (<API key>.get(serviceName) == null) {
<API key>.put(serviceName, <API key>);
}
}
}
/**
* This method stores the data of all the entity tags into entityServiceMap
* @param entityElementList the root element of the XML document
*/
private void <API key>(List<Element> entityElementList) {
for (Element entityElement : entityElementList) {
String entityName = entityElement.attributeValue(ATTRIBUTE_NAME);
String serviceName = entityElement.attributeValue(<API key>);
List<String> serviceList = <API key>.get(entityName);
if (serviceList == null) {
serviceList = new ArrayList<String>();
<API key>.put(entityName, serviceList);
}
serviceList.add(serviceName);
}
}
/**
* This method returns the instance given the respective class name.
* @param className name of the class
* @return an instance of the given class name
*/
private <E> E getInstance(String className, Class<E> clazz) {
Object instance = null;
try {
Class classDefinition = Class.forName(className);
instance = classDefinition.newInstance();
} catch (<API key> e) {
} catch (<API key> e) {
} catch (<API key> e) {
}
Class<?> instanceClass = instance.getClass();
if (!clazz.isAssignableFrom(instanceClass)) {
throw new RuntimeException(instanceClass.getName() + " does not implement the interface "
+ clazz.getName());
}
return (E) instance;
}
/**
* This method returns the List of the service names of the respective givne entity name.
* @param entityName the name of the entity
* @return the List of the service names
*/
private List<String> <API key>(String entityName) {
List<String> <API key> = new ArrayList<String>();
List<String> serviceNameList = <API key>.get(entityName);
if (serviceNameList != null) {
for (String serviceName : serviceNameList) {
List<String> <API key> = <API key>.get(serviceName);
if (<API key> != null) {
<API key>.addAll(<API key>);
}
}
}
return <API key>;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
/**
* Clones this object
* @return Cloned object
* @throws <API key>
*/
public Object clone() throws <API key> {
throw new <API key>();
}
/**
* This method returns the List of all the corresponding ServiceDetailsClass given the Entity.
* @param entity an instance of Entity
* @return List of all the ServiceDetailClass corresponding to the given Entity
*/
public List<<API key>> getServices(EntityInterface entity) {
List<<API key>> <API key> = new ArrayList<<API key>>();
List<String> <API key> = <API key>(entity.getName());
//TODO This is a hack. To be deleted after testing.
//List<String> <API key> = <API key>("gov.nih.nci.mageom.domain.BioAssay.BioAssay");
for (String <API key> : <API key>) {
<API key> serviceDetails = getInstance(<API key>,
<API key>.class);
<API key>.add(serviceDetails);
}
return <API key>;
}
/**
* This method returns an instance of the Service Invoker Class given the respective Service Details Class.
* @param serviceDetails the instance of the Service Details class
* @return an instance of the Service Invoker Class
*/
public <API key> getServiceInvoker(<API key> serviceDetails) {
String <API key> = serviceDetails.getClass().getName();
String <API key> = <API key>.get(<API key>);
<API key> serviceInvoker = null;
if (<API key> != null) {
serviceInvoker = getInstance(<API key>, <API key>.class);
}
return serviceInvoker;
}
// public static void main(String[] args) {
// EntityInterface entity = new Entity();
// entity.setName("Entity1");
// <API key> entityServiceMapper = <API key>.getInstance();
// List<<API key>> serviceList = entityServiceMapper.getServices(entity);
// <API key> serviceInvoker1 = entityServiceMapper.getServiceInvoker(serviceList.get(0));
// <API key> serviceInvoker2 = entityServiceMapper.getServiceInvoker(serviceList.get(1));
}
|
package com.jtex.plot;
/**
*
* @author hios
*/
public interface ScatterCanvas {
public ScatterOptions getScatterOptions();
public void setScatterOptions(ScatterOptions options);
}
|
/* $NetBSD: rpc_soc.c,v 1.6 2000/07/06 03:10:35 christos Exp $ */
/* #ident "@(#)rpc_soc.c 1.17 94/04/24 SMI" */
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)rpc_soc.c 1.41 89/05/02 Copyr 1988 Sun Micro";
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#ifdef PORTMAP
/*
* rpc_soc.c
*
* The backward compatibility routines for the earlier implementation
* of RPC, where the only transports supported were tcp/ip and udp/ip.
* Based on berkeley socket abstraction, now implemented on the top
* of TLI/Streams
*/
#include "namespace.h"
#include "reentrant.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include <rpc/pmap_prot.h>
#include <rpc/nettype.h>
#include <syslog.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "un-namespace.h"
#include "rpc_com.h"
#include "mt_misc.h"
static CLIENT *clnt_com_create(struct sockaddr_in *, rpcprog_t, rpcvers_t,
int *, u_int, u_int, char *);
static SVCXPRT *svc_com_create(int, u_int, u_int, char *);
static bool_t rpc_wrap_bcast(char *, struct netbuf *, struct netconfig *);
/* XXX */
#define <API key> "127.0.0.1"
#define <API key> "::1"
/*
* A common clnt create routine
*/
static CLIENT *
clnt_com_create(raddr, prog, vers, sockp, sendsz, recvsz, tp)
struct sockaddr_in *raddr;
rpcprog_t prog;
rpcvers_t vers;
int *sockp;
u_int sendsz;
u_int recvsz;
char *tp;
{
CLIENT *cl;
int madefd = FALSE;
int fd = *sockp;
struct netconfig *nconf;
struct netbuf bindaddr;
mutex_lock(&rpcsoc_lock);
if ((nconf = __rpc_getconfip(tp)) == NULL) {
rpc_createerr.cf_stat = RPC_UNKNOWNPROTO;
mutex_unlock(&rpcsoc_lock);
return (NULL);
}
if (fd == RPC_ANYSOCK) {
fd = __rpc_nconf2fd(nconf);
if (fd == -1)
goto syserror;
madefd = TRUE;
}
if (raddr->sin_port == 0) {
u_int proto;
u_short sport;
mutex_unlock(&rpcsoc_lock); /* pmap_getport is recursive */
proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP;
sport = pmap_getport(raddr, (u_long)prog, (u_long)vers,
proto);
if (sport == 0) {
goto err;
}
raddr->sin_port = htons(sport);
mutex_lock(&rpcsoc_lock); /* pmap_getport is recursive */
}
/* Transform sockaddr_in to netbuf */
bindaddr.maxlen = bindaddr.len = sizeof (struct sockaddr_in);
bindaddr.buf = raddr;
bindresvport(fd, NULL);
cl = clnt_tli_create(fd, nconf, &bindaddr, prog, vers,
sendsz, recvsz);
if (cl) {
if (madefd == TRUE) {
/*
* The fd should be closed while destroying the handle.
*/
(void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL);
*sockp = fd;
}
(void) freenetconfigent(nconf);
mutex_unlock(&rpcsoc_lock);
return (cl);
}
goto err;
syserror:
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
err: if (madefd == TRUE)
(void)_close(fd);
(void) freenetconfigent(nconf);
mutex_unlock(&rpcsoc_lock);
return (NULL);
}
CLIENT *
clntudp_bufcreate(raddr, prog, vers, wait, sockp, sendsz, recvsz)
struct sockaddr_in *raddr;
u_long prog;
u_long vers;
struct timeval wait;
int *sockp;
u_int sendsz;
u_int recvsz;
{
CLIENT *cl;
cl = clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
sendsz, recvsz, "udp");
if (cl == NULL) {
return (NULL);
}
(void) CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait);
return (cl);
}
CLIENT *
clntudp_create(raddr, program, version, wait, sockp)
struct sockaddr_in *raddr;
u_long program;
u_long version;
struct timeval wait;
int *sockp;
{
return clntudp_bufcreate(raddr, program, version, wait, sockp,
UDPMSGSIZE, UDPMSGSIZE);
}
CLIENT *
clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz)
struct sockaddr_in *raddr;
u_long prog;
u_long vers;
int *sockp;
u_int sendsz;
u_int recvsz;
{
return clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp,
sendsz, recvsz, "tcp");
}
CLIENT *
clntraw_create(prog, vers)
u_long prog;
u_long vers;
{
return clnt_raw_create((rpcprog_t)prog, (rpcvers_t)vers);
}
/*
* A common server create routine
*/
static SVCXPRT *
svc_com_create(fd, sendsize, recvsize, netid)
int fd;
u_int sendsize;
u_int recvsize;
char *netid;
{
struct netconfig *nconf;
SVCXPRT *svc;
int madefd = FALSE;
int port;
struct sockaddr_in sin;
if ((nconf = __rpc_getconfip(netid)) == NULL) {
(void) syslog(LOG_ERR, "Could not get %s transport", netid);
return (NULL);
}
if (fd == RPC_ANYSOCK) {
fd = __rpc_nconf2fd(nconf);
if (fd == -1) {
(void) freenetconfigent(nconf);
(void) syslog(LOG_ERR,
"svc%s_create: could not open connection", netid);
return (NULL);
}
madefd = TRUE;
}
memset(&sin, 0, sizeof sin);
sin.sin_family = AF_INET;
bindresvport(fd, &sin);
_listen(fd, SOMAXCONN);
svc = svc_tli_create(fd, nconf, NULL, sendsize, recvsize);
(void) freenetconfigent(nconf);
if (svc == NULL) {
if (madefd)
(void)_close(fd);
return (NULL);
}
port = (((struct sockaddr_in *)svc->xp_ltaddr.buf)->sin_port);
svc->xp_port = ntohs(port);
return (svc);
}
SVCXPRT *
svctcp_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return svc_com_create(fd, sendsize, recvsize, "tcp");
}
SVCXPRT *
svcudp_bufcreate(fd, sendsz, recvsz)
int fd;
u_int sendsz, recvsz;
{
return svc_com_create(fd, sendsz, recvsz, "udp");
}
SVCXPRT *
svcfd_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return svc_fd_create(fd, sendsize, recvsize);
}
SVCXPRT *
svcudp_create(fd)
int fd;
{
return svc_com_create(fd, UDPMSGSIZE, UDPMSGSIZE, "udp");
}
SVCXPRT *
svcraw_create()
{
return svc_raw_create();
}
int
get_myaddress(addr)
struct sockaddr_in *addr;
{
memset((void *) addr, 0, sizeof(*addr));
addr->sin_family = AF_INET;
addr->sin_port = htons(PMAPPORT);
addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
return (0);
}
/*
* For connectionless "udp" transport. Obsoleted by rpc_call().
*/
int
callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out)
const char *host;
int prognum, versnum, procnum;
xdrproc_t inproc, outproc;
void *in, *out;
{
return (int)rpc_call(host, (rpcprog_t)prognum, (rpcvers_t)versnum,
(rpcproc_t)procnum, inproc, in, outproc, out, "udp");
}
/*
* For connectionless kind of transport. Obsoleted by rpc_reg()
*/
int
registerrpc(prognum, versnum, procnum, progname, inproc, outproc)
int prognum, versnum, procnum;
char *(*progname)(char [UDPMSGSIZE]);
xdrproc_t inproc, outproc;
{
return rpc_reg((rpcprog_t)prognum, (rpcvers_t)versnum,
(rpcproc_t)procnum, progname, inproc, outproc, "udp");
}
/*
* All the following clnt_broadcast stuff is convulated; it supports
* the earlier calling style of the callback function
*/
static thread_key_t clnt_broadcast_key;
static resultproc_t <API key>;
static once_t clnt_broadcast_once = ONCE_INITIALIZER;
static void
<API key>(void)
{
thr_keycreate(&clnt_broadcast_key, free);
}
/*
* Need to translate the netbuf address into sockaddr_in address.
* Dont care about netid here.
*/
/* ARGSUSED */
static bool_t
rpc_wrap_bcast(resultp, addr, nconf)
char *resultp; /* results of the call */
struct netbuf *addr; /* address of the guy who responded */
struct netconfig *nconf; /* Netconf of the transport */
{
resultproc_t <API key>;
if (strcmp(nconf->nc_netid, "udp"))
return (FALSE);
if (thr_main())
<API key> = <API key>;
else
<API key> = (resultproc_t)thr_getspecific(clnt_broadcast_key);
return (*<API key>)(resultp,
(struct sockaddr_in *)addr->buf);
}
/*
* Broadcasts on UDP transport. Obsoleted by rpc_broadcast().
*/
enum clnt_stat
clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult)
u_long prog; /* program number */
u_long vers; /* version number */
u_long proc; /* procedure number */
xdrproc_t xargs; /* xdr routine for args */
void *argsp; /* pointer to args */
xdrproc_t xresults; /* xdr routine for results */
void *resultsp; /* pointer to results */
resultproc_t eachresult; /* call with each result obtained */
{
if (thr_main())
<API key> = eachresult;
else {
thr_once(&clnt_broadcast_once, <API key>);
thr_setspecific(clnt_broadcast_key, (void *) eachresult);
}
return rpc_broadcast((rpcprog_t)prog, (rpcvers_t)vers,
(rpcproc_t)proc, xargs, argsp, xresults, resultsp,
(resultproc_t) rpc_wrap_bcast, "udp");
}
/*
* Create the client des authentication object. Obsoleted by
* authdes_seccreate().
*/
AUTH *
authdes_create(servername, window, syncaddr, ckey)
char *servername; /* network name of server */
u_int window; /* time to live */
struct sockaddr *syncaddr; /* optional hostaddr to sync with */
des_block *ckey; /* optional conversation key to use */
{
AUTH *dummy;
AUTH *nauth;
char hostname[NI_MAXHOST];
if (syncaddr) {
/*
* Change addr to hostname, because that is the way
* new interface takes it.
*/
if (getnameinfo(syncaddr, syncaddr->sa_len, hostname,
sizeof hostname, NULL, 0, 0) != 0)
goto fallback;
n<API key>(servername, window, hostname, ckey);
return (nauth);
}
fallback:
dummy = authdes_seccreate(servername, window, NULL, ckey);
return (dummy);
}
/*
* Create a client handle for a unix connection. Obsoleted by clnt_vc_create()
*/
CLIENT *
clntunix_create(raddr, prog, vers, sockp, sendsz, recvsz)
struct sockaddr_un *raddr;
u_long prog;
u_long vers;
int *sockp;
u_int sendsz;
u_int recvsz;
{
struct netbuf *svcaddr;
struct netconfig *nconf;
CLIENT *cl;
int len;
cl = NULL;
nconf = NULL;
svcaddr = NULL;
if ((raddr->sun_len == 0) ||
((svcaddr = malloc(sizeof(struct netbuf))) == NULL ) ||
((svcaddr->buf = malloc(sizeof(struct sockaddr_un))) == NULL)) {
if (svcaddr != NULL)
free(svcaddr);
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
return(cl);
}
if (*sockp < 0) {
*sockp = _socket(AF_LOCAL, SOCK_STREAM, 0);
len = raddr->sun_len = SUN_LEN(raddr);
if ((*sockp < 0) || (_connect(*sockp,
(struct sockaddr *)raddr, len) < 0)) {
rpc_createerr.cf_stat = RPC_SYSTEMERROR;
rpc_createerr.cf_error.re_errno = errno;
if (*sockp != -1)
(void)_close(*sockp);
goto done;
}
}
svcaddr->buf = raddr;
svcaddr->len = raddr->sun_len;
svcaddr->maxlen = sizeof (struct sockaddr_un);
cl = clnt_vc_create(*sockp, svcaddr, prog,
vers, sendsz, recvsz);
done:
free(svcaddr->buf);
free(svcaddr);
return(cl);
}
/*
* Creates, registers, and returns a (rpc) unix based transporter.
* Obsoleted by svc_vc_create().
*/
SVCXPRT *
svcunix_create(sock, sendsize, recvsize, path)
int sock;
u_int sendsize;
u_int recvsize;
char *path;
{
struct netconfig *nconf;
void *localhandle;
struct sockaddr_un sun;
struct sockaddr *sa;
struct t_bind taddr;
SVCXPRT *xprt;
int addrlen;
xprt = (SVCXPRT *)NULL;
localhandle = setnetconfig();
while ((nconf = getnetconfig(localhandle)) != NULL) {
if (nconf->nc_protofmly != NULL &&
strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0)
break;
}
if (nconf == NULL)
return(xprt);
if ((sock = __rpc_nconf2fd(nconf)) < 0)
goto done;
memset(&sun, 0, sizeof sun);
sun.sun_family = AF_LOCAL;
if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
sizeof(sun.sun_path))
goto done;
sun.sun_len = SUN_LEN(&sun);
addrlen = sizeof (struct sockaddr_un);
sa = (struct sockaddr *)&sun;
if (_bind(sock, sa, addrlen) < 0)
goto done;
taddr.addr.len = taddr.addr.maxlen = addrlen;
taddr.addr.buf = malloc(addrlen);
if (taddr.addr.buf == NULL)
goto done;
memcpy(taddr.addr.buf, sa, addrlen);
if (nconf->nc_semantics != NC_TPI_CLTS) {
if (_listen(sock, SOMAXCONN) < 0) {
free(taddr.addr.buf);
goto done;
}
}
xprt = (SVCXPRT *)svc_tli_create(sock, nconf, &taddr, sendsize, recvsize);
done:
endnetconfig(localhandle);
return(xprt);
}
/*
* Like svunix_create(), except the routine takes any *open* UNIX file
* descriptor as its first input. Obsoleted by svc_fd_create();
*/
SVCXPRT *
svcunixfd_create(fd, sendsize, recvsize)
int fd;
u_int sendsize;
u_int recvsize;
{
return (svc_fd_create(fd, sendsize, recvsize));
}
#endif /* PORTMAP */
|
#ifndef _LOGGER_H
#define _LOGGER_H
void logmsg(const char* message, ...);
#endif // _LOGGER_H
|
<?php
namespace osCommerce\OM\Core\Site\Website\SQL\Partner;
use osCommerce\OM\Core\Registry;
class GetCategories
{
public static function execute(array $data): array
{
$OSCOM_PDO = Registry::get('PDO');
if (isset($data['language_id'])) {
$sql = <<<EOD
select
coalesce(lang_user.title, lang_en.title) as title,
c.code
from
:<API key> c
left join
:<API key> lang_user
on
(c.id = lang_user.id and lang_user.languages_id = :languages_id)
left join
:<API key> lang_en
on
(c.id = lang_en.id and lang_en.languages_id = :default_language_id),
:<API key> t,
:<API key> p
left join
:<API key> pi_lang_user
on
(p.id = pi_lang_user.partner_id and pi_lang_user.languages_id = :languages_id)
left join
:<API key> pi_lang_en
on
(p.id = pi_lang_en.partner_id and pi_lang_en.languages_id = :default_language_id),
:<API key> pp
where
t.date_start <= now() and
t.date_end >= now() and
t.package_id = pp.id and
pp.status = 1 and
t.partner_id = p.id and
p.category_id = c.id and
coalesce(pi_lang_user.image_small, pi_lang_en.image_small) != '' and
coalesce(pi_lang_user.desc_short, pi_lang_en.desc_short) != '' and
coalesce(pi_lang_user.desc_long, pi_lang_en.desc_long) != ''
group by
c.id
order by
c.sort_order,
title
EOD;
} else {
$sql = <<<EOD
select
cl.title,
c.code
from
:<API key> c,
:<API key> cl,
:<API key> t,
:<API key> p,
:<API key> pi,
:<API key> pp
where
t.date_start <= now() and
t.date_end >= now() and
t.package_id = pp.id and
pp.status = 1 and
t.partner_id = p.id and
p.category_id = c.id and
c.id = cl.id and
cl.languages_id = :default_language_id and
p.id = pi.partner_id and
pi.languages_id = cl.languages_id and
pi.image_small != '' and
pi.desc_short != '' and
pi.desc_long != ''
group by
c.id
order by
c.sort_order,
cl.title
EOD;
}
$Qgroups = $OSCOM_PDO->prepare($sql);
if (isset($data['language_id'])) {
$Qgroups->bindInt(':languages_id', $data['language_id']);
}
$Qgroups->bindInt(':default_language_id', $data['default_language_id']);
$Qgroups->setCache('<API key>' . ($data['language_id'] ?? $data['default_language_id']), 720);
$Qgroups->execute();
return $Qgroups->fetchAll();
}
}
|
#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/future.hpp>
#include <agency/execution/executor/executor_traits/executor_future.hpp>
#include <agency/execution/executor/executor_traits/is_executor.hpp>
#include <utility>
#include <type_traits>
namespace agency
{
namespace detail
{
template<class Executor, class T, class... Args>
struct <API key>
{
template<
class Executor2,
typename = decltype(
std::declval<Executor2&>().template make_ready_future<T>(
std::declval<Args>()...
)
)
>
static std::true_type test(int);
template<class>
static std::false_type test(...);
using type = decltype(test<Executor>(0));
};
template<class Executor, class T, class... Args>
using <API key> = typename <API key><Executor,T,Args...>::type;
// this overload handles the case of executors which have the member function .make_ready_future()
<API key>
template<class T, class Executor, class... Args>
__AGENCY_ANNOTATION
executor_future_t<Executor,T>
<API key>(std::true_type, Executor& exec, Args&&... args)
{
return exec.template make_ready_future<T>(std::forward<Args>(args)...);
} // end <API key>()
// this overload handles the case of executors which do not have the member function .make_ready_future()
template<class T, class Executor, class... Args>
__AGENCY_ANNOTATION
executor_future_t<Executor,T>
<API key>(std::false_type, Executor&, Args&&... args)
{
using future_type = executor_future_t<Executor,T>;
return future_traits<future_type>::template make_ready<T>(std::forward<Args>(args)...);
} // end <API key>()
} // end detail
template<class T, class E, class... Args,
__AGENCY_REQUIRES(detail::Executor<E>())
>
__AGENCY_ANNOTATION
executor_future_t<E,T> make_ready_future(E& exec, Args&&... args)
{
using <API key> = detail::<API key><
E,
T,
Args&&...
>;
return detail::<API key><T>(<API key>(), exec, std::forward<Args>(args)...);
} // end make_ready_future()
} // end agency
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE <API key> #-}
module Test.Hspec.Snap (
-- * Running blocks of hspec-snap tests
snap
, modifySite
, modifySite'
, afterEval
, beforeEval
-- * Core data types
, TestResponse(..)
, SnapHspecM
-- * Factory style test data generation
, Factory(..)
-- * Requests
, delete
, get
, get'
, post
, postJson
, put
, put'
, params
-- * Helpers for dealing with TestResponses
, restrictResponse
-- * Dealing with session state (EXPERIMENTAL)
, recordSession
, HasSession(..)
, <API key>
, <API key>
-- * Evaluating application code
, eval
-- * Unit test assertions
, shouldChange
, shouldEqual
, shouldNotEqual
, shouldBeTrue
, shouldNotBeTrue
-- * Response assertions
, should200
, shouldNot200
, should404
, shouldNot404
, should300
, shouldNot300
, should300To
, shouldNot300To
, shouldHaveSelector
, <API key>
, shouldHaveText
, shouldNotHaveText
-- * Form tests
, FormExpectations(..)
, form
-- * Internal types and helpers
, SnapHspecState(..)
, setResult
, runRequest
, runHandlerSafe
, evalHandlerSafe
) where
import Control.Applicative ((<$>))
import Control.Concurrent.MVar (MVar, newEmptyMVar, newMVar
,putMVar, readMVar, takeMVar)
import Control.Exception (SomeException, catch)
import Control.Monad (void)
import Control.Monad.State (StateT (..), runStateT)
import qualified Control.Monad.State as S (get, put)
import Control.Monad.Trans (liftIO)
import Data.Aeson (encode, ToJSON)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS (ByteString)
import Data.ByteString.Lazy (fromStrict, toStrict)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Snap.Core (Response (..), getHeader)
import qualified Snap.Core as Snap
import Snap.Snaplet (Handler, Snaplet, SnapletInit,
SnapletLens, with)
import Snap.Snaplet.Session (SessionManager, commitSession,
sessionToList, setInSession)
import Snap.Snaplet.Test (InitializerState, closeSnaplet,
evalHandler', getSnaplet, runHandler')
import Snap.Test (RequestBuilder, getResponseBody)
import qualified Snap.Test as Test
import Test.Hspec
import Test.Hspec.Core.Spec
import qualified Text.Digestive as DF
import qualified Text.HandsomeSoup as HS
import qualified Text.XML.HXT.Core as HXT
-- | The result of making requests against your application. Most
-- assertions act against these types (for example, `should200`,
-- `shouldHaveSelector`, etc).
data TestResponse = Html Text
| Json LBS.ByteString
| NotFound
| Redirect Int Text
| Other Int
| Empty
deriving (Show, Eq)
-- | The main monad that tests run inside of. This allows both access
-- to the application (via requests and `eval`) and to running
-- assertions (like `should404` or `shouldHaveText`).
type SnapHspecM b = StateT (SnapHspecState b) IO
-- | Internal state used to share site initialization across tests, and to propogate failures.
-- Understanding it is completely unnecessary to use the library.
-- The fields it contains, in order, are:
-- > Result
-- > Main handler
-- > Startup state
-- > Startup state
-- > Session state
-- > Before handler (runs before each eval)
-- > After handler (runs after each eval).
data SnapHspecState b = SnapHspecState Result
(Handler b b ())
(Snaplet b)
(InitializerState b)
(MVar [(Text, Text)])
(Handler b b ())
(Handler b b ())
instance Example (SnapHspecM b ()) where
type Arg (SnapHspecM b ()) = SnapHspecState b
evaluateExample s _ cb _ =
do mv <- newEmptyMVar
cb $ \st -> do ((),SnapHspecState r' _ _ _ _ _ _) <- runStateT s st
putMVar mv r'
takeMVar mv
-- | Factory instances allow you to easily generate test data.
-- Essentially, you specify a default way of constructing a
-- data type, and allow certain parts of it to be modified (via
-- the 'fields' data structure).
-- An example follows:
-- > data Foo = Foo Int
-- > newtype FooFields = FooFields (IO Int)
-- > instance Factory App Foo FooFields where
-- > fields = FooFields randomIO
-- > save f = liftIO f >>= saveFoo . Foo1
-- > main = do create id :: SnapHspecM App Foo
-- > create (const $ FooFields (return 1)) :: SnapHspecM App Foo
class Factory b a d | a -> b, a -> d, d -> a where
fields :: d
save :: d -> SnapHspecM b a
create :: (d -> d) -> SnapHspecM b a
create transform = save $ transform fields
reload :: a -> SnapHspecM b a
reload = return
-- | The way to run a block of `SnapHspecM` tests within an `hspec`
-- test suite. This takes both the top level handler (usually `route
-- routes`, where `routes` are all the routes for your site) and the
-- site initializer (often named `app`), and a block of tests. A test
-- suite can have multiple calls to `snap`, though each one will cause
-- the site initializer to run, which is often a slow operation (and
-- will slow down test suites).
snap :: Handler b b () -> SnapletInit b b -> SpecWith (SnapHspecState b) -> Spec
snap site app spec = do
snapinit <- runIO $ getSnaplet (Just "test") app
mv <- runIO (newMVar [])
case snapinit of
Left err -> error $ show err
Right (snaplet, initstate) ->
afterAll (const $ closeSnaplet initstate) $
before (return (SnapHspecState Success site snaplet initstate mv (return ()) (return ()))) spec
-- | This allows you to change the default handler you are running
-- requests against within a block. This is most likely useful for
-- setting request state (for example, logging a user in).
modifySite :: (Handler b b () -> Handler b b ())
-> SpecWith (SnapHspecState b)
-> SpecWith (SnapHspecState b)
modifySite f = beforeWith (\(SnapHspecState r site snaplet initst sess bef aft) ->
return (SnapHspecState r (f site) snaplet initst sess bef aft))
-- | This performs a similar operation to `modifySite` but in the context
-- of `SnapHspecM` (which is needed if you need to `eval`, produce values, and
-- hand them somewhere else (so they can't be created within `f`).
modifySite' :: (Handler b b () -> Handler b b ())
-> SnapHspecM b a
-> SnapHspecM b a
modifySite' f a = do (SnapHspecState r site s i sess bef aft) <- S.get
S.put (SnapHspecState r (f site) s i sess bef aft)
a
-- | Evaluate a Handler action after each test.
afterEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
afterEval h = after (\(SnapHspecState _r _site s i _ _ _) ->
do res <- evalHandlerSafe h s i
case res of
Right _ -> return ()
Left msg -> liftIO $ print msg)
-- | Evaluate a Handler action before each test.
beforeEval :: Handler b b () -> SpecWith (SnapHspecState b) -> SpecWith (SnapHspecState b)
beforeEval h = beforeWith (\state@(SnapHspecState _r _site s i _ _ _) -> do void $ evalHandlerSafe h s i
return state)
class HasSession b where
getSessionLens :: SnapletLens b SessionManager
recordSession :: HasSession b => SnapHspecM b a -> SnapHspecM b a
recordSession a =
do (SnapHspecState r site s i mv bef aft) <- S.get
S.put (SnapHspecState r site s i mv
(do ps <- liftIO $ readMVar mv
with getSessionLens $ mapM_ (uncurry setInSession) ps
with getSessionLens commitSession)
(do ps' <- with getSessionLens sessionToList
void . liftIO $ takeMVar mv
liftIO $ putMVar mv ps'))
res <- a
(SnapHspecState r' _ _ _ _ _ _) <- S.get
void . liftIO $ takeMVar mv
liftIO $ putMVar mv []
S.put (SnapHspecState r' site s i mv bef aft)
return res
sessContents :: SnapHspecM b Text
sessContents = do
(SnapHspecState _ _ _ _ mv _ _) <- S.get
ps <- liftIO $ readMVar mv
return $ T.concat (map (uncurry T.append) ps)
<API key> :: Text -> SnapHspecM b ()
<API key> t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult Success
else setResult (Fail $ "Session did not contain: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
<API key> :: Text -> SnapHspecM b ()
<API key> t =
do contents <- sessContents
if t `T.isInfixOf` contents
then setResult (Fail $ "Session should not have contained: " ++ T.unpack t
++ "\n\nSession was:\n" ++ T.unpack contents)
else setResult Success
-- | Runs a DELETE request
delete :: Text -> SnapHspecM b TestResponse
delete path = runRequest (Test.delete (T.encodeUtf8 path) M.empty)
-- | Runs a GET request.
get :: Text -> SnapHspecM b TestResponse
get path = get' path M.empty
-- | Runs a GET request, with a set of parameters.
get' :: Text -> Snap.Params -> SnapHspecM b TestResponse
get' path ps = runRequest (Test.get (T.encodeUtf8 path) ps)
-- | A helper to construct parameters.
params :: [(ByteString, ByteString)] -- ^ Pairs of parameter and value.
-> Snap.Params
params = M.fromList . map (\x -> (fst x, [snd x]))
-- | Creates a new POST request, with a set of parameters.
post :: Text -> Snap.Params -> SnapHspecM b TestResponse
post path ps = runRequest (Test.postUrlEncoded (T.encodeUtf8 path) ps)
-- | Creates a new POST request with a given JSON value as the request body.
postJson :: ToJSON tj => Text -> tj -> SnapHspecM b TestResponse
postJson path json = runRequest $ Test.postRaw (T.encodeUtf8 path)
"application/json"
(toStrict $ encode json)
-- | Creates a new PUT request, with a set of parameters, with a default type of "application/<API key>"
put :: Text -> Snap.Params -> SnapHspecM b TestResponse
put path params' = put' path "application/<API key>" params'
-- | Creates a new PUT request with a configurable MIME/type
put' :: Text -> Text -> Snap.Params -> SnapHspecM b TestResponse
put' path mime params' = runRequest $ do
Test.put (T.encodeUtf8 path) (T.encodeUtf8 mime) ""
Test.setQueryString params'
-- | Restricts a response to matches for a given CSS selector.
-- Does nothing to non-Html responses.
restrictResponse :: Text -> TestResponse -> TestResponse
restrictResponse selector (Html body) =
case HXT.runLA (HXT.xshow $ HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> Html ""
matches -> Html (T.concat (map T.pack matches))
restrictResponse _ r = r
-- | Runs an arbitrary stateful action from your application.
eval :: Handler b b a -> SnapHspecM b a
eval act = do (SnapHspecState _ _site app is _mv bef aft) <- S.get
liftIO $ either (error . T.unpack) id <$> evalHandlerSafe (do bef
r <- act
aft
return r) app is
-- | Records a test Success or Fail. Only the first Fail will be
-- recorded (and will cause the whole block to Fail).
setResult :: Result -> SnapHspecM b ()
setResult r = do (SnapHspecState r' s a i sess bef aft) <- S.get
case r' of
Success -> S.put (SnapHspecState r s a i sess bef aft)
_ -> return ()
-- | Asserts that a given stateful action will produce a specific different result after
-- an action has been run.
shouldChange :: (Show a, Eq a)
=> (a -> a)
-> Handler b b a
-> SnapHspecM b c
-> SnapHspecM b ()
shouldChange f v act = do before' <- eval v
void act
after' <- eval v
shouldEqual (f before') after'
-- | Asserts that two values are equal.
shouldEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldEqual a b = if a == b
then setResult Success
else setResult (Fail ("Should have held: " ++ show a ++ " == " ++ show b))
-- | Asserts that two values are not equal.
shouldNotEqual :: (Show a, Eq a)
=> a
-> a
-> SnapHspecM b ()
shouldNotEqual a b = if a == b
then setResult (Fail ("Should not have held: " ++ show a ++ " == " ++ show b))
else setResult Success
-- | Asserts that the value is True.
shouldBeTrue :: Bool
-> SnapHspecM b ()
shouldBeTrue True = setResult Success
shouldBeTrue False = setResult (Fail "Value should have been True.")
-- | Asserts that the value is not True (otherwise known as False).
shouldNotBeTrue :: Bool
-> SnapHspecM b ()
shouldNotBeTrue False = setResult Success
shouldNotBeTrue True = setResult (Fail "Value should have been True.")
-- | Asserts that the response is a success (either Html, or Other with status 200).
should200 :: TestResponse -> SnapHspecM b ()
should200 (Html _) = setResult Success
should200 (Other 200) = setResult Success
should200 r = setResult (Fail (show r))
-- | Asserts that the response is not a normal 200.
shouldNot200 :: TestResponse -> SnapHspecM b ()
shouldNot200 (Html _) = setResult (Fail "Got Html back.")
shouldNot200 (Other 200) = setResult (Fail "Got Other with 200 back.")
shouldNot200 _ = setResult Success
-- | Asserts that the response is a NotFound.
should404 :: TestResponse -> SnapHspecM b ()
should404 NotFound = setResult Success
should404 r = setResult (Fail (show r))
-- | Asserts that the response is not a NotFound.
shouldNot404 :: TestResponse -> SnapHspecM b ()
shouldNot404 NotFound = setResult (Fail "Got NotFound back.")
shouldNot404 _ = setResult Success
-- | Asserts that the response is a redirect.
should300 :: TestResponse -> SnapHspecM b ()
should300 (Redirect _ _) = setResult Success
should300 r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect.
shouldNot300 :: TestResponse -> SnapHspecM b ()
shouldNot300 (Redirect _ _) = setResult (Fail "Got Redirect back.")
shouldNot300 _ = setResult Success
-- | Asserts that the response is a redirect, and thet the url it
-- redirects to starts with the given path.
should300To :: Text -> TestResponse -> SnapHspecM b ()
should300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult Success
should300To _ r = setResult (Fail (show r))
-- | Asserts that the response is not a redirect to a given path. Note
-- that it can still be a redirect for this assertion to succeed, the
-- path it redirects to just can't start with the given path.
shouldNot300To :: Text -> TestResponse -> SnapHspecM b ()
shouldNot300To pth (Redirect _ to) | pth `T.isPrefixOf` to = setResult (Fail "Got Redirect back.")
shouldNot300To _ _ = setResult Success
-- | Assert that a response (which should be Html) has a given selector.
shouldHaveSelector :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveSelector selector r@(Html body) =
setResult $ if haveSelector' selector r
then Success
else Fail msg
where msg = T.unpack $ T.concat ["Html should have contained selector: ", selector, "\n\n", body]
shouldHaveSelector match _ = setResult (Fail (T.unpack $ T.concat ["Non-HTML body should have contained css selector: ", match]))
-- | Assert that a response (which should be Html) doesn't have a given selector.
<API key> :: Text -> TestResponse -> SnapHspecM b ()
<API key> selector r@(Html body) =
setResult $ if haveSelector' selector r
then Fail msg
else Success
where msg = T.unpack $ T.concat ["Html should not have contained selector: ", selector, "\n\n", body]
<API key> _ _ = setResult Success
haveSelector' :: Text -> TestResponse -> Bool
haveSelector' selector (Html body) =
case HXT.runLA (HXT.hread HXT.>>> HS.css (T.unpack selector)) (T.unpack body) of
[] -> False
_ -> True
haveSelector' _ _ = False
-- | Asserts that the response (which should be Html) contains the given text.
shouldHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldHaveText match (Html body) =
if T.isInfixOf match body
then setResult Success
else setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
shouldHaveText match _ = setResult (Fail (T.unpack $ T.concat ["Body contains: ", match]))
-- | Asserts that the response (which should be Html) does not contain the given text.
shouldNotHaveText :: Text -> TestResponse -> SnapHspecM b ()
shouldNotHaveText match (Html body) =
if T.isInfixOf match body
then setResult (Fail $ T.unpack $ T.concat [body, "' contains '", match, "'."])
else setResult Success
shouldNotHaveText _ _ = setResult Success
-- | A data type for tests against forms.
data FormExpectations a = Value a -- ^ The value the form should take (and should be valid)
| Predicate (a -> Bool)
| ErrorPaths [Text] -- ^ The error paths that should be populated
-- | Tests against digestive-functors forms.
form :: (Eq a, Show a)
=> FormExpectations a -- ^ If the form should succeed, Value a is what it should produce.
-- If failing, ErrorPaths should be all the errors that are triggered.
-> DF.Form Text (Handler b b) a -- ^ The form to run
-> M.Map Text Text -- ^ The parameters to pass
-> SnapHspecM b ()
form expected theForm theParams =
do r <- eval $ DF.postForm "form" theForm (const $ return lookupParam)
case expected of
Value a -> shouldEqual (snd r) (Just a)
Predicate f ->
case snd r of
Nothing -> setResult (Fail $ T.unpack $
T.append "Expected form to validate. Resulted in errors: "
(T.pack (show $ DF.viewErrors $ fst r)))
Just v -> if f v
then setResult Success
else setResult (Fail $ T.unpack $
T.append "Expected predicate to pass on value: "
(T.pack (show v)))
ErrorPaths expectedPaths ->
do let viewErrorPaths = map (DF.fromPath . fst) $ DF.viewErrors $ fst r
if all (`elem` viewErrorPaths) expectedPaths
then if length viewErrorPaths == length expectedPaths
then setResult Success
else setResult (Fail $ "Number of errors did not match test. Got:\n\n "
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
else setResult (Fail $ "Did not have all errors specified. Got:\n\n"
++ show viewErrorPaths
++ "\n\nBut expected:\n\n"
++ show expectedPaths)
where lookupParam pth = case M.lookup (DF.fromPath pth) fixedParams of
Nothing -> return []
Just v -> return [DF.TextInput v]
fixedParams = M.mapKeys (T.append "form.") theParams
-- | Runs a request (built with helpers from Snap.Test), resulting in a response.
runRequest :: RequestBuilder IO () -> SnapHspecM b TestResponse
runRequest req = do
(SnapHspecState _ site app is _ bef aft) <- S.get
res <- liftIO $ runHandlerSafe req (bef >> site >> aft) app is
case res of
Left err ->
error $ T.unpack err
Right response ->
case rspStatus response of
404 -> return NotFound
200 ->
liftIO $ parse200 response
_ -> if rspStatus response >= 300 && rspStatus response < 400
then do let url = fromMaybe "" $ getHeader "Location" response
return (Redirect (rspStatus response) (T.decodeUtf8 url))
else return (Other (rspStatus response))
parse200 :: Response -> IO TestResponse
parse200 resp =
let body = getResponseBody resp
contentType = getHeader "content-type" resp in
case contentType of
Just "application/json" -> Json . fromStrict <$> body
_ -> Html . T.decodeUtf8 <$> body
-- | Runs a request against a given handler (often the whole site),
-- with the given state. Returns any triggered exception, or the response.
runHandlerSafe :: RequestBuilder IO ()
-> Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text Response)
runHandlerSafe req site s is =
catch (runHandler' s is req site) (\(e::SomeException) -> return $ Left (T.pack $ show e))
-- | Evaluates a given handler with the given state. Returns any
-- triggered exception, or the value produced.
evalHandlerSafe :: Handler b b v
-> Snaplet b
-> InitializerState b
-> IO (Either Text v)
evalHandlerSafe act s is =
catch (evalHandler' s is (Test.get "" M.empty) act) (\(e::SomeException) -> return $ Left (T.pack $ show e))
{-# ANN put ("HLint: ignore Eta reduce"::String) #-}
|
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta charset="utf-8" />
<title>statsmodels.sandbox.stats.multicomp.set_remove_subs — statsmodels v0.10.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="<API key>" data-url_root="../" src="../_static/<API key>.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script>
<link rel="shortcut icon" href="../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.stats.multicomp.tiecorrect" href="statsmodels.sandbox.stats.multicomp.tiecorrect.html" />
<link rel="prev" title="statsmodels.sandbox.stats.multicomp.set_partition" href="statsmodels.sandbox.stats.multicomp.set_partition.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.stats.multicomp.tiecorrect.html" title="statsmodels.sandbox.stats.multicomp.tiecorrect"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.stats.multicomp.set_partition.html" title="statsmodels.sandbox.stats.multicomp.set_partition"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../stats.html" accesskey="U">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.sandbox.stats.multicomp.set_remove_subs<a class="headerlink" href="
<dl class="function">
<dt id="statsmodels.sandbox.stats.multicomp.set_remove_subs">
<code class="sig-prename descclassname">statsmodels.sandbox.stats.multicomp.</code><code class="sig-name descname">set_remove_subs</code><span class="sig-paren">(</span><em class="sig-param">ssli</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/stats/multicomp.html
<dd><p>remove sets that are subsets of another set from a list of tuples</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl class="simple">
<dt><strong>ssli</strong><span class="classifier">list of tuples</span></dt><dd><p>each tuple is considered as a set</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl class="simple">
<dt><strong>part</strong><span class="classifier">list of tuples</span></dt><dd><p>new list with subset tuples removed, it is sorted by set-length of tuples. The
list contains original tuples, duplicate elements are not removed.</p>
</dd>
</dl>
</dd>
</dl>
<p class="rubric">Examples</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">set_remove_subs</span><span class="p">([(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">0</span><span class="p">,)])</span>
<span class="go">[(1, 2, 3), (0, 1)]</span>
<span class="gp">>>> </span><span class="n">set_remove_subs</span><span class="p">([(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">0</span><span class="p">,)])</span>
<span class="go">[(1, 1, 1, 2, 3), (0, 1)]</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.sandbox.stats.multicomp.set_partition.html"
title="previous chapter">statsmodels.sandbox.stats.multicomp.set_partition</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.sandbox.stats.multicomp.tiecorrect.html"
title="next chapter">statsmodels.sandbox.stats.multicomp.tiecorrect</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.sandbox.stats.multicomp.set_remove_subs.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html>
|
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unicode/ustring.h>
#include <unicode/utypes.h>
#include <unicode/uchar.h>
#include "string.h"
#define FAST_COUNT 0
#define FAST_SEARCH 1
#define <API key> sizeof(UChar)
#define STRINGLIB_BLOOM_ADD(mask, ch) \
((mask |= (1UL << ((ch) & (<API key> - 1)))))
#define STRINGLIB_BLOOM(mask, ch) \
((mask & (1UL << ((ch) & (<API key> - 1)))))
static inline ssize_t
fast_search(const UChar *str,
size_t str_len,
const UChar *pattern,
size_t pattern_len,
size_t max_count,
int mode)
{
const UChar *str_ptr;
const UChar *pattern_ptr;
unsigned long mask;
size_t i, j, mlast;
size_t skip, count = 0;
ssize_t w;
w = str_len - pattern_len;
if (w < 0 || (mode == FAST_COUNT && max_count == 0))
return -1;
/* look for special cases */
if (pattern_len <= 1) {
if (pattern_len <= 0)
return -1;
/* use special case for 1-character strings */
if (str_len > 10 && (mode == FAST_SEARCH)) {
/* use memchr if we can choose a needle without too many
likely false positives */
UChar *ptr = u_memchr(str, pattern[0], str_len);
if (!ptr)
return -1;
return ptr - str;
}
if (mode == FAST_COUNT) {
for (i = 0; i < str_len; i++)
if (str[i] == pattern[0]) {
count++;
if (count == max_count)
return max_count;
}
return count;
} else { /* (mode == FAST_SEARCH) */
for (i = 0; i < str_len; i++)
if (str[i] == pattern[0])
return i;
}
return -1;
}
mlast = pattern_len - 1;
skip = mlast - 1;
mask = 0;
str_ptr = str + pattern_len - 1;
pattern_ptr = pattern + pattern_len - 1;
/* create compressed boyer-moore delta 1 table */
/* process pattern[:-1] */
for (i = 0; i < mlast; i++) {
STRINGLIB_BLOOM_ADD(mask, pattern[i]);
if (pattern[i] == pattern[mlast])
skip = mlast - i - 1;
}
/* process pattern[-1] outside the loop */
STRINGLIB_BLOOM_ADD(mask, pattern[mlast]);
for (i = 0; i <= (size_t)w; i++) {
/* note: using mlast in the skip path slows things down on x86 */
if (str_ptr[i] == pattern_ptr[0]) {
/* candidate match */
for (j = 0; j < mlast; j++)
if (str[i + j] != pattern[j])
break;
if (j == mlast) {
/* got a match! */
if (mode != FAST_COUNT)
return i;
count++;
if (count == max_count)
return max_count;
i = i + mlast;
continue;
}
/* miss: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1]))
i = i + pattern_len;
else
i = i + skip;
} else {
/* skip: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, str_ptr[i + 1]))
i = i + pattern_len;
}
}
if (mode != FAST_COUNT)
return -1;
return count;
}
static inline ssize_t
sub_str_count(const UChar *str,
size_t str_len,
const UChar *sub,
size_t sub_len,
size_t max_count)
{
ssize_t count;
if (sub_len == 0)
return (str_len < max_count) ? str_len + 1 : max_count;
count = fast_search(str, str_len, sub, sub_len, max_count, FAST_COUNT);
if (count < 0)
return 0; /* no match */
return count;
}
static inline ssize_t
sub_str_find(const UChar *str,
ssize_t str_len,
const UChar *sub,
ssize_t sub_len,
ssize_t offset)
{
ssize_t pos;
if (sub_len == 0)
return offset;
pos = fast_search(str, str_len, sub, sub_len, -1, FAST_SEARCH);
if (pos >= 0)
pos += offset;
return pos;
}
#define <API key>(_icu_str, _icu_sz, _icu_err_val, \
_utf_str, _icu_size_calc_goto, _no_mem_goto, _icu_conv_goto) \
do { \
_icu_err_val = U_ZERO_ERROR; \
u_strFromUTF8(NULL, 0, &_icu_sz, _utf_str, -1, &_icu_err_val); \
if (U_FAILURE(_icu_err_val) && \
_icu_err_val != <API key>) \
goto _icu_size_calc_goto; \
_icu_str = calloc(_icu_sz + 1, sizeof(*_icu_str)); \
if (!_icu_str) \
goto _no_mem_goto; \
_icu_err_val = U_ZERO_ERROR; \
u_strFromUTF8(_icu_str, _icu_sz + 1, &_icu_sz, _utf_str, \
-1, &_icu_err_val); \
if (U_FAILURE(_icu_err_val)) { \
goto _icu_conv_goto; \
} \
} while (0)
static UChar *
u_strdup(UChar *in)
{
uint32_t len = u_strlen(in) + 1;
UChar *result = malloc(sizeof(UChar) * len);
SOL_NULL_CHECK(result, NULL);
u_memcpy(result, in, len);
return result;
}
static inline void
<API key>(UChar *s, UChar *end,
UChar u1, UChar u2, ssize_t max_count)
{
*s = u2;
while (--max_count && ++s != end) {
/* Find the next character to be replaced. If it occurs often,
* it is faster to scan for it using an inline loop. If it
* occurs seldom, it is faster to scan for it using a function
* call; the overhead of the function call is amortized across
* the many characters that call covers. We start with an
* inline loop and use a heuristic to determine whether to
* fall back to a function call.
*/
if (*s != u1) {
int attempts = 10;
while (true) {
if (++s == end)
return;
if (*s == u1)
break;
if (!--attempts) {
s++;
s = u_memchr(s, u1, end - s);
if (s == NULL)
return;
/* restart the dummy loop */
break;
}
}
}
*s = u2;
}
}
UChar *
string_replace(struct sol_flow_node *node,
UChar *value,
UChar *change_from,
UChar *change_to,
size_t max_count)
{
UChar *ret;
size_t value_len = u_strlen(value);
size_t change_to_len = u_strlen(change_to);
size_t change_from_len = u_strlen(change_from);
if (max_count == 0) {
ret = u_strdup(value);
goto nothing;
}
if (u_strcmp(change_from, change_to) == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len == change_to_len) {
/* same length */
if (change_from_len == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len == 1) {
/* replace characters */
ret = u_strdup(value);
<API key>(ret, ret + value_len, change_from[0],
change_to[0], max_count);
} else {
UChar *token;
ssize_t i;
ret = u_strdup(value);
token = u_strFindFirst(value, value_len, change_from,
change_from_len);
if (!token)
goto nothing;
i = token - value;
u_memcpy(ret, value, value_len);
/* change everything in-place, starting with this one */
u_memcpy(ret + i, change_to, change_to_len);
i += change_from_len;
while (--max_count > 0) {
token = u_strFindFirst(value + i, value_len - i, change_from,
change_from_len);
if (!token)
break;
u_memcpy(ret + i, change_to, change_to_len);
i += change_from_len;
}
}
} else {
ssize_t count, i, j, ires, new_size;
int r;
count = sub_str_count(value, value_len,
change_from, change_from_len, max_count);
if (count == 0) {
ret = u_strdup(value);
goto nothing;
}
if (change_from_len < change_to_len &&
change_to_len - change_from_len >
(INT32_MAX - value_len) / count) {
<API key>(node, -EINVAL,
"replace string is too long");
goto error;
}
r = sol_util_ssize_mul(count,
(ssize_t)(change_to_len - change_from_len), &new_size);
if (r < 0 ||
(new_size > 0 && SSIZE_MAX - new_size < (ssize_t)value_len)) {
<API key>(node, -EINVAL,
"replace string is too long");
goto error;
}
new_size += value_len;
if (new_size == 0) {
UErrorCode err;
r = icu_str_from_utf8("", &ret, &err);
SOL_INT_CHECK_GOTO(r, < 0, error);
goto done;
}
ret = calloc(new_size + 1, sizeof(*ret));
if (!ret)
goto error;
ires = i = 0;
if (change_from_len > 0) {
while (count
UChar *token;
/* look for next match */
token = u_strFindFirst(value + i, value_len - i, change_from,
change_from_len);
if (!token) {
free(ret);
ret = u_strdup(value);
goto nothing;
}
j = sub_str_find(value + i, value_len - i,
change_from, change_from_len, i);
if (j == -1)
break;
else if (j > i) {
/* copy unchanged part [i:j] */
u_memcpy(ret + ires, value + i, (j - i));
ires += j - i;
}
/* copy substitution string */
if (change_to_len > 0) {
u_memcpy(ret + ires, change_to, change_to_len);
ires += change_to_len;
}
i = j + change_from_len;
}
if (i < (ssize_t)value_len)
/* copy tail [i:] */
u_memcpy(ret + ires, value + i, (value_len - i));
} else {
/* interleave */
while (count > 0) {
u_memcpy(ret + ires, change_to, change_to_len);
ires += change_to_len;
if (--count <= 0)
break;
u_memcpy(ret + ires, value + i, 1);
ires++;
i++;
}
u_memcpy(ret + ires, value + i, (value_len - i));
}
}
done:
nothing:
return ret;
error:
return NULL;
}
|
#include "server.h"
#include "../util/strings.h"
#include "../util/file.h"
#include "../util/config.h"
#include "../util/log.h"
#include "../util/ip_filter.h"
#include "link.h"
#include <vector>
static DEF_PROC(ping);
static DEF_PROC(info);
static DEF_PROC(auth);
#define TICK_INTERVAL 100
#define STATUS_REPORT_TICKS (300 * 1000/TICK_INTERVAL) // second
volatile bool quit = false;
volatile uint32_t g_ticks = 0;
void signal_handler(int sig){
switch(sig){
case SIGTERM:
case SIGINT:{
quit = true;
break;
}
case SIGALRM:{
g_ticks ++;
break;
}
}
}
NetworkServer::NetworkServer(){
tick_interval = TICK_INTERVAL;
status_report_ticks = STATUS_REPORT_TICKS;
conf = NULL;
serv_link = NULL;
link_count = 0;
fdes = new Fdevents();
ip_filter = new IpFilter();
// add built-in procs, can be overridden
proc_map.set_proc("ping", "r", proc_ping);
proc_map.set_proc("info", "r", proc_info);
proc_map.set_proc("auth", "r", proc_auth);
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifndef __CYGWIN__
signal(SIGALRM, signal_handler);
{
struct itimerval tv;
tv.it_interval.tv_sec = (TICK_INTERVAL / 1000);
tv.it_interval.tv_usec = (TICK_INTERVAL % 1000) * 1000;
tv.it_value.tv_sec = 1;
tv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tv, NULL);
}
#endif
}
NetworkServer::~NetworkServer(){
delete conf;
delete serv_link;
delete fdes;
delete ip_filter;
writer->stop();
delete writer;
reader->stop();
delete reader;
}
void NetworkServer::init(const char *conf_file){
if(!is_file(conf_file)){
fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
exit(1);
}
conf = Config::load(conf_file);
if(!conf){
fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
exit(1);
}
{
std::string conf_dir = real_dirname(conf_file);
if(chdir(conf_dir.c_str()) == -1){
fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
exit(1);
}
}
this->init(*conf);
}
void NetworkServer::init(const Config &conf){
// init ip_filter
{
Config *cc = (Config *)conf.get("server");
if(cc != NULL){
std::vector<Config *> *children = &cc->children;
std::vector<Config *>::iterator it;
for(it = children->begin(); it != children->end(); it++){
if((*it)->key == "allow"){
const char *ip = (*it)->str();
log_info(" allow %s", ip);
ip_filter->add_allow(ip);
}
if((*it)->key == "deny"){
const char *ip = (*it)->str();
log_info(" deny %s", ip);
ip_filter->add_deny(ip);
}
}
}
}
{ // server
const char *ip = conf.get_str("server.ip");
int port = conf.get_num("server.port");
if(ip == NULL || ip[0] == '\0'){
ip = "127.0.0.1";
}
serv_link = Link::listen(ip, port);
if(serv_link == NULL){
log_fatal("error opening server socket! %s", strerror(errno));
fprintf(stderr, "error opening server socket! %s\n", strerror(errno));
exit(1);
}
log_info("server listen on %s:%d", ip, port);
std::string password;
password = conf.get_str("server.auth");
if(password.size() && (password.size() < 32 || <API key>)){
log_fatal("weak password is not allowed!");
fprintf(stderr, "WARNING! Weak password is not allowed!\n");
exit(1);
}
if(password.empty()){
log_info("auth: off");
}else{
log_info("auth: on");
}
this->need_auth = false;
if(!password.empty()){
this->need_auth = true;
this->password = password;
}
}
}
void NetworkServer::serve(){
writer = new ProcWorkerPool("writer");
writer->start(WRITER_THREADS);
reader = new ProcWorkerPool("reader");
reader->start(READER_THREADS);
ready_list_t ready_list;
ready_list_t ready_list_2;
ready_list_t::iterator it;
const Fdevents::events_t *events;
fdes->set(serv_link->fd(), FDEVENT_IN, 0, serv_link);
fdes->set(this->reader->fd(), FDEVENT_IN, 0, this->reader);
fdes->set(this->writer->fd(), FDEVENT_IN, 0, this->writer);
uint32_t last_ticks = g_ticks;
while(!quit){
// status report
if((uint32_t)(g_ticks - last_ticks) >= STATUS_REPORT_TICKS){
last_ticks = g_ticks;
log_info("server running, links: %d", this->link_count);
}
ready_list.swap(ready_list_2);
ready_list_2.clear();
if(!ready_list.empty()){
// ready_list not empty, so we should return immediately
events = fdes->wait(0);
}else{
events = fdes->wait(50);
}
if(events == NULL){
log_fatal("events.wait error: %s", strerror(errno));
break;
}
for(int i=0; i<(int)events->size(); i++){
const Fdevent *fde = events->at(i);
if(fde->data.ptr == serv_link){
Link *link = accept_link();
if(link){
this->link_count ++;
log_debug("new link from %s:%d, fd: %d, links: %d",
link->remote_ip, link->remote_port, link->fd(), this->link_count);
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}
}else if(fde->data.ptr == this->reader || fde->data.ptr == this->writer){
ProcWorkerPool *worker = (ProcWorkerPool *)fde->data.ptr;
ProcJob job;
if(worker->pop(&job) == 0){
log_fatal("reading result from workers error!");
exit(0);
}
if(proc_result(&job, &ready_list) == PROC_ERROR){
}
}else{
proc_client_event(fde, &ready_list);
}
}
for(it = ready_list.begin(); it != ready_list.end(); it ++){
Link *link = *it;
if(link->error()){
this->link_count
fdes->del(link->fd());
delete link;
continue;
}
const Request *req = link->recv();
if(req == NULL){
log_warn("fd: %d, link parse error, delete link", link->fd());
this->link_count
fdes->del(link->fd());
delete link;
continue;
}
if(req->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
continue;
}
link->active_time = millitime();
ProcJob job;
job.link = link;
this->proc(&job);
if(job.result == PROC_THREAD){
fdes->del(link->fd());
continue;
}
if(job.result == PROC_BACKEND){
fdes->del(link->fd());
this->link_count
continue;
}
if(proc_result(&job, &ready_list_2) == PROC_ERROR){
}
} // end foreach ready link
}
}
Link* NetworkServer::accept_link(){
Link *link = serv_link->accept();
if(link == NULL){
log_error("accept failed! %s", strerror(errno));
return NULL;
}
if(!ip_filter->check_pass(link->remote_ip)){
log_debug("ip_filter deny link from %s:%d", link->remote_ip, link->remote_port);
delete link;
return NULL;
}
link->nodelay();
link->noblock();
link->create_time = millitime();
link->active_time = link->create_time;
return link;
}
int NetworkServer::proc_result(ProcJob *job, ready_list_t *ready_list){
Link *link = job->link;
int len;
if(job->cmd){
job->cmd->calls += 1;
job->cmd->time_wait += job->time_wait;
job->cmd->time_proc += job->time_proc;
}
if(job->result == PROC_ERROR){
log_info("fd: %d, proc error, delete link", link->fd());
goto proc_err;
}
len = link->write();
//log_debug("write: %d", len);
if(len < 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
goto proc_err;
}
if(!link->output->empty()){
fdes->set(link->fd(), FDEVENT_OUT, 1, link);
}
if(link->input->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}else{
fdes->clr(link->fd(), FDEVENT_IN);
ready_list->push_back(link);
}
return PROC_OK;
proc_err:
this->link_count
fdes->del(link->fd());
delete link;
return PROC_ERROR;
}
/*
event:
read => ready_list OR close
write => NONE
proc =>
done: write & (read OR ready_list)
async: stop (read & write)
1. When writing to a link, it may happen to be in the ready_list,
so we cannot close that link in write process, we could only
just mark it as closed.
2. When reading from a link, it is never in the ready_list, so it
is safe to close it in read process, also safe to put it into
ready_list.
3. Ignore FDEVENT_ERR
A link is in either one of these places:
1. ready list
2. async worker queue
So it safe to delete link when processing ready list and async worker result.
*/
int NetworkServer::proc_client_event(const Fdevent *fde, ready_list_t *ready_list){
Link *link = (Link *)fde->data.ptr;
if(fde->events & FDEVENT_IN){
ready_list->push_back(link);
if(link->error()){
return 0;
}
int len = link->read();
//log_debug("fd: %d read: %d", link->fd(), len);
if(len <= 0){
log_debug("fd: %d, read: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
}
if(fde->events & FDEVENT_OUT){
if(link->error()){
return 0;
}
int len = link->write();
if(len <= 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
if(link->output->empty()){
fdes->clr(link->fd(), FDEVENT_OUT);
}
}
return 0;
}
void NetworkServer::proc(ProcJob *job){
job->serv = this;
job->result = PROC_OK;
job->stime = millitime();
const Request *req = job->link->last_recv();
Response resp;
do{
// AUTH
if(this->need_auth && job->link->auth == false && req->at(0) != "auth"){
resp.push_back("noauth");
resp.push_back("authentication required");
break;
}
Command *cmd = proc_map.get_proc(req->at(0));
if(!cmd){
resp.push_back("client_error");
resp.push_back("Unknown Command: " + req->at(0).String());
break;
}
job->cmd = cmd;
if(cmd->flags & Command::FLAG_THREAD){
if(cmd->flags & Command::FLAG_WRITE){
job->result = PROC_THREAD;
writer->push(*job);
}else{
job->result = PROC_THREAD;
reader->push(*job);
}
return;
}
proc_t p = cmd->proc;
job->time_wait = 1000 * (millitime() - job->stime);
job->result = (*p)(this, job->link, *req, &resp);
job->time_proc = 1000 * (millitime() - job->stime) - job->time_wait;
}while(0);
if(job->link->send(resp.resp) == -1){
job->result = PROC_ERROR;
}else{
if(log_level() >= Logger::LEVEL_DEBUG){
log_debug("w:%.3f,p:%.3f, req: %s, resp: %s",
job->time_wait, job->time_proc,
serialize_req(*req).c_str(),
serialize_req(resp.resp).c_str());
}
}
}
/* built-in procs */
static int proc_ping(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
return 0;
}
static int proc_info(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
resp->push_back("ideawu's network server framework");
resp->push_back("version");
resp->push_back("1.0");
resp->push_back("links");
resp->add(net->link_count);
{
int64_t calls = 0;
proc_map_t::iterator it;
for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){
Command *cmd = it->second;
calls += cmd->calls;
}
resp->push_back("total_calls");
resp->add(calls);
}
return 0;
}
static int proc_auth(NetworkServer *net, Link *link, const Request &req, Response *resp){
if(req.size() != 2){
resp->push_back("client_error");
}else{
if(!net->need_auth || req[1] == net->password){
link->auth = true;
resp->push_back("ok");
resp->push_back("1");
}else{
resp->push_back("error");
resp->push_back("invalid password");
}
}
return 0;
}
|
import { Page } from 'puppeteer';
import Textbox from 'app/element/textbox';
import AuthenticatedPage from 'app/page/authenticated-page';
import { <API key>, waitForUrl, waitWhileLoading } from 'utils/waits-utils';
import Button from 'app/element/button';
import Textarea from 'app/element/textarea';
import { PageUrl } from 'app/text-labels';
import Link from 'app/element/link';
export const PageTitle = 'Profile';
const LabelAlias = {
ResearchBackground: 'Your research background, experience and research interests',
SaveProfile: 'Save Profile',
NeedsConfirmation: 'Please update or verify your profile.',
LooksGood: 'Looks Good'
};
const DataTestIdAlias = {
FirstName: 'givenName',
LastName: 'familyName',
ProfessionalUrl: 'professionalUrl',
Address1: 'streetAddress1',
Address2: 'streetAddress2',
City: 'city',
State: 'state',
Zip: 'zipCode',
Country: 'country'
};
export const MissingErrorAlias = {
FirstName: 'First Name',
LastName: 'Last Name',
ResearchBackground: 'Current Research',
Address1: 'Street address1',
City: 'City',
State: 'State',
Zip: 'Zip code',
Country: 'Country'
};
export default class ProfilePage extends AuthenticatedPage {
constructor(page: Page) {
super(page);
}
/**
* Load 'Profile' page and ensure page load is completed.
*/
async load(): Promise<this> {
await this.loadPage({ url: PageUrl.Profile });
await waitWhileLoading(this.page);
return this;
}
async isLoaded(): Promise<boolean> {
await Promise.all([waitForUrl(this.page, '/profile'), <API key>(this.page, PageTitle)]);
await waitWhileLoading(this.page);
return true;
}
getFirstNameInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.FirstName });
}
getLastNameInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.LastName });
}
<API key>(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.ProfessionalUrl });
}
<API key>(): Textarea {
return Textarea.findByName(this.page, { normalizeSpace: LabelAlias.ResearchBackground });
}
getAddress1Input(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Address1 });
}
getAddress2Input(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Address2 });
}
getCityInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.City });
}
getStateInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.State });
}
getZipCodeInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Zip });
}
getCountryInput(): Textbox {
return Textbox.findByName(this.page, { dataTestId: DataTestIdAlias.Country });
}
<API key>(): Button {
return Button.findByName(this.page, { name: LabelAlias.SaveProfile });
}
async needsConfirmation(): Promise<boolean> {
return await this.containsText(LabelAlias.NeedsConfirmation);
}
getLooksGoodLink(): Link {
return Link.findByName(this.page, { name: LabelAlias.LooksGood });
}
}
|
// This program sends logging records directly to the server, rather
// than going through the client logging daemon.
#include "ace/SOCK_Connector.h"
#include "ace/Log_Record.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_time.h"
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_unistd.h"
#include "ace/CDR_Stream.h"
static u_short LOGGER_PORT = <API key>;
static const ACE_TCHAR *const LOGGER_HOST = <API key>;
static const ACE_TCHAR *const DATA = ACE_TEXT ("hello world\n");
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
u_short logger_port = argc > 1 ? ACE_OS::atoi (argv[1]) : LOGGER_PORT;
const ACE_TCHAR *logger_host = argc > 2 ? argv[2] : LOGGER_HOST;
ACE_SOCK_Stream logger;
ACE_SOCK_Connector connector;
ACE_INET_Addr addr (logger_port, logger_host);
ACE_Log_Record log_record (LM_DEBUG,
ACE_OS::time ((time_t *) 0),
ACE_OS::getpid ());
if (connector.connect (logger, addr) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "open"), -1);
log_record.msg_data (DATA);
const size_t max_payload_size =
4 // type()
+ 8 // timestamp
+ 4 // process id
+ 4 // data length
+ ACE_Log_Record::MAXLOGMSGLEN // data
+ ACE_CDR::MAX_ALIGNMENT; // padding;
// Insert contents of <log_record> into payload stream.
ACE_OutputCDR payload (max_payload_size);
payload << log_record;
// Get the number of bytes used by the CDR stream.
ACE_CDR::ULong length = payload.total_length ();
// Send a header so the receiver can determine the byte order and
// size of the incoming CDR stream.
ACE_OutputCDR header (ACE_CDR::MAX_ALIGNMENT + 8);
header << ACE_OutputCDR::from_boolean (ACE_CDR_BYTE_ORDER);
// Store the size of the payload that follows
header << ACE_CDR::ULong (length);
// Use an iovec to send both buffer and payload simultaneously.
iovec iov[2];
iov[0].iov_base = header.begin ()->rd_ptr ();
iov[0].iov_len = 8;
iov[1].iov_base = payload.begin ()->rd_ptr ();
iov[1].iov_len = length;
if (logger.sendv_n (iov, 2) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "send"), -1);
else if (logger.close () == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "close"), -1);
#if defined (ACE_WIN32)
// !!Important, Winsock is broken in that if you don't close
// down the connection before exiting main, you'll lose data.
// More over, your server might get "Access Violation" from
// within Winsock functions.
// Here we close down the connection to Logger by redirecting
// the logging destination back to stderr.
ACE_LOG_MSG->open (0, ACE_Log_Msg::STDERR, 0);
#endif /* ACE_WIN32 */
return 0;
}
|
#ifndef SOURCE_HPP
#define SOURCE_HPP
#include <QSpinBox>
#include <QProgressBar>
#include "entity.hpp"
#include "mainwindow.hpp"
class source : virtual public entity {
public:
source(environment* env, QWidget* parent, QString name);
~source() override;
void start() override;
void add_consumer(caf::actor consumer);
protected:
// Pointer to the next stage in the pipeline.
std::vector<caf::actor> consumers_;
// Pointer to the CAF stream handler to advance the stream manually.
caf::stream_manager_ptr stream_manager_;
};
#endif // SOURCE_HPP
|
<?php
namespace app\controllers;
use app\models\User;
use Yii;
use yii\base\<API key>;
use yii\web\<API key>;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\LoginForm;
use app\models\<API key>;
use app\models\ResetPasswordForm;
use app\models\SignupForm;
use app\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => false,
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* @return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* @return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* @return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* @return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
public function actionControl()
{
return $this->render('control');
}
/**
* Signs user up.
*
* @return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Requests password reset.
*
* @return mixed
*/
public function <API key>()
{
$model = new <API key>();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('<API key>', [
'model' => $model,
]);
}
/**
* Resets password.
*
* @param string $token
* @return mixed
* @throws <API key>
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (<API key> $e) {
throw new <API key>($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
public function actionTest()
{
// echo 'text';
/**
* where
* ['name'=>'value'] => WHERE name = value
* 'name = :value',[':value'=>'value'] => WHERE name = value
* [[], [] ...]
* []
*
* Yii::$app->db->createCommand('')
*/
// var_dump(User::find()->where(['id'=>'2'])->asArray()->one());
// var_dump(Yii::$app->db->createCommand('SELECT * FROM user WHERE id=:id')
// ->bindValue(':id',$_GET['id'])
// ->queryOne());
$bannedUsers=User::find()->where('id>=:value and id<:value1',[':value'=>2,':value1'=>4])->asArray()->all();
foreach($bannedUsers as $user){
echo $user['username'];
echo $user['email'].'<br>';
}
}
}
|
var $ = require('jquery');
var CoreView = require('backbone/core-view');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var REQUIRED_OPTS = [
'el'
];
module.exports = CoreView.extend({
events: {
'click .js-foo': '_fooHandler'
},
initialize: function (opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this);
this._onWindowScroll = this._onWindowScroll.bind(this);
this._topBoundary = this.$el.offset().top;
this._initBinds();
},
_initBinds: function () {
this._bindScroll();
},
_onWindowScroll: function () {
this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary);
},
_unbindScroll: function () {
$(window).unbind('scroll', this._onWindowScroll);
},
_bindScroll: function () {
this._unbindScroll();
$(window).bind('scroll', this._onWindowScroll);
},
clean: function () {
this._unbindScroll();
}
});
|
import os
import os.path as op
import pytest
import numpy as np
from numpy.testing import (assert_array_equal, assert_equal, assert_allclose,
assert_array_less, assert_almost_equal)
import itertools
import mne
from mne.datasets import testing
from mne.fixes import _get_img_fdata
from mne import read_trans, write_trans
from mne.io import read_info
from mne.transforms import (invert_transform, _get_trans,
rotation, rotation3d, rotation_angles, _find_trans,
combine_transforms, apply_trans, translation,
<API key>, _pol_to_cart,
quat_to_rot, rot_to_quat, <API key>,
<API key>, _sph_to_cart, _cart_to_sph,
_topo_to_sph, _average_quats,
<API key> as <API key>,
<API key>, _read_fs_xfm,
_write_fs_xfm, _quat_real, _fit_matched_points,
_quat_to_euler, _euler_to_quat,
_quat_to_affine, _compute_r2, _validate_pipeline)
from mne.utils import requires_nibabel, requires_dipy
data_path = testing.data_path(download=False)
fname = op.join(data_path, 'MEG', 'sample', '<API key>.fif')
fname_eve = op.join(data_path, 'MEG', 'sample',
'<API key>.fif')
subjects_dir = op.join(data_path, 'subjects')
fname_t1 = op.join(subjects_dir, 'fsaverage', 'mri', 'T1.mgz')
base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')
fname_trans = op.join(base_dir, '<API key>.txt')
test_fif_fname = op.join(base_dir, 'test_raw.fif')
ctf_fname = op.join(base_dir, 'test_ctf_raw.fif')
hp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')
def test_tps():
"""Test TPS warping."""
az = np.linspace(0., 2 * np.pi, 20, endpoint=False)
pol = np.linspace(0, np.pi, 12)[1:-1]
sph = np.array(np.meshgrid(1, az, pol, indexing='ij'))
sph.shape = (3, -1)
assert_equal(sph.shape[1], 200)
source = _sph_to_cart(sph.T)
destination = source.copy()
destination *= 2
destination[:, 0] += 1
# fit with 100 points
warp = <API key>()
assert 'no ' in repr(warp)
warp.fit(source[::3], destination[::2])
assert 'oct5' in repr(warp)
destination_est = warp.transform(source)
assert_allclose(destination_est, destination, atol=1e-3)
@testing.<API key>
def test_get_trans():
"""Test converting '-trans.txt' to '-trans.fif'."""
trans = read_trans(fname)
trans = invert_transform(trans) # starts out as head->MRI, so invert
trans_2 = _get_trans(fname_trans)[0]
assert trans.__eq__(trans_2, atol=1e-5)
@testing.<API key>
def test_io_trans(tmpdir):
"""Test reading and writing of trans files."""
tempdir = str(tmpdir)
os.mkdir(op.join(tempdir, 'sample'))
pytest.raises(RuntimeError, _find_trans, 'sample', subjects_dir=tempdir)
trans0 = read_trans(fname)
fname1 = op.join(tempdir, 'sample', 'test-trans.fif')
trans0.save(fname1)
assert fname1 == _find_trans('sample', subjects_dir=tempdir)
trans1 = read_trans(fname1)
# check all properties
assert trans0 == trans1
# check reading non -trans.fif files
pytest.raises(IOError, read_trans, fname_eve)
# check warning on bad filenames
fname2 = op.join(tempdir, 'trans-test-bad-name.fif')
with pytest.warns(RuntimeWarning, match='-trans.fif'):
write_trans(fname2, trans0)
def <API key>():
"""Test the coordinate transformation from ras to neuromag."""
# create model points in neuromag-like space
rng = np.random.RandomState(0)
anterior = [0, 1, 0]
left = [-1, 0, 0]
right = [.8, 0, 0]
up = [0, 0, 1]
rand_pts = rng.uniform(-1, 1, (3, 3))
pts = np.vstack((anterior, left, right, up, rand_pts))
# change coord system
rx, ry, rz, tx, ty, tz = rng.uniform(-2 * np.pi, 2 * np.pi, 6)
trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz))
pts_changed = apply_trans(trans, pts)
# transform back into original space
nas, lpa, rpa = pts_changed[:3]
hsp_trans = <API key>(nas, lpa, rpa)
pts_restored = apply_trans(hsp_trans, pts_changed)
err = "Neuromag transformation failed"
assert_allclose(pts_restored, pts, atol=1e-6, err_msg=err)
def <API key>(x, y, z):
"""Convert using old function."""
hypotxy = np.hypot(x, y)
r = np.hypot(hypotxy, z)
elev = np.arctan2(z, hypotxy)
az = np.arctan2(y, x)
return az, elev, r
def <API key>(theta, phi, r):
"""Convert using old function."""
z = r * np.sin(phi)
rcos_phi = r * np.cos(phi)
x = rcos_phi * np.cos(theta)
y = rcos_phi * np.sin(theta)
return x, y, z
def test_sph_to_cart():
"""Test conversion between sphere and cartesian."""
# Simple test, expected value (11, 0, 0)
r, theta, phi = 11., 0., np.pi / 2.
z = r * np.cos(phi)
rsin_phi = r * np.sin(phi)
x = rsin_phi * np.cos(theta)
y = rsin_phi * np.sin(theta)
coord = _sph_to_cart(np.array([[r, theta, phi]]))[0]
assert_allclose(coord, (x, y, z), atol=1e-7)
assert_allclose(coord, (r, 0, 0), atol=1e-7)
rng = np.random.RandomState(0)
# round-trip test
coords = rng.randn(10, 3)
assert_allclose(_sph_to_cart(_cart_to_sph(coords)), coords, atol=1e-5)
# equivalence tests to old versions
for coord in coords:
sph = _cart_to_sph(coord[np.newaxis])
cart = _sph_to_cart(sph)
sph_old = np.array(<API key>(*coord))
cart_old = <API key>(*sph_old)
sph_old[1] = np.pi / 2. - sph_old[1] # new convention
assert_allclose(sph[0], sph_old[[2, 0, 1]], atol=1e-7)
assert_allclose(cart[0], cart_old, atol=1e-7)
assert_allclose(cart[0], coord, atol=1e-7)
def _polar_to_cartesian(theta, r):
"""Transform polar coordinates to cartesian."""
x = r * np.cos(theta)
y = r * np.sin(theta)
return x, y
def <API key>():
"""Test helper transform function from polar to cartesian."""
r = 1
theta = np.pi
# expected values are (-1, 0)
x = r * np.cos(theta)
y = r * np.sin(theta)
coord = _pol_to_cart(np.array([[r, theta]]))[0]
# np.pi is an approx since pi is irrational
assert_allclose(coord, (x, y), atol=1e-7)
assert_allclose(coord, (-1, 0), atol=1e-7)
assert_allclose(coord, _polar_to_cartesian(theta, r), atol=1e-7)
rng = np.random.RandomState(0)
r = rng.randn(10)
theta = rng.rand(10) * (2 * np.pi)
polar = np.array((r, theta)).T
assert_allclose([_polar_to_cartesian(p[1], p[0]) for p in polar],
_pol_to_cart(polar), atol=1e-7)
def _topo_to_phi_theta(theta, radius):
"""Convert using old function."""
sph_phi = (0.5 - radius) * 180
sph_theta = -theta
return sph_phi, sph_theta
def test_topo_to_sph():
"""Test topo to sphere conversion."""
rng = np.random.RandomState(0)
angles = rng.rand(10) * 360
radii = rng.rand(10)
angles[0] = 30
radii[0] = 0.25
# new way
sph = _topo_to_sph(np.array([angles, radii]).T)
new = _sph_to_cart(sph)
new[:, [0, 1]] = new[:, [1, 0]] * [-1, 1]
# old way
for ii, (angle, radius) in enumerate(zip(angles, radii)):
sph_phi, sph_theta = _topo_to_phi_theta(angle, radius)
if ii == 0:
assert_allclose(_topo_to_phi_theta(angle, radius), [45, -30])
azimuth = sph_theta / 180.0 * np.pi
elevation = sph_phi / 180.0 * np.pi
assert_allclose(sph[ii], [1., azimuth, np.pi / 2. - elevation],
atol=1e-7)
r = np.ones_like(radius)
x, y, z = <API key>(azimuth, elevation, r)
pos = [-y, x, z]
if ii == 0:
expected = np.array([1. / 2., np.sqrt(3) / 2., 1.])
expected /= np.sqrt(2)
assert_allclose(pos, expected, atol=1e-7)
assert_allclose(pos, new[ii], atol=1e-7)
def test_rotation():
"""Test conversion between rotation angles and transformation matrix."""
tests = [(0, 0, 1), (.5, .5, .5), (np.pi, 0, -1.5)]
for rot in tests:
x, y, z = rot
m = rotation3d(x, y, z)
m4 = rotation(x, y, z)
assert_array_equal(m, m4[:3, :3])
back = rotation_angles(m)
assert_almost_equal(actual=back, desired=rot, decimal=12)
back4 = rotation_angles(m4)
assert_almost_equal(actual=back4, desired=rot, decimal=12)
def <API key>():
"""Test <API key>."""
# The more complex z axis fails the assert presumably due to tolerance
inp_zs = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, -1],
[-0.75071668, -0.62183808, 0.22302888]]
exp_res = [[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
[[1., 0., 0.], [0., 0., 1.], [0., -1., 0.]],
[[0., 0., 1.], [0., 1., 0.], [-1., 0., 0.]],
[[1., 0., 0.], [0., -1., 0.], [0., 0., -1.]],
[[0.53919688, -0.38169517, -0.75071668],
[-0.38169517, 0.683832, -0.62183808],
[0.75071668, 0.62183808, 0.22302888]]]
for res, z in zip(exp_res, inp_zs):
assert_allclose(res, <API key>(z), atol=1e-7)
@testing.<API key>
def test_combine():
"""Test combining transforms."""
trans = read_trans(fname)
inv = invert_transform(trans)
combine_transforms(trans, inv, trans['from'], trans['from'])
pytest.raises(RuntimeError, combine_transforms, trans, inv,
trans['to'], trans['from'])
pytest.raises(RuntimeError, combine_transforms, trans, inv,
trans['from'], trans['to'])
pytest.raises(RuntimeError, combine_transforms, trans, trans,
trans['from'], trans['to'])
def test_quaternions():
"""Test quaternion calculations."""
rots = [np.eye(3)]
for fname in [test_fif_fname, ctf_fname, hp_fif_fname]:
rots += [read_info(fname)['dev_head_t']['trans'][:3, :3]]
# nasty numerical cases
rots += [np.array([
[-0.99978541, -0.01873462, -0.00898756],
[-0.01873462, 0.62565561, 0.77987608],
[-0.00898756, 0.77987608, -0.62587152],
])]
rots += [np.array([
[0.62565561, -0.01873462, 0.77987608],
[-0.01873462, -0.99978541, -0.00898756],
[0.77987608, -0.00898756, -0.62587152],
])]
rots += [np.array([
[-0.99978541, -0.00898756, -0.01873462],
[-0.00898756, -0.62587152, 0.77987608],
[-0.01873462, 0.77987608, 0.62565561],
])]
for rot in rots:
assert_allclose(rot, quat_to_rot(rot_to_quat(rot)),
rtol=1e-5, atol=1e-5)
rot = rot[np.newaxis, np.newaxis, :, :]
assert_allclose(rot, quat_to_rot(rot_to_quat(rot)),
rtol=1e-5, atol=1e-5)
# let's make sure our angle function works in some reasonable way
for ii in range(3):
for jj in range(3):
a = np.zeros(3)
b = np.zeros(3)
a[ii] = 1.
b[jj] = 1.
expected = np.pi if ii != jj else 0.
assert_allclose(<API key>(a, b), expected, atol=1e-5)
y_180 = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1.]])
assert_allclose(<API key>(rot_to_quat(y_180),
np.zeros(3)), np.pi)
h_180_attitude_90 = np.array([[0, 1, 0], [1, 0, 0], [0, 0, -1.]])
assert_allclose(<API key>(rot_to_quat(h_180_attitude_90),
np.zeros(3)), np.pi)
def <API key>():
"""Test basic rotation matrix math."""
x = np.array([1., 0., 0.])
y = np.array([0., 1., 0.])
rot = <API key>(x, y)
assert_array_equal(rot,
[[0, -1, 0], [1, 0, 0], [0, 0, 1]])
quat_1 = rot_to_quat(rot)
quat_2 = rot_to_quat(np.eye(3))
assert_allclose(<API key>(quat_1, quat_2), np.pi / 2.)
def test_average_quats():
"""Test averaging of quaternions."""
sq2 = 1. / np.sqrt(2.)
quats = np.array([[0, sq2, sq2],
[0, sq2, sq2],
[0, sq2, 0],
[0, 0, sq2],
[sq2, 0, 0]], float)
# In MATLAB:
# quats = [[0, sq2, sq2, 0]; [0, sq2, sq2, 0];
# [0, sq2, 0, sq2]; [0, 0, sq2, sq2]; [sq2, 0, 0, sq2]];
expected = [quats[0],
quats[0],
[0, 0.788675134594813, 0.577350269189626],
[0, 0.657192299694123, 0.657192299694123],
[0.100406058540540, 0.616329446922803, 0.616329446922803]]
# Averaging the first two should give the same thing:
for lim, ex in enumerate(expected):
assert_allclose(_average_quats(quats[:lim + 1]), ex, atol=1e-7)
quats[1] *= -1 # same quaternion (hidden value is zero here)!
rot_0, rot_1 = quat_to_rot(quats[:2])
assert_allclose(rot_0, rot_1, atol=1e-7)
for lim, ex in enumerate(expected):
assert_allclose(_average_quats(quats[:lim + 1]), ex, atol=1e-7)
# Assert some symmetry
count = 0
extras = [[sq2, sq2, 0]] + list(np.eye(3))
for quat in np.concatenate((quats, expected, extras)):
if np.isclose(_quat_real(quat), 0., atol=1e-7): # can flip sign
count += 1
angle = <API key>(quat, -quat)
assert_allclose(angle, 0., atol=1e-7)
rot_0, rot_1 = quat_to_rot(np.array((quat, -quat)))
assert_allclose(rot_0, rot_1, atol=1e-7)
assert count == 4 + len(extras)
@testing.<API key>
@pytest.mark.parametrize('subject', ('fsaverage', 'sample'))
def test_fs_xfm(subject, tmpdir):
"""Test reading and writing of Freesurfer transforms."""
fname = op.join(data_path, 'subjects', subject, 'mri', 'transforms',
'talairach.xfm')
xfm, kind = _read_fs_xfm(fname)
if subject == 'fsaverage':
assert_allclose(xfm, np.eye(4), atol=1e-5) # fsaverage is in MNI
assert kind == 'MNI Transform File'
tempdir = str(tmpdir)
fname_out = op.join(tempdir, 'out.xfm')
_write_fs_xfm(fname_out, xfm, kind)
xfm_read, kind_read = _read_fs_xfm(fname_out)
assert kind_read == kind
assert_allclose(xfm, xfm_read, rtol=1e-5, atol=1e-5)
# Some wacky one
xfm[:3] = np.random.RandomState(0).randn(3, 4)
_write_fs_xfm(fname_out, xfm, 'foo')
xfm_read, kind_read = _read_fs_xfm(fname_out)
assert kind_read == 'foo'
assert_allclose(xfm, xfm_read, rtol=1e-5, atol=1e-5)
# degenerate conditions
with open(fname_out, 'w') as fid:
fid.write('foo')
with pytest.raises(ValueError, match='Failed to find'):
_read_fs_xfm(fname_out)
_write_fs_xfm(fname_out, xfm[:2], 'foo')
with pytest.raises(ValueError, match='Could not find'):
_read_fs_xfm(fname_out)
@pytest.fixture()
def quats():
"""Make some unit quats."""
quats = np.random.RandomState(0).randn(5, 3)
quats[:, 0] = 0 # identity
quats /= 2 * np.linalg.norm(quats, axis=1, keepdims=True) # some real part
return quats
def <API key>(
p, x, weights, do_scale, angtol=1e-5, dtol=1e-5, stol=1e-7):
__tracebackhide__ = True
mne.coreg._ALLOW_ANALITICAL = False
try:
params = mne.coreg.fit_matched_points(
p, x, weights=weights, scale=do_scale, out='params')
finally:
mne.coreg._ALLOW_ANALITICAL = True
quat_an, scale_an = _fit_matched_points(p, x, weights, scale=do_scale)
assert len(params) == 6 + int(do_scale)
q_co = _euler_to_quat(params[:3])
translate_co = params[3:6]
angle = np.rad2deg(<API key>(quat_an[:3], q_co))
dist = np.linalg.norm(quat_an[3:] - translate_co)
assert 0 <= angle < angtol, 'angle'
assert 0 <= dist < dtol, 'dist'
if do_scale:
scale_co = params[6]
assert_allclose(scale_an, scale_co, rtol=stol, err_msg='scale')
# errs
trans = _quat_to_affine(quat_an)
trans[:3, :3] *= scale_an
weights = np.ones(1) if weights is None else weights
err_an = np.linalg.norm(
weights[:, np.newaxis] * apply_trans(trans, p) - x)
trans = mne.coreg._trans_from_params((True, True, do_scale), params)
err_co = np.linalg.norm(
weights[:, np.newaxis] * apply_trans(trans, p) - x)
if err_an > 1e-14:
assert err_an < err_co * 1.5
return quat_an, scale_an
@pytest.mark.parametrize('scaling', [0.25, 1])
@pytest.mark.parametrize('do_scale', (True, False))
def <API key>(quats, scaling, do_scale):
"""Test analytical least-squares matched point fitting."""
if scaling != 1 and not do_scale:
return # no need to test this, it will not be good
rng = np.random.RandomState(0)
fro = rng.randn(10, 3)
translation = rng.randn(3)
for qi, quat in enumerate(quats):
to = scaling * np.dot(quat_to_rot(quat), fro.T).T + translation
for corrupted in (False, True):
# mess up a point
if corrupted:
to[0, 2] += 100
weights = np.ones(len(to))
weights[0] = 0
else:
weights = None
est, scale_est = <API key>(
fro, to, weights=weights, do_scale=do_scale)
assert_allclose(scale_est, scaling, rtol=1e-5)
assert_allclose(est[:3], quat, atol=1e-14)
assert_allclose(est[3:], translation, atol=1e-14)
# if we don't adjust for the corruption above, it should get worse
angle = dist = None
for weighted in (False, True):
if not weighted:
weights = None
dist_bounds = (5, 20)
if scaling == 1:
angle_bounds = (5, 95)
angtol, dtol, stol = 1, 15, 3
else:
angle_bounds = (5, 105)
angtol, dtol, stol = 20, 15, 3
else:
weights = np.ones(len(to))
weights[0] = 10 # weighted=True here means "make it worse"
angle_bounds = (angle, 180) # unweighted values as new min
dist_bounds = (dist, 100)
if scaling == 1:
# XXX this angtol is not great but there is a hard to
# identify linalg/angle calculation bug on Travis...
angtol, dtol, stol = 180, 70, 3
else:
angtol, dtol, stol = 50, 70, 3
est, scale_est = <API key>(
fro, to, weights=weights, do_scale=do_scale,
angtol=angtol, dtol=dtol, stol=stol)
assert not np.allclose(est[:3], quat, atol=1e-5)
assert not np.allclose(est[3:], translation, atol=1e-5)
angle = np.rad2deg(<API key>(est[:3], quat))
assert_array_less(angle_bounds[0], angle)
assert_array_less(angle, angle_bounds[1])
dist = np.linalg.norm(est[3:] - translation)
assert_array_less(dist_bounds[0], dist)
assert_array_less(dist, dist_bounds[1])
def test_euler(quats):
"""Test euler transformations."""
euler = _quat_to_euler(quats)
quats_2 = _euler_to_quat(euler)
assert_allclose(quats, quats_2, atol=1e-14)
quat_rot = quat_to_rot(quats)
euler_rot = np.array([rotation(*e)[:3, :3] for e in euler])
assert_allclose(quat_rot, euler_rot, atol=1e-14)
@requires_nibabel()
@requires_dipy()
@pytest.mark.slowtest
@testing.<API key>
def <API key>():
"""Test volume registration."""
import nibabel as nib
from dipy.align import resample
T1 = nib.load(fname_t1)
affine = np.eye(4)
affine[0, 3] = 10
T1_resampled = resample(moving=T1.get_fdata(),
static=T1.get_fdata(),
moving_affine=T1.affine,
static_affine=T1.affine,
between_affine=np.linalg.inv(affine))
for pipeline in ('rigids', ('translation', 'sdr')):
reg_affine, sdr_morph = mne.transforms.<API key>(
T1_resampled, T1, pipeline=pipeline, zooms=10, niter=[5])
assert_allclose(affine, reg_affine, atol=0.25)
T1_aligned = mne.transforms.<API key>(
T1_resampled, T1, reg_affine, sdr_morph)
r2 = _compute_r2(_get_img_fdata(T1_aligned), _get_img_fdata(T1))
assert 99.9 < r2
# check that all orders of the pipeline work
for pipeline_len in range(1, 5):
for pipeline in itertools.combinations(
('translation', 'rigid', 'affine', 'sdr'), pipeline_len):
_validate_pipeline(pipeline)
_validate_pipeline(list(pipeline))
with pytest.raises(ValueError, match='Steps in pipeline are out of order'):
_validate_pipeline(('sdr', 'affine'))
with pytest.raises(ValueError,
match='Steps in pipeline should not be repeated'):
_validate_pipeline(('affine', 'affine'))
|
package cartago;
/**
* Unique identifier of an operation (instance)
* executed by an artifact
*
* @author aricci
*
*/
public class OpId implements java.io.Serializable {
private int id;
private ArtifactId aid;
private AgentId agentId;
private String opName;
OpId(ArtifactId aid, String opName, int id, AgentId ctxId){
this.id = id;
this.aid = aid;
this.agentId = ctxId;
this.opName = opName;
}
/**
* Get the numeric identifier of the operation id
*
* @return
*/
public int getId(){
return id;
}
/**
* Get the operation name.
*
* @return
*/
public String getOpName(){
return opName;
}
/**
* Get the id of the artifact where the operation has been executed
*
* @return
*/
public ArtifactId getArtifactId(){
return aid;
}
/**
* Get the identifier of the agent performer of the operation
*
* @return
*/
public AgentId getAgentBodyId(){
return agentId;
}
AgentId getContextId(){
return agentId;
}
public boolean equals(Object obj){
return aid.equals(((OpId)obj).aid) && ((OpId)obj).id==id;
}
public String toString(){
return "opId("+id+","+opName+","+aid+","+agentId+")";
}
}
|
<!DOCTYPE html>
<html lang="en" itemscope itemtype="https://schema.org/WebPage">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vitess / GitHub Workflow</title>
<!-- Webfont -->
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<!--<link rel="shortcut icon" type="image/png" href="/favicon.png">-->
<!-- Bootstrap -->
<link href="/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
<!-- Styles -->
<link rel="stylesheet" type="text/css" href="/css/site.css" />
<!-- Font Awesome icons -->
<link href="/libs/font-awesome-4.4.0/css/font-awesome.min.css"
rel="stylesheet"
type="text/css">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/libs/bootstrap/js/bootstrap.min.js"></script>
<!-- metadata -->
<meta name="og:title" content="Vitess / GitHub Workflow"/>
<meta name="og:image" content="/images/<API key>.svg"/>
<meta name="og:description" content="Vitess is a database clustering system for horizontal scaling of MySQL."/>
<link rel="icon" href="/images/vitess_icon.png" type="image/png">
<script>
(function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','
ga('create', 'UA-60219601-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body class="docs" id="top_of_page">
<span id="toc-depth" data-toc-depth="h2,h3"></span>
<nav id="common-nav" class="navbar navbar-fixed-top inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">
<img class="logo" src="/images/<API key>.svg" alt="Vitess">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav navbar-right" id="standard-menu-links">
<li><a href="/overview/">Overview</a></li>
<li><a href="/user-guide/introduction.html">Guides</a></li>
<li><a href="/reference/vitess-api.html">Reference</a></li>
<li><a href="http://blog.vitess.io">Blog</a></li>
<li><a href="https://github.com/youtube/vitess"><i class="fa fa-github"></i> GitHub</a></li>
<!-- Hide link to blog unless we have actual posts -->
<!-- <li><a href="/blog/" title="">Blog</a></li> -->
</ul>
<ul class="nav nav-stacked <API key>" id="collapsed-left-menu">
<li class="submenu">
<h4 class="arrow-r no-top-margin">Overview</h4>
<ul style="display: none">
<li><a href="/overview/">What is Vitess</a></li>
<li><a href="/overview/scaling-mysql.html">Scaling MySQL with Vitess</a></li>
<li><a href="/overview/concepts.html">Key Concepts</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Getting Started</h4>
<ul style="display: none">
<li style="padding-bottom: 0"><a href="/getting-started/">Run Vitess on Kubernetes</a>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/getting-started/docker-build.html">Custom Docker Build</a></li>
</ul>
</li>
<li><a href="/getting-started/local-instance.html">Run Vitess Locally</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">User Guide</h4>
<ul style="display: none">
<li><a href="/user-guide/introduction.html">Introduction</a>
<li><a href="/user-guide/client-libraries.html">Client Libraries</a>
<li><a href="/user-guide/backup-and-restore.html">Backing Up Data</a>
<li><a href="/user-guide/reparenting.html">Reparenting</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/schema-management.html">Schema Management</a></li>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/user-guide/<API key>.html">Pivot Schema Changes (Tutorial)</a></li>
</ul>
<li style="padding-bottom: 0"><a href="/user-guide/sharding.html">Sharding</a>
<ul style="display: block">
<li><a href="/user-guide/horizontal-sharding.html">Horizontal Sharding (Codelab)</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/sharding-kubernetes.html">Sharding in Kubernetes (Codelab)</a></li>
</ul>
</li>
<li><a href="/user-guide/vitess-replication.html">Vitess and Replication</a></li>
<li><a href="/user-guide/topology-service.html">Topology Service</a></li>
<li><a href="/user-guide/<API key>.html">Transport Security Model</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/launching.html">Launching</a>
<ul style="display: block">
<li><a href="/user-guide/<API key>.html">Scalability Philosophy</a></li>
<li><a href="/user-guide/production-planning.html">Production Planning</a></li>
<li><a href="/user-guide/<API key>.html">Server Configuration</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/troubleshooting.html">Troubleshooting</a></li>
</ul>
</li>
<li><a href="/user-guide/upgrading.html">Upgrading</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Reference Guides</h4>
<ul style="display: none">
<li><a href="/reference/vitess-api.html">Vitess API</a>
<li><a href="/reference/vtctl.html">vtctl Commands</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Other Resources</h4>
<ul style="display: none">
<li><a href="/resources/presentations.html">Presentations</a>
<li><a href="http://blog.vitess.io/">Blog</a>
<li><a href="/resources/roadmap.html">Roadmap</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Contributing</h4>
<ul style="display: none">
<li><a href="/contributing/">Contributing to Vitess</a>
<li><a href="/contributing/github-workflow.html">GitHub Workflow</a>
<li><a href="/contributing/code-reviews.html">Code Reviews</a>
</ul>
</li>
<div>
<form method="get" action="/search/">
<input id="search-form" name="q" type="text" placeholder="Search">
</form>
</div>
<li><a href="https://github.com/youtube/vitess" id="<API key>"><i class="fa fa-github"></i> GitHub</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div id="masthead">
<div class="container">
<div class="row">
<div class="col-md-9">
<h1>GitHub Workflow</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row scroll-margin" id="toc-content-row">
<div class="col-md-2" id="leftCol">
<ul class="nav nav-stacked <API key>" id="sidebar">
<li class="submenu">
<h4 class="arrow-r no-top-margin">Overview</h4>
<ul style="display: none">
<li><a href="/overview/">What is Vitess</a></li>
<li><a href="/overview/scaling-mysql.html">Scaling MySQL with Vitess</a></li>
<li><a href="/overview/concepts.html">Key Concepts</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Getting Started</h4>
<ul style="display: none">
<li style="padding-bottom: 0"><a href="/getting-started/">Run Vitess on Kubernetes</a>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/getting-started/docker-build.html">Custom Docker Build</a></li>
</ul>
</li>
<li><a href="/getting-started/local-instance.html">Run Vitess Locally</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">User Guide</h4>
<ul style="display: none">
<li><a href="/user-guide/introduction.html">Introduction</a>
<li><a href="/user-guide/client-libraries.html">Client Libraries</a>
<li><a href="/user-guide/backup-and-restore.html">Backing Up Data</a>
<li><a href="/user-guide/reparenting.html">Reparenting</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/schema-management.html">Schema Management</a></li>
<ul style="display: block">
<li style="padding-bottom: 0"><a href="/user-guide/<API key>.html">Pivot Schema Changes (Tutorial)</a></li>
</ul>
<li style="padding-bottom: 0"><a href="/user-guide/sharding.html">Sharding</a>
<ul style="display: block">
<li><a href="/user-guide/horizontal-sharding.html">Horizontal Sharding (Codelab)</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/sharding-kubernetes.html">Sharding in Kubernetes (Codelab)</a></li>
</ul>
</li>
<li><a href="/user-guide/vitess-replication.html">Vitess and Replication</a></li>
<li><a href="/user-guide/topology-service.html">Topology Service</a></li>
<li><a href="/user-guide/<API key>.html">Transport Security Model</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/launching.html">Launching</a>
<ul style="display: block">
<li><a href="/user-guide/<API key>.html">Scalability Philosophy</a></li>
<li><a href="/user-guide/production-planning.html">Production Planning</a></li>
<li><a href="/user-guide/<API key>.html">Server Configuration</a></li>
<li style="padding-bottom: 0"><a href="/user-guide/troubleshooting.html">Troubleshooting</a></li>
</ul>
</li>
<li><a href="/user-guide/upgrading.html">Upgrading</a></li>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Reference Guides</h4>
<ul style="display: none">
<li><a href="/reference/vitess-api.html">Vitess API</a>
<li><a href="/reference/vtctl.html">vtctl Commands</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Other Resources</h4>
<ul style="display: none">
<li><a href="/resources/presentations.html">Presentations</a>
<li><a href="http://blog.vitess.io/">Blog</a>
<li><a href="/resources/roadmap.html">Roadmap</a>
</ul>
</li>
<li class="submenu">
<h4 class="arrow-r">Contributing</h4>
<ul style="display: none">
<li><a href="/contributing/">Contributing to Vitess</a>
<li><a href="/contributing/github-workflow.html">GitHub Workflow</a>
<li><a href="/contributing/code-reviews.html">Code Reviews</a>
</ul>
</li>
<div>
<form method="get" action="/search/">
<input id="search-form" name="q" type="text" placeholder="Search">
</form>
</div>
</ul>
</div>
<div class="col-md-3" id="rightCol">
<div class="nav nav-stacked" id="tocSidebar">
<div id="toc"></div>
</div>
</div>
<div class="col-md-7" id="centerCol">
<div id="centerTextCol">
<h1 id="github-workflow">GitHub Workflow</h1>
<p>If you are new to Git and GitHub, we recommend to read this page. Otherwise, you may skip it.</p>
<p>Our GitHub workflow is a so called triangular workflow:</p>
<p><img src="https://cloud.githubusercontent.com/assets/1319791/8943755/<API key>.png" alt="visualization of the GitHub triangular workflow" style="width: 100%;"/></p>
<p><em>Image Source:</em> <a href="https:
<p>You develop and commit your changes in a clone of our upstream repository
(<code class="prettyprint">local</code>). Then you push your changes to your forked repository (<code class="prettyprint">origin</code>) and
send us a pull request. Eventually, we will merge your pull request back into
the <code class="prettyprint">upstream</code> repository.</p>
<h2 id="remotes">Remotes</h2>
<p>Since you should have cloned the repository from your fork, the <code class="prettyprint">origin</code> remote
should look like this:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git remote -v
origin git@github.com:<yourname>/vitess.git (fetch)
origin git@github.com:<yourname>/vitess.git (push)
</code></pre></div>
<p>To help you keep your fork in sync with the main repo, add an <code class="prettyprint">upstream</code> remote:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git remote add upstream git@github.com:youtube/vitess.git
$ git remote -v
origin git@github.com:<yourname>/vitess.git (fetch)
origin git@github.com:<yourname>/vitess.git (push)
upstream git@github.com:youtube/vitess.git (fetch)
upstream git@github.com:youtube/vitess.git (push)
</code></pre></div>
<p>Now to sync your local <code class="prettyprint">master</code> branch, do this:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout master
(master) $ git pull upstream master
</code></pre></div>
<p>Note: In the example output above we prefixed the prompt with <code class="prettyprint">(master)</code> to
stress the fact that the command must be run from the branch <code class="prettyprint">master</code>.</p>
<p>You can omit the <code class="prettyprint">upstream master</code> from the <code class="prettyprint">git pull</code> command when you let your
<code class="prettyprint">master</code> branch always track the main <code class="prettyprint">youtube/vitess</code> repository. To achieve
this, run this command once:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(master) $ git branch --set-upstream-to=upstream/master
</code></pre></div>
<p>Now the following command syncs your local <code class="prettyprint">master</code> branch as well:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(master) $ git pull
</code></pre></div>
<h2 id="topic-branches">Topic Branches</h2>
<p>Before you start working on changes, create a topic branch:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout master
(master) $ git pull
(master) $ git checkout -b new-feature
(new-feature) $ # You are now in the new-feature branch.
</code></pre></div>
<p>Try to commit small pieces along the way as you finish them, with an explanation
of the changes in the commit message. As you work in a package, you can run just
the unit tests for that package by running <code class="prettyprint">go test</code> from within that package.</p>
<p>When you're ready to test the whole system, run the full test suite with <code class="prettyprint">make
test</code> from the root of the Git tree.
If you haven't installed all dependencies for <code class="prettyprint">make test</code>, you can rely on the Travis CI test results as well.
These results will be linked on your pull request.</p>
<h2 id="<API key>">Sending Pull Requests</h2>
<p>Push your branch to the repository (and set it to track with <code class="prettyprint">-u</code>):</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(new-feature) $ git push -u origin new-feature
</code></pre></div>
<p>You can omit <code class="prettyprint">origin</code> and <code class="prettyprint">-u new-feature</code> parameters from the <code class="prettyprint">git push</code>
command with the following two Git configuration changes:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git config remote.pushdefault origin
$ git config push.default current
</code></pre></div>
<p>The first setting saves you from typing <code class="prettyprint">origin</code> every time. And with the second
setting, Git assumes that the remote branch on the GitHub side will have the
same name as your local branch.</p>
<p>After this change, you can run <code class="prettyprint">git push</code> without arguments:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">(new-feature) $ git push
</code></pre></div>
<p>Then go to the <a href="https://github.com/youtube/vitess">repository page</a> and it
should prompt you to create a Pull Request from a branch you recently pushed.
You can also <a href="https://github.com/youtube/vitess/compare">choose a branch manually</a>.</p>
<h2 id="addressing-changes">Addressing Changes</h2>
<p>If you need to make changes in response to the reviewer's comments, just make
another commit on your branch and then push it again:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">$ git checkout new-feature
(new-feature) $ git commit
(new-feature) $ git push
</code></pre></div>
<p>That is because a pull request always mirrors all commits from your topic branch which are not in the master branch.</p>
<p>After you merge, close the issue (if it wasn't automatically closed) and delete
the topic branch.</p>
</div>
</div>
</div>
</div>
<div class="page-spacer"></div>
<footer role="contentinfo" id="site-footer">
<nav role="navigation" class="menu bottom-menu">
<a href="https:
<a href="https:
&
</nav>
</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- Include all compiled plugins (below), or include individual files as needed -->
<!
<script src="/libs/bootstrap/js/bootstrap.min.js"></script>
<!-- Include the common site javascript -->
<script src="/js/common.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20131203141255) do
create_table "alchemy_attachments", :force => true do |t|
t.string "name"
t.string "file_name"
t.string "file_mime_type"
t.integer "file_size"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.text "cached_tag_list"
t.string "file_uid"
end
add_index "alchemy_attachments", ["file_uid"], :name => "<API key>"
create_table "alchemy_cells", :force => true do |t|
t.integer "page_id"
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "alchemy_contents", :force => true do |t|
t.string "name"
t.string "essence_type"
t.integer "essence_id"
t.integer "element_id"
t.integer "position"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "alchemy_contents", ["element_id", "position"], :name => "<API key>"
create_table "alchemy_elements", :force => true do |t|
t.string "name"
t.integer "position"
t.integer "page_id"
t.boolean "public", :default => true
t.boolean "folded", :default => false
t.boolean "unique", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.integer "cell_id"
t.text "cached_tag_list"
end
add_index "alchemy_elements", ["page_id", "position"], :name => "<API key>"
create_table "<API key>", :id => false, :force => true do |t|
t.integer "element_id"
t.integer "page_id"
end
create_table "<API key>", :force => true do |t|
t.boolean "value"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "<API key>", ["value"], :name => "<API key>"
create_table "<API key>", :force => true do |t|
t.datetime "date"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.integer "attachment_id"
t.string "title"
t.string "css_class"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.text "source"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.string "link"
t.string "link_title"
t.string "link_target"
t.string "link_class_name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
create_table "<API key>", :force => true do |t|
t.integer "picture_id"
t.string "caption"
t.string "title"
t.string "alt_tag"
t.string "link"
t.string "link_class_name"
t.string "link_title"
t.string "css_class"
t.string "link_target"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "crop_from"
t.string "crop_size"
t.string "render_size"
end
create_table "<API key>", :force => true do |t|
t.text "body"
t.text "stripped_body"
t.boolean "do_not_index", :default => false
t.boolean "public"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.string "value"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
end
add_index "<API key>", ["value"], :name => "<API key>"
create_table "<API key>", :force => true do |t|
t.text "body"
t.string "link"
t.string "link_title"
t.string "link_class_name"
t.boolean "public", :default => false
t.boolean "do_not_index", :default => false
t.string "link_target"
t.integer "creator_id"
t.integer "updater_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "<API key>", :force => true do |t|
t.integer "page_id"
t.integer "user_id"
t.boolean "folded", :default => false
end
create_table "alchemy_languages", :force => true do |t|
t.string "name"
t.string "language_code"
t.string "frontpage_name"
t.string "page_layout", :default => "intro"
t.boolean "public", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.boolean "default", :default => false
t.string "country_code", :default => "", :null => false
t.integer "site_id"
end
add_index "alchemy_languages", ["language_code", "country_code"], :name => "<API key>"
add_index "alchemy_languages", ["language_code"], :name => "<API key>"
add_index "alchemy_languages", ["site_id"], :name => "<API key>"
create_table "<API key>", :force => true do |t|
t.string "urlname", :null => false
t.integer "page_id", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "<API key>", ["urlname"], :name => "<API key>"
create_table "alchemy_pages", :force => true do |t|
t.string "name"
t.string "urlname"
t.string "title"
t.string "language_code"
t.boolean "language_root"
t.string "page_layout"
t.text "meta_keywords"
t.text "meta_description"
t.integer "lft"
t.integer "rgt"
t.integer "parent_id"
t.integer "depth"
t.boolean "visible", :default => false
t.boolean "public", :default => false
t.boolean "locked", :default => false
t.integer "locked_by"
t.boolean "restricted", :default => false
t.boolean "robot_index", :default => true
t.boolean "robot_follow", :default => true
t.boolean "sitemap", :default => true
t.boolean "layoutpage", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.integer "language_id"
t.text "cached_tag_list"
end
add_index "alchemy_pages", ["language_id"], :name => "<API key>"
add_index "alchemy_pages", ["parent_id", "lft"], :name => "<API key>"
add_index "alchemy_pages", ["urlname"], :name => "<API key>"
create_table "alchemy_pictures", :force => true do |t|
t.string "name"
t.string "image_file_name"
t.integer "image_file_width"
t.integer "image_file_height"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.string "upload_hash"
t.text "cached_tag_list"
t.string "image_file_uid"
t.integer "image_file_size"
end
create_table "alchemy_sites", :force => true do |t|
t.string "host"
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "public", :default => false
t.text "aliases"
t.boolean "<API key>"
end
add_index "alchemy_sites", ["host", "public"], :name => "<API key>"
add_index "alchemy_sites", ["host"], :name => "<API key>"
create_table "alchemy_users", :force => true do |t|
t.string "firstname"
t.string "lastname"
t.string "login"
t.string "email"
t.string "gender"
t.string "roles", :default => "registered"
t.string "language"
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "password_salt", :limit => 128, :default => "", :null => false
t.integer "sign_in_count", :default => 0, :null => false
t.integer "failed_attempts", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "creator_id"
t.integer "updater_id"
t.text "cached_tag_list"
t.string "<API key>"
t.datetime "<API key>"
end
add_index "alchemy_users", ["email"], :name => "<API key>", :unique => true
add_index "alchemy_users", ["login"], :name => "<API key>", :unique => true
add_index "alchemy_users", ["<API key>"], :name => "<API key>", :unique => true
add_index "alchemy_users", ["roles"], :name => "<API key>"
create_table "events", :force => true do |t|
t.string "name"
t.string "hidden_name"
t.datetime "starts_at"
t.datetime "ends_at"
t.text "description"
t.decimal "entrance_fee", :precision => 6, :scale => 2
t.boolean "published"
t.integer "location_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "locations", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "<API key>"
add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "<API key>"
create_table "tags", :force => true do |t|
t.string "name"
end
end
|
package team.gif;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import team.gif.commands.*;
public class OI {
public static final Joystick leftStick = new Joystick(1);
public static final rightStick = new Joystick(2);
public static final auxStick = new Joystick(3);
private final Button leftTrigger = new JoystickButton(leftStick, 1);
private final Button right2 = new JoystickButton(rightStick, 2);
private final Button right3 = new JoystickButton(rightStick, 3);
private final Button right6 = new JoystickButton(rightStick, 6);
private final Button right7 = new JoystickButton(rightStick, 7);
public static final Button auxTrigger = new JoystickButton(rightStick, 1);
public OI() {
leftTrigger.whileHeld(new ShifterHigh());
right2.whileHeld(new CollectorReceive());
right2.whenPressed(new EarsOpen());
right3.whileHeld(new CollectorPass());
right3.whenPressed(new EarsOpen());
right3.whenReleased(new CollectorStandby());
right3.whenReleased(new EarsClosed());
right6.whileHeld(new BumperUp());
right7.whileHeld(new CollectorRaise());
}
}
|
<?php
namespace app\modules\currency\models\ar;
/**
* This is the model class for table "currency".
*
* @property integer $id
* @property string $code
* @property string $short_name
* @property string $sign
*/
class Currency extends \app\modules\core\db\ActiveRecord
{
const EUR = 'EUR';
const RUB = 'RUB';
const UAH = 'UAH';
const USD = 'USD';
/**
* @inheritdoc
*/
public static function tableName()
{
return 'currency';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['code', 'short_name'], 'required'],
[['code'], 'string', 'max' => 3],
[['sign'], 'string', 'max' => 12],
[['short_name'], 'string', 'max' => 8],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'code' => 'Код',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRates()
{
return $this->hasMany(CurrencyRate::className(), ['src_id' => 'id']);
}
/**
* Returns currency symbol by its code.
* @param string $code
* @return string mixed
*/
public static function getSignByCode($code)
{
$signs = [self::UAH => '₴', self::USD => '$', self::EUR => '€', self::RUB => '₽'];
return $signs[$code];
}
/**
* Returns full currency name in prepositional case.
* @param string $code
* @return string
*/
public static function <API key>($code)
{
$signs = [self::UAH => 'гривнах', self::USD => 'долларах', self::EUR => 'евро', self::RUB => 'рублях'];
return $signs[$code];
}
}
|
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from brambling.utils.payment import <API key>
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--days',
action='store',
dest='days',
default=15,
help='Number of days ahead of time to update refresh tokens.'),
)
def handle(self, *args, **options):
try:
days = int(options['days'])
except ValueError:
raise CommandError("Days must be an integer value.")
self.stdout.write("Updating dwolla tokens...")
self.stdout.flush()
count, test_count = <API key>(days)
self.stdout.write("Test tokens updated: {}".format(count))
self.stdout.write("Live tokens updated: {}".format(test_count))
self.stdout.flush()
|
# -*- coding: utf-8 -*-
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
<API key> = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(<API key>, verbose=False)
raw.crop(tmax=60).load_data()
raw.pick(['EEG 0{:02}'.format(n) for n in range(41, 60)])
# Background
# EEG measures a voltage (difference in electric potential) between each
# electrode and a reference electrode. This means that whatever signal is
# present at the reference electrode is effectively subtracted from all the
# measurement electrodes. Therefore, an ideal reference signal is one that
# captures *none* of the brain-specific fluctuations in electric potential,
# while capturing *all* of the environmental noise/interference that is being
# picked up by the measurement electrodes.
# In practice, this means that the reference electrode is often placed in a
# location on the subject's body and close to their head (so that any
# environmental interference affects the reference and measurement electrodes
# similarly) but as far away from the neural sources as possible (so that the
# reference signal doesn't pick up brain-based fluctuations). Typical reference
# locations are the subject's earlobe, nose, mastoid process, or collarbone.
# Each of these has advantages and disadvantages regarding how much brain
# signal it picks up (e.g., the mastoids pick up a fair amount compared to the
# others), and regarding the environmental noise it picks up (e.g., earlobe
# electrodes may shift easily, and have signals more similar to electrodes on
# the same side of the head).
# Even in cases where no electrode is specifically designated as the reference,
# EEG recording hardware will still treat one of the scalp electrodes as the
# reference, and the recording software may or may not display it to you (it
# might appear as a completely flat channel, or the software might subtract out
# the average of all signals before displaying, making it *look like* there is
# no reference).
# Setting or changing the reference channel
# If you want to recompute your data with a different reference than was used
# when the raw data were recorded and/or saved, MNE-Python provides the
# :meth:`~mne.io.Raw.set_eeg_reference` method on :class:`~mne.io.Raw` objects
# as well as the :func:`mne.<API key>` function. To use an
# existing channel as the new reference, use the
# :meth:`~mne.io.Raw.set_eeg_reference` method; you can also designate multiple
# existing electrodes as reference channels, as is sometimes done with mastoid
# references:
# code lines below are commented out because the sample data doesn't have
# earlobe or mastoid channels, so this is just for demonstration purposes:
# use a single channel reference (left earlobe)
# raw.set_eeg_reference(ref_channels=['A1'])
# use average of mastoid channels as reference
# raw.set_eeg_reference(ref_channels=['M1', 'M2'])
# If a scalp electrode was used as reference but was not saved alongside the
# raw data (reference channels often aren't), you may wish to add it back to
# the dataset before re-referencing. For example, if your EEG system recorded
# with channel ``Fp1`` as the reference but did not include ``Fp1`` in the data
# file, using :meth:`~mne.io.Raw.set_eeg_reference` to set (say) ``Cz`` as the
# new reference will then subtract out the signal at ``Cz`` *without restoring
# the signal at* ``Fp1``. In this situation, you can add back ``Fp1`` as a flat
# channel prior to re-referencing using :func:`~mne.<API key>`.
# (Since our example data doesn't use the `10-20 electrode naming system`_, the
# example below adds ``EEG 999`` as the missing reference, then sets the
# reference to ``EEG 050``.) Here's how the data looks in its original state:
raw.plot()
# By default, :func:`~mne.<API key>` returns a copy, so we can go
# back to our original ``raw`` object later. If you wanted to alter the
# existing :class:`~mne.io.Raw` object in-place you could specify
# ``copy=False``.
# add new reference channel (all zero)
raw_new_ref = mne.<API key>(raw, ref_channels=['EEG 999'])
raw_new_ref.plot()
# .. KEEP THESE BLOCKS SEPARATE SO FIGURES ARE BIG ENOUGH TO READ
# set reference to `EEG 050`
raw_new_ref.set_eeg_reference(ref_channels=['EEG 050'])
raw_new_ref.plot()
# Notice that the new reference (``EEG 050``) is now flat, while the original
# reference channel that we added back to the data (``EEG 999``) has a non-zero
# signal. Notice also that ``EEG 053`` (which is marked as "bad" in
# ``raw.info['bads']``) is not affected by the re-referencing.
# Setting average reference
# To set a "virtual reference" that is the average of all channels, you can use
# :meth:`~mne.io.Raw.set_eeg_reference` with ``ref_channels='average'``. Just
# as above, this will not affect any channels marked as "bad", nor will it
# include bad channels when computing the average. However, it does modify the
# :class:`~mne.io.Raw` object in-place, so we'll make a copy first so we can
# still go back to the unmodified :class:`~mne.io.Raw` object later:
# <API key> = 4
# use the average of all channels as reference
raw_avg_ref = raw.copy().set_eeg_reference(ref_channels='average')
raw_avg_ref.plot()
# Creating the average reference as a projector
# If using an average reference, it is possible to create the reference as a
# :term:`projector` rather than subtracting the reference from the data
# immediately by specifying ``projection=True``:
raw.set_eeg_reference('average', projection=True)
print(raw.info['projs'])
# Creating the average reference as a projector has a few advantages:
# 1. It is possible to turn projectors on or off when plotting, so it is easy
# to visualize the effect that the average reference has on the data.
# 2. If additional channels are marked as "bad" or if a subset of channels are
# later selected, the projector will be re-computed to take these changes
# into account (thus guaranteeing that the signal is zero-mean).
# 3. If there are other unapplied projectors affecting the EEG channels (such
# as SSP projectors for removing heartbeat or blink artifacts), EEG
# re-referencing cannot be performed until those projectors are either
# applied or removed; adding the EEG reference as a projector is not subject
# to that constraint. (The reason this wasn't a problem when we applied the
# non-projector average reference to ``raw_avg_ref`` above is that the
# empty-room projectors included in the sample data :file:`.fif` file were
# only computed for the magnetometers.)
for title, proj in zip(['Original', 'Average'], [False, True]):
fig = raw.plot(proj=proj, n_channels=len(raw))
# make room for title
fig.subplots_adjust(top=0.9)
fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold')
# EEG reference and source modeling
# If you plan to perform source modeling (either with EEG or combined EEG/MEG
# data), it is **strongly recommended** to use the
# <API key> approach. It is important to use an average
# reference because using a specific
# reference sensor (or even an average of a few sensors) spreads the forward
# model error from the reference sensor(s) into all sensors, effectively
# amplifying the importance of the reference sensor(s) when computing source
# estimates. In contrast, using the average of all EEG channels as reference
# spreads the forward modeling error evenly across channels, so no one channel
# is weighted more strongly during source estimation. See also this `FieldTrip
# FAQ on average referencing`_ for more information.
# The main reason for specifying the average reference as a projector was
# mentioned in the previous section: an average reference projector adapts if
# channels are dropped, ensuring that the signal will always be zero-mean when
# the source modeling is performed. In contrast, applying an average reference
# by the traditional subtraction method offers no such guarantee.
# For these reasons, when performing inverse imaging, *MNE-Python will
# automatically average-reference the EEG channels if they are present and no
# reference strategy has been specified*. If you want to perform inverse
# imaging and do not want to use an average reference (and hence you accept the
# risks presented in the previous paragraphs), you can force MNE-Python to
# relax its average reference requirement by passing an empty list to
# :meth:`~mne.io.Raw.set_eeg_reference` (i.e., by calling
# ``raw.set_eeg_reference(ref_channels=[])``) prior to performing inverse
# imaging.
# .. LINKS
# .. _`FieldTrip FAQ on average referencing`:
# .. _`10-20 electrode naming system`:
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of hiDOF, Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// 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.
\author Adolfo Rodriguez Tsouroukdissian
#include <string>
#include <gtest/gtest.h>
#include <ros/console.h>
#include <hardware_interface/<API key>.h>
using std::string;
using namespace hardware_interface;
TEST(<API key>, HandleConstruction)
{
string name = "name1";
double pos, vel, eff;
double cmd_pos, cmd_vel, cmd_acc;
EXPECT_NO_THROW(<API key> tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, &cmd_vel, &cmd_acc));
EXPECT_THROW(<API key> tmp(JointStateHandle(name, &pos, &vel, &eff), nullptr, &cmd_vel, &cmd_acc), <API key>);
EXPECT_THROW(<API key> tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, nullptr, &cmd_acc), <API key>);
EXPECT_THROW(<API key> tmp(JointStateHandle(name, &pos, &vel, &eff), &cmd_pos, &cmd_vel, nullptr), <API key>);
// Print error messages
// Requires manual output inspection, but exception message should be descriptive
try {<API key> tmp(JointStateHandle(name, &pos, &vel, &eff), nullptr, nullptr, nullptr);}
catch(const <API key>& e) {ROS_ERROR_STREAM(e.what());}
}
#ifndef NDEBUG // NOTE: This test validates assertion triggering, hence only gets compiled in debug mode
TEST(<API key>, AssertionTriggering)
{
<API key> h;
// Data with invalid pointers should trigger an assertion
EXPECT_DEATH(h.getPosition(), ".*");
EXPECT_DEATH(h.getVelocity(), ".*");
EXPECT_DEATH(h.getEffort(), ".*");
EXPECT_DEATH(h.getCommandPosition(), ".*");
EXPECT_DEATH(h.getCommandVelocity(), ".*");
EXPECT_DEATH(h.<API key>(), ".*");
EXPECT_DEATH(h.setCommandPosition(2.0), ".*");
EXPECT_DEATH(h.setCommandVelocity(3.0), ".*");
EXPECT_DEATH(h.<API key>(4.0), ".*");
EXPECT_DEATH(h.setCommand(1.0, 2.0, 3.0), ".*");
}
#endif // NDEBUG
class <API key> : public ::testing::Test
{
protected:
double pos1 = {1.0}, vel1 = {2.0}, eff1 = {3.0}, cmd_pos1 = {0.0}, cmd_vel1 = {0.0}, cmd_acc1 = {0.0};
double pos2 = {4.0}, vel2 = {5.0}, eff2 = {6.0}, cmd_pos2 = {0.0}, cmd_vel2 = {0.0}, cmd_acc2 = {0.0};
string name1 = {"name_1"};
string name2 = {"name_2"};
JointStateHandle hs1 = {name1, &pos1, &vel1, &eff1};
JointStateHandle hs2 = {name2, &pos2, &vel2, &eff2};
<API key> hc1 = {hs1, &cmd_pos1, &cmd_vel1, &cmd_acc1};
<API key> hc2 = {hs2, &cmd_pos2, &cmd_vel2, &cmd_acc2};
};
TEST_F(<API key>, ExcerciseApi)
{
<API key> iface;
iface.registerHandle(hc1);
iface.registerHandle(hc2);
// Get handles
EXPECT_NO_THROW(iface.getHandle(name1));
EXPECT_NO_THROW(iface.getHandle(name2));
<API key> hc1_tmp = iface.getHandle(name1);
EXPECT_EQ(name1, hc1_tmp.getName());
EXPECT_DOUBLE_EQ(pos1, hc1_tmp.getPosition());
EXPECT_DOUBLE_EQ(vel1, hc1_tmp.getVelocity());
EXPECT_DOUBLE_EQ(eff1, hc1_tmp.getEffort());
EXPECT_DOUBLE_EQ(cmd_pos1, hc1_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(cmd_vel1, hc1_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(cmd_acc1, hc1_tmp.<API key>());
const double new_cmd_pos1 = -1.0, new_cmd_vel1 = -2.0, new_cmd_acc1 = -3.0;
hc1_tmp.setCommand(new_cmd_pos1, new_cmd_vel1, new_cmd_acc1);
EXPECT_DOUBLE_EQ(new_cmd_pos1, hc1_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(new_cmd_vel1, hc1_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(new_cmd_acc1, hc1_tmp.<API key>());
<API key> hc2_tmp = iface.getHandle(name2);
EXPECT_EQ(name2, hc2_tmp.getName());
EXPECT_DOUBLE_EQ(pos2, hc2_tmp.getPosition());
EXPECT_DOUBLE_EQ(vel2, hc2_tmp.getVelocity());
EXPECT_DOUBLE_EQ(eff2, hc2_tmp.getEffort());
EXPECT_DOUBLE_EQ(cmd_pos2, hc2_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(cmd_vel2, hc2_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(cmd_acc2, hc2_tmp.<API key>());
const double new_cmd_pos2 = -1.0, new_cmd_vel2 = -2.0, new_cmd_acc2 = -3.0;
hc2_tmp.setCommand(new_cmd_pos2, new_cmd_vel2, new_cmd_acc2);
EXPECT_DOUBLE_EQ(new_cmd_pos2, hc2_tmp.getCommandPosition());
EXPECT_DOUBLE_EQ(new_cmd_vel2, hc2_tmp.getCommandVelocity());
EXPECT_DOUBLE_EQ(new_cmd_acc2, hc2_tmp.<API key>());
// This interface claims resources
EXPECT_EQ(2, iface.getClaims().size());
// Print error message
// Requires manual output inspection, but exception message should contain the interface name (not its base clase)
try {iface.getHandle("unknown_name");}
catch(const <API key>& e) {ROS_ERROR_STREAM(e.what());}
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
package gov.nih.nci.cdmsconnector.c3d.service.globus.resource;
import gov.nih.nci.cdmsconnector.c3d.common.<API key>;
import gov.nih.nci.cdmsconnector.c3d.stubs.<API key>;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.<API key>;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceContext;
import gov.nih.nci.cagrid.introduce.servicetools.<API key>;
import org.globus.wsrf.jndi.Initializable;
public class <API key> extends <API key> implements Initializable {
static final Log logger = LogFactory.getLog(<API key>.class);
private static final UUIDGen UUIDGEN = UUIDGenFactory.getUUIDGen();
public Resource createSingleton() {
logger.info("Creating a single resource.");
try {
<API key> props = new <API key>();
<API key> resource = new <API key>();
if (resource instanceof PersistenceCallback) {
//try to load the resource if it was persisted
try{
((PersistenceCallback) resource).load(null);
} catch (<API key> ex){
//persisted singleton resource was not found so we will just create a new one
resource.initialize(props, <API key>.<API key>, UUIDGEN.nextUUID());
}
} else {
resource.initialize(props, <API key>.<API key>, UUIDGEN.nextUUID());
}
return resource;
} catch (Exception e) {
logger.error("Exception when creating the resource",e);
return null;
}
}
public Resource find(ResourceKey key) throws ResourceException {
<API key> resource = (<API key>) super.find(key);
return resource;
}
/**
* Initialze the singleton resource, when the home is initialized.
*/
public void initialize() throws Exception {
logger.info("Attempting to initialize resource.");
Resource resource = find(null);
if (resource == null) {
logger.error("Unable to initialize resource!");
} else {
logger.info("Successfully initialized resource.");
}
}
/**
* Get the resouce that is being addressed in this current context
*/
public <API key> <API key>() throws Exception {
<API key> thisResource;
thisResource = (<API key>) ResourceContext.getResourceContext().getResource();
return thisResource;
}
}
|
// Use of this source code is governed by a BSD-style
(function() {
"use strict";
var runFunc;
var count = 0;
function getId() {
return "code" + (count++);
}
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var id = getId();
var output = document.createElement('div');
var outpre = document.createElement('pre');
var stopFunc;
function onKill() {
if (stopFunc) {
stopFunc();
}
}
function onRun(e) {
onKill();
outpre.innerHTML = "";
output.style.display = "block";
run.style.display = "none";
var options = {Race: e.shiftKey};
stopFunc = runFunc(text(code), outpre, options);
}
function onClose() {
onKill();
output.style.display = "none";
run.style.display = "inline-block";
}
var run = document.createElement('button');
run.innerHTML = 'Run';
run.className = 'run';
run.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);
buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
if (play.length > 0) {
if (window.connectPlayground) {
runFunc = window.connectPlayground("ws://" + window.location.host + "/socket");
} else {
// If this message is logged,
// we have neglected to include socket.js or playground.js.
console.log("No playground transport available.");
}
}
})();
|
#define _PAS2_MIXER_C_
#include <i386/isa/sound/sound_config.h>
#if defined(CONFIG_PAS)
#include <i386/isa/sound/pas_hw.h>
#define TRACE(what) /* (what) */
extern int translat_code;
extern char pas_model;
extern sound_os_info *pas_osp;
static int rec_devices = (SOUND_MASK_MIC); /* Default recording source */
static int mode_control = 0;
#define <API key> (SOUND_MASK_SYNTH | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | SOUND_MASK_ALTPCM)
#define <API key> (SOUND_MASK_SYNTH | SOUND_MASK_PCM | SOUND_MASK_SPEAKER | SOUND_MASK_LINE | SOUND_MASK_MIC | \
SOUND_MASK_CD | SOUND_MASK_ALTPCM | SOUND_MASK_IMIX | \
SOUND_MASK_VOLUME | SOUND_MASK_BASS | SOUND_MASK_TREBLE | SOUND_MASK_RECLEV | \
SOUND_MASK_MUTE | SOUND_MASK_ENHANCE | SOUND_MASK_LOUD)
static u_short levels[<API key>] =
{
0x3232, /* Master Volume */
0x3232, /* Bass */
0x3232, /* Treble */
0x5050,
0x4b4b, /* PCM */
0x3232, /* PC Speaker */
0x4b4b, /* Ext Line */
0x4b4b, /* Mic */
0x4b4b,
0x6464, /* Recording monitor */
0x4b4b, /* SB PCM */
0x6464 /* Recording level */
};
void
mix_write(u_char data, int ioaddr)
{
/*
* The Revision D cards have a problem with their MVA508 interface.
* The kludge-o-rama fix is to make a 16-bit quantity with identical
* LSB and MSBs out of the output byte and to do a 16-bit out to the
* mixer port - 1. We need to do this because it isn't timing problem
* but chip access sequence problem.
*/
if (pas_model == PAS_16D) {
outw((ioaddr ^ translat_code) - 1, data | (data << 8));
outb(0, 0x80);
} else
pas_write(data, ioaddr);
}
static int
mixer_output(int right_vol, int left_vol, int div, int bits,
int mixer)
{ /* Input or output mixer */
int left = left_vol * div / 100;
int right = right_vol * div / 100;
if (bits & P_M_MV508_MIXER) { /* Select input or output mixer */
left |= mixer;
right |= mixer;
}
if (bits == P_M_MV508_BASS || bits == P_M_MV508_TREBLE) { /* Bass and treble are
* mono devices */
mix_write(P_M_MV508_ADDRESS | bits, PARALLEL_MIXER);
mix_write(left, PARALLEL_MIXER);
right_vol = left_vol;
} else {
mix_write(P_M_MV508_ADDRESS | P_M_MV508_LEFT | bits, PARALLEL_MIXER);
mix_write(left, PARALLEL_MIXER);
mix_write(P_M_MV508_ADDRESS | P_M_MV508_RIGHT | bits, PARALLEL_MIXER);
mix_write(right, PARALLEL_MIXER);
}
return (left_vol | (right_vol << 8));
}
static void
set_mode(int new_mode)
{
mix_write(P_M_MV508_ADDRESS | P_M_MV508_MODE, PARALLEL_MIXER);
mix_write(new_mode, PARALLEL_MIXER);
mode_control = new_mode;
}
static int
pas_mixer_set(int whichDev, u_int level)
{
int left, right, devmask, changed, i, mixer = 0;
TRACE(printf("static int pas_mixer_set(int whichDev = %d, u_int level = %X)\n", whichDev, level));
left = level & 0x7f;
right = (level & 0x7f00) >> 8;
if (whichDev < <API key>)
if ((1 << whichDev) & rec_devices)
mixer = P_M_MV508_INPUTMIX;
else
mixer = P_M_MV508_OUTPUTMIX;
switch (whichDev) {
case SOUND_MIXER_VOLUME: /* Master volume (0-63) */
levels[whichDev] = mixer_output(right, left, 63, P_M_MV508_MASTER_A, 0);
break;
/*
* Note! Bass and Treble are mono devices. Will use just the
* left channel.
*/
case SOUND_MIXER_BASS: /* Bass (0-12) */
levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_BASS, 0);
break;
case SOUND_MIXER_TREBLE: /* Treble (0-12) */
levels[whichDev] = mixer_output(right, left, 12, P_M_MV508_TREBLE, 0);
break;
case SOUND_MIXER_SYNTH:/* Internal synthesizer (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_FM, mixer);
break;
case SOUND_MIXER_PCM: /* PAS PCM (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_PCM, mixer);
break;
case SOUND_MIXER_ALTPCM: /* SB PCM (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SB, mixer);
break;
case SOUND_MIXER_SPEAKER: /* PC speaker (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_SPEAKER, mixer);
break;
case SOUND_MIXER_LINE: /* External line (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_LINE, mixer);
break;
case SOUND_MIXER_CD: /* CD (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_CDROM, mixer);
break;
case SOUND_MIXER_MIC: /* External microphone (0-31) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_MIC, mixer);
break;
case SOUND_MIXER_IMIX: /* Recording monitor (0-31) (Output mixer
* only) */
levels[whichDev] = mixer_output(right, left, 31, P_M_MV508_MIXER | P_M_MV508_IMIXER,
P_M_MV508_OUTPUTMIX);
break;
case SOUND_MIXER_RECLEV: /* Recording level (0-15) */
levels[whichDev] = mixer_output(right, left, 15, P_M_MV508_MASTER_B, 0);
break;
case SOUND_MIXER_MUTE:
return 0;
break;
case SOUND_MIXER_ENHANCE:
i = 0;
level &= 0x7f;
if (level)
i = (level / 20) - 1;
mode_control &= ~<API key>;
mode_control |= <API key>;
set_mode(mode_control);
if (i)
i = (i + 1) * 20;
return i;
break;
case SOUND_MIXER_LOUD:
mode_control &= ~P_M_MV508_LOUDNESS;
if (level)
mode_control |= P_M_MV508_LOUDNESS;
set_mode(mode_control);
return !!level; /* 0 or 1 */
break;
case SOUND_MIXER_RECSRC:
devmask = level & <API key>;
changed = devmask ^ rec_devices;
rec_devices = devmask;
for (i = 0; i < <API key>; i++)
if (changed & (1 << i)) {
pas_mixer_set(i, levels[i]);
}
return rec_devices;
break;
default:
return -(EINVAL);
}
return (levels[whichDev]);
}
static void
pas_mixer_reset(void)
{
int foo;
TRACE(printf("pas2_mixer.c: void pas_mixer_reset(void)\n"));
for (foo = 0; foo < <API key>; foo++)
pas_mixer_set(foo, levels[foo]);
set_mode(P_M_MV508_LOUDNESS | <API key>);
}
static int
pas_mixer_ioctl(int dev, u_int cmd, ioctl_arg arg)
{
TRACE(printf("pas2_mixer.c: int pas_mixer_ioctl(u_int cmd = %X, u_int arg = %X)\n", cmd, arg));
if (((cmd >> 8) & 0xff) == 'M') {
if (cmd & IOC_IN)
return *(int *) arg = pas_mixer_set(cmd & 0xff, (*(int *) arg));
else { /* Read parameters */
switch (cmd & 0xff) {
case SOUND_MIXER_RECSRC:
return *(int *) arg = rec_devices;
break;
case <API key>:
return *(int *) arg = <API key> & ~(SOUND_MASK_BASS | SOUND_MASK_TREBLE);
break;
case SOUND_MIXER_DEVMASK:
return *(int *) arg = <API key>;
break;
case SOUND_MIXER_RECMASK:
return *(int *) arg = <API key> & <API key>;
break;
case SOUND_MIXER_CAPS:
return *(int *) arg = 0; /* No special
* capabilities */
break;
case SOUND_MIXER_MUTE:
return *(int *) arg = 0; /* No mute yet */
break;
case SOUND_MIXER_ENHANCE:
if (!(mode_control & <API key>))
return *(int *) arg = 0;
return *(int *) arg = ((mode_control & <API key>) + 1) * 20;
break;
case SOUND_MIXER_LOUD:
if (mode_control & P_M_MV508_LOUDNESS)
return *(int *) arg = 1;
return *(int *) arg = 0;
break;
default:
return *(int *) arg = levels[cmd & 0xff];
}
}
}
return -(EINVAL);
}
static struct mixer_operations <API key> =
{
"Pro Audio Spectrum 16",
pas_mixer_ioctl
};
int
pas_init_mixer(void)
{
pas_mixer_reset();
if (num_mixers < MAX_MIXER_DEV)
mixer_devs[num_mixers++] = &<API key>;
return 1;
}
#endif
|
<?php
namespace tests\models;
use yii\db\ActiveRecord;
/**
* Post
*
* @property integer $id
* @property string $title
* @property string $body
*
* @property string $tagNames
* @property array $imageNames
*
* @property Tag[] $tags
* @property Image[] $images
*/
class Post extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'body'], 'required'],
];
}
/**
* @inheritdoc
*/
public function transactions()
{
return [
self::SCENARIO_DEFAULT => self::OP_ALL,
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTags()
{
return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
->viaTable('post_tag', ['post_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getImages()
{
return $this->hasMany(Image::className(), ['post_id' => 'id']);
}
}
|
package org.caleydo.view.<API key>.ui.collection;
import java.util.HashSet;
import java.util.Set;
import org.caleydo.core.data.datadomain.<API key>;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.view.<API key>.ui.ConTourElement;
import org.caleydo.view.<API key>.ui.collection.idprovider.IElementIDProvider;
import org.caleydo.view.<API key>.ui.column.factory.ColumnFactories;
import org.caleydo.view.<API key>.ui.column.factory.IColumnFactory;
import org.caleydo.view.<API key>.ui.detail.parcoords.<API key>;
import com.google.common.collect.Sets;
/**
* @author Christian
*
*/
public class <API key> extends AEntityCollection {
protected final <API key> dataDomain;
protected final IDCategory itemIDCategory;
protected final TablePerspective tablePerspective;
protected final IDType itemIDType;
protected final VirtualArray va;
protected final Perspective <API key>;
protected final IDType mappingIDType;
public <API key>(TablePerspective tablePerspective, IDCategory itemIDCategory,
IElementIDProvider elementIDProvider, ConTourElement <API key>) {
super(<API key>);
dataDomain = tablePerspective.getDataDomain();
this.itemIDCategory = itemIDCategory;
this.tablePerspective = tablePerspective;
this.mappingIDType = dataDomain.<API key>(itemIDCategory);
if (dataDomain.<API key>() == itemIDCategory) {
va = tablePerspective.<API key>().getVirtualArray();
itemIDType = tablePerspective.<API key>().getIdType();
<API key> = tablePerspective.<API key>();
} else {
va = tablePerspective.<API key>().getVirtualArray();
itemIDType = tablePerspective.<API key>().getIdType();
<API key> = tablePerspective.<API key>();
}
if (elementIDProvider == null)
elementIDProvider = <API key>(va);
allElementIDs.addAll(elementIDProvider.getElementIDs());
filteredElementIDs.addAll(allElementIDs);
setLabel(dataDomain.getLabel());
detailViewFactory = new <API key>();
}
@Override
public IDType <API key>() {
return itemIDType;
}
@Override
protected Set<Object> <API key>(Object elementID) {
return Sets.newHashSet(elementID);
}
@Override
protected Set<Object> <API key>(Object broadcastingID) {
return Sets.newHashSet(broadcastingID);
}
@Override
protected IColumnFactory <API key>() {
return ColumnFactories.<API key>();
}
/**
* @return the dataDomain, see {@link #dataDomain}
*/
public <API key> getDataDomain() {
return dataDomain;
}
/**
* @return the perspective, see {@link #<API key>}
*/
public Perspective <API key>() {
return <API key>;
}
/**
* @return the itemIDCategory, see {@link #itemIDCategory}
*/
public IDCategory getItemIDCategory() {
return itemIDCategory;
}
/**
* @return the itemIDType, see {@link #itemIDType}
*/
public IDType getItemIDType() {
return itemIDType;
}
@Override
public IDType getMappingIDType() {
return mappingIDType;
}
/**
* @return the tablePerspective, see {@link #tablePerspective}
*/
public TablePerspective getTablePerspective() {
return tablePerspective;
}
/**
* @return the va, see {@link #va}
*/
public VirtualArray getVa() {
return va;
}
public static IElementIDProvider <API key>(final VirtualArray va) {
return new IElementIDProvider() {
@Override
public Set<Object> getElementIDs() {
return new HashSet<Object>(va.getIDs());
}
};
}
@Override
public String getText(Object elementID) {
return elementID.toString();
}
}
|
<?php
namespace backend\models\base;
use Yii;
/**
* This is the base model class for table "auth_item_child".
*
* @property string $parent
* @property string $child
*
* @property \backend\models\AuthItem $parent0
* @property \backend\models\AuthItem $child0
*/
class AuthItemChild extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['parent', 'child'], 'required'],
[['parent', 'child'], 'string', 'max' => 64]
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'auth_item_child';
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'parent' => 'Parent',
'child' => 'Child',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getParent0()
{
return $this->hasOne(\backend\models\AuthItem::className(), ['name' => 'parent']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getChild0()
{
return $this->hasOne(\backend\models\AuthItem::className(), ['name' => 'child']);
}
/**
* @inheritdoc
* @return \app\models\AuthItemChildQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\models\AuthItemChildQuery(get_called_class());
}
}
|
var PgQuery = require('bindings')('pg-query');
module.exports = {
parse: function(query) {
var result = PgQuery.parse(query);
if (result.query) {
result.query = JSON.parse(result.query);
}
if (result.error) {
var err = new Error(result.error.message);
err.fileName = result.error.fileName;
err.lineNumber = result.error.lineNumber;
err.cursorPosition = result.error.cursorPosition;
err.functionName = result.error.functionName;
err.context = result.error.context;
result.error = err;
}
return result;
}
};
|
// Replacement for jquery.ui.accordion to avoid dealing with
// jquery.ui theming.
// Usage: $('#container').squeezebox(options);
// where the direct child elements of '#container' are
// sequential pairs of header/panel elements, and options
// is an optional object with any of the following properties:
// activeHeaderClass: Class name to apply to the active header
// headerSelector: Selector for the header elements
// nextPanelSelector: Selector for the next panel from a header
// speed: Animation speed
(function($) {
$.fn.squeezebox = function(options) {
// Default options.
options = $.extend({
activeHeaderClass: '<API key>',
headerSelector: '> *:even',
nextPanelSelector: ':first',
speed: 500
}, options);
var headers = this.find(options.headerSelector);
// When a header is clicked, iterate through each of the
// headers, getting their corresponding panels, and opening
// the panel for the header that was clicked (slideDown),
// closing the others (slideUp).
headers.click(function() {
var clicked = this;
$.each(headers, function(i, header) {
var panel = $(header).next(options.nextPanelSelector);
if (clicked == header) {
panel.slideDown(options.speed);
$(header).addClass(options.activeHeaderClass);
} else {
panel.slideUp(options.speed);
$(header).removeClass(options.activeHeaderClass);
}
});
});
};
})(jQuery);
|
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
$org = $auth->createRole('org');
$auth->add($org);
$adviser = $auth->createRole('adviser');
$auth->add($adviser);
$osa = $auth->createRole('osa');
$auth->add($osa);
$auth->addChild($osa, $adviser);
$auth->addChild($osa, $org);
$admin = $auth->createRole('admin');
$auth->add($admin);
$index_organizations = $auth->createPermission('indexOrganizations');
$index_organizations->description = 'view the list of organizations';
$auth->add($index_organizations);
$create_organization = $auth->createPermission('createOrganization');
$create_organization->description = 'creates an organization';
$auth->add($create_organization);
$delete_organization = $auth->createPermission('deleteOrganization');
$delete_organization->description = 'deletes an organization';
$auth->add($delete_organization);
$view_organization = $auth->createPermission('viewOrganization');
$view_organization->description = 'views the details of an organization';
$auth->add($view_organization);
$<API key> = $auth->createPermission('viewOwnOrganization');
$<API key>->description = 'views the details of own organization';
$auth->add($<API key>);
$auth->addChild($org, $<API key>);
$auth->addChild($osa, $index_organizations);
$auth->addChild($osa, $create_organization);
$auth->addChild($osa, $delete_organization);
$auth->addChild($osa, $view_organization);
$auth->assign($org, 4);
$auth->assign($adviser, 3);
$auth->assign($osa, 2);
$auth->assign($admin, 1);
}
}
|
import base64
import json
from twisted.internet.defer import inlineCallbacks, DeferredQueue, returnValue
from twisted.web.http_headers import Headers
from twisted.web import http
from twisted.web.server import NOT_DONE_YET
from vumi.config import ConfigContext
from vumi.message import <API key>, TransportEvent
from vumi.tests.helpers import VumiTestCase
from vumi.tests.utils import MockHttpServer, LogCatcher
from vumi.transports.vumi_bridge.client import StreamingClient
from vumi.utils import http_request_full
from go.apps.http_api.resource import (
StreamResourceMixin, <API key>)
from go.apps.tests.helpers import AppWorkerHelper
from go.apps.http_api.vumi_app import StreamingHTTPWorker
class <API key>(VumiTestCase):
@inlineCallbacks
def setUp(self):
self.app_helper = self.add_helper(AppWorkerHelper(StreamingHTTPWorker))
self.config = {
'health_path': '/health/',
'web_path': '/foo',
'web_port': 0,
'metrics_prefix': 'metrics_prefix.',
'<API key>': 0,
}
self.app = yield self.app_helper.get_app_worker(self.config)
self.addr = self.app.webserver.getHost()
self.url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['web_path'])
conv_config = {
'http_api': {
'api_tokens': [
'token-1',
'token-2',
'token-3',
],
'metric_store': 'metric_store',
}
}
conversation = yield self.app_helper.create_conversation(
config=conv_config)
yield self.app_helper.start_conversation(conversation)
self.conversation = yield self.app_helper.get_conversation(
conversation.key)
self.auth_headers = {
'Authorization': ['Basic ' + base64.b64encode('%s:%s' % (
conversation.user_account.key, 'token-1'))],
}
self.client = StreamingClient()
# Mock server to test HTTP posting of inbound messages & events
self.mock_push_server = MockHttpServer(self.handle_request)
yield self.mock_push_server.start()
self.add_cleanup(self.mock_push_server.stop)
self.push_calls = DeferredQueue()
self.<API key>()
self.add_cleanup(self._wait_for_requests)
def <API key>(self):
# Hackery to wait for the request to finish
self._req_state = {
'queue': DeferredQueue(),
'expected': 0,
}
orig_track = <API key>.track_request
orig_release = <API key>.release_request
def track_wrapper(*args, **kw):
self._req_state['expected'] += 1
return orig_track(*args, **kw)
def release_wrapper(*args, **kw):
return orig_release(*args, **kw).addCallback(
self._req_state['queue'].put)
self.patch(
<API key>, 'track_request', track_wrapper)
self.patch(
<API key>, 'release_request', release_wrapper)
@inlineCallbacks
def _wait_for_requests(self):
while self._req_state['expected'] > 0:
yield self._req_state['queue'].get()
self._req_state['expected'] -= 1
def handle_request(self, request):
self.push_calls.put(request)
return NOT_DONE_YET
@inlineCallbacks
def pull_message(self, count=1):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
<API key>, messages.put, errors.put, url,
Headers(self.auth_headers))
received_messages = []
for msg_id in range(count):
yield self.app_helper.<API key>(
'in %s' % (msg_id,), message_id=str(msg_id),
conv=self.conversation)
recv_msg = yield messages.get()
received_messages.append(recv_msg)
receiver.disconnect()
returnValue((receiver, received_messages))
def assert_bad_request(self, response, reason):
self.assertEqual(response.code, http.BAD_REQUEST)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
data = json.loads(response.delivered_body)
self.assertEqual(data, {
"success": False,
"reason": reason,
})
@inlineCallbacks
def <API key>(self):
# This is the default, but we patch it anyway to make sure we're
# testing the right thing should the default change.
self.patch(StreamResourceMixin, 'proxy_buffering', False)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['no'])
@inlineCallbacks
def <API key>(self):
self.patch(StreamResourceMixin, 'proxy_buffering', True)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['yes'])
@inlineCallbacks
def test_content_type(self):
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(
headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
@inlineCallbacks
def <API key>(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
<API key>, messages.put, errors.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.<API key>(
'in 1', message_id='1', conv=self.conversation)
msg2 = yield self.app_helper.<API key>(
'in 2', message_id='2', conv=self.conversation)
rm1 = yield messages.get()
rm2 = yield messages.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
rm1, rm2 = sorted([rm1, rm2], key=lambda m: m['message_id'])
self.assertEqual(msg1['message_id'], rm1['message_id'])
self.assertEqual(msg2['message_id'], rm2['message_id'])
self.assertEqual(errors.size, None)
@inlineCallbacks
def test_events_stream(self):
url = '%s/%s/events.json' % (self.url, self.conversation.key)
events = DeferredQueue()
errors = DeferredQueue()
receiver = yield self.client.stream(TransportEvent, events.put,
events.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.<API key>(
self.conversation, 'out 1', message_id='1')
ack1 = yield self.app_helper.make_dispatch_ack(
msg1, conv=self.conversation)
msg2 = yield self.app_helper.<API key>(
self.conversation, 'out 2', message_id='2')
ack2 = yield self.app_helper.make_dispatch_ack(
msg2, conv=self.conversation)
ra1 = yield events.get()
ra2 = yield events.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
if ra1['event_id'] != ack1['event_id']:
ra1, ra2 = ra2, ra1
self.assertEqual(ack1['event_id'], ra1['event_id'])
self.assertEqual(ack2['event_id'], ra2['event_id'])
self.assertEqual(errors.size, None)
@inlineCallbacks
def test_missing_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
receiver = self.client.stream(
<API key>, queue.put, queue.put, url)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"'])
@inlineCallbacks
def test_invalid_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
headers = Headers({
'Authorization': ['Basic %s' % (base64.b64encode('foo:bar'),)],
})
receiver = self.client.stream(
<API key>, queue.put, queue.put, url, headers)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"'])
@inlineCallbacks
def test_send_to(self):
msg = {
'to_addr': '+2345',
'content': 'foo',
'message_id': 'evil_id',
}
# TaggingMiddleware.add_tag_to_msg(msg, self.tag)
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
self.assertEqual(response.code, http.OK)
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.<API key>()
self.assertEqual(sent_msg['to_addr'], sent_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], msg['to_addr'])
self.assertEqual(sent_msg['from_addr'], None)
@inlineCallbacks
def <API key>(self):
self.conversation.config['http_api'].update({
'<API key>': 182,
})
yield self.conversation.save()
msg = {
'content': 'foo',
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.<API key>()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], '+1234')
self.assertEqual(sent_msg['from_addr'], None)
@inlineCallbacks
def <API key>(self):
self.conversation.config['http_api'].update({
'<API key>': 10,
})
yield self.conversation.save()
msg = {
'content': "This message is longer than 10 characters.",
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10")
@inlineCallbacks
def <API key>(self):
msg = {
'content': 0xBAD,
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'")
@inlineCallbacks
def <API key>(self):
msg = {
'content': 'good',
'to_addr': 1234,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'to_addr'")
@inlineCallbacks
def test_in_reply_to(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.<API key>()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def <API key>(self):
self.conversation.config['http_api'].update({
'<API key>': 182,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.<API key>()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def <API key>(self):
self.conversation.config['http_api'].update({
'<API key>': 10,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': "This message is longer than 10 characters.",
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10")
@inlineCallbacks
def <API key>(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 0xBAD,
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'")
@inlineCallbacks
def <API key>(self):
msg = {
'content': 'foo',
'in_reply_to': '1', # this doesn't exist
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(response, 'Invalid in_reply_to value')
@inlineCallbacks
def <API key>(self):
# create a message with no conversation
inbound_msg = self.app_helper.make_inbound('in 1', message_id='msg-1')
vumi_api = self.app_helper.vumi_helper.get_vumi_api()
yield vumi_api.mdb.add_inbound_message(inbound_msg)
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
with LogCatcher(message='Invalid reply to message <Message .*>'
' which has no conversation key') as lc:
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
[error_log] = lc.messages()
self.assert_bad_request(response, "Invalid in_reply_to value")
self.assertTrue(inbound_msg['message_id'] in error_log)
@inlineCallbacks
def <API key>(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'session_event': 0xBAD5E55104,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response,
"Invalid or missing value for payload key 'session_event'")
self.assertEqual(self.app_helper.<API key>(), [])
@inlineCallbacks
def <API key>(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'message_id': 'evil_id'
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.<API key>()
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292')
@inlineCallbacks
def <API key>(self):
metric_data = [
("vumi.test.v1", 1234, 'SUM'),
("vumi.test.v2", 3456, 'AVG'),
]
url = '%s/%s/metrics.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(metric_data), self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
prefix = "go.campaigns.test-0-user.stores.metric_store"
self.assertEqual(
self.app_helper.<API key>(self.app),
[("%s.vumi.test.v1" % prefix, 1234),
("%s.vumi.test.v2" % prefix, 3456)])
@inlineCallbacks
def <API key>(self):
config = yield self.app.get_config(None)
concurrency = config.concurrency_limit
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
max_receivers = [self.client.stream(
<API key>, queue.put, queue.put, url,
Headers(self.auth_headers)) for _ in range(concurrency)]
for i in range(concurrency):
msg = yield self.app_helper.<API key>(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
received = yield queue.get()
self.assertEqual(msg['message_id'], received['message_id'])
maxed_out_resp = yield http_request_full(
url, method='GET', headers=self.auth_headers)
self.assertEqual(maxed_out_resp.code, 403)
self.assertTrue(
'Too many concurrent connections' in maxed_out_resp.delivered_body)
[r.disconnect() for r in max_receivers]
@inlineCallbacks
def <API key>(self):
conv_resource = <API key>(
self.app, self.conversation.key)
# negative concurrency limit disables it
ctxt = ConfigContext(user_account=self.conversation.user_account.key,
concurrency_limit=-1)
config = yield self.app.get_config(msg=None, ctxt=ctxt)
self.assertTrue(
(yield conv_resource.is_allowed(
config, self.conversation.user_account.key)))
@inlineCallbacks
def <API key>(self):
for i in range(10):
yield self.app_helper.<API key>(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
receiver = self.client.stream(
<API key>, queue.put, queue.put, url,
Headers(self.auth_headers))
for i in range(10):
received = yield queue.get()
self.assertEqual(received['message_id'], str(i))
receiver.disconnect()
@inlineCallbacks
def <API key>(self):
health_url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['health_path'])
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
yield self.app_helper.<API key>(
'in 1', message_id='1', conv=self.conversation)
queue = DeferredQueue()
stream_url = '%s/%s/messages.json' % (self.url, self.conversation.key)
stream_receiver = self.client.stream(
<API key>, queue.put, queue.put, stream_url,
Headers(self.auth_headers))
yield queue.get()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '1')
stream_receiver.disconnect()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
self.assertEqual(self.app.client_manager.clients, {
'sphex.stream.message.%s' % (self.conversation.key,): []
})
@inlineCallbacks
def <API key>(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg_d = self.app_helper.<API key>(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
msg = yield msg_d
posted_msg = <API key>.from_json(posted_json_data)
self.assertEqual(posted_msg['message_id'], msg['message_id'])
@inlineCallbacks
def <API key>(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.<API key>(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(201)
req.finish()
yield msg_d
self.assertEqual(lc.messages(), [])
@inlineCallbacks
def <API key>(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.<API key>(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(500)
req.finish()
yield msg_d
[warning_log] = lc.messages()
self.assertTrue(self.mock_push_server.url in warning_log)
self.assertTrue('500' in warning_log)
@inlineCallbacks
def <API key>(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_event_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg = yield self.app_helper.<API key>(
self.conversation, 'out 1', message_id='1')
event_d = self.app_helper.make_dispatch_ack(
msg, conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
ack = yield event_d
self.assertEqual(TransportEvent.from_json(posted_json_data), ack)
@inlineCallbacks
def test_bad_urls(self):
def assert_not_found(url, headers={}):
d = http_request_full(self.url, method='GET', headers=headers)
d.addCallback(lambda r: self.assertEqual(r.code, http.NOT_FOUND))
return d
yield assert_not_found(self.url)
yield assert_not_found(self.url + '/')
yield assert_not_found('%s/%s' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/foo' % (self.url, self.conversation.key),
headers=self.auth_headers)
@inlineCallbacks
def <API key>(self):
yield self.app_helper.dispatch_command(
'send_message',
user_account_key=self.conversation.user_account.key,
conversation_key=self.conversation.key,
command_data={
u'batch_id': u'batch-id',
u'content': u'foo',
u'to_addr': u'to_addr',
u'msg_options': {
u'helper_metadata': {
u'tag': {
u'tag': [u'longcode', u'default10080']
}
},
u'from_addr': u'default10080',
}
})
[msg] = self.app_helper.<API key>()
self.assertEqual(msg.payload['to_addr'], "to_addr")
self.assertEqual(msg.payload['from_addr'], "default10080")
self.assertEqual(msg.payload['content'], "foo")
self.assertEqual(msg.payload['message_type'], "user_message")
self.assertEqual(
msg.payload['helper_metadata']['go']['user_account'],
self.conversation.user_account.key)
self.assertEqual(
msg.payload['helper_metadata']['tag']['tag'],
['longcode', 'default10080'])
@inlineCallbacks
def <API key>(self):
msg = yield self.app_helper.make_stored_inbound(
self.conversation, "foo")
yield self.app_helper.dispatch_command(
'send_message',
user_account_key=self.conversation.user_account.key,
conversation_key=self.conversation.key,
command_data={
u'batch_id': u'batch-id',
u'content': u'foo',
u'to_addr': u'to_addr',
u'msg_options': {
u'helper_metadata': {
u'tag': {
u'tag': [u'longcode', u'default10080']
}
},
u'transport_name': u'smpp_transport',
u'in_reply_to': msg['message_id'],
u'transport_type': u'sms',
u'from_addr': u'default10080',
}
})
[sent_msg] = self.app_helper.<API key>()
self.assertEqual(sent_msg['to_addr'], msg['from_addr'])
self.assertEqual(sent_msg['content'], 'foo')
self.assertEqual(sent_msg['in_reply_to'], msg['message_id'])
|
from flask import request, current_app, url_for
from flask_jsonschema import validate
from .. import db
from ..models import AHBot as Bot
from .decorators import json_response
from . import api
@api.route('/abusehelper', methods=['GET'])
@json_response
def get_abusehelper():
bots = Bot.query.filter().all()
return {'abusehelper': [a.serialize() for a in bots]}
@api.route('/abusehelper/<int:bot_id>', methods=['GET'])
@json_response
def get_got(bot_id):
a = Bot.query.get_or_404(bot_id)
return a.serialize()
@api.route('/abusehelper', methods=['POST', 'PUT'])
@validate('abusehelper', 'add_bot')
@json_response
def add_bot():
a = Bot.fromdict(request.json)
db.session.add(a)
db.session.commit()
return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \
{'Location': url_for('api.get_bot', bot_id=a.id)}
@api.route('/abusehelper/<int:bot_id>', methods=['PUT'])
@validate('abusehelper', 'update_bot')
@json_response
def update_bot(bot_id):
return NotImplemented
@api.route('/abusehelper/<int:bot_id>', methods=['DELETE'])
@json_response
def delete_bot(bot_id):
"""Delete bot
**Example request**:
.. sourcecode:: http
DELETE /api/1.0/abusehelper/1 HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"message": "Bot deleted"
}
:param bot_id: Bot unique ID.
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json string message: Action status status
:status 200: Bot was deleted
:status 404: Bot was not found
"""
a = Bot.query.filter_by(id == bot_id).delete()
if not a:
return {'message': 'No such bot'}, 404
db.session.commit()
return {'message': 'Bot deleted'}
@api.route('/abusehelper', methods=['DELETE'])
@json_response
def delete_abusehelper():
"""Clear abusehelper table
**Example request**:
.. sourcecode:: http
DELETE /api/1.0/abusehelper HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"message": "Bots deleted"
}
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>json string message: Action status status
:status 200: Bot was deleted
:status 404: Bot was not found
"""
a = Bot.query.all().delete()
db.session.commit()
current_app.log.debug('Deleted {} abusehelper'.format(a))
return {'message': 'Bots deleted'}
|
package gov.hhs.fha.nhinc.common.dda;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "<API key>", propOrder = {
"userId",
"dataSource",
"itemId"
})
public class <API key> {
@XmlElement(required = true)
protected String userId;
@XmlElement(required = true)
protected String dataSource;
@XmlElement(required = true)
protected String itemId;
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the dataSource property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataSource() {
return dataSource;
}
/**
* Sets the value of the dataSource property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataSource(String value) {
this.dataSource = value;
}
/**
* Gets the value of the itemId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getItemId() {
return itemId;
}
/**
* Sets the value of the itemId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setItemId(String value) {
this.itemId = value;
}
}
|
use actix::Addr;
use actix_web::{http, middleware};
use actix_web::{web, App, HttpServer};
use diesel::r2d2::{self, ConnectionManager};
use diesel::PgConnection;
use crate::database::DbExecutor;
use badge::handlers::badge_handler;
// use run::handlers::run_handler;
use status::handlers::status_handler;
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
#[derive(Clone)]
pub struct WebState {
pub db: Pool,
pub db_actor: Addr<DbExecutor>,
}
pub fn http_server(state: WebState, http_bind: String, http_port: String) {
use actix_web::middleware::cors::Cors;
HttpServer::new(move || {
App::new()
.data(state.clone())
.wrap(middleware::Logger::default())
.wrap(
Cors::new() // <- Construct CORS middleware builder
.allowed_methods(vec!["GET", "POST", "OPTION"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
.allowed_header(http::header::CONTENT_TYPE)
.max_age(3600),
)
.service(web::resource("/{project}/{workflow}/badge.svg").to_async(badge_handler))
.service(web::resource("/mon/status").to(status_handler))
})
.bind(format!("{}:{}", http_bind, http_port))
.unwrap()
.start();
}
|
from django.contrib import admin
# Register your models here.
from .models import Photos
admin.site.register(Photos)
|
#include "Ht.h"
#include "PersBug.h"
void
CPersBug::PersBug()
{
if (PR_htValid) {
switch (PR_htInst) {
case BUG_RTN: {
if (<API key>()) {
HtRetry();
break;
}
SendReturn_htmain();
}
break;
default:
assert(0);
}
}
}
|
# Thanks for using Enthought open source!
""" Tests for the BetterZoom Chaco tool """
import unittest
import numpy
from chaco.api import create_line_plot
from chaco.tools.api import BetterZoom
from enable.testing import EnableTestAssistant
class TestBetterZoomTool(EnableTestAssistant, unittest.TestCase):
""" Tests for the BetterZoom Chaco tool """
def setUp(self):
values = numpy.arange(10)
self.plot = create_line_plot((values, values))
self.plot.bounds = [100, 100]
self.plot._window = self.create_mock_window()
self.tool = BetterZoom(component=self.plot)
self.plot.active_tool = self.tool
self.plot.do_layout()
def tearDown(self):
del self.tool
del self.plot
def <API key>(self):
tool = self.tool
# this doesn't throw an exception
self.send_key(tool, '+')
self.assertEqual(tool.position, (50, 50))
# expected behaviour for a normal zoom in operation
self.assertNotEqual(tool._index_factor, 1.0)
self.assertNotEqual(tool._value_factor, 1.0)
self.assertEqual(len(tool._history), 2)
|
package org.mini2Dx.core.di.exception;
/**
* A base class for bean exceptions
*/
public class BeanException extends Exception {
private static final long serialVersionUID = <API key>;
public BeanException(String message) {
super(message);
}
}
|
<?php
namespace Ordemservico\Form\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormElementErrors;
class FormElementErros extends FormElementErrors {
public function render(ElementInterface $element, array $attributes = array()){
//Associando menssagem com varivel
$messages = $element->getMessages();
if(empty($messages)){
return '';
}
$markup = '<div class="alert alert-danger col-sm-10 col-sm-offset-2" role="alert">';
$markup .= implode(' - ', $messages);
$markup .= '</div>';
return $markup;
}
}
|
<?php
use yii\helpers\Html;
use yii\bootstrap\Modal;
use yii\bootstrap\ButtonGroup;
use yii\widgets\Menu;
use yii\widgets\Pjax;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\<API key> */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', '<API key>');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="<API key> col-lg-12 col-md-12 col-xs-12 well">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="col-md-12 col-lg-12 col-xs-12 well">
<?php $datagrid=[
['class' => 'kartik\grid\SerialColumn'],
// '<API key>',
[
'attribute'=>'id_lineaprovisional',
'value'=>'tblMaquinaIdMaquina.tblLineaIdLinea.tbl_linea_nombre',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>$model->tbllineaList,
'filterInputOptions'=>['placeholder' => 'Selecciona '],
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'group'=>true,
'groupFooter'=>function ($model, $key, $index, $widget) { // Closure method
return [
'mergeColumns'=>[[0,2]], // columns to merge in summary
'content'=>[ // content to show in each summary cell
0=>'Resumen (' . $model->tblMaquinaIdMaquina->tblLineaIdLinea->tbl_linea_nombre . ')',
2=>GridView::F_SUM,
3=>GridView::F_SUM,
],
'contentFormats'=>[ // content reformatting for each summary cell
2=>['format'=>'number', 'decimals'=>0],
3=>['format'=>'number', 'decimals'=>2],
],
'contentOptions'=>[ // content html attributes for each summary cell
0=>['style'=>'font-variant:small-caps'],
2=>['style'=>'text-align:right'],
3=>['style'=>'text-align:right'],
],
'options'=>['class'=>'danger','style'=>'font-weight:bold;']
];
}
],
[
'attribute'=>'<API key>',
'value'=>'tblMaquinaIdMaquina.tbl_maquina_bim',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>$model->tblmaquinaList,
'filterInputOptions'=>['placeholder' => 'Selecciona '],
'group'=>true,
'subGroupOf'=>1,
'groupFooter'=>function ($model, $key, $index, $widget) { // Closure method
return [
'mergeColumns'=>[[3]], // columns to merge in summary
'content'=>[ // content to show in each summary cell
2=>'Resumen (' . $model->tblMaquinaIdMaquina->tbl_maquina_bim . ')',
3=>GridView::F_SUM,
],
'contentFormats'=>[ // content reformatting for each summary cell
3=>['format'=>'number', 'decimals'=>0],
4=>['format'=>'number', 'decimals'=>2],
],
'contentOptions'=>[ // content html attributes for each summary cell
2=>['style'=>'font-variant:small-caps'],
3=>['style'=>'text-align:right'],
],
'options'=>['class'=>'success','style'=>'font-weight:bold;']
];
},
],
[
'label'=>'Total',
'value'=>function ($model, $key, $index, $column) {
$precios=$model->tblItemIdItem->tblPrecios;
$costo=0;
foreach($precios as $precio){
if($precio->tbl_precio_opcion==1){
$costo=$costo+$precio->tbl_precio_precio;
}
}
return $costo*$model->sumacount;
},
],
[
'attribute'=>'<API key>',
'value'=>'<API key>',
'filter'=> kartik\daterange\DateRangePicker::widget([
'model' => $searchModel,
'attribute'=>'<API key>',
'convertFormat'=>true,
'pluginOptions'=>[
'locale'=>[
'format'=>'Y-m-d',
'separator' => 'to',
]
]
]),
'format' => ['date', 'php:Y-m-d'],
],
];
$exportvar=ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' =>$datagrid,
'target' => ExportMenu::TARGET_BLANK,
'asDropdown' => false,
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' =>$datagrid,
'responsive'=>true,
'panel'=>[
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i>'.Html::encode($this->title).'</h3>',
],
'toolbar'=>[
'{export}',[
'content'=>Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['reporte'], ['class' => 'btn btn-default', 'title'=> 'Reset Grid'])
]
],
'export'=>[
'itemsAfter'=> [
'<li role="presentation" class="divider"></li>',
'<li class="dropdown-header">All Data</li>',
$exportvar
]
]
]); ?>
</div>
<?php Modal::begin([
'id'=>'<API key>',
'size'=>'modal-lg'
]);
?>
<div id="<API key>"></div>
<?php Modal::end(); ?>
</div>
|
# Minimal makefile for Sphinx documentation
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = DjangoCorrelationId
SOURCEDIR = .
BUILDDIR = ../build/sphinx
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Sun Mar 01 12:04:16 AEDT 2015 -->
<title><API key> (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="<API key> (Bouncy Castle Library 1.52 API Specification)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.52</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/cert/selector/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.bouncycastle.cert.selector</div>
<h2 title="Class <API key>" class="title">Class <API key></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.bouncycastle.cert.selector.<API key></li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong"><API key></span>
extends java.lang.Object</pre>
<div class="block">This class builds selectors according to the set criteria.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#<API key>()"><API key></a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)">addTargetGroup</a></strong>(org.bouncycastle.asn1.x509.GeneralName group)</code>
<div class="block">Adds a target group criterion for the attribute certificate to the target
information extension criteria.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#addTargetName(org.bouncycastle.asn1.x509.GeneralName)">addTargetName</a></strong>(org.bouncycastle.asn1.x509.GeneralName name)</code>
<div class="block">Adds a target name criterion for the attribute certificate to the target
information extension criteria.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><API key></a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#build()">build</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setAttributeCert(org.bouncycastle.cert.<API key>)">setAttributeCert</a></strong>(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> attributeCert)</code>
<div class="block">Set the attribute certificate to be matched.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#<API key>(java.util.Date)"><API key></a></strong>(java.util.Date <API key>)</code>
<div class="block">Set the time, when the certificate must be valid.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setHolder(org.bouncycastle.cert.<API key>)">setHolder</a></strong>(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> holder)</code>
<div class="block">Sets the holder.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setIssuer(org.bouncycastle.cert.<API key>)">setIssuer</a></strong>(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> issuer)</code>
<div class="block">Sets the issuer the attribute certificate must have.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setSerialNumber(java.math.BigInteger)">setSerialNumber</a></strong>(java.math.BigInteger serialNumber)</code>
<div class="block">Sets the serial number the attribute certificate must have.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setTargetGroups(java.util.Collection)">setTargetGroups</a></strong>(java.util.Collection names)</code>
<div class="block">Adds a collection with target groups criteria.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#setTargetNames(java.util.Collection)">setTargetNames</a></strong>(java.util.Collection names)</code>
<div class="block">Adds a collection with target names criteria.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="<API key>()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4><API key></h4>
<pre>public <API key>()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="setAttributeCert(org.bouncycastle.cert.<API key>)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setAttributeCert</h4>
<pre>public void setAttributeCert(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> attributeCert)</pre>
<div class="block">Set the attribute certificate to be matched. If <code>null</code> is
given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>attributeCert</code> - The attribute certificate holder to set.</dd></dl>
</li>
</ul>
<a name="<API key>(java.util.Date)">
</a>
<ul class="blockList">
<li class="blockList">
<h4><API key></h4>
<pre>public void <API key>(java.util.Date <API key>)</pre>
<div class="block">Set the time, when the certificate must be valid. If <code>null</code>
is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code><API key></code> - The attribute certificate validation
time to set.</dd></dl>
</li>
</ul>
<a name="setHolder(org.bouncycastle.cert.<API key>)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHolder</h4>
<pre>public void setHolder(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> holder)</pre>
<div class="block">Sets the holder. If <code>null</code> is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>holder</code> - The holder to set.</dd></dl>
</li>
</ul>
<a name="setIssuer(org.bouncycastle.cert.<API key>)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setIssuer</h4>
<pre>public void setIssuer(<a href="../../../../org/bouncycastle/cert/<API key>.html" title="class in org.bouncycastle.cert"><API key></a> issuer)</pre>
<div class="block">Sets the issuer the attribute certificate must have. If <code>null</code>
is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>issuer</code> - The issuer to set.</dd></dl>
</li>
</ul>
<a name="setSerialNumber(java.math.BigInteger)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSerialNumber</h4>
<pre>public void setSerialNumber(java.math.BigInteger serialNumber)</pre>
<div class="block">Sets the serial number the attribute certificate must have. If
<code>null</code> is given any will do.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>serialNumber</code> - The serialNumber to set.</dd></dl>
</li>
</ul>
<a name="addTargetName(org.bouncycastle.asn1.x509.GeneralName)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>addTargetName</h4>
<pre>public void addTargetName(org.bouncycastle.asn1.x509.GeneralName name)</pre>
<div class="block">Adds a target name criterion for the attribute certificate to the target
information extension criteria. The <code><API key></code>
must contain at least one of the specified target names.
<p>
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - The name as a GeneralName (not <code>null</code>)</dd></dl>
</li>
</ul>
<a name="setTargetNames(java.util.Collection)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTargetNames</h4>
<pre>public void setTargetNames(java.util.Collection names)
throws java.io.IOException</pre>
<div class="block">Adds a collection with target names criteria. If <code>null</code> is
given any will do.
<p>
The collection consists of either GeneralName objects or byte[] arrays representing
DER encoded GeneralName structures.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>names</code> - A collection of target names.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - if a parsing error occurs.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#addTargetName(org.bouncycastle.asn1.x509.GeneralName)"><code>addTargetName(org.bouncycastle.asn1.x509.GeneralName)</code></a></dd></dl>
</li>
</ul>
<a name="addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>addTargetGroup</h4>
<pre>public void addTargetGroup(org.bouncycastle.asn1.x509.GeneralName group)</pre>
<div class="block">Adds a target group criterion for the attribute certificate to the target
information extension criteria. The <code><API key></code>
must contain at least one of the specified target groups.
<p>
Each attribute certificate may contain a target information extension
limiting the servers where this attribute certificate can be used. If
this extension is not present, the attribute certificate is not targeted
and may be accepted by any server.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>group</code> - The group as GeneralName form (not <code>null</code>)</dd></dl>
</li>
</ul>
<a name="setTargetGroups(java.util.Collection)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTargetGroups</h4>
<pre>public void setTargetGroups(java.util.Collection names)
throws java.io.IOException</pre>
<div class="block">Adds a collection with target groups criteria. If <code>null</code> is
given any will do.
<p>
The collection consists of <code>GeneralName</code> objects or <code>byte[]</code representing DER
encoded GeneralNames.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>names</code> - A collection of target groups.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.io.IOException</code> - if a parsing error occurs.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/bouncycastle/cert/selector/<API key>.html#addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)"><code>addTargetGroup(org.bouncycastle.asn1.x509.GeneralName)</code></a></dd></dl>
</li>
</ul>
<a name="build()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>build</h4>
<pre>public <a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><API key></a> build()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.52</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/cert/selector/<API key>.html" title="class in org.bouncycastle.cert.selector"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/cert/selector/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
.icheckbox_square,
.iradio_square {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 22px;
height: 22px;
background: url(square.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_square {
background-position: 0 0;
}
.icheckbox_square.hover {
background-position: -24px 0;
}
.icheckbox_square.checked {
background-position: -48px 0;
}
.icheckbox_square.disabled {
background-position: -72px 0;
cursor: default;
}
.icheckbox_square.checked.disabled {
background-position: -96px 0;
}
.iradio_square {
background-position: -120px 0;
}
.iradio_square.hover {
background-position: -144px 0;
}
.iradio_square.checked {
background-position: -168px 0;
}
.iradio_square.disabled {
background-position: -192px 0;
cursor: default;
}
.iradio_square.checked.disabled {
background-position: -216px 0;
}
/* HiDPI support */
@media (-<API key>: 5/4), (-<API key>: 1.25), (min-resolution: 120dpi), (min-resolution: 1.25dppx) {
.icheckbox_square,
.iradio_square {
background-image: url(square@2x.png);
-<API key>: 240px 24px;
background-size: 240px 24px;
}
}
|
import pytest
from py4jdbc.dbapi2 import connect, Connection
from py4jdbc.resultset import ResultSet
from py4jdbc.exceptions.dbapi2 import Error
def test_connect(gateway):
url = "jdbc:derby:memory:testdb;create=true"
conn = connect(url, gateway=gateway)
cur = conn.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs, ResultSet)
def test_execute(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs, ResultSet)
def <API key>(derby):
derby.autocommit = False
cur = derby.cursor()
cur.execute("create schema x_with_params")
cur.execute("create table x_with_params.cowtest(a int, b char(1))")
# Verify table is empty.
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == 0
# Insert one with parameter binding..
sql = "insert into x_with_params.cowtest (a, b) values (?, ?)"
cur.execute(sql, (12, "m"))
# Verify there's 1 row.
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == 1
# Insert a bunch.
params = list(enumerate("thecowsaremooing"))
cur.executemany(sql, params)
rows = cur.execute("select * from x_with_params.cowtest as r").fetchall()
assert len(rows) == len("thecowsaremooing") + 1
derby.rollback()
derby.autocommit = True
def test_fetchone(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert isinstance(rs.fetchone(), rs.Row)
def test_fetchmany(derby):
'''Assert all rows of result set have the correct class.
'''
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs.fetchmany(5)})
def test_fetchManyCount(derby):
derby.autocommit = False
cur = derby.cursor()
cur.execute("create schema x_with_params")
cur.execute("create table x_with_params.cowtest(a int, b char(1))")
sql = "insert into x_with_params.cowtest (a, b) values (?, ?)"
params = list(enumerate("thecowsaremooing"))
cur.executemany(sql, params)
rs = cur.execute("select a from x_with_params.cowtest")
ress = []
while True:
x = rs.fetchmany(3)
ress.append(x)
if len(x) < 3:
break
derby.rollback()
derby.autocommit = True
assert sum(map(len, ress)) == len("thecowsaremooing")
def test_fetchall(derby):
'''Assert all rows of result set have the correct class.
'''
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs.fetchall()})
def test_Cursor__iter__(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
assert all({isinstance(row, rs.Row) for row in rs})
def test_Cursor__iter__(derby):
cur = derby.cursor()
rs = cur.execute("select * from SYS.SYSTABLES")
# Exhaust all rows.
list(rs)
assert rs.fetchone() == None
def <API key>(derby):
cur = derby.cursor()
cur.close()
with pytest.raises(Error):
cur.execute("select * from SYS.SYSTABLES")
def <API key>(derby):
cur = derby.cursor()
cur.execute("select * from SYS.SYSTABLES")
cur.close()
with pytest.raises(Error):
cur.fetchone()
def test_close_twice(derby):
cur = derby.cursor()
cur.close()
with pytest.raises(Error):
cur.close()
|
## How to be a contributor to this project
Are you submitting a pull request?
* Make sure to fill out an issue for your PR, so that we have traceability as to what you are trying to fix,
versus how you fixed it.
* Spaces (not tabs), and 2 of them, that's what we like. Set your code style :)
* Sign the [Sonatype CLA](https://sonatypecla.herokuapp.com/sign-cla)
* Try to fix one thing per pull request! Many people work on this code, so the more focused your changes are, the less
of a headache other people will have when they merge their work in.
* Ensure your Pull Request passes tests either locally or via CircleCI (it will run automatically on your PR)
* Make sure to add yourself or your organization to CONTRIBUTORS.md as a part of your PR, if you are new to the project!
* If you're stuck, ask our [gitter channel](https://gitter.im/sonatype/nexus-developers)! There are a number of
experienced programmers who are happy to help with learning and troubleshooting.
Are you new and looking to dive in?
* Check our issues to see if there is something you can dive in to.
* Come hang out with us at our [gitter channel](https://gitter.im/sonatype/nexus-developers).
|
"""Unit-tests for `tree.visitors`
"""
from py2c import tree
from py2c.tree import visitors
from py2c.tests import Test, data_driven_test
from nose.tools import assert_equal
# TEST:: Add non-node fields
# Helper classes
class BasicNode(tree.Node):
_fields = []
class <API key>(tree.Node):
_fields = []
class <API key>(tree.Node):
_fields = []
class BasicNodeDeletable(tree.Node):
_fields = []
class ParentNode(tree.Node):
_fields = [
('child', tree.Node, 'OPTIONAL'),
]
class <API key>(tree.Node):
"""Node with list of nodes as field
"""
_fields = [
('child', tree.Node, 'ZERO_OR_MORE'),
]
# Concrete Visitors used for testing
class <API key>(visitors.<API key>):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
super().generic_visit(node)
def <API key>(self, node):
self.visited.append("visited Copy!")
class <API key>(visitors.<API key>):
def __init__(self):
super().__init__()
self.<API key> = None
def visit_BasicNode(self, node):
self.<API key> = self.access_path[:]
class EmptyTransformer(visitors.<API key>):
pass
class <API key>(visitors.<API key>):
def __init__(self):
super().__init__()
self.visited = []
def generic_visit(self, node):
self.visited.append(node.__class__.__name__)
return super().generic_visit(node)
def <API key>(self, node):
self.visited.append("visited Copy!")
return node
class <API key>(visitors.<API key>):
def __init__(self):
super().__init__()
self.<API key> = None
def visit_BasicNode(self, node):
self.<API key> = self.access_path[:]
return node
class <API key>(visitors.<API key>):
def visit_BasicNode(self, node):
return <API key>()
def <API key>(self, node):
return None # Delete this node
def <API key>(self, node):
return self.NONE_DEPUTY # Replace this node with None
def <API key>(self, node):
return [BasicNode(), <API key>()]
# Tests
class <API key>(Test):
"""py2c.tree.visitors.<API key>
"""
context = globals()
@data_driven_test("<API key>.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = <API key>()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order)
@data_driven_test("<API key>.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = <API key>()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.<API key>, access_path)
class <API key>(Test):
"""py2c.tree.visitors.<API key>
"""
context = globals()
@data_driven_test("<API key>.yaml", prefix="empty transformer does not transform ")
def <API key>(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
@data_driven_test("<API key>.yaml", prefix="visit order of ")
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = <API key>()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order)
@data_driven_test("<API key>.yaml", prefix="access path on visit of ")
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = <API key>()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.<API key>, access_path)
@data_driven_test("visitors-transform.yaml", prefix="transformation of ")
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = <API key>()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node)
if __name__ == '__main__':
from py2c.tests import runmodule
runmodule()
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\WindowSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="window-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'status_ventana') ?>
<?= $form->field($model, 'status_cortina') ?>
<?= $form->field($model, 'rain_sensor') ?>
<?= $form->field($model, 'light_sensor') ?>
<?= $form->field($model, 'voice_sensor') ?>
<?php // echo $form->field($model, 'datetime') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
from importlib import import_module
from inspect import getdoc
def attribs(name):
mod = import_module(name)
print name
print 'Has __all__?', hasattr(mod, '__all__')
print 'Has __doc__?', hasattr(mod, '__doc__')
print 'doc: ', getdoc(mod)
if __name__=='__main__':
attribs('cairo')
attribs('zope')
attribs('A.B.C')
import hacked
class Object(object):
pass
opt = Object()
opt.ignore_errors = False
a, d = hacked.<API key>('/home/ali/ws-pydev/apidocfilter/A/B',
'/home/ali/ws-pydev/apidocfilter/A/B/C',
opt)
print(a)
print(d)
|
#include "Statistics.hpp"
#include "CaptureInstance.hpp"
#include "MainWindow.hpp"
#include "ui_Statistics.h"
using namespace EPL_Viz;
using namespace EPL_DataCollect;
Statistics::Statistics(MainWindow *parent) : QDialog(parent), ui(new Ui::Statistics), mw(parent) {
ui->setupUi(this);
refresh();
}
Statistics::~Statistics() { delete ui; }
void Statistics::refresh() {
CaptureInstance *ci = mw->getCaptureInstance();
auto stats = ci->getCycleBuilder()->getStats();
auto ihStats = ci->getInputHandler()->getStats();
ui->List->clear();
// Make sure not to devide by 0
if (stats.cycleCount == 0)
stats.cycleCount = 1;
if (ihStats.packetsParsed == 0)
ihStats.packetsParsed = 1;
if (ihStats.cyclesParsed == 0)
ihStats.cyclesParsed = 1;
QList<QTreeWidgetItem *> items;
QTreeWidgetItem * pItem = nullptr;
items.append(new QTreeWidgetItem({"Cycle count", std::to_string(stats.cycleCount).c_str()}));
items.append(new QTreeWidgetItem({"Cycle count", std::to_string(stats.cycleCount).c_str()}));
items.append(new QTreeWidgetItem({"Packet count", std::to_string(stats.packetCount).c_str()}));
items.append(new QTreeWidgetItem({"Events count", std::to_string(stats.eventsCount).c_str()}));
items.append(new QTreeWidgetItem({"Packet parsed", std::to_string(ihStats.packetsParsed).c_str()}));
items.append(new QTreeWidgetItem({"Cycles parsed", std::to_string(ihStats.cyclesParsed).c_str()}));
items.append(new QTreeWidgetItem({"Cycle Processing time", ""}));
pItem = items.back();
items.append(new QTreeWidgetItem(pItem, {"Total", (std::to_string(stats.totalTime.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(stats.totalTime.count() / stats.cycleCount) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Time waited for packets to be parsed", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(stats.waitForPacketsTime.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(stats.waitForPacketsTime.count() / stats.cycleCount) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Packets parsing time", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(ihStats.timePacketsParsed.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem,
{"Average", (std::to_string(ihStats.timePacketsParsed.count() / ihStats.packetsParsed) + " ns").c_str()}));
items.append(new QTreeWidgetItem({"Packets of a Cycle parsing time", ""}));
pItem = items.back();
items.append(
new QTreeWidgetItem(pItem, {"Total", (std::to_string(ihStats.timeCyclesParsed.count()) + " ns").c_str()}));
items.append(new QTreeWidgetItem(
pItem, {"Average", (std::to_string(ihStats.timeCyclesParsed.count() / ihStats.cyclesParsed) + " ns").c_str()}));
ui->List->addTopLevelItems(items);
ui->List->expandAll();
ui->List->header()->resizeSection(0, 275);
}
|
layout: organization
category: national
title: Sereolipi Nomadic Education Foundation Inc.
impact_area: Children
keywords:
location_services:
location_offices:
website: www.thorntreeproject.org
description:
mission: |
Our mission is to help educate the children of traditional nomadic families in Northern Samburu. We work to help more Samburu children go to school and receive the level of education they desire, whether that is primary school, high school, technical school, or college. With hard work, resourcefulness, and a little help from the outside world, the Samburu people have begun to create significant, meaningful, and measurable change by providing education for their children. The Thorn Tree Project exists to do all it can to support their efforts.
Our mission comes from the Samburu people themselves. It is a privilege to be invited into the Samburu tribe, and we make sure that everything we do is in tune with their culture and aligned with their goals. We aim to have the smallest possible footprint in Samburu, maintaining our focus on education.
cash_grants:
grants:
service_opp:
services:
learn:
cont_relationship:
salutation:
first_name:
last_name:
<API key>:
city: Troutman
state: NC
address: |
PO Box 263
Troutman NC 28166
lat: 35.677955
lng: -80.879258
phone:
ext:
fax:
email:
preferred_contact:
<API key>:
|
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Vectors/Sqr Magnitude (Vector4)")]
[UnitFriendlyName("Sqr Magnitude")]
[UnitUsage(typeof(System.Single), <API key> = true)]
public class <API key> : JLExpression
{
[Parameter(ExpressionType = typeof(Vector4))]
public JLExpression OperandValue;
public override object GetAnyResult(IExecutionContext context)
{
Vector4 opValue = OperandValue.GetResult<Vector4>(context);
return opValue.SqrMagnitude();
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Sat Oct 20 16:08:50 CDT 2012 -->
<TITLE>
I-Index
</TITLE>
<META NAME="date" CONTENT="2012-10-20">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="I-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR>
<A NAME="_I_"></A><H2>
<B>I</B></H2>
<DL>
<DT><A HREF="../org/epri/pt2/gui/FuzzTestUtils.html#<API key>()"><B><API key>()</B></A> -
Method in class org.epri.pt2.gui.<A HREF="../org/epri/pt2/gui/FuzzTestUtils.html" title="class in org.epri.pt2.gui">FuzzTestUtils</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/RequestPanel.html#<API key>()"><B><API key>()</B></A> -
Method in class org.epri.pt2.fuzzer.<A HREF="../org/epri/pt2/fuzzer/RequestPanel.html" title="class in org.epri.pt2.fuzzer">RequestPanel</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/ResponsePanel.html#<API key>()"><B><API key>()</B></A> -
Method in class org.epri.pt2.fuzzer.<A HREF="../org/epri/pt2/fuzzer/ResponsePanel.html" title="class in org.epri.pt2.fuzzer">ResponsePanel</A>
<DD>
<DT><A HREF="../org/epri/pt2/gui/StatusArea.html#initTabComponent(int, java.lang.String, org.epri.pt2.gui.TestExecutionTask)"><B>initTabComponent(int, String, TestExecutionTask)</B></A> -
Method in class org.epri.pt2.gui.<A HREF="../org/epri/pt2/gui/StatusArea.html" title="class in org.epri.pt2.gui">StatusArea</A>
<DD>
<DT><A HREF="../org/epri/pt2/InterfaceMapper.html" title="class in org.epri.pt2"><B>InterfaceMapper</B></A> - Class in <A HREF="../org/epri/pt2/package-summary.html">org.epri.pt2</A><DD>The InterfaceMapper class provides a static mapping method
<A HREF="../org/epri/pt2/InterfaceMapper.html#getClass(org.epri.pt2.InterfaceType)"><CODE>InterfaceMapper.getClass(InterfaceType)</CODE></A> which returns an AbstractIfaceDO instance.<DT><A HREF="../org/epri/pt2/InterfaceMapper.html#InterfaceMapper()"><B>InterfaceMapper()</B></A> -
Constructor for class org.epri.pt2.<A HREF="../org/epri/pt2/InterfaceMapper.html" title="class in org.epri.pt2">InterfaceMapper</A>
<DD>
<DT><A HREF="../org/epri/pt2/InterfaceType.html" title="enum in org.epri.pt2"><B>InterfaceType</B></A> - Enum in <A HREF="../org/epri/pt2/package-summary.html">org.epri.pt2</A><DD>A list of permissible interface types.<DT><A HREF="../org/epri/pt2/gui/model/MyTableModel.html#isCellEditable(int, int)"><B>isCellEditable(int, int)</B></A> -
Method in class org.epri.pt2.gui.model.<A HREF="../org/epri/pt2/gui/model/MyTableModel.html" title="class in org.epri.pt2.gui.model">MyTableModel</A>
<DD>
<DT><A HREF="../org/epri/pt2/gui/model/<API key>.html#isCellEditable(int, int)"><B>isCellEditable(int, int)</B></A> -
Method in class org.epri.pt2.gui.model.<A HREF="../org/epri/pt2/gui/model/<API key>.html" title="class in org.epri.pt2.gui.model"><API key></A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/AbstractIfaceDO.html#isConnected()"><B>isConnected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/AbstractIfaceDO.html" title="class in org.epri.pt2.DO">AbstractIfaceDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isEnabled()"><B>isEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html#isErroredOrClosed()"><B>isErroredOrClosed()</B></A> -
Method in class org.epri.pt2.fuzzer.request.<A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html" title="class in org.epri.pt2.fuzzer.request">SocketHandler</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isFilteringEnabled()"><B>isFilteringEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/PacketDO.html#isFuzzed()"><B>isFuzzed()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isFuzzingEnabled()"><B>isFuzzingEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isInterceptEnabled()"><B>isInterceptEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html#isLeaf()"><B>isLeaf()</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html" title="class in org.epri.pt2.packetparser.treemodel">XMLNode</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLTreeModel.html#isLeaf(java.lang.Object)"><B>isLeaf(Object)</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLTreeModel.html" title="class in org.epri.pt2.packetparser.treemodel">XMLTreeModel</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html#isOpen()"><B>isOpen()</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html" title="class in org.epri.pt2.sniffer">PCAPEthListener</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferController.html#isOpen(org.epri.pt2.DO.DeviceDO)"><B>isOpen(DeviceDO)</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferController.html" title="class in org.epri.pt2.sniffer">SnifferController</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferInterface.html#isOpen()"><B>isOpen()</B></A> -
Method in interface org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferInterface.html" title="interface in org.epri.pt2.sniffer">SnifferInterface</A>
<DD>
<DT><A HREF="../org/epri/pt2/reassembler/TcpLink.html#isProcessed()"><B>isProcessed()</B></A> -
Method in class org.epri.pt2.reassembler.<A HREF="../org/epri/pt2/reassembler/TcpLink.html" title="class in org.epri.pt2.reassembler">TcpLink</A>
<DD>
<DT><A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html#isReadyToSend()"><B>isReadyToSend()</B></A> -
Method in class org.epri.pt2.fuzzer.request.<A HREF="../org/epri/pt2/fuzzer/request/SocketHandler.html" title="class in org.epri.pt2.fuzzer.request">SocketHandler</A>
<DD>
<DT><A HREF="../org/epri/pt2/reassembler/TcpReassembler.html#isRunning()"><B>isRunning()</B></A> -
Method in class org.epri.pt2.reassembler.<A HREF="../org/epri/pt2/reassembler/TcpReassembler.html" title="class in org.epri.pt2.reassembler">TcpReassembler</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/DataTypeDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/DataTypeDO.html" title="class in org.epri.pt2.DO">DataTypeDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/FuzzTestDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/FuzzTestDO.html" title="class in org.epri.pt2.DO">FuzzTestDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/PacketDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/DO/TestCaseDO.html#isSelected()"><B>isSelected()</B></A> -
Method in class org.epri.pt2.DO.<A HREF="../org/epri/pt2/DO/TestCaseDO.html" title="class in org.epri.pt2.DO">TestCaseDO</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html#isSnifferType(int)"><B>isSnifferType(int)</B></A> -
Method in class org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/PCAPEthListener.html" title="class in org.epri.pt2.sniffer">PCAPEthListener</A>
<DD>
<DT><A HREF="../org/epri/pt2/sniffer/SnifferInterface.html#isSnifferType(int)"><B>isSnifferType(int)</B></A> -
Method in interface org.epri.pt2.sniffer.<A HREF="../org/epri/pt2/sniffer/SnifferInterface.html" title="interface in org.epri.pt2.sniffer">SnifferInterface</A>
<DD>
<DT><A HREF="../org/epri/pt2/proxy/ProxyController.html#isSSLEnabled()"><B>isSSLEnabled()</B></A> -
Method in class org.epri.pt2.proxy.<A HREF="../org/epri/pt2/proxy/ProxyController.html" title="class in org.epri.pt2.proxy">ProxyController</A>
<DD>
<DT><A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html#isText()"><B>isText()</B></A> -
Method in class org.epri.pt2.packetparser.treemodel.<A HREF="../org/epri/pt2/packetparser/treemodel/XMLNode.html" title="class in org.epri.pt2.packetparser.treemodel">XMLNode</A>
<DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-8.html"><B>PREV LETTER</B></A>
<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">K</A> <A HREF="index-11.html">L</A> <A HREF="index-12.html">M</A> <A HREF="index-13.html">N</A> <A HREF="index-14.html">O</A> <A HREF="index-15.html">P</A> <A HREF="index-16.html">Q</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <HR>
</BODY>
</HTML>
|
class Requirement(object):
"""
Requirements are the basis for Dominion. They define
what needs to exist on a host/role, or perhaps what *mustn't* exist.
Requirements are defined on Roles.
"""
creation_counter = 0
"The base class for requirements."
def __init__(self, required=True, ensure=None, depends=None, post=None):
self.required = required
self.ensure = ensure or "exists"
self.depends = depends or ()
if self.ensure == "removed":
self.required = False
self.post = post or ()
# Increase the creation counter, and save our local copy.
self.creation_counter = Requirement.creation_counter
Requirement.creation_counter += 1
def __call__(self):
self.apply()
def apply(self):
if self.ensure == "exists" or self.required:
if hasattr(self, 'install'):
return self.install()
if self.ensure == "removed":
if hasattr(self, 'uninstall'):
return self.uninstall()
|
<?php
use app\components\Formatter;
use yii\helpers\Html;
?>
<div class="rep-wrapper">
<div id="stats">
<div id="rep-page-container">
<table class="rep-table">
<tbody>
<?php foreach ($reputes as $date => $repute): ?>
<tr class="rep-table-row">
<td class="rep-cell">
<span class="rep-up"><?php echo $repute['total']; ?></span>
</td>
<td title="<?php echo $date; ?>" class="rep-day ">
<a class="load-body <API key> hide-body <API key>" style=""></a>
<?php echo $date; ?>
</td>
</tr>
<tr class="loaded-body">
<td style="height: 0px; padding: 0px;" class="body-container body-loaded" colspan="2">
<div style="display: block;">
<div class="rep-breakdown">
<table class="tbl-reputation">
<tbody>
<?php foreach ($repute['list'] as $item): ?>
<tr class="rep-breakdown-row rep-recent-row expandable-row">
<td class="rep-left">
<span class="rep-up"><?php echo $item->reputation; ?></span>
</td>
<td title="<?php echo Formatter::time($item->time); ?>" class="rep-time"><?php echo Formatter::ago($item->time); ?></td>
<td class="rep-desc"><?php echo $item->lng; ?></td>
<td class="rep-link async-load load-prepped">
<?php
$url = $item->question->url;
if ($item->apostid > 0) {
$url .= '#' . $item->apostid;
}
echo Html::a(Html::encode($item->question->title), $url, array('class' => "answer-hyperlink"));
?>
</td>
</tr>
<tr class="loaded-body">
<td colspan="4" class="body-container" style="padding: 0px;"></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
expandPostBody('.tbl-reputation td.rep-link.async-load:not(.load-prepped)', null, null, 4);
});
</script>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= yii\widgets\LinkPager::widget(['pagination' => $pages, 'options' => ['id' => 'reputation-pager', 'class' => 'pagination']]); ?>
<script type="text/javascript">
var reputationView = 'post';
var reputationPageSize = 30;
$(function () {
expandPostBody('.rep-table td.async-load:not(.load-prepped)', '', null, 2);
if (!$('.rep-day .<API key>').length)
$(".rep-table .load-body").slice(0, 3).click();
});
</script>
</div>
</div>
</div>
|
include ../../Library/GNU.mk
Title= libzip
Name= libzip
Version= 0.12.2
Revision= 0
Site= http://nih.at/libzip/
Source= http://nih.at/libzip//$(Name)-$(Version).tar.bz2
License= BSD
LicenseFile= $(SourceDir)/LICENSE
define test_inner_hook
/usr/local/bin/zipcmp -h
/usr/local/bin/zipmerge -h
endef
|
package registry
import (
"crypto/tls"
"fmt"
"log"
"net/http"
"strings"
)
type LogfCallback func(format string, args ...interface{})
/*
* Discard log messages silently.
*/
func Quiet(format string, args ...interface{}) {
/* discard logs */
}
/*
* Pass log messages along to Go's "log" module.
*/
func Log(format string, args ...interface{}) {
log.Printf(format, args...)
}
type Registry struct {
URL string
Client *http.Client
Logf LogfCallback
}
/*
* Create a new Registry with the given URL and credentials, then Ping()s it
* before returning it to verify that the registry is available.
*
* You can, alternately, construct a Registry manually by populating the fields.
* This passes http.DefaultTransport to WrapTransport when creating the
* http.Client.
*/
func New(registryURL, username, password string) (*Registry, error) {
transport := http.DefaultTransport
return newFromTransport(registryURL, username, password, transport, Log)
}
/*
* Create a new Registry, as with New, using an http.Transport that disables
* SSL certificate verification.
*/
func NewInsecure(registryURL, username, password string) (*Registry, error) {
transport := &http.Transport{
TLSClientConfig: &tls.Config{
// TODO: Why?
InsecureSkipVerify: true, //nolint:gosec
},
}
return newFromTransport(registryURL, username, password, transport, Log)
}
/*
* Given an existing http.RoundTripper such as http.DefaultTransport, build the
* transport stack necessary to authenticate to the Docker registry API. This
* adds in support for OAuth bearer tokens and HTTP Basic auth, and sets up
* error handling this library relies on.
*/
func WrapTransport(transport http.RoundTripper, url, username, password string) http.RoundTripper {
tokenTransport := &TokenTransport{
Transport: transport,
Username: username,
Password: password,
}
basicAuthTransport := &BasicTransport{
Transport: tokenTransport,
URL: url,
Username: username,
Password: password,
}
errorTransport := &ErrorTransport{
Transport: basicAuthTransport,
}
return errorTransport
}
func newFromTransport(registryURL, username, password string, transport http.RoundTripper, logf LogfCallback) (*Registry, error) {
url := strings.TrimSuffix(registryURL, "/")
transport = WrapTransport(transport, url, username, password)
registry := &Registry{
URL: url,
Client: &http.Client{
Transport: transport,
},
Logf: logf,
}
if err := registry.Ping(); err != nil {
return nil, err
}
return registry, nil
}
func (r *Registry) url(pathTemplate string, args ...interface{}) string {
pathSuffix := fmt.Sprintf(pathTemplate, args...)
url := fmt.Sprintf("%s%s", r.URL, pathSuffix)
return url
}
func (r *Registry) Ping() error {
url := r.url("/v2/")
r.Logf("registry.ping url=%s", url)
resp, err := r.Client.Get(url)
if resp != nil {
defer resp.Body.Close()
}
return err
}
|
package com.sap.coap;
import com.ibm.saguaro.system.*;
import com.ibm.iris.*;
import com.ibm.saguaro.mrv6.*;
//##if LOGGING
import com.ibm.saguaro.logger.*;
//##endif
public class Message {
public byte[] header = new byte[4];
public byte[] token = null;
public byte[] payload = null;
public int payloadLength = 0;
public byte[] options;
public int optionArraySize = 0;
public int roundCounter = 0;
@Immutable public static final byte CON = 0x00;
@Immutable public static final byte NON = 0x01;
@Immutable public static final byte ACK = 0x02;
@Immutable public static final byte RST = 0x03;
@Immutable public static final byte EMPTY = 0x00;
@Immutable public static final byte GET = 0x01;
@Immutable public static final byte POST = 0x02;
@Immutable public static final byte PUT = 0x03;
@Immutable public static final byte DELETE = 0x04;
public final void setPayload(byte[] mypayload){
this.payload = mypayload;
this.payloadLength = mypayload.length;
}
public Message() {
header[0] = 0x40; // set the version number
}
<summary>
Constructor.
</summary>
<param name="type"> something </param>
<param name="tokenLen"> token legnth </param>
<param name="code"> CoAP message code </param>
<param name="msgid"> CoAP message id </param>
public Message(byte type, byte tokenLen, byte code, int msgid) {
setMessageHeader(type, tokenLen, code, msgid);
}
public final void setMessageHeader(byte type, byte tokenLen, byte code, int msgid) {
header[0] = (byte) ((0x40 | (type << 4)) | tokenLen);
header[1] = code;
Util.set16be(header,2,msgid);
}
public static byte createResponseCode(final byte cl, final byte cc) {
return (byte) ((cl << 5) | cc);
}
public final byte getVersion() {
return (byte) ((header[0] >>> 6) & 0x03);
}
public final byte getType() {
return (byte) ((header[0] & 0x30) >> 4);
}
public final void setType(final byte type) {
byte tl = (byte) (header [0] & 0x0F);
header[0] = (byte) ((0x40 | (type << 4)) | tl); // set the version number
}
public final byte getTokenLength() {
return (byte) (header[0] & 0x0F);
}
public final byte getCode() {
return header[1];
}
public final int getMessageId() {
return Util.get16be(header,2);
}
public final void clearOptions() {
options=null;
optionArraySize=0;
}
public final void clearPayload() {
payloadLength = 0;
payload = null;
}
public final byte[] getPayload() {
return this.payload;
}
public final int getPayloadSize() {
return this.payloadLength;
}
public byte[] <API key>() {
int partNo = 0;
int bufferOffset = 0;
int offset = <API key>(11, partNo);
if (offset<0)
return null;
int bufferSize = 0;
// Calculate buffer size
int firstOffset = offset;
while (offset>=0) {
if (partNo>0)
bufferSize++;
int valueSize = <API key>(offset);
bufferSize += valueSize;
partNo++;
offset = <API key>(11, partNo);
}
byte[] buffer = new byte[bufferSize];
partNo=0;
offset = <API key>(11, partNo);
int valueSize = <API key>(offset);
byte[] data = <API key>(offset);
while (data != null) {
if (partNo>0) {
buffer[bufferOffset]='/';
bufferOffset++;
}
partNo++;
Util.copyData(data, 0, buffer, bufferOffset, valueSize);
bufferOffset += valueSize;
offset = <API key>(11, partNo);
data = null;
if (offset>=0) {
valueSize = <API key>(offset);
data = <API key>(offset);
}
}
return buffer;
}
public boolean hasOption(int id) {
return (<API key>(id,0) != -1);
}
public void insertOption(int id, byte[] value, int valueSize) {
//1. find position
// an ascending order of the options has to be kept
// find start offsets of the 'enclosing' options left and right of the one to insert
// special case: inserting at the beginning: offsetRightOption = 0
// special case: inserting at the end: offsetRightOption = optionArraySize (i.e. points behind the array)
int offsetRightOption = 0;
int idRightOption = 0;
int idLeftOption = 0;
while(offsetRightOption < optionArraySize) { //if the loop is not left by a break, the option has to be inserted at the end
idRightOption = <API key>(options, offsetRightOption, idRightOption);
if(idRightOption > id) { //insertion point found
break;
}
idLeftOption = idRightOption;
offsetRightOption = <API key>(options, offsetRightOption);
}
//2. calculate value length field size for this option
int <API key> = <API key>(valueSize);
//3. calculate delta value for this option.
// depends on the previous id (being 0 when no previous option exists)
int delta = id - idLeftOption;
//4. calculate delta field size for this option
int <API key> = <API key>(delta);
//5. recalculate the delta field size for the next option
// the delta value for the next option decreases due to the insertion
// this may result in less bytes being used for the size field
int <API key> = 0;
int <API key> = 0;
int deltaRightOptionNew = 0;
int <API key> = 0;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
<API key> = <API key>(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = idRightOption - id;
<API key> = <API key>(deltaRightOptionNew);
//determine the size difference between the new and the old field
<API key> = <API key> - <API key>;
}
//7. calculate total size of new option array
int optionArraySizeNew = optionArraySize
+ 1
+ <API key>
+ <API key>
+ valueSize
- <API key>;
//8. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//9. copy options until insertion point to new array
if(offsetRightOption>0) {
Util.copyData(options, 0, optionsNew, 0, offsetRightOption);
}
int currentOffset = offsetRightOption; //next position to read from the old options where no additional option is present. points now to the header byte of the next option
int offsetFirstByte = offsetRightOption; //points to the header byte of the option to insert
int currentOffsetNew = offsetFirstByte+1; //next position to write in the new array (after the header byte of the option to insert)
//10. write delta
if(<API key> == 1) {
optionsNew[offsetFirstByte] += 13 << 4;
optionsNew[currentOffsetNew] = (byte)(delta-13);
}
else if(<API key> == 2) {
optionsNew[offsetFirstByte] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew, delta-269);
}
else { //<API key> == 0
optionsNew[offsetFirstByte] += delta << 4;
}
currentOffsetNew += <API key>;
//11. write value length
if(<API key> == 1) {
optionsNew[offsetFirstByte] += 13;
optionsNew[currentOffsetNew] = (byte)(valueSize-13);
}
else if(<API key> == 2) {
optionsNew[offsetFirstByte] += 14;
Util.set16(optionsNew, currentOffsetNew, valueSize-269);
}
else { //<API key> == 0
optionsNew[offsetFirstByte] += valueSize;
}
currentOffsetNew += <API key>;
//12. copy value
if(valueSize>0) {
Util.copyData(value, 0, optionsNew, currentOffsetNew, valueSize);
}
currentOffsetNew += valueSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//13. write header of next option with adjusted delta
//length stays constant, delta is erased
optionsNew[currentOffsetNew] = (byte) (options[currentOffset] & 0x0F);
//write recalculated delta to the next option
if(<API key> == 1) {
optionsNew[currentOffsetNew] += 13 << 4;
optionsNew[currentOffsetNew+1] = (byte) (<API key>);
}
else if(<API key> == 2){
optionsNew[currentOffsetNew] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew+1, <API key>);
}
else { //<API key> == 0
optionsNew[currentOffsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
currentOffsetNew += 1+<API key>;
//jump behind the next option's extended delta field in the old array
currentOffset += 1+<API key>;
//14. copy rest of array (= next option's extended value length field, next option's value, all subsequent options)
int restLength = optionArraySize - currentOffset;
Util.copyData(options, currentOffset, optionsNew, currentOffsetNew, restLength);
}
//15. replace old options by new
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public int <API key>(int wantedOptionId, int matchNumber) {
int currentOptionOffset = 0;
int currentDelta = 0;
while(currentOptionOffset < optionArraySize) {
int currentOptionId = <API key>(options, currentOptionOffset, currentDelta);
if(currentOptionId == wantedOptionId) { //first of the options has been found. iterate them until the right match number is found
for(int i = 0; i<matchNumber; i++) {
currentOptionOffset = <API key>(options, currentOptionOffset);
if(currentOptionOffset == optionArraySize || (options[currentOptionOffset] & 0xF0) != 0x00) {
return -1; //array length has been exceeded or the delta is not 0, i.e. an option with an higher id was found
}
}
return currentOptionOffset;
}
if(currentOptionId > wantedOptionId) {
return -1;
}
currentDelta = currentOptionId;
currentOptionOffset = <API key>(options, currentOptionOffset);
}
return -1;
}
public byte[] <API key>(int offset) {
int valueSize = <API key>(options, offset);
int headerSize = <API key>(options, offset);
offset += headerSize;
byte[] value = new byte[valueSize];
if(valueSize>0) {
Util.copyData(options, offset, value, 0, valueSize);
}
return value;
}
public int <API key>(int offset) {
return <API key>(options, offset);
}
public void <API key>(int offset) {
//1. get delta of this option
int delta = <API key>(options, offset, 0); //this method with 0 as previous delta gives just the delta of this option
//2. get length of the block to remove
int optionSize = <API key>(options, offset)
+ <API key>(options, offset);
//3. recalculate next option's new delta value
int offsetRightOption = offset + optionSize; //same as <API key>(options, offset);
int deltaRightOption;
int <API key> = 0;
int deltaRightOptionNew = 0;
int <API key> = 0;
int <API key> = 0;
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaRightOption = <API key>(options, offsetRightOption, 0); //this method with 0 as previous delta gives just the delta of this option
<API key> = <API key>(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = delta + deltaRightOption;
<API key> = <API key>(deltaRightOptionNew);
//determine the size difference between the new and the old field
<API key> = <API key> - <API key>;
}
//6. calculate new array size
int optionArraySizeNew = optionArraySize
- optionSize
+ <API key>;
//7. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//8. copy old option array to the start of the option to remove
if (offset>0)
Util.copyData(options, 0, optionsNew, 0, offset);
int offsetNew = offset;
offset += optionSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//9. write new delta for next option
//length stays constant, delta is erased
optionsNew[offsetNew] = (byte) (options[offset] & 0x0F);
//write recalculated delta to the next option
if(<API key> == 1) {
optionsNew[offsetNew] += 13 << 4;
optionsNew[offsetNew+1] = (byte) (<API key>);
}
else if(<API key> == 2){
optionsNew[offsetNew] += 14 << 4;
Util.set16(optionsNew, offsetNew+1, <API key>);
}
else { //<API key> == 0
optionsNew[offsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
offsetNew += 1+<API key>;
//jump behind the next option's extended delta field in the old array
offset += 1+<API key>;
//10. copy rest of the array
int restLength = optionArraySizeNew - offsetNew;
Util.copyData(options, offset, optionsNew, offsetNew, restLength);
}
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public void removeOptionWithId(int id, int matchNumber) {
int offset = <API key>(id, matchNumber);
<API key>(offset);
}
public byte[] valueOfOptionWithId(int id, int no) {
int partNo = 0;
int offset = <API key>(id, no);
if (offset>=0) {
int valueSize = <API key>(offset);
byte[] data = <API key>(offset);
return data;
}
return null;
}
public int <API key>(int offset) {
return <API key>(this.options, offset);
}
public int <API key>(int offset, int currentDelta) {
return <API key>(this.options, offset, currentDelta);
}
public void encodeTo(byte[] buffer, int offset) {
int iOffset = 0;
Util.copyData(header, 0, buffer, offset, 4);
iOffset+=4;
byte tokenLength = this.getTokenLength();
if (tokenLength > 0) {
Util.copyData(token,0, buffer, offset+iOffset, tokenLength);
iOffset += tokenLength;
}
if (optionArraySize>0) {
Util.copyData(options, 0, buffer, offset+iOffset, optionArraySize);
iOffset += optionArraySize;
}
if (this.payloadLength!=0) {
buffer[offset+iOffset] = (byte) 0xFF;
iOffset++;
Util.copyData(this.payload,0, buffer, offset+iOffset, this.payloadLength);
}
}
// Return:
// 0: OK
// -1: Protocol error
// -2: Currently unsupported feature
public byte decode(byte[] inBuffer, int offset, int len) {
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: ENTER DECODE"));
Logger.flush(Mote.INFO);
//##endif
int inOffset = offset;
int endLen = offset+len;
payloadLength = 0;
Util.copyData(inBuffer, offset, header, 0, 4);
inOffset += 4;
// Read token
byte tokenLength = getTokenLength();
if(tokenLength > 8) {
return -1;
}
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: token len"));
Logger.appendInt(tokenLength);
Logger.flush(Mote.INFO);
//##endif
if (tokenLength>0) {
token = new byte[tokenLength];
Util.copyData(inBuffer, inOffset, token, 0, tokenLength);
}
inOffset += tokenLength;
// Check if end of Message
if (inOffset >= endLen) // Zero length Message, zero options
return 0;
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: start reading options "));
Logger.flush(Mote.INFO);
//##endif
// Check if payload marker or options
int optionOffset = inOffset;
inOffset = jumpOverOptions(inBuffer, inOffset, endLen);
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: new offset"));
Logger.appendInt(inOffset);
Logger.appendString(csr.s2b("CoAPDecode :: endlen"));
Logger.appendInt(endLen);
Logger.flush(Mote.INFO);
//##endif
optionArraySize = inOffset - optionOffset; //may be 0 if no options are given
options = new byte[optionArraySize];
if(optionArraySize > 0) {
Util.copyData(inBuffer, optionOffset, options, 0, optionArraySize);
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: end reading options "));
Logger.flush(Mote.INFO);
//##endif
if (inOffset == endLen) { // Zero length Message
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: no payload "));
Logger.flush(Mote.INFO);
//##endif
return 0;
}
if (inBuffer[inOffset] == (byte) 0xFF) {
inOffset++;
if(inOffset == endLen) { //protocol error: there is no payload though the marker indicates
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
// Payload
payloadLength = endLen-inOffset;
payload = new byte[payloadLength];
Util.copyData(inBuffer, inOffset, payload, 0, payloadLength);
}
else {
inOffset++;
if(inOffset < endLen) { //protocol error: there is payload though there is no marker
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
}
return 0;
}
public final int getMessageLength() {
int len=4+getTokenLength();
if (this.payloadLength!=0)
len += 1+payloadLength;
len += optionArraySize;
return len;
}
public final Packet <API key>(int inDstPort, byte[] inDstAddr, byte[] inSrcAddr, int srcPort) {
int dstport = inDstPort;
int lenp = getMessageLength();
Packet tempPacket = Mac.getPacket();
tempPacket.release();
Address.copyAddress(inDstAddr, 0, tempPacket.dstaddr, 0);
Address.copyAddress(inSrcAddr, 0, tempPacket.srcaddr, 0);
tempPacket.create(dstport, srcPort, lenp);
encodeTo(tempPacket.payloadBuf, tempPacket.payloadOff);
return tempPacket;
}
private static int jumpOverOptions(byte[] inBuffer, int offset, int len) {
int nextOptionOffset = offset;
while(nextOptionOffset < len && inBuffer[nextOptionOffset] != (byte) 0xFF) {
// checking for protocol violation -- one of the nibbles is F but it's not the payload marker
// check belongs only here since the first time parsing of a received message happens here
if( (inBuffer[offset] & 0x0F) == 0x0F || (inBuffer[offset] & 0xF0) == 0xF0 ) {
return -1;
}
nextOptionOffset = <API key>(inBuffer, nextOptionOffset);
}
return nextOptionOffset;
}
private static int <API key>(byte[] inBuffer, int offset) {
int headerSize = <API key>(inBuffer, offset);
int valueSize = <API key>(inBuffer, offset);
int currentOptionSize = headerSize + valueSize;
return offset + currentOptionSize;
}
private static int <API key>(byte[] inBuffer, int offset) {
int size = 1;
size += <API key>(inBuffer, offset);
size += <API key>(inBuffer, offset);
return size;
}
private static int <API key>(byte[] inBuffer, int offset) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return 0;
if(optionDelta == 13)
return 1;
return 2; //optionDelta == 14
}
private static int <API key>(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return 0;
if(optionLength == 13)
return 1;
return 2; //optionLength == 14
}
private static int <API key>(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return optionLength;
else {
offset += 1 + <API key>(inBuffer, offset);
if(optionLength == 13) {
return inBuffer[offset] + 13;
}
return Util.get16(inBuffer, offset) + 269; //optionLength == 14
}
}
private static int <API key>(byte[] inBuffer, int offset, int currentDelta) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return currentDelta + optionDelta;
else {
offset += 1;
if(optionDelta == 13) {
return currentDelta + inBuffer[offset] + 13;
}
return currentDelta + Util.get16(inBuffer, offset) + 269; //optionDelta == 14
}
}
private static int <API key>(int input) {
if(input<13)
return 0;
else if(input >= 13 && input < 269)
return 1;
return 2; //input >= 269
}
}
|
// #include "StdAfx.h"
#include "OLPreloadArchive.h"
#include "OgreFileSystem.h"
#include "LookingGlassOgre.h"
#include "RendererOgre.h"
namespace LG {
OLPreloadArchive::OLPreloadArchive( const Ogre::String& name, const Ogre::String& archType )
: Ogre::Archive(name, archType) {
LG::Log("OLPreloadArchive creation: n=%s, t=%s", name.c_str(), archType.c_str());
m_FSArchive = NULL;
return;
}
OLPreloadArchive::~OLPreloadArchive(void) {
unload();
}
Get the name of this archive
// const String& OLPreloadArchive::getName(void) const { return mName; }
Returns whether this archive is case sensitive in the way it matches files
bool OLPreloadArchive::isCaseSensitive(void) const {
return m_FSArchive->isCaseSensitive();
}
// Loads the archive.
void OLPreloadArchive::load() {
// this is really a wrapper for a filesystem archive
LG::Log("OLPreloadArchive::load(): mName=%s", mName.c_str());
<API key> = LG::GetParameter("Renderer.Ogre.DefaultMeshFilename");
LG::Log("OLPreloadArchive::load(): DefaultMeshFile=%s", <API key>.c_str());
<API key> = LG::GetParameter("Renderer.Ogre.<API key>");
LG::Log("OLPreloadArchive::load(): DefaultTextureFile=%s", <API key>.c_str());
m_FSArchive = OGRE_NEW Ogre::FileSystemArchive(mName, "XXOLFilesystem");
m_FSArchive->load();
}
// Unloads the archive.
void OLPreloadArchive::unload() {
Ogre::ArchiveManager::getSingleton().unload(m_FSArchive);
}
// The preloaded entities are in a filesystem without the grid name at the beginning.
// This routine strips the grid name of the beginning and looks for the file.
Ogre::DataStreamPtr OLPreloadArchive::open(const Ogre::String& filename, bool readonly) const {
LG::Log("OLPreloadArchive::open(%s)", filename.c_str());
Ogre::String entityName = <API key>(filename);
if (m_FSArchive->exists(entityName)) {
return m_FSArchive->open(entityName);
}
// if the file doesn't exist, we shouldn't have been asked for it
LG::Log("OLPreloadArchive::open(): the entity didn't exist!!!!. '%s'", entityName.c_str());
return Ogre::DataStreamPtr(new Ogre::MemoryDataStream(10));
}
Ogre::DataStreamPtr OLPreloadArchive::open(const Ogre::String& filename) const {
return this->open(filename, true);
}
// List all file names in the archive.
Ogre::StringVectorPtr OLPreloadArchive::list(bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::list()");
return m_FSArchive->list(recursive, dirs);
}
// List all files in the archive with accompanying information.
Ogre::FileInfoListPtr OLPreloadArchive::listFileInfo(bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::listFileInfo()");
return m_FSArchive->listFileInfo(recursive, dirs);
}
Ogre::// Find all file or directory names matching a given pattern
StringVectorPtr OLPreloadArchive::find(const Ogre::String& pattern, bool recursive, bool dirs) {
LG::Log("OLPreloadArchive::find(%s)", pattern.c_str());
return m_FSArchive->find(pattern, recursive, dirs);
}
// Find out if the named file exists (note: fully qualified filename required) */
bool OLPreloadArchive::exists(const Ogre::String& filename) {
// Ogre::String entityName = <API key>(filename);
// bool answer = m_FSArchive->exists(<API key>(filename));
// LG::Log("OLPreloadArchive::exists(%s)(%s)(%s)", filename.c_str(),
// entityName.c_str(), answer ? "exists" : "does not exist");
// return answer;
return m_FSArchive->exists(<API key>(filename));
}
// Retrieve the modification time of a given file */
time_t OLPreloadArchive::getModifiedTime(const Ogre::String& filename) {
return m_FSArchive->getModifiedTime(<API key>(filename));
}
// Find all files or directories matching a given pattern in this
Ogre::FileInfoListPtr OLPreloadArchive::findFileInfo(const Ogre::String& pattern,
bool recursive, bool dirs) {
return m_FSArchive->findFileInfo(pattern, recursive, dirs);
}
const Ogre::String& <API key>::getType(void) const {
static Ogre::String name = OLPreloadTypeName;
return name;
}
Ogre::Archive* <API key>::createInstance( const Ogre::String& name ) {
LG::Log("<API key>::createInstance(%s)", name.c_str());
return OGRE_NEW OLPreloadArchive(name, OLPreloadTypeName);
}
// The filename passed to us has the grid name at the beginning. Remove that and
// return the result. We presume it's everything up the slash.
Ogre::String OLPreloadArchive::<API key>(Ogre::String filename) const {
int pos = filename.find("/");
if (pos > 0) {
return filename.substr(pos + 1);
}
return Ogre::String("");
}
}
|
import py
try:
from pypy.rpython.test.test_llinterp import interpret
except ImportError:
py.test.skip('Needs PyPy to be on the PYTHONPATH')
from rply import ParserGenerator, Token
from rply.errors import <API key>
from .base import BaseTests
from .utils import FakeLexer, BoxInt, ParserState
class TestTranslation(BaseTests):
def run(self, func, args):
return interpret(func, args)
def test_basic(self):
pg = ParserGenerator(["NUMBER", "PLUS"])
@pg.production("main : expr")
def main(p):
return p[0]
@pg.production("expr : expr PLUS expr")
def expr_op(p):
return BoxInt(p[0].getint() + p[2].getint())
@pg.production("expr : NUMBER")
def expr_num(p):
return BoxInt(int(p[0].getstr()))
with self.assert_warns(<API key>, "1 shift/reduce conflict"):
parser = pg.build()
def f(n):
return parser.parse(FakeLexer([
Token("NUMBER", str(n)),
Token("PLUS", "+"),
Token("NUMBER", str(n))
])).getint()
assert self.run(f, [12]) == 24
def test_state(self):
pg = ParserGenerator(["NUMBER", "PLUS"], precedence=[
("left", ["PLUS"]),
])
@pg.production("main : expression")
def main(state, p):
state.count += 1
return p[0]
@pg.production("expression : expression PLUS expression")
def expression_plus(state, p):
state.count += 1
return BoxInt(p[0].getint() + p[2].getint())
@pg.production("expression : NUMBER")
def expression_number(state, p):
state.count += 1
return BoxInt(int(p[0].getstr()))
parser = pg.build()
def f():
state = ParserState()
return parser.parse(FakeLexer([
Token("NUMBER", "10"),
Token("PLUS", "+"),
Token("NUMBER", "12"),
Token("PLUS", "+"),
Token("NUMBER", "-2"),
]), state=state).getint() + state.count
assert self.run(f, []) == 26
|
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>SLS_PHP_SDK » \<API key></title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/<API key>.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/<API key>.png">
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner"><div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">SLS_PHP_SDK</a><div class="nav-collapse"><ul class="nav">
<li class="dropdown">
<a href="#api" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b></a><ul class="dropdown-menu">
<li><a>Packages</a></li>
<li><a href="../packages/SLS_PHP_SDK.html"><i class="icon-folder-open"></i> SLS_PHP_SDK</a></li>
</ul>
</li>
<li class="dropdown" id="charts-menu">
<a href="#charts" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="../graph_class.html"><i class="icon-list-alt"></i> Class hierarchy diagram</a></li></ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#reports" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b></a><ul class="dropdown-menu">
<li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors
<span class="label label-info">290</span></a></li>
<li><a href="../markers.html"><i class="icon-map-marker"></i> Markers
<ul></ul></a></li>
<li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements
<span class="label label-info">0</span></a></li>
</ul>
</li>
</ul></div>
</div></div>
<div class="go_to_top"><a href="
</div>
<div id="___" class="container">
<noscript><div class="alert alert-warning">
Javascript is disabled; several features are only available
if Javascript is enabled.
</div></noscript>
<div class="row">
<div class="span4">
<div xmlns:php="http://php.net/xsl" class="btn-toolbar">
<div class="btn-group visibility" data-toggle="buttons-checkbox">
<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>
</div>
<div class="btn-group view pull-right" data-toggle="buttons-radio">
<button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button>
</div>
</div>
<ul xmlns:php="http://php.net/xsl" class="side-nav nav nav-list">
<li class="nav-header">
<i title="Methods" class="icon-custom icon-method"></i> Methods
<ul>
<li class="method public "><a href="
<li class="method public inherited"><a href="
<li class="method public inherited"><a href="#method_getProject" title="getProject() :: Get project name"><span class="description">Get project name</span><pre>getProject()</pre></a></li>
<li class="method public inherited"><a href="#method_setProject" title="setProject() :: Set project name"><span class="description">Set project name</span><pre>setProject()</pre></a></li>
</ul>
</li>
<li class="nav-header">
<i title="Properties" class="icon-custom icon-property"></i> Properties
<ul></ul>
</li>
<li class="nav-header private">» Private
<ul><li class="property private "><a href="#property_project" title="$project() :: "><span class="description">project name</span><pre>$project</pre></a></li></ul>
</li>
</ul>
</div>
<div class="span8">
<a xmlns:php="http:
<li>
<a href="../index.html"><i title="Classes" class="icon-custom icon-class"></i></a><span class="divider">\</span>
</li>
<li class="active">
<span class="divider">\</span><a href="../classes/<API key>.html"><API key></a>
</li>
</ul>
<div xmlns:php="http://php.net/xsl" class="element class">
<p class="short_description">The request used to list logstore from sls.</p>
<div class="details">
<div class="long_description"></div>
<table class="table table-bordered">
<tr>
<th>author</th>
<td><a href="">sls_dev</a></td>
</tr>
<tr>
<th>package</th>
<td><a href="../packages/SLS_PHP_SDK.html">SLS_PHP_SDK</a></td>
</tr>
<tr>
<th>inherited_from</th>
<td>\<API key></td>
</tr>
</table>
<h3>
<i title="Methods" class="icon-custom icon-method"></i> Methods</h3>
<a id="method___construct"></a><div class="element clickable method public method___construct " data-toggle="collapse" data-target=".method___construct .collapse" title="public">
<h2><API key> constructor</h2>
<pre>__construct(string $project<code> = null</code>) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>inherited_from</th>
<td>\<API key>::__construct()</td>
</tr></table>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<a id="method___construct"></a><div class="element clickable method public method___construct inherited" data-toggle="collapse" data-target=".method___construct .collapse" title="public">
<h2><API key> constructor</h2>
<pre>__construct(string $project) </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<a id="method_getProject"></a><div class="element clickable method public method_getProject inherited" data-toggle="collapse" data-target=".method_getProject .collapse" title="public">
<h2>Get project name</h2>
<pre>getProject() : string</pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Returns</h3>
<div class="subelement response">
<code>string</code>project name</div>
</div></div>
</div>
<a id="method_setProject"></a><div class="element clickable method public method_setProject inherited" data-toggle="collapse" data-target=".method_setProject .collapse" title="public">
<h2>Set project name</h2>
<pre>setProject(string $project) </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$project</h4>
<code>string</code><p>project name</p></div>
</div></div>
</div>
<h3>
<i title="Properties" class="icon-custom icon-property"></i> Properties</h3>
<a id="property_project"> </a><div class="element clickable property private property_project" data-toggle="collapse" data-target=".property_project .collapse" title="private">
<h2>project name</h2>
<pre>$project : string</pre>
<div class="row collapse"><div class="detail-description">
<h3>Default</h3>
<div class="subelement argument"></div>
</div></div>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
</div>
</div>
</div>
</div>
<div class="row"><footer class="span12">
Template is built using <a href="http:
Documentation is powered by <a href="http:
generated on 2015-01-26T01:53:31-08:00.<br></footer></div>
</div>
</body>
</html>
|
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String formatType1(String date)
{
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType2(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType3(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
}
|
#ifndef <API key>
#define <API key>
#include <stdint.h>
#include <map>
#include <memory>
#include "base/containers/lru_cache.h"
#include "base/macros.h"
#include "base/sequence_checker.h"
#include "gpu/ipc/service/<API key>.h"
#include "media/base/video_decoder.h"
#include "media/gpu/test/video_player/<API key>.h"
#include "media/media_buildflags.h"
#include "media/video/<API key>.h"
namespace media {
class VideoFrame;
namespace test {
class FrameRenderer;
// The test VDA video decoder translates between the media::VideoDecoder and the
// media::<API key> interfaces. This makes it possible to run
// VD-based tests against VDA's.
class TestVDAVideoDecoder : public media::VideoDecoder,
public <API key>::Client {
public:
// Constructor for the TestVDAVideoDecoder.
TestVDAVideoDecoder(bool use_vd_vda,
const gfx::ColorSpace& target_color_space,
FrameRenderer* const frame_renderer,
gpu::<API key>* <API key>);
TestVDAVideoDecoder(const TestVDAVideoDecoder&) = delete;
TestVDAVideoDecoder& operator=(const TestVDAVideoDecoder&) = delete;
~TestVDAVideoDecoder() override;
// media::VideoDecoder implementation
VideoDecoderType GetDecoderType() const override;
bool IsPlatformDecoder() const override;
void Initialize(const VideoDecoderConfig& config,
bool low_delay,
CdmContext* cdm_context,
InitCB init_cb,
const OutputCB& output_cb,
const WaitingCB& waiting_cb) override;
void Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) override;
void Reset(base::OnceClosure reset_cb) override;
bool <API key>() const override;
bool <API key>() const override;
int <API key>() const override;
private:
// media::<API key>::Client implementation
void <API key>(Status status) override;
void <API key>(uint32_t <API key>,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
uint32_t texture_target) override;
void <API key>(uint32_t <API key>,
VideoPixelFormat format,
uint32_t textures_per_buffer,
const gfx::Size& dimensions,
const gfx::Rect& visible_rect,
uint32_t texture_target) override;
void <API key>(int32_t picture_buffer_id) override;
void PictureReady(const Picture& picture) override;
void <API key>(int32_t picture_buffer_id);
void <API key>(int32_t bitstream_buffer_id) override;
void NotifyFlushDone() override;
void NotifyResetDone() override;
void NotifyError(<API key>::Error error) override;
// Helper thunk to avoid dereferencing WeakPtrs on the wrong thread.
static void <API key>(
absl::optional<base::WeakPtr<TestVDAVideoDecoder>> decoder_client,
scoped_refptr<base::SequencedTaskRunner> task_runner,
int32_t picture_buffer_id);
// Get the next bitstream buffer id to be used.
int32_t <API key>();
// Get the next picture buffer id to be used.
int32_t <API key>();
// Called when initialization is done. The callback is stored only when VDA
// allows deferred initialization.
InitCB init_cb_;
// Called when a buffer is decoded.
OutputCB output_cb_;
// Called when the decoder finished flushing.
DecodeCB flush_cb_;
// Called when the decoder finished resetting.
base::OnceClosure reset_cb_;
// Whether <API key> is used.
bool use_vd_vda_;
// Output color space, used as hint to decoder to avoid conversions.
const gfx::ColorSpace target_color_space_;
// Frame renderer used to manage GL context.
FrameRenderer* const frame_renderer_;
#if BUILDFLAG(<API key>)
// Owned by VideoDecoderClient.
gpu::<API key>* const <API key>;
#endif // BUILDFLAG(<API key>)
// Map of video frames the decoder uses as output, keyed on picture buffer id.
std::map<int32_t, scoped_refptr<VideoFrame>> video_frames_;
// Map of video frame decoded callbacks, keyed on bitstream buffer id.
std::map<int32_t, DecodeCB> decode_cbs_;
// Records the time at which each bitstream buffer decode operation started.
base::LRUCache<int32_t, base::TimeDelta> <API key>;
int32_t <API key> = 0;
int32_t <API key> = 0;
std::unique_ptr<<API key>> decoder_;
scoped_refptr<base::SequencedTaskRunner> <API key>;
SEQUENCE_CHECKER(<API key>);
base::WeakPtr<TestVDAVideoDecoder> weak_this_;
base::WeakPtrFactory<TestVDAVideoDecoder> weak_this_factory_{this};
};
} // namespace test
} // namespace media
#endif // <API key>
|
extract:
${tooldir}/ecore2bgf BIBTEXML.ecore grammar.bgf
include ../../Makefile.grammar
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2619.SirLancebot2016.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc2619.SirLancebot2016.subsystems.*;
public class CrossRockWallCG extends CommandGroup {
double distanceFromStart = 4.2;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
public CrossRockWallCG() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=<API key>
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=<API key>
addSequential(new DriveXfeet(distanceFromStart));
addSequential(new DriveUntilFlat(1));
}
}
|
#include<iostream>
using namespace std;
int n,k;
const int maxn=100010;
bool b[2*maxn];
struct
{
int num,cn;
}queue[2*maxn];
int head,tail;
void bfs()
{
b[n]=1;
queue[0].num=n;
queue[0].cn=1;
while(head<=tail)
{
if(queue[head].num==k)
{
printf("%d\n",queue[head].cn);
return;
}
else if(queue[head].num>k&&!b[queue[head].num-1])
{
b[queue[head].num-1]=1;
queue[++tail].num=queue[head].num-1;
queue[tail].cn=queue[head].cn+1;
}
else
{
if(queue[head].num>0&&!b[queue[head].num-1])
{
b[queue[head].num-1]=1;
queue[++tail].num=queue[head].num-1;
queue[tail].cn=queue[head].cn+1;
}
if(!b[queue[head].num*2])
{
b[queue[head].num*2]=1;
queue[++tail].num=queue[head].num*2;
queue[tail].cn=queue[head].cn+1;
}
if(!b[queue[head].num+1])
{
b[queue[head].num+1]=1;
queue[++tail].num=queue[head].num+1;
queue[tail].cn=queue[head].cn+1;
}
}
++head;
}
}
int main()
{
scanf("%d%d",&n,&k);
if(n==k)
{
printf("1\n");
return 0;
}
memset(b,0,sizeof(b));
head=tail=0;
bfs();
return 0;
}
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "contact".
*
* @property integer $id
* @property string $type
* @property string $name
* @property string $lastname
* @property string $email
* @property string $cellphone
* @property string $message
* @property string $identity
* @property string $medium
*/
class Contact extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'contact';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['type', 'name', 'lastname', 'email', 'cellphone', 'message'], 'required'],
[['type', 'message'], 'string'],
[['name', 'lastname', 'email'], 'string', 'max' => 150],
[['cellphone', 'identity'], 'string', 'max' => 10],
[['medium'], 'string', 'max' => 50]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'type' => 'Type',
'name' => 'Name',
'lastname' => 'Lastname',
'email' => 'Email',
'cellphone' => 'Cellphone',
'message' => 'Message',
'identity' => 'Identity',
'medium' => 'Medium',
];
}
}
|
#include <iostream>
#include <type_traits>
#include <vector>
#include <cassert>
#include <agency/execution/executor/sequenced_executor.hpp>
#include <agency/execution/executor/executor_traits.hpp>
int main()
{
using namespace agency;
static_assert(<API key><sequenced_executor>::value,
"sequenced_executor should be a bulk synchronous executor");
static_assert(is_bulk_executor<sequenced_executor>::value,
"sequenced_executor should be a bulk executor");
static_assert(detail::is_detected_exact<<API key>, <API key>, sequenced_executor>::value,
"sequenced_executor should have <API key> execution_category");
static_assert(detail::is_detected_exact<size_t, executor_shape_t, sequenced_executor>::value,
"sequenced_executor should have size_t shape_type");
static_assert(detail::is_detected_exact<size_t, executor_index_t, sequenced_executor>::value,
"sequenced_executor should have size_t index_type");
static_assert(detail::is_detected_exact<std::future<int>, executor_future_t, sequenced_executor, int>::value,
"sequenced_executor should have std::future furture");
static_assert(<API key><sequenced_executor>::value == 1,
"sequenced_executor should have execution_depth == 1");
sequenced_executor exec;
size_t shape = 10;
auto result = exec.bulk_sync_execute(
[](size_t idx, std::vector<int>& results, std::vector<int>& shared_arg)
{
results[idx] = shared_arg[idx];
},
shape,
[=]{ return std::vector<int>(shape); }, // results
[=]{ return std::vector<int>(shape, 13); } // shared_arg
);
assert(std::vector<int>(10, 13) == result);
std::cout << "OK" << std::endl;
return 0;
}
|
// .NAME vtkBitArray - dynamic, self-adjusting array of bits
// .SECTION Description
// vtkBitArray is an array of bits (0/1 data value). The array is packed
// so that each byte stores eight bits. vtkBitArray provides methods
// for insertion and retrieval of bits, and will automatically resize
// itself to hold new data.
#ifndef vtkBitArray_h
#define vtkBitArray_h
#include "vtkCommonCoreModule.h" // For export macro
#include "vtkDataArray.h"
class vtkBitArrayLookup;
class <API key> vtkBitArray : public vtkDataArray
{
public:
static vtkBitArray *New();
vtkTypeMacro(vtkBitArray,vtkDataArray);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Allocate memory for this array. Delete old storage only if necessary.
// Note that ext is no longer used.
int Allocate(vtkIdType sz, vtkIdType ext=1000);
// Description:
// Release storage and reset array to initial state.
void Initialize();
// satisfy vtkDataArray API
int GetDataType() {return VTK_BIT;};
int GetDataTypeSize() { return 0; }
// Description:
// Set the number of n-tuples in the array.
void SetNumberOfTuples(vtkIdType number);
// Description:
// Set the tuple at the ith location using the jth tuple in the source array.
// This method assumes that the two arrays have the same type
// and structure. Note that range checking and memory allocation is not
// performed; use in conjunction with SetNumberOfTuples() to allocate space.
virtual void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source);
// Description:
// Insert the jth tuple in the source array, at ith location in this array.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source);
// Description:
// Copy the tuples indexed in srcIds from the source array to the tuple
// locations indexed by dstIds in this array.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds,
vtkAbstractArray *source);
// Description:
// Copy n consecutive tuples starting at srcStart from the source array to
// this array, starting at the dstStart location.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart,
vtkAbstractArray* source);
// Description:
// Insert the jth tuple in the source array, at the end in this array.
// Note that memory allocation is performed as necessary to hold the data.
// Returns the location at which the data was inserted.
virtual vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray* source);
// Description:
// Get a pointer to a tuple at the ith location. This is a dangerous method
// (it is not thread safe since a pointer is returned).
double *GetTuple(vtkIdType i);
// Description:
// Copy the tuple value into a user-provided array.
void GetTuple(vtkIdType i, double * tuple);
// Description:
// Set the tuple value at the ith location in the array.
void SetTuple(vtkIdType i, const float * tuple);
void SetTuple(vtkIdType i, const double * tuple);
// Description:
// Insert (memory allocation performed) the tuple into the ith location
// in the array.
void InsertTuple(vtkIdType i, const float * tuple);
void InsertTuple(vtkIdType i, const double * tuple);
// Description:
// Insert (memory allocation performed) the tuple onto the end of the array.
vtkIdType InsertNextTuple(const float * tuple);
vtkIdType InsertNextTuple(const double * tuple);
// Description:
// These methods remove tuples from the data array. They shift data and
// resize array, so the data array is still valid after this operation. Note,
// this operation is fairly slow.
virtual void RemoveTuple(vtkIdType id);
virtual void RemoveFirstTuple();
virtual void RemoveLastTuple();
// Description:
// Set the data component at the ith tuple and jth component location.
// Note that i is less then NumberOfTuples and j is less then
// NumberOfComponents. Make sure enough memory has been allocated (use
// SetNumberOfTuples() and <API key>()).
void SetComponent(vtkIdType i, int j, double c);
// Description:
// Free any unneeded memory.
void Squeeze();
// Description:
// Resize the array while conserving the data.
virtual int Resize(vtkIdType numTuples);
// Description:
// Get the data at a particular index.
int GetValue(vtkIdType id);
// Description:
// Fast method based setting of values without memory checks. First
// use SetNumberOfValues then use SetValue to actually set them.
// Specify the number of values for this object to hold. Does an
// allocation as well as setting the MaxId ivar. Used in conjunction with
// SetValue() method for fast insertion.
void SetNumberOfValues(vtkIdType number);
// Description:
// Set the data at a particular index. Does not do range checking. Make sure
// you use the method SetNumberOfValues() before inserting data.
void SetValue(vtkIdType id, int value);
// Description:
// Inserts values and checks to make sure there is enough memory
void InsertValue(vtkIdType id, int i);
// Description:
// Set a value in the array from a variant.
void SetVariantValue(vtkIdType idx, vtkVariant value);
// Description:
// Inserts values from a variant and checks to ensure there is enough memory
void InsertVariantValue(vtkIdType idx, vtkVariant value);
vtkIdType InsertNextValue(int i);
// Description:
// Insert the data component at ith tuple and jth component location.
// Note that memory allocation is performed as necessary to hold the data.
virtual void InsertComponent(vtkIdType i, int j, double c);
// Description:
// Direct manipulation of the underlying data.
unsigned char *GetPointer(vtkIdType id) {return this->Array + id/8;}
// Description:
// Get the address of a particular data index. Make sure data is allocated
// for the number of items requested. Set MaxId according to the number of
// data values requested.
unsigned char *WritePointer(vtkIdType id, vtkIdType number);
void* WriteVoidPointer(vtkIdType id, vtkIdType number)
{ return this->WritePointer(id, number); }
void *GetVoidPointer(vtkIdType id)
{
return static_cast<void *>(this->GetPointer(id));
}
// Description:
// Deep copy of another bit array.
void DeepCopy(vtkDataArray *da);
void DeepCopy(vtkAbstractArray* aa)
{ this->Superclass::DeepCopy(aa); }
// Description:
// This method lets the user specify data to be held by the array. The
// array argument is a pointer to the data. size is the size of
// the array supplied by the user. Set save to 1 to keep the class
// from deleting the array when it cleans up or reallocates memory.
// The class uses the actual array provided; it does not copy the data
// from the supplied array. If save 0, the array must have been allocated
// with new[] not malloc.
#ifndef __VTK_WRAP__
void SetArray(unsigned char* array, vtkIdType size, int save);
#endif
void SetVoidArray(void *array, vtkIdType size, int save)
{
this->SetArray(static_cast<unsigned char *>(array), size, save);
}
void SetVoidArray(void *array, vtkIdType size, int save,
int vtkNotUsed(deleteMethod))
{
this->SetArray(static_cast<unsigned char *>(array), size, save);
}
// Description:
// Returns a new vtkBitArrayIterator instance.
VTK_NEWINSTANCE vtkArrayIterator* NewIterator();
// Description:
// Return the indices where a specific value appears.
virtual vtkIdType LookupValue(vtkVariant value);
virtual void LookupValue(vtkVariant value, vtkIdList* ids);
vtkIdType LookupValue(int value);
void LookupValue(int value, vtkIdList* ids);
// Description:
// Tell the array explicitly that the data has changed.
// This is only necessary to call when you modify the array contents
// without using the array's API (i.e. you retrieve a pointer to the
// data and modify the array contents). You need to call this so that
// the fast lookup will know to rebuild itself. Otherwise, the lookup
// functions will give incorrect results.
virtual void DataChanged();
// Description:
// Delete the associated fast lookup data structure on this array,
// if it exists. The lookup will be rebuilt on the next call to a lookup
// function.
virtual void ClearLookup();
protected:
vtkBitArray();
~vtkBitArray();
unsigned char *Array; // pointer to data
unsigned char *ResizeAndExtend(vtkIdType sz);
// function to resize data
int TupleSize; //used for data conversion
double *Tuple;
int SaveUserArray;
private:
// hide superclass' DeepCopy() from the user and the compiler
void DeepCopy(vtkDataArray &da) {this->vtkDataArray::DeepCopy(&da);}
private:
vtkBitArray(const vtkBitArray&) VTK_DELETE_FUNCTION;
void operator=(const vtkBitArray&) VTK_DELETE_FUNCTION;
vtkBitArrayLookup* Lookup;
void UpdateLookup();
};
inline void vtkBitArray::SetNumberOfValues(vtkIdType number)
{
this->Allocate(number);
this->MaxId = number - 1;
this->DataChanged();
}
inline void vtkBitArray::SetValue(vtkIdType id, int value)
{
if (value)
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] | (0x80 >> id%8));
}
else
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] & (~(0x80 >> id%8)));
}
this->DataChanged();
}
inline void vtkBitArray::InsertValue(vtkIdType id, int i)
{
if ( id >= this->Size )
{
if (!this->ResizeAndExtend(id+1))
{
return;
}
}
if (i)
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] | (0x80 >> id%8));
}
else
{
this->Array[id/8] = static_cast<unsigned char>(
this->Array[id/8] & (~(0x80 >> id%8)));
}
if ( id > this->MaxId )
{
this->MaxId = id;
}
this->DataChanged();
}
inline void vtkBitArray::SetVariantValue(vtkIdType id, vtkVariant value)
{
this->SetValue(id, value.ToInt());
}
inline void vtkBitArray::InsertVariantValue(vtkIdType id, vtkVariant value)
{
this->InsertValue(id, value.ToInt());
}
inline vtkIdType vtkBitArray::InsertNextValue(int i)
{
this->InsertValue (++this->MaxId,i);
this->DataChanged();
return this->MaxId;
}
inline void vtkBitArray::Squeeze() {this->ResizeAndExtend (this->MaxId+1);}
#endif
|
#ifndef <API key>
#define <API key>
#include <iostream>
#include "mem/gems_common/Map.hh"
#include "mem/protocol/AccessType.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/system/MachineID.hh"
class <API key>
{
public:
void print(std::ostream& out) const {}
NetDest m_starving;
NetDest m_marked;
NetDest m_request_to_write;
};
class PersistentTable
{
public:
// Constructors
PersistentTable();
// Destructor
~PersistentTable();
// Public Methods
void <API key>(const Address& address, MachineID locker,
AccessType type);
void <API key>(const Address& address, MachineID unlocker);
bool okToIssueStarving(const Address& address, MachineID machID) const;
MachineID findSmallest(const Address& address) const;
AccessType typeOfSmallest(const Address& address) const;
void markEntries(const Address& address);
bool isLocked(const Address& addr) const;
int <API key>(const Address& addr) const;
int <API key>(const Address& addr) const;
static void printConfig(std::ostream& out) {}
void print(std::ostream& out) const;
private:
// Private copy constructor and assignment operator
PersistentTable(const PersistentTable& obj);
PersistentTable& operator=(const PersistentTable& obj);
// Data Members (m_prefix)
Map<Address, <API key>>* m_map_ptr;
};
inline std::ostream&
operator<<(std::ostream& out, const PersistentTable& obj)
{
obj.print(out);
out << std::flush;
return out;
}
inline std::ostream&
operator<<(std::ostream& out, const <API key>& obj)
{
obj.print(out);
out << std::flush;
return out;
}
#endif // <API key>
|
package uk.ac.manchester.cs.owl.semspreadsheets.model;
public interface NamedRange {
String getName();
Range getRange();
}
|
package gov.nih.nci.caadapter.sdtm.util;
public class Entity {
private String schema = null;
private String entityName = null;
/**
* Creates a new instance of Entity
*/
public Entity(String schema, String entityName) {
this.setSchema(schema);
this.setEntityName(entityName);
}
public String toString() {
return getEntityName();
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
|
define(function () {
return [
{
"default": {
name: 'form1',
label: 'Form 1',
"_elements": [
{
"default": {
"name": "id",
"type": "hidden"
}
},
{
"default": {
"name": "test1",
"type": "text",
"label": "Test1",
"defaultValue": "test1",
"page": 0
}
},
{
"default": {
"name": "test2",
"type": "text",
"label": "Test2",
"defaultValue": "test2",
"page": 0
}
},
{
"default": {
"name": "calc_button",
"type": "button",
"label": "Calculate",
"persist": false,
"page": 0
}
},
{
"default": {
"name": "calc",
"type": "message",
"label": "Calc",
"labelPlacement": "default",
"labelStyle": "Plain",
"showTextbox": "show",
"calculationType": "manual",
"buttonText": "Calculate",
"persist": true,
"page": 0
}
}
],
"_checks": [
],
"_actions": [
{
"default": {
"javascript": "\"[test1]\"+\"[test2]\"",
"outputTarget": "calc",
"name": "CALC_calc"
}
}
],
"_behaviours": [
{
"default": {
"name": "auto_calculations",
"trigger": {
"formElements": ["calc_button"]
},
"actions": [
"CALC_calc"
]
}
}
]
}
}
];
});
|
#include <stdio.h>
#include <stdlib.h>
static void foo()
{
throw 123;
}
int main(int argc, char *argv[])
{
int count = argc == 1 ? 10000 : atoi(argv[ 1 ]);
int n = 0;
for(int i = 0; i < count; ++i) {
try {
foo();
}
catch(...) {
++n;
}
}
printf("%d\n", n);
return 0;
}
|
# Boilerplate
import logging # isort:skip
log = logging.getLogger(__name__)
# Imports
# Bokeh imports
from .notebook import run_notebook_hook
from .state import curstate
# Globals and constants
__all__ = (
'output_file',
'output_notebook',
'reset_output',
)
# General API
def output_file(filename, title="Bokeh Plot", mode=None, root_dir=None):
'''Configure the default output state to generate output saved
to a file when :func:`show` is called.
Does not change the current ``Document`` from ``curdoc()``. File and notebook
output may be active at the same time, so e.g., this does not clear the
effects of ``output_notebook()``.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document (default: "Bokeh Plot")
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details.
root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or
``CDN``.
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
.. warning::
This output file will be overwritten on every save, e.g., each time
show() or save() is invoked.
'''
curstate().output_file(
filename,
title=title,
mode=mode,
root_dir=root_dir
)
def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'):
''' Configure the default output state to generate output in notebook cells
when :func:`show` is called. Note that, :func:`show` may be called multiple
times in a single cell to display multiple objects in the output cell. The
objects will be displayed in order.
Args:
resources (Resource, optional) :
How and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to display detailed BokehJS banner (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
notebook_type (string, optional):
Notebook type (default: jupyter)
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
'''
# verify notebook_type first in curstate().output_notebook
curstate().output_notebook(notebook_type)
run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout)
def reset_output(state=None):
''' Clear the default state of all output modes.
Returns:
None
'''
curstate().reset()
# Dev API
# Private API
# Code
|
module Main where
import Build_doctests (flags, pkgs, module_sources)
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
main :: IO ()
main = do
traverse_ putStrLn args
doctest args
where
args = ["-XOverloadedStrings"] ++ flags ++ pkgs ++ module_sources
|
require './test_common.rb'
require '../lib/crocus/minibloom'
class TestMiniBloom < Test::Unit::TestCase
def test_single_push
results = []
mb = MiniBloom.new
mb.source('p1',1)
mb.p1.pro {|i| results << [2*i[0]]}
mb.p1 << [2]
assert_equal([4], results.pop)
end
def test_single_table
results = []
mb = MiniBloom.new
mb.table('p1',{[:key]=>[:val]})
mb.p1 << [1,2]
mb.p1.pro {|i| results << [2*i[0]]}
keys = mb.p1.keys
vals = mb.p1.values
mb.tick
assert_equal([[2]], results)
assert_equal([[1]], keys)
assert_equal([[2]], vals)
end
def test_join_tables
results = []
mb = MiniBloom.new
mb.table('rel1',{[:key]=>[:val]})
mb.table('p2',{[:key]=>[:val]})
mb.rel1 <= [[:alpha,1], [:beta,2]]
mb.p2 <= [[:alpha,3], [:beta,4]]
(mb.rel1 * mb.p2).pairs([0]=>[0]){|x,y| results << [x[0],x[1],y[1]]}
mb.tick
assert_equal([[:alpha, 1, 3], [:beta, 2, 4]], results)
end
def test_join
results = []
mb = MiniBloom.new
mb.run_bg
mb.source('rel1',2)
mb.source('rel2',2)
(mb.rel1*mb.rel2).pairs([1]=>[1]) {|i,j| results << [i[0], j[0], j[1]]}
mb.rel1 <= [['a',1], ['c', 3]]
mb.rel2 << ['b',1]
mb.stop
assert_equal(['a', 'b', 1], results.pop)
assert_equal([], results)
end
def test_cross_product
results = []
mb = MiniBloom.new
mb.run_bg
mb.source('rel1',2)
mb.source('rel2',2)
(mb.rel1*mb.rel2).pairs {|i,j| results << i+j}
mb.rel1 <= [['a',1], ['c', 3]]
mb.rel2 << ['b',1]
mb.stop
assert_equal([['a', 1, 'b', 1],['c',3, 'b',1]], results.sort)
end
def test_two_joins
outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('rel1',2)
mb.source('rel2',2)
mb.source('rel3',2)
((mb.rel1*mb.rel2).pairs([0]=>[0]){|i,j| i+j} * mb.rel3).pairs([2]=>[0]).pro do |i,j|
outs << i+j
end
mb.rel1 <= [[1,:a],[2,:a]]
mb.rel2 <= [[1,:b],[2,:b]]
mb.rel3 <= [[1,:c],[2,:c]]
mb.stop
assert_equal([[1, :a, 1, :b, 1, :c], [2, :a, 2, :b, 2, :c]], outs.sort)
end
require 'set'
def test_recursion
outs = Set.new
links = Set.new
mb = MiniBloom.new
mb.run_bg
mb.source('link', 2)
mb.source('path', 2)
mb.path <= mb.link
mb.path <= (mb.link*mb.path).pairs([1]=>[0]) do |i,j|
tup = [i[0], j[1]]
unless outs.include? tup
outs << tup
tup
else
nil
end
end
[[1,2],[2,3],[3,4],[6,7],[2,7]].each{|i| links << i}
mb.link <= links
mb.stop
assert_equal([[1,2],[1,3],[1,4],[1,7],[2,3],[2,4],[2,7],[3,4],[6,7]], (outs+links).to_a.sort)
end
def test_group_by
outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
mb.r.group([1], Crocus::sum(0)) {|i| outs << i unless i.nil?}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal([['a', 3],['c', 2]], outs.sort)
end
def test_agg_nogroup
outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
mb.r.group([], Crocus::sum(0)) {|i| outs << i unless i.nil?}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal([[5]], outs.sort)
end
def test_argagg
agg_outs = []
max_outs = []
min_outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
mb.r.argagg([1], Crocus::min(0)) {|i| agg_outs << i unless i.nil?}
mb.r.argmin([1], 0) {|i| min_outs << i unless i.nil?}
mb.r.argmax([1], 0) {|i| max_outs << i unless i.nil?}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal([[1,'a'],[2,'c']], agg_outs.sort)
assert_equal([[1,'a'],[2,'c']], min_outs.sort)
assert_equal([[2,'a'],[2,'c']], max_outs.sort)
end
def test_argagg_nogroup
outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
mb.r.argagg([], Crocus::min(0)) {|i| outs << i unless i.nil?}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal([[1,'a']], outs)
end
def test_preds
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
ex_outs = false
inc_outs = false
fail_outs = false
mb.r.on_exists? {ex_outs = true}
mb.r.on_include?([1,'a']) {inc_outs = true}
mb.r.on_include?(['joe']) {fail_outs = true}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal(true, ex_outs)
assert_equal(true, inc_outs)
assert_equal(false, fail_outs)
end
def test_inspected
outs = []
mb = MiniBloom.new
mb.run_bg
mb.source('r',2)
mb.r.inspected.pro {|i| outs << i}
mb.r <= [[1,'a'],[2,'a'],[2,'c']]
mb.stop
assert_equal([[1,'a'],[2,'a'],[2,'c']].map{|i| [i.inspect]}, outs)
end
end
|
#include "media/audio/mac/<API key>.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/mac/mac_logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
#include "media/base/media_switches.h"
namespace media {
static std::ostream& operator<<(std::ostream& os,
const <API key>& format) {
os << "sample rate : " << format.mSampleRate << std::endl
<< "format ID : " << format.mFormatID << std::endl
<< "format flags : " << format.mFormatFlags << std::endl
<< "bytes per packet : " << format.mBytesPerPacket << std::endl
<< "frames per packet : " << format.mFramesPerPacket << std::endl
<< "bytes per frame : " << format.mBytesPerFrame << std::endl
<< "channels per frame: " << format.mChannelsPerFrame << std::endl
<< "bits per channel : " << format.mBitsPerChannel;
return os;
}
static <API key> <API key> = {
<API key>,
<API key>,
<API key>
};
// Overview of operation:
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, const AudioParameters& params)
: manager_(manager),
source_(NULL),
output_unit_(0),
output_device_id_(kAudioObjectUnknown),
volume_(1),
<API key>(0),
stopped_(false),
audio_bus_(AudioBus::Create(params)) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate();
format_.mFormatID = <API key>;
format_.mFormatFlags = <API key> |
<API key>;
format_.mBitsPerChannel = params.bits_per_sample();
format_.mChannelsPerFrame = params.channels();
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels()) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
format_.mReserved = 0;
DVLOG(1) << "Desired ouput format: " << format_;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetBytesPerBuffer() / format_.mBytesPerPacket;
DVLOG(1) << "Number of frames per callback: " << number_of_frames_;
const AudioParameters parameters =
manager_-><API key>();
CHECK_EQ(number_of_frames_,
static_cast<size_t>(parameters.frames_per_buffer()));
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Obtain the current input device selected by the user.
UInt32 size = sizeof(output_device_id_);
OSStatus result = <API key>(<API key>,
&<API key>,
0,
0,
&size,
&output_device_id_);
if (result != noErr || output_device_id_ == kAudioObjectUnknown) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default audio output device.";
return false;
}
// Open and initialize the DefaultOutputUnit.
AudioComponent comp;
<API key> desc;
desc.componentType = <API key>;
desc.componentSubType = <API key>;
desc.<API key> = <API key>;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = <API key>(0, &desc);
if (!comp)
return false;
result = <API key>(comp, &output_unit_);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "<API key>() failed.";
return false;
}
result = AudioUnitInitialize(output_unit_);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "AudioUnitInitialize() failed.";
return false;
}
<API key> = GetHardwareLatency();
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
<API key> input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = <API key>(
output_unit_,
<API key>,
<API key>,
0,
&input,
sizeof(input));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "<API key>(<API key>) failed.";
return false;
}
// Set the stream format.
result = <API key>(
output_unit_,
<API key>,
<API key>,
0,
&format_,
sizeof(format_));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "<API key>(<API key>) failed.";
return false;
}
// Set the buffer frame size.
// WARNING: Setting this value changes the frame size for all audio units in
// the current process. It's imperative that the input and output frame sizes
// be the same as the frames_per_buffer() returned by
// <API key>.
UInt32 buffer_size = number_of_frames_;
result = <API key>(
output_unit_,
<API key>,
<API key>,
0,
&buffer_size,
sizeof(buffer_size));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "<API key>(<API key>) failed.";
return false;
}
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
<API key>(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
if (!output_unit_) {
DLOG(ERROR) << "Open() has not been called successfully";
return;
}
stopped_ = false;
{
base::AutoLock auto_lock(source_lock_);
source_ = callback;
}
<API key>(output_unit_);
}
void AUAudioOutputStream::Stop() {
if (stopped_)
return;
AudioOutputUnitStop(output_unit_);
base::AutoLock auto_lock(source_lock_);
source_ = NULL;
stopped_ = true;
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data,
const AudioTimeStamp* output_time_stamp) {
// Update the playout latency.
double <API key> = GetPlayoutLatency(output_time_stamp);
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 <API key> = static_cast<uint32>
((<API key> + 0.5) * format_.mBytesPerFrame);
// Unfortunately AUAudioInputStream and AUAudioOutputStream share the frame
// size set by <API key> above on a per process
// basis. What this means is that the |number_of_frames| value may be larger
// or smaller than the value set during Configure(). In this case either
// audio input or audio output will be broken, so just output silence.
// TODO(crogers): Figure out what can trigger a change in |number_of_frames|.
if (number_of_frames != static_cast<UInt32>(audio_bus_->frames())) {
memset(audio_data, 0, number_of_frames * format_.mBytesPerFrame);
return noErr;
}
int frames_filled = 0;
{
// Render() shouldn't be called except between <API key>() and
// AudioOutputUnitStop() calls, but crash reports have shown otherwise:
// crashes in Render() when |source_| is cleared.
base::AutoLock auto_lock(source_lock_);
if (!source_) {
memset(audio_data, 0, number_of_frames * format_.mBytesPerFrame);
return noErr;
}
frames_filled = source_->OnMoreData(
audio_bus_.get(), AudioBuffersState(0, <API key>));
}
// Note: If this ever changes to output raw float the data must be clipped and
// sanitized since it may come from an untrusted source such as NaCl.
audio_bus_->ToInterleaved(
frames_filled, format_.mBitsPerChannel / 8, audio_data);
uint32 filled = frames_filled * format_.mBytesPerFrame;
// Perform in-place, software-volume adjustments.
media::AdjustVolume(audio_data,
filled,
audio_bus_->channels(),
format_.mBitsPerChannel / 8,
volume_);
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
<API key>*,
const AudioTimeStamp* output_time_stamp,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data, output_time_stamp);
}
int AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioObjectUnknown;
UInt32 info_size = sizeof(device_id);
OSStatus result = <API key>(<API key>,
&<API key>,
0,
0,
&info_size,
&device_id);
if (result != noErr || device_id == kAudioObjectUnknown) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default audio output device.";
return 0;
}
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
<API key> <API key> = {
<API key>,
<API key>,
<API key>
};
result = <API key>(device_id,
&<API key>,
0,
0,
&info_size,
&nominal_sample_rate);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default sample rate for device: " << device_id;
return 0;
}
return static_cast<int>(nominal_sample_rate);
}
double AUAudioOutputStream::GetHardwareLatency() {
if (!output_unit_ || output_device_id_ == kAudioObjectUnknown) {
DLOG(WARNING) << "Audio unit object is NULL or device ID is unknown";
return 0.0;
}
// Get audio unit latency.
Float64 <API key> = 0.0;
UInt32 size = sizeof(<API key>);
OSStatus result = <API key>(output_unit_,
<API key>,
<API key>,
0,
&<API key>,
&size);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "Could not get audio unit latency";
return 0.0;
}
// Get output audio device latency.
<API key> property_address = {
<API key>,
<API key>,
<API key>
};
UInt32 <API key> = 0;
size = sizeof(<API key>);
result = <API key>(output_device_id_,
&property_address,
0,
NULL,
&size,
&<API key>);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "Could not get audio unit latency";
return 0.0;
}
return static_cast<double>((<API key> *
format_.mSampleRate) + <API key>);
}
double AUAudioOutputStream::GetPlayoutLatency(
const AudioTimeStamp* output_time_stamp) {
// Ensure mHostTime is valid.
if ((output_time_stamp->mFlags & <API key>) == 0)
return 0;
// Get the delay between the moment getting the callback and the scheduled
// time stamp that tells when the data is going to be played out.
UInt64 output_time_ns = <API key>(
output_time_stamp->mHostTime);
UInt64 now_ns = <API key>(<API key>());
// Prevent overflow leading to huge delay information; occurs regularly on
// the bots, probably less so in the wild.
if (now_ns > output_time_ns)
return 0;
double delay_frames = static_cast<double>
(1e-9 * (output_time_ns - now_ns) * format_.mSampleRate);
return (delay_frames + <API key>);
}
} // namespace media
|
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\ComputerVih */
$this->title = Yii::t('app', 'Create Computer Vih');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Computer Vihs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="computer-vih-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
|
<?php
class CmsModule extends CWebModule
{
/**
* @var string the name of the default controller
*/
public $defaultController = 'admin';
/**
* Initializes the module.
*/
public function init()
{
// Register module imports.
$this->setImport(array(
'cms.components.*',
'cms.models.*',
'ext.bootstrap.widgets.*'
));
}
/**
* Performs access check to this module.
* @param CController $controller the controller to be accessed
* @param CAction $action the action to be accessed
* @return boolean whether the action should be executed
*/
public function <API key>($controller, $action)
{
if (parent::<API key>($controller, $action))
{
$route = $controller->id.'/'.$action->id;
if (!Yii::app()->cms->checkAccess() && $route !== 'node/page')
throw new CHttpException(403, Yii::t('CmsModule.core', 'You are not allowed to access this page.'));
$publicPages = array('node/page');
if (Yii::app()->user->isGuest && !in_array($route, $publicPages))
Yii::app()->user->loginRequired();
else
return true;
}
return false;
}
public function getVersion()
{
return '0.9.1';
}
}
|
// <API key>.h
#import "SDLRPCRequest.h"
#import "SDLAppHMIType.h"
#import "SDLLanguage.h"
@class SDLAppInfo;
@class SDLDeviceInfo;
@class <API key>;
@class SDLSyncMsgVersion;
@class <API key>;
@class SDLTTSChunk;
<API key>
@interface <API key> : SDLRPCRequest
/**
* Convenience init for registering the application with a lifecycle configuration.
*
* @param <API key> Configuration options for SDLManager
*/
- (instancetype)<API key>:(<API key> *)<API key>;
/**
* Convenience init for registering the application.
*
* @param appName The mobile application's name
* @param appId An appId used to validate app with policy table entries
* @param languageDesired The language the application intends to use for user interaction
* @return A <API key> object
*/
- (instancetype)initWithAppName:(NSString *)appName appId:(NSString *)appId languageDesired:(SDLLanguage)languageDesired;
/**
* Convenience init for registering the application.
*
* @param appName The mobile application's name
* @param appId An appId used to validate app with policy table entries
* @param languageDesired The language the application intends to use for user interaction
* @param isMediaApp Indicates if the application is a media or a non-media application
* @param appTypes A list of all applicable app types stating which classifications to be given to the app
* @param shortAppName An abbreviated version of the mobile application's name
* @return A <API key> object
*/
- (instancetype)initWithAppName:(NSString *)appName appId:(NSString *)appId languageDesired:(SDLLanguage)languageDesired isMediaApp:(BOOL)isMediaApp appTypes:(NSArray<SDLAppHMIType> *)appTypes shortAppName:(nullable NSString *)shortAppName __deprecated_msg(("Use initWithAppName:appId:fullAppId:languageDesired:isMediaApp:appTypes:shortAppName:ttsName:vrSynonyms:<API key>:resumeHash:dayColorScheme:nightColorScheme: instead"));
/**
* Convenience init for registering the application.
*
* @param appName The mobile application's name
* @param appId An appId used to validate app with policy table entries
* @param languageDesired The language the application intends to use for user interaction
* @param isMediaApp Indicates if the application is a media or a non-media application
* @param appTypes A list of all applicable app types stating which classifications to be given to the app
* @param shortAppName An abbreviated version of the mobile application's name
* @param ttsName TTS string for VR recognition of the mobile application name
* @param vrSynonyms Additional voice recognition commands
* @param <API key> Current app's expected VR+TTS language
* @param resumeHash ID used to uniquely identify current state of all app data that can persist through connection cycles
* @return A <API key> object
*/
- (instancetype)initWithAppName:(NSString *)appName appId:(NSString *)appId languageDesired:(SDLLanguage)languageDesired isMediaApp:(BOOL)isMediaApp appTypes:(NSArray<SDLAppHMIType> *)appTypes shortAppName:(nullable NSString *)shortAppName ttsName:(nullable NSArray<SDLTTSChunk *> *)ttsName vrSynonyms:(nullable NSArray<NSString *> *)vrSynonyms <API key>:(SDLLanguage)<API key> resumeHash:(nullable NSString *)resumeHash __deprecated_msg(("Use initWithAppName:appId:fullAppId:languageDesired:isMediaApp:appTypes:shortAppName:ttsName:vrSynonyms:<API key>:resumeHash:dayColorScheme:nightColorScheme: instead"));
/**
* Convenience init for registering the application with all possible options.
*
* @param appName The mobile application's name
* @param appId An appId used to validate app with policy table entries
* @param fullAppId A full UUID appID used to validate app with policy table entries.
* @param languageDesired The language the application intends to use for user interaction
* @param isMediaApp Indicates if the application is a media or a non-media application
* @param appTypes A list of all applicable app types stating which classifications to be given to the app
* @param shortAppName An abbreviated version of the mobile application's name
* @param ttsName TTS string for VR recognition of the mobile application name
* @param vrSynonyms Additional voice recognition commands
* @param <API key> Current app's expected VR+TTS language
* @param resumeHash ID used to uniquely identify current state of all app data that can persist through connection cycles
* @param dayColorScheme The color scheme to be used on a head unit using a "light" or "day" color scheme.
* @param nightColorScheme The color scheme to be used on a head unit using a "dark" or "night" color scheme
* @return A <API key> object
*/
- (instancetype)initWithAppName:(NSString *)appName appId:(NSString *)appId fullAppId:(nullable NSString *)fullAppId languageDesired:(SDLLanguage)languageDesired isMediaApp:(BOOL)isMediaApp appTypes:(NSArray<SDLAppHMIType> *)appTypes shortAppName:(nullable NSString *)shortAppName ttsName:(nullable NSArray<SDLTTSChunk *> *)ttsName vrSynonyms:(nullable NSArray<NSString *> *)vrSynonyms <API key>:(SDLLanguage)<API key> resumeHash:(nullable NSString *)resumeHash dayColorScheme:(nullable <API key> *)dayColorScheme nightColorScheme:(nullable <API key> *)nightColorScheme;
/**
* The version of the SDL interface
*
* Required
*/
@property (strong, nonatomic) SDLSyncMsgVersion *syncMsgVersion;
/**
* The mobile application's name. This name is displayed in the SDL Mobile Applications menu. It also serves as the unique identifier of the application for SmartDeviceLink.
*
* 1. Needs to be unique over all applications. Applications with the same name will be rejected.
* 2. May not be empty.
* 3. May not start with a new line character.
* 4. May not interfere with any name or synonym of previously registered applications and any predefined blacklist of words (global commands).
*
* Required, Max length 100 chars
*/
@property (strong, nonatomic) NSString *appName;
/**
* TTS string for VR recognition of the mobile application name.
*
* @discussion Meant to overcome any failing on speech engine in properly pronouncing / understanding app name.
* 1. Needs to be unique over all applications.
* 2. May not be empty.
* 3. May not start with a new line character.
*
* Optional, Array of SDLTTSChunk, Array size 1 - 100
*
* @since SDL 2.0
* @see SDLTTSChunk
*/
@property (nullable, strong, nonatomic) NSArray<SDLTTSChunk *> *ttsName;
/**
* A String representing an abbreviated version of the mobile application's name (if necessary) that will be displayed on the media screen.
*
* @discussion If not provided, the appName is used instead (and will be truncated if too long)
*
* Optional, Max length 100 chars
*/
@property (nullable, strong, nonatomic) NSString *<API key>;
/**
* Defines additional voice recognition commands
*
* @discussion May not interfere with any app name of previously registered applications and any predefined blacklist of words (global commands).
*
* Optional, Array of Strings, Array length 1 - 100, Max String length 40
*/
@property (nullable, strong, nonatomic) NSArray<NSString *> *vrSynonyms;
/**
* Indicates if the application is a media or a non-media application.
*
* @discussion Only media applications will be able to stream audio to head units that is audible outside of the BT media source.
*
* Required, Boolean
*/
@property (strong, nonatomic) NSNumber<SDLBool> *isMediaApplication;
/**
* A Language enumeration indicating what language the application intends to use for user interaction (TTS and VR).
*
* @discussion If there is a mismatch with the head unit, the app will be able to change this registration with changeRegistration prior to app being brought into focus.
*
* Required
*/
@property (strong, nonatomic) SDLLanguage languageDesired;
/**
* An enumeration indicating what language the application intends to use for user interaction (Display).
*
* @discussion If there is a mismatch with the head unit, the app will be able to change this registration with changeRegistration prior to app being brought into focus.
*
* Required
*
* @since SDL 2.0
*/
@property (strong, nonatomic) SDLLanguage <API key>;
/**
* A list of all applicable app types stating which classifications to be given to the app.
*
* Optional, Array of SDLAppHMIType, Array size 1 - 100
*
* @since SDL 2.0
* @see SDLAppHMIType
*/
@property (nullable, strong, nonatomic) NSArray<SDLAppHMIType> *appHMIType;
/**
* ID used to uniquely identify current state of all app data that can persist through connection cycles (e.g. ignition cycles).
*
* @discussion This registered data (commands, submenus, choice sets, etc.) can be reestablished without needing to explicitly reregister each piece. If omitted, then the previous state of an app's commands, etc. will not be restored.
*
* When sending hashID, all <API key> parameters should still be provided (e.g. ttsName, etc.).
*
* Optional, max length 100 chars
*/
@property (nullable, strong, nonatomic) NSString *hashID;
/**
* Information about the connecting device
*
* Optional
*/
@property (nullable, strong, nonatomic) SDLDeviceInfo *deviceInfo;
/**
* ID used to validate app with policy table entries
*
* Required, max length 100
*
* @see `fullAppID`
*
* @since SDL 2.0
*/
@property (strong, nonatomic) NSString *appID;
/**
* A full UUID appID used to validate app with policy table entries.
*
* Optional
*
* @discussion The `fullAppId` is used to authenticate apps that connect with head units that implement SDL Core v.5.0 and newer. If connecting with older head units, the `fullAppId` can be truncated to create the required `appId` needed to register the app. The `appId` is the first 10 non-dash ("-") characters of the `fullAppID` (e.g. if you have a `fullAppId` of <API key>, the `appId` will be 123e4567e8).
*/
@property (nullable, strong, nonatomic) NSString *fullAppID;
/**
* Information about the application running
*
* Optional
*/
@property (nullable, strong, nonatomic) SDLAppInfo *appInfo;
/**
* The color scheme to be used on a head unit using a "light" or "day" color scheme. The OEM may only support this theme if their head unit only has a light color scheme.
*
* Optional
*/
@property (strong, nonatomic, nullable) <API key> *dayColorScheme;
/**
* The color scheme to be used on a head unit using a "dark" or "night" color scheme. The OEM may only support this theme if their head unit only has a dark color scheme.
*
* Optional
*/
@property (strong, nonatomic, nullable) <API key> *nightColorScheme;
@end
<API key>
|
<style>
.buy-tickets__title{margin: 10px; width: 6%; margin-left: 0px;}
.buy-tickets__title.ticket-title{width: 50%;}
.buy-tickets__title.flash{width: 15%;}
.buy-tickets__title.flash-price{width: 11%;}
.form .input__number .<API key>.sold-out{ width: 80px;height: 10px;margin: 5px;}
p.error{display: none; color: #ff0000;text-align: center;margin: 10px;}
.buy-tickets{ display:none }
.hidden-div{ display:none; margin-bottom:0;}
</style>
<button onclick="getElementById('hidden-div').style.display = 'block'" style="margin-bottom: 1px"> Buy Tickets Now </button>
<div class="hidden-div" id="hidden-div" style="height: 100%;"><?php echo $eventbrite;?></div>
<br><br><br><br><br>
|
// These tests check that Torque-generated verifier functions crash the process
// when encountering data that doesn't fit the Torque type definitions.
#include "src/api/api-inl.h"
#include "src/objects/descriptor-array.h"
#include "src/objects/map-inl.h"
#include "test/cctest/cctest.h"
#include "torque-generated/class-verifiers.h"
namespace v8 {
namespace internal {
// Defines a pair of tests with similar code. The goal is to test that a
// specific action causes a failure, but that everything else in the test case
// succeeds. The general pattern should be:
// TEST_PAIR(Something) {
// <API key>();
// if (should_fail) {
// <API key>();
// <API key>();
// A corresponding entry in cctest.status specifies that all Fail* tests in this
// file must fail.
#define TEST_PAIR(Name) \
static void Name(bool should_fail); \
TEST(Pass##Name) { Name(false); } \
TEST(Fail##Name) { Name(true); } \
static void Name(bool should_fail)
#ifdef VERIFY_HEAP
TEST_PAIR(<API key>) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})");
Handle<JSObject> o = Handle<JSObject>::cast(v8::Utils::OpenHandle(*v));
Handle<Object> original_elements(
TaggedField<Object>::load(*o, JSObject::kElementsOffset), i_isolate);
CHECK(original_elements->IsFixedArrayBase());
// There must be no GC (and therefore no verifiers running) until we can
// restore the modified data.
<API key> no_gc;
// Elements must be FixedArrayBase according to the Torque definition, so a
// JSObject should cause a failure.
TaggedField<Object>::store(*o, JSObject::kElementsOffset, *o);
if (should_fail) {
<API key>::JSObjectVerify(*o, i_isolate);
}
// Put back the original value in case verifiers run on test shutdown.
TaggedField<Object>::store(*o, JSObject::kElementsOffset, *original_elements);
}
TEST_PAIR(<API key>) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})");
Handle<Object> o = v8::Utils::OpenHandle(*v);
Handle<Map> map(Handle<HeapObject>::cast(o)->map(), i_isolate);
Handle<DescriptorArray> descriptors(map-><API key>(kRelaxedLoad),
i_isolate);
int offset = DescriptorArray::<API key>(1) +
DescriptorArray::kEntryKeyOffset;
Handle<Object> original_key(TaggedField<Object>::load(*descriptors, offset),
i_isolate);
CHECK(original_key->IsString());
// There must be no GC (and therefore no verifiers running) until we can
// restore the modified data.
<API key> no_gc;
// Key must be Name|Undefined according to the Torque definition, so a
// JSObject should cause a failure.
TaggedField<Object>::store(*descriptors, offset, *o);
if (should_fail) {
<API key>::<API key>(*descriptors,
i_isolate);
}
// Put back the original value in case verifiers run on test shutdown.
TaggedField<Object>::store(*descriptors, offset, *original_key);
}
TEST_PAIR(<API key>) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})");
Handle<Object> o = v8::Utils::OpenHandle(*v);
Handle<Map> map(Handle<HeapObject>::cast(o)->map(), i_isolate);
Handle<DescriptorArray> descriptors(map-><API key>(kRelaxedLoad),
i_isolate);
int offset = DescriptorArray::<API key>(0) +
DescriptorArray::kEntryValueOffset;
Handle<Object> original_value(TaggedField<Object>::load(*descriptors, offset),
i_isolate);
// There must be no GC (and therefore no verifiers running) until we can
// restore the modified data.
<API key> no_gc;
// Value can be JSAny, which includes JSObject, and it can be Weak<Map>, but
// it can't be Weak<JSObject>.
TaggedField<Object>::store(*descriptors, offset, *o);
<API key>::<API key>(*descriptors, i_isolate);
MaybeObject weak = MaybeObject::MakeWeak(MaybeObject::FromObject(*o));
TaggedField<MaybeObject>::store(*descriptors, offset, weak);
if (should_fail) {
<API key>::<API key>(*descriptors,
i_isolate);
}
// Put back the original value in case verifiers run on test shutdown.
TaggedField<Object>::store(*descriptors, offset, *original_value);
}
TEST_PAIR(TestWrongOddball) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> v = CompileRun("new Date()");
Handle<JSDate> date = Handle<JSDate>::cast(v8::Utils::OpenHandle(*v));
Handle<Object> original_hour(
TaggedField<Object>::load(*date, JSDate::kHourOffset), i_isolate);
// There must be no GC (and therefore no verifiers running) until we can
// restore the modified data.
<API key> no_gc;
// Hour is Undefined|Smi|NaN. Other oddballs like null should cause a failure.
TaggedField<Object>::store(*date, JSDate::kHourOffset,
*i_isolate->factory()->null_value());
if (should_fail) {
<API key>::JSDateVerify(*date, i_isolate);
}
// Put back the original value in case verifiers run on test shutdown.
TaggedField<Object>::store(*date, JSDate::kHourOffset, *original_hour);
}
TEST_PAIR(TestWrongNumber) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> v = CompileRun("new Date()");
Handle<JSDate> date = Handle<JSDate>::cast(v8::Utils::OpenHandle(*v));
Handle<Object> original_hour(
TaggedField<Object>::load(*date, JSDate::kHourOffset), i_isolate);
v8::Local<v8::Value> v2 = CompileRun("1.1");
Handle<Object> float_val = v8::Utils::OpenHandle(*v2);
// There must be no GC (and therefore no verifiers running) until we can
// restore the modified data.
<API key> no_gc;
// Hour is Undefined|Smi|NaN. Other doubles like 1.1 should cause a failure.
TaggedField<Object>::store(*date, JSDate::kHourOffset, *float_val);
if (should_fail) {
<API key>::JSDateVerify(*date, i_isolate);
}
// Put back the original value in case verifiers run on test shutdown.
TaggedField<Object>::store(*date, JSDate::kHourOffset, *original_hour);
}
#endif // VERIFY_HEAP
#undef TEST_PAIR
} // namespace internal
} // namespace v8
|
from django import template
from django.utils.safestring import mark_safe
from mezzanine.conf import settings
from <API key>.utils import refactor_html
register = template.Library()
# Checking settings.TEMPLATE_STYLE.
# Possible values are:
# - <API key>.styles.macos
# - <API key>.styles.ubuntu
# - <API key>.styles.windows
_prefix = "<API key>.styles"
try:
if settings.TERMINAL_STYLE not in \
["%s.macos" % _prefix, "%s.ubuntu" % _prefix, "%s.windows" % _prefix]:
# If the user has specified a wrong terminal styling format, we
# raise an exception warning about this.
msg = "Wrong terminal style format. Check the value of TERMINAL_STYLE"\
" in your settings.py file."
raise Exception(msg)
except AttributeError:
msg = "You have not specified a terminal output format. You have to"\
" define the attribute TERMINAL_STYLE in your settings.py"
raise Exception(msg)
@register.filter(name='safe_developer')
def safe_developer(content, style="macos"):
"""
Renders content without cleaning the original.
Replaces the terminal divs for a more complext html layout.
"""
new_content = refactor_html(content, style)
return mark_safe(new_content)
|
#pragma once
#include "common/vect.h"
#include "M120AN/system.hpp"
#include "M120AN/intr.hpp"
#include "M120AN/comp.hpp"
namespace device {
/*!
@brief
*/
enum class comp_filter {
none,
f1,
f8,
f32
};
/*!
@brief
*/
enum class comp_edge {
a_lt_r,
a_gt_r,
ltgt = 3,
};
/*!
@brief I/O
@param[in] TASK1
@param[in] TASK3
*/
template <class TASK1, class TASK3>
class comp_io {
static TASK1 task1_;
static TASK3 task3_;
public:
static inline void itask1() {
task1_();
WCB1INTR.WCB1F = 0;
}
static inline void itask3() {
task3_();
WCB3INTR.WCB3F = 0;
}
public:
/*!
@brief
*/
comp_io() { }
/*!
@brief
@param[in] et
@para,[in] fl
*/
void start1(comp_edge eg = comp_edge::ltgt, comp_filter fl = comp_filter::none, uint8_t ir_lvl = 0) const {
WCMPR.WCB1M0 = 1;
ILVL2.B01 = ir_lvl;
if(ir_lvl) {
WCB1INTR.WCB1FL = static_cast<uint8_t>(fl);
WCB1INTR.WCB1S = static_cast<uint8_t>(eg);
WCB1INTR.WCB1INTEN = 1;
} else {
WCB1INTR.WCB1INTEN = 0;
}
}
/*!
@brief
@param[in] et
@para,[in] fl
*/
void start3(comp_edge eg = comp_edge::ltgt, comp_filter fl = comp_filter::none, uint8_t ir_lvl = 0) const {
WCMPR.WCB3M0 = 1;
ILVL2.B45 = ir_lvl;
if(ir_lvl) {
WCB3INTR.WCB3FL = static_cast<uint8_t>(fl);
WCB3INTR.WCB3S = static_cast<uint8_t>(eg);
WCB3INTR.WCB3INTEN = 1;
} else {
WCB3INTR.WCB3INTEN = 0;
}
}
/*!
@brief
@return
*/
bool get_value1() const {
return WCMPR.WCB1OUT();
}
/*!
@brief
@return
*/
bool get_value3() const {
return WCMPR.WCB3OUT();
}
};
}
|
To update Mongo to Version 4.0 you must first upgrade to 3.6 then to version 4.0 as follows
1. Install 3.6 Binary
2. Close mongo and mongod
3. Start mongo and mongod in 3.6 bin folder
4. run command db.adminCommand({<API key>: "3.6"})
1. Install 4.0 Binary
2. Close mongo and mongod
3. Start mongo and mongod in 3.6 bin folder
4. run command db.adminCommand({<API key>: "4.0"})
|
#include <vector>
#include <list>
#include <cctype>
#include <algorithm>
#include "libtorrent/config.hpp"
#include "libtorrent/gzip.hpp"
#include "libtorrent/socket_io.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/bind.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/<API key>.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/broadcast_socket.hpp" // for is_local
using namespace libtorrent;
namespace libtorrent
{
#if TORRENT_USE_I2P
// defined in torrent_info.cpp
bool is_i2p_url(std::string const& url);
#endif
<API key>::<API key>(
io_service& ios
, connection_queue& cc
, tracker_manager& man
, tracker_request const& req
, boost::weak_ptr<request_callback> c
, aux::session_impl& ses
, std::string const& auth
#if TORRENT_USE_I2P
, i2p_connection* i2p_conn
#endif
)
: tracker_connection(man, req, ios, c)
, m_man(man)
, m_ses(ses)
, m_cc(cc)
, m_ios(ios)
#if TORRENT_USE_I2P
, m_i2p_conn(i2p_conn)
#endif
{}
void <API key>::start()
{
// TODO: 0 support authentication (i.e. user name and password) in the URL
std::string url = tracker_req().url;
if (tracker_req().kind == tracker_request::scrape_request)
{
// find and replace "announce" with "scrape"
// in request
std::size_t pos = url.find("announce");
if (pos == std::string::npos)
{
tracker_connection::fail(error_code(errors::<API key>));
return;
}
url.replace(pos, 8, "scrape");
}
#if TORRENT_USE_I2P
bool i2p = is_i2p_url(url);
#else
static const bool i2p = false;
#endif
aux::session_settings const& settings = m_ses.settings();
// if request-string already contains
// some parameters, append an ampersand instead
// of a question mark
size_t arguments_start = url.find('?');
if (arguments_start != std::string::npos)
url += "&";
else
url += "?";
if (tracker_req().kind == tracker_request::announce_request)
{
const char* event_string[] = {"completed", "started", "stopped", "paused"};
char str[1024];
const bool stats = tracker_req().send_stats;
snprintf(str, sizeof(str)
, "info_hash=%s"
"&peer_id=%s"
"&port=%d"
"&uploaded=%" PRId64
"&downloaded=%" PRId64
"&left=%" PRId64
"&corrupt=%" PRId64
"&key=%08X"
"%s%s" // event
"&numwant=%d"
"&compact=1"
"&no_peer_id=1"
, escape_string((const char*)&tracker_req().info_hash[0], 20).c_str()
, escape_string((const char*)&tracker_req().pid[0], 20).c_str()
// the i2p tracker seems to verify that the port is not 0,
// even though it ignores it otherwise
, i2p ? 1 : tracker_req().listen_port
, stats ? tracker_req().uploaded : 0
, stats ? tracker_req().downloaded : 0
, stats ? tracker_req().left : 0
, stats ? tracker_req().corrupt : 0
, tracker_req().key
, (tracker_req().event != tracker_request::none) ? "&event=" : ""
, (tracker_req().event != tracker_request::none) ? event_string[tracker_req().event - 1] : ""
, tracker_req().num_want);
url += str;
#ifndef <API key>
if (m_ses.settings().get_int(settings_pack::in_enc_policy) != settings_pack::pe_disabled
&& m_ses.settings().get_bool(settings_pack::<API key>))
url += "&supportcrypto=1";
#endif
if (stats && m_ses.settings().get_bool(settings_pack::<API key>))
{
url += "&redundant=";
url += to_string(tracker_req().redundant).elems;
}
if (!tracker_req().trackerid.empty())
{
std::string id = tracker_req().trackerid;
url += "&trackerid=";
url += escape_string(id.c_str(), id.length());
}
#if TORRENT_USE_I2P
if (i2p)
{
url += "&ip=";
url += escape_string(m_i2p_conn->local_endpoint().c_str()
, m_i2p_conn->local_endpoint().size());
url += ".i2p";
}
else
#endif
if (!m_ses.settings().get_bool(settings_pack::anonymous_mode))
{
std::string announce_ip = settings.get_str(settings_pack::announce_ip);
if (!announce_ip.empty())
{
url += "&ip=" + escape_string(announce_ip.c_str(), announce_ip.size());
}
else if (m_ses.settings().get_bool(settings_pack::announce_double_nat)
&& is_local(m_ses.listen_address()))
{
// only use the global external listen address here
// if it turned out to be on a local network
// since otherwise the tracker should use our
// source IP to determine our origin
url += "&ip=" + print_address(m_ses.listen_address());
}
}
}
<API key>.reset(new http_connection(m_ios, m_cc, m_ses.m_host_resolver
, boost::bind(&<API key>::on_response, self(), _1, _2, _3, _4)
, true, settings.get_int(settings_pack::<API key>)
, boost::bind(&<API key>::on_connect, self(), _1)
, boost::bind(&<API key>::on_filter, self(), _1, _2)
#ifdef TORRENT_USE_OPENSSL
, tracker_req().ssl_ctx
#endif
));
int timeout = tracker_req().event==tracker_request::stopped
?settings.get_int(settings_pack::<API key>)
:settings.get_int(settings_pack::<API key>);
// when sending stopped requests, prefer the cached DNS entry
// to avoid being blocked for slow or failing responses. Chances
// are that we're shutting down, and this should be a best-effort
// attempt. It's not worth stalling shutdown.
proxy_settings ps = m_ses.proxy();
<API key>->get(url, seconds(timeout)
, tracker_req().event == tracker_request::stopped ? 2 : 1
, &ps, 5, settings.get_bool(settings_pack::anonymous_mode)
? "" : settings.get_str(settings_pack::user_agent)
, bind_interface()
, tracker_req().event == tracker_request::stopped
? resolver_interface::prefer_cache
: 0
#if TORRENT_USE_I2P
, m_i2p_conn
#endif
);
// the url + 100 estimated header size
sent_bytes(url.size() + 100);
#if defined(<API key>) || defined(TORRENT_LOGGING)
boost::shared_ptr<request_callback> cb = requester();
if (cb)
{
cb->debug_log("==> TRACKER_REQUEST [ url: %s ]", url.c_str());
}
#endif
}
void <API key>::close()
{
if (<API key>)
{
<API key>->close();
<API key>.reset();
}
tracker_connection::close();
}
void <API key>::on_filter(http_connection& c, std::vector<tcp::endpoint>& endpoints)
{
if (tracker_req().apply_ip_filter == false) return;
// remove endpoints that are filtered by the IP filter
for (std::vector<tcp::endpoint>::iterator i = endpoints.begin();
i != endpoints.end();)
{
if (m_ses.m_ip_filter.access(i->address()) == ip_filter::blocked)
i = endpoints.erase(i);
else
++i;
}
#if defined(<API key>) || defined(TORRENT_LOGGING)
boost::shared_ptr<request_callback> cb = requester();
if (cb)
{
cb->debug_log("*** TRACKER_FILTER");
}
#endif
if (endpoints.empty())
fail(error_code(errors::banned_by_ip_filter));
}
void <API key>::on_connect(http_connection& c)
{
error_code ec;
tcp::endpoint ep = c.socket().remote_endpoint(ec);
m_tracker_ip = ep.address();
boost::shared_ptr<request_callback> cb = requester();
}
void <API key>::on_response(error_code const& ec
, http_parser const& parser, char const* data, int size)
{
// keep this alive
boost::intrusive_ptr<<API key>> me(this);
if (ec && ec != asio::error::eof)
{
fail(ec);
return;
}
if (!parser.header_finished())
{
fail(asio::error::eof);
return;
}
if (parser.status_code() != 200)
{
fail(error_code(parser.status_code(), get_http_category())
, parser.status_code(), parser.message().c_str());
return;
}
if (ec && ec != asio::error::eof)
{
fail(ec, parser.status_code());
return;
}
received_bytes(size + parser.body_start());
// handle tracker response
error_code ecode;
boost::shared_ptr<request_callback> cb = requester();
if (!cb)
{
close();
return;
}
tracker_response resp = <API key>(data, size, ecode
, tracker_req().kind == tracker_request::scrape_request
, tracker_req().info_hash);
if (!resp.warning_message.empty())
cb->tracker_warning(tracker_req(), resp.warning_message);
if (ecode)
{
fail(ecode, parser.status_code());
close();
return;
}
if (!resp.failure_reason.empty())
{
fail(error_code(errors::tracker_failure), parser.status_code()
, resp.failure_reason.c_str(), resp.interval, resp.min_interval);
close();
return;
}
// do slightly different things for scrape requests
if (tracker_req().kind == tracker_request::scrape_request)
{
cb-><API key>(tracker_req(), resp.complete
, resp.incomplete, resp.downloaded, resp.downloaders);
}
else
{
std::list<address> ip_list;
if (<API key>)
{
error_code ec;
ip_list.push_back(
<API key>->socket().remote_endpoint(ec).address());
std::vector<tcp::endpoint> const& epts = <API key>->endpoints();
for (std::vector<tcp::endpoint>::const_iterator i = epts.begin()
, end(epts.end()); i != end; ++i)
{
ip_list.push_back(i->address());
}
}
cb->tracker_response(tracker_req(), m_tracker_ip, ip_list, resp);
}
close();
}
bool extract_peer_info(lazy_entry const& info, peer_entry& ret, error_code& ec)
{
// extract peer id (if any)
if (info.type() != lazy_entry::dict_t)
{
ec.assign(errors::invalid_peer_dict, <API key>());
return false;
}
lazy_entry const* i = info.dict_find_string("peer id");
if (i != 0 && i->string_length() == 20)
{
std::copy(i->string_ptr(), i->string_ptr()+20, ret.pid.begin());
}
else
{
// if there's no peer_id, just initialize it to a bunch of zeroes
std::fill_n(ret.pid.begin(), 20, 0);
}
// extract ip
i = info.dict_find_string("ip");
if (i == 0)
{
ec.assign(errors::<API key>, <API key>());
return false;
}
ret.hostname = i->string_value();
// extract port
i = info.dict_find_int("port");
if (i == 0)
{
ec.assign(errors::<API key>, <API key>());
return false;
}
ret.port = (unsigned short)i->int_value();
return true;
}
tracker_response <API key>(char const* data, int size, error_code& ec
, bool scrape_request, sha1_hash scrape_ih)
{
tracker_response resp;
lazy_entry e;
int res = lazy_bdecode(data, data + size, e, ec);
if (ec) return resp;
if (res != 0 || e.type() != lazy_entry::dict_t)
{
ec.assign(errors::<API key>, <API key>());
return resp;
}
int interval = int(e.dict_find_int_value("interval", 0));
// if no interval is specified, default to 30 minutes
if (interval == 0) interval = 1800;
int min_interval = int(e.dict_find_int_value("min interval", 30));
resp.interval = interval;
resp.min_interval = min_interval;
lazy_entry const* tracker_id = e.dict_find_string("tracker id");
if (tracker_id)
resp.trackerid = tracker_id->string_value();
// parse the response
lazy_entry const* failure = e.dict_find_string("failure reason");
if (failure)
{
resp.failure_reason = failure->string_value();
ec.assign(errors::tracker_failure, <API key>());
return resp;
}
lazy_entry const* warning = e.dict_find_string("warning message");
if (warning)
resp.warning_message = warning->string_value();
if (scrape_request)
{
lazy_entry const* files = e.dict_find_dict("files");
if (files == 0)
{
ec.assign(errors::invalid_files_entry, <API key>());
return resp;
}
lazy_entry const* scrape_data = files->dict_find_dict(
scrape_ih.to_string());
if (scrape_data == 0)
{
ec.assign(errors::invalid_hash_entry, <API key>());
return resp;
}
resp.complete = int(scrape_data->dict_find_int_value("complete", -1));
resp.incomplete = int(scrape_data->dict_find_int_value("incomplete", -1));
resp.downloaded = int(scrape_data->dict_find_int_value("downloaded", -1));
resp.downloaders = int(scrape_data->dict_find_int_value("downloaders", -1));
return resp;
}
// look for optional scrape info
resp.complete = int(e.dict_find_int_value("complete", -1));
resp.incomplete = int(e.dict_find_int_value("incomplete", -1));
resp.downloaded = int(e.dict_find_int_value("downloaded", -1));
lazy_entry const* peers_ent = e.dict_find("peers");
if (peers_ent && peers_ent->type() == lazy_entry::string_t)
{
char const* peers = peers_ent->string_ptr();
int len = peers_ent->string_length();
resp.peers4.reserve(len / 6);
for (int i = 0; i < len; i += 6)
{
if (len - i < 6) break;
ipv4_peer_entry p;
error_code ec;
p.ip = detail::read_v4_address(peers).to_v4().to_bytes();
p.port = detail::read_uint16(peers);
resp.peers4.push_back(p);
}
}
else if (peers_ent && peers_ent->type() == lazy_entry::list_t)
{
int len = peers_ent->list_size();
resp.peers.reserve(len);
error_code parse_error;
for (int i = 0; i < len; ++i)
{
peer_entry p;
if (!extract_peer_info(*peers_ent->list_at(i), p, parse_error))
continue;
resp.peers.push_back(p);
}
// only report an error if all peer entries are invalid
if (resp.peers.empty() && parse_error)
{
ec = parse_error;
return resp;
}
}
else
{
peers_ent = 0;
}
#if TORRENT_USE_IPV6
lazy_entry const* ipv6_peers = e.dict_find_string("peers6");
if (ipv6_peers)
{
char const* peers = ipv6_peers->string_ptr();
int len = ipv6_peers->string_length();
resp.peers6.reserve(len / 18);
for (int i = 0; i < len; i += 18)
{
if (len - i < 18) break;
ipv6_peer_entry p;
p.ip = detail::read_v6_address(peers).to_v6().to_bytes();
p.port = detail::read_uint16(peers);
resp.peers6.push_back(p);
}
}
else
{
ipv6_peers = 0;
}
#else
lazy_entry const* ipv6_peers = 0;
#endif
/*
// if we didn't receive any peers. We don't care if we're stopping anyway
if (peers_ent == 0 && ipv6_peers == 0
&& tracker_req().event != tracker_request::stopped)
{
ec.assign(errors::invalid_peers_entry, <API key>());
return resp;
}
*/
lazy_entry const* ip_ent = e.dict_find_string("external ip");
if (ip_ent)
{
char const* p = ip_ent->string_ptr();
if (ip_ent->string_length() == int(address_v4::bytes_type().size()))
resp.external_ip = detail::read_v4_address(p);
#if TORRENT_USE_IPV6
else if (ip_ent->string_length() == int(address_v6::bytes_type().size()))
resp.external_ip = detail::read_v6_address(p);
#endif
}
return resp;
}
}
|
<?php
use yii\helpers\Url;
?>
<div class="bjui-pageContent">
<form action="<?= Url::toRoute([$model?'update':'create','name'=>$model?$model->name:'']) ?>" id="user_form" data-toggle="validate" data-alertmsg="false">
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
<table class="table table-condensed table-hover" width="100%">
<tbody>
<tr>
<td><label for="name" class="control-label x120"></label> <input type="text" name="name" id="name" value="<?= $model?$model->name:''; ?>" data-rule="required" size="20"></td>
</tr>
<tr>
<td><label for="class" class="control-label x120"></label> <input type="text" name="class" id="class" value="<?= $model?$model::className():''; ?>" data-rule="required" size="35"></td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="bjui-pageFooter">
<ul>
<li>
<button type="button" class="btn-close" data-icon="close"></button>
</li>
<li>
<button type="submit" class="btn-default" data-icon="save"></button>
</li>
</ul>
</div>
|
// <API key>.h
// SeafloorExplore
// Modified from Brad Larson's Molecules Project in 2011-2012 for use in The SeafloorExplore Project
// Molecules
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface <API key> : UITableViewCell
{
CAGradientLayer *<API key>;
BOOL isSelected;
}
@property(assign, nonatomic) CAGradientLayer *<API key>;
@property(assign, nonatomic) BOOL isSelected;
@end
|
# Migration Guide 2.x to 3.0
## General
Removed ui object
The `ui` object (`tabris.ui`) and `Ui` class no longer exist. All properties formerly hosted by `ui` are now directly attached to the `tabris` object/namespace. Example:
Tabris 2.x
js
import {ui} from 'tabris';
ui.contentView.background = 'red';
ui.drawer.background = 'red';
ui.statusBar.background = 'red';
ui.navigationBar.background = 'red';
Tabris 3.0
js
import {contentView, drawer, statusBar, navigationBar} from 'tabris';
contentView.background = 'red';
drawer.background = 'red';
statusBar.background = 'red';
navigationBar.background = 'red';
Removed `get("prop")` and `set("prop", value)`
This concerns all instances of `NativeObject` (including widgets) and `WidgetCollection`.
The `set` method still exists, but now only takes one argument (the properties object).
The `get` method has been removed entirely.
# Alternatives for `set("prop", value)`:
On both `NativeObject` and `WidgetCollection`, `obj.set('foo', baz)` can be replaced with `obj.set({foo: baz})`,
and `obj.set(bar, baz)` can be replaced with `obj.set({[foo]: baz})`.
On `NativeObject` only, `obj.set('foo', baz)` can be replaced with `obj.foo = baz`,
and `obj.set(bar, baz)` can be replaced with `obj[bar] = baz`.
# Alternatives for `get("prop")`:
On `NativeObject`, `bar = obj.get('foo')` can be replaced with `bar = obj.foo`,
and `baz = obj.get(bar)` can be replaced with `baz = obj[bar]`.
On `WidgetCollection`, `bar = wc.get('foo');` can be replaced with `bar = wc.first().foo`,
and `baz = wc.get(bar)` can be replaced with `baz = wc.first()[bar]`.
app.installPatch removed
You can no longer patch your application using this method.
AlertDialog textInputs property is now a ContentView
Instead of assigning `TextInputs` widgets to that property they need to be appended:
Old:
js
alertDialog.textInputs = [new TextInput()];
New:
js
alertDialog.textInputs.append(new TextInput());
Alternatively JSX my be used:
jsx
<AlertDialog>
<TextInput/>
</AlertDialog>
Removed properties "placementPriority" of Action and "navigationAction" of NavigationView
These properties are replaced by a new property `placement` on the `Action` widget. It accepts the values `'default'` (same as `placementPriority = 'normal'`), `'overflow'` (same as a `placementPriority = 'low'`) and `'navigation'`, which puts the action in the place usually reserved by the drawer icon.
Removed property `topToolbarHeight` and `bottomToolbarHeight` on `NavigationView`
On iOS a toolbar at the bottom of a `NavigationView` has been used for actions with low priority. With the introduction of the new `Action` `placement` property the bottom toolbar has been removed along with the respective properties `topToolbarHeight` and `bottomToolbarHeight`. In their place a new property `toolbarHeight` has been added.
Removed widgetCollection.find
This method has been removed due to its ambiguous nature. This does not affect `composite.find` which still exists.
"trigger" object/eventObject parameter is now cloned
**This is relevant only if in your application you are passing values to `trigger` of types other than `Object` or `EventObject`.** Examples would be passing primitives (e.g. `trigger('select', selectionIndex);`) or instances of classes other than `Object` (e.g. `trigger('select', someArray);`). If you do that you need to change this to pass an object that references the value instead (e.g. `trigger('select', {selectionIndex});`)
Previously the second parameter of the `trigger` method was directly passed on to all listeners in all cases. However, we want to ensure that listeners can always expect to be called with a valid `EventObject` instance. For that reason the values of the `trigger` parameter are now copied to a new event object, *unless* the given parameter is already an instance of `EventObject` and has not been initialized yet.
Color properties
All color properties are now of the type `ColorValue`. While these properties still accept the same string values as in 2.x, they will return a "Color" class instance instead of a string. The exception is CanvasContext, where color properties still return a string for W3C compatibility.
Widget.background property
Widget background setter now also accepts `ColorValue`, `ImageValue`, and `LinearGradientValue` values and the getter will return instances of the "Color", "Image" and "LinearGradient" classes.
Widget.backgroundImage property removed
You can now set images directly on the `background` property.
alignment properties
All widget `alignment` properties (on `Button`, `TextInput`, `TextView` and `ToggleButton`) now expect `centerX` instead of `center`.
TabFolder.textColor property replaced with more flexible properties
The `TabFolder.textColor` property has been replaced with a set of new properties which provide more
control over the appearance of the TabFolder tabs:
- `tabTintColor`
- `<API key>`
- `tabBarBackground`
- `<API key>`
In addition the `TabFolder` gained the property `tabBarElevation` which is applicable on Android.
Tab.badge property changed to be of type number instead of string
With the added support for `badge` on Android, the type of the `badge` property has been updated to be a number:
js
tab.badge = 10
CollectionView select event removed
The collectionView no longer provides a select event. Interactions with a cell have to be handled directly by listeners attached to the cell. A new method `itemIndex` may be used to determine the index associated with a cell:
js
collectionView.createCell = () => {
const cell = new SomeWidget();
cell.onTap(() => {
const index = cell.parent(CollectionView).itemIndex(cell);
// do something with the item...
});
return cell;
}
Picker allows empty state with "message" property as placeholder
The `Picker` now allows to show an (initial) empty state. This unselected state can be filled with a `message` text similar to a `TextInput`. The initial `selectionIndex` is therefore `-1`. It can also be set to `-1` which shows the empty state or the `message` respectively.
To recreate the previous behavior the `selectionIndex` could be set to `0`.
Picker property "fillColor" removed
With the introduction of the new `style` property on `Picker`, the iOS only property `fillColor` became redundant.
Previously the `fillColor` was required to separate the Android underline colorization from the ios picker background color. Setting the `Picker` `style` to _underline_ on Android now ignores the background and only applies the `borderColor` property.
Font properties
All font properties are now of the type "FontValue". While these properties still accept the same string values as in 2.x, they will return a "Font" class instance instead of a string. The exception is CanvasContext, where font properties still return a string for W3C compatibility.
Image properties
All image properties are now of the type "ImageValue". While these properties still accept the same string values as in 2.x, they will return an "Image" class instance instead of a string.
Gesture event "longpress" renamed to "longPress"
To be consistent with the event naming scheme of gesture events, the event "longpress" has been renamed to "longPress".
TextInput property "fillColor" removed
With the introduction of the new `style` property on `TextInput`, the iOS only property `fillColor` became redundant. Previously the `fillColor` was required to separate the Android underline colorization from the ios input background color. Setting the `TextInput` `style` to _underline_ on Android now ignores the background and only applies the `borderColor` property.
## TypeScript
Properties interfaces removed
The `tabris` module no longer exports a separate properties interfaces for every built-in type. These can be replaced with the generic `Properties` type:
`CompositeProperties` `=>` `Properties<Composite>`
"tsProperties" property no longer supported
It is no longer necessary or supported to create a property `tsProperties` on classes inheriting from `Widget` to control the properties accepted by the `set` method. In most cases public properties are recognized by `set` automatically. That excludes methods/functions.
When called on `this` the supported properties can not be inferred. To fix this the `set` method can be overwritten/re-declared, or it may be called with the appropriate generic type like this: `this.set<MyComponent>({propA: valueA});`
type "Partial"
The helper type `Partial<T, U>` was removed to avoid confusion with the `Partial` type built in to newer TypeScript versions. It can be replaced with `Partial<Pick<T, U>>`.
CollectionView is generic
The `CollectionView` is now a generic type `CollectionView<Cell extends Widget>`, where `Cell` is the type of widget returned by the `createCell` callback. All occurrences of `CollectionView` as a type should be replaced with the appropriate generic version, e.g. `CollectionView<Composite>`.
types "dimension" and "offset"
Types "dimension" and "offset" have been renamed to start with an upper case.
Type "margin" has been replaced with "ConstraintValue", which includes the former "margin" type.
LayoutData and related properties
The `layoutData` property is now of the type `LayoutDataValue`. The values that were accepted in 2.x are still accepted, with one exception: It was previously possible to give a percentage as a number type within a `margin` (now `ConstraintValue`) type array, i.e. `[number, number]`. However, this was an undocumented feature, as the documentation stated:
> "All **percentages** are provided as strings with a percent suffix, e.g. `"50%"`."
All percentages are now of the `PercentValue` type, i.e. a string like `"50%"`, an instance of the `Percent` class, or a `Percent`-like object, e.g. `{percent: 50}`.
The return value of the `layoutData` property is now always an instance of the `LayoutData` class instead of a plain object.
The shorthand properties to `layoutData` now also return the normalized types used in the `LayoutData` class, i.e. an instance of `Constraint` (for `left`, `right`, `top` and `bottom`) or `SiblingReference` (for `baseline`), a number (for `width`, `height`, `centerX` and `centerY`), or `"auto"` (the default for all of these).
In 2.x, negative edge offsets were previously supported on some platforms. To prevent inconsistent layouts among platforms, they are not supported anymore.
Event handling
The methods `on` and `once` no longer have widget-specific parameters, meaning they are not type-safe anymore. Strictly speaking this is not a breaking change, but it is strongly recommended to switch to the new (type safe) `Listeners` API as soon as possible. Some examples:
`widget.on('resize', listener)` and `widget.on({resize: listener})` become `widget.onResize(listener)`.
`widget.off('resize', listener)` becomes `widget.onResize.removeListener(listener)`.
`widget.once('resize', listener)` becomes `widget.onResize.once(listener)`.
## JSX
Elements need to be imported
Tabris no longer provides "intrinsic" elements. This means that instead of creating a built-in widget via a lowercase element it has to be done by referencing the actual widget class.
Example:
This...
jsx
import { ui } from 'tabris';
ui.contentView.append(<textView text='foo'/>);
has to be changed to:
jsx
import { contentView, TextView } from 'tabris';
contentView.append(<TextView text='foo' />);
Only widgets actually supporting different fonts now have a font property. Most applications should not have to adjust to this change.
jsxProperties
It used to be necessary to declare this property to add JSX attributes to a custom component. This now happens automatically. The mechanism itself is still present, but the property is now named `jsxAttributes` to make it distinct from the properties of the created object. Declaring `jsxAttributes` may sometimes be be necessary because properties that are either functions or are marked as readonly are not available as JSX attributes by default.
## Cordova plugins
The Cordova CLI dependency has been updated from `6.5.0` to `8.1.2`. The Cordova CLI will now use the system `npm` to install plugins. This has following implications:
* Plugins need to provide a `package.json` in their root directory.
* Plugins in package [subdirectories](https://cordova.apache.org/docs/en/6.x/reference/cordova-cli/index.html#plugin-spec) are not supported anymore.
## Android custom theme
Creating a custom theme follows the same approach as in 2.x but the paths to the theme.xml file has been changed slightly due to the migration to cordova-android 8.0. Declared theme.xml resource files need to be prefixed with with `app/src/main/`, e.g.:
<resource-file src="res/android/values/my_theme.xml" target="res/values/my_theme.xml" />
should be changed to:
<resource-file src="res/android/values/my_theme.xml" target="app/src/main/res/values/my_theme.xml" />
For more details on Android custom themes see: https://docs.tabris.com/3.0/theming-android.html
|
#include "main.h"
#include "User.h"
#include "Nick.h"
#include "Modules.h"
#include "Chan.h"
#include "FileUtils.h"
#include <pthread.h>
#include <climits>
#define MAX_EXTS 6
#define MAX_CHARS 16
class CUrlBufferModule : public CModule
{
private:
VCString lastUrls, nicks;
unsigned int linkNum;
CString target;
static const string supportedExts[MAX_EXTS];
static const char unSupportedChars[MAX_CHARS];
static inline CString <API key>(const CString& cmd);
inline void LoadDefaults();
inline CString convertTime(const CString& str)
{
time_t curtime;
tm* timeinfo;
char buffer[1024];
time(&curtime);
curtime += (time_t) (m_pUser->GetTimezoneOffset() * 60 * 60);
timeinfo = localtime(&curtime);
if (!strftime(buffer, sizeof(buffer), str.c_str(), timeinfo))
{
return "";
}
return CString(buffer);
}
inline bool isValidExtension(CString ext)
{
ext.MakeLower();
for(int i=0; i< MAX_EXTS; i++)
{
if( ext == supportedExts[i])
return true;
}
return false;
}
inline bool isValidDir(const string& dir)
{
for(int i=0; i< MAX_CHARS; i++)
{
if (dir.find(unSupportedChars[i]) !=string::npos)
return false;
}
return true;
}
static void* sendLinks(void *ptr);
inline void CheckLineForLink(const CString& sMessage, const CString& sOrigin);
inline void CheckLineForTrigger(const CString& sMessage, const CString& sTarget);
public:
MODCONSTRUCTOR(CUrlBufferModule) {}
bool OnLoad(const CString& sArgs, CString& sErrorMsg);
~CUrlBufferModule();
EModRet OnUserMsg(CString& sTarget, CString& sMessage);
EModRet OnPrivMsg(CNick& Nick, CString& sMessage);
EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage);
void OnModCommand(const CString& sCommand);
};
const string CUrlBufferModule::supportedExts[MAX_EXTS] =
{"jpg", "png", "gif", "jpeg", "bmp", "tiff"} ;
const char CUrlBufferModule::unSupportedChars[MAX_CHARS] =
{'|', ';', '!', '@', '
bool CUrlBufferModule::OnLoad(const CString& sArgs, CString& sErrorMsg)
{
LoadDefaults();
return true;
}
CUrlBufferModule::~CUrlBufferModule() {}
CUrlBufferModule::EModRet CUrlBufferModule::OnUserMsg(CString& sTarget, CString& sMessage)
{
CheckLineForLink(sMessage, "");
CheckLineForTrigger(sMessage, m_pUser->GetIRCNick().GetNick());
return CONTINUE;
}
CUrlBufferModule::EModRet CUrlBufferModule::OnPrivMsg(CNick& Nick, CString& sMessage)
{
CheckLineForLink(sMessage, Nick.GetNick());
CheckLineForTrigger(sMessage, Nick.GetNick());
return CONTINUE;
}
CUrlBufferModule::EModRet CUrlBufferModule::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage)
{
CheckLineForLink(sMessage, Nick.GetNick());
CheckLineForTrigger(sMessage, Nick.GetNick());
return CONTINUE;
}
void CUrlBufferModule::OnModCommand(const CString& sCommand)
{
CString command = sCommand.Token(0).AsLower().Trim_n();
if (command == "help")
{
CTable CmdTable;
CmdTable.AddColumn("Command");
CmdTable.AddColumn("Description");
CmdTable.AddRow();
CmdTable.SetCell("Command", "ENABLE");
CmdTable.SetCell("Description", "Activates link buffering.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DISABLE");
CmdTable.SetCell("Description", "Deactivates link buffering.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "ENABLELOCAL");
CmdTable.SetCell("Description", "Enables downloading of each link to local directory.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DISABLELOCAL");
CmdTable.SetCell("Description", "Disables downloading of each link to local directory.");
CmdTable.AddRow();
CmdTable.SetCell("Command","ENABLEPUBLIC");
CmdTable.SetCell("Description", "Enables the usage of !showlinks publicly, by other users.");
CmdTable.AddRow();
CmdTable.SetCell("Command","DISABLEPUBLIC");
CmdTable.SetCell("Description", "Disables the usage of !showlinks publicly, by other users.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "DIRECTORY <#directory>");
CmdTable.SetCell("Description", "Sets the local directory where the links will be saved.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "CLEARBUFFER");
CmdTable.SetCell("Description", "Empties the link buffer.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "BUFFERSIZE <#size>");
CmdTable.SetCell("Description", "Sets the size of the link buffer. Only integers >=0.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "SHOWSETTINGS");
CmdTable.SetCell("Description", "Prints all the settings.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "BUFFERALLLINKS");
CmdTable.SetCell("Description", "Toggles the buffering of all links or only image links.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "SHOWLINKS <#number>");
CmdTable.SetCell("Description", "Prints <#number> or <#buffersize> number of cached links.");
CmdTable.AddRow();
CmdTable.SetCell("Command", "HELP");
CmdTable.SetCell("Description", "This help.");
PutModule(CmdTable);
return;
}else if (command == "enable")
{
SetNV("enable","true",true);
PutModule("Enabled buffering");
}else if (command == "disable")
{
SetNV("enable","false",true);
PutModule("Disabled buffering");
}else if (command == "enablelocal")
{
if(GetNV("directory") == "")
{
PutModule("Directory is not set. First set a directory and then enable local caching");
return;
}
SetNV("enablelocal","true",true);
PutModule("Enabled local caching");
}else if (command == "disablelocal")
{
SetNV("enablelocal", "false", true);
PutModule("Disabled local caching");
}else if (command == "enablepublic")
{
SetNV("enablepublic", "true", true);
PutModule("Enabled public usage of showlinks.");
}else if (command == "disablepublic")
{
SetNV("enablepublic", "false", true);
PutModule("Disabled public usage of showlinks.");
}else if (command == "directory")
{
CString dir=sCommand.Token(1).Replace_n("//", "/").TrimRight_n("/") + "/";
if (!isValidDir(dir))
{
PutModule("Error in directory name. Avoid using: | ; ! @ # ( ) < > \" ' ` ~ = & ^ <space> <tab>");
return;
}
// Check if file exists and is directory
if (dir.empty() || !CFile::Exists(dir) || !CFile::IsDir(dir, false))
{
PutModule("Invalid path or no write access to ["+ sCommand.Token(1) +"].");
return;
}
SetNV("directory", dir, true);
PutModule("Directory for local caching set to " + GetNV("directory"));
}else if (command == "clearbuffer")
{
lastUrls.clear();
nicks.clear();
}else if (command == "buffersize")
{
unsigned int bufSize = sCommand.Token(1).ToUInt();
if(bufSize==0 || bufSize==UINT_MAX)
{
PutModule("Error in buffer size. Use only integers >= 0.");
return;
}
SetNV("buffersize", CString(bufSize), true);
PutModule("Buffer size set to " + GetNV("buffersize"));
}else if (command == "showsettings")
{
for(MCString::iterator it = BeginNV(); it != EndNV(); it++)
{
PutModule(it->first.AsUpper() + " : " + it->second);
}
}else if(command == "bufferalllinks"){
SetNV("bufferalllinks", CString(!GetNV("bufferalllinks").ToBool()), true);
PutModule( CString(GetNV("bufferalllinks").ToBool()?"Enabled":"Disabled") + " buffering of all links.");
}else if (command == "showlinks")
{
if(lastUrls.empty())
PutModule("No links were found...");
else
{
unsigned int maxLinks = GetNV("buffersize").ToUInt();
unsigned int size = sCommand.Token(1).ToUInt();
if(size!=0 && size<UINT_MAX) //if it was a valid number
maxLinks = size;
unsigned int maxSize = lastUrls.size()-1;
for(unsigned int i=0; i<=maxSize && i< maxLinks; i++)
{
PutModule(nicks[maxSize-i] + ": " + lastUrls[maxSize-i]);
}
}
}else
{
PutModule("Unknown command! Try HELP.");
}
}
void CUrlBufferModule::LoadDefaults()
{
if(GetNV("enable")==""){
SetNV("enable", "true", true);
}
if(GetNV("enablelocal")==""){
SetNV("enablelocal", "false", true);
}
if(GetNV("buffersize")== ""){
SetNV("buffersize", "5", true);
}
if(GetNV("enablepublic")==""){
SetNV("enablepublic", "true", true);
}
if(GetNV("bufferalllinks")==""){
SetNV("bufferalllinks", "false", true);
}
}
void CUrlBufferModule::CheckLineForLink(const CString& sMessage, const CString& sOrigin)
{
if(sOrigin != m_pUser->GetIRCNick().GetNick() && GetNV("enable").ToBool() )
{
VCString words;
CString output;
sMessage.Split(" ", words, false, "", "", true, true);
for (size_t a = 0; a < words.size(); a++)
{
CString& word = words[a];
if(word.Left(4) == "http" || word.Left(4) == "www.")
{
//if you find an image download it, save it in the www directory and keep the new link in buffer
VCString tokens;
word.Split("/", tokens, false, "", "", true, true);
string name = tokens[tokens.size()-1];
word.Split(".", tokens, false, "", "", true, true);
//if it's an image link download/upload it else just keep the link
if(isValidExtension( tokens[tokens.size()-1] ))
{
std::stringstream ss;
if( GetNV("enablelocal").ToBool())
{
CString dir = GetNV("directory") + convertTime("%Y-%m-%d") + "/";
if(!CFile::Exists(dir) && !CFile::IsDir(dir, false))
{
CDir::MakeDir(dir, 0755);
}
ss << "wget -b -O " << dir.c_str() << name <<" -q " << word.c_str() << " 2>&1";
<API key>(ss.str());
}
ss.str("");
if (!word.WildCmp("*imgur*")) {
ss << "curl -d \"image=" << word.c_str() << "\" -d \"key=<API key>\" http://api.imgur.com/2/upload.xml | sed -n 's/.*<original>\\(.*\\)<\\/original>.*/\\1/p' 2>&1";
output = <API key>(ss.str());
lastUrls.push_back(output);
}else {
lastUrls.push_back(word);
}
} else if(GetNV("bufferalllinks").ToBool()){
lastUrls.push_back(word);
}
nicks.push_back( (sOrigin.empty())? m_pUser->GetIRCNick().GetNick() : sOrigin );
}
}
}
}
CString CUrlBufferModule::<API key>(const CString& cmd)
{
string data="";
char buffer[128];
FILE* stream = popen(cmd.c_str(), "r");
if (stream == NULL || !stream || ferror(stream))
{
return "Error!";
}
while (!feof(stream))
{
if (fgets(buffer, 128, stream) != NULL)
data.append(buffer);
}
pclose(stream);
return data;
}
void *CUrlBufferModule::sendLinks(void *ptr)
{
CUrlBufferModule *caller = static_cast<CUrlBufferModule*> (ptr);
VCString links = caller->lastUrls;
VCString nicks = caller->nicks;
unsigned int maxSize = links.size()-1;
for(unsigned int i=0; i<=maxSize && i<caller->linkNum; i++)
{
sleep(2);
caller->PutIRC("PRIVMSG " + caller->target + " :" + nicks[maxSize-i] + ": "+ links[maxSize-i]);
}
return NULL;
}
void CUrlBufferModule::CheckLineForTrigger(const CString& sMessage, const CString& sTarget)
{
if(GetNV("enablepublic").ToBool())
{
VCString words;
sMessage.Split(" ", words, false, "", "", true, true);
for (size_t a = 0; a < words.size(); a++)
{
CString& word = words[a];
if(word.AsLower() == "!showlinks")
{
if(lastUrls.empty())
PutIRC("PRIVMSG " + sTarget + " :No links were found...");
else
{
unsigned int maxLinks = GetNV("buffersize").ToUInt();
if (a+1 < words.size())
{
unsigned int size = words[a+1].ToUInt();
if(size!=0 && size<UINT_MAX) //if it was a valid number
maxLinks = size;
}
linkNum = maxLinks;
target = sTarget;
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
<API key>(&attr, <API key>);
pthread_create( &thread, &attr, &sendLinks, this);
}
}
}
}
}
MODULEDEFS(CUrlBufferModule, "Module that caches locally images/links posted on irc channels.")
|
@extends('layout.master')
@section('title','Administração')
@section('content')
@include('layout.topo')
<div class="row">
@include('layout.menu')
<div class="col-md-9">
<div class="row">
<div class="col-md-12">
<h1>Cadastro de Textos</h1>
</div>
</div>
<form action="{{Route('admin.gravaTexto')}}" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col-md-2"><span>Título</span></div>
<div class="col-md-10"><input type="text" id="titulo" name="titulo"></div>
</div>
<div class="row">
<div class="col-md-2"><span>Imagem</span></div>
<div class="col-md-10"><input type="file" id="imagem" name="imagem"></div>
</div>
<div class="row">
<div class="col-md-2"><span>Texto</span></div>
<div class="col-md-10">
<?php
$oFCKeditor = new FCKeditor('texto');
$oFCKeditor->BasePath = "/fckeditor/";
$oFCKeditor->Height = '300';
echo $oFCKeditor->CreateHtml();
?>
</div>
</div>
<div class="row">
<div class="col-md-12"><button type="submit" class="btn btn-default">Enviar</button><a href="{{Route('admin.textos')}}" class="btn btn-danger">Cancelar</a></div>
</div>
</form>
</div>
</div>
@include('layout.rodape')
@stop
|
from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def <API key>():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST:
connection = Connection.paired(
left=(settings.MONGODB_HOST, settings.MONGODB_PORT),
right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT)
)
else:
connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT)
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
'params': params
})
class Event(models.Model):
"Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField()
|
#include "ash/display/display_controller.h"
#include <algorithm>
#include "ash/ash_switches.h"
#include "ash/display/display_manager.h"
#include "ash/<API key>.h"
#include "ash/screen_ash.h"
#include "ash/shell.h"
#include "ash/wm/<API key>.h"
#include "ash/wm/property_util.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "base/json/<API key>.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "ui/aura/client/<API key>.h"
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/compositor/dip_util.h"
#include "ui/gfx/display.h"
#include "ui/gfx/screen.h"
#if defined(OS_CHROMEOS)
#include "ash/display/<API key>.h"
#include "base/chromeos/chromeos_version.h"
#include "base/<API key>.h"
#include "base/time.h"
#include "chromeos/display/output_configurator.h"
#include "ui/base/x/x11_util.h"
#endif // defined(OS_CHROMEOS)
namespace ash {
namespace {
// Primary display stored in global object as it can be
// accessed after Shell is deleted. A separate display instance is created
// during the shutdown instead of always keeping two display instances
// (one here and another one in display_manager) in sync, which is error prone.
int64 primary_display_id = gfx::Display::kInvalidDisplayID;
gfx::Display* <API key> = NULL;
// Keeps the number of displays during the shutdown after
// ash::Shell:: is deleted.
int <API key> = -1;
// The maximum value for 'offset' in DisplayLayout in case of outliers. Need
// to change this value in case to support even larger displays.
const int kMaxValidOffset = 10000;
// The number of pixels to overlap between the primary and secondary displays,
// in case that the offset value is too large.
const int <API key> = 100;
// Specifies how long the display change should have been disabled
// after each display change operations.
// |<API key>| is set to be longer to avoid
// changing the settings while the system is still configurating
// displays. It will be overriden by |<API key>|
// when the display change happens, so the actual timeout is much shorter.
const int64 <API key> = 500;
const int64 <API key> = 4000;
const int64 <API key> = 500;
bool <API key>(const base::StringPiece& position,
DisplayLayout::Position* field) {
if (position == "top") {
*field = DisplayLayout::TOP;
return true;
} else if (position == "bottom") {
*field = DisplayLayout::BOTTOM;
return true;
} else if (position == "right") {
*field = DisplayLayout::RIGHT;
return true;
} else if (position == "left") {
*field = DisplayLayout::LEFT;
return true;
}
LOG(ERROR) << "Invalid position value: " << position;
return false;
}
std::string <API key>(DisplayLayout::Position position) {
switch (position) {
case DisplayLayout::TOP:
return std::string("top");
case DisplayLayout::BOTTOM:
return std::string("bottom");
case DisplayLayout::RIGHT:
return std::string("right");
case DisplayLayout::LEFT:
return std::string("left");
}
return std::string("unknown");
}
internal::DisplayManager* GetDisplayManager() {
return Shell::GetInstance()->display_manager();
}
void <API key>(aura::RootWindow* root,
const gfx::Display& display) {
#if defined(OS_CHROMEOS)
// Native window property (Atom in X11) that specifies the display's
// rotation and scale factor. They are read and used by
// touchpad/mouse driver directly on X (contact adlr@ for more
// details on touchpad/mouse driver side). The value of the rotation
// is one of 0 (normal), 1 (90 degrees clockwise), 2 (180 degree) or
// 3 (270 degrees clockwise). The value of the scale factor is in
// percent (100, 140, 200 etc).
const char kRotationProp[] = "<API key>";
const char kScaleFactorProp[] = "<API key>";
const char kCARDINAL[] = "CARDINAL";
CommandLine* command_line = CommandLine::ForCurrentProcess();
int rotation = 0;
if (command_line->HasSwitch(switches::<API key>)) {
std::string value = command_line->
GetSwitchValueASCII(switches::<API key>);
DCHECK(base::StringToInt(value, &rotation));
DCHECK(0 <= rotation && rotation <= 3) << "Invalid rotation value="
<< rotation;
if (rotation < 0 || rotation > 3)
rotation = 0;
}
gfx::AcceleratedWidget xwindow = root-><API key>();
ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, rotation);
ui::SetIntProperty(xwindow,
kScaleFactorProp,
kCARDINAL,
100 * display.device_scale_factor());
#endif
}
} // namespace
// DisplayLayout
DisplayLayout::DisplayLayout()
: position(RIGHT),
offset(0) {}
DisplayLayout::DisplayLayout(DisplayLayout::Position position, int offset)
: position(position),
offset(offset) {
DCHECK_LE(TOP, position);
DCHECK_GE(LEFT, position);
// Set the default value to |position| in case position is invalid. DCHECKs
// above doesn't stop in Release builds.
if (TOP > position || LEFT < position)
this->position = RIGHT;
DCHECK_GE(kMaxValidOffset, abs(offset));
}
DisplayLayout DisplayLayout::Invert() const {
Position inverted_position = RIGHT;
switch (position) {
case TOP:
inverted_position = BOTTOM;
break;
case BOTTOM:
inverted_position = TOP;
break;
case RIGHT:
inverted_position = LEFT;
break;
case LEFT:
inverted_position = RIGHT;
break;
}
return DisplayLayout(inverted_position, -offset);
}
// static
bool DisplayLayout::ConvertFromValue(const base::Value& value,
DisplayLayout* layout) {
base::JSONValueConverter<DisplayLayout> converter;
return converter.Convert(value, layout);
}
// static
bool DisplayLayout::ConvertToValue(const DisplayLayout& layout,
base::Value* value) {
base::DictionaryValue* dict_value = NULL;
if (!value->GetAsDictionary(&dict_value) || dict_value == NULL)
return false;
const std::string position_str = <API key>(layout.position);
dict_value->SetString("position", position_str);
dict_value->SetInteger("offset", layout.offset);
return true;
}
std::string DisplayLayout::ToString() const {
const std::string position_str = <API key>(position);
return StringPrintf("%s, %d", position_str.c_str(), offset);
}
// static
void DisplayLayout::<API key>(
base::JSONValueConverter<DisplayLayout>* converter) {
converter->RegisterCustomField<Position>(
"position", &DisplayLayout::position, &<API key>);
converter->RegisterIntField("offset", &DisplayLayout::offset);
}
// <API key>
DisplayController::<API key>::<API key>()
: throttle_timeout_(base::Time::Now()) {
}
void DisplayController::<API key>::SetThrottleTimeout(
int64 throttle_ms) {
throttle_timeout_ =
base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
}
bool DisplayController::<API key>::IsThrottled() const {
return base::Time::Now() < throttle_timeout_;
}
// DisplayController
DisplayController::DisplayController()
: <API key>(gfx::Display::kInvalidDisplayID),
<API key>(NULL) {
#if defined(OS_CHROMEOS)
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::<API key>) &&
base::chromeos::IsRunningOnChromeOS())
limiter_.reset(new <API key>);
#endif
// Reset primary display to make sure that tests don't use
// stale display info from previous tests.
primary_display_id = gfx::Display::kInvalidDisplayID;
delete <API key>;
<API key> = NULL;
<API key> = -1;
Shell::GetScreen()->AddObserver(this);
}
DisplayController::~DisplayController() {
DCHECK(<API key>);
}
void DisplayController::Shutdown() {
DCHECK(!<API key>);
<API key> = new gfx::Display(
GetDisplayManager()->GetDisplayForId(primary_display_id));
<API key> = GetDisplayManager()->GetNumDisplays();
Shell::GetScreen()->RemoveObserver(this);
// Delete all root window controllers, which deletes root window
// from the last so that the primary root window gets deleted last.
for (std::map<int64, aura::RootWindow*>::<API key> it =
root_windows_.rbegin(); it != root_windows_.rend(); ++it) {
internal::<API key>* controller =
<API key>(it->second);
DCHECK(controller);
delete controller;
}
}
// static
const gfx::Display& DisplayController::GetPrimaryDisplay() {
DCHECK_NE(primary_display_id, gfx::Display::kInvalidDisplayID);
if (<API key>)
return *<API key>;
return GetDisplayManager()->GetDisplayForId(primary_display_id);
}
// static
int DisplayController::GetNumDisplays() {
if (<API key> >= 0)
return <API key>;
return GetDisplayManager()->GetNumDisplays();
}
// static
bool DisplayController::HasPrimaryDisplay() {
return primary_display_id != gfx::Display::kInvalidDisplayID;
}
void DisplayController::InitPrimaryDisplay() {
const gfx::Display* primary_candidate = GetDisplayManager()->GetDisplayAt(0);
#if defined(OS_CHROMEOS)
if (base::chromeos::IsRunningOnChromeOS()) {
internal::DisplayManager* display_manager = GetDisplayManager();
// On ChromeOS device, root windows are stacked vertically, and
// default primary is the one on top.
int count = display_manager->GetNumDisplays();
int y = primary_candidate->bounds_in_pixel().y();
for (int i = 1; i < count; ++i) {
const gfx::Display* display = display_manager->GetDisplayAt(i);
if (display->IsInternal()) {
primary_candidate = display;
break;
} else if (display->bounds_in_pixel().y() < y) {
primary_candidate = display;
y = display->bounds_in_pixel().y();
}
}
}
#endif
primary_display_id = primary_candidate->id();
<API key>(*primary_candidate);
<API key>();
}
void DisplayController::<API key>() {
internal::DisplayManager* display_manager = GetDisplayManager();
for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
const gfx::Display* display = display_manager->GetDisplayAt(i);
if (primary_display_id != display->id()) {
aura::RootWindow* root = <API key>(*display);
Shell::GetInstance()-><API key>(root);
}
}
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::<API key>)) {
std::string value = command_line->GetSwitchValueASCII(
switches::<API key>);
char layout;
int offset;
if (sscanf(value.c_str(), "%c,%d", &layout, &offset) == 2) {
if (layout == 't')
<API key>.position = DisplayLayout::TOP;
else if (layout == 'b')
<API key>.position = DisplayLayout::BOTTOM;
else if (layout == 'r')
<API key>.position = DisplayLayout::RIGHT;
else if (layout == 'l')
<API key>.position = DisplayLayout::LEFT;
<API key>.offset = offset;
}
}
<API key>();
}
void DisplayController::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void DisplayController::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
aura::RootWindow* DisplayController::<API key>() {
DCHECK(!root_windows_.empty());
return root_windows_[primary_display_id];
}
aura::RootWindow* DisplayController::<API key>(int64 id) {
return root_windows_[id];
}
void DisplayController::CloseChildWindows() {
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
aura::RootWindow* root_window = it->second;
internal::<API key>* controller =
<API key>(root_window);
if (controller) {
controller->CloseChildWindows();
} else {
while (!root_window->children().empty()) {
aura::Window* child = root_window->children()[0];
delete child;
}
}
}
}
std::vector<aura::RootWindow*> DisplayController::GetAllRootWindows() {
std::vector<aura::RootWindow*> windows;
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
DCHECK(it->second);
if (<API key>(it->second))
windows.push_back(it->second);
}
return windows;
}
gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
return GetDisplayManager()->GetOverscanInsets(display_id);
}
void DisplayController::SetOverscanInsets(int64 display_id,
const gfx::Insets& insets_in_dip) {
GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
}
std::vector<internal::<API key>*>
DisplayController::<API key>() {
std::vector<internal::<API key>*> controllers;
for (std::map<int64, aura::RootWindow*>::const_iterator it =
root_windows_.begin(); it != root_windows_.end(); ++it) {
internal::<API key>* controller =
<API key>(it->second);
if (controller)
controllers.push_back(controller);
}
return controllers;
}
void DisplayController::<API key>(const DisplayLayout& layout) {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::<API key>) &&
(<API key>.position != layout.position ||
<API key>.offset != layout.offset)) {
<API key> = layout;
<API key>();
<API key>();
}
}
void DisplayController::<API key>(int64 id,
const DisplayLayout& layout) {
DisplayLayout& display_for_id = secondary_layouts_[id];
if (display_for_id.position != layout.position ||
display_for_id.offset != layout.offset) {
secondary_layouts_[id] = layout;
<API key>();
<API key>();
}
}
const DisplayLayout& DisplayController::GetLayoutForDisplay(
const gfx::Display& display) const {
std::map<int64, DisplayLayout>::const_iterator it =
secondary_layouts_.find(display.id());
if (it != secondary_layouts_.end())
return it->second;
return <API key>;
}
const DisplayLayout& DisplayController::<API key>() const {
DCHECK_EQ(2U, GetDisplayManager()->GetNumDisplays());
if (GetDisplayManager()->GetNumDisplays() > 1) {
DisplayController* non_const = const_cast<DisplayController*>(this);
return GetLayoutForDisplay(*(non_const->GetSecondaryDisplay()));
}
// On release build, just fallback to default instead of blowing up.
return <API key>;
}
void DisplayController::CycleDisplayMode() {
if (limiter_.get()) {
if (limiter_->IsThrottled())
return;
limiter_->SetThrottleTimeout(<API key>);
}
#if defined(OS_CHROMEOS)
Shell* shell = Shell::GetInstance();
if (!base::chromeos::IsRunningOnChromeOS()) {
internal::DisplayManager::CycleDisplay();
} else if (shell->output_configurator()-><API key>() > 1) {
internal::<API key>* animation =
shell-><API key>();
animation-><API key>(base::Bind(
base::IgnoreResult(&chromeos::OutputConfigurator::CycleDisplayMode),
base::Unretained(shell->output_configurator())));
}
#endif
}
void DisplayController::SwapPrimaryDisplay() {
if (limiter_.get()) {
if (limiter_->IsThrottled())
return;
limiter_->SetThrottleTimeout(<API key>);
}
if (Shell::GetScreen()->GetNumDisplays() > 1)
SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
}
void DisplayController::SetPrimaryDisplayId(int64 id) {
<API key> = id;
if (<API key> == primary_display_id)
return;
internal::DisplayManager* display_manager = GetDisplayManager();
for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
gfx::Display* display = display_manager->GetDisplayAt(i);
if (display->id() == id) {
SetPrimaryDisplay(*display);
break;
}
}
}
void DisplayController::SetPrimaryDisplay(
const gfx::Display& new_primary_display) {
internal::DisplayManager* display_manager = GetDisplayManager();
DCHECK(new_primary_display.is_valid());
DCHECK(display_manager->IsActiveDisplay(new_primary_display));
if (!new_primary_display.is_valid() ||
!display_manager->IsActiveDisplay(new_primary_display)) {
LOG(ERROR) << "Invalid or non-existent display is requested:"
<< new_primary_display.ToString();
return;
}
if (primary_display_id == new_primary_display.id() ||
root_windows_.size() < 2) {
return;
}
aura::RootWindow* non_primary_root = root_windows_[new_primary_display.id()];
LOG_IF(ERROR, !non_primary_root)
<< "Unknown display is requested in SetPrimaryDisplay: id="
<< new_primary_display.id();
if (!non_primary_root)
return;
gfx::Display old_primary_display = GetPrimaryDisplay();
// Swap root windows between current and new primary display.
aura::RootWindow* primary_root = root_windows_[primary_display_id];
DCHECK(primary_root);
DCHECK_NE(primary_root, non_primary_root);
root_windows_[new_primary_display.id()] = primary_root;
primary_root->SetProperty(internal::kDisplayIdKey, new_primary_display.id());
root_windows_[old_primary_display.id()] = non_primary_root;
non_primary_root->SetProperty(internal::kDisplayIdKey,
old_primary_display.id());
primary_display_id = new_primary_display.id();
<API key> = primary_display_id;
display_manager-><API key>(
primary_root, old_primary_display.GetWorkAreaInsets());
display_manager-><API key>(
non_primary_root, new_primary_display.GetWorkAreaInsets());
// Update the layout.
<API key>(old_primary_display.id(),
GetLayoutForDisplay(new_primary_display).Invert());
// Update the dispay manager with new display info.
std::vector<gfx::Display> displays;
displays.push_back(display_manager->GetDisplayForId(primary_display_id));
displays.push_back(*GetSecondaryDisplay());
GetDisplayManager()-><API key>(true);
GetDisplayManager()->UpdateDisplays(displays);
GetDisplayManager()-><API key>(false);
}
gfx::Display* DisplayController::GetSecondaryDisplay() {
internal::DisplayManager* display_manager = GetDisplayManager();
CHECK_EQ(2U, display_manager->GetNumDisplays());
return display_manager->GetDisplayAt(0)->id() == primary_display_id ?
display_manager->GetDisplayAt(1) : display_manager->GetDisplayAt(0);
}
void DisplayController::<API key>(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(<API key>);
<API key>();
<API key>();
aura::RootWindow* root = root_windows_[display.id()];
<API key>(root, display);
root->SetHostBounds(display.bounds_in_pixel());
}
void DisplayController::OnDisplayAdded(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(<API key>);
<API key>();
if (<API key>) {
DCHECK(root_windows_.empty());
primary_display_id = display.id();
root_windows_[display.id()] = <API key>;
<API key>->SetProperty(
internal::kDisplayIdKey, display.id());
<API key> = NULL;
<API key>();
root_windows_[display.id()]->SetHostBounds(display.bounds_in_pixel());
} else {
DCHECK(!root_windows_.empty());
aura::RootWindow* root = <API key>(display);
<API key>();
if (<API key> == display.id())
SetPrimaryDisplay(display);
Shell::GetInstance()-><API key>(root);
}
}
void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
if (limiter_.get())
limiter_->SetThrottleTimeout(<API key>);
aura::RootWindow* root_to_delete = root_windows_[display.id()];
DCHECK(root_to_delete) << display.ToString();
<API key>();
// Display for root window will be deleted when the Primary RootWindow
// is deleted by the Shell.
root_windows_.erase(display.id());
// When the primary root window's display is removed, move the primary
// root to the other display.
if (primary_display_id == display.id()) {
// Temporarily store the primary root window in
// |<API key>| when replacing the display.
if (root_windows_.size() == 0) {
primary_display_id = gfx::Display::kInvalidDisplayID;
<API key> = root_to_delete;
return;
}
DCHECK_EQ(1U, root_windows_.size());
primary_display_id = GetSecondaryDisplay()->id();
aura::RootWindow* primary_root = root_to_delete;
// Delete the other root instead.
root_to_delete = root_windows_[primary_display_id];
root_to_delete->SetProperty(internal::kDisplayIdKey, display.id());
// Setup primary root.
root_windows_[primary_display_id] = primary_root;
primary_root->SetProperty(internal::kDisplayIdKey, primary_display_id);
<API key>(
GetDisplayManager()->GetDisplayForId(primary_display_id));
}
internal::<API key>* controller =
<API key>(root_to_delete);
DCHECK(controller);
controller->MoveWindowsTo(<API key>());
// Delete most of root window related objects, but don't delete
// root window itself yet because the stack may be using it.
controller->Shutdown();
MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
}
aura::RootWindow* DisplayController::<API key>(
const gfx::Display& display) {
aura::RootWindow* root =
GetDisplayManager()-><API key>(display);
root_windows_[display.id()] = root;
<API key>(root, display);
#if defined(OS_CHROMEOS)
static bool <API key> =
CommandLine::ForCurrentProcess()->HasSwitch(
switches::<API key>);
if (base::chromeos::IsRunningOnChromeOS() || <API key>)
root-><API key>();
#endif
return root;
}
void DisplayController::<API key>() {
if (Shell::GetScreen()->GetNumDisplays() <= 1)
return;
DCHECK_EQ(2, Shell::GetScreen()->GetNumDisplays());
const gfx::Rect& primary_bounds = GetPrimaryDisplay().bounds();
gfx::Display* secondary_display = GetSecondaryDisplay();
const gfx::Rect& secondary_bounds = secondary_display->bounds();
gfx::Point <API key> = primary_bounds.origin();
const DisplayLayout& layout = GetLayoutForDisplay(*secondary_display);
DisplayLayout::Position position = layout.position;
// Ignore the offset in case the secondary display doesn't share edges with
// the primary display.
int offset = layout.offset;
if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
offset = std::min(
offset, primary_bounds.width() - <API key>);
offset = std::max(
offset, -secondary_bounds.width() + <API key>);
} else {
offset = std::min(
offset, primary_bounds.height() - <API key>);
offset = std::max(
offset, -secondary_bounds.height() + <API key>);
}
switch (position) {
case DisplayLayout::TOP:
<API key>.Offset(offset, -secondary_bounds.height());
break;
case DisplayLayout::RIGHT:
<API key>.Offset(primary_bounds.width(), offset);
break;
case DisplayLayout::BOTTOM:
<API key>.Offset(offset, primary_bounds.height());
break;
case DisplayLayout::LEFT:
<API key>.Offset(-secondary_bounds.width(), offset);
break;
}
gfx::Insets insets = secondary_display->GetWorkAreaInsets();
secondary_display->set_bounds(
gfx::Rect(<API key>, secondary_bounds.size()));
secondary_display-><API key>(insets);
}
void DisplayController::<API key>() {
FOR_EACH_OBSERVER(Observer, observers_, <API key>());
}
} // namespace ash
|
package gov.nih.nci.caintegrator.web.action.study.management;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caintegrator.application.study.LogEntry;
import gov.nih.nci.caintegrator.application.study.StudyConfiguration;
import gov.nih.nci.caintegrator.application.study.<API key>;
import gov.nih.nci.caintegrator.web.action.<API key>;
import gov.nih.nci.caintegrator.web.action.study.management.EditStudyLogAction;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.Action;
public class <API key> extends <API key> {
private EditStudyLogAction action = new EditStudyLogAction();
private <API key> <API key>;
private LogEntry logEntry1;
private LogEntry logEntry2;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
action.<API key>(new StudyConfiguration());
action = new EditStudyLogAction();
<API key> = new <API key>();
action.<API key>(<API key>);
action.setWorkspaceService(workspaceService);
logEntry1 = new LogEntry();
logEntry1.<API key>("message");
logEntry1.setLogDate(new Date());
logEntry1.setTrimDescription("desc");
try {
Thread.sleep(20l);
} catch (<API key> e) {
}
logEntry2 = new LogEntry();
logEntry2.setSystemLogMessage("message2");
logEntry2.setLogDate(new Date());
logEntry2.setDescription("desc");
action.<API key>().getLogEntries().add(logEntry1);
action.<API key>().getLogEntries().add(logEntry2);
}
@Test
public void testPrepare() throws <API key> {
action.prepare();
// Verify the most recent ones are sorted first.
assertEquals(logEntry2, action.<API key>().get(0).getLogEntry());
assertEquals(logEntry1, action.<API key>().get(1).getLogEntry());
assertTrue(<API key>.<API key>);
}
@Test
public void testSave() {
action.prepare();
// logEntry2 is first
action.<API key>().get(0).setDescription("new");
action.<API key>().get(0).<API key>(true);
// logEntry1 will have a new description, but the checkbox will be false.
action.<API key>().get(1).setDescription("new");
action.<API key>().get(1).<API key>(false);
assertEquals(Action.SUCCESS, action.save());
assertEquals("new", logEntry2.getDescription());
assertEquals("desc", logEntry1.getDescription());
assertTrue(<API key>.saveCalled);
}
@Test
public void <API key>() {
assertTrue(action.<API key>(null));
assertTrue(action.<API key>("ABC"));
assertFalse(action.<API key>("123"));
assertFalse(action.<API key>("d-123-e"));
}
}
|
# AWS SDK for JavaScript
[. Prior to v2.4.8, release notes can be found at http://aws.amazon.com/releasenotes/SDK/JavaScript
<p class="note">
If you are upgrading from 1.x to 2.0 of the SDK, please see
the {file:UPGRADING.md} notes for information on how to migrate existing code
to work with the new major version.
</p>
## Installing
In the Browser
To use the SDK in the browser, simply add the following script tag to your
HTML pages:
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.7.min.js"></script>
You can also build a custom browser SDK with your specified set of AWS services.
This can allow you to reduce the SDK's size, specify different API versions of
services, or use AWS services that don't currently support CORS if you are
working in an environment that does not enforce CORS. To get started:
http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/<API key>.html
The AWS SDK is also compatible with [browserify](http://browserify.org).
In Node.js
The preferred way to install the AWS SDK for Node.js is to use the
[npm](http://npmjs.org) package manager for Node.js. Simply type the following
into a terminal window:
sh
npm install aws-sdk
Using Bower
You can also use [Bower](http://bower.io) to install the SDK by typing the
following into a terminal window:
sh
bower install aws-sdk-js
## Usage and Getting Started
You can find a getting started guide at:
http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide
## Usage with TypeScript
The AWS SDK for JavaScript bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.
Our goal is to keep these TypeScript definition files updated with each release for any public api.
Pre-requisites
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
* Use TypeScript v2.x
* Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
sh
npm install --save-dev @types/node
* Your `tsconfig.json` or `jsconfig.json` includes `'dom'` and `'es2015.promise'` under `compilerOptions.lib`.
See [tsconfig.json](./ts/tsconfig.json) for an example.
In the Browser
To use the TypeScript definition files with the global `AWS` object in a front-end project, add the following line to the top of your JavaScript file:
javascript
<reference types="aws-sdk" />
This will provide support for the global `AWS` object.
In Node.js
To use the TypeScript definition files within a Node.js project, simply import `aws-sdk` as you normally would.
In a TypeScript file:
javascript
// import entire SDK
import AWS = require('aws-sdk');
// import AWS object without services
import AWS = require('aws-sdk/global');
// import individual service
import S3 = require('aws-sdk/clients/s3');
In a JavaScript file:
javascript
// import entire SDK
var AWS = require('aws-sdk');
// import AWS object without services
var AWS = require('aws-sdk/global');
// import individual service
var S3 = require('aws-sdk/clients/s3');
Known Limitations
There are a few known limitations with the bundled TypeScript definitions at this time:
* Service client typings reflect the latest `apiVersion`, regardless of which `apiVersion` is specified when creating a client.
* Service-bound parameters use the `any` type.
## Supported Services
<p class="note"><strong>Note</strong>:
Although all services are supported in the browser version of the SDK,
not all of the services are available in the default hosted build (using the
script tag provided above). Instructions on how to build a
custom version of the SDK with individual services are provided
in the "<a href="http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/<API key>.html">Building the SDK for Browsers</a>" section of the SDK Developer Guide.
</p>
The SDK currently supports the following services:
<table>
<thead>
<th>Service Name</th>
<th>Class Name</th>
<th>API Version</th>
</thead>
<tbody>
<tr><td>Amazon API Gateway</td><td>AWS.APIGateway</td><td>2015-07-09</td></tr>
<tr><td>Amazon CloudFront</td><td>AWS.CloudFront</td><td>2014-10-21</td></tr>
<tr><td>Amazon CloudHSM</td><td>AWS.CloudHSM</td><td>2014-05-30</td></tr>
<tr><td>Amazon CloudSearch</td><td>AWS.CloudSearch</td><td>2013-01-01</td></tr>
<tr><td>Amazon CloudSearch Domain</td><td>AWS.CloudSearchDomain</td><td>2013-01-01</td></tr>
<tr><td>Amazon CloudWatch</td><td>AWS.CloudWatch</td><td>2010-08-01</td></tr>
<tr><td>Amazon CloudWatch Events</td><td>AWS.CloudWatchLogs</td><td>2015-10-07</td></tr>
<tr><td>Amazon CloudWatch Logs</td><td>AWS.CloudWatchLogs</td><td>2014-03-28</td></tr>
<tr><td>Amazon Cognito Identity</td><td>AWS.CognitoIdentity</td><td>2014-06-30</td></tr>
<tr><td>Amazon Cognito Sync</td><td>AWS.CognitoSync</td><td>2014-06-30</td></tr>
<tr><td>Amazon DynamoDB</td><td>AWS.DynamoDB</td><td>2012-08-10</td></tr>
<tr><td>Amazon DynamoDB Streams</td><td>AWS.DynamoDBStreams</td><td>2012-08-10</td></tr>
<tr><td>Amazon EC2 Container Registry</td><td>AWS.ECR</td><td>2015-09-21</td></tr>
<tr><td>Amazon EC2 Container Service</td><td>AWS.ECS</td><td>2014-11-13</td></tr>
<tr><td>Amazon Elastic Compute Cloud</td><td>AWS.EC2</td><td>2014-10-01</td></tr>
<tr><td>Amazon Elastic File System</td><td>AWS.EFS</td><td>2015-02-01</td></tr>
<tr><td>Amazon Elastic MapReduce</td><td>AWS.EMR</td><td>2009-03-31</td></tr>
<tr><td>Amazon Elastic Transcoder</td><td>AWS.ElasticTranscoder</td><td>2012-09-25</td></tr>
<tr><td>Amazon ElastiCache</td><td>AWS.ElastiCache</td><td>2014-09-30</td></tr>
<tr><td>Amazon Elasticsearch Service</td><td>AWS.ES</td><td>2015-01-01</td></tr>
<tr><td>Amazon GameLift</td><td>AWS.GameLift</td><td>2015-10-01</td></tr>
<tr><td>Amazon Glacier</td><td>AWS.Glacier</td><td>2012-06-01</td></tr>
<tr><td>Amazon Inspector</td><td>AWS.Inspector</td><td>2016-02-16</td></tr>
<tr><td>Amazon Kinesis</td><td>AWS.Kinesis</td><td>2013-12-02</td></tr>
<tr><td>Amazon Kinesis Analytics</td><td>AWS.KinesisAnalytics</td><td>2015-08-14</td></tr>
<tr><td>Amazon Kinesis Firehose</td><td>AWS.Firehose</td><td>2015-08-04</td></tr>
<tr><td>Amazon Machine Learning</td><td>AWS.MachineLearning</td><td>2014-12-12</td></tr>
<tr><td>Amazon Mobile Analytics</td><td>AWS.MobileAnalytics</td><td>2014-06-05</td></tr>
<tr><td>Amazon Redshift</td><td>AWS.Redshift</td><td>2012-12-01</td></tr>
<tr><td>Amazon Relational Database Service</td><td>AWS.RDS</td><td>2014-09-01</td></tr>
<tr><td>Amazon Route 53</td><td>AWS.Route53</td><td>2013-04-01</td></tr>
<tr><td>Amazon Route 53 Domains</td><td>AWS.Route53Domains</td><td>2014-05-15</td></tr>
<tr><td>Amazon Simple Email Service</td><td>AWS.SES</td><td>2010-12-01</td></tr>
<tr><td>Amazon Simple Notification Service</td><td>AWS.SNS</td><td>2010-03-31</td></tr>
<tr><td>Amazon Simple Queue Service</td><td>AWS.SQS</td><td>2012-11-05</td></tr>
<tr><td>Amazon Simple Storage Service</td><td>AWS.S3</td><td>2006-03-01</td></tr>
<tr><td>Amazon Simple Systems Management Service</td><td>AWS.SSM</td><td>2014-11-06</td></tr>
<tr><td>Amazon Simple Workflow Service</td><td>AWS.SWF</td><td>2012-01-25</td></tr>
<tr><td>Amazon SimpleDB</td><td>AWS.SimpleDB</td><td>2009-04-15</td></tr>
<tr><td>Amazon Snowball</td><td>AWS.Snowball</td><td>2016-06-30</td></tr>
<tr><td>Amazon WorkSpaces</td><td>AWS.WorkSpaces</td><td>2015-04-08</td></tr>
<tr><td>Auto Scaling</td><td>AWS.AutoScaling</td><td>2011-01-01</td></tr>
<tr><td>AWS Certificate Manager</td><td>AWS.ACM</td><td>2015-12-08</td></tr>
<tr><td>AWS CloudFormation</td><td>AWS.CloudFormation</td><td>2010-05-15</td></tr>
<tr><td>AWS CloudTrail</td><td>AWS.CloudTrail</td><td>2013-11-01</td></tr>
<tr><td>AWS CodeCommit</td><td>AWS.CodeCommit</td><td>2015-04-13</td></tr>
<tr><td>AWS CodeDeploy</td><td>AWS.CodeDeploy</td><td>2014-10-06</td></tr>
<tr><td>AWS CodePipeline</td><td>AWS.CodePipeline</td><td>2015-07-09</td></tr>
<tr><td>AWS Config</td><td>AWS.ConfigService</td><td>2014-11-12</td></tr>
<tr><td>AWS Data Pipeline</td><td>AWS.DataPipeline</td><td>2012-10-29</td></tr>
<tr><td>AWS Database Migration Service</td><td>AWS.DMS</td><td>2016-01-01</td></tr>
<tr><td>AWS Device Farm</td><td>AWS.DeviceFarm</td><td>2015-06-23</td></tr>
<tr><td>AWS Direct Connect</td><td>AWS.DirectConnect</td><td>2012-10-25</td></tr>
<tr><td>AWS Directory Service</td><td>AWS.DirectoryService</td><td>2015-04-16</td></tr>
<tr><td>AWS Elastic Beanstalk</td><td>AWS.ElasticBeanstalk</td><td>2010-12-01</td></tr>
<tr><td>AWS Identity and Access Management</td><td>AWS.IAM</td><td>2010-05-08</td></tr>
<tr><td>AWS Import/Export</td><td>AWS.ImportExport</td><td>2010-06-01</td></tr>
<tr><td>AWS IoT</td><td>AWS.Iot</td><td>2015-05-28</td></tr>
<tr><td>AWS IoT Data Plane</td><td>AWS.IotData</td><td>2015-05-28</td></tr>
<tr><td>AWS Key Management Service</td><td>AWS.KMS</td><td>2014-11-01</td></tr>
<tr><td>AWS Lambda</td><td>AWS.Lambda</td><td>2015-03-31</td></tr>
<tr><td>AWS Marketplace Commerce Analytics</td><td>AWS.<API key></td><td>2015-07-01</td></tr>
<tr><td>AWS Marketplace Metering</td><td>AWS.MarketplaceMetering</td><td>2016-01-14</td></tr>
<tr><td>AWS OpsWorks</td><td>AWS.OpsWorks</td><td>2013-02-18</td></tr>
<tr><td>AWS Security Token Service</td><td>AWS.STS</td><td>2011-06-15</td></tr>
<tr><td>AWS Storage Gateway</td><td>AWS.StorageGateway</td><td>2013-06-30</td></tr>
<tr><td>AWS Support</td><td>AWS.Support</td><td>2013-04-15</td></tr>
<tr><td>AWS WAF</td><td>AWS.WAF</td><td>2015-08-24</td></tr>
<tr><td>Elastic Load Balancing</td><td>AWS.ELB</td><td>2012-06-01</td></tr>
<tr><td>Elastic Load Balancing v2</td><td>AWS.ELBv2</td><td>2015-12-01</td></tr>
</tbody>
</table>
This SDK is distributed under the
[Apache License, Version 2.0](http:
see LICENSE.txt and NOTICE.txt for more information.
|
# encoding: utf-8
import sys
sys.path.append(sys.path.insert(0,"../src"))
def urlopen(*args, **kwargs):
# Only parse one arg: the url
return Urls[args[0]]
# Provide a simple hashtable to contain the content of the urls and
# provide a mock object similar to what will be returned from the
# real urlopen() function calls
from io import StringIO
from time import time
import re
from nose.tools import with_setup
class MockUrlContent(StringIO):
def __init__(self, content):
super(MockUrlContent, self).__init__(content)
self.headers = {
'last-modified': time()
}
def close(self):
pass
scheme_re = re.compile(r'file:(/+)?')
class MockUrlCache(dict):
def __setitem__(self, name, content):
super(MockUrlCache, self).__setitem__(name, MockUrlContent(content))
def __getitem__(self, name):
if name in self:
return super(MockUrlCache, self).__getitem__(name)
# Strip off 'file:[///]' from url
elif name.startswith('file:'):
try:
name= scheme_re.sub('', name)
return super(MockUrlCache, self).__getitem__(name)
except:
# Fall through
pass
# urlopen raises ValueError if unable to load content (not KeyError)
raise ValueError("{0}: Cannot find file content".format(name))
Urls = MockUrlCache()
def clear_configs():
pass
@with_setup(clear_configs)
def testImportContent():
"Cannot import content from a file"
from xmlconfig import getConfig
Urls.clear()
Urls["file:file.txt"] = "Content embedded in a file"
Urls["config.xml"] = \
u"""<?xml version="1.0" encoding="utf-8"?>
<config>
<constants>
<string key="import" src="file:file.txt"/>
</constants>
</config>
"""
conf=getConfig()
conf.load("config.xml")
assert conf.get("import") == "Content embedded in a file"
@with_setup(clear_configs)
def testImportConfig():
"Cannot import another config file"
from xmlconfig import getConfig
Urls.clear()
Urls["config2.xml"] = \
"""<?xml version="1.0"?>
<config>
<constants>
<string key="key22">This was imported from config2.xml</string>
</constants>
</config>
"""
Urls["config.xml"] = \
u"""<?xml version="1.0" encoding="utf-8"?>
<config>
<constants namespace="import" src="file:config2.xml"/>
<constants>
<string key="imported">%(import:key22)</string>
</constants>
</config>
"""
conf=getConfig()
conf.load("config.xml")
assert conf.get("imported") == "This was imported from config2.xml"
@with_setup(clear_configs)
def testCircularImport():
"Property detect circluar importing"
from xmlconfig import getConfig
Urls.clear()
Urls["config2.xml"] = \
"""<?xml version="1.0"?>
<config>
<constants namespace="circular" src="file:config.xml"/>
<constants>
<string key="key22">This was imported from config2.xml</string>
<string key="foreign">
Namespace changed in %(circular:key4.import)
</string>
</constants>
</config>
"""
Urls["config.xml"] = \
"""<?xml version="1.0"?>
<config>
<constants namespace="import" src="file:config2.xml"/>
<constants>
<section key="key4">
<string key="key5">value2</string>
<string key="import">%(import:key22)</string>
</section>
</constants>
</config>
"""
conf=getConfig()
conf.load("config.xml")
assert conf.get("import:foreign") == \
"Namespace changed in This was imported from config2.xml"
@with_setup(clear_configs)
def testRelativeImport():
"""Transfer leading absolute or relative path to the location of
documents imported"""
from xmlconfig import getConfig
Urls["../config/config2.xml"] = \
"""<?xml version="1.0"?>
<config>
<constants>
<string key="key22">This was imported from config2.xml</string>
</constants>
</config>
"""
Urls["../config/config.xml"] = \
"""<?xml version="1.0" encoding="utf-8"?>
<config>
<constants namespace="import" src="file:config2.xml"/>
<constants>
<string key="imported">%(import:key22)</string>
</constants>
</config>
"""
conf=getConfig()
conf.load("../config/config.xml")
assert conf.get("imported") == "This was imported from config2.xml"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.