code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package zmq4 /* #include <zmq.h> #include <stdint.h> #include <stdlib.h> #include "zmq4.h" */ import "C" import ( "time" "unsafe" ) func (soc *Socket) setString(opt C.int, s string) error { if !soc.opened { return ErrorSocketClosed } cs := C.CString(s) defer C.free(unsafe.Pointer(cs)) var i C.int var err error for { i, err = C.zmq4_setsockopt(soc.soc, opt, unsafe.Pointer(cs), C.size_t(len(s))) if i == 0 || !soc.ctx.retry(err) { break } } if i != 0 { return errget(err) } return nil } func (soc *Socket) setNullString(opt C.int) error { if !soc.opened { return ErrorSocketClosed } var i C.int var err error for { i, err = C.zmq4_setsockopt(soc.soc, opt, nil, 0) if i == 0 || !soc.ctx.retry(err) { break } } if i != 0 { return errget(err) } return nil } func (soc *Socket) setInt(opt C.int, value int) error { if !soc.opened { return ErrorSocketClosed } val := C.int(value) var i C.int var err error for { i, err = C.zmq4_setsockopt(soc.soc, opt, unsafe.Pointer(&val), C.size_t(unsafe.Sizeof(val))) if i == 0 || !soc.ctx.retry(err) { break } } if i != 0 { return errget(err) } return nil } func (soc *Socket) setInt64(opt C.int, value int64) error { if !soc.opened { return ErrorSocketClosed } val := C.int64_t(value) var i C.int var err error for { i, err = C.zmq4_setsockopt(soc.soc, opt, unsafe.Pointer(&val), C.size_t(unsafe.Sizeof(val))) if i == 0 || !soc.ctx.retry(err) { break } } if i != 0 { return errget(err) } return nil } func (soc *Socket) setUInt64(opt C.int, value uint64) error { if !soc.opened { return ErrorSocketClosed } val := C.uint64_t(value) var i C.int var err error for { i, err = C.zmq4_setsockopt(soc.soc, opt, unsafe.Pointer(&val), C.size_t(unsafe.Sizeof(val))) if i == 0 || !soc.ctx.retry(err) { break } } if i != 0 { return errget(err) } return nil } // ZMQ_SNDHWM: Set high water mark for outbound messages // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc39 func (soc *Socket) SetSndhwm(value int) error { return soc.setInt(C.ZMQ_SNDHWM, value) } // ZMQ_RCVHWM: Set high water mark for inbound messages // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc28 func (soc *Socket) SetRcvhwm(value int) error { return soc.setInt(C.ZMQ_RCVHWM, value) } // ZMQ_AFFINITY: Set I/O thread affinity // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc3 func (soc *Socket) SetAffinity(value uint64) error { return soc.setUInt64(C.ZMQ_AFFINITY, value) } // ZMQ_SUBSCRIBE: Establish message filter // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc41 func (soc *Socket) SetSubscribe(filter string) error { return soc.setString(C.ZMQ_SUBSCRIBE, filter) } // ZMQ_UNSUBSCRIBE: Remove message filter // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc47 func (soc *Socket) SetUnsubscribe(filter string) error { return soc.setString(C.ZMQ_UNSUBSCRIBE, filter) } // ZMQ_IDENTITY: Set socket identity // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc16 func (soc *Socket) SetIdentity(value string) error { return soc.setString(C.ZMQ_IDENTITY, value) } // ZMQ_RATE: Set multicast data rate // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc26 func (soc *Socket) SetRate(value int) error { return soc.setInt(C.ZMQ_RATE, value) } // ZMQ_RECOVERY_IVL: Set multicast recovery interval // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc32 func (soc *Socket) SetRecoveryIvl(value time.Duration) error { val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_RECOVERY_IVL, val) } // ZMQ_SNDBUF: Set kernel transmit buffer size // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc38 func (soc *Socket) SetSndbuf(value int) error { return soc.setInt(C.ZMQ_SNDBUF, value) } // ZMQ_RCVBUF: Set kernel receive buffer size // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc27 func (soc *Socket) SetRcvbuf(value int) error { return soc.setInt(C.ZMQ_RCVBUF, value) } // ZMQ_LINGER: Set linger period for socket shutdown // // For infinite, use -1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc19 func (soc *Socket) SetLinger(value time.Duration) error { val := int(value / time.Millisecond) if value == -1 { val = -1 } return soc.setInt(C.ZMQ_LINGER, val) } // ZMQ_RECONNECT_IVL: Set reconnection interval // // For no reconnection, use -1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc30 func (soc *Socket) SetReconnectIvl(value time.Duration) error { val := int(value / time.Millisecond) if value == -1 { val = -1 } return soc.setInt(C.ZMQ_RECONNECT_IVL, val) } // ZMQ_RECONNECT_IVL_MAX: Set maximum reconnection interval // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc31 func (soc *Socket) SetReconnectIvlMax(value time.Duration) error { val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_RECONNECT_IVL_MAX, val) } // ZMQ_BACKLOG: Set maximum length of the queue of outstanding connections // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc4 func (soc *Socket) SetBacklog(value int) error { return soc.setInt(C.ZMQ_BACKLOG, value) } // ZMQ_MAXMSGSIZE: Maximum acceptable inbound message size // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc20 func (soc *Socket) SetMaxmsgsize(value int64) error { return soc.setInt64(C.ZMQ_MAXMSGSIZE, value) } // ZMQ_MULTICAST_HOPS: Maximum network hops for multicast packets // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc21 func (soc *Socket) SetMulticastHops(value int) error { return soc.setInt(C.ZMQ_MULTICAST_HOPS, value) } // ZMQ_RCVTIMEO: Maximum time before a recv operation returns with EAGAIN // // For infinite, use -1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc29 func (soc *Socket) SetRcvtimeo(value time.Duration) error { val := int(value / time.Millisecond) if value == -1 { val = -1 } return soc.setInt(C.ZMQ_RCVTIMEO, val) } // ZMQ_SNDTIMEO: Maximum time before a send operation returns with EAGAIN // // For infinite, use -1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc40 func (soc *Socket) SetSndtimeo(value time.Duration) error { val := int(value / time.Millisecond) if value == -1 { val = -1 } return soc.setInt(C.ZMQ_SNDTIMEO, val) } // ZMQ_IPV6: Enable IPv6 on socket // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc18 func (soc *Socket) SetIpv6(value bool) error { val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_IPV6, val) } // ZMQ_IMMEDIATE: Queue messages only to completed connections // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc17 func (soc *Socket) SetImmediate(value bool) error { val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_IMMEDIATE, val) } // ZMQ_ROUTER_MANDATORY: accept only routable messages on ROUTER sockets // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc36 func (soc *Socket) SetRouterMandatory(value int) error { return soc.setInt(C.ZMQ_ROUTER_MANDATORY, value) } // ZMQ_ROUTER_RAW: switch ROUTER socket to raw mode // // This option is deprecated since ZeroMQ version 4.1, please use ZMQ_STREAM sockets instead. // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc37 func (soc *Socket) SetRouterRaw(value int) error { return soc.setInt(C.ZMQ_ROUTER_RAW, value) } // ZMQ_PROBE_ROUTER: bootstrap connections to ROUTER sockets // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc25 func (soc *Socket) SetProbeRouter(value int) error { return soc.setInt(C.ZMQ_PROBE_ROUTER, value) } // ZMQ_XPUB_VERBOSE: provide all subscription messages on XPUB sockets // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc48 func (soc *Socket) SetXpubVerbose(value int) error { return soc.setInt(C.ZMQ_XPUB_VERBOSE, value) } // ZMQ_REQ_CORRELATE: match replies with requests // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc33 func (soc *Socket) SetReqCorrelate(value int) error { return soc.setInt(C.ZMQ_REQ_CORRELATE, value) } // ZMQ_REQ_RELAXED: relax strict alternation between request and reply // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc34 func (soc *Socket) SetReqRelaxed(value int) error { return soc.setInt(C.ZMQ_REQ_RELAXED, value) } // ZMQ_TCP_KEEPALIVE: Override SO_KEEPALIVE socket option // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc42 func (soc *Socket) SetTcpKeepalive(value int) error { return soc.setInt(C.ZMQ_TCP_KEEPALIVE, value) } // ZMQ_TCP_KEEPALIVE_IDLE: Override TCP_KEEPCNT(or TCP_KEEPALIVE on some OS) // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc44 func (soc *Socket) SetTcpKeepaliveIdle(value int) error { return soc.setInt(C.ZMQ_TCP_KEEPALIVE_IDLE, value) } // ZMQ_TCP_KEEPALIVE_CNT: Override TCP_KEEPCNT socket option // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc43 func (soc *Socket) SetTcpKeepaliveCnt(value int) error { return soc.setInt(C.ZMQ_TCP_KEEPALIVE_CNT, value) } // ZMQ_TCP_KEEPALIVE_INTVL: Override TCP_KEEPINTVL socket option // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc45 func (soc *Socket) SetTcpKeepaliveIntvl(value int) error { return soc.setInt(C.ZMQ_TCP_KEEPALIVE_INTVL, value) } // ZMQ_TCP_ACCEPT_FILTER: Assign filters to allow new TCP connections // // This option is deprecated since ZeroMQ version 4.1, please use authentication via // the ZAP API and IP address whitelisting / blacklisting. // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc50 func (soc *Socket) SetTcpAcceptFilter(filter string) error { if len(filter) == 0 { return soc.setNullString(C.ZMQ_TCP_ACCEPT_FILTER) } return soc.setString(C.ZMQ_TCP_ACCEPT_FILTER, filter) } // ZMQ_PLAIN_SERVER: Set PLAIN server role // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc23 func (soc *Socket) SetPlainServer(value int) error { return soc.setInt(C.ZMQ_PLAIN_SERVER, value) } // ZMQ_PLAIN_USERNAME: Set PLAIN security username // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc24 func (soc *Socket) SetPlainUsername(username string) error { if len(username) == 0 { return soc.setNullString(C.ZMQ_PLAIN_USERNAME) } return soc.setString(C.ZMQ_PLAIN_USERNAME, username) } // ZMQ_PLAIN_PASSWORD: Set PLAIN security password // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc22 func (soc *Socket) SetPlainPassword(password string) error { if len(password) == 0 { return soc.setNullString(C.ZMQ_PLAIN_PASSWORD) } return soc.setString(C.ZMQ_PLAIN_PASSWORD, password) } // ZMQ_CURVE_SERVER: Set CURVE server role // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc9 func (soc *Socket) SetCurveServer(value int) error { return soc.setInt(C.ZMQ_CURVE_SERVER, value) } // ZMQ_CURVE_PUBLICKEY: Set CURVE public key // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc7 func (soc *Socket) SetCurvePublickey(key string) error { return soc.setString(C.ZMQ_CURVE_PUBLICKEY, key) } // ZMQ_CURVE_SECRETKEY: Set CURVE secret key // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc8 func (soc *Socket) SetCurveSecretkey(key string) error { return soc.setString(C.ZMQ_CURVE_SECRETKEY, key) } // ZMQ_CURVE_SERVERKEY: Set CURVE server key // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc10 func (soc *Socket) SetCurveServerkey(key string) error { return soc.setString(C.ZMQ_CURVE_SERVERKEY, key) } // ZMQ_ZAP_DOMAIN: Set RFC 27 authentication domain // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc49 func (soc *Socket) SetZapDomain(domain string) error { return soc.setString(C.ZMQ_ZAP_DOMAIN, domain) } // ZMQ_CONFLATE: Keep only last message // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc6 func (soc *Socket) SetConflate(value bool) error { val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_CONFLATE, val) } //////////////////////////////////////////////////////////////// // // New in ZeroMQ 4.1.0 // //////////////////////////////////////////////////////////////// // // + : yes // D : deprecated // implemented documented test // ZMQ_ROUTER_HANDOVER + + // ZMQ_TOS + + // ZMQ_IPC_FILTER_PID D // ZMQ_IPC_FILTER_UID D // ZMQ_IPC_FILTER_GID D // ZMQ_CONNECT_RID + + // ZMQ_GSSAPI_SERVER + + // ZMQ_GSSAPI_PRINCIPAL + + // ZMQ_GSSAPI_SERVICE_PRINCIPAL + + // ZMQ_GSSAPI_PLAINTEXT + + // ZMQ_HANDSHAKE_IVL + + // ZMQ_SOCKS_PROXY + // ZMQ_XPUB_NODROP + // //////////////////////////////////////////////////////////////// // ZMQ_ROUTER_HANDOVER: handle duplicate client identities on ROUTER sockets // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc35 func (soc *Socket) SetRouterHandover(value bool) error { if minor < 1 { return ErrorNotImplemented41 } val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_ROUTER_HANDOVER, val) } // ZMQ_TOS: Set the Type-of-Service on socket // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc46 func (soc *Socket) SetTos(value int) error { if minor < 1 { return ErrorNotImplemented41 } return soc.setInt(C.ZMQ_TOS, value) } // ZMQ_CONNECT_RID: Assign the next outbound connection id // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc5 func (soc *Socket) SetConnectRid(value string) error { if minor < 1 { return ErrorNotImplemented41 } if value == "" { return soc.setNullString(C.ZMQ_CONNECT_RID) } return soc.setString(C.ZMQ_CONNECT_RID, value) } // ZMQ_GSSAPI_SERVER: Set GSSAPI server role // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc13 func (soc *Socket) SetGssapiServer(value bool) error { if minor < 1 { return ErrorNotImplemented41 } val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_GSSAPI_SERVER, val) } // ZMQ_GSSAPI_PRINCIPAL: Set name of GSSAPI principal // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc12 func (soc *Socket) SetGssapiPrincipal(value string) error { if minor < 1 { return ErrorNotImplemented41 } return soc.setString(C.ZMQ_GSSAPI_PRINCIPAL, value) } // ZMQ_GSSAPI_SERVICE_PRINCIPAL: Set name of GSSAPI service principal // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc14 func (soc *Socket) SetGssapiServicePrincipal(value string) error { if minor < 1 { return ErrorNotImplemented41 } return soc.setString(C.ZMQ_GSSAPI_SERVICE_PRINCIPAL, value) } // ZMQ_GSSAPI_PLAINTEXT: Disable GSSAPI encryption // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc11 func (soc *Socket) SetGssapiPlaintext(value bool) error { if minor < 1 { return ErrorNotImplemented41 } val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_GSSAPI_PLAINTEXT, val) } // ZMQ_HANDSHAKE_IVL: Set maximum handshake interval // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-1:zmq-setsockopt#toc15 func (soc *Socket) SetHandshakeIvl(value time.Duration) error { if minor < 1 { return ErrorNotImplemented41 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_HANDSHAKE_IVL, val) } // ZMQ_SOCKS_PROXY: NOT DOCUMENTED // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 func (soc *Socket) SetSocksProxy(value string) error { if minor < 1 { return ErrorNotImplemented41 } if value == "" { return soc.setNullString(C.ZMQ_SOCKS_PROXY) } return soc.setString(C.ZMQ_SOCKS_PROXY, value) } // Available since ZeroMQ 4.1, documented since ZeroMQ 4.2 // ZMQ_XPUB_NODROP: do not silently drop messages if SENDHWM is reached // // Returns ErrorNotImplemented41 with ZeroMQ version < 4.1 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc60 func (soc *Socket) SetXpubNodrop(value bool) error { if minor < 1 { return ErrorNotImplemented41 } val := 0 if value { val = 1 } return soc.setInt(C.ZMQ_XPUB_NODROP, val) } //////////////////////////////////////////////////////////// // // New in ZeroMQ 4.2.0 // //////////////////////////////////////////////////////////////// // // + : yes // o : getsockopt only // implemented documented test // ZMQ_BLOCKY // ZMQ_XPUB_MANUAL + + // ZMQ_XPUB_WELCOME_MSG + + // ZMQ_STREAM_NOTIFY + + // ZMQ_INVERT_MATCHING + + // ZMQ_HEARTBEAT_IVL + + // ZMQ_HEARTBEAT_TTL + + // ZMQ_HEARTBEAT_TIMEOUT + + // ZMQ_XPUB_VERBOSER + + // ZMQ_CONNECT_TIMEOUT + + // ZMQ_TCP_MAXRT + + // ZMQ_THREAD_SAFE o // ZMQ_MULTICAST_MAXTPDU + + // ZMQ_VMCI_BUFFER_SIZE + + // ZMQ_VMCI_BUFFER_MIN_SIZE + + // ZMQ_VMCI_BUFFER_MAX_SIZE + + // ZMQ_VMCI_CONNECT_TIMEOUT + + // ZMQ_USE_FD + + // //////////////////////////////////////////////////////////////// // ZMQ_XPUB_MANUAL: change the subscription handling to manual // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc59 func (soc *Socket) SetXpubManual(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_XPUB_MANUAL, value) } // ZMQ_XPUB_WELCOME_MSG: set welcome message that will be received by subscriber when connecting // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc61 func (soc *Socket) SetXpubWelcomeMsg(value string) error { if minor < 2 { return ErrorNotImplemented42 } if value == "" { return soc.setNullString(C.ZMQ_XPUB_WELCOME_MSG) } return soc.setString(C.ZMQ_XPUB_WELCOME_MSG, value) } // ZMQ_STREAM_NOTIFY: send connect and disconnect notifications // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc48 func (soc *Socket) SetStreamNotify(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_STREAM_NOTIFY, value) } // ZMQ_INVERT_MATCHING: Invert message filtering // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc22 func (soc *Socket) SetInvertMatching(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_INVERT_MATCHING, value) } // ZMQ_HEARTBEAT_IVL: Set interval between sending ZMTP heartbeats // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc17 func (soc *Socket) SetHeartbeatIvl(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_HEARTBEAT_IVL, val) } // ZMQ_HEARTBEAT_TTL: Set the TTL value for ZMTP heartbeats // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc19 func (soc *Socket) SetHeartbeatTtl(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_HEARTBEAT_TTL, val) } // ZMQ_HEARTBEAT_TIMEOUT: Set timeout for ZMTP heartbeats // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc18 func (soc *Socket) SetHeartbeatTimeout(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_HEARTBEAT_TIMEOUT, val) } // ZMQ_XPUB_VERBOSER: pass subscribe and unsubscribe messages on XPUB socket // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc58 func (soc *Socket) SetXpubVerboser(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_XPUB_VERBOSER, value) } // ZMQ_CONNECT_TIMEOUT: Set connect() timeout // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc7 func (soc *Socket) SetConnectTimeout(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_CONNECT_TIMEOUT, val) } // ZMQ_TCP_MAXRT: Set TCP Maximum Retransmit Timeout // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc54 func (soc *Socket) SetTcpMaxrt(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_TCP_MAXRT, val) } // ZMQ_MULTICAST_MAXTPDU: Maximum transport data unit size for multicast packets // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc27 func (soc *Socket) SetMulticastMaxtpdu(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_MULTICAST_MAXTPDU, value) } // ZMQ_VMCI_BUFFER_SIZE: Set buffer size of the VMCI socket // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc68 func (soc *Socket) SetVmciBufferSize(value uint64) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setUInt64(C.ZMQ_VMCI_BUFFER_SIZE, value) } // ZMQ_VMCI_BUFFER_MIN_SIZE: Set min buffer size of the VMCI socket // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc69 func (soc *Socket) SetVmciBufferMinSize(value uint64) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setUInt64(C.ZMQ_VMCI_BUFFER_MIN_SIZE, value) } // ZMQ_VMCI_BUFFER_MAX_SIZE: Set max buffer size of the VMCI socket // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc70 func (soc *Socket) SetVmciBufferMaxSize(value uint64) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setUInt64(C.ZMQ_VMCI_BUFFER_MAX_SIZE, value) } // ZMQ_VMCI_CONNECT_TIMEOUT: Set connection timeout of the VMCI socket // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc71 func (soc *Socket) SetVmciConnectTimeout(value time.Duration) error { if minor < 2 { return ErrorNotImplemented42 } val := int(value / time.Millisecond) return soc.setInt(C.ZMQ_VMCI_CONNECT_TIMEOUT, val) } // ZMQ_USE_FD: Set the pre-allocated socket file descriptor // // Returns ErrorNotImplemented42 with ZeroMQ version < 4.2 // // See: http://api.zeromq.org/4-2:zmq-setsockopt#toc31 func (soc *Socket) SetUseFd(value int) error { if minor < 2 { return ErrorNotImplemented42 } return soc.setInt(C.ZMQ_USE_FD, value) }
postmates/go-triton
vendor/github.com/pebbe/zmq4/socketset.go
GO
isc
23,258
<?php namespace ZEDx\Listeners; use ZEDx\Jobs\UpdateCache; class PageEventListener { /** * Handle page create events. */ public function onPageCreate($event) { dispatch(new UpdateCache($event->page)); } /** * Handle page delete events. */ public function onPageDelete($event) { dispatch(new UpdateCache($event->page, true)); } /** * Handle page update events. */ public function onPageUpdate($event) { dispatch(new UpdateCache($event->page)); } /** * Handle page template switch events. */ public function onPageTemplateSwitch($event) { dispatch(new UpdateCache($event->page)); } /** * Handle page themepartial attach events. */ public function onPageThemepartialAttach($event) { dispatch(new UpdateCache($event->page)); } /** * Handle page themepartial detach events. */ public function onPageThemepartialDetach($event) { dispatch(new UpdateCache($event->page)); } /** * Register the listeners for the subscriber. * * @param Illuminate\Events\Dispatcher $events * * @return array */ public function subscribe($events) { $class = "ZEDx\Listeners\PageEventListener"; $events->listen('ZEDx\Events\Page\PageTemplateWasSwitched', $class.'@onPageTemplateSwitch'); $events->listen('ZEDx\Events\Page\PageThemepartialWasAttached', $class.'@onPageThemepartialAttach'); $events->listen('ZEDx\Events\Page\PageThemepartialWasDetached', $class.'@onPageThemepartialDetach'); $events->listen('ZEDx\Events\Page\PageWasCreated', $class.'@onPageCreate'); $events->listen('ZEDx\Events\Page\PageWasDeleted', $class.'@onPageDelete'); $events->listen('ZEDx\Events\Page\PageWasUpdated', $class.'@onPageUpdate'); } }
zorx/core
src/Listeners/PageEventListener.php
PHP
mit
1,909
require 'rails_helper' RSpec.describe User, type: :model do let(:user) { User.new } it { expect(user).to validate_presence_of(:first_name) } it { expect(user).to validate_presence_of(:last_name)} it { expect(user).to validate_presence_of(:email)} it { expect(user).to validate_presence_of(:password)} # it { expect(user).to validate_uniqueness_of(:email)} it { expect(user).to validate_length_of(:password)} it { expect(user).to have_many(:housing_assignments) } it { expect(user).to have_many(:houses) } it { expect(user).to have_many(:chore_logs) } it { expect(user).to have_many(:chores) } it { expect(user).to have_many(:issues) } it { expect(user).to have_many(:user_promises) } it { expect(user).to have_many(:chores) } end
chi-sea-lions-2015/house-rules
spec/models/user_spec.rb
Ruby
mit
757
/*! * bootstrap 3 modal 封装 */ (function ($) { window.BSModal = function () { var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm'); var generateId = function () { var date = new Date(); return 'mdl' + date.valueOf(); } var init = function (options) { options = $.extend({}, { title: "操作提示", content: "提示内容", btnOK: "确定", btnOKDismiss: true, btnOKClass: 'btn-primary', btnCancel: "取消", modalClass: '', width: '', height: '', maxHeight: '', hasFooter: true, footerContent : '', afterInit : false, modalOptions : { backdrop : 'static' } }, options || {}); var modalId = generateId(); var footerHtml = ""; if(options.hasFooter) { var btnOKDismissHtml = options.btnOKDismiss ? 'data-dismiss="modal"' : ''; var btnClHtml = (typeof options.btnCancel == 'string' && options.btnCancel !="") ? '<button type="button" class="btn btn-default cancel" data-dismiss="modal">[BtnCancel]</button>' : ''; var btnOkHtml = (typeof options.btnOK == 'string' && options.btnOK != "") ? '<button type="button" class="btn ' + options.btnOKClass + ' ok" ' + btnOKDismissHtml +'>[BtnOk]</button>' : ''; var footerContentHtml = (typeof options.footerContent == 'string' && options.footerContent != "") ? options.footerContent : btnClHtml + btnOkHtml; footerHtml= '<div class="modal-footer">' + footerContentHtml + '</div>'; } var modalHtml = '<div id="[Id]" class="modal ' + options.modalClass + ' fade" role="dialog" aria-labelledby="modalLabel">' + '<div class="modal-dialog modal-sm">' + '<div class="modal-content">' + '<div class="modal-header">' + '<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>' + '<h4 class="modal-title" id="modalLabel">[Title]</h4>' + '</div>' + '<div class="modal-body">' + '[modalBodyHtml]' + '</div>' + footerHtml + '</div>' + '</div>' + '</div>'; var content = modalHtml.replace(reg, function (node, key) { return { Id: modalId, Title: options.title, modalBodyHtml: options.content, BtnOk: options.btnOK, BtnCancel: options.btnCancel }[key]; }); $('body').append(content); var $modal = $('#' + modalId); $modal.modal(options.modalOptions); if(typeof options.width == 'string' && options.width != 'auto' && options.width != '') { $modal.find('.modal-dialog').css('width', options.width); } if(typeof options.height == 'string' && options.height != 'auto' && options.height != '') { $modal.find('.modal-body').css({ 'height': options.height, 'overflow': 'auto' }); } if(typeof options.maxHeight == 'string' && options.maxHeight != 'auto' && options.maxHeight != '') { $modal.find('.modal-body').css({ 'maxHeight': options.maxHeight, 'overflow': 'auto' }); } //移动端统一处理弹窗的宽度高度,选项中定义的宽度、高度、最大高度不在移动端起作用 if(device.mobile()) { $modal.find('.modal-dialog').css({ 'width': 'auto', 'margin': '0.08rem' }); $modal.find('.modal-body').css({ 'height': 'auto', 'maxHeight': 'none', 'overflow': 'auto' }); } if (typeof options.afterInit === "function") options.afterInit.apply(this, [$modal]); $modal.on('hide.bs.modal', function (e) { $('body').find('#' + modalId).remove(); }); return modalId; } return { alert: function (options) { if (typeof options == 'string') { options = { content: options }; } var id = init(options); var $modal = $('#' + id); $modal.find('.cancel').hide(); return { id: id, on: function (callback) { if (callback && callback instanceof Function) { $modal.find('.ok').click(function () { callback(true); }); } }, hide: function (callback) { if (callback && callback instanceof Function) { $modal.on('hide.bs.modal', function (e) { callback(e); }); } } }; }, confirm: function (options) { var id = init(options); var $modal = $('#' + id); $modal.find('.cancel').show(); return { id: id, on: function (callback) { if (callback && callback instanceof Function) { $modal.find('.ok').click(function () { callback(true, id); }); $modal.find('.cancel').click(function () { callback(false, id); }); } }, hide: function (callback) { if (callback && callback instanceof Function) { $modal.on('hide.bs.modal', function (e) { callback(e); }); } } }; } } }(); })(jQuery);
Mutueye/MutueyeWeb
src/apps/HaierAdmin/static/js/BSModal.js
JavaScript
mit
7,097
/*************************************************************************/ /* slider.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "slider.h" #include "os/keyboard.h" Size2 Slider::get_minimum_size() const { Ref<StyleBox> style = get_stylebox("slider"); Size2i ms = style->get_minimum_size() + style->get_center_size(); return ms; } void Slider::_gui_input(Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { Ref<Texture> grabber = get_icon(mouse_inside || has_focus() ? "grabber_highlight" : "grabber"); grab.pos = orientation == VERTICAL ? mb->get_pos().y : mb->get_pos().x; double grab_width = (double)grabber->get_size().width; double grab_height = (double)grabber->get_size().height; double max = orientation == VERTICAL ? get_size().height - grab_height : get_size().width - grab_width; if (orientation == VERTICAL) set_as_ratio(1 - (((double)grab.pos - (grab_height / 2.0)) / max)); else set_as_ratio(((double)grab.pos - (grab_width / 2.0)) / max); grab.active = true; grab.uvalue = get_as_ratio(); } else { grab.active = false; } } else if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) { set_value(get_value() + get_step()); } else if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { set_value(get_value() - get_step()); } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { if (grab.active) { Size2i size = get_size(); Ref<Texture> grabber = get_icon("grabber"); float motion = (orientation == VERTICAL ? mm->get_pos().y : mm->get_pos().x) - grab.pos; if (orientation == VERTICAL) motion = -motion; float areasize = orientation == VERTICAL ? size.height - grabber->get_size().height : size.width - grabber->get_size().width; if (areasize <= 0) return; float umotion = motion / float(areasize); set_as_ratio(grab.uvalue + umotion); } } if (!mm.is_valid() && !mb.is_valid()) { if (p_event->is_action("ui_left") && p_event->is_pressed()) { if (orientation != HORIZONTAL) return; set_value(get_value() - (custom_step >= 0 ? custom_step : get_step())); accept_event(); } else if (p_event->is_action("ui_right") && p_event->is_pressed()) { if (orientation != HORIZONTAL) return; set_value(get_value() + (custom_step >= 0 ? custom_step : get_step())); accept_event(); } else if (p_event->is_action("ui_up") && p_event->is_pressed()) { if (orientation != VERTICAL) return; set_value(get_value() + (custom_step >= 0 ? custom_step : get_step())); accept_event(); } else if (p_event->is_action("ui_down") && p_event->is_pressed()) { if (orientation != VERTICAL) return; set_value(get_value() - (custom_step >= 0 ? custom_step : get_step())); accept_event(); } else { Ref<InputEventKey> k = p_event; if (!k.is_valid() || !k->is_pressed()) return; switch (k->get_scancode()) { case KEY_HOME: { set_value(get_min()); accept_event(); } break; case KEY_END: { set_value(get_max()); accept_event(); } break; } } } } void Slider::_notification(int p_what) { switch (p_what) { case NOTIFICATION_MOUSE_ENTER: { mouse_inside = true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_inside = false; update(); } break; case NOTIFICATION_DRAW: { RID ci = get_canvas_item(); Size2i size = get_size(); Ref<StyleBox> style = get_stylebox("slider"); Ref<StyleBox> focus = get_stylebox("focus"); Ref<Texture> grabber = get_icon(mouse_inside || has_focus() ? "grabber_highlight" : "grabber"); Ref<Texture> tick = get_icon("tick"); if (orientation == VERTICAL) { style->draw(ci, Rect2i(Point2i(), Size2i(style->get_minimum_size().width + style->get_center_size().width, size.height))); /* if (mouse_inside||has_focus()) focus->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height))); */ float areasize = size.height - grabber->get_size().height; if (ticks > 1) { int tickarea = size.height - tick->get_height(); for (int i = 0; i < ticks; i++) { if (!ticks_on_borders && (i == 0 || i + 1 == ticks)) continue; int ofs = i * tickarea / (ticks - 1); tick->draw(ci, Point2(0, ofs)); } } grabber->draw(ci, Point2i(size.width / 2 - grabber->get_size().width / 2, size.height - get_as_ratio() * areasize - grabber->get_size().height)); } else { style->draw(ci, Rect2i(Point2i(), Size2i(size.width, style->get_minimum_size().height + style->get_center_size().height))); /* if (mouse_inside||has_focus()) focus->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height))); */ float areasize = size.width - grabber->get_size().width; if (ticks > 1) { int tickarea = size.width - tick->get_width(); for (int i = 0; i < ticks; i++) { if ((!ticks_on_borders) && ((i == 0) || ((i + 1) == ticks))) continue; int ofs = i * tickarea / (ticks - 1); tick->draw(ci, Point2(ofs, 0)); } } grabber->draw(ci, Point2i(get_as_ratio() * areasize, size.height / 2 - grabber->get_size().height / 2)); } } break; } } void Slider::set_custom_step(float p_custom_step) { custom_step = p_custom_step; } float Slider::get_custom_step() const { return custom_step; } void Slider::set_ticks(int p_count) { ticks = p_count; update(); } int Slider::get_ticks() const { return ticks; } bool Slider::get_ticks_on_borders() const { return ticks_on_borders; } void Slider::set_ticks_on_borders(bool _tob) { ticks_on_borders = _tob; update(); } void Slider::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &Slider::_gui_input); ClassDB::bind_method(D_METHOD("set_ticks", "count"), &Slider::set_ticks); ClassDB::bind_method(D_METHOD("get_ticks"), &Slider::get_ticks); ClassDB::bind_method(D_METHOD("get_ticks_on_borders"), &Slider::get_ticks_on_borders); ClassDB::bind_method(D_METHOD("set_ticks_on_borders", "ticks_on_border"), &Slider::set_ticks_on_borders); ADD_PROPERTY(PropertyInfo(Variant::INT, "tick_count", PROPERTY_HINT_RANGE, "0,4096,1"), "set_ticks", "get_ticks"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ticks_on_borders"), "set_ticks_on_borders", "get_ticks_on_borders"); ADD_PROPERTY(PropertyInfo(Variant::INT, "focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_focus_mode", "get_focus_mode"); } Slider::Slider(Orientation p_orientation) { orientation = p_orientation; mouse_inside = false; grab.active = false; ticks = 0; custom_step = -1; set_focus_mode(FOCUS_ALL); }
MrMaidx/godot
scene/gui/slider.cpp
C++
mit
8,893
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\CmsBundle\Entity; use WellCommerce\Bundle\CoreBundle\Entity\Route; /** * Class PageRoute * * @author Adam Piotrowski <adam@wellcommerce.org> */ class PageRoute extends Route { public function getType(): string { return 'page'; } }
diversantvlz/WellCommerce
src/WellCommerce/Bundle/CmsBundle/Entity/PageRoute.php
PHP
mit
583
/* * GMLGraphReader.cpp * * Created on: 18.09.2014 * Author: Maximilian Vogel (maximilian.vogel@student.kit.edu) */ #include "GMLGraphReader.h" #include "../auxiliary/Enforce.h" #include "../auxiliary/StringTools.h" #include "../auxiliary/Log.h" #include <unordered_map> #include <exception> #include <fstream> namespace NetworKit { Graph GMLGraphReader::read(const std::string& path) { std::ifstream graphFile(path); Aux::enforceOpened(graphFile); std::string line; std::unordered_map<std::string,node> nodeMap; auto ignoreWhitespaces = [](std::string& s, index i) { index newIdx = i; index end = s.size(); while (s[newIdx] == ' ' && newIdx < end) ++newIdx; return newIdx; }; auto getPair = [&ignoreWhitespaces](std::string& s) { if (s.find("[") < s.size()) { throw std::runtime_error("found opening bracket"); } else if (s.find("]") < s.size()) { throw std::runtime_error("found closing bracket"); } //DEBUG(s); index length = s.size(); index start = ignoreWhitespaces(s,0); index i = start; while (s[i] != ' ' && i < length) ++i; index end = i; std::string key = s.substr(start,end-start); //DEBUG(key, ", ",start, ", ", end); i = ignoreWhitespaces(s,i+1); // TODO: get next line if value is not in the current line ? not really necessary. start = i; while (s[i] != ' ' && i < length) ++i; end = i; std::string value = s.substr(start, end-start); //DEBUG(value, ", ",start, ", ", end); return std::make_pair(key,value); }; auto parseNode = [&](Graph& G) { bool closed = false; if (line.find("node") < line.size() && line.find("[") < line.size()) { std::getline(graphFile, line); closed = line.find("]") < line.size(); while (!closed) { try { auto pair = getPair(line); if (pair.first == "id") { // currently, node attributes are ignored and only the id is relevant for edges later on node u = G.addNode(); nodeMap.insert(std::make_pair(pair.second,u)); DEBUG("added node: ",u,", ",pair.second); } } catch (std::exception e) { //throw std::runtime_error("something went wrong when parsing a node"); return false; } std::getline(graphFile, line); closed = line.find("]") < line.size(); } } else { return false; } if (closed) { //std::getline(graphFile, line); return true; } else { return false; } }; auto parseEdge = [&](Graph& G) { //DEBUG("trying to parse an edge"); if (line.find("edge") < line.size() && line.find("[") < line.size()) { std::getline(graphFile, line); node u = 0; node v = 0; while (!(line.find("]") < line.size())) { try { auto pair = getPair(line); if (pair.first == "source") { // currently, node attributes are ignored and only the id is relevant for edges later on u = nodeMap[pair.second]; } else if (pair.first == "target") { v = nodeMap[pair.second]; } } catch (std::exception e) { //throw std::runtime_error("something went wrong when parsing an edge"); return false; } std::getline(graphFile,line); } G.addEdge(u,v); DEBUG("added edge ",u ,", ", v); } else { return false; } if (line.find("]") < line.size()) { //std::getline(graphFile, line); return true; } else { return false; } }; auto parseGraph = [&]() { Graph G; int key_type = 0; // 0 for graph keys, 1 for node, 2 for edges bool directed = false; std::getline(graphFile, line); index pos = line.find("graph"); bool graphTagFound = pos < line.size(); if (graphTagFound) { if (line.find("[",pos) < line.size()) { while (graphFile.good()) { std::getline(graphFile,line); switch (key_type) { case 0: try { auto pair = getPair(line); // currently, it is only interesting, if the graph is directed if (pair.first == "directed" && pair.second == "1") { directed = true; DEBUG("set directed to true"); } break; } catch (std::exception e) { if (directed) { G = Graph(0,false,true); } else { G = Graph(0,false,false); } ++key_type; } //break; case 1: if (parseNode(G)) { //DEBUG("parsed node successfully"); break; } else { ++key_type; DEBUG("couldn't parse node; key type is now: ",key_type); } //break; case 2: if (parseEdge(G)) { //DEBUG("parsed edge successfully"); break; } else { DEBUG("parsing edge went wrong"); ++key_type; } default: if (!(line.find("]") < line.size())) { DEBUG("expected closing bracket \"]\", got: ",line); } } } // at the end of the file, make sure the closing bracket is there. } else { throw std::runtime_error("GML graph file broken"); } } else { throw std::runtime_error("graph key not found"); } return G; }; // try { Graph G = parseGraph(); // } catch (std::exception e) { // std::string msg = "reading GML file went wrong: "; // msg+=e.what(); // throw std::runtime_error(msg); // } std::string graphName = Aux::StringTools::split(Aux::StringTools::split(path, '/').back(), '.').front(); G.setName(graphName); G.shrinkToFit(); return G; } } /* namespace NetworKit */
fmaschler/networkit
networkit/cpp/io/GMLGraphReader.cpp
C++
mit
5,327
# frozen_string_literal: true require File.dirname(__FILE__) + '/../test_helper.rb' class TestFakerCity < Test::Unit::TestCase def setup I18n.reload! xx = { :factory_helper => { :name => {:female_first_name => ['alice'], :male_first_name => ['alice'], :last_name => ['smith']}, :address => {:city_prefix => ['west'], :city_suffix => ['burg']} } } I18n.backend.store_translations(:xx, xx) xy = { :factory_helper => { :address => { :city_prefix => ['big'], :city_root => ['rock'], :city_root_suffix => ['ing'], :city_suffix => ['town'], :city => ['#{city_prefix} #{city_root}#{city_root_suffix} #{city_suffix}'] } } } I18n.backend.store_translations(:xy, xy) end def test_default_city_formats I18n.with_locale(:xx) do 100.times do cities = ["west alice", "west smith", "west aliceburg", "west smithburg", "aliceburg", "smithburg"] city = Faker::Address.city assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}" end end end def test_city_formats_are_flexible I18n.with_locale(:xy) do cities = ['big rocking town'] city = Faker::Address.city assert cities.include?(city), "Expected <#{cities.join(' / ')}>, but got #{city}" end end end
razorcd/factory-helper
test/legacy/test_faker_city.rb
Ruby
mit
1,382
<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\Constraint; use PHPUnit\Framework\ExpectationFailedException; /** * Logical NOT. */ class LogicalNot extends Constraint { /** * @var Constraint */ private $constraint; public static function negate(string $string): string { $positives = [ 'contains ', 'exists', 'has ', 'is ', 'are ', 'matches ', 'starts with ', 'ends with ', 'reference ', 'not not ' ]; $negatives = [ 'does not contain ', 'does not exist', 'does not have ', 'is not ', 'are not ', 'does not match ', 'starts not with ', 'ends not with ', 'don\'t reference ', 'not ' ]; \preg_match('/(\'[\w\W]*\')([\w\W]*)("[\w\W]*")/i', $string, $matches); if (\count($matches) > 0) { $nonInput = $matches[2]; $negatedString = \str_replace( $nonInput, \str_replace( $positives, $negatives, $nonInput ), $string ); } else { $negatedString = \str_replace( $positives, $negatives, $string ); } return $negatedString; } /** * @param Constraint|mixed $constraint */ public function __construct($constraint) { parent::__construct(); if (!($constraint instanceof Constraint)) { $constraint = new IsEqual($constraint); } $this->constraint = $constraint; } /** * Evaluates the constraint for parameter $other * * If $returnResult is set to false (the default), an exception is thrown * in case of a failure. null is returned otherwise. * * If $returnResult is true, the result of the evaluation is returned as * a boolean value instead: true in case of success, false in case of a * failure. * * @param mixed $other value or object to evaluate * @param string $description Additional information about the test * @param bool $returnResult Whether to return a result or throw an exception * * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * * @return mixed */ public function evaluate($other, $description = '', $returnResult = false) { $success = !$this->constraint->evaluate($other, $description, true); if ($returnResult) { return $success; } if (!$success) { $this->fail($other, $description); } } /** * Returns a string representation of the constraint. */ public function toString(): string { switch (\get_class($this->constraint)) { case LogicalAnd::class: case self::class: case LogicalOr::class: return 'not( ' . $this->constraint->toString() . ' )'; default: return self::negate( $this->constraint->toString() ); } } /** * Counts the number of constraint elements. */ public function count(): int { return \count($this->constraint); } /** * Returns the description of the failure * * The beginning of failure messages is "Failed asserting that" in most * cases. This method should return the second part of that sentence. * * @param mixed $other evaluated value or object * * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ protected function failureDescription($other): string { switch (\get_class($this->constraint)) { case LogicalAnd::class: case self::class: case LogicalOr::class: return 'not( ' . $this->constraint->failureDescription($other) . ' )'; default: return self::negate( $this->constraint->failureDescription($other) ); } } }
shi-yang/iisns
vendor/phpunit/phpunit/src/Framework/Constraint/LogicalNot.php
PHP
mit
4,566
<?php namespace Frontend\Modules\Blog\Tests\Actions; use Common\WebTestCase; class ArchiveTest extends WebTestCase { /** * @runInSeparateProcess */ public function testArchiveContainsBlogPosts() { $client = static::createClient(); $this->loadFixtures( $client, array( 'Backend\Modules\Blog\DataFixtures\LoadBlogCategories', 'Backend\Modules\Blog\DataFixtures\LoadBlogPosts', ) ); $client->request('GET', '/en/blog/archive/2015/02'); self::assertEquals( 200, $client->getResponse()->getStatusCode() ); self::assertContains( 'Blogpost for functional tests', $client->getResponse()->getContent() ); } /** * @runInSeparateProcess */ public function testArchiveWithOnlyYearsContainsBlogPosts() { $client = static::createClient(); $client->request('GET', '/en/blog/archive/2015'); self::assertEquals( 200, $client->getResponse()->getStatusCode() ); self::assertContains( 'Blogpost for functional tests', $client->getResponse()->getContent() ); } /** * @runInSeparateProcess */ public function testArchiveWithWrongMonthsGives404() { $client = static::createClient(); $client->request('GET', '/en/blog/archive/1990/07'); $this->assertIs404($client); } /** * @runInSeparateProcess */ public function testNonExistingPageGives404() { $client = static::createClient(); $client->request('GET', '/en/blog/archive/2015/02', array('page' => 34)); $this->assertIs404($client); } }
Thijzer/forkcms
src/Frontend/Modules/Blog/Tests/Actions/ArchiveTest.php
PHP
mit
1,803
function downloadBlob(data: string, mimeType: string, filename: string) { const blob = new Blob([data], { type: mimeType }); var el = document.createElement('a'); el.setAttribute('href', window.URL.createObjectURL(blob)); el.setAttribute('download', filename); el.style.display = 'none'; document.body.appendChild(el); el.click(); document.body.removeChild(el); } export { downloadBlob };
CatalystCode/ibex-dashboard
client/src/components/Dashboard/DownloadFile.tsx
TypeScript
mit
412
#include "jni/JniHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "CCApplication.h" #include "CCDirector.h" #include "CCEGLView.h" #include <android/log.h> #include <jni.h> #include <cstring> #define LOG_TAG "CCApplication_android Debug" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) NS_CC_BEGIN // sharedApplication pointer Application * Application::sm_pSharedApplication = 0; Application::Application() { CCAssert(! sm_pSharedApplication, ""); sm_pSharedApplication = this; } Application::~Application() { CCAssert(this == sm_pSharedApplication, ""); sm_pSharedApplication = NULL; } int Application::run() { // Initialize instance and cocos2d. if (! applicationDidFinishLaunching()) { return 0; } return -1; } void Application::setAnimationInterval(double interval) { // NYI } ////////////////////////////////////////////////////////////////////////// // static member function ////////////////////////////////////////////////////////////////////////// Application* Application::getInstance() { CCAssert(sm_pSharedApplication, ""); return sm_pSharedApplication; } // @deprecated Use getInstance() instead Application* Application::sharedApplication() { return Application::getInstance(); } LanguageType Application::getCurrentLanguage() { std::string languageName = getCurrentLanguageJNI(); const char* pLanguageName = languageName.c_str(); LanguageType ret = LanguageType::ENGLISH; if (0 == strcmp("zh", pLanguageName)) { ret = LanguageType::CHINESE; } else if (0 == strcmp("en", pLanguageName)) { ret = LanguageType::ENGLISH; } else if (0 == strcmp("fr", pLanguageName)) { ret = LanguageType::FRENCH; } else if (0 == strcmp("it", pLanguageName)) { ret = LanguageType::ITALIAN; } else if (0 == strcmp("de", pLanguageName)) { ret = LanguageType::GERMAN; } else if (0 == strcmp("es", pLanguageName)) { ret = LanguageType::SPANISH; } else if (0 == strcmp("ru", pLanguageName)) { ret = LanguageType::RUSSIAN; } else if (0 == strcmp("ko", pLanguageName)) { ret = LanguageType::KOREAN; } else if (0 == strcmp("ja", pLanguageName)) { ret = LanguageType::JAPANESE; } else if (0 == strcmp("hu", pLanguageName)) { ret = LanguageType::HUNGARIAN; } else if (0 == strcmp("pt", pLanguageName)) { ret = LanguageType::PORTUGUESE; } else if (0 == strcmp("ar", pLanguageName)) { ret = LanguageType::ARABIC; } else if (0 == strcmp("nb", pLanguageName)) { ret = LanguageType::NORWEGIAN; } else if (0 == strcmp("pl", pLanguageName)) { ret = LanguageType::POLISH; } return ret; } Application::Platform Application::getTargetPlatform() { return Platform::OS_ANDROID; } NS_CC_END
qq2588258/floweers
libs/cocos2dx/platform/android/CCApplication.cpp
C++
mit
2,999
import { Overlay } from '@angular/cdk/overlay'; import { ComponentType } from '@angular/cdk/portal'; import { Injector, TemplateRef } from '@angular/core'; import { Location } from '@angular/common'; import { MatBottomSheetConfig } from './bottom-sheet-config'; import { MatBottomSheetRef } from './bottom-sheet-ref'; /** * Service to trigger Material Design bottom sheets. */ export declare class MatBottomSheet { private _overlay; private _injector; private _parentBottomSheet; private _location; private _bottomSheetRefAtThisLevel; /** Reference to the currently opened bottom sheet. */ _openedBottomSheetRef: MatBottomSheetRef<any> | null; constructor(_overlay: Overlay, _injector: Injector, _parentBottomSheet: MatBottomSheet, _location?: Location | undefined); open<T, D = any, R = any>(component: ComponentType<T>, config?: MatBottomSheetConfig<D>): MatBottomSheetRef<T, R>; open<T, D = any, R = any>(template: TemplateRef<T>, config?: MatBottomSheetConfig<D>): MatBottomSheetRef<T, R>; /** * Dismisses the currently-visible bottom sheet. */ dismiss(): void; /** * Attaches the bottom sheet container component to the overlay. */ private _attachContainer(overlayRef, config); /** * Creates a new overlay and places it in the correct location. * @param config The user-specified bottom sheet config. */ private _createOverlay(config); /** * Creates an injector to be used inside of a bottom sheet component. * @param config Config that was used to create the bottom sheet. * @param bottomSheetRef Reference to the bottom sheet. */ private _createInjector<T>(config, bottomSheetRef); }
friendsofagape/mt2414ui
node_modules/@angular/material/typings/esm5/bottom-sheet/bottom-sheet.d.ts
TypeScript
mit
1,720
/******************************************************************************* * Copyright (c) 2015 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.graphics.action; import jsettlers.common.action.Action; import jsettlers.common.action.EActionType; /** * This is an action that can be executed. When fired, this action is not interpreted but executed instead. * * @author Michael Zangl * */ public abstract class ExecutableAction extends Action { /** * Creates a new {@link ExecutableAction}. */ public ExecutableAction() { super(EActionType.EXECUTABLE); } /** * Executes this action. */ public abstract void execute(); }
jsettlers/settlers-remake
jsettlers.graphics/src/main/java/jsettlers/graphics/action/ExecutableAction.java
Java
mit
1,754
/* eslint-disable no-undef */ import update from 'react/lib/update'; import { mapValues, pickBy } from 'lodash'; import { flow, keyBy, mapValues as mapValuesFp } from 'lodash/fp'; import * as types from '../types'; const cdn = window.location.host.startsWith('pre') || window.location.host.startsWith('localhost') ? 'precdn' : 'cdn'; export default (state = {}, action) => { let pkgAssets; switch (action.type) { case types.PACKAGE_ASSETS_LOAD_REQUESTED: pkgAssets = mapValues(action.pkg.assets, item => flow( keyBy( key => action.pkg.local ? `http://localhost:4000/packages/${key}` : `https://${cdn}.worona.io/packages/${key}`, ), mapValuesFp(() => false), )(item)); return update(state, { $merge: { [action.pkg.name]: pkgAssets } }); case types.PACKAGE_ASSETS_UNLOAD_REQUESTED: return pickBy(state, (value, key) => key !== action.pkg.name); case types.PACKAGE_ASSET_FILE_DOWNLOADED: return update(state, { $merge: { [action.pkgName]: { [action.assetType]: { [action.path]: true } } }, }); default: return state; } };
worona/worona
client/packages/core-dashboard-worona/src/dashboard/build-dashboard-extension-worona/reducers/assets.js
JavaScript
mit
1,195
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Represents the health state of the stateful service replica, which contains * the replica id and the aggregated health state. * * @extends models['ReplicaHealthState'] */ class StatefulServiceReplicaHealthState extends models['ReplicaHealthState'] { /** * Create a StatefulServiceReplicaHealthState. * @member {string} [replicaId] */ constructor() { super(); } /** * Defines the metadata of StatefulServiceReplicaHealthState * * @returns {object} metadata of StatefulServiceReplicaHealthState * */ mapper() { return { required: false, serializedName: 'Stateful', type: { name: 'Composite', className: 'StatefulServiceReplicaHealthState', modelProperties: { aggregatedHealthState: { required: false, serializedName: 'AggregatedHealthState', type: { name: 'String' } }, partitionId: { required: false, serializedName: 'PartitionId', type: { name: 'String' } }, serviceKind: { required: true, serializedName: 'ServiceKind', type: { name: 'String' } }, replicaId: { required: false, serializedName: 'ReplicaId', type: { name: 'String' } } } } }; } } module.exports = StatefulServiceReplicaHealthState;
lmazuel/azure-sdk-for-node
lib/services/serviceFabric/lib/models/statefulServiceReplicaHealthState.js
JavaScript
mit
1,913
<?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'user', 'passwords' => 'user', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */ 'guards' => [ 'user' => [ 'driver' => 'session', 'provider' => 'user', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admin', ], 'api' => [ 'driver' => 'token', 'provider' => 'user', ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'user' => [ 'driver' => 'eloquent', 'model' => ZEDx\Models\User::class, ], 'admin' => [ 'driver' => 'eloquent', 'model' => ZEDx\Models\Admin::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | Here you may set the options for resetting passwords including the view | that is your password reset e-mail. You may also set the name of the | table that maintains all of the reset tokens for your application. | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'passwords' => [ 'user' => [ 'provider' => 'user', 'email' => 'emails.user.passwordReset', 'table' => 'password_resets', 'expire' => 60, ], 'admin' => [ 'provider' => 'admin', 'email' => 'emails.admin.passwordReset', 'table' => 'admins_password_resets', 'expire' => 60, ], ], ];
zorx/core
config/auth.php
PHP
mit
3,986
// Copyright: All contributers to the Umple Project // This file is made available subject to the open source license found at: // http://umple.org/license // // Models history (undo stack) in UmpleOnline History = new Object(); // History item currently on display; -1 means nothing saved. History.currentIndex = -1; // Initially there is nothing saved. History.oldestAvailableIndex = 0; History.newestAvailableIndex = 0; // capacity of the circular structure; we will reuse after cycling through History.versionCount = 9999; History.noChange = "//$?[No_Change]$?"; // Initially nothing is saved. History.firstSave = true; // Returns the version that had been saved; called when moving forward // using a 'redo' operation; called from Action.redo History.getNextVersion = function() { Page.enablePaletteItem("buttonUndo", true); var result; if (!History.FirstSave && History.newestAvailableIndex != History.currentIndex) { History.currentIndex = History.incrementIndex(History.currentIndex); // Page.catFeedbackMessage("Set history for next to " + History.currentIndex); // DEBUG result = History.getVersion(History.currentIndex); if (result == undefined) result = History.noChange; } else { result = History.noChange; } if (History.newestAvailableIndex == History.currentIndex) { Page.enablePaletteItem("buttonRedo", false); } return result; } // Returns the previously saved version in the undo stack // Moves the pointer back in the undo stack // Called from Action.undo and also from save in the case of an apparent undo History.getPreviousVersion = function() { var result; if (!History.FirstSave && History.oldestAvailableIndex != History.currentIndex) { History.currentIndex = History.decrementIndex(History.currentIndex); // Page.catFeedbackMessage("Set history back to " + History.currentIndex); // DEBUG result = History.getVersion(History.currentIndex); if (result == undefined) result = History.noChange; else Page.enablePaletteItem("buttonRedo", true); } else { // No previously saved versions result = History.noChange; } if (History.oldestAvailableIndex == History.currentIndex) { Page.enablePaletteItem("buttonUndo", false); } return result; } // Save a new version of the code History.save = function(umpleCode, reason) { if (!History.firstSave) { // Whenever we save we set the highest saved index // So we can't redo Page.enablePaletteItem("buttonRedo", false); Page.enablePaletteItem("buttonUndo", true); } var gap = History.distanceBetween(History.oldestAvailableIndex, History.currentIndex); if (gap == History.versionCount - 1) { History.oldestAvailableIndex = History.incrementIndex(History.oldestAvailableIndex); } History.currentIndex = History.incrementIndex(History.currentIndex); // Page.catFeedbackMessage("Set history for new to " + History.currentIndex + " " + reason);// DEBUG History.newestAvailableIndex = History.currentIndex; History.setVersion(History.currentIndex, umpleCode); if(History.firstSave) { History.firstSave = false; } } // Find the previous index of a saved item, this // is simply by decrementing, except if we hit zero, in which case we // cycle back around from versionCount. // The result may be 'invalid' in that nothing may have bet been stored there History.decrementIndex = function(index) { var result; if (index == 0) { result = History.versionCount - 1; } else { result = index - 1; } return result; } // Find the next index above the argument; loop around to zero // if we exceed versionCount since we are using a circular structure // The result may be 'invalid' in that nothing may have bet been stored there History.incrementIndex = function(index) { var result = (index + 1) % History.versionCount; return result; } // Retrieve the index with version versionNumber History.getVersion = function(versionNumber) { var selector = "#" + "textEditorColumn"; var requested = "version" + versionNumber; return jQuery(selector).data(requested); } // Store a new version with index versionNumber History.setVersion = function(versionNumber, umpleCode) { var selector = "#" + "textEditorColumn"; var requested = "version" + versionNumber; return jQuery(selector).data(requested, umpleCode); } History.distanceBetween = function(index1, index2) { if (History.currentIndex == -1) return 0; var distance = 0; var i = index1; while (i != index2) { i = History.incrementIndex(i); distance += 1; } return distance; }
ahmedvc/umple
umpleonline/scripts/umple_history.js
JavaScript
mit
4,793
//------------------------------------------------------------------ // // For licensing information and to get the latest version go to: // http://www.codeplex.com/perspective // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR // FITNESS FOR A PARTICULAR PURPOSE. // //------------------------------------------------------------------ using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; using Perspective.Wpf3D.Primitives; using Perspective.Wpf3D.Sculptors; namespace Perspective.Wpf3D.Shapes { /// <summary> /// A 3D isocahedron element. /// Default radius is 1.0. /// </summary> public class Isocahedron3D : GeometryElement3D { /// <summary> /// Indicates if the isocahedron is truncated. /// Default value is false /// </summary> public bool Truncated { get { return (bool)GetValue(TruncatedProperty); } set { SetValue(TruncatedProperty, value); } } /// <summary> /// Identifies the Truncated dependency property. /// </summary> public static readonly DependencyProperty TruncatedProperty = DependencyProperty.Register( "Truncated", typeof(bool), typeof(Isocahedron3D), new UIPropertyMetadata(false)); /// <summary> /// Called by UIElement3D.InvalidateModel() to update the 3D model. /// </summary> protected override void OnUpdateModel() { Sculptor sculptor; if (Truncated) { sculptor = new TruncatedIsocahedronSculptor(); } else { sculptor = new IsocahedronSculptor(); } sculptor.BuildMesh(); Geometry = sculptor.Mesh; base.OnUpdateModel(); } } }
winark/ai-algorithmplatform
AIAlgorithmPlatform/2008/reference/Perspective/Perspective.Wpf3D/Shapes/Isocahedron3D.cs
C#
mit
2,143
/** * @fileoverview 管道对象,包含过滤规则和被过滤的数据,作为数据树的节点 * @authors Tony Liang <pillar0514@163.com> */ define('mods/model/pipe',function(require,exports,module){ var $ = require('lib'); var $model = require('lib/mvc/model'); var $tip = require('mods/dialog/tip'); var $channel = require('mods/channel/global'); var $getDataModel = require('mods/util/getDataModel'); var $delay = require('lib/kit/func/delay'); var $contains = require('lib/kit/arr/contains'); var Pipe = $model.extend({ defaults : { type : 'pipe', name : '', data : null, source : null, state : 'prepare', ready : false, filter : null }, events : { //数据源变更时需要计算 'change:source' : 'compute', //过滤器变更时需要计算 'change:filter' : 'compute', 'change:ready' : 'checkReady', }, build : function(){ this.compute = $delay(this.compute, 10); this.executeCompute = $delay(this.executeCompute, 10); this.checkPrepare(); this.checkUpdate(); this.checkReady(); }, setEvents : function(action){ var proxy = this.proxy(); this.delegate(action); $channel[action]('data-prepare', proxy('checkPrepare')); $channel[action]('data-ready', proxy('checkUpdate')); }, setConf : function(options){ this.set(options); }, //检查数据是否准备完毕,准备完毕后要发送广播通知关联组件更新数据 checkReady : function(){ if(this.isReady()){ $channel.trigger('data-ready', this.get('name')); }else{ $channel.trigger('data-prepare', this.get('name')); } }, isReady : function(){ return !!this.get('ready'); }, //检查是否要将自己变更为数据准备中状态 checkPrepare : function(name){ if(name === this.get('name')){return;} var requiredPath = this.getRequiredPath(); if(name){ if($contains(requiredPath, name)){ this.set('ready', false); this.set('state', 'prepare'); }else{ //do nothing } }else{ this.set('ready', false); this.set('state', 'prepare'); } }, //检查是否要更新自己的数据 checkUpdate : function(name){ if(name === this.get('name')){return;} var requiredPath = this.getRequiredPath(); if(name){ if($contains(requiredPath, name)){ this.checkCompute(); }else{ //do nothing } }else{ this.checkCompute(); } }, //检查是否可以进行数据计算 checkCompute : function(){ var requiredPath = this.getRequiredPath(); var allReady = requiredPath.every(function(name){ var requiredModel = $getDataModel(name); return requiredModel ? requiredModel.isReady() : false; }); if(allReady){ this.compute(); } }, //根据用户设置的源数据表单项,获取源数据列表 getRequiredPath : function(){ var source = this.get('source'); if(source){ return Object.keys(source).map(function(key){ return source[key]; }); }else{ return []; } }, //使用多线程计算 runWithWorker : function(){ var that = this; var source = this.get('source'); var filter = this.get('filter'); var code = []; code = code.concat([ 'onmessage = function(e){', ' postMessage(', ' (function(' + Object.keys(source).join(',') + '){', filter, ' })(' + Object.keys(source).map(function(name){ return 'e.data["' + name + '"]'; }).join(',') + ')', ' );', ' self.close();', '};' ]); var blob = new Blob(code, {type: "text/javascript;charset=UTF-8"}); var url = window.URL.createObjectURL(blob); var worker = new Worker(url); worker.onerror = function(e){ worker.terminate(); console.error(that.get('type') + ' ' + that.get('name') + ' compute error:', e.message); that.set('data', null); that.set('state', 'error'); that.set('ready', true); }; worker.onmessage = function(e){ worker.terminate(); that.set('data', e.data); that.set('state', 'success'); that.set('ready', true); }; var rs = {}; $.each(source, function(name, path){ var smodel = $getDataModel(path); if(smodel){ rs[name] = smodel.get(true, 'data'); }else{ rs[name] = null; } }); worker.postMessage(rs); }, //不使用多线程计算 runWithoutWorker : function(){ var that = this; var source = this.get('source'); var filter = this.get('filter'); var code = []; var args = []; var data; Object.keys(source).forEach(function(name, index){ code.push('var ' + name + ' = arguments[' + index + '];'); var smodel = $getDataModel(source[name]); if(smodel){ args.push(smodel.get('data')); }else{ args.push(null); } }); code = code.join('\n') + '\n'; code = code + filter; setTimeout(function(){ try{ var fn = new Function(code); data = fn.apply(that, args); if(data){ that.set('data', data); that.set('state', 'success'); }else{ that.set('data', null); that.set('state', 'error'); } }catch(e){ console.error(this.get('type') + ' ' + that.get('name') + ' compute error:', e.message); that.set('data', null); that.set('state', 'error'); }finally{ that.set('ready', true); } }); }, executeCompute : function(){ var that = this; var source = this.get('source'); var filter = this.get('filter'); var requiredPath = this.getRequiredPath(); var data; var sourceModel; if($.type(source) !== 'object'){ this.set('data', null); this.set('state', 'error'); this.set('ready', true); }else{ if(requiredPath.length){ if(!filter){ sourceModel = $getDataModel(requiredPath[0]); if(sourceModel){ data = sourceModel.get('data'); } if(data){ this.set('data', data); this.set('state', 'success'); }else{ this.set('data', null); this.set('state', 'error'); } this.set('ready', true); }else{ if(window.Worker){ this.runWithWorker(); }else{ this.runWithoutWorker(); } } }else{ this.set('data', null); this.set('state', 'error'); this.set('ready', true); } } }, //计算经过自己的过滤器过滤的数据 compute : function(){ this.set('ready', false); this.set('state', 'prepare'); this.checkReady(); this.executeCompute(); } }); module.exports = Pipe; });
Esoul/log-analysis
src/js/mods/model/pipe.js
JavaScript
mit
6,524
module MergeRequests class BaseService < ::IssuableBaseService def create_note(merge_request) SystemNoteService.change_status(merge_request, merge_request.target_project, current_user, merge_request.state, nil) end def create_title_change_note(issuable, old_title) removed_wip = MergeRequest.work_in_progress?(old_title) && !issuable.work_in_progress? added_wip = !MergeRequest.work_in_progress?(old_title) && issuable.work_in_progress? changed_title = MergeRequest.wipless_title(old_title) != issuable.wipless_title if removed_wip SystemNoteService.remove_merge_request_wip(issuable, issuable.project, current_user) elsif added_wip SystemNoteService.add_merge_request_wip(issuable, issuable.project, current_user) end super if changed_title end def hook_data(merge_request, action, oldrev = nil) hook_data = merge_request.to_hook_data(current_user) hook_data[:object_attributes][:url] = Gitlab::UrlBuilder.build(merge_request) hook_data[:object_attributes][:action] = action if oldrev && !Gitlab::Git.blank_ref?(oldrev) hook_data[:object_attributes][:oldrev] = oldrev end hook_data end def execute_hooks(merge_request, action = 'open', oldrev = nil) if merge_request.project merge_data = hook_data(merge_request, action, oldrev) merge_request.project.execute_hooks(merge_data, :merge_request_hooks) merge_request.project.execute_services(merge_data, :merge_request_hooks) end end private def filter_params super(:merge_request) end def merge_requests_for(branch) origin_merge_requests = @project.origin_merge_requests .opened.where(source_branch: branch).to_a fork_merge_requests = @project.fork_merge_requests .opened.where(source_branch: branch).to_a (origin_merge_requests + fork_merge_requests) .uniq.select(&:source_project) end def pipeline_merge_requests(pipeline) merge_requests_for(pipeline.ref).each do |merge_request| next unless pipeline == merge_request.pipeline yield merge_request end end def commit_status_merge_requests(commit_status) merge_requests_for(commit_status.ref).each do |merge_request| pipeline = merge_request.pipeline next unless pipeline next unless pipeline.sha == commit_status.sha yield merge_request end end end end
shinexiao/gitlabhq
app/services/merge_requests/base_service.rb
Ruby
mit
2,503
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Buffers.Text { public partial class SymbolTable { private sealed class Utf8InvariantSymbolTable : SymbolTable { private static readonly byte[][] Utf8DigitsAndSymbols = new byte[][] { new byte[] { 48, }, new byte[] { 49, }, new byte[] { 50, }, new byte[] { 51, }, new byte[] { 52, }, new byte[] { 53, }, new byte[] { 54, }, new byte[] { 55, }, new byte[] { 56, }, new byte[] { 57, }, // digit 9 new byte[] { 46, }, // decimal separator new byte[] { 44, }, // group separator new byte[] { 73, 110, 102, 105, 110, 105, 116, 121, }, new byte[] { 45, }, // minus sign new byte[] { 43, }, // plus sign new byte[] { 78, 97, 78, }, // NaN new byte[] { 69, }, // E new byte[] { 101, }, // e }; public Utf8InvariantSymbolTable() : base(Utf8DigitsAndSymbols) {} public override bool TryEncode(byte utf8, Span<byte> destination, out int bytesWritten) { if (destination.Length < 1) goto ExitFailed; if (utf8 > 0x7F) goto ExitFailed; destination[0] = utf8; bytesWritten = 1; return true; ExitFailed: bytesWritten = 0; return false; } public override bool TryEncode(ReadOnlySpan<byte> utf8, Span<byte> destination, out int bytesConsumed, out int bytesWritten) { // TODO: We might want to validate that the stream we are moving from utf8 to destination (also UTF-8) is valid. // For now, we are just doing a copy. if (utf8.TryCopyTo(destination)) { bytesConsumed = bytesWritten = utf8.Length; return true; } bytesConsumed = bytesWritten = 0; return false; } public override bool TryParse(ReadOnlySpan<byte> source, out byte utf8, out int bytesConsumed) { if (source.Length < 1) goto ExitFailed; utf8 = source[0]; if (utf8 > 0x7F) goto ExitFailed; bytesConsumed = 1; return true; ExitFailed: utf8 = 0; bytesConsumed = 0; return false; } public override bool TryParse(ReadOnlySpan<byte> source, Span<byte> utf8, out int bytesConsumed, out int bytesWritten) { // TODO: We might want to validate that the stream we are moving from utf8 to destination (also UTF-8) is valid. // For now, we are just doing a copy. if (source.TryCopyTo(utf8)) { bytesConsumed = bytesWritten = source.Length; return true; } bytesConsumed = bytesWritten = 0; return false; } } } }
benaadams/corefxlab
src/System.Text.Primitives/System/Text/SymbolTable/SymbolTable_utf8.cs
C#
mit
3,497
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // include these in the editor bundle because they are widely used by many languages import 'vs/editor/common/languages.common'; import 'vs/editor/common/worker/validationHelper'; import Severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import {WorkerServer} from 'vs/base/common/worker/workerServer'; import {EventService} from 'vs/platform/event/common/eventService'; import {IEventService} from 'vs/platform/event/common/event'; import {AbstractExtensionService, ActivatedExtension} from 'vs/platform/extensions/common/abstractExtensionService'; import {IExtensionDescription, IExtensionService} from 'vs/platform/extensions/common/extensions'; import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection'; import {InstantiationService} from 'vs/platform/instantiation/common/instantiationService'; import {SecondaryMarkerService} from 'vs/platform/markers/common/markerService'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {BaseRequestService} from 'vs/platform/request/common/baseRequestService'; import {IRequestService} from 'vs/platform/request/common/request'; import {RemoteTelemetryService} from 'vs/platform/telemetry/common/remoteTelemetryService'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {WorkerThreadService} from 'vs/platform/thread/common/workerThreadService'; import {IThreadService} from 'vs/platform/thread/common/thread'; import {BaseWorkspaceContextService} from 'vs/platform/workspace/common/baseWorkspaceContextService'; import {IWorkspaceContextService, IWorkspace} from 'vs/platform/workspace/common/workspace'; import {ModeServiceImpl, ModeServiceWorkerHelper} from 'vs/editor/common/services/modeServiceImpl'; import {IModeService} from 'vs/editor/common/services/modeService'; import {ModelServiceWorkerHelper} from 'vs/editor/common/services/modelServiceImpl'; import {ResourceService} from 'vs/editor/common/services/resourceServiceImpl'; import {IResourceService} from 'vs/editor/common/services/resourceService'; export interface IInitData { contextService: { workspace:any; configuration:any; options:any; }; } interface IWorkspaceWithTelemetry extends IWorkspace { telemetry?:string; } interface IWorkspaceWithSearch extends IWorkspace { search?:string; } export interface ICallback { (something:any):void; } class WorkerExtensionService extends AbstractExtensionService<ActivatedExtension> { constructor() { super(true); } protected _showMessage(severity:Severity, msg:string): void { switch (severity) { case Severity.Error: console.error(msg); break; case Severity.Warning: console.warn(msg); break; case Severity.Info: console.info(msg); break; default: console.log(msg); } } protected _createFailedExtension(): ActivatedExtension { throw new Error('unexpected'); } protected _actualActivateExtension(extensionDescription: IExtensionDescription): TPromise<ActivatedExtension> { throw new Error('unexpected'); } } export class EditorWorkerServer { private threadService:WorkerThreadService; constructor() { } public initialize(mainThread:WorkerServer, complete:ICallback, error:ICallback, progress:ICallback, initData:IInitData):void { const services = new ServiceCollection(); const extensionService = new WorkerExtensionService(); const contextService = new BaseWorkspaceContextService(initData.contextService.workspace, initData.contextService.configuration, initData.contextService.options); this.threadService = new WorkerThreadService(mainThread.getRemoteCom()); this.threadService.setInstantiationService(new InstantiationService(new ServiceCollection([IThreadService, this.threadService]))); const telemetryServiceInstance = new RemoteTelemetryService('workerTelemetry', this.threadService); const resourceService = new ResourceService(); const markerService = new SecondaryMarkerService(this.threadService); const modeService = new ModeServiceImpl(this.threadService, extensionService); const requestService = new BaseRequestService(contextService, telemetryServiceInstance); services.set(IExtensionService, extensionService); services.set(IThreadService, this.threadService); services.set(IModeService, modeService); services.set(IWorkspaceContextService, contextService); services.set(IEventService, new EventService()); services.set(IResourceService, resourceService); services.set(IMarkerService, markerService); services.set(ITelemetryService, telemetryServiceInstance); services.set(IRequestService, requestService); const instantiationService = new InstantiationService(services); this.threadService.setInstantiationService(instantiationService); // Instantiate thread actors this.threadService.getRemotable(ModeServiceWorkerHelper); this.threadService.getRemotable(ModelServiceWorkerHelper); complete(undefined); } public request(mainThread:WorkerServer, complete:ICallback, error:ICallback, progress:ICallback, data:any):void { this.threadService.dispatch(data).then(complete, error, progress); } } export var value = new EditorWorkerServer();
f111fei/vscode
src/vs/editor/common/worker/editorWorkerServer.ts
TypeScript
mit
5,557
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const path = require("path") const jade = require("jade") const fs = require("fs") describe("templates", function () { const render = function (template, options) { const file = path.resolve(__dirname, `../${template}.jade`) return jade.render(fs.readFileSync(file).toString(), options) } describe("pre-rendered template", function () { before(function () { const facet = { facetName: "some-parameter", displayName: "Things" } return (this.el = render("template", { facet })) }) it("assigns correct class", function () { return this.el.should.containEql( '<div class="partners-facet-dropdown filter-partners-dropdown dropdown-some-parameter">' ) }) it("assigns initial placeholder", function () { return this.el.should.containEql( '<input placeholder="All Things" class="partners-facet-input no-selection"/>' ) }) return it("renders correct search icon", function () { return this.el.should.containEql('<span class="icon-chevron-down">') }) }) describe("suggestion template", function () { it("renders an item with no count specified", function () { const item = { name: "Foo Bar", id: "some-id" } const el = render("suggestion", { item }) return el.should.equal( '<a class="js-partner-filter partner-search-filter-item">Foo Bar</a>' ) }) it("renders an item with a count of zero", function () { const item = { name: "Foo Bar", id: "some-id", count: 0 } const el = render("suggestion", { item }) return el.should.equal( '<a class="js-partner-filter partner-search-filter-item is-disabled">Foo Bar (0)</a>' ) }) return it("renders an item with a results count", function () { const item = { name: "Foo Bar", id: "some-id", count: 1 } const el = render("suggestion", { item }) return el.should.equal( '<a class="js-partner-filter partner-search-filter-item">Foo Bar (1)</a>' ) }) }) return describe("search facet", function () { before(function () { const facet = { facetName: "some-parameter", displayName: "Things", search: true, } return (this.el = render("template", { facet })) }) it("assigns correct class", function () { return this.el.should.containEql( '<div class="partners-facet-dropdown filter-partners-dropdown dropdown-some-parameter">' ) }) it("assigns initial placeholder", function () { return this.el.should.containEql( '<input placeholder="All Things" class="partners-facet-input no-selection"/>' ) }) return it("renders correct search icon", function () { return this.el.should.containEql('<span class="icon-search">') }) }) })
joeyAghion/force
src/desktop/apps/galleries_institutions/components/dropdown/test/templates.test.js
JavaScript
mit
3,005
package com.ouwenjie.note.utils; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Handler; import android.os.Vibrator; import java.util.List; /** * 系统级常用方法 * 1、检测某个intent是否可用 * 2、检测设备是否安装了GooglePlay\mobileQQ\weChat\BaiduMap\ ?? * 3、检测某个类是否可用 * 4、跳转到应用市场 * 5、检测某个服务是否正在执行 * 6、检测本应用是否处于可见状态 * 7、震动 * * Created by 文杰 on 2015/4/2. */ public class SysUtils { private static SysUtils sysUtils; private Context mContext; private PackageManager packageManager; private SysUtils(Context cxt) { this.mContext = cxt; this.packageManager = mContext.getPackageManager(); } public static SysUtils getInstance(Context cxt) { if (null == sysUtils) { sysUtils = new SysUtils(cxt); } return sysUtils; } /** * 查询某个 Action 是否可用 * * @param action * @return */ public boolean isIntentAvailable(String action) { Intent intent = new Intent(action); return isIntentAvailable(intent); } /** * 查询带参数的 Action 是否可用 * * @param action * @param URIs * @return */ public boolean isIntentAvailable(String action, String URIs) { Intent intent = new Intent(action, Uri.parse(URIs)); return isIntentAvailable(intent); } /** * 检测某个intent是否可用 * * @param intent * @return */ public boolean isIntentAvailable(Intent intent) { List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /** * 检测Google Play是否可用 */ public boolean hasGooglePlayInstalled() { return hasInstalledPackage("com.android.vending"); } /** * 是否已经安装了微信应用 * * @return */ public boolean hasWechatInstalled() { return hasInstalledPackage("com.tencent.mm"); } /** * 是否已经安装了QQ应用 * * @return */ public boolean hasQQInstalled() { return hasInstalledPackage("com.tencent.mobileqq"); } /** * 是否已经安装了百度地图应用 * * @return */ public boolean hasBaiduMapInstalled() { return hasInstalledPackage("com.baidu.BaiduMap"); } /** * 查询是否安装了某个包 * * @param packageName * @return */ public boolean hasInstalledPackage(String packageName) { List<PackageInfo> list = packageManager.getInstalledPackages(0); if (null == list || list.size() == 0) return false; for (PackageInfo info : list) { if (info.packageName.equals(packageName)) return true; } return false; } /** * 检查所支持的类 * * @param className * 类的名称 * @return 支持返回true,否则false */ public static boolean isClassAvailable(String className) { try { Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } return true; } /** * 跳转到应用市场的本应用的页面 * */ public void goMarket() { String strUri = "market://details?id=" + mContext.getPackageName(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(strUri)); if (isIntentAvailable(intent)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } else { // "很抱歉,调用电子市场失败" } } /** * * 判断某个服务是否正在执行 * * @param cxt * @param serviceName * @return */ public boolean isServiceRunning(Context cxt, String serviceName) { if (null == cxt || null == serviceName || "".equals(serviceName)) return false; ActivityManager mActivityManager; List<ActivityManager.RunningServiceInfo> mServiceList; mActivityManager = (ActivityManager) cxt .getSystemService(Context.ACTIVITY_SERVICE); mServiceList = mActivityManager.getRunningServices(30); if (null != mServiceList && !mServiceList.isEmpty()) { for (int i = 0; i < mServiceList.size(); i++) { if (serviceName.equals(mServiceList.get(i).service .getClassName())) { return true; } } } return false; } /** * 本应用是否为当前可视状态 * * @param cxt * @return */ public boolean isTopActivity(Context cxt) { String packageName = null; ActivityManager am; List<ActivityManager.RunningTaskInfo> tasksInfo; packageName = cxt.getPackageName(); if (null != packageName) { am = (ActivityManager) cxt .getSystemService(Context.ACTIVITY_SERVICE); tasksInfo = am.getRunningTasks(2); if (tasksInfo.size() > 0) { if (packageName.equals(tasksInfo.get(0).topActivity .getPackageName())) { // 应用程序位于堆栈的顶层 return true; } } } return false; } /** * 震动(隔100ms,然后震动400ms) */ public void vibrate() { long[] pattern = { 100, 400 }; // 震动时间(停止 开启) final Vibrator vibrator; vibrator = (Vibrator) mContext .getSystemService(Context.VIBRATOR_SERVICE); // 震动服务 vibrator.vibrate(pattern, -1); // 震动一次 new Handler().postDelayed(new Runnable() { @Override public void run() { vibrator.cancel(); } }, 500); } }
JackOwen/Jide-Note
app/src/main/java/com/ouwenjie/note/utils/SysUtils.java
Java
mit
6,402
require 'test_helper' class EducationTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
KevinRPope/defriendalize
test/unit/education_test.rb
Ruby
mit
156
# Copyright (c) 2015 Microsoft Corporation """ >>> from z3 import * >>> b = BitVec('b', 16) >>> Extract(12, 2, b).sexpr() '((_ extract 12 2) b)' >>> Extract(12, 2, b) Extract(12, 2, b) >>> SignExt(10, b).sexpr() '((_ sign_extend 10) b)' >>> SignExt(10, b) SignExt(10, b) >>> ZeroExt(10, b).sexpr() '((_ zero_extend 10) b)' >>> ZeroExt(10, b) ZeroExt(10, b) >>> RepeatBitVec(3, b).sexpr() '((_ repeat 3) b)' >>> RepeatBitVec(3, b) RepeatBitVec(3, b) """ if __name__ == "__main__": import doctest if doctest.testmod().failed: exit(1)
dstaple/z3test
regressions/python/bug.2.py
Python
mit
551
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TypographicResolution.cs" company="QuantityTypes"> // Copyright (c) 2014 QuantityTypes contributors // </copyright> // <summary> // Implements the operator /. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace QuantityTypes { public partial struct TypographicResolution { /// <summary> /// Implements the operator /. /// </summary> /// <param name="x"> The x. </param> /// <param name="y"> The y. </param> /// <returns> The result of the operator. </returns> public static TypographicLength operator /(double x, TypographicResolution y) { return new TypographicLength(x / y.Value); } /// <summary> /// Implements the operator *. /// </summary> /// <param name="x"> The x. </param> /// <param name="y"> The y. </param> /// <returns> The result of the operator. </returns> public static double operator *(TypographicResolution x, TypographicLength y) { return x.Value * y.Value; } } }
BadBabyJames/QunityTypes
Source/QuantityTypes/Operators/TypographicResolution.cs
C#
mit
1,349
// Github: https://github.com/shdwjk/Roll20API/blob/master/DarknessClosingIn/DarknessClosingIn.js // By: The Aaron, Arcane Scriptomancer // Contact: https://app.roll20.net/users/104025/the-aaron var DarknessClosingIn = DarknessClosingIn || (function() { 'use strict'; var version = 0.1, schemaVersion = 0.1, checkInstall = function() { if( ! _.has(state,'DarknessClosingIn') || state.DarknessClosingIn.version !== schemaVersion) { log('DarknessClosingIn: Resetting state'); state.DarknessClosingIn = { version: schemaVersion, gettingDarker: false }; } }, handleInput = function(msg) { var args; if (msg.type !== "api" || ! isGM(msg.playerid) ) { return; } args = msg.content.split(/\s+/); switch(args[0]) { case '!DarknessClosingIn': state.DarknessClosingIn.gettingDarker = ! state.DarknessClosingIn.gettingDarker; sendChat('','/w gm ' + ( state.DarknessClosingIn.gettingDarker ? 'Darkness is now closing in.' : 'Darkness is no longer closing in.' ) ); break; } }, gettingDarker = function(obj, prev) { if( state.DarknessClosingIn.gettingDarker && ( obj.get("left") !== prev.left || obj.get("top") !== prev.top ) ) { obj.set({ light_radius: Math.floor(obj.get("light_radius") * 0.90) }); } }, registerEventHandlers = function() { on('chat:message', handleInput); on("change:token", gettingDarker); }; return { CheckInstall: checkInstall, RegisterEventHandlers: registerEventHandlers }; }()); on('ready',function() { 'use strict'; if("undefined" !== typeof isGM && _.isFunction(isGM)) { DarknessClosingIn.CheckInstall(); DarknessClosingIn.RegisterEventHandlers(); } else { log('--------------------------------------------------------------'); log('DarknessClosingIn requires the isGM module to work.'); log('isGM GIST: https://gist.github.com/shdwjk/8d5bb062abab18463625'); log('--------------------------------------------------------------'); } });
maekstr/roll20-api-scripts
DarknessClosingIn/DarknessClosingIn.js
JavaScript
mit
2,062
require File.dirname(__FILE__) + "/helper" class UnaryPlusNodeTest < NodeTestCase def test_to_sexp node = UnaryPlusNode.new(NumberNode.new(10)) assert_sexp([:u_plus, [:lit, 10]], node) end end
tobie/modulr
vendor/rkelly/test/test_unary_plus_node.rb
Ruby
mit
206
require 'aws/ops_works' class Service::AwsOpsWorks < Service::HttpPost self.title = 'AWS OpsWorks' string :app_id, # see AppId at http://docs.aws.amazon.com/opsworks/latest/APIReference/API_App.html :stack_id, # see StackId at http://docs.aws.amazon.com/opsworks/latest/APIReference/API_Stack.html :branch_name, # see Revision at http://docs.aws.amazon.com/opsworks/latest/APIReference/API_Source.html :endpoint_region, # see AWS Opsworks Stacks at http://docs.aws.amazon.com/general/latest/gr/rande.html#opsworks_region :github_api_url, # The GitHub API endpoint to post DeploymentStatus callbacks to :aws_access_key_id # see AWSAccessKeyID at http://docs.aws.amazon.com/opsworks/latest/APIReference/CommonParameters.html password :aws_secret_access_key, :github_token white_list :app_id, :stack_id, :branch_name, :endpoint_region, :github_api_url, :aws_access_key_id default_events :push, :deployment url "http://docs.aws.amazon.com/opsworks/latest/APIReference/API_CreateDeployment.html" def app_id environment_app_id || required_config_value('app_id') end def stack_id environment_stack_id || required_config_value('stack_id') end def deployment_payload payload['deployment'] end def deployment_command (deployment_payload && deployment_payload['task']) || 'deploy' end def environment_stack_id opsworks_payload_environment('stack_id') end def environment_app_id opsworks_payload_environment('app_id') end def opsworks_payload_environment(key) opsworks_payload && opsworks_payload[environment] && opsworks_payload[environment][key] end def opsworks_payload deployment_payload && deployment_payload['payload'] && deployment_payload['payload']['config'] && deployment_payload['payload']['config']['opsworks'] end def environment deployment_payload['environment'] end def receive_event http.ssl[:verify] = true case event.to_s when 'deployment' update_app_revision(deployment_ref_name) app_deployment = create_deployment update_deployment_statuses(app_deployment) app_deployment when 'push' if branch_name == required_config_value('branch_name') create_deployment end else raise_config_error("The #{event} event is currently unsupported.") end end def update_deployment_statuses(app_deployment) return unless config_value('github_token') && !config_value('github_token').empty? deployment_id = app_deployment['deployment_id'] deployment_status_options = { "state" => "success", "target_url" => aws_opsworks_output_url, "description" => "Deployment #{payload['deployment']['id']} Accepted by Amazon. (github-services@#{Service.current_sha[0..7]})" } deployment_path = "/repos/#{github_repo_path}/deployments/#{payload['deployment']['id']}/statuses" response = http_post "#{github_api_url}#{deployment_path}" do |req| req.headers.merge!(default_github_headers) req.body = JSON.dump(deployment_status_options) end raise_config_error("Unable to post deployment statuses back to the GitHub API.") unless response.success? end def aws_opsworks_output_url "https://console.aws.amazon.com/opsworks/home?#/stack/#{stack_id}/deployments" end def default_github_headers { 'Accept' => "application/vnd.github.cannonball-preview+json", 'User-Agent' => "Operation: California", 'Content-Type' => "application/json", 'Authorization' => "token #{required_config_value('github_token')}" } end def github_repo_path payload['repository']['full_name'] end def configured_branch_name required_config_value('branch_name') end def deployment_ref_name payload['deployment']['ref'] end def update_app_revision(revision_name) app_source = { revision: revision_name } if config_value('github_token') && !config_value('github_token').empty? app_source = { url: "#{github_api_url}/repos/#{github_repo_path}/zipball/#{revision_name}", type: "archive", username: required_config_value("github_token"), password: "x-oauth-basic", revision: revision_name } end ops_works_client.update_app app_id: app_id, app_source: app_source end def create_deployment ops_works_client.create_deployment stack_id: stack_id, app_id: app_id, command: { name: deployment_command } end def ops_works_client region = config_value('endpoint_region') # The AWS library requires you pass `nil`, and not an empty string, if you # want to connect to a legitimate default AWS host name. region = nil if region.empty? AWS::OpsWorks::Client.new access_key_id: required_config_value('aws_access_key_id'), secret_access_key: required_config_value('aws_secret_access_key'), region: region end def github_api_url if config_value("github_api_url").empty? "https://api.github.com" else config_value("github_api_url") end end end
github/github-services
lib/services/aws_ops_works.rb
Ruby
mit
5,350
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ connection: 'localMongo', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe' };
timkendall/vigil
config/models.js
JavaScript
mit
1,443
// // CreatePrerenderSubgraph.cpp // HCi571X-ARToolkit // // Created by Dr.-Ing. Rafael Radkowski on 3/6/13. // Copyright (c) 2013 Dr.-Ing. Rafael Radkowski. All rights reserved. // #include "PrerenderSubgraph.h" void PrerenderSubgraph::create(osg::Group *subgraph, int width, int height, const osg::Vec4 &clearColor, osg::Camera::RenderTargetImplementation renderImplementation, osg::Texture2D* destination) { // Set the clear mask; it determines what memories get cleared every frame this->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set the clear color this->setClearColor(clearColor); // Set a default projection matrix and a default view matrix. // Note, this settings are replaced this->setProjectionMatrixAsPerspective(1.57, 0.7, 0.01, 10000000.0); this->setViewMatrixAsLookAt(osg::Vec3d(1.0f, 0.0f, 0.0f), osg::Vec3d(0.0f, 0.0f, 0.0f), osg::Vec3d(0.0f, 0.0f, 1.0f)); // Set the coordinate reference frame this->setReferenceFrame(osg::Transform::ABSOLUTE_RF); // Set the viewport for the texture; it determines the region of the texture in which the // prerenderer can render the image this->setViewport(0,0,width, height); // The sequence of rendering this->setRenderOrder(osg::Camera::PRE_RENDER); // The target implementation specifies how the target texture is realized on the graphics card. // It can be implemented as frame buffer memory or as a frame buffer object etc. this->setRenderTargetImplementation(renderImplementation); // Attach the target texture to a memory. this->attach(osg::Camera::COLOR_BUFFER, destination); // Culling is deactivated. You can activate it. Sometimes, the culling cause some problems. this->setCullingActive(false); // Here we add the subgraph to the second camera this->addChild(subgraph); } void PrerenderSubgraph::attachView(osg::Camera* camera) { _cb = new PrerenderSubgraphCallback(camera, this); this->setProjectionMatrix(camera->getProjectionMatrix()); this->addUpdateCallback(_cb); }
rafael-radkowski/HCI571-AR
19_Magic_Lens/PrerenderSubgraph.cpp
C++
mit
2,293
import React from 'react'; import SvgIcon from '../../SvgIcon'; const NotificationNetworkLocked = (props) => ( <SvgIcon {...props}> <path d="M19.5 10c.17 0 .33.03.5.05V1L1 20h13v-3c0-.89.39-1.68 1-2.23v-.27c0-2.48 2.02-4.5 4.5-4.5zm2.5 6v-1.5c0-1.38-1.12-2.5-2.5-2.5S17 13.12 17 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z"/> </SvgIcon> ); NotificationNetworkLocked.displayName = 'NotificationNetworkLocked'; NotificationNetworkLocked.muiName = 'SvgIcon'; export default NotificationNetworkLocked;
alvarolobato/blueocean-plugin
jenkins-design-language/src/js/components/material-ui/svg-icons/notification/network-locked.js
JavaScript
mit
597
# frozen_string_literal: true module Admin class PagesController < Admin::AdminController include PagesCore::Admin::PageJsonHelper include PagesCore::Admin::NewsPageController before_action :find_categories before_action :find_page, only: %i[show edit update destroy move] require_authorization helper_method :page_json def index @pages = Page.admin_list(@locale) end def deleted @pages = Page.deleted.by_updated_at.in_locale(@locale) end def show redirect_to edit_admin_page_url(@locale, @page) end def new build_params = params[:page] ? page_params : nil @page = build_page(@locale, build_params) @page.parent = if params[:parent] Page.find(params[:parent]) elsif @news_pages @news_pages.first end end def create @page = build_page(@locale, page_params, param_categories) if @page.valid? @page.save respond_with_page(@page) do redirect_to(edit_admin_page_url(@locale, @page)) end else render action: :new end end def edit; end def update if @page.update(page_params) @page.categories = param_categories respond_with_page(@page) do flash[:notice] = "Your changes were saved" redirect_to edit_admin_page_url(@locale, @page) end else render action: :edit end end def move parent = params[:parent_id] ? Page.find(params[:parent_id]) : nil @page.update(parent: parent, position: params[:position]) respond_with_page(@page) { redirect_to admin_pages_url(@locale) } end def destroy Page.find(params[:id]).flag_as_deleted! redirect_to admin_pages_url(@locale) end private def build_page(locale, attributes = nil, categories = nil) Page.new.localize(locale).tap do |page| page.author = default_author || current_user page.attributes = attributes if attributes page.categories = categories if categories end end def default_author User.find_by_email(PagesCore.config.default_author) end def page_attributes %i[template user_id status feed_enabled published_at redirect_to image_link news_page unique_name pinned parent_page_id serialized_tags meta_image_id starts_at ends_at all_day image_id path_segment meta_title meta_description open_graph_title open_graph_description] end def page_params params.require(:page).permit( PagesCore::Templates::TemplateConfiguration.all_blocks + page_attributes, page_images_attributes: %i[id position image_id primary _destroy], page_files_attributes: %i[id position attachment_id _destroy] ) end def param_categories return [] unless params[:category] params.permit(category: {})[:category] .to_hash .map { |id, _| Category.find(id) } end def find_page @page = Page.find(params[:id]).localize(@locale) end def find_categories @categories = Category.order("name") end def respond_with_page(page, &block) respond_to do |format| format.html { block.call } format.json { render json: page_json(page) } end end end end
manualdesign/pages
app/controllers/admin/pages_controller.rb
Ruby
mit
3,415
<?php /** * @package hubzero-cms * @copyright Copyright 2005-2019 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ use Hubzero\Content\Migration\Base; // No direct access defined('_HZEXEC_') or die(); /** * Migration script for adding Antispam - Linkrife plugin **/ class Migration20170831000000PlgAntispamLinkrife extends Base { /** * Up **/ public function up() { $this->addPluginEntry('antispam', 'linkrife'); } /** * Down **/ public function down() { $this->deletePluginEntry('antispam', 'linkrife'); } }
zweidner/hubzero-cms
core/plugins/antispam/linkrife/migrations/Migration20170831000000PlgAntispamLinkrife.php
PHP
mit
575
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; internal static partial class Interop { internal static partial class Sys { internal const int IPv4AddressBytes = 4; internal const int IPv6AddressBytes = 16; internal const int MAX_IP_ADDRESS_BYTES = 16; internal const int INET_ADDRSTRLEN = 22; internal const int INET6_ADDRSTRLEN = 65; // NOTE: `_isIPv6` cannot be of type `bool` because `bool` is not a blittable type and this struct is // embedded in other structs for interop purposes. [StructLayout(LayoutKind.Sequential)] internal unsafe struct IPAddress { public bool IsIPv6 { get { return _isIPv6 != 0; } set { _isIPv6 = value ? 1u : 0u; } } internal fixed byte Address[MAX_IP_ADDRESS_BYTES]; // Buffer to fit an IPv4 or IPv6 address private uint _isIPv6; // Non-zero if this is an IPv6 address; zero for IPv4. internal uint ScopeId; // Scope ID (IPv6 only) } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_IPv6StringToAddress", SetLastError = true)] internal static extern int IPv6StringToAddress(string address, string port, byte[] buffer, int bufferLength, out uint scope); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_IPv4StringToAddress", SetLastError = true)] internal static extern int IPv4StringToAddress(string address, byte[] buffer, int bufferLength, out ushort port); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_IPAddressToString")] internal unsafe static extern int IPAddressToString(byte* address, int addressLength, bool isIPv6, byte* str, int stringLength, uint scope = 0); internal unsafe static uint IPAddressToString(byte[] address, bool isIPv6, StringBuilder addressString, uint scope = 0) { Debug.Assert(address != null); Debug.Assert((address.Length == IPv4AddressBytes) || (address.Length == IPv6AddressBytes)); int err; fixed (byte* rawAddress = address) { int bufferLength = isIPv6 ? INET6_ADDRSTRLEN : INET_ADDRSTRLEN; byte* buffer = stackalloc byte[bufferLength]; err = IPAddressToString(rawAddress, address.Length, isIPv6, buffer, bufferLength, scope); if (err == 0) { addressString.Append(Marshal.PtrToStringAnsi((IntPtr)buffer)); } } return unchecked((uint)err); } } }
mafiya69/corefx
src/Common/src/Interop/Unix/System.Native/Interop.IPAddress.cs
C#
mit
2,959
# -*- encoding: utf-8 -*- require File.dirname(__FILE__) + '/../spec_helper.rb' describe "RGhost" do before(:each) do @valid_attributes = { :especie_documento => "DM", :moeda => "9", :data_documento => Date.today, :dias_vencimento => 1, :aceite => "S", :quantidade => 1, :valor => 0.0, :local_pagamento => "QUALQUER BANCO ATÉ O VENCIMENTO", :cedente => "Kivanio Barbosa", :documento_cedente => "12345678912", :sacado => "Claudio Pozzebom", :sacado_documento => "12345678900", :agencia => "4042", :conta_corrente => "61900", :convenio => 12387989, :numero_documento => "777700168" } end it "Testar se RGhost e GhostScript estão instalados" do # RGhost::Config.config_platform File.exist?(RGhost::Config::GS[:path]).should be_true File.executable?(RGhost::Config::GS[:path]).should be_true s=`#{RGhost::Config::GS[:path]} -v` s.should =~ /^GPL Ghostscript/ s=`#{RGhost::Config::GS[:path]} --version` s.should =~ /[8-9]\.[0-9]/ end end
luizcamargo/brcobranca
spec/brcobranca/rghost_spec.rb
Ruby
mit
1,078
<?php /* * This file is part of the Haven package. * * (c) Stéphan Champagne <sc@evocatio.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Haven\Bundle\PosBundle\Controller; // Symfony includes use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; // Sensio includes use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; // Haven includes use Haven\Bundle\PosBundle\Form\BasketType as Form; use Haven\Bundle\PosBundle\Entity\Purchase as Entity; class BasketController extends ContainerAware { /** * @Route("/", name="HavenPosBundle_BasketIndex") * @Method("GET") * @Template() */ public function indexAction() { $entity = $this->container->get("Doctrine")->getRepository("HavenPosBundle:Purchase")->find(1); return array("entity" => $entity); } /** * Finds and displays a basket entity. * * @Route("/show", name="HavenPosBundle_BasketShow") * @Method("GET") * @Template() */ public function showAction() { $entity = $this->getBasketFromSession(); if (!$entity) { throw new NotFoundHttpException('entity.not.found'); } // $delete_form = $this->createDeleteForm($id); return array( 'entity' => $entity // , "delete_form" => $delete_form->createView() ); } /** * Finds and displays all baskets for admin. * * @Route("/list", name="HavenPosBundle_BasketList") * @Method("GET") * @Template() */ public function listAction() { $entity = $this->getBasketFromSession(); return array("entity" => $entity); } /** * @Route("/reset", name="HavenPosBundle_BasketReset") * @Method("GET") * @Template */ public function resetAction() { $this->container->get("session")->set("basket", new Entity()); return new RedirectResponse($this->container->get('router')->generate('HavenPosBundle_BasketEdit')); } // // /** // * Creates a new basket entity. // * // * @Route("/new", name="HavenPosBundle_BasketCreate") // * @Method("POST") // * @Template("HavenPosBundle:Basket:new.html.twig") // */ // public function createAction() { // // $edit_form = $this->createBasketForm(new Entity()); // $edit_form->bindRequest($this->container->get('Request')); // // if ($this->saveToSession($edit_form) === true) { // $this->container->get("session")->getFlashBag()->add("success", "create.success"); // // return new RedirectResponse($this->container->get('router')->generate('HavenPosBundle_BasketList')); // } // // $this->container->get("session")->getFlashBag()->add("error", "create.error"); // return array( // 'edit_form' => $edit_form->createView() // ); // } /** * @Route("/new", name="HavenPosBundle_BasketCreate") * @Route("/edit", name="HavenPosBundle_BasketEdit") * @return RedirectResponse * @Method("GET") * @Template */ public function editAction() { // $this->container->get("session")->set("basket", null); $entity = $this->getBasketFromSession(); if (!$entity) { throw new NotFoundHttpException('entity.not.found'); } $edit_form = $this->createBasketForm($entity); // $delete_form = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $edit_form->createView(), // 'delete_form' => $delete_form->createView(), ); } /** * @Route("/new", name="HavenPosBundle_BasketCreate") * @Route("/edit", name="HavenPosBundle_BasketUpdate") * @return RedirectResponse * @Method("POST") * @Template("HavenPosBundle:Basket:edit.html.twig") */ public function updateAction() { $entity = $this->getBasketFromSession(); $basket_post = $this->container->get('Request')->get("haven_bundle_posbundle_baskettype"); echo "mets en "; if (!$entity) { throw new NotFoundHttpException('entity.not.found'); } $edit_form = $this->createBasketForm($entity); $edit_form->bind($basket_post); if ($this->saveToSession($edit_form) === true) { $this->container->get("session")->getFlashBag()->add("success", "update.success"); // return new RedirectResponse($this->container->get('router')->generate('HavenPosBundle_BasketList')); } // $this->container->get("session")->getFlashBag()->add("error", "update.error"); return array( 'entity' => $entity, 'edit_form' => $edit_form->createView(), // 'delete_form' => $delete_form->createView(), ); } /** * Finds and displays all baskets for admin. * * @Route("/purchase", name="HavenPosBundle_BasketPurchase") * @Method("GET") * @Template() */ public function purchaseAction() { $entity = $this->getBasketFromSession(); // $entity = new Entity(); if (!$entity) { throw new NotFoundHttpException('entity.not.found'); } $edit_form = $this->createPurchaseForm($entity); // $delete_form = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $edit_form->createView(), // 'delete_form' => $delete_form->createView(), ); } /** * @Route("/confirmPurchase", name="HavenPosBundle_BasketConfirmPurchase") * @return RedirectResponse * @Method("POST") * @Template("HavenPosBundle:Basket:purchase.html.twig") */ public function confirmPurchaseAction() { $entity = $this->getBasketFromSession(); $purchase_post = $this->container->get('Request')->get("haven_bundle_posbundle_purchasetype"); if (!$entity) { throw new NotFoundHttpException('entity.not.found'); } $edit_form = $this->createPurchaseForm($entity); $edit_form->bind($purchase_post); if ($this->processPurchaseForm($edit_form) === true) { $this->container->get("session")->getFlashBag()->add("success", "update.success"); return new RedirectResponse($this->container->get('router')->generate('HavenPosBundle_BasketPayment')); } $this->container->get("session")->getFlashBag()->add("error", "update.error"); return array( 'entity' => $entity, 'edit_form' => $edit_form->createView(), // 'delete_form' => $delete_form->createView(), ); } /** * Start payment workflow. * * @Route("/{id}/state", name="HavenPosBundle_BasketToggleState") * @Method("GET") */ public function toggleStateAction($id) { $em = $this->container->get('doctrine')->getEntityManager(); $entity = $em->find('HavenPosBundle:Basket', $id); if (!$entity) { throw new NotFoundHttpException("Basket non trouvé"); } $entity->setStatus(!$entity->getStatus()); $em->persist($entity); $em->flush(); return new RedirectResponse($this->container->get("request")->headers->get('referer')); } // // /** // * Deletes a basket entity. // * // * @Route("/{id}/delete", name="HavenPosBundle_BasketDelete") // * @Method("POST") // */ // public function deleteAction($id) { // // $em = $this->container->get('Doctrine')->getEntityManager(); // $entity = $em->getRepository("HavenPosBundle:Basket")->find($id); // // if (!$entity) { // throw new NotFoundHttpException('entity.not.found'); // } // // $em->remove($entity); // $em->flush(); // // return new RedirectResponse($this->container->get('router')->generate('HavenPosBundle_BasketList')); // } // ------------- Privates ------------------------------------------- /** * Creates an edit_form with all the translations objects added for status languages * @param basket $entity * @return Form or RedirectResponse if validation error */ protected function createBasketForm($entity) { $edit_form = $this->container->get('form.factory')->create(new Form(), $entity); return $edit_form; } /** * Creates an edit_form with all the translations objects added for status languages * @param basket $entity * @return Form or RedirectResponse if validation error */ protected function createPurchaseForm($entity) { $edit_form = $this->container->get('form.factory')->create(new \Haven\Bundle\PosBundle\Form\PurchaseType(), $entity); return $edit_form; } // /** // * Create the simple delete form // * @param integer $id // * @return form // */ // protected function createDeleteForm($id) { // // return $this->container->get('form.factory')->createBuilder('form', array('id' => $id)) // ->add('id', 'hidden') // ->getForm() // ; // } /** * Validate and save form, if invalid returns form * @param type $edit_form * @return true or form */ protected function saveToSession($edit_form) { if ($edit_form->isValid()) { $entity = $edit_form->getData(); $em = $this->container->get('doctrine')->getEntityManager(); // $entity->removePurchaseProduct($entity->getPurchaseProducts()->first()); $em->detach($entity); $this->container->get("session")->set("basket", $entity); return true; } return $edit_form; } /** * Validate and save form, if invalid returns form * @param type $edit_form * @return true or form */ protected function processPurchaseForm($edit_form) { if ($edit_form->isValid()) { $entity = $edit_form->getData(); //// update purchase and purchase product here for price taxes and other // foreach ($entity->getPurchaseProducts() as $pp) { // $pp->setPurchase($entity); // echo $pp->getId(); // } $em = $this->container->get('doctrine')->getEntityManager(); $em->persist($entity); $em->flush(); // detach to put the new information back in the session. $this->saveToSession($edit_form); return true; } return $edit_form; } private function getBasketFromSession() { if (!$entity = $this->container->get("session")->get("basket")) { return new Entity(); } $em = $this->container->get("doctrine")->getEntityManager(); echo "<p>STATE_MANAGED: " . \Doctrine\ORM\UnitOfWork::STATE_MANAGED . "</p>"; echo "<p>STATE_REMOVED: " . \Doctrine\ORM\UnitOfWork::STATE_REMOVED . "</p>"; echo "<p>STATE_DETACHED: " . \Doctrine\ORM\UnitOfWork::STATE_DETACHED . "</p>"; echo "<p>STATE_NEW: " . \Doctrine\ORM\UnitOfWork::STATE_NEW . "</p>"; echo "<p>STATE_REMOVED: " . \Doctrine\ORM\UnitOfWork::STATE_REMOVED . "</p>"; echo "<p>" . $em->getUnitOfWork()->getEntityState($entity) . "</p>"; // If the state is detached for the entity, then merge // if ($em->getUnitOfWork()->getEntityState($entity) == 3) { $entity = $em->merge($entity); // } // else{ // $entity->getPurchaseProducts()->map(function($line_item) use ($em) { // // if ($line_item->getProduct() != NULL) { // $product = $em->getRepository("HavenPosBundle:Product")->find($line_item->getProduct()->getId()); // $line_item->setProduct($product); // $line_item->setPrice($line_item->getProduct()->getPrice()); // } // }); // } echo "<p>" . $em->getUnitOfWork()->getEntityState($entity) . "</p>"; // die(); // $entity = $em->merge($entity); return $entity; } }
havenlib/haven-standard
src/Haven/Bundle/PosBundle/Controller/BasketController.php
PHP
mit
12,579
define([ 'ufojs/main' , 'ufojs/errors' , 'ufojs/ufoLib/filenames' , 'ufojs/ufoLib/validators' , 'ufojs/ufoLib/glifLib/misc'], function( main , errors , filenames , validators , misc ) { "use strict"; doh.register("ufoLib.glifLib.misc", [ /** * this wraps ufoLib/filenames.userNameToFileName which is already tested * so here is just a short check */ function Test_glyphNameToFileName() { var glyphSet = { contents: {} } , glyphName = 'a' , resultA , resultB , i = 10 ; for(;i>0;i--) { resultA = filenames.userNameToFileName(glyphName, glyphSet.contents, '', '.glif'); resultB = misc.glyphNameToFileName(glyphName, glyphSet) doh.assertEqual(resultA, resultB); // create new clashes each iteration glyphSet.contents[resultA] = null; } } , function Test_validateLayerInfoVersion3ValueForAttribute() { doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('made-up', 1)) // this uses ufoLib.validators.genericTypeValidator doh.assertTrue(misc.validateLayerInfoVersion3ValueForAttribute('lib', {})) doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('lib', 1)) doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('lib', false)) // this uses ufoLib.validators.colorValidator, so just a rough check here: //good doh.assertTrue(misc.validateLayerInfoVersion3ValueForAttribute('color','1,1,1,1')) doh.assertTrue(misc.validateLayerInfoVersion3ValueForAttribute('color','1,0,0,0')) // may not be > 1 doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('color', '1,0,0,2')) // missing comma doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('color', '1,1,1 1')) // something else doh.assertFalse(misc.validateLayerInfoVersion3ValueForAttribute('color', [1,2,3,4])) } , function Test_validateLayerInfoVersion3Data() { var infoData, result; infoData = { 'made-up': 1000 } doh.assertError( errors.GlifLib, misc, 'validateLayerInfoVersion3Data', [infoData], 'unknown attribute' ); infoData = {}; doh.assertEqual(infoData, misc.validateLayerInfoVersion3Data(infoData)) infoData = { 'color': '1 1 1 1', }; doh.assertError( errors.GlifLib, misc, 'validateLayerInfoVersion3Data', [infoData], 'invalid value for attribute' ); infoData.color = '0,.7,.1,1'; doh.assertEqual(infoData, misc.validateLayerInfoVersion3Data(infoData)) infoData.lib = undefined; doh.assertError( errors.GlifLib, misc, 'validateLayerInfoVersion3Data', [infoData], 'invalid value for attribute' ); infoData.lib = {answer: 42}; doh.assertEqual(infoData, misc.validateLayerInfoVersion3Data(infoData)) delete infoData.color; doh.assertEqual(infoData, misc.validateLayerInfoVersion3Data(infoData)) // validateLayerInfoVersion3Data copies the values to a new object result = misc.validateLayerInfoVersion3Data(infoData); doh.assertFalse(result === infoData) } ]) });
moyogo/ufoJS
tests/ufoLib/glifLib/misc.js
JavaScript
mit
3,610
/* jshint maxlen: false */ var ca = require('../client_action'); var api = module.exports = {}; api._namespaces = ['cat', 'cluster', 'indices', 'nodes', 'snapshot']; /** * Perform a [abortBenchmark](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.name - A benchmark name */ api.abortBenchmark = ca({ url: { fmt: '/_bench/abort/<%=name%>', req: { name: { type: 'string' } } }, method: 'POST' }); /** * Perform a [bulk](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-bulk.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Explicitely set the replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.type - Default document type for items which don't provide one * @param {String} params.index - Default index for items which don't provide one */ api.bulk = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, type: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_bulk', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_bulk', req: { index: { type: 'string' } } }, { fmt: '/_bulk' } ], needBody: true, bulkBody: true, method: 'POST' }); api.cat = function CatNS(transport) { this.transport = transport; }; /** * Perform a [cat.aliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.cat.prototype.aliases = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_cat/aliases' } ] }); /** * Perform a [cat.allocation](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-allocation.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information */ api.cat.prototype.allocation = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/allocation/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cat/allocation' } ] }); /** * Perform a [cat.count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.count = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/count/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/count' } ] }); /** * Perform a [cat.fielddata](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-fielddata.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return the fielddata size */ api.cat.prototype.fielddata = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fields: { type: 'list' } }, urls: [ { fmt: '/_cat/fielddata/<%=fields%>', req: { fields: { type: 'list' } } }, { fmt: '/_cat/fielddata' } ] }); /** * Perform a [cat.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} [params.ts=true] - Set to false to disable timestamping * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.health = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, ts: { type: 'boolean', 'default': true }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/health' } }); /** * Perform a [cat.help](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.help - Return help information */ api.cat.prototype.help = ca({ params: { help: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat' } }); /** * Perform a [cat.indices](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-indices.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.pri - Set to true to return stats only for primary shards * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.indices = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, pri: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/indices/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/indices' } ] }); /** * Perform a [cat.master](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-master.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.master = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/master' } }); /** * Perform a [cat.nodes](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-nodes.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.nodes = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/nodes' } }); /** * Perform a [cat.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-pending-tasks.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/pending_tasks' } }); /** * Perform a [cat.plugins](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-plugins.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers */ api.cat.prototype.plugins = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, url: { fmt: '/_cat/plugins' } }); /** * Perform a [cat.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.bytes - The unit in which to display byte values * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.recovery = ca({ params: { bytes: { type: 'enum', options: [ 'b', 'k', 'm', 'g' ] }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/recovery/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/recovery' } ] }); /** * Perform a [cat.shards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cat-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {String, String[], Boolean} params.index - A comma-separated list of index names to limit the returned information */ api.cat.prototype.shards = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cat/shards/<%=index%>', req: { index: { type: 'list' } } }, { fmt: '/_cat/shards' } ] }); /** * Perform a [cat.threadPool](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/cat-thread-pool.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String, String[], Boolean} params.h - Comma-separated list of column names to display * @param {Boolean} params.help - Return help information * @param {Boolean} params.v - Verbose mode. Display column headers * @param {Boolean} params.fullId - Enables displaying the complete node ids */ api.cat.prototype.threadPool = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, h: { type: 'list' }, help: { type: 'boolean', 'default': false }, v: { type: 'boolean', 'default': false }, fullId: { type: 'boolean', 'default': false, name: 'full_id' } }, url: { fmt: '/_cat/thread_pool' } }); /** * Perform a [clearScroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.scrollId - A comma-separated list of scroll IDs to clear */ api.clearScroll = ca({ urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'list' } } }, { fmt: '/_search/scroll' } ], method: 'DELETE' }); api.cluster = function ClusterNS(transport) { this.transport = transport; }; /** * Perform a [cluster.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.getSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/settings' } }); /** * Perform a [cluster.health](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-health.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} [params.level=cluster] - Specify the level of detail for returned information * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.waitForActiveShards - Wait until the specified number of shards is active * @param {String} params.waitForNodes - Wait until the specified number of nodes is available * @param {Number} params.waitForRelocatingShards - Wait until the specified number of relocating shards is finished * @param {String} params.waitForStatus - Wait until cluster is in a specific state * @param {String} params.index - Limit the information returned to a specific index */ api.cluster.prototype.health = ca({ params: { level: { type: 'enum', 'default': 'cluster', options: [ 'cluster', 'indices', 'shards' ] }, local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' }, waitForActiveShards: { type: 'number', name: 'wait_for_active_shards' }, waitForNodes: { type: 'string', name: 'wait_for_nodes' }, waitForRelocatingShards: { type: 'number', name: 'wait_for_relocating_shards' }, waitForStatus: { type: 'enum', 'default': null, options: [ 'green', 'yellow', 'red' ], name: 'wait_for_status' } }, urls: [ { fmt: '/_cluster/health/<%=index%>', req: { index: { type: 'string' } } }, { fmt: '/_cluster/health' } ] }); /** * Perform a [cluster.pendingTasks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-pending.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.cluster.prototype.pendingTasks = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_cluster/pending_tasks' } }); /** * Perform a [cluster.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) */ api.cluster.prototype.putSettings = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' } }, url: { fmt: '/_cluster/settings' }, method: 'PUT' }); /** * Perform a [cluster.reroute](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-reroute.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.dryRun - Simulate the operation only and return the resulting state * @param {Boolean} params.explain - Return an explanation of why the commands can or cannot be executed * @param {Boolean} params.filterMetadata - Don't return cluster state metadata (default: false) * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout */ api.cluster.prototype.reroute = ca({ params: { dryRun: { type: 'boolean', name: 'dry_run' }, explain: { type: 'boolean' }, filterMetadata: { type: 'boolean', name: 'filter_metadata' }, masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_cluster/reroute' }, method: 'POST' }); /** * Perform a [cluster.state](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-state.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics */ api.cluster.prototype.state = ca({ params: { local: { type: 'boolean' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, urls: [ { fmt: '/_cluster/state/<%=metric%>/<%=index%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] }, index: { type: 'list' } } }, { fmt: '/_cluster/state/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'blocks', 'metadata', 'nodes', 'routing_table', 'master_node', 'version' ] } } }, { fmt: '/_cluster/state' } ] }); /** * Perform a [cluster.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.cluster.prototype.stats = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_cluster/stats/nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_cluster/stats' } ] }); /** * Perform a [count](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-count.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.minScore - Include only documents with a specific `_score` value in the result * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the results * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the results */ api.count = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, minScore: { type: 'number', name: 'min_score' }, preference: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_count', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_count', req: { index: { type: 'list' } } }, { fmt: '/_count' } ], method: 'POST' }); /** * Perform a [countPercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateIndex - The index to count percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to count percolate document into. Defaults to type. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being count percolated. * @param {String} params.type - The type of the document being count percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.countPercolate = ca({ params: { routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate/count', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} params.parent - ID of parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api['delete'] = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteByQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-delete-by-query.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {String} params.consistency - Specific write consistency setting for the operation * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.index - A comma-separated list of indices to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of types to restrict the operation */ api.deleteByQuery = ca({ params: { analyzer: { type: 'string' }, consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, q: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' }, timeout: { type: 'time' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_query', req: { index: { type: 'list' } } } ], method: 'DELETE' }); /** * Perform a [deleteScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.deleteScript = ca({ url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Template ID */ api.deleteTemplate = ca({ url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.exists = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [explain](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-explain.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.analyzeWildcard - Specify whether wildcards and prefix queries in the query string query should be analyzed (default: false) * @param {String} params.analyzer - The analyzer for the query string query * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The default field for query string query (default: _all) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.explain = ca({ params: { analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, analyzer: { type: 'string' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, fields: { type: 'list' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, parent: { type: 'string' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_explain', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.get = ca({ params: { fields: { type: 'list' }, parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.getScript = ca({ url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getSource](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.parent - The ID of the parent document * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String} params.routing - Specific routing value * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document; use `_all` to fetch the first document matching the ID across all types */ api.getSource = ca({ params: { parent: { type: 'string' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, routing: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_source', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } } }); /** * Perform a [getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Template ID */ api.getTemplate = ca({ url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } } }); /** * Perform a [index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.index = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, opType: { type: 'enum', 'default': 'index', options: [ 'index', 'create' ], name: 'op_type' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, routing: { type: 'string' }, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'string' }, type: { type: 'string' } } } ], needBody: true, method: 'POST' }); api.indices = function IndicesNS(transport) { this.transport = transport; }; /** * Perform a [indices.analyze](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-analyze.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The name of the analyzer to use * @param {String, String[], Boolean} params.charFilters - A comma-separated list of character filters to use for the analysis * @param {String} params.field - Use the analyzer configured for this field (instead of passing the analyzer name) * @param {String, String[], Boolean} params.filters - A comma-separated list of filters to use for the analysis * @param {String} params.index - The name of the index to scope the operation * @param {Boolean} params.preferLocal - With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true) * @param {String} params.text - The text on which the analysis should be performed (when request body is not used) * @param {String} params.tokenizer - The name of the tokenizer to use for the analysis * @param {String} [params.format=detailed] - Format of the output */ api.indices.prototype.analyze = ca({ params: { analyzer: { type: 'string' }, charFilters: { type: 'list', name: 'char_filters' }, field: { type: 'string' }, filters: { type: 'list' }, index: { type: 'string' }, preferLocal: { type: 'boolean', name: 'prefer_local' }, text: { type: 'string' }, tokenizer: { type: 'string' }, format: { type: 'enum', 'default': 'detailed', options: [ 'detailed', 'text' ] } }, urls: [ { fmt: '/<%=index%>/_analyze', req: { index: { type: 'string' } } }, { fmt: '/_analyze' } ], method: 'POST' }); /** * Perform a [indices.clearCache](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-clearcache.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.fieldData - Clear field data * @param {Boolean} params.fielddata - Clear field data * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to clear when using the `field_data` parameter (default: all) * @param {Boolean} params.filter - Clear filter caches * @param {Boolean} params.filterCache - Clear filter caches * @param {Boolean} params.filterKeys - A comma-separated list of keys to clear when using the `filter_cache` parameter (default: all) * @param {Boolean} params.id - Clear ID caches for parent/child * @param {Boolean} params.idCache - Clear ID caches for parent/child * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index name to limit the operation * @param {Boolean} params.recycler - Clear the recycler cache */ api.indices.prototype.clearCache = ca({ params: { fieldData: { type: 'boolean', name: 'field_data' }, fielddata: { type: 'boolean' }, fields: { type: 'list' }, filter: { type: 'boolean' }, filterCache: { type: 'boolean', name: 'filter_cache' }, filterKeys: { type: 'boolean', name: 'filter_keys' }, id: { type: 'boolean' }, idCache: { type: 'boolean', name: 'id_cache' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, index: { type: 'list' }, recycler: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_cache/clear', req: { index: { type: 'list' } } }, { fmt: '/_cache/clear' } ], method: 'POST' }); /** * Perform a [indices.close](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.close = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_close', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-create-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.index - The name of the index */ api.indices.prototype.create = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-index.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices */ api.indices.prototype['delete'] = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.name - A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices. */ api.indices.prototype.deleteAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-delete-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to delete (supports wildcards); use `_all` to delete all document types in the specified indices. */ api.indices.prototype.deleteMapping = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/<%=index%>/<%=type%>/_mapping', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String} params.name - The name of the template */ api.indices.prototype.deleteTemplate = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [indices.deleteWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.name - A comma-separated list of warmer names to delete (supports wildcards); use `_all` to delete all warmers in the specified indices. You must specify a name either in the uri or in the parameters. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to delete warmers from (supports wildcards); use `_all` to perform the operation on all indices. */ api.indices.prototype.deleteWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, name: { type: 'list' } }, url: { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [indices.exists](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of indices to check */ api.indices.prototype.exists = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>', req: { index: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.existsAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.existsAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } } ], method: 'HEAD' }); /** * Perform a [indices.existsTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.existsTemplate = ca({ params: { local: { type: 'boolean' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, method: 'HEAD' }); /** * Perform a [indices.existsType](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-types-exists.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` to check the types across all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to check */ api.indices.prototype.existsType = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, url: { fmt: '/<%=index%>/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, method: 'HEAD' }); /** * Perform a [indices.flush](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-flush.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.force - Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal) * @param {Boolean} params.full - If set to true a new index writer is created and settings that have been changed related to the index writer will be refreshed. Note: if a full flush is required for a setting to take effect this will be part of the settings update process and it not required to be executed by the user. (This setting can be considered as internal) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string for all indices */ api.indices.prototype.flush = ca({ params: { force: { type: 'boolean' }, full: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_flush', req: { index: { type: 'list' } } }, { fmt: '/_flush' } ], method: 'POST' }); /** * Perform a [indices.getAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to return */ api.indices.prototype.getAlias = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/<%=index%>/_alias', req: { index: { type: 'list' } } }, { fmt: '/_alias' } ] }); /** * Perform a [indices.getAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to filter aliases * @param {String, String[], Boolean} params.name - A comma-separated list of alias names to filter */ api.indices.prototype.getAliases = ca({ params: { timeout: { type: 'time' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_aliases/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_aliases', req: { index: { type: 'list' } } }, { fmt: '/_aliases/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_aliases' } ] }); /** * Perform a [indices.getFieldMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-field-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.includeDefaults - Whether the default mapping values should be returned as well * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types * @param {String, String[], Boolean} params.field - A comma-separated list of fields */ api.indices.prototype.getFieldMapping = ca({ params: { includeDefaults: { type: 'boolean', name: 'include_defaults' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>/field/<%=field%>', req: { index: { type: 'list' }, type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping/field/<%=field%>', req: { index: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>/field/<%=field%>', req: { type: { type: 'list' }, field: { type: 'list' } } }, { fmt: '/_mapping/field/<%=field%>', req: { field: { type: 'list' } } } ] }); /** * Perform a [indices.getMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names * @param {String, String[], Boolean} params.type - A comma-separated list of document types */ api.indices.prototype.getMapping = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_mapping', req: { index: { type: 'list' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'list' } } }, { fmt: '/_mapping' } ] }); /** * Perform a [indices.getSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-get-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open,closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the settings that should be included */ api.indices.prototype.getSettings = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': [ 'open', 'closed' ], options: [ 'open', 'closed' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_settings/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_settings' } ] }); /** * Perform a [indices.getTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.getTemplate = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, { fmt: '/_template' } ] }); /** * Perform a [indices.getWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` to perform the operation on all indices * @param {String, String[], Boolean} params.name - The name of the warmer (supports wildcards); leave empty to get all warmers * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.getWarmer = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, local: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'list' } } }, { fmt: '/<%=index%>/_warmer', req: { index: { type: 'list' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'list' } } }, { fmt: '/_warmer' } ] }); /** * Perform a [indices.open](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-open-close.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=closed] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index */ api.indices.prototype.open = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'closed', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, url: { fmt: '/<%=index%>/_open', req: { index: { type: 'string' } } }, method: 'POST' }); /** * Perform a [indices.optimize](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-optimize.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flush - Specify whether the index should be flushed after performing the operation (default: true) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Number} params.maxNumSegments - The number of segments the index should be merged into (default: dynamic) * @param {Boolean} params.onlyExpungeDeletes - Specify whether the operation should only expunge deleted documents * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.waitForMerge - Specify whether the request should block until the merge process is finished (default: true) * @param {Boolean} params.force - Force a merge operation to run, even if there is a single segment in the index (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.optimize = ca({ params: { flush: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, maxNumSegments: { type: 'number', name: 'max_num_segments' }, onlyExpungeDeletes: { type: 'boolean', name: 'only_expunge_deletes' }, operationThreading: { name: 'operation_threading' }, waitForMerge: { type: 'boolean', name: 'wait_for_merge' }, force: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_optimize', req: { index: { type: 'list' } } }, { fmt: '/_optimize' } ], method: 'POST' }); /** * Perform a [indices.putAlias](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Explicit timestamp for the document * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {String, String[], Boolean} params.index - A comma-separated list of index names the alias should point to (supports wildcards); use `_all` or omit to perform the operation on all indices. * @param {String} params.name - The name of the alias to be created or updated */ api.indices.prototype.putAlias = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, urls: [ { fmt: '/<%=index%>/_alias/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/_alias/<%=name%>', req: { name: { type: 'string' } } } ], method: 'PUT' }); /** * Perform a [indices.putMapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-put-mapping.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreConflicts - Specify whether to ignore conflicts while updating the mapping (default: false) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.index - A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices. * @param {String} params.type - The name of the document type */ api.indices.prototype.putMapping = ca({ params: { ignoreConflicts: { type: 'boolean', name: 'ignore_conflicts' }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/_mapping/<%=type%>', req: { index: { type: 'list' }, type: { type: 'string' } } }, { fmt: '/_mapping/<%=type%>', req: { type: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putSettings](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-update-settings.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.putSettings = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, urls: [ { fmt: '/<%=index%>/_settings', req: { index: { type: 'list' } } }, { fmt: '/_settings' } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-templates.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.order - The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers) * @param {Boolean} params.create - Whether the index template should only be added if new or can also replace an existing one * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {String} params.name - The name of the template */ api.indices.prototype.putTemplate = ca({ params: { order: { type: 'number' }, create: { type: 'boolean', 'default': false }, timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' }, flatSettings: { type: 'boolean', name: 'flat_settings' } }, url: { fmt: '/_template/<%=name%>', req: { name: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [indices.putWarmer](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-warmers.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) in the search request to warm * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices in the search request to warm. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both, in the search request to warm. * @param {String, String[], Boolean} params.index - A comma-separated list of index names to register the warmer for; use `_all` or omit to perform the operation on all indices * @param {String} params.name - The name of the warmer * @param {String, String[], Boolean} params.type - A comma-separated list of document types to register the warmer for; leave empty to perform the operation on all types */ api.indices.prototype.putWarmer = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_warmer/<%=name%>', req: { index: { type: 'list' }, type: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/<%=index%>/_warmer/<%=name%>', req: { index: { type: 'list' }, name: { type: 'string' } } }, { fmt: '/_warmer/<%=name%>', req: { name: { type: 'string' } } } ], needBody: true, method: 'PUT' }); /** * Perform a [indices.recovery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/indices-recovery.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.detailed - Whether to display detailed information about shard recovery * @param {Boolean} params.activeOnly - Display only those recoveries that are currently on-going * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.recovery = ca({ params: { detailed: { type: 'boolean', 'default': false }, activeOnly: { type: 'boolean', 'default': false, name: 'active_only' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/<%=index%>/_recovery', req: { index: { type: 'list' } } }, { fmt: '/_recovery' } ] }); /** * Perform a [indices.refresh](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-refresh.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.force - Force a refresh even if not required * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.refresh = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, force: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_refresh', req: { index: { type: 'list' } } }, { fmt: '/_refresh' } ], method: 'POST' }); /** * Perform a [indices.segments](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-segments.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.segments = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' } }, urls: [ { fmt: '/<%=index%>/_segments', req: { index: { type: 'list' } } }, { fmt: '/_segments' } ] }); /** * Perform a [indices.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {String, String[], Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=indices] - Return stats aggregated at cluster, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.metric - Limit the information returned the specific metrics. */ api.indices.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'list' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'indices', options: [ 'cluster', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/<%=index%>/_stats/<%=metric%>', req: { index: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/<%=index%>/_stats', req: { index: { type: 'list' } } }, { fmt: '/_stats' } ] }); /** * Perform a [indices.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-status.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {Anything} params.operationThreading - TODO: ? * @param {Boolean} params.recovery - Return information about shard recovery * @param {Boolean} params.snapshot - TODO: ? * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ api.indices.prototype.status = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, human: { type: 'boolean', 'default': false }, operationThreading: { name: 'operation_threading' }, recovery: { type: 'boolean' }, snapshot: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/_status', req: { index: { type: 'list' } } }, { fmt: '/_status' } ] }); /** * Perform a [indices.updateAliases](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/indices-aliases.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.timeout - Request timeout * @param {Date, Number} params.masterTimeout - Specify timeout for connection to master */ api.indices.prototype.updateAliases = ca({ params: { timeout: { type: 'time' }, masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_aliases' }, needBody: true, method: 'POST' }); /** * Perform a [indices.validateQuery](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-validate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.explain - Return detailed information about the error * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {Anything} params.operationThreading - TODO: ? * @param {String} params.source - The URL-encoded query definition (instead of using the request body) * @param {String} params.q - Query in the Lucene query string syntax * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types */ api.indices.prototype.validateQuery = ca({ params: { explain: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, operationThreading: { name: 'operation_threading' }, source: { type: 'string' }, q: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_validate/query', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_validate/query', req: { index: { type: 'list' } } }, { fmt: '/_validate/query' } ], method: 'POST' }); /** * Perform a [info](http://www.elasticsearch.org/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.info = ca({ url: { fmt: '/' } }); /** * Perform a [listBenchmarks](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.index - A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param {String} params.type - The name of the document type */ api.listBenchmarks = ca({ urls: [ { fmt: '/<%=index%>/<%=type%>/_bench', req: { index: { type: 'list' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_bench', req: { index: { type: 'list' } } }, { fmt: '/_bench' } ] }); /** * Perform a [mget](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-get.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.realtime - Specify whether to perform the operation in realtime or search mode * @param {Boolean} params.refresh - Refresh the shard containing the document before performing the operation * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.mget = ca({ params: { fields: { type: 'list' }, preference: { type: 'string' }, realtime: { type: 'boolean' }, refresh: { type: 'boolean' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mget', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mget', req: { index: { type: 'string' } } }, { fmt: '/_mget' } ], needBody: true, method: 'POST' }); /** * Perform a [mlt](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-more-like-this.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Number} params.boostTerms - The boost factor * @param {Number} params.maxDocFreq - The word occurrence frequency as count: words with higher occurrence in the corpus will be ignored * @param {Number} params.maxQueryTerms - The maximum query terms to be included in the generated query * @param {Number} params.maxWordLength - The minimum length of the word: longer words will be ignored * @param {Number} params.minDocFreq - The word occurrence frequency as count: words with lower occurrence in the corpus will be ignored * @param {Number} params.minTermFreq - The term frequency as percent: terms with lower occurence in the source document will be ignored * @param {Number} params.minWordLength - The minimum length of the word: shorter words will be ignored * @param {String, String[], Boolean} params.mltFields - Specific fields to perform the query against * @param {Number} params.percentTermsToMatch - How many terms have to match in order to consider the document a match (default: 0.3) * @param {String} params.routing - Specific routing value * @param {Number} params.searchFrom - The offset from which to return results * @param {String, String[], Boolean} params.searchIndices - A comma-separated list of indices to perform the query against (default: the index containing the document) * @param {String} params.searchQueryHint - The search query hint * @param {String} params.searchScroll - A scroll search request definition * @param {Number} params.searchSize - The number of documents to return (default: 10) * @param {String} params.searchSource - A specific search request definition (instead of using the request body) * @param {String} params.searchType - Specific search type (eg. `dfs_then_fetch`, `count`, etc) * @param {String, String[], Boolean} params.searchTypes - A comma-separated list of types to perform the query against (default: the same type as the document) * @param {String, String[], Boolean} params.stopWords - A list of stop words to be ignored * @param {String} params.id - The document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document (use `_all` to fetch the first document matching the ID across all types) */ api.mlt = ca({ params: { boostTerms: { type: 'number', name: 'boost_terms' }, maxDocFreq: { type: 'number', name: 'max_doc_freq' }, maxQueryTerms: { type: 'number', name: 'max_query_terms' }, maxWordLength: { type: 'number', name: 'max_word_length' }, minDocFreq: { type: 'number', name: 'min_doc_freq' }, minTermFreq: { type: 'number', name: 'min_term_freq' }, minWordLength: { type: 'number', name: 'min_word_length' }, mltFields: { type: 'list', name: 'mlt_fields' }, percentTermsToMatch: { type: 'number', name: 'percent_terms_to_match' }, routing: { type: 'string' }, searchFrom: { type: 'number', name: 'search_from' }, searchIndices: { type: 'list', name: 'search_indices' }, searchQueryHint: { type: 'string', name: 'search_query_hint' }, searchScroll: { type: 'string', name: 'search_scroll' }, searchSize: { type: 'number', name: 'search_size' }, searchSource: { type: 'string', name: 'search_source' }, searchType: { type: 'string', name: 'search_type' }, searchTypes: { type: 'list', name: 'search_types' }, stopWords: { type: 'list', name: 'stop_words' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_mlt', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [mpercolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The index of the document being count percolated to use as default * @param {String} params.type - The type of the document being percolated to use as default. */ api.mpercolate = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mpercolate', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mpercolate', req: { index: { type: 'string' } } }, { fmt: '/_mpercolate' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [msearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-multi-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to use as default * @param {String, String[], Boolean} params.type - A comma-separated list of document types to use as default */ api.msearch = ca({ params: { searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_msearch', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_msearch', req: { index: { type: 'list' } } }, { fmt: '/_msearch' } ], needBody: true, bulkBody: true, method: 'POST' }); /** * Perform a [mtermvectors](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-multi-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.ids - A comma-separated list of documents ids. You must define ids as parameter or set "ids" or "docs" in the request body * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) .Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.routing - Specific routing value. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.parent - Parent id of documents. Applies to all returned documents unless otherwise specified in body "params" or "docs". * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.mtermvectors = ca({ params: { ids: { type: 'list', required: false }, termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_mtermvectors', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_mtermvectors', req: { index: { type: 'string' } } }, { fmt: '/_mtermvectors' } ], method: 'POST' }); api.nodes = function NodesNS(transport) { this.transport = transport; }; /** * Perform a [nodes.hotThreads](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-hot-threads.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.interval - The interval for the second sampling of threads * @param {Number} params.snapshots - Number of samples of thread stacktrace (default: 10) * @param {Number} params.threads - Specify the number of threads to provide information for (default: 3) * @param {String} params.type - The type to sample (default: cpu) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.hotThreads = ca({ params: { interval: { type: 'time' }, snapshots: { type: 'number' }, threads: { type: 'number' }, type: { type: 'enum', options: [ 'cpu', 'wait', 'block' ] } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/hotthreads', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/hotthreads' } ] }); /** * Perform a [nodes.info](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-info.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.flatSettings - Return settings in flat format (default: false) * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes * @param {String, String[], Boolean} params.metric - A comma-separated list of metrics you wish returned. Leave empty to return all. */ api.nodes.prototype.info = ca({ params: { flatSettings: { type: 'boolean', name: 'flat_settings' }, human: { type: 'boolean', 'default': false } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes/<%=nodeId%>', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/<%=metric%>', req: { metric: { type: 'list', options: [ 'settings', 'os', 'process', 'jvm', 'thread_pool', 'network', 'transport', 'http', 'plugins' ] } } }, { fmt: '/_nodes' } ] }); /** * Perform a [nodes.shutdown](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-shutdown.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.delay - Set the delay for the operation (default: 1s) * @param {Boolean} params.exit - Exit the JVM as well (default: true) * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to perform the operation on; use `_local` to perform the operation on the node you're connected to, leave empty to perform the operation on all nodes */ api.nodes.prototype.shutdown = ca({ params: { delay: { type: 'time' }, exit: { type: 'boolean' } }, urls: [ { fmt: '/_cluster/nodes/<%=nodeId%>/_shutdown', req: { nodeId: { type: 'list' } } }, { fmt: '/_shutdown' } ], method: 'POST' }); /** * Perform a [nodes.stats](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/cluster-nodes-stats.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.completionFields - A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param {String, String[], Boolean} params.fielddataFields - A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param {String, String[], Boolean} params.fields - A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param {Boolean} params.groups - A comma-separated list of search groups for `search` index metric * @param {Boolean} params.human - Whether to return time and byte values in human-readable format. * @param {String} [params.level=node] - Return indices stats aggregated at node, index or shard level * @param {String, String[], Boolean} params.types - A comma-separated list of document types for the `indexing` index metric * @param {String, String[], Boolean} params.metric - Limit the information returned to the specified metrics * @param {String, String[], Boolean} params.indexMetric - Limit the information returned for `indices` metric to the specific index metrics. Isn't used if `indices` (or `all`) metric isn't specified. * @param {String, String[], Boolean} params.nodeId - A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes */ api.nodes.prototype.stats = ca({ params: { completionFields: { type: 'list', name: 'completion_fields' }, fielddataFields: { type: 'list', name: 'fielddata_fields' }, fields: { type: 'list' }, groups: { type: 'boolean' }, human: { type: 'boolean', 'default': false }, level: { type: 'enum', 'default': 'node', options: [ 'node', 'indices', 'shards' ] }, types: { type: 'list' } }, urls: [ { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats/<%=metric%>', req: { nodeId: { type: 'list' }, metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats/<%=metric%>/<%=indexMetric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] }, indexMetric: { type: 'list', options: [ '_all', 'completion', 'docs', 'fielddata', 'filter_cache', 'flush', 'get', 'id_cache', 'indexing', 'merge', 'percolate', 'refresh', 'search', 'segments', 'store', 'warmer', 'suggest' ] } } }, { fmt: '/_nodes/<%=nodeId%>/stats', req: { nodeId: { type: 'list' } } }, { fmt: '/_nodes/stats/<%=metric%>', req: { metric: { type: 'list', options: [ '_all', 'breaker', 'fs', 'http', 'indices', 'jvm', 'network', 'os', 'process', 'thread_pool', 'transport' ] } } }, { fmt: '/_nodes/stats' } ] }); /** * Perform a [percolate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-percolate.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.percolateIndex - The index to percolate the document into. Defaults to index. * @param {String} params.percolateType - The type to percolate document into. Defaults to type. * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.index - The index of the document being percolated. * @param {String} params.type - The type of the document being percolated. * @param {String} params.id - Substitute the document in the request body with a document that is known by the specified id. On top of the id, the index and type parameter will be used to retrieve the document from within the cluster. */ api.percolate = ca({ params: { routing: { type: 'list' }, preference: { type: 'string' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, percolateIndex: { type: 'string', name: 'percolate_index' }, percolateType: { type: 'string', name: 'percolate_type' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'external', 'external_gte', 'force' ], name: 'version_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/<%=id%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, { fmt: '/<%=index%>/<%=type%>/_percolate', req: { index: { type: 'string' }, type: { type: 'string' } } } ], method: 'POST' }); /** * Perform a [ping](http://www.elasticsearch.org/guide/) request * * @param {Object} params - An object with parameters used to carry out this action */ api.ping = ca({ url: { fmt: '/' }, requestTimeout: 100, method: 'HEAD' }); /** * Perform a [putScript](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Script ID * @param {String} params.lang - Script language */ api.putScript = ca({ url: { fmt: '/_scripts/<%=lang%>/<%=id%>', req: { lang: { type: 'string' }, id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [putTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.id - Template ID */ api.putTemplate = ca({ url: { fmt: '/_search/template/<%=id%>', req: { id: { type: 'string' } } }, needBody: true, method: 'PUT' }); /** * Perform a [scroll](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-request-scroll.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.scrollId - The scroll ID */ api.scroll = ca({ params: { scroll: { type: 'duration' }, scrollId: { type: 'string', name: 'scroll_id' } }, urls: [ { fmt: '/_search/scroll/<%=scrollId%>', req: { scrollId: { type: 'string' } } }, { fmt: '/_search/scroll' } ], method: 'POST' }); /** * Perform a [search](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.analyzer - The analyzer to use for the query string * @param {Boolean} params.analyzeWildcard - Specify whether wildcard and prefix queries should be analyzed (default: false) * @param {String} [params.defaultOperator=OR] - The default operator for query string query (AND or OR) * @param {String} params.df - The field to use as default where no field prefix is given in the query string * @param {Boolean} params.explain - Specify whether to return detailed information about score computation as part of a hit * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return as part of a hit * @param {Number} params.from - Starting offset (default: 0) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String, String[], Boolean} params.indicesBoost - Comma-separated list of index boosts * @param {Boolean} params.lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param {Boolean} params.lowercaseExpandedTerms - Specify whether query terms should be lowercased * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.q - Query in the Lucene query string syntax * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {Number} params.size - Number of hits to return (default: 10) * @param {String, String[], Boolean} params.sort - A comma-separated list of <field>:<direction> pairs * @param {String} params.source - The URL-encoded request definition using the Query DSL (instead of using request body) * @param {String, String[], Boolean} params._source - True or false to return the _source field or not, or a list of fields to return * @param {String, String[], Boolean} params._sourceExclude - A list of fields to exclude from the returned _source field * @param {String, String[], Boolean} params._sourceInclude - A list of fields to extract and return from the _source field * @param {String, String[], Boolean} params.stats - Specific 'tag' of the request for logging and statistical purposes * @param {String} params.suggestField - Specify which field to use for suggestions * @param {String} [params.suggestMode=missing] - Specify suggest mode * @param {Number} params.suggestSize - How many suggestions to return in response * @param {Text} params.suggestText - The source text for which the suggestions should be returned * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Boolean} params.trackScores - Whether to calculate and return scores even if they are not used for sorting * @param {Boolean} params.version - Specify whether to return document version as part of a hit * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.search = ca({ params: { analyzer: { type: 'string' }, analyzeWildcard: { type: 'boolean', name: 'analyze_wildcard' }, defaultOperator: { type: 'enum', 'default': 'OR', options: [ 'AND', 'OR' ], name: 'default_operator' }, df: { type: 'string' }, explain: { type: 'boolean' }, fields: { type: 'list' }, from: { type: 'number' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, indicesBoost: { type: 'list', name: 'indices_boost' }, lenient: { type: 'boolean' }, lowercaseExpandedTerms: { type: 'boolean', name: 'lowercase_expanded_terms' }, preference: { type: 'string' }, q: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' }, size: { type: 'number' }, sort: { type: 'list' }, source: { type: 'string' }, _source: { type: 'list' }, _sourceExclude: { type: 'list', name: '_source_exclude' }, _sourceInclude: { type: 'list', name: '_source_include' }, stats: { type: 'list' }, suggestField: { type: 'string', name: 'suggest_field' }, suggestMode: { type: 'enum', 'default': 'missing', options: [ 'missing', 'popular', 'always' ], name: 'suggest_mode' }, suggestSize: { type: 'number', name: 'suggest_size' }, suggestText: { type: 'text', name: 'suggest_text' }, timeout: { type: 'time' }, trackScores: { type: 'boolean', name: 'track_scores' }, version: { type: 'boolean' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search', req: { index: { type: 'list' } } }, { fmt: '/_search' } ], method: 'POST' }); /** * Perform a [searchShards](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-shards.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.searchShards = ca({ params: { preference: { type: 'string' }, routing: { type: 'string' }, local: { type: 'boolean' }, ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search_shards', req: { index: { type: 'string' }, type: { type: 'string' } } }, { fmt: '/<%=index%>/_search_shards', req: { index: { type: 'string' } } }, { fmt: '/_search_shards' } ], method: 'POST' }); /** * Perform a [searchTemplate](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String, String[], Boolean} params.routing - A comma-separated list of specific routing values * @param {Duration} params.scroll - Specify how long a consistent view of the index should be maintained for scrolled search * @param {String} params.searchType - Search operation type * @param {String, String[], Boolean} params.index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices * @param {String, String[], Boolean} params.type - A comma-separated list of document types to search; leave empty to perform the operation on all types */ api.searchTemplate = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'list' }, scroll: { type: 'duration' }, searchType: { type: 'enum', options: [ 'query_then_fetch', 'query_and_fetch', 'dfs_query_then_fetch', 'dfs_query_and_fetch', 'count', 'scan' ], name: 'search_type' } }, urls: [ { fmt: '/<%=index%>/<%=type%>/_search/template', req: { index: { type: 'list' }, type: { type: 'list' } } }, { fmt: '/<%=index%>/_search/template', req: { index: { type: 'list' } } }, { fmt: '/_search/template' } ], method: 'POST' }); api.snapshot = function SnapshotNS(transport) { this.transport = transport; }; /** * Perform a [snapshot.create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.create = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.createRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String} params.repository - A repository name */ api.snapshot.prototype.createRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'string' } } }, needBody: true, method: 'POST' }); /** * Perform a [snapshot.delete](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype['delete'] = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'DELETE' }); /** * Perform a [snapshot.deleteRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Date, Number} params.timeout - Explicit operation timeout * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.deleteRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, timeout: { type: 'time' } }, url: { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, method: 'DELETE' }); /** * Perform a [snapshot.get](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.get = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } } }); /** * Perform a [snapshot.getRepository](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.local - Return local information, do not retrieve the state from master node (default: false) * @param {String, String[], Boolean} params.repository - A comma-separated list of repository names */ api.snapshot.prototype.getRepository = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, local: { type: 'boolean' } }, urls: [ { fmt: '/_snapshot/<%=repository%>', req: { repository: { type: 'list' } } }, { fmt: '/_snapshot' } ] }); /** * Perform a [snapshot.restore](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {Boolean} params.waitForCompletion - Should this request wait until the operation has completed before returning * @param {String} params.repository - A repository name * @param {String} params.snapshot - A snapshot name */ api.snapshot.prototype.restore = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' }, waitForCompletion: { type: 'boolean', 'default': false, name: 'wait_for_completion' } }, url: { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_restore', req: { repository: { type: 'string' }, snapshot: { type: 'string' } } }, method: 'POST' }); /** * Perform a [snapshot.status](http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Date, Number} params.masterTimeout - Explicit operation timeout for connection to master node * @param {String} params.repository - A repository name * @param {String, String[], Boolean} params.snapshot - A comma-separated list of snapshot names */ api.snapshot.prototype.status = ca({ params: { masterTimeout: { type: 'time', name: 'master_timeout' } }, urls: [ { fmt: '/_snapshot/<%=repository%>/<%=snapshot%>/_status', req: { repository: { type: 'string' }, snapshot: { type: 'list' } } }, { fmt: '/_snapshot/<%=repository%>/_status', req: { repository: { type: 'string' } } }, { fmt: '/_snapshot/_status' } ] }); /** * Perform a [suggest](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/search-search.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.ignoreUnavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param {Boolean} params.allowNoIndices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param {String} [params.expandWildcards=open] - Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random) * @param {String} params.routing - Specific routing value * @param {String} params.source - The URL-encoded request definition (instead of using request body) * @param {String, String[], Boolean} params.index - A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices */ api.suggest = ca({ params: { ignoreUnavailable: { type: 'boolean', name: 'ignore_unavailable' }, allowNoIndices: { type: 'boolean', name: 'allow_no_indices' }, expandWildcards: { type: 'enum', 'default': 'open', options: [ 'open', 'closed' ], name: 'expand_wildcards' }, preference: { type: 'string' }, routing: { type: 'string' }, source: { type: 'string' } }, urls: [ { fmt: '/<%=index%>/_suggest', req: { index: { type: 'list' } } }, { fmt: '/_suggest' } ], needBody: true, method: 'POST' }); /** * Perform a [termvector](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-termvectors.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {Boolean} params.termStatistics - Specifies if total term frequency and document frequency should be returned. * @param {Boolean} [params.fieldStatistics=true] - Specifies if document count, sum of document frequencies and sum of total term frequencies should be returned. * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return. * @param {Boolean} [params.offsets=true] - Specifies if term offsets should be returned. * @param {Boolean} [params.positions=true] - Specifies if term positions should be returned. * @param {Boolean} [params.payloads=true] - Specifies if term payloads should be returned. * @param {String} params.preference - Specify the node or shard the operation should be performed on (default: random). * @param {String} params.routing - Specific routing value. * @param {String} params.parent - Parent id of documents. * @param {String} params.index - The index in which the document resides. * @param {String} params.type - The type of the document. * @param {String} params.id - The id of the document. */ api.termvector = ca({ params: { termStatistics: { type: 'boolean', 'default': false, required: false, name: 'term_statistics' }, fieldStatistics: { type: 'boolean', 'default': true, required: false, name: 'field_statistics' }, fields: { type: 'list', required: false }, offsets: { type: 'boolean', 'default': true, required: false }, positions: { type: 'boolean', 'default': true, required: false }, payloads: { type: 'boolean', 'default': true, required: false }, preference: { type: 'string', required: false }, routing: { type: 'string', required: false }, parent: { type: 'string', required: false } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_termvector', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [update](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-update.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String, String[], Boolean} params.fields - A comma-separated list of fields to return in the response * @param {String} params.lang - The script language (default: mvel) * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {Number} params.retryOnConflict - Specify how many times should the operation be retried when a conflict occurs (default: 0) * @param {String} params.routing - Specific routing value * @param {Anything} params.script - The URL-encoded script definition (instead of using request body) * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.update = ca({ params: { consistency: { type: 'enum', options: [ 'one', 'quorum', 'all' ] }, fields: { type: 'list' }, lang: { type: 'string' }, parent: { type: 'string' }, refresh: { type: 'boolean' }, replication: { type: 'enum', 'default': 'sync', options: [ 'sync', 'async' ] }, retryOnConflict: { type: 'number', name: 'retry_on_conflict' }, routing: { type: 'string' }, script: {}, timeout: { type: 'time' }, timestamp: { type: 'time' }, ttl: { type: 'duration' }, version: { type: 'number' }, versionType: { type: 'enum', options: [ 'internal', 'force' ], name: 'version_type' } }, url: { fmt: '/<%=index%>/<%=type%>/<%=id%>/_update', req: { index: { type: 'string' }, type: { type: 'string' }, id: { type: 'string' } } }, method: 'POST' }); /** * Perform a [create](http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/docs-index_.html) request * * @param {Object} params - An object with parameters used to carry out this action * @param {String} params.consistency - Explicit write consistency setting for the operation * @param {String} params.parent - ID of the parent document * @param {Boolean} params.refresh - Refresh the index after performing the operation * @param {String} [params.replication=sync] - Specific replication type * @param {String} params.routing - Specific routing value * @param {Date, Number} params.timeout - Explicit operation timeout * @param {Date, Number} params.timestamp - Explicit timestamp for the document * @param {Duration} params.ttl - Expiration time for the document * @param {Number} params.version - Explicit version number for concurrency control * @param {String} params.versionType - Specific version type * @param {String} params.id - Document ID * @param {String} params.index - The name of the index * @param {String} params.type - The type of the document */ api.create = ca.proxy(api.index, { transform: function (params) { params.op_type = 'create'; } });
Christopheraburns/projecttelemetry
node_modules/elasticsearch/src/lib/apis/1_3.js
JavaScript
mit
164,513
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function XLFuzzTest() { try { do { function apInitTest() { do { function apEndTest() { do { apInitTest: if (false) { return; } return; } while (false); } } while (false); } } while (false); } catch (e) {} } for (var i = 0; i < 1; i++) { XLFuzzTest(); } print("PASSED");
Microsoft/ChakraCore
test/Closures/bug_OS_9008744.js
JavaScript
mit
802
<?php $name='DejaVuSansCondensed-Bold'; $type='TTF'; $desc=array ( 'Ascent' => 928, 'Descent' => -236, 'CapHeight' => 928, 'Flags' => 262148, 'FontBBox' => '[-962 -415 1778 1174]', 'ItalicAngle' => 0, 'StemV' => 165, 'unitsPerEm' => 2048, 'MissingWidth' => 540, ); $up=-63; $ut=44; $ttffile='D:/UniServerZ/www/yii-kv/vendor/kartik-v/yii2-grid/lib/mpdf/ttfonts/DejaVuSansCondensed-Bold.ttf'; $TTCfontID='0'; $originalsize=653336; $sip=false; $smp=false; $BMPselected=true; $fontkey='dejavusanscondensedB'; $panose=' 0 0 2 b 8 6 3 6 4 2 2 4'; $haskerninfo=true; $haskernGPOS=true; $hassmallcapsGSUB=false; $useOTL=255; $rtlPUAstr='\x{0E21E}-\x{0E228}\x{0E22A}-\x{0E23B}\x{0E258}\x{0E25A}-\x{0E260}\x{0E262}\x{0E26D}-\x{0E2CE}\x{0E2DC}-\x{0E330}\x{0EF00}-\x{0EF19}'; $GSUBScriptLang=array ( 'DFLT' => 'DFLT ', 'arab' => 'DFLT KUR SND URD ', 'armn' => 'DFLT ', 'brai' => 'DFLT ', 'cans' => 'DFLT ', 'cher' => 'DFLT ', 'cyrl' => 'DFLT MKD SRB ', 'geor' => 'DFLT ', 'grek' => 'DFLT ', 'hani' => 'DFLT ', 'hebr' => 'DFLT ', 'kana' => 'DFLT ', 'lao ' => 'DFLT ', 'latn' => 'DFLT ISM KSM LSM MOL NSM ROM SKS SSM ', 'math' => 'DFLT ', 'nko ' => 'DFLT ', 'ogam' => 'DFLT ', 'runr' => 'DFLT ', 'tfng' => 'DFLT ', 'thai' => 'DFLT ', ); $GSUBFeatures=array ( 'DFLT' => array ( 'DFLT' => array ( ' RQD' => array ( 0 => 0, ), 'ccmp' => array ( 0 => 6, ), 'dlig' => array ( 0 => 21, ), ), ), 'arab' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 4, 1 => 6, ), 'fina' => array ( 0 => 9, ), 'medi' => array ( 0 => 10, ), 'init' => array ( 0 => 11, ), 'rlig' => array ( 0 => 12, 1 => 13, 2 => 14, ), 'liga' => array ( 0 => 15, 1 => 17, ), ), 'KUR ' => array ( 'ccmp' => array ( 0 => 4, 1 => 6, ), 'fina' => array ( 0 => 9, ), 'medi' => array ( 0 => 10, ), 'init' => array ( 0 => 11, ), 'rlig' => array ( 0 => 12, 1 => 13, 2 => 14, ), 'liga' => array ( 0 => 15, 1 => 17, ), ), 'SND ' => array ( 'ccmp' => array ( 0 => 4, 1 => 6, ), 'fina' => array ( 0 => 9, ), 'medi' => array ( 0 => 10, ), 'init' => array ( 0 => 11, ), 'rlig' => array ( 0 => 13, 1 => 14, ), 'liga' => array ( 0 => 15, 1 => 17, ), ), 'URD ' => array ( 'ccmp' => array ( 0 => 4, 1 => 6, ), 'fina' => array ( 0 => 9, ), 'medi' => array ( 0 => 10, ), 'init' => array ( 0 => 11, ), 'rlig' => array ( 0 => 13, 1 => 14, ), 'liga' => array ( 0 => 15, 1 => 17, ), ), ), 'armn' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), 'dlig' => array ( 0 => 18, ), ), ), 'brai' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'cans' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'cher' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'cyrl' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), ), 'MKD ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 7, ), ), 'SRB ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 7, ), ), ), 'geor' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'grek' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'aalt' => array ( 0 => 24, ), 'salt' => array ( 0 => 25, ), ), ), 'hani' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'hebr' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 4, 1 => 6, ), 'aalt' => array ( 0 => 22, ), 'salt' => array ( 0 => 23, ), ), ), 'kana' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'lao ' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'latn' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'ISM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'KSM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'LSM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'MOL ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'NSM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'ROM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'SKS ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), 'SSM ' => array ( 'ccmp' => array ( 0 => 5, 1 => 6, ), 'locl' => array ( 0 => 8, ), 'liga' => array ( 0 => 16, ), 'dlig' => array ( 0 => 19, ), 'hlig' => array ( 0 => 20, ), 'salt' => array ( 0 => 26, ), 'aalt' => array ( 0 => 27, ), ), ), 'math' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'nko ' => array ( 'DFLT' => array ( ' RQD' => array ( 0 => 0, ), 'fina' => array ( 0 => 1, ), 'medi' => array ( 0 => 2, ), 'init' => array ( 0 => 3, ), 'ccmp' => array ( 0 => 4, 1 => 6, ), ), ), 'ogam' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'runr' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'tfng' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), 'thai' => array ( 'DFLT' => array ( 'ccmp' => array ( 0 => 6, ), ), ), ); $GSUBLookups=array ( 0 => array ( 'Type' => 6, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 36644, ), 'MarkFilteringSet' => '', ), 1 => array ( 'Type' => 1, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 36768, ), 'MarkFilteringSet' => '', ), 2 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 36844, ), 'MarkFilteringSet' => '', ), 3 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 36920, ), 'MarkFilteringSet' => '', ), 4 => array ( 'Type' => 6, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 36996, ), 'MarkFilteringSet' => '', ), 5 => array ( 'Type' => 6, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 37076, ), 'MarkFilteringSet' => '', ), 6 => array ( 'Type' => 6, 'Flag' => 0, 'SubtableCount' => 10, 'Subtables' => array ( 0 => 37962, 1 => 38050, 2 => 38138, 3 => 38226, 4 => 38314, 5 => 38402, 6 => 38468, 7 => 38540, 8 => 38612, 9 => 38684, ), 'MarkFilteringSet' => '', ), 7 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 38750, ), 'MarkFilteringSet' => '', ), 8 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 38762, ), 'MarkFilteringSet' => '', ), 9 => array ( 'Type' => 1, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 38774, ), 'MarkFilteringSet' => '', ), 10 => array ( 'Type' => 1, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39032, ), 'MarkFilteringSet' => '', ), 11 => array ( 'Type' => 1, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39264, ), 'MarkFilteringSet' => '', ), 12 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39496, ), 'MarkFilteringSet' => '', ), 13 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39556, ), 'MarkFilteringSet' => '', ), 14 => array ( 'Type' => 4, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39698, ), 'MarkFilteringSet' => '', ), 15 => array ( 'Type' => 4, 'Flag' => 9, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39736, ), 'MarkFilteringSet' => '', ), 16 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39806, ), 'MarkFilteringSet' => '', ), 17 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 39866, ), 'MarkFilteringSet' => '', ), 18 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40058, ), 'MarkFilteringSet' => '', ), 19 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40134, ), 'MarkFilteringSet' => '', ), 20 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40158, ), 'MarkFilteringSet' => '', ), 21 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40182, ), 'MarkFilteringSet' => '', ), 22 => array ( 'Type' => 1, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40338, ), 'MarkFilteringSet' => '', ), 23 => array ( 'Type' => 1, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40350, ), 'MarkFilteringSet' => '', ), 24 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40362, ), 'MarkFilteringSet' => '', ), 25 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40400, ), 'MarkFilteringSet' => '', ), 26 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40438, ), 'MarkFilteringSet' => '', ), 27 => array ( 'Type' => 3, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40468, ), 'MarkFilteringSet' => '', ), 28 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40526, ), 'MarkFilteringSet' => '', ), 29 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40584, ), 'MarkFilteringSet' => '', ), 30 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40646, ), 'MarkFilteringSet' => '', ), 31 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40662, ), 'MarkFilteringSet' => '', ), 32 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40678, ), 'MarkFilteringSet' => '', ), 33 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40694, ), 'MarkFilteringSet' => '', ), 34 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40710, ), 'MarkFilteringSet' => '', ), 35 => array ( 'Type' => 1, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40726, ), 'MarkFilteringSet' => '', ), 36 => array ( 'Type' => 1, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 40752, ), 'MarkFilteringSet' => '', ), ); $GPOSScriptLang=array ( 'DFLT' => 'DFLT ', 'arab' => 'DFLT KUR SND URD ', 'armn' => 'DFLT ', 'brai' => 'DFLT ', 'cans' => 'DFLT ', 'cher' => 'DFLT ', 'cyrl' => 'DFLT MKD SRB ', 'geor' => 'DFLT ', 'grek' => 'DFLT ', 'hani' => 'DFLT ', 'hebr' => 'DFLT ', 'kana' => 'DFLT ', 'lao ' => 'DFLT ', 'latn' => 'DFLT ISM KSM LSM MOL NSM ROM SKS SSM ', 'math' => 'DFLT ', 'nko ' => 'DFLT ', 'ogam' => 'DFLT ', 'runr' => 'DFLT ', 'tfng' => 'DFLT ', 'thai' => 'DFLT ', ); $GPOSFeatures=array ( 'DFLT' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'arab' => array ( 'DFLT' => array ( 'mkmk' => array ( 0 => 0, 1 => 1, ), 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), 'KUR ' => array ( 'mkmk' => array ( 0 => 0, 1 => 1, ), 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), 'SND ' => array ( 'mkmk' => array ( 0 => 0, 1 => 1, ), 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), 'URD ' => array ( 'mkmk' => array ( 0 => 0, 1 => 1, ), 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), ), 'armn' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'brai' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'cans' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'cher' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'cyrl' => array ( 'DFLT' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 14, ), ), 'MKD ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 14, ), ), 'SRB ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 14, ), ), ), 'geor' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'grek' => array ( 'DFLT' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 14, ), ), ), 'hani' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'hebr' => array ( 'DFLT' => array ( 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), ), 'lao ' => array ( 'DFLT' => array ( 'mkmk' => array ( 0 => 2, 1 => 3, ), 'mark' => array ( 0 => 10, 1 => 11, ), 'kern' => array ( 0 => 14, ), ), ), 'latn' => array ( 'DFLT' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'ISM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'KSM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'LSM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'MOL ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'NSM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'ROM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'SKS ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), 'SSM ' => array ( 'mkmk' => array ( 0 => 4, ), 'mark' => array ( 0 => 12, ), 'kern' => array ( 0 => 13, 1 => 14, ), ), ), 'math' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'nko ' => array ( 'DFLT' => array ( 'mark' => array ( 0 => 5, 1 => 6, 2 => 7, 3 => 8, 4 => 9, ), 'kern' => array ( 0 => 14, ), ), ), 'ogam' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'runr' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'tfng' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), 'thai' => array ( 'DFLT' => array ( 'kern' => array ( 0 => 14, ), ), ), ); $GPOSLookups=array ( 0 => array ( 'Type' => 6, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 1650, ), ), 1 => array ( 'Type' => 6, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 1740, ), ), 2 => array ( 'Type' => 6, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 2204, ), ), 3 => array ( 'Type' => 6, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 2262, ), ), 4 => array ( 'Type' => 6, 'Flag' => 0, 'SubtableCount' => 2, 'Subtables' => array ( 0 => 2412, 1 => 3182, ), ), 5 => array ( 'Type' => 5, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 4392, ), ), 6 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 4766, ), ), 7 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 9996, ), ), 8 => array ( 'Type' => 5, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 10260, ), ), 9 => array ( 'Type' => 4, 'Flag' => 1, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 10728, ), ), 10 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 15940, ), ), 11 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 16256, ), ), 12 => array ( 'Type' => 4, 'Flag' => 0, 'SubtableCount' => 6, 'Subtables' => array ( 0 => 16682, 1 => 18156, 2 => 18284, 3 => 18830, 4 => 23098, 5 => 29478, ), ), 13 => array ( 'Type' => 2, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 29804, ), ), 14 => array ( 'Type' => 2, 'Flag' => 0, 'SubtableCount' => 1, 'Subtables' => array ( 0 => 35268, ), ), ); $kerninfo=array ( 45 => array ( 84 => -146, 86 => -72, 87 => -44, 88 => -81, 89 => -146, 221 => -146, 356 => -146, 376 => -146, ), 65 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 66 => array ( 86 => -40, 87 => -54, 89 => -54, 221 => -54, 372 => -54, 374 => -54, 376 => -54, 562 => -54, 7808 => -54, 7810 => -54, 7812 => -54, 7922 => -54, ), 67 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 68 => array ( 45 => 18, 89 => -72, 221 => -72, 374 => -72, 376 => -72, 562 => -72, 7922 => -72, 8218 => -17, 8222 => -17, ), 70 => array ( 44 => -160, 45 => -30, 46 => -146, 58 => -54, 59 => -54, 65 => -114, 97 => -58, 101 => -40, 111 => -40, 114 => -63, 117 => -49, 121 => -54, 192 => -114, 193 => -114, 194 => -114, 195 => -114, 196 => -114, 224 => -58, 225 => -58, 226 => -58, 227 => -58, 228 => -58, 229 => -58, 230 => -58, 232 => -40, 233 => -40, 234 => -40, 235 => -40, 242 => -40, 243 => -40, 244 => -40, 245 => -40, 246 => -40, 248 => -40, 249 => -49, 250 => -49, 251 => -49, 252 => -49, 253 => -54, 255 => -54, 256 => -114, 257 => -58, 258 => -114, 259 => -58, 260 => -114, 261 => -58, 275 => -40, 277 => -40, 279 => -40, 281 => -40, 283 => -40, 333 => -40, 335 => -40, 337 => -40, 339 => -40, 341 => -63, 343 => -63, 345 => -63, 361 => -49, 363 => -49, 365 => -49, 367 => -49, 369 => -49, 371 => -49, 375 => -54, 483 => -58, 491 => -40, 493 => -40, 559 => -40, 563 => -54, 7923 => -54, 8217 => 18, 8218 => -165, 8222 => -165, ), 71 => array ( 84 => -17, 89 => -21, 221 => -21, 356 => -17, 376 => -21, ), 75 => array ( 45 => -86, 67 => -44, 79 => -44, 85 => -17, 101 => -17, 111 => -17, 117 => -17, 121 => -63, 199 => -44, 210 => -44, 211 => -44, 212 => -44, 213 => -44, 214 => -44, 216 => -26, 217 => -17, 218 => -17, 219 => -17, 220 => -17, 232 => -17, 233 => -17, 234 => -17, 235 => -17, 242 => -17, 243 => -17, 244 => -17, 245 => -17, 246 => -17, 248 => -17, 249 => -17, 250 => -17, 251 => -17, 252 => -17, 253 => -63, 255 => -63, 262 => -44, 268 => -44, 283 => -17, 338 => -49, 339 => -17, 366 => -17, 367 => -17, 8218 => 18, 8222 => 18, ), 76 => array ( 79 => -35, 84 => -165, 85 => -35, 86 => -137, 87 => -77, 89 => -155, 121 => -67, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -35, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -155, 253 => -67, 255 => -67, 338 => -35, 356 => -165, 366 => -35, 376 => -155, 8217 => -229, 8221 => -239, ), 79 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 80 => array ( 44 => -183, 45 => -17, 46 => -183, 65 => -91, 97 => -26, 115 => -17, 121 => 18, 192 => -91, 193 => -91, 194 => -91, 195 => -91, 196 => -91, 224 => -26, 225 => -26, 226 => -26, 227 => -26, 228 => -26, 229 => -26, 230 => -26, 253 => 18, 255 => 18, 351 => -17, 353 => -17, 8217 => 27, 8218 => -202, 8221 => 18, 8222 => -202, ), 81 => array ( 45 => 18, ), 82 => array ( 44 => 18, 46 => 18, 84 => -44, 89 => -54, 121 => -44, 221 => -54, 253 => -44, 255 => -44, 356 => -44, 376 => -54, ), 83 => array ( 83 => -44, 350 => -44, 352 => -44, ), 84 => array ( 44 => -142, 45 => -146, 46 => -151, 58 => -54, 59 => -54, 65 => -77, 84 => 22, 97 => -128, 99 => -132, 101 => -132, 111 => -132, 114 => -109, 115 => -132, 117 => -109, 119 => -109, 121 => -118, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 224 => -80, 225 => -128, 226 => -80, 227 => -80, 228 => -80, 229 => -80, 230 => -95, 231 => -132, 232 => -103, 233 => -132, 234 => -103, 235 => -103, 242 => -93, 243 => -132, 244 => -93, 245 => -93, 246 => -93, 248 => -77, 249 => -95, 250 => -109, 251 => -95, 252 => -95, 253 => -118, 255 => -118, 263 => -132, 269 => -132, 283 => -132, 339 => -77, 341 => -109, 345 => -109, 351 => -132, 353 => -132, 367 => -109, 8218 => -128, 8222 => -128, ), 85 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 86 => array ( 44 => -128, 45 => -72, 46 => -128, 58 => -44, 59 => -44, 65 => -67, 79 => -17, 97 => -54, 101 => -54, 105 => -17, 111 => -54, 117 => -35, 192 => -67, 193 => -67, 194 => -67, 195 => -67, 196 => -67, 210 => -17, 211 => -17, 212 => -17, 213 => -17, 214 => -17, 216 => -17, 224 => -54, 225 => -54, 226 => -54, 227 => -54, 228 => -54, 229 => -54, 230 => -54, 232 => -54, 233 => -54, 234 => -54, 235 => -54, 242 => -54, 243 => -54, 244 => -54, 245 => -54, 246 => -54, 248 => -54, 249 => -35, 250 => -35, 251 => -35, 252 => -35, 283 => -54, 338 => -17, 339 => -54, 367 => -35, 8218 => -109, 8222 => -91, ), 87 => array ( 44 => -81, 45 => -44, 46 => -81, 58 => -30, 59 => -30, 65 => -44, 97 => -35, 101 => -35, 111 => -35, 114 => -17, 192 => -44, 193 => -44, 194 => -44, 195 => -44, 196 => -44, 224 => -35, 225 => -35, 226 => -35, 227 => -35, 228 => -35, 229 => -35, 230 => -35, 232 => -35, 233 => -35, 234 => -35, 235 => -35, 242 => -35, 243 => -35, 244 => -35, 245 => -35, 246 => -35, 248 => -35, 283 => -35, 339 => -35, 341 => -17, 345 => -17, ), 88 => array ( 45 => -81, 67 => -35, 79 => -35, 101 => -26, 199 => -35, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -35, 232 => -26, 233 => -26, 234 => -26, 235 => -26, 262 => -35, 268 => -35, 283 => -26, 338 => -35, 8218 => 18, 8222 => 18, ), 89 => array ( 44 => -165, 45 => -146, 46 => -165, 58 => -86, 59 => -86, 65 => -95, 67 => -35, 79 => -35, 97 => -91, 101 => -91, 111 => -91, 117 => -72, 192 => -95, 193 => -95, 194 => -95, 195 => -95, 196 => -95, 199 => -35, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -17, 224 => -91, 225 => -91, 226 => -91, 227 => -91, 228 => -91, 229 => -91, 230 => -91, 232 => -91, 233 => -91, 234 => -91, 235 => -91, 242 => -91, 243 => -91, 244 => -91, 245 => -91, 246 => -91, 248 => -91, 249 => -72, 250 => -72, 251 => -72, 252 => -72, 262 => -35, 268 => -35, 283 => -91, 338 => -44, 339 => -91, 367 => -72, 8218 => -183, 8222 => -146, ), 90 => array ( 45 => -17, ), 97 => array ( 121 => -30, 253 => -30, 255 => -30, ), 102 => array ( 44 => -54, 45 => -17, 46 => -54, 8217 => 68, 8221 => 41, ), 107 => array ( 101 => -26, 111 => -26, 232 => -26, 233 => -26, 234 => -26, 235 => -26, 242 => -26, 243 => -26, 244 => -26, 245 => -26, 246 => -26, 248 => -21, 283 => -26, 339 => -26, ), 114 => array ( 44 => -146, 46 => -142, 8217 => 41, 8221 => 18, ), 118 => array ( 44 => -81, 46 => -81, ), 119 => array ( 44 => -63, 46 => -63, ), 121 => array ( 44 => -77, 46 => -91, ), 192 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 193 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 194 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 195 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 196 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 198 => array ( 45 => -17, ), 199 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 208 => array ( 45 => 18, 89 => -72, 221 => -72, 374 => -72, 376 => -72, 562 => -72, 7922 => -72, 8218 => -17, 8222 => -17, ), 210 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 211 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 212 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 213 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 214 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -26, 86 => -26, 88 => -35, 89 => -35, 192 => -26, 193 => -26, 194 => -26, 195 => -26, 196 => -26, 221 => -35, 376 => -35, ), 216 => array ( 44 => -21, 45 => 18, 46 => -21, 65 => -17, 86 => -17, 88 => -35, 89 => -17, 192 => -17, 193 => -17, 194 => -17, 195 => -17, 196 => -17, 221 => -17, 376 => -17, ), 217 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 218 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 219 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 220 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 221 => array ( 44 => -165, 45 => -146, 46 => -165, 58 => -86, 59 => -86, 65 => -95, 67 => -35, 79 => -35, 97 => -91, 101 => -91, 111 => -91, 117 => -72, 192 => -95, 193 => -95, 194 => -95, 195 => -95, 196 => -95, 199 => -35, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -17, 224 => -91, 225 => -91, 226 => -91, 227 => -91, 228 => -91, 229 => -91, 230 => -91, 232 => -91, 233 => -91, 234 => -91, 235 => -91, 242 => -91, 243 => -91, 244 => -91, 245 => -91, 246 => -91, 248 => -91, 249 => -72, 250 => -72, 251 => -72, 252 => -72, 262 => -35, 268 => -35, 283 => -91, 338 => -44, 339 => -91, 367 => -72, 8218 => -183, 8222 => -146, ), 224 => array ( 121 => -30, 253 => -30, 255 => -30, ), 225 => array ( 121 => -30, 253 => -30, 255 => -30, ), 226 => array ( 121 => -30, 253 => -30, 255 => -30, ), 227 => array ( 121 => -30, 253 => -30, 255 => -30, ), 228 => array ( 121 => -30, 253 => -30, 255 => -30, ), 229 => array ( 121 => -30, 253 => -30, 255 => -30, ), 253 => array ( 44 => -77, 46 => -91, ), 255 => array ( 44 => -77, 46 => -91, ), 256 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 258 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7812 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 260 => array ( 44 => 18, 46 => 18, 58 => 18, 59 => 18, 84 => -77, 85 => -30, 86 => -67, 87 => -44, 89 => -95, 118 => -35, 121 => -35, 217 => -30, 218 => -30, 219 => -30, 220 => -30, 221 => -95, 253 => -35, 255 => -35, 354 => -77, 356 => -77, 360 => -30, 362 => -30, 364 => -30, 366 => -30, 368 => -30, 372 => -44, 374 => -95, 375 => -35, 376 => -95, 538 => -77, 562 => -95, 563 => -35, 7808 => -44, 7810 => -44, 7922 => -95, 8217 => -91, 8218 => 55, 8221 => -91, 8222 => 55, ), 262 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 264 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 266 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 268 => array ( 45 => 22, 83 => 18, 346 => 18, 348 => 18, 350 => 18, 352 => 18, 536 => 18, 8217 => 36, 8221 => 36, ), 270 => array ( 45 => 18, 89 => -72, 221 => -72, 374 => -72, 376 => -72, 562 => -72, 7922 => -72, 8218 => -17, 8222 => -17, ), 272 => array ( 45 => 18, 89 => -72, 221 => -72, 374 => -72, 376 => -72, 562 => -72, 7922 => -72, 8218 => -17, 8222 => -17, ), 286 => array ( 84 => -17, 89 => -21, 221 => -21, 356 => -17, 376 => -21, ), 313 => array ( 79 => -35, 84 => -165, 85 => -35, 86 => -137, 87 => -77, 89 => -155, 121 => -67, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -35, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -155, 253 => -67, 255 => -67, 338 => -35, 356 => -165, 366 => -35, 376 => -155, 8217 => -229, 8221 => -239, ), 317 => array ( 79 => -35, 84 => -165, 85 => -35, 86 => -137, 87 => -77, 89 => -155, 121 => -67, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -35, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -155, 253 => -67, 255 => -67, 338 => -35, 356 => -165, 366 => -35, 376 => -155, 8217 => -229, 8221 => -239, ), 320 => array ( 108 => -120, ), 321 => array ( 79 => -35, 84 => -165, 85 => -35, 86 => -137, 87 => -77, 89 => -155, 121 => -67, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -35, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -155, 253 => -67, 255 => -67, 338 => -35, 356 => -165, 366 => -35, 376 => -155, 8217 => -165, 8221 => -183, ), 340 => array ( 44 => 18, 46 => 18, 84 => -44, 89 => -54, 121 => -44, 221 => -54, 253 => -44, 255 => -44, 356 => -44, 376 => -54, ), 341 => array ( 44 => -146, 46 => -142, 8217 => 41, 8221 => 18, ), 344 => array ( 44 => 18, 46 => 18, 84 => -44, 89 => -54, 121 => -44, 221 => -54, 253 => -44, 255 => -44, 356 => -44, 376 => -54, ), 345 => array ( 44 => -146, 46 => -142, 8217 => 41, 8221 => 18, ), 350 => array ( 83 => -44, 350 => -44, 352 => -44, ), 352 => array ( 83 => -44, 350 => -44, 352 => -44, ), 356 => array ( 44 => -142, 45 => -146, 46 => -151, 58 => -54, 59 => -54, 65 => -77, 84 => 22, 97 => -128, 99 => -132, 101 => -132, 111 => -132, 114 => -109, 115 => -132, 117 => -109, 119 => -109, 121 => -118, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 224 => -128, 225 => -128, 226 => -128, 227 => -128, 228 => -128, 229 => -128, 230 => -95, 231 => -132, 232 => -132, 233 => -132, 234 => -132, 235 => -132, 242 => -132, 243 => -132, 244 => -132, 245 => -132, 246 => -132, 248 => -77, 249 => -109, 250 => -109, 251 => -109, 252 => -109, 253 => -118, 255 => -118, 263 => -132, 269 => -132, 283 => -132, 339 => -77, 341 => -109, 345 => -109, 351 => -132, 353 => -132, 356 => 22, 367 => -109, 8218 => -128, 8222 => -128, ), 366 => array ( 65 => -30, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 376 => array ( 44 => -165, 45 => -146, 46 => -165, 58 => -86, 59 => -86, 65 => -95, 67 => -35, 79 => -35, 97 => -91, 101 => -91, 111 => -91, 117 => -72, 192 => -95, 193 => -95, 194 => -95, 195 => -95, 196 => -95, 199 => -35, 210 => -35, 211 => -35, 212 => -35, 213 => -35, 214 => -35, 216 => -17, 224 => -91, 225 => -91, 226 => -91, 227 => -91, 228 => -91, 229 => -91, 230 => -91, 232 => -91, 233 => -91, 234 => -91, 235 => -91, 242 => -91, 243 => -91, 244 => -91, 245 => -91, 246 => -91, 248 => -91, 249 => -72, 250 => -72, 251 => -72, 252 => -72, 262 => -35, 268 => -35, 283 => -91, 338 => -44, 339 => -91, 367 => -72, 8218 => -183, 8222 => -146, ), 381 => array ( 45 => -17, ), 699 => array ( 65 => -114, 74 => -44, 86 => 18, 89 => 36, 192 => -114, 193 => -114, 194 => -114, 195 => -114, 196 => -114, 198 => -128, 221 => 36, 376 => 36, ), 8208 => array ( 84 => -146, 86 => -72, 87 => -44, 88 => -81, 89 => -146, 221 => -146, 356 => -146, 376 => -146, ), 8216 => array ( 65 => -114, 74 => -44, 86 => 18, 89 => 36, 192 => -114, 193 => -114, 194 => -114, 195 => -114, 196 => -114, 198 => -128, 221 => 36, 376 => 36, ), 8218 => array ( 84 => -202, 86 => -137, 87 => -104, 89 => -174, 221 => -174, 356 => -202, 376 => -174, ), 8220 => array ( 65 => -128, 74 => -44, 89 => 18, 192 => -128, 193 => -128, 194 => -128, 195 => -128, 196 => -128, 198 => -146, 221 => 18, 376 => 18, ), 8222 => array ( 84 => -202, 86 => -137, 87 => -104, 89 => -174, 221 => -174, 356 => -202, 376 => -174, ), 42788 => array ( 44 => -142, 45 => -146, 46 => -151, 58 => -54, 59 => -54, 65 => -77, 84 => 22, 97 => -128, 99 => -132, 101 => -132, 111 => -132, 114 => -109, 115 => -132, 117 => -109, 119 => -109, 121 => -118, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 224 => -80, 225 => -128, 226 => -80, 227 => -80, 228 => -80, 229 => -80, 230 => -95, 231 => -132, 232 => -103, 233 => -132, 234 => -103, 235 => -103, 242 => -93, 243 => -132, 244 => -93, 245 => -93, 246 => -93, 248 => -77, 249 => -95, 250 => -109, 251 => -95, 252 => -95, 253 => -118, 255 => -118, 263 => -132, 269 => -132, 283 => -132, 339 => -77, 341 => -109, 345 => -109, 351 => -132, 353 => -132, 367 => -109, 8218 => -128, 8222 => -128, ), 42816 => array ( 45 => -86, 67 => -44, 79 => -44, 85 => -17, 101 => -17, 111 => -17, 117 => -17, 121 => -63, 199 => -44, 210 => -44, 211 => -44, 212 => -44, 213 => -44, 214 => -44, 216 => -26, 217 => -17, 218 => -17, 219 => -17, 220 => -17, 232 => -17, 233 => -17, 234 => -17, 235 => -17, 242 => -17, 243 => -17, 244 => -17, 245 => -17, 246 => -17, 248 => -17, 249 => -17, 250 => -17, 251 => -17, 252 => -17, 253 => -63, 255 => -63, 262 => -44, 268 => -44, 283 => -17, 338 => -49, 339 => -17, 366 => -17, 367 => -17, 8218 => 18, 8222 => 18, ), 42817 => array ( 101 => -26, 111 => -26, 232 => -26, 233 => -26, 234 => -26, 235 => -26, 242 => -26, 243 => -26, 244 => -26, 245 => -26, 246 => -26, 248 => -21, 283 => -26, 339 => -26, ), 61185 => array ( 61209 => -26, ), 61186 => array ( 61209 => -50, ), 61187 => array ( 61209 => -61, ), 61188 => array ( 61209 => -66, ), 61189 => array ( 61209 => -26, ), 61191 => array ( 61209 => -26, ), 61192 => array ( 61209 => -50, ), 61193 => array ( 61209 => -61, ), 61194 => array ( 61209 => -50, ), 61195 => array ( 61209 => -26, ), 61197 => array ( 61209 => -26, ), 61198 => array ( 61209 => -50, ), 61199 => array ( 61209 => -61, ), 61200 => array ( 61209 => -50, ), 61201 => array ( 61209 => -26, ), 61203 => array ( 61209 => -26, ), 61204 => array ( 61209 => -66, ), 61205 => array ( 61209 => -61, ), 61206 => array ( 61209 => -50, ), 61207 => array ( 61209 => -26, ), ); ?>
VitalyKoynash/univer.admin
vendor/kartik-v/mpdf/ttfontdata/dejavusanscondensedB.mtx.php
PHP
mit
52,846
import { IListService, IList, IListItem } from '../services'; import { SPHttpClient, ISPHttpClientOptions, SPHttpClientResponse } from '@microsoft/sp-http'; import { IWebPartContext } from '@microsoft/sp-webpart-base'; export class ListService implements IListService { constructor(private context: IWebPartContext) { } public getLists(): Promise<IList[]> { var httpClientOptions : ISPHttpClientOptions = {}; // httpClientOptions.headers = { // 'Accept': 'application/json;odata=nometadata', // 'odata-version': '' // }; return new Promise<IList[]>((resolve: (results: IList[]) => void, reject: (error: any) => void): void => { this.context.spHttpClient.get(this.context.pageContext.web.serverRelativeUrl + `/_api/web/lists?$select=id,title`, SPHttpClient.configurations.v1, httpClientOptions ) .then((response: SPHttpClientResponse): Promise<{ value: IList[] }> => { return response.json(); }) .then((lists: { value: IList[] }): void => { resolve(lists.value); }, (error: any): void => { reject(error); }); }); } public getList(listName: string): Promise<IListItem[]> { var httpClientOptions : ISPHttpClientOptions = {}; // httpClientOptions.headers = { // 'Accept': 'application/json;odata=nometadata', // 'odata-version': '' // }; return new Promise<IListItem[]>((resolve: (results: IListItem[]) => void, reject: (error: any) => void): void => { this.context.spHttpClient.get(this.context.pageContext.web.serverRelativeUrl + `/_api/web/lists('${listName}')/items?$select=Id,Title`, SPHttpClient.configurations.v1, httpClientOptions ) .then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => { return response.json(); }) .then((listItems: { value: IListItem[] }): void => { resolve(listItems.value); }, (error: any): void => { reject(error); }); }); } }
AJIXuMuK/sp-dev-fx-webparts
samples/react-custompropertypanecontrols/src/webparts/dropdownWithRemoteData/services/ListService.ts
TypeScript
mit
2,073
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Bundle\OAuthBundle\DependencyInjection; use WellCommerce\Bundle\CoreBundle\DependencyInjection\AbstractExtension; /** * Class WellCommerceOAuthExtension * * @author Adam Piotrowski <adam@wellcommerce.org> */ class WellCommerceOAuthExtension extends AbstractExtension { }
diversantvlz/WellCommerce
src/WellCommerce/Bundle/OAuthBundle/DependencyInjection/WellCommerceOAuthExtension.php
PHP
mit
596
module.exports = { 'name': 'mad', 'category': 'Statistics', 'syntax': [ 'mad(a, b, c, ...)', 'mad(A)' ], 'description': 'Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.', 'examples': [ 'mad(10, 20, 30)', 'mad([1, 2, 3])' ], 'seealso': [ 'mean', 'median', 'std', 'abs' ] };
ocadni/citychrone
node_modules/mathjs/lib/expression/embeddedDocs/function/statistics/mad.js
JavaScript
mit
447
var HtmlWebpackPlugin = require('html-webpack-plugin') var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' }); module.exports = { entry: [ './app/index.js' ], output: { filename: "index_bundle.js", path: __dirname + '/dist' }, module: { loaders: [ {test: /\.js$/, include: __dirname + '/app', loader: "babel-loader"}, {test: /\.css$/, loader: "style-loader!css-loader"} ] }, plugins: [HTMLWebpackPluginConfig] }
absurdSquid/thumbroll
client/desktop/webpack.config.js
JavaScript
mit
548
define({ "selectAnalysisTools": "Selecione ferramentas de análise para utilizar no widget.", "graphicalDisplay": "Visualização gráfica", "toolSetting": "Configurar detalhes da ferramenta", "toolLabel": "O nome de visualização da ferramenta", "showHelpTip": "Mostrar links de ajuda no widget", "showCurrentMapExtent": "Mostrar opção para utilizar a extensão de mapa atual", "showCredits": "Exibir a opção <b>Mostrar créditos</b>", "saveAsFeatureService": "Salva o resultado na conta de usuário", "showReadyToUseLayers": "Mostrar camadas prontas para uso de Altas do Mundo em Tempo Real do ArcGIS Online", "toolNotAvailable": "Esta ferramenta não está disponível, pois o mapa não contém as camadas de feição exigidas.", "aggregatePoints": "Agregar Pontos", "aggregatePointsUsage": "Agrega os pontos em polígonos onde os pontos são localizados.", "calculateDensity": "Calcular Densidade", "calculateDensityUsage": "Cria um mapa de densidade a partir das feições de ponto ou linha ao espalhar quantidades conhecidas de algum fenômeno (representados como atributos de pontos ou linhas) ao longo do mapa.", "connectOriginsToDestinations": "Conectar Origens aos Destinos", "connectOriginsToDestinationsUsage": "Mede a distância ou tempo de percurso entre os pares de pontos.", "createBuffers": "Criar Buffers", "createBuffersUsage": "Cria polígonos de buffer a partir das feições de entrada.", "createDriveTimeAreas": "Criar Áreas de Tempo do Percurso", "createDriveTimeAreasUsage": "Cria polígonos de tempo do percurso (ou distância do percurso) ao redor dos pontos de entrada para os valores de tempo do percurso fornecidos.", "createViewshed": "Criar Panorama", "createViewshedUsage": "Cria áreas que são visíveis baseadas em locais que você especifica.", "createWatersheds": "Criar Vertentes", "createWatershedsUsage": "Cria áreas de captação baseadas em locais que você especifica.", "deriveNewLocations": "Derivar Novos Locais", "deriveNewLocationsUsage": "Deriva novas feições a partir das camadas de entrada que atenderem uma consulta que você especificar", "dissolveBoundaries": "Dissolver Limites", "dissolveBoundariesUsage": "Dissolve polígonos que sobrepõem ou compartilham um limite em comum.", "enrichLayer": "Enriquecer Camada", "enrichLayerUsage": "Enriquece feições de entrada com pessoas, lugares e fatos de negócios sobre áreas de proximidade.", "extractData": "Extrair Dados", "extractDataDesc": "Extrai dados de uma ou mais camadas dentro de uma extensão fornecida", "findExistingLocations": "Encontrar Locais Existentes", "findExistingLocationsUsage": "Seleciona feições na camada de entrada que atendem uma consulta de atributo e/ou espacial que você especificou", "findHotSpots": "Localizar Valor Alto de Incidência", "findHotSpotsUsage": "Localiza agrupamentos da feição de entrada estatísticamente significativos ou valores altos/baixos.", "findNearest": "Localizar Mais Próximo", "findNearestUsage": "Para cada feição em uma camada de entrada, localize sua feição mais próxima em outra camada", "findSimilarLocations": "Encontrar Locais Semelhantes", "findSimilarLocationsUsage": "Mede a semelhança de locais de candidatos para um ou mais locais de referência.", "interpolatePoints": "Interpolar Pontos", "interpolatePointsUsage": "Prevê valores em novos locais baseado em medidas de uma coleta de pontos.", "mergeLayers": "Juntar Camadas", "mergeLayersUsage": "Junta as feições de múltiplas camadas em uma nova camada", "overlayLayers": "Sobrepor Camadas", "overlayLayersUsage": "Combina múltiplas camadas em uma única camada com informações de camadas originais preservadas.", "planRoutes": "Planejar Rotas", "planRoutesUsage": "Determina como dividir eficazmente tarefas entre uma mão-de-obra móvel.", "summarizeNearby": "Resumir Mais Próximo", "summarizeNearbyUsage": "Para cada feição em uma camada de entrada, resuma os dados dentro de uma distância das feições em outra camada.", "summarizeWithin": "Resumir Dentro", "summarizeWithinUsage": "Para cada polígono em uma camada de polígono de entrada, resuma os dados localizados dentro dela a partir das feições em outra camada.", "traceDownstream": "Traçar Jusante", "traceDownstreamUsage": "Determina os caminhos de fluxo em uma direção da jusante a partir de locais que você especifica.", "allowToExport": "Permitir exportar os resultados" });
cmccullough2/cmv-wab-widgets
wab/2.3/widgets/Analysis/setting/nls/pt-br/strings.js
JavaScript
mit
4,520
<?php namespace Oro\Bundle\DashboardBundle\Model; use Doctrine\Common\Collections\Collection; use Oro\Bundle\OrganizationBundle\Entity\Organization; use Oro\Bundle\UserBundle\Entity\User; use Oro\Bundle\DashboardBundle\Entity\Dashboard; use Oro\Component\PhpUtils\ArrayUtil; class DashboardModel implements EntityModelInterface { const DEFAULT_TEMPLATE = 'OroDashboardBundle:Index:default.html.twig'; /** * @var Dashboard */ protected $entity; /** * @var array */ protected $config; /** * @var Collection */ protected $widgets; /** * @param Dashboard $dashboard * @param Collection $widgets * @param array $config */ public function __construct(Dashboard $dashboard, Collection $widgets, array $config) { $this->entity = $dashboard; $this->widgets = $widgets; $this->config = $config; } /** * Get dashboard config * * @return array */ public function getConfig() { return $this->config; } /** * Get dashboard entity * * @return Dashboard */ public function getEntity() { return $this->entity; } /** * Get widgets models * * @return Collection */ public function getWidgets() { return $this->widgets; } /** * Get identifier of dashboard * * @return int */ public function getId() { return $this->getEntity()->getId(); } /** * @return string */ public function getName() { return $this->getEntity()->getName(); } /** * @param string $name * @return DashboardModel */ public function setName($name) { $this->getEntity()->setName($name); return $this; } /** * @return Dashboard */ public function getStartDashboard() { return $this->getEntity()->getStartDashboard(); } /** * @param Dashboard $startDashboard * @return DashboardModel */ public function setStartDashboard(Dashboard $startDashboard) { $this->getEntity()->setStartDashboard($startDashboard); return $this; } /** * Add widget to dashboard * * @param WidgetModel $widget * @param int|null $layoutColumn * @return DashboardModel */ public function addWidget(WidgetModel $widget, $layoutColumn = null) { if (null !== $layoutColumn) { $widget->setLayoutPosition($this->getMinLayoutPosition($layoutColumn)); } $this->widgets->add($widget); $this->getEntity()->addWidget($widget->getEntity()); return $this; } /** * Get widget model by id * * @param integer $id * @return WidgetModel|null */ public function getWidgetById($id) { /** @var WidgetModel $widget */ foreach ($this->getWidgets() as $widget) { if ($widget->getId() == $id) { return $widget; } } return null; } /** * Get ordered widgets for column * * @param int $column * @param bool $appendGreater * @param bool $appendLesser * @return array */ public function getOrderedColumnWidgets($column, $appendGreater = false, $appendLesser = false) { $elements = $this->widgets->filter( function ($element) use ($column, $appendGreater, $appendLesser) { /** @var WidgetModel $element */ $actualColumn = current($element->getLayoutPosition()); return ($actualColumn == $column) || ($appendGreater && $actualColumn > $column) || ($appendLesser && $actualColumn < $column); } ); $result = $elements->getValues(); /** * We had to use stable sort to make UI consistent * independent of php version */ ArrayUtil::sortBy($result, false, 'layout_position'); return $result; } /** * Checks if dashboard has widget * * @param WidgetModel $widgetModel * @return bool */ public function hasWidget(WidgetModel $widgetModel) { return $this->getEntity()->hasWidget($widgetModel->getEntity()); } /** * @return boolean */ public function isDefault() { return $this->entity->getIsDefault(); } /** * @param boolean $isDefault * @return DashboardModel */ public function setIsDefault($isDefault) { $this->getEntity()->setIsDefault($isDefault); return $this; } /** * Get dashboard label * * @return string */ public function getLabel() { $label = $this->entity->getLabel(); return $label ? $label : (isset($this->config['label']) ? $this->config['label'] : ''); } /** * @param string $label * @return DashboardModel */ public function setLabel($label) { $this->getEntity()->setLabel($label); return $this; } /** * Get dashboard owner * * @return User */ public function getOwner() { return $this->entity->getOwner(); } /** * @param User $owner * @return DashboardModel */ public function setOwner(User $owner) { $this->getEntity()->setOwner($owner); return $this; } /** * Get dashboard organization * * @return User */ public function getOrganization() { return $this->entity->getOrganization(); } /** * @param Organization $organization * @return DashboardModel */ public function setOrganization(Organization $organization) { $this->getEntity()->setOrganization($organization); return $this; } /** * Get dashboard template * * @return string */ public function getTemplate() { $config = $this->getConfig(); return isset($config['twig']) ? $config['twig'] : self::DEFAULT_TEMPLATE; } /** * Get min layout position in passed column * * @param int $column * @return array */ protected function getMinLayoutPosition($column) { $result = array($column, 1); /** @var WidgetModel $currentWidget */ foreach ($this->getWidgets() as $currentWidget) { $position = $currentWidget->getLayoutPosition(); if ($position[0] == $result[0] && $position[1] < $result[1]) { $result = $position; } } $result[1] = $result[1] - 1; return $result; } }
Djamy/platform
src/Oro/Bundle/DashboardBundle/Model/DashboardModel.php
PHP
mit
6,782
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.manipulator.mutable.entity; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.immutable.entity.ImmutableInvisibilityData; import org.spongepowered.api.data.value.mutable.Value; import org.spongepowered.api.entity.Entity; /** * A {@link DataManipulator} for the "vanish" state. If the value is true, * the {@link Entity} is rendered "vanish". */ public interface InvisibilityData extends DataManipulator<InvisibilityData, ImmutableInvisibilityData> { /** * Gets the {@link Value} of the "invisible" state of an {@link Entity}. * * <p>Note that this is different from the {@link #vanish()} state as when an * {@link Entity} is "invisible", update packets are still sent to all clients * and the server. Likewise, no </p> * * @return The value of the invisible state */ Value<Boolean> invisible(); /** * Gets the {@link Value} of the "vanish" state of an {@link Entity}. * * @return The value of the vanish state */ Value<Boolean> vanish(); Value<Boolean> ignoresCollisionDetection(); Value<Boolean> untargetable(); }
AlphaModder/SpongeAPI
src/main/java/org/spongepowered/api/data/manipulator/mutable/entity/InvisibilityData.java
Java
mit
2,454
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Collections.Generic; using System.Reflection; namespace System.Runtime.Serialization.Formatters.Binary { // This class contains information about an object. It is used so that // the rest of the Formatter routines can use a common interface for // a normal object, an ISerializable object, and a surrogate object internal sealed class WriteObjectInfo { internal int _objectInfoId; internal object _obj; internal Type _objectType; internal bool _isSi = false; internal bool _isNamed = false; internal bool _isArray = false; internal SerializationInfo _si = null; internal SerObjectInfoCache _cache = null; internal object[] _memberData = null; internal ISerializationSurrogate _serializationSurrogate = null; internal StreamingContext _context; internal SerObjectInfoInit _serObjectInfoInit = null; // Writing and Parsing information internal long _objectId; internal long _assemId; // Binder information private string _binderTypeName; private string _binderAssemblyString; internal WriteObjectInfo() { } internal void ObjectEnd() { PutObjectInfo(_serObjectInfoInit, this); } private void InternalInit() { _obj = null; _objectType = null; _isSi = false; _isNamed = false; _isArray = false; _si = null; _cache = null; _memberData = null; // Writing and Parsing information _objectId = 0; _assemId = 0; // Binder information _binderTypeName = null; _binderAssemblyString = null; } internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit); woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder); return woi; } // Write constructor internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { _context = context; _obj = obj; _serObjectInfoInit = serObjectInfoInit; _objectType = obj.GetType(); if (_objectType.IsArray) { _isArray = true; InitNoMembers(); return; } InvokeSerializationBinder(binder); objectWriter.ObjectManager.RegisterObject(obj); ISurrogateSelector surrogateSelectorTemp; if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null) { _si = new SerializationInfo(_objectType, converter); if (!_objectType.GetTypeInfo().IsPrimitive) { _serializationSurrogate.GetObjectData(obj, _si, context); } InitSiWrite(); } else if (obj is ISerializable) { if (!_objectType.GetTypeInfo().IsSerializable) { throw new SerializationException(SR.Format(SR.Serialization_NonSerType, _objectType.FullName, _objectType.GetTypeInfo().Assembly.FullName)); } _si = new SerializationInfo(_objectType, converter); ((ISerializable)obj).GetObjectData(_si, context); InitSiWrite(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } else { InitMemberInfo(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } } internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit); woi.InitSerialize(objectType, surrogateSelector, context, serObjectInfoInit, converter, binder); return woi; } // Write Constructor used for array types or null members internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { _objectType = objectType; _context = context; _serObjectInfoInit = serObjectInfoInit; if (objectType.IsArray) { InitNoMembers(); return; } InvokeSerializationBinder(binder); ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { // surrogate does not have this problem since user has pass in through the BF's ctor _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); _isSi = true; } if (!_isSi) { InitMemberInfo(); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); } } private void InitSiWrite() { SerializationInfoEnumerator siEnum = null; _isSi = true; siEnum = _si.GetEnumerator(); int infoLength = 0; infoLength = _si.MemberCount; int count = infoLength; // For ISerializable cache cannot be saved because each object instance can have different values // BinaryWriter only puts the map on the wire if the ISerializable map cannot be reused. TypeInformation typeInformation = null; string fullTypeName = _si.FullTypeName; string assemblyString = _si.AssemblyName; bool hasTypeForwardedFrom = false; if (!_si.IsFullTypeNameSetExplicit) { typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); fullTypeName = typeInformation.FullTypeName; hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } if (!_si.IsAssemblyNameSetExplicit) { if (typeInformation == null) { typeInformation = BinaryFormatter.GetTypeInformation(_si.ObjectType); } assemblyString = typeInformation.AssemblyString; hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } _cache = new SerObjectInfoCache(fullTypeName, assemblyString, hasTypeForwardedFrom); _cache._memberNames = new string[count]; _cache._memberTypes = new Type[count]; _memberData = new object[count]; siEnum = _si.GetEnumerator(); for (int i = 0; siEnum.MoveNext(); i++) { _cache._memberNames[i] = siEnum.Name; _cache._memberTypes[i] = siEnum.ObjectType; _memberData[i] = siEnum.Value; } _isNamed = true; } private static void CheckTypeForwardedFrom(SerObjectInfoCache cache, Type objectType, string binderAssemblyString) { // nop } private void InitNoMembers() { if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerObjectInfoCache(_objectType); _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } } private void InitMemberInfo() { if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerObjectInfoCache(_objectType); _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context); int count = _cache._memberInfos.Length; _cache._memberNames = new string[count]; _cache._memberTypes = new Type[count]; // Calculate new arrays for (int i = 0; i < count; i++) { _cache._memberNames[i] = _cache._memberInfos[i].Name; _cache._memberTypes[i] = ((FieldInfo)_cache._memberInfos[i]).FieldType; } _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } if (_obj != null) { _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos); } _isNamed = true; } internal string GetTypeFullName() => _binderTypeName ?? _cache._fullTypeName; internal string GetAssemblyString() => _binderAssemblyString ?? _cache._assemblyString; private void InvokeSerializationBinder(SerializationBinder binder) => binder?.BindToName(_objectType, out _binderAssemblyString, out _binderTypeName); internal void GetMemberInfo(out string[] outMemberNames, out Type[] outMemberTypes, out object[] outMemberData) { outMemberNames = _cache._memberNames; outMemberTypes = _cache._memberTypes; outMemberData = _memberData; if (_isSi && !_isNamed) { throw new SerializationException(SR.Serialization_ISerializableMemberInfo); } } private static WriteObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit) { WriteObjectInfo objectInfo; if (!serObjectInfoInit._oiPool.IsEmpty()) { objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop(); objectInfo.InternalInit(); } else { objectInfo = new WriteObjectInfo(); objectInfo._objectInfoId = serObjectInfoInit._objectInfoIdCount++; } return objectInfo; } private static void PutObjectInfo(SerObjectInfoInit serObjectInfoInit, WriteObjectInfo objectInfo) => serObjectInfoInit._oiPool.Push(objectInfo); } internal sealed class ReadObjectInfo { internal int _objectInfoId; internal static int _readObjectInfoCounter; internal Type _objectType; internal ObjectManager _objectManager; internal int _count; internal bool _isSi = false; internal bool _isTyped = false; internal bool _isSimpleAssembly = false; internal SerObjectInfoCache _cache; internal string[] _wireMemberNames; internal Type[] _wireMemberTypes; private int _lastPosition = 0; internal ISerializationSurrogate _serializationSurrogate = null; internal StreamingContext _context; // Si Read internal List<Type> _memberTypesList; internal SerObjectInfoInit _serObjectInfoInit = null; internal IFormatterConverter _formatterConverter; internal ReadObjectInfo() { } internal void ObjectEnd() { } internal void PrepareForReuse() { _lastPosition = 0; } internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit); roi.Init(objectType, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly); return roi; } internal void Init(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { _objectType = objectType; _objectManager = objectManager; _context = context; _serObjectInfoInit = serObjectInfoInit; _formatterConverter = converter; _isSimpleAssembly = bSimpleAssembly; InitReadConstructor(objectType, surrogateSelector, context); } internal static ReadObjectInfo Create(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit); roi.Init(objectType, memberNames, memberTypes, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly); return roi; } internal void Init(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly) { _objectType = objectType; _objectManager = objectManager; _wireMemberNames = memberNames; _wireMemberTypes = memberTypes; _context = context; _serObjectInfoInit = serObjectInfoInit; _formatterConverter = converter; _isSimpleAssembly = bSimpleAssembly; if (memberTypes != null) { _isTyped = true; } if (objectType != null) { InitReadConstructor(objectType, surrogateSelector, context); } } private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context) { if (objectType.IsArray) { InitNoMembers(); return; } ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _isSi = true; } if (_isSi) { InitSiRead(); } else { InitMemberInfo(); } } private void InitSiRead() { if (_memberTypesList != null) { _memberTypesList = new List<Type>(20); } } private void InitNoMembers() { _cache = new SerObjectInfoCache(_objectType); } private void InitMemberInfo() { _cache = new SerObjectInfoCache(_objectType); _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context); _count = _cache._memberInfos.Length; _cache._memberNames = new string[_count]; _cache._memberTypes = new Type[_count]; // Calculate new arrays for (int i = 0; i < _count; i++) { _cache._memberNames[i] = _cache._memberInfos[i].Name; _cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]); } _isTyped = true; } // Get the memberInfo for a memberName internal MemberInfo GetMemberInfo(string name) { if (_cache == null) { return null; } if (_isSi) { throw new SerializationException(SR.Format(SR.Serialization_MemberInfo, _objectType + " " + name)); } if (_cache._memberInfos == null) { throw new SerializationException(SR.Format(SR.Serialization_NoMemberInfo, _objectType + " " + name)); } int position = Position(name); return position != -1 ? _cache._memberInfos[position] : null; } // Get the ObjectType for a memberName internal Type GetType(string name) { int position = Position(name); if (position == -1) { return null; } Type type = _isTyped ? _cache._memberTypes[position] : _memberTypesList[position]; if (type == null) { throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name)); } return type; } // Adds the value for a memberName internal void AddValue(string name, object value, ref SerializationInfo si, ref object[] memberData) { if (_isSi) { si.AddValue(name, value); } else { // If a member in the stream is not found, ignore it int position = Position(name); if (position != -1) { memberData[position] = value; } } } internal void InitDataStore(ref SerializationInfo si, ref object[] memberData) { if (_isSi) { if (si == null) { si = new SerializationInfo(_objectType, _formatterConverter); } } else { if (memberData == null && _cache != null) { memberData = new object[_cache._memberNames.Length]; } } } // Records an objectId in a member when the actual object for that member is not yet known internal void RecordFixup(long objectId, string name, long idRef) { if (_isSi) { _objectManager.RecordDelayedFixup(objectId, name, idRef); } else { int position = Position(name); if (position != -1) { _objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef); } } } // Fills in the values for an object internal void PopulateObjectMembers(object obj, object[] memberData) { if (!_isSi && memberData != null) { FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData); } } // Specifies the position in the memberNames array of this name private int Position(string name) { if (_cache == null) { return -1; } if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name)) { return _lastPosition; } else if ((++_lastPosition < _cache._memberNames.Length) && (_cache._memberNames[_lastPosition].Equals(name))) { return _lastPosition; } else { // Search for name for (int i = 0; i < _cache._memberNames.Length; i++) { if (_cache._memberNames[i].Equals(name)) { _lastPosition = i; return _lastPosition; } } _lastPosition = 0; return -1; } } // Return the member Types in order of memberNames internal Type[] GetMemberTypes(string[] inMemberNames, Type objectType) { if (_isSi) { throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, objectType)); } if (_cache == null) { return null; } if (_cache._memberTypes == null) { _cache._memberTypes = new Type[_count]; for (int i = 0; i < _count; i++) { _cache._memberTypes[i] = GetMemberType(_cache._memberInfos[i]); } } bool memberMissing = false; if (inMemberNames.Length < _cache._memberInfos.Length) { memberMissing = true; } Type[] outMemberTypes = new Type[_cache._memberInfos.Length]; bool isFound = false; for (int i = 0; i < _cache._memberInfos.Length; i++) { if (!memberMissing && inMemberNames[i].Equals(_cache._memberInfos[i].Name)) { outMemberTypes[i] = _cache._memberTypes[i]; } else { // MemberNames on wire in different order then memberInfos returned by reflection isFound = false; for (int j = 0; j < inMemberNames.Length; j++) { if (_cache._memberInfos[i].Name.Equals(inMemberNames[j])) { outMemberTypes[i] = _cache._memberTypes[i]; isFound = true; break; } } if (!isFound) { // A field on the type isn't found. See if the field has OptionalFieldAttribute. We only throw // when the assembly format is set appropriately. if (!_isSimpleAssembly && _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null) { throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName)); } } } } return outMemberTypes; } // Retrieves the member type from the MemberInfo internal Type GetMemberType(MemberInfo objMember) { if (objMember is FieldInfo) { return ((FieldInfo)objMember).FieldType; } throw new SerializationException(SR.Format(SR.Serialization_SerMemberInfo, objMember.GetType())); } private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit) { ReadObjectInfo roi = new ReadObjectInfo(); roi._objectInfoId = Interlocked.Increment(ref _readObjectInfoCounter); return roi; } } internal sealed class SerObjectInfoInit { internal readonly Dictionary<Type, SerObjectInfoCache> _seenBeforeTable = new Dictionary<Type, SerObjectInfoCache>(); internal int _objectInfoIdCount = 1; internal SerStack _oiPool = new SerStack("SerObjectInfo Pool"); } internal sealed class SerObjectInfoCache { internal readonly string _fullTypeName; internal readonly string _assemblyString; internal readonly bool _hasTypeForwardedFrom; internal MemberInfo[] _memberInfos; internal string[] _memberNames; internal Type[] _memberTypes; internal SerObjectInfoCache(string typeName, string assemblyName, bool hasTypeForwardedFrom) { _fullTypeName = typeName; _assemblyString = assemblyName; _hasTypeForwardedFrom = hasTypeForwardedFrom; } internal SerObjectInfoCache(Type type) { TypeInformation typeInformation = BinaryFormatter.GetTypeInformation(type); _fullTypeName = typeInformation.FullTypeName; _assemblyString = typeInformation.AssemblyString; _hasTypeForwardedFrom = typeInformation.HasTypeForwardedFrom; } } internal sealed class TypeInformation { internal TypeInformation(string fullTypeName, string assemblyString, bool hasTypeForwardedFrom) { FullTypeName = fullTypeName; AssemblyString = assemblyString; HasTypeForwardedFrom = hasTypeForwardedFrom; } internal string FullTypeName { get; } internal string AssemblyString { get; } internal bool HasTypeForwardedFrom { get; } } }
shmao/corefx
src/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs
C#
mit
26,352
#!/usr/bin/python # -*- coding: utf-8 -*- """ Magic Encode This module tries to convert an UTF-8 string to an encoded string for the printer. It uses trial and error in order to guess the right codepage. The code is based on the encoding-code in py-xml-escpos by @fvdsn. :author: `Patrick Kanzler <dev@pkanzler.de>`_ :organization: `python-escpos <https://github.com/python-escpos>`_ :copyright: Copyright (c) 2016 Patrick Kanzler and Frédéric van der Essen :license: MIT """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import bytes from .constants import CODEPAGE_CHANGE from .exceptions import Error from .codepages import CodePages import six class Encoder(object): """Takes a list of available code spaces. Picks the right one for a given character. Note: To determine the code page, it needs to do the conversion, and thus already knows what the final byte in the target encoding would be. Nevertheless, the API of this class doesn't return the byte. The caller use to do the character conversion itself. $ python -m timeit -s "{u'ö':'a'}.get(u'ö')" 100000000 loops, best of 3: 0.0133 usec per loop $ python -m timeit -s "u'ö'.encode('latin1')" 100000000 loops, best of 3: 0.0141 usec per loop """ def __init__(self, codepage_map): self.codepages = codepage_map self.available_encodings = set(codepage_map.keys()) self.available_characters = {} self.used_encodings = set() def get_sequence(self, encoding): return int(self.codepages[encoding]) def get_encoding_name(self, encoding): """Given an encoding provided by the user, will return a canonical encoding name; and also validate that the encoding is supported. TODO: Support encoding aliases: pc437 instead of cp437. """ encoding = CodePages.get_encoding_name(encoding) if encoding not in self.codepages: raise ValueError(( 'Encoding "{}" cannot be used for the current profile. ' 'Valid encodings are: {}' ).format(encoding, ','.join(self.codepages.keys()))) return encoding @staticmethod def _get_codepage_char_list(encoding): """Get codepage character list Gets characters 128-255 for a given code page, as an array. :param encoding: The name of the encoding. This must appear in the CodePage list """ codepage = CodePages.get_encoding(encoding) if 'data' in codepage: encodable_chars = list("".join(codepage['data'])) assert(len(encodable_chars) == 128) return encodable_chars elif 'python_encode' in codepage: encodable_chars = [u" "] * 128 for i in range(0, 128): codepoint = i + 128 try: encodable_chars[i] = bytes([codepoint]).decode(codepage['python_encode']) except UnicodeDecodeError: # Non-encodable character, just skip it pass return encodable_chars raise LookupError("Can't find a known encoding for {}".format(encoding)) def _get_codepage_char_map(self, encoding): """ Get codepage character map Process an encoding and return a map of UTF-characters to code points in this encoding. This is generated once only, and returned from a cache. :param encoding: The name of the encoding. """ # Skip things that were loaded previously if encoding in self.available_characters: return self.available_characters[encoding] codepage_char_list = self._get_codepage_char_list(encoding) codepage_char_map = dict((utf8, i + 128) for (i, utf8) in enumerate(codepage_char_list)) self.available_characters[encoding] = codepage_char_map return codepage_char_map def can_encode(self, encoding, char): """Determine if a character is encodeable in the given code page. :param encoding: The name of the encoding. :param char: The character to attempt to encode. """ available_map = {} try: available_map = self._get_codepage_char_map(encoding) except LookupError: return False # Decide whether this character is encodeable in this code page is_ascii = ord(char) < 128 is_encodable = char in available_map return is_ascii or is_encodable @staticmethod def _encode_char(char, charmap, defaultchar): """ Encode a single character with the given encoding map :param char: char to encode :param charmap: dictionary for mapping characters in this code page """ if ord(char) < 128: return ord(char) if char in charmap: return charmap[char] return ord(defaultchar) def encode(self, text, encoding, defaultchar='?'): """ Encode text under the given encoding :param text: Text to encode :param encoding: Encoding name to use (must be defined in capabilities) :param defaultchar: Fallback for non-encodable characters """ codepage_char_map = self._get_codepage_char_map(encoding) output_bytes = bytes([self._encode_char(char, codepage_char_map, defaultchar) for char in text]) return output_bytes def __encoding_sort_func(self, item): key, index = item return ( key in self.used_encodings, index ) def find_suitable_encoding(self, char): """The order of our search is a specific one: 1. code pages that we already tried before; there is a good chance they might work again, reducing the search space, and by re-using already used encodings we might also reduce the number of codepage change instructiosn we have to send. Still, any performance gains will presumably be fairly minor. 2. code pages in lower ESCPOS slots first. Presumably, they are more likely to be supported, so if a printer profile is missing or incomplete, we might increase our change that the code page we pick for this character is actually supported. """ sorted_encodings = sorted( self.codepages.items(), key=self.__encoding_sort_func) for encoding, _ in sorted_encodings: if self.can_encode(encoding, char): # This encoding worked; at it to the set of used ones. self.used_encodings.add(encoding) return encoding def split_writable_text(encoder, text, encoding): """Splits off as many characters from the begnning of text as are writable with "encoding". Returns a 2-tuple (writable, rest). """ if not encoding: return None, text for idx, char in enumerate(text): if encoder.can_encode(encoding, char): continue return text[:idx], text[idx:] return text, None class MagicEncode(object): """A helper that helps us to automatically switch to the right code page to encode any given Unicode character. This will consider the printers supported codepages, according to the printer profile, and if a character cannot be encoded with the current profile, it will attempt to find a suitable one. If the printer does not support a suitable code page, it can insert an error character. """ def __init__(self, driver, encoding=None, disabled=False, defaultsymbol='?', encoder=None): """ :param driver: :param encoding: If you know the current encoding of the printer when initializing this class, set it here. If the current encoding is unknown, the first character emitted will be a codepage switch. :param disabled: :param defaultsymbol: :param encoder: """ if disabled and not encoding: raise Error('If you disable magic encode, you need to define an encoding!') self.driver = driver self.encoder = encoder or Encoder(driver.profile.get_code_pages()) self.encoding = self.encoder.get_encoding_name(encoding) if encoding else None self.defaultsymbol = defaultsymbol self.disabled = disabled def force_encoding(self, encoding): """Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page. """ if not encoding: self.disabled = False else: self.write_with_encoding(encoding, None) self.disabled = True def write(self, text): """Write the text, automatically switching encodings. """ if self.disabled: self.write_with_encoding(self.encoding, text) return # See how far we can go into the text with the current encoding to_write, text = split_writable_text(self.encoder, text, self.encoding) if to_write: self.write_with_encoding(self.encoding, to_write) while text: # See if any of the code pages that the printer profile # supports can encode this character. encoding = self.encoder.find_suitable_encoding(text[0]) if not encoding: self._handle_character_failed(text[0]) text = text[1:] continue # Write as much text as possible with the encoding found. to_write, text = split_writable_text(self.encoder, text, encoding) if to_write: self.write_with_encoding(encoding, to_write) def _handle_character_failed(self, char): """Called when no codepage was found to render a character. """ # Writing the default symbol via write() allows us to avoid # unnecesary codepage switches. self.write(self.defaultsymbol) def write_with_encoding(self, encoding, text): if text is not None and type(text) is not six.text_type: raise Error("The supplied text has to be unicode, but is of type {type}.".format( type=type(text) )) # We always know the current code page; if the new codepage # is different, emit a change command. if encoding != self.encoding: self.encoding = encoding self.driver._raw( CODEPAGE_CHANGE + six.int2byte(self.encoder.get_sequence(encoding))) if text: self.driver._raw(self.encoder.encode(text, encoding))
belono/python-escpos
src/escpos/magicencode.py
Python
mit
10,963
// Type definitions for ramda 0.25 // Project: https://github.com/donnut/typescript-ramda // Definitions by: Erwin Poeze <https://github.com/donnut> // Matt DeKrey <https://github.com/mdekrey> // Matt Dziuban <https://github.com/mrdziuban> // Stephen King <https://github.com/sbking> // Alejandro Fernandez Haro <https://github.com/afharo> // Vítor Castro <https://github.com/teves-castro> // Jordan Quagliatini <https://github.com/1M0reBug> // Simon Højberg <https://github.com/hojberg> // Charles-Philippe Clermont <https://github.com/charlespwd> // Samson Keung <https://github.com/samsonkeung> // Angelo Ocana <https://github.com/angeloocana> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 declare let R: R.Static; declare namespace R { type Ord = number | string | boolean; type Path = Array<(number | string)>; interface Functor<T> { map<U>(fn: (t: T) => U): Functor<U>; } interface KeyValuePair<K, V> extends Array<K | V> { 0: K; 1: V; } interface ArrayLike { nodeType: number; } type Arity0Fn = () => any; type Arity1Fn = (a: any) => any; type Arity2Fn = (a: any, b: any) => any; interface ObjFunc { [index: string]: (...a: any[]) => any; } interface ObjFunc2 { [index: string]: (x: any, y: any) => boolean; } type Pred = (...a: any[]) => boolean; type ObjPred = (value: any, key: string) => boolean; interface Dictionary<T> { [index: string]: T; } interface CharList extends String { push(x: string): void; } interface Lens { <T, U>(obj: T): U; set<T, U>(str: string, obj: T): U; } interface Filter<T> { (list: T[]): T[]; (obj: Dictionary<T>): Dictionary<T>; } type Evolver<T> = | ((x: T) => T) | { [K in keyof T]?: Evolver<T[K]> }; // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow interface CurriedTypeGuard2<T1, T2, R extends T2> { (t1: T1): (t2: T2) => t2 is R; (t1: T1, t2: T2): t2 is R; } interface CurriedTypeGuard3<T1, T2, T3, R extends T3> { (t1: T1): CurriedTypeGuard2<T2, T3, R>; (t1: T1, t2: T2): (t3: T3) => t3 is R; (t1: T1, t2: T2, t3: T3): t3 is R; } interface CurriedTypeGuard4<T1, T2, T3, T4, R extends T4> { (t1: T1): CurriedTypeGuard3<T2, T3, T4, R>; (t1: T1, t2: T2): CurriedTypeGuard2<T3, T4, R>; (t1: T1, t2: T2, t3: T3): (t4: T4) => t4 is R; (t1: T1, t2: T2, t3: T3, t4: T4): t4 is R; } interface CurriedTypeGuard5<T1, T2, T3, T4, T5, R extends T5> { (t1: T1): CurriedTypeGuard4<T2, T3, T4, T5, R>; (t1: T1, t2: T2): CurriedTypeGuard3<T3, T4, T5, R>; (t1: T1, t2: T2, t3: T3): CurriedTypeGuard2<T4, T5, R>; (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => t5 is R; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): t5 is R; } interface CurriedTypeGuard6<T1, T2, T3, T4, T5, T6, R extends T6> { (t1: T1): CurriedTypeGuard5<T2, T3, T4, T5, T6, R>; (t1: T1, t2: T2): CurriedTypeGuard4<T3, T4, T5, T6, R>; (t1: T1, t2: T2, t3: T3): CurriedTypeGuard3<T4, T5, T6, R>; (t1: T1, t2: T2, t3: T3, t4: T4): CurriedTypeGuard2<T5, T6, R>; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => t6 is R; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): t6 is R; } interface CurriedFunction2<T1, T2, R> { (t1: T1): (t2: T2) => R; (t1: T1, t2: T2): R; } interface CurriedFunction3<T1, T2, T3, R> { (t1: T1): CurriedFunction2<T2, T3, R>; (t1: T1, t2: T2): (t3: T3) => R; (t1: T1, t2: T2, t3: T3): R; } interface CurriedFunction4<T1, T2, T3, T4, R> { (t1: T1): CurriedFunction3<T2, T3, T4, R>; (t1: T1, t2: T2): CurriedFunction2<T3, T4, R>; (t1: T1, t2: T2, t3: T3): (t4: T4) => R; (t1: T1, t2: T2, t3: T3, t4: T4): R; } interface CurriedFunction5<T1, T2, T3, T4, T5, R> { (t1: T1): CurriedFunction4<T2, T3, T4, T5, R>; (t1: T1, t2: T2): CurriedFunction3<T3, T4, T5, R>; (t1: T1, t2: T2, t3: T3): CurriedFunction2<T4, T5, R>; (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => R; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; } interface CurriedFunction6<T1, T2, T3, T4, T5, T6, R> { (t1: T1): CurriedFunction5<T2, T3, T4, T5, T6, R>; (t1: T1, t2: T2): CurriedFunction4<T3, T4, T5, T6, R>; (t1: T1, t2: T2, t3: T3): CurriedFunction3<T4, T5, T6, R>; (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction2<T5, T6, R>; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => R; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } interface Reduced { [index: number]: any; [index: string]: any; } interface Static { /** * Adds two numbers (or strings). Equivalent to a + b but curried. */ add(a: number, b: number): number; add(a: string, b: string): string; add(a: number): (b: number) => number; add(a: string): (b: string) => string; /** * Creates a new list iteration function from an existing one by adding two new parameters to its callback * function: the current index, and the entire list. */ addIndex<T, U>(fn: (f: (item: T) => U, list: T[]) => U[]): CurriedFunction2<(item: T, idx: number, list?: T[]) => U, T[], U[]>; /* Special case for forEach */ addIndex<T>(fn: (f: (item: T) => void, list: T[]) => T[]): CurriedFunction2<(item: T, idx: number, list?: T[]) => void, T[], T[]>; /* Special case for reduce */ addIndex<T, U>(fn: (f: (acc: U, item: T) => U, aci: U, list: T[]) => U): CurriedFunction3<(acc: U, item: T, idx: number, list?: T[]) => U, U, T[], U>; /** * Applies a function to the value at the given index of an array, returning a new copy of the array with the * element at the given index replaced with the result of the function application. */ adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[]; adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[]; /** * Returns true if all elements of the list match the predicate, false if there are any that don't. */ all<T>(fn: (a: T) => boolean, list: T[]): boolean; all<T>(fn: (a: T) => boolean): (list: T[]) => boolean; /** * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. */ allPass(preds: Pred[]): Pred; /** * Returns a function that always returns the given value. */ always<T>(val: T): () => T; /** * A function that returns the first argument if it's falsy otherwise the second argument. Note that this is * NOT short-circuited, meaning that if expressions are passed they are both evaluated. */ and<T extends { and?: ((...a: any[]) => any); } | number | boolean | string>(fn1: T, val2: any): boolean; and<T extends { and?: ((...a: any[]) => any); } | number | boolean | string>(fn1: T): (val2: any) => boolean; /** * Returns true if at least one of elements of the list match the predicate, false otherwise. */ any<T>(fn: (a: T) => boolean, list: T[]): boolean; any<T>(fn: (a: T) => boolean): (list: T[]) => boolean; /** * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. */ anyPass(preds: Pred[]): Pred; /** * ap applies a list of functions to a list of values. */ ap<T, U>(fns: Array<((a: T) => U)>, vs: T[]): U[]; ap<T, U>(fns: Array<((a: T) => U)>): (vs: T[]) => U[]; /** * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, * an empty list is returned. */ aperture<T>(n: number, list: T[]): T[][]; aperture(n: number): <T>(list: T[]) => T[][]; /** * Returns a new list containing the contents of the given list, followed by the given element. */ append<T>(el: T, list: T[]): T[]; append<T>(el: T): <T>(list: T[]) => T[]; /** * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from * a variadic function. fn should be a bound function if context is significant. */ apply<T, U, TResult>(fn: (arg0: T, ...args: T[]) => TResult, args: U[]): TResult; apply<T, TResult>(fn: (arg0: T, ...args: T[]) => TResult): <U>(args: U[]) => TResult; /** * Given a spec object recursively mapping properties to functions, creates a function producing an object * of the same structure, by mapping each property to the result of calling its associated function with * the supplied arguments. */ applySpec<T>(obj: any): (...args: any[]) => T; /** * Takes a value and applies a function to it. * This function is also known as the thrush combinator. */ applyTo<T, U>(el: T, fn: (t: T) => U): U; applyTo<T>(el: T): <U>(fn: (t: T) => U) => U; /** * Makes an ascending comparator function out of a function that returns a value that can be compared with < and >. */ ascend<T>(fn: (obj: T) => any, a: T, b: T): number; ascend<T>(fn: (obj: T) => any): (a: T, b: T) => number; /** * Makes a shallow clone of an object, setting or overriding the specified property with the given value. */ assoc<T, U, K extends string>(prop: K, val: T, obj: U): Record<K, T> & U; assoc<K extends string>(prop: K): <T, U>(val: T, obj: U) => Record<K, T> & U; assoc<T, K extends string>(prop: K, val: T): <U>(obj: U) => Record<K, T> & U; /** * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and * placing the specific value at the tail end of that path. */ assocPath<T, U>(path: Path, val: T, obj: U): U; assocPath<T, U>(path: Path, val: T): (obj: U) => U; assocPath<T, U>(path: Path): CurriedFunction2<T, U, U>; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 * parameters. Any extraneous parameters will not be passed to the supplied function. */ binary(fn: (...args: any[]) => any): (...a: any[]) => any; /** * Creates a function that is bound to a context. Note: R.bind does not provide the additional argument-binding * capabilities of Function.prototype.bind. */ bind<T>(thisObj: T, fn: (...args: any[]) => any): (...args: any[]) => any; /** * A function wrapping calls to the two functions in an && operation, returning the result of the first function * if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning * that the second function will not be invoked if the first returns a false-y value. */ both(pred1: Pred, pred2: Pred): Pred; both(pred1: Pred): (pred2: Pred) => Pred; /** * Returns the result of calling its first argument with the remaining arguments. This is occasionally useful * as a converging function for R.converge: the left branch can produce a function while the right branch * produces a value to be passed to that function as an argument. */ call(fn: (...args: any[]) => (...args: any[]) => any, ...args: any[]): any; /** * `chain` maps a function over a list and concatenates the results. * This implementation is compatible with the Fantasy-land Chain spec */ chain<T, U>(fn: (n: T) => U[], list: T[]): U[]; chain<T, U>(fn: (n: T) => U[]): (list: T[]) => U[]; /** * Restricts a number to be within a range. * Also works for other ordered types such as Strings and Date */ clamp<T>(min: T, max: T, value: T): T; clamp<T>(min: T, max: T): (value: T) => T; clamp<T>(min: T): (max: T, value: T) => T; clamp<T>(min: T): (max: T) => (value: T) => T; /** * Creates a deep copy of the value which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates. */ clone<T>(value: T): T; clone<T>(value: T[]): T[]; /** * Makes a comparator function out of a function that reports whether the first element is less than the second. */ // comparator(pred: (a: any, b: any) => boolean): (x: number, y: number) => number; comparator<T>(pred: (a: T, b: T) => boolean): (x: T, y: T) => number; /** * Takes a function f and returns a function g such that: * - applying g to zero or more arguments will give true if applying the same arguments to f gives * a logical false value; and * - applying g to zero or more arguments will give false if applying the same arguments to f gives * a logical true value. */ complement(pred: (...args: any[]) => boolean): (...args: any[]) => boolean; /** * Performs right-to-left function composition. The rightmost function may have any arity; the remaining * functions must be unary. */ compose<V0, T1>(fn0: (x0: V0) => T1): (x0: V0) => T1; compose<V0, V1, T1>(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; compose<V0, V1, V2, T1>(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; compose<V0, T1, T2>(fn1: (x: T1) => T2, fn0: (x0: V0) => T1): (x0: V0) => T2; compose<V0, V1, T1, T2>(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T2; compose<V0, V1, V2, T1, T2>(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T2; compose<V0, T1, T2, T3>(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T3; compose<V0, V1, T1, T2, T3>(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T3; compose<V0, V1, V2, T1, T2, T3>(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T3; compose<V0, T1, T2, T3, T4>(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T4; compose<V0, V1, T1, T2, T3, T4>(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T4; compose<V0, V1, V2, T1, T2, T3, T4>(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T4; compose<V0, T1, T2, T3, T4, T5>(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T5; compose<V0, V1, T1, T2, T3, T4, T5>(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T5; compose<V0, V1, V2, T1, T2, T3, T4, T5>(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; compose<V0, T1, T2, T3, T4, T5, T6>(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; compose<V0, V1, T1, T2, T3, T4, T5, T6>( fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; compose<V0, V1, V2, T1, T2, T3, T4, T5, T6>( fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; /** * TODO composeK */ /** * TODO composeP */ /** * Returns a new list consisting of the elements of the first list followed by the elements * of the second. */ concat<T>(list1: T[], list2: T[]): T[]; concat<T>(list1: T[]): (list2: T[]) => T[]; concat(list1: string, list2: string): string; concat(list1: string): (list2: string) => string; /** * Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. * All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which * point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates * matches, fn returns undefined. */ cond(fns: Array<[Pred, (...a: any[]) => any]>): (...a: any[]) => any; /** * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. */ construct(fn: (...a: any[]) => any): (...a: any[]) => any; /** * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. * The arity of the function returned is specified to allow using variadic constructor functions. */ constructN(n: number, fn: (...a: any[]) => any): (...a: any[]) => any; /** * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. */ contains(a: string, list: string): boolean; contains<T>(a: T, list: T[]): boolean; contains(a: string): (list: string) => boolean; contains<T>(a: T): (list: T[]) => boolean; /** * Accepts a converging function and a list of branching functions and returns a new * function. When invoked, this new function is applied to some arguments, each branching * function is applied to those same arguments. The results of each branching function * are passed as arguments to the converging function to produce the return value. */ converge(after: ((...a: any[]) => any), fns: Array<((...a: any[]) => any)>): (...a: any[]) => any; /** * Counts the elements of a list according to how many match each value * of a key generated by the supplied function. Returns an object * mapping the keys produced by `fn` to the number of occurrences in * the list. Note that all keys are coerced to strings because of how * JavaScript objects work. */ countBy<T>(fn: (a: T) => string | number, list: T[]): { [index: string]: number }; countBy<T>(fn: (a: T) => string | number): (list: T[]) => { [index: string]: number }; /** * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. * First, its arguments needn't be provided one at a time. */ curry<T1, T2, TResult extends T2>(fn: (a: T1, b: T2) => b is TResult): CurriedTypeGuard2<T1, T2, TResult>; curry<T1, T2, T3, TResult extends T3>(fn: (a: T1, b: T2, c: T3) => c is TResult): CurriedTypeGuard3<T1, T2, T3, TResult>; curry<T1, T2, T3, T4, TResult extends T4>(fn: (a: T1, b: T2, c: T3, d: T4) => d is TResult): CurriedTypeGuard4<T1, T2, T3, T4, TResult>; curry<T1, T2, T3, T4, T5, TResult extends T5>(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => e is TResult): CurriedTypeGuard5<T1, T2, T3, T4, T5, TResult>; curry<T1, T2, T3, T4, T5, T6, TResult extends T6>(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => f is TResult): CurriedTypeGuard6<T1, T2, T3, T4, T5, T6, TResult>; curry<T1, T2, TResult>(fn: (a: T1, b: T2) => TResult): CurriedFunction2<T1, T2, TResult>; curry<T1, T2, T3, TResult>(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3<T1, T2, T3, TResult>; curry<T1, T2, T3, T4, TResult>(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4<T1, T2, T3, T4, TResult>; curry<T1, T2, T3, T4, T5, TResult>(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => TResult): CurriedFunction5<T1, T2, T3, T4, T5, TResult>; curry<T1, T2, T3, T4, T5, T6, TResult>(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => TResult): CurriedFunction6<T1, T2, T3, T4, T5, T6, TResult>; curry(fn: (...a: any[]) => any): (...a: any[]) => any; /** * Returns a curried equivalent of the provided function, with the specified arity. The curried function has * two unusual capabilities. First, its arguments needn't be provided one at a time. */ curryN(length: number, fn: (...args: any[]) => any): (...a: any[]) => any; /** * Decrements its argument. */ dec(n: number): number; /** * Returns the second argument if it is not null or undefined. If it is null or undefined, the * first (default) argument is returned. */ defaultTo<T, U>(a: T, b: U): T | U; defaultTo<T>(a: T): <U>(b: U) => T | U; /** * Makes a descending comparator function out of a function that returns a value that can be compared with < and >. */ descend<T>(fn: (obj: T) => any, a: T, b: T): number; descend<T>(fn: (obj: T) => any): (a: T, b: T) => number; /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. */ difference<T>(list1: T[], list2: T[]): T[]; difference<T>(list1: T[]): (list2: T[]) => T[]; /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. * Duplication is determined according to the value returned by applying the supplied predicate to two list * elements. */ differenceWith<T>(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; /* * Returns a new object that does not contain a prop property. */ // It seems impossible to infer the return type, so this may to be specified explicitely dissoc<T>(prop: string, obj: any): T; dissoc(prop: string): <U>(obj: any) => U; /** * Makes a shallow clone of an object, omitting the property at the given path. */ dissocPath<T>(path: Path, obj: any): T; dissocPath<T>(path: Path): (obj: any) => T; /** * Divides two numbers. Equivalent to a / b. */ divide(a: number, b: number): number; divide(a: number): (b: number) => number; /** * Returns a new list containing all but the first n elements of the given list. */ drop<T>(n: number, xs: T[]): T[]; drop(n: number, xs: string): string; drop<T>(n: number): { (xs: string): string; (xs: T[]): T[]; }; /** * Returns a list containing all but the last n elements of the given list. */ dropLast<T>(n: number, xs: T[]): T[]; dropLast(n: number, xs: string): string; dropLast<T>(n: number): { (xs: T[]): T[]; (xs: string): string; }; /** * Returns a new list containing all but last then elements of a given list, passing each value from the * right to the supplied predicate function, skipping elements while the predicate function returns true. */ dropLastWhile<T>(fn: (a: T) => boolean, list: T[]): T[]; dropLastWhile<T>(fn: (a: T) => boolean): (list: T[]) => T[]; /** * Returns a new list containing the last n elements of a given list, passing each value to the supplied * predicate function, skipping elements while the predicate function returns true. */ dropWhile<T>(fn: (a: T) => boolean, list: T[]): T[]; dropWhile<T>(fn: (a: T) => boolean): (list: T[]) => T[]; /** * A function wrapping calls to the two functions in an || operation, returning the result of the first * function if it is truth-y and the result of the second function otherwise. Note that this is * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. */ either(pred1: Pred, pred2: Pred): Pred; either(pred1: Pred): (pred2: Pred) => Pred; /** * Returns the empty value of its argument's type. Ramda defines the empty value of Array ([]), Object ({}), * String (''), and Arguments. Other types are supported if they define <Type>.empty and/or <Type>.prototype.empty. * Dispatches to the empty method of the first argument, if present. */ empty<T>(x: T): T; /** * Checks if a list ends with the provided values */ endsWith(a: string, list: string): boolean; endsWith(a: string): (list: string) => boolean; endsWith<T>(a: T | T[], list: T[]): boolean; endsWith<T>(a: T | T[]): (list: T[]) => boolean; /** * Takes a function and two values in its domain and returns true if the values map to the same value in the * codomain; false otherwise. */ eqBy<T>(fn: (a: T) => T, a: T, b: T): boolean; eqBy<T>(fn: (a: T) => T, a: T): (b: T) => boolean; eqBy<T>(fn: (a: T) => T): (a: T, b: T) => boolean; eqBy<T>(fn: (a: T) => T): (a: T) => (b: T) => boolean; /** * Reports whether two functions have the same value for the specified property. */ eqProps<T, U>(prop: string, obj1: T, obj2: U): boolean; eqProps(prop: string): <T, U>(obj1: T, obj2: U) => boolean; eqProps<T>(prop: string, obj1: T): <U>(obj2: U) => boolean; /** * Returns true if its arguments are equivalent, false otherwise. Dispatches to an equals method if present. * Handles cyclical data structures. */ equals<T>(a: T, b: T): boolean; equals<T>(a: T): (b: T) => boolean; /** * Creates a new object by evolving a shallow copy of object, according to the transformation functions. */ evolve<V>(transformations: Evolver<V>, obj: V): V; evolve<V>(transformations: Evolver<V>): <W extends V>(obj: W) => W; /* * A function that always returns false. Any passed in parameters are ignored. */ F(): boolean; /** * Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value). */ filter<T>(fn: (value: T) => boolean): Filter<T>; filter<T>(fn: (value: T) => boolean, list: T[]): T[]; filter<T>(fn: (value: T) => boolean, obj: Dictionary<T>): Dictionary<T>; /** * Returns the first element of the list which matches the predicate, or `undefined` if no * element matches. */ find<T>(fn: (a: T) => boolean, list: T[]): T | undefined; find<T>(fn: (a: T) => boolean): (list: T[]) => T | undefined; /** * Returns the index of the first element of the list which matches the predicate, or `-1` * if no element matches. */ findIndex<T>(fn: (a: T) => boolean, list: T[]): number; findIndex<T>(fn: (a: T) => boolean): (list: T[]) => number; /** * Returns the last element of the list which matches the predicate, or `undefined` if no * element matches. */ findLast<T>(fn: (a: T) => boolean, list: T[]): T | undefined; findLast<T>(fn: (a: T) => boolean): (list: T[]) => T | undefined; /** * Returns the index of the last element of the list which matches the predicate, or * `-1` if no element matches. */ findLastIndex<T>(fn: (a: T) => boolean, list: T[]): number; findLastIndex<T>(fn: (a: T) => boolean): (list: T[]) => number; /** * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting * them in a new array, depth-first. */ flatten<T>(x: T[] | T[][]): T[]; /** * Returns a new function much like the supplied one, except that the first two arguments' * order is reversed. */ flip<T, U, TResult>(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult; flip<T, U, TResult>(fn: (arg0: T, arg1: U, ...args: any[]) => TResult): (arg1: U, arg0?: T, ...args: any[]) => TResult; /** * Iterate over an input list, calling a provided function fn for each element in the list. */ forEach<T>(fn: (x: T) => void, list: T[]): T[]; forEach<T>(fn: (x: T) => void): (list: T[]) => T[]; /** * Iterate over an input object, calling a provided function fn for each key and value in the object. */ forEachObjIndexed<T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void, obj: T): T; forEachObjIndexed<T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void): (obj: T) => T; /** * Creates a new object out of a list key-value pairs. */ fromPairs<V>(pairs: Array<KeyValuePair<string, V>>): { [index: string]: V }; fromPairs<V>(pairs: Array<KeyValuePair<number, V>>): { [index: number]: V }; /** * Splits a list into sublists stored in an object, based on the result of * calling a String-returning function * on each element, and grouping the results according to values returned. */ groupBy<T>(fn: (a: T) => string, list: T[]): { [index: string]: T[] }; groupBy<T>(fn: (a: T) => string): <T>(list: T[]) => { [index: string]: T[] }; /** * Takes a list and returns a list of lists where each sublist's elements are all "equal" according to the provided equality function */ groupWith<T>(fn: (x: T, y: T) => boolean, list: T[]): T[][]; groupWith<T>(fn: (x: T, y: T) => boolean, list: string): string[]; /** * Returns true if the first parameter is greater than the second. */ gt(a: number, b: number): boolean; gt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is greater than or equal to the second. */ gte(a: number, b: number): boolean; gte(a: number): (b: number) => boolean; /** * Returns whether or not an object has an own property with the specified name. */ has<T>(s: string, obj: T): boolean; has(s: string): <T>(obj: T) => boolean; /** * Returns whether or not an object or its prototype chain has a property with the specified name */ hasIn<T>(s: string, obj: T): boolean; hasIn(s: string): <T>(obj: T) => boolean; /** * Returns the first element in a list. * In some libraries this function is named `first`. */ head<T>(list: T[]): T | undefined; head(list: string): string; /** * Returns true if its arguments are identical, false otherwise. Values are identical if they reference the * same memory. NaN is identical to NaN; 0 and -0 are not identical. */ identical<T>(a: T, b: T): boolean; identical<T>(a: T): (b: T) => boolean; /** * A function that does nothing but return the parameter supplied to it. Good as a default * or placeholder function. */ identity<T>(a: T): T; /** * Creates a function that will process either the onTrue or the onFalse function depending upon the result * of the condition predicate. */ ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; /** * Increments its argument. */ inc(n: number): number; /** * Given a function that generates a key, turns a list of objects into an object indexing the objects * by the given key. */ indexBy<T, U>(fn: (a: T) => string, list: T[]): U; indexBy<T>(fn: (a: T) => string): <U>(list: T[]) => U; /** * Returns the position of the first occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. */ indexOf<T>(target: T, list: T[]): number; indexOf<T>(target: T): (list: T[]) => number; /** * Returns all but the last element of a list or string. */ init<T>(list: T[]): T[]; init(list: string): string; /** * Inserts the supplied element into the list, at index index. Note that * this is not destructive: it returns a copy of the list with the changes. */ insert<T>(index: number, elt: T, list: T[]): T[]; insert<T>(index: number, elt: T): (list: T[]) => T[]; insert(index: number): <T>(elt: T, list: T[]) => T[]; /** * Inserts the sub-list into the list, at index `index`. _Note that this * is not destructive_: it returns a copy of the list with the changes. */ insertAll<T>(index: number, elts: T[], list: T[]): T[]; insertAll<T>(index: number, elts: T[]): (list: T[]) => T[]; insertAll(index: number): <T>(elts: T[], list: T[]) => T[]; /** * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. */ intersection<T>(list1: T[], list2: T[]): T[]; intersection<T>(list1: T[]): (list2: T[]) => T[]; /** * Combines two lists into a set (i.e. no duplicates) composed of those * elements common to both lists. Duplication is determined according * to the value returned by applying the supplied predicate to two list * elements. */ intersectionWith<T>(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; /** * Creates a new list with the separator interposed between elements. */ intersperse<T>(separator: T, list: T[]): T[]; intersperse<T>(separator: T): (list: T[]) => T[]; /** * Transforms the items of the list with the transducer and appends the transformed items to the accumulator * using an appropriate iterator function based on the accumulator type. */ into<T>(acc: any, xf: (...a: any[]) => any, list: T[]): T[]; into(acc: any, xf: (...a: any[]) => any): <T>(list: T[]) => T[]; into(acc: any): <T>(xf: (...a: any[]) => any, list: T[]) => T[]; /** * Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array. */ invert<T>(obj: T): { [index: string]: string[] }; /** * Returns a new object with the keys of the given object as values, and the values of the given object as keys. */ invertObj(obj: { [index: string]: string } | { [index: number]: string }): { [index: string]: string }; /** * Turns a named method of an object (or object prototype) into a function that can be * called directly. Passing the optional `len` parameter restricts the returned function to * the initial `len` parameters of the method. * * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` * when `len` is not specified), and the final parameter is the target object. */ invoker(name: string, obj: any, len?: number): (...a: any[]) => any; invoker(name: string): (obj: any, len?: number) => (...a: any[]) => any; /** * See if an object (`val`) is an instance of the supplied constructor. * This function will check up the inheritance chain, if any. */ is(ctor: any, val: any): boolean; is(ctor: any): (val: any) => boolean; /** * Tests whether or not an object is similar to an array. */ isArrayLike(val: any): boolean; /** * Reports whether the list has zero elements. */ isEmpty(value: any): boolean; /** * Returns true if the input value is NaN. */ isNaN(x: any): boolean; /** * Checks if the input value is null or undefined. */ isNil(value: any): value is null | undefined; /** * Returns a string made by inserting the `separator` between each * element and concatenating all the elements into a single string. */ join(x: string, xs: any[]): string; join(x: string): (xs: any[]) => string; /** * Applies a list of functions to a list of values. */ juxt<T, U>(fns: Array<(...args: T[]) => U>): (...args: T[]) => U[]; /** * Returns a list containing the names of all the enumerable own * properties of the supplied object. */ keys<T>(x: T): string[]; /** * Returns a list containing the names of all the * properties of the supplied object, including prototype properties. */ keysIn<T>(obj: T): string[]; /** * Returns the last element from a list. */ last<T>(list: T[]): T | undefined; last(list: string): string; /** * Returns the position of the last occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. */ lastIndexOf<T>(target: T, list: T[]): number; /** * Returns the number of elements in the array by returning list.length. */ length(list: any[]): number; /** * Returns a lens for the given getter and setter functions. The getter * "gets" the value of the focus; the setter "sets" the value of the focus. * The setter should not mutate the data structure. */ lens<T, U, V>(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens; /** * Creates a lens that will focus on index n of the source array. */ lensIndex(n: number): Lens; /** * Returns a lens whose focus is the specified path. * See also view, set, over. */ lensPath(path: Path): Lens; /** * lensProp creates a lens that will focus on property k of the source object. */ lensProp(str: string): { <T, U>(obj: T): U; set<T, U, V>(val: T, obj: U): V; /*map<T>(fn: (...a: any[]) => any, obj: T): T*/ }; /** * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies * the FantasyLand Apply spec. */ lift(fn: ((...a: any[]) => any), ...args: any[]): any; /** * "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other * objects that satisfy the FantasyLand Apply spec. */ liftN(n: number, fn: ((...a: any[]) => any), ...args: any[]): any; /** * Returns true if the first parameter is less than the second. */ lt(a: number, b: number): boolean; lt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is less than or equal to the second. */ lte(a: number, b: number): boolean; lte(a: number): (b: number) => boolean; /** * Returns a new list, constructed by applying the supplied function to every element of the supplied list. */ map<T, U>(fn: (x: T) => U, list: T[]): U[]; map<T, U>(fn: (x: T) => U, obj: Functor<T>): Functor<U>; // used in functors map<T, U>(fn: (x: T) => U): (list: T[]) => U[]; map<T extends object, U extends {[P in keyof T]: U[P]}>(fn: (x: T[keyof T]) => U[keyof T], obj: T): U; map<T extends object, U extends {[P in keyof T]: U[P]}>(fn: (x: T[keyof T]) => U[keyof T]): (obj: T) => U; /** * The mapAccum function behaves like a combination of map and reduce. */ mapAccum<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; mapAccum<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; mapAccum<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; /** * The mapAccumRight function behaves like a combination of map and reduce. */ mapAccumRight<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; mapAccumRight<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; mapAccumRight<T, U, TResult>(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; /** * Like mapObj, but but passes additional arguments to the predicate function. */ mapObjIndexed<T, TResult>(fn: (value: T, key: string, obj?: any) => TResult, obj: any): { [index: string]: TResult }; mapObjIndexed<T, TResult>(fn: (value: T, key: string, obj?: any) => TResult): (obj: any) => { [index: string]: TResult }; /** * Tests a regular expression agains a String */ match(regexp: RegExp, str: string): any[]; match(regexp: RegExp): (str: string) => any[]; /** * mathMod behaves like the modulo operator should mathematically, unlike the `%` * operator (and by extension, R.modulo). So while "-17 % 5" is -2, * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. */ mathMod(a: number, b: number): number; mathMod(a: number): (b: number) => number; /** * Returns the larger of its two arguments. */ max<T extends Ord>(a: T, b: T): T; max<T extends Ord>(a: T): (b: T) => T; /** * Takes a function and two values, and returns whichever value produces * the larger result when passed to the provided function. */ maxBy<T>(keyFn: (a: T) => Ord, a: T, b: T): T; maxBy<T>(keyFn: (a: T) => Ord, a: T): (b: T) => T; maxBy<T>(keyFn: (a: T) => Ord): CurriedFunction2<T, T, T>; /** * Returns the mean of the given list of numbers. */ mean(list: number[]): number; /** * Returns the median of the given list of numbers. */ median(list: number[]): number; /** * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an * additional call to fn; instead, the cached result for that set of arguments will be returned. */ memoize<T = any>(fn: (...a: any[]) => T): (...a: any[]) => T; /** * Create a new object with the own properties of a * merged with the own properties of object b. * This function will *not* mutate passed-in objects. */ merge<T1, T2>(a: T1, b: T2): T1 & T2; merge<T1>(a: T1): <T2>(b: T2) => T1 & T2; /** * Merges a list of objects together into one object. */ mergeAll<T>(list: any[]): T; /** * Creates a new object with the own properties of the first object merged with the own properties of the second object. * If a key exists in both objects: * and both values are objects, the two values will be recursively merged * otherwise the value from the first object will be used. */ mergeDeepLeft<T1, T2>(a: T1, b: T2): T1 & T2; mergeDeepLeft<T1>(a: T1): <T2>(b: T2) => T1 & T2; /** * Creates a new object with the own properties of the first object merged with the own properties of the second object. * If a key exists in both objects: * and both values are objects, the two values will be recursively merged * otherwise the value from the second object will be used. */ mergeDeepRight<A, B>(a: A, b: B): A & B; mergeDeepRight<A>(a: A): <B>(b: B) => A & B; /** * Creates a new object with the own properties of the two provided objects. If a key exists in both objects: * and both associated values are also objects then the values will be recursively merged. * otherwise the provided function is applied to associated values using the resulting value as the new value * associated with the key. If a key only exists in one object, the value will be associated with the key of the resulting object. */ mergeDeepWith<T1, T2>(fn: (x: any, z: any) => any, a: T1, b: T2): T1 & T2; mergeDeepWith<T1, T2>(fn: (x: any, z: any) => any, a: T1): (b: T2) => T1 & T2; mergeDeepWith<T1, T2>(fn: (x: any, z: any) => any): (a: T1, b: T2) => T1 & T2; /** * Creates a new object with the own properties of the two provided objects. If a key exists in both objects: * and both associated values are also objects then the values will be recursively merged. * otherwise the provided function is applied to the key and associated values using the resulting value as * the new value associated with the key. If a key only exists in one object, the value will be associated with * the key of the resulting object. */ mergeDeepWithKey<T1, T2>(fn: (k: string, x: any, z: any) => any, a: T1, b: T2): T1 & T2; mergeDeepWithKey<T1, T2>(fn: (k: string, x: any, z: any) => any, a: T1): (b: T2) => T1 & T2; mergeDeepWithKey<T1, T2>(fn: (k: string, x: any, z: any) => any): (a: T1, b: T2) => T1 & T2; /** * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, * the provided function is applied to the values associated with the key in each object, with the result being used as * the value associated with the key in the returned object. The key will be excluded from the returned object if the * resulting value is undefined. */ mergeWith<U, V>(fn: (x: any, z: any) => any, a: U, b: V): U & V; mergeWith<U>(fn: (x: any, z: any) => any, a: U): <V>(b: V) => U & V; mergeWith(fn: (x: any, z: any) => any): <U, V>(a: U, b: V) => U & V; /** * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, * the provided function is applied to the key and the values associated with the key in each object, with the * result being used as the value associated with the key in the returned object. The key will be excluded from * the returned object if the resulting value is undefined. */ mergeWithKey<U, V>(fn: (str: string, x: any, z: any) => any, a: U, b: V): U & V; mergeWithKey<U>(fn: (str: string, x: any, z: any) => any, a: U): <V>(b: V) => U & V; mergeWithKey(fn: (str: string, x: any, z: any) => any): <U, V>(a: U, b: V) => U & V; /** * Returns the smaller of its two arguments. */ min<T extends Ord>(a: T, b: T): T; min<T extends Ord>(a: T): (b: T) => T; /** * Takes a function and two values, and returns whichever value produces * the smaller result when passed to the provided function. */ minBy<T>(keyFn: (a: T) => Ord, a: T, b: T): T; minBy<T>(keyFn: (a: T) => Ord, a: T): (b: T) => T; minBy<T>(keyFn: (a: T) => Ord): CurriedFunction2<T, T, T>; /** * Divides the second parameter by the first and returns the remainder. * The flipped version (`moduloBy`) may be more useful curried. * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` */ modulo(a: number, b: number): number; modulo(a: number): (b: number) => number; /** * Multiplies two numbers. Equivalent to a * b but curried. */ multiply(a: number, b: number): number; multiply(a: number): (b: number) => number; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. * Any extraneous parameters will not be passed to the supplied function. */ nAry(n: number, fn: (...arg: any[]) => any): (...a: any[]) => any; nAry(n: number): (fn: (...arg: any[]) => any) => (...a: any[]) => any; /** * Negates its argument. */ negate(n: number): number; /** * Returns true if no elements of the list match the predicate, false otherwise. */ none<T>(fn: (a: T) => boolean, list: T[]): boolean; none<T>(fn: (a: T) => boolean): (list: T[]) => boolean; /** * A function wrapping a call to the given function in a `!` operation. It will return `true` when the * underlying function would return a false-y value, and `false` when it would return a truth-y one. */ not(value: any): boolean; /** * Returns the nth element in a list. */ nth<T>(n: number, list: T[]): T; nth(n: number): <T>(list: T[]) => T; /** * Returns a function which returns its nth argument. */ nthArg(n: number): (...a: any[]) => any; /** * Creates an object containing a single key:value pair. */ objOf<T, K extends string>(key: K, value: T): Record<K, T>; objOf<K extends string>(key: K): <T>(value: T) => Record<K, T>; /** * Returns a singleton array containing the value provided. */ of<T>(x: T): T[]; /** * Returns a partial copy of an object omitting the keys specified. */ omit<T>(names: string[], obj: T): T; omit(names: string[]): <T>(obj: T) => T; /** * Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be * called once, no matter how many times the returned function is invoked. The first value calculated is * returned in subsequent invocations. */ once(fn: (...a: any[]) => any): (...a: any[]) => any; once<T>(fn: (...a: any[]) => T): (...a: any[]) => T; /** * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is * NOT short-circuited, meaning that if expressions are passed they are both evaluated. * Dispatches to the or method of the first argument if applicable. */ or<T, U>(a: T, b: U): T | U; or<T>(a: T): <U>(b: U) => T | U; or<T extends { or?: ((...a: any[]) => any); }, U>(fn1: T, val2: U): T | U; or<T extends { or?: ((...a: any[]) => any); }>(fn1: T): <U>(val2: U) => T | U; /** * Returns the result of "setting" the portion of the given data structure * focused by the given lens to the given value. */ over<T>(lens: Lens, fn: Arity1Fn, value: T): T; over<T>(lens: Lens, fn: Arity1Fn, value: T[]): T[]; over(lens: Lens, fn: Arity1Fn): <T>(value: T) => T; over(lens: Lens, fn: Arity1Fn): <T>(value: T[]) => T[]; over(lens: Lens): <T>(fn: Arity1Fn, value: T) => T; over(lens: Lens): <T>(fn: Arity1Fn, value: T[]) => T[]; /** * Takes two arguments, fst and snd, and returns [fst, snd]. */ pair<F, S>(fst: F, snd: S): [F, S]; /** * Takes a function `f` and a list of arguments, and returns a function `g`. * When applied, `g` returns the result of applying `f` to the arguments * provided initially followed by the arguments provided to `g`. */ partial<T>(fn: (...a: any[]) => T, args: any[]): (...a: any[]) => T; /** * Takes a function `f` and a list of arguments, and returns a function `g`. * When applied, `g` returns the result of applying `f` to the arguments * provided to `g` followed by the arguments provided initially. */ partialRight<T>(fn: (...a: any[]) => T, args: any[]): (...a: any[]) => T; /** * Takes a predicate and a list and returns the pair of lists of elements * which do and do not satisfy the predicate, respectively. */ partition(fn: (a: string) => boolean, list: string[]): string[][]; partition<T>(fn: (a: T) => boolean, list: T[]): T[][]; partition<T>(fn: (a: T) => boolean): (list: T[]) => T[][]; partition(fn: (a: string) => boolean): (list: string[]) => string[][]; /** * Retrieve the value at a given path. */ path<T>(path: Path, obj: any): T; path<T>(path: Path): (obj: any) => T; /** * Determines whether a nested path on an object has a specific value, * in `R.equals` terms. Most likely used to filter a list. */ pathEq(path: Path, val: any, obj: any): boolean; pathEq(path: Path, val: any): (obj: any) => boolean; pathEq(path: Path): CurriedFunction2<any, any, boolean>; /** * If the given, non-null object has a value at the given path, returns the value at that path. * Otherwise returns the provided default value. */ pathOr<T>(defaultValue: T, path: Path, obj: any): any; pathOr<T>(defaultValue: T, path: Path): (obj: any) => any; pathOr<T>(defaultValue: T): CurriedFunction2<Path, any, any>; /** * Returns true if the specified object property at given path satisfies the given predicate; false otherwise. */ pathSatisfies<T, U>(pred: (val: T) => boolean, path: Path, obj: U): boolean; pathSatisfies<T, U>(pred: (val: T) => boolean, path: Path): (obj: U) => boolean; pathSatisfies<T, U>(pred: (val: T) => boolean): CurriedFunction2<Path, U, boolean>; /** * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the * property is ignored. */ pick<T, K extends keyof T>(names: Array<K | string>, obj: T): Pick<T, K>; pick(names: string[]): <T, U>(obj: T) => U; /** * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. */ pickAll<T, U>(names: string[], obj: T): U; pickAll(names: string[]): <T, U>(obj: T) => U; /** * Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. */ pickBy<T, U>(pred: ObjPred, obj: T): U; pickBy(pred: ObjPred): <T, U>(obj: T) => U; /** * Creates a new function that runs each of the functions supplied as parameters in turn, * passing the return value of each function invocation to the next function invocation, * beginning with whatever arguments were passed to the initial invocation. */ pipe<V0, T1>(fn0: (x0: V0) => T1): (x0: V0) => T1; pipe<V0, V1, T1>(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; pipe<V0, V1, V2, T1>(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; pipe<V0, T1, T2>(fn0: (x0: V0) => T1, fn1: (x: T1) => T2): (x0: V0) => T2; pipe<V0, V1, T1, T2>(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1) => T2; pipe<V0, V1, V2, T1, T2>(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1, x2: V2) => T2; pipe<V0, T1, T2, T3>(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x: V0) => T3; pipe<V0, V1, T1, T2, T3>(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1) => T3; pipe<V0, V1, V2, T1, T2, T3>(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1, x2: V2) => T3; pipe<V0, T1, T2, T3, T4>(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x: V0) => T4; pipe<V0, V1, T1, T2, T3, T4>(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1) => T4; pipe<V0, V1, V2, T1, T2, T3, T4>(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1, x2: V2) => T4; pipe<V0, T1, T2, T3, T4, T5>(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x: V0) => T5; pipe<V0, V1, T1, T2, T3, T4, T5>(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1) => T5; pipe<V0, V1, V2, T1, T2, T3, T4, T5>(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1, x2: V2) => T5; pipe<V0, T1, T2, T3, T4, T5, T6>(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; pipe<V0, V1, T1, T2, T3, T4, T5, T6>(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; pipe<V0, V1, V2, T1, T2, T3, T4, T5, T6>( fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; pipe<V0, T1, T2, T3, T4, T5, T6, T7>( fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn: (x: T6) => T7): (x: V0) => T7; pipe<V0, V1, T1, T2, T3, T4, T5, T6, T7>( fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; pipe<V0, V1, V2, T1, T2, T3, T4, T5, T6, T7>( fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; pipe<V0, T1, T2, T3, T4, T5, T6, T7, T8>( fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn: (x: T7) => T8): (x: V0) => T8; pipe<V0, V1, T1, T2, T3, T4, T5, T6, T7, T8>( fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; pipe<V0, V1, V2, T1, T2, T3, T4, T5, T6, T7, T8>( fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; pipe<V0, T1, T2, T3, T4, T5, T6, T7, T8, T9>( fn0: (x0: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9): (x0: V0) => T9; pipe<V0, V1, T1, T2, T3, T4, T5, T6, T7, T8, T9>( fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9): (x0: V0, x1: V1) => T9; pipe<V0, V1, V2, T1, T2, T3, T4, T5, T6, T7, T8, T9>( fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9): (x0: V0, x1: V1, x2: V2) => T9; pipe<V0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( fn0: (x0: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9, fn9: (x: T9) => T10): (x0: V0) => T10; pipe<V0, V1, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9, fn9: (x: T9) => T10): (x0: V0, x1: V1) => T10; pipe<V0, V1, V2, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn7: (x: T7) => T8, fn8: (x: T8) => T9, fn9: (x: T9) => T10): (x0: V0, x1: V1, x2: V2) => T10; /** * Returns a new list by plucking the same named property off all objects in the list supplied. */ pluck<P extends string, T>(p: P, list: Array<Record<P, T>>): T[]; pluck<T>(p: number, list: Array<{ [k: number]: T }>): T[]; pluck<P extends string>(p: P): <T>(list: Array<Record<P, T>>) => T[]; pluck(p: number): <T>(list: Array<{ [k: number]: T }>) => T[]; /** * Returns a new list with the given element at the front, followed by the contents of the * list. */ prepend<T>(el: T, list: T[]): T[]; prepend<T>(el: T): (list: T[]) => T[]; /** * Multiplies together all the elements of a list. */ product(list: number[]): number; /** * Reasonable analog to SQL `select` statement. */ project<T, U>(props: string[], objs: T[]): U[]; /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. * Note: TS1.9 # replace any by dictionary */ prop<P extends string, T>(p: P, obj: Record<P, T>): T; prop<P extends string>(p: P): <T>(obj: Record<P, T>) => T; /** * Determines whether the given property of an object has a specific * value according to strict equality (`===`). Most likely used to * filter a list. */ // propEq<T>(name: string, val: T, obj: {[index:string]: T}): boolean; // propEq<T>(name: string, val: T, obj: {[index:number]: T}): boolean; propEq<T>(name: string, val: T, obj: any): boolean; // propEq<T>(name: number, val: T, obj: any): boolean; propEq<T>(name: string, val: T): (obj: any) => boolean; // propEq<T>(name: number, val: T): (obj: any) => boolean; propEq(name: string): <T>(val: T, obj: any) => boolean; // propEq(name: number): <T>(val: T, obj: any) => boolean; /** * Returns true if the specified object property is of the given type; false otherwise. */ propIs(type: any, name: string, obj: any): boolean; propIs(type: any, name: string): (obj: any) => boolean; propIs(type: any): { (name: string, obj: any): boolean; (name: string): (obj: any) => boolean; }; /** * If the given, non-null object has an own property with the specified name, returns the value of that property. * Otherwise returns the provided default value. */ propOr<T, U, V>(val: T, p: string, obj: U): V; propOr<T>(val: T, p: string): <U, V>(obj: U) => V; propOr<T>(val: T): <U, V>(p: string, obj: U) => V; /** * Returns the value at the specified property. * The only difference from `prop` is the parameter order. * Note: TS1.9 # replace any by dictionary */ props<P extends string, T>(ps: P[], obj: Record<P, T>): T[]; props<P extends string>(ps: P[]): <T>(obj: Record<P, T>) => T[]; /** * Returns true if the specified object property satisfies the given predicate; false otherwise. */ propSatisfies<T, U>(pred: (val: T) => boolean, name: string, obj: U): boolean; propSatisfies<T, U>(pred: (val: T) => boolean, name: string): (obj: U) => boolean; propSatisfies<T, U>(pred: (val: T) => boolean): CurriedFunction2<string, U, boolean>; /** * Returns a list of numbers from `from` (inclusive) to `to` * (exclusive). In mathematical terms, `range(a, b)` is equivalent to * the half-open interval `[a, b)`. */ range(from: number, to: number): number[]; range(from: number): (to: number) => number[]; /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. */ reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced, acc: TResult, list: T[]): TResult; reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced): (acc: TResult, list: T[]) => TResult; reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced, acc: TResult): (list: T[]) => TResult; /** * Groups the elements of the list according to the result of calling the String-returning function keyFn on each * element and reduces the elements of each group to a single value via the reducer function valueFn. */ reduceBy<T, TResult>(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string, list: T[]): { [index: string]: TResult }; reduceBy<T, TResult>(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string): (list: T[]) => { [index: string]: TResult }; reduceBy<T, TResult>(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult): CurriedFunction2<(elem: T) => string, T[], { [index: string]: TResult }>; reduceBy<T, TResult>(valueFn: (acc: TResult, elem: T) => TResult): CurriedFunction3<TResult, (elem: T) => string, T[], { [index: string]: TResult }>; /** * Returns a value wrapped to indicate that it is the final value of the reduce and * transduce functions. The returned value should be considered a black box: the internal * structure is not guaranteed to be stable. */ reduced<T>(elem: T): Reduced; /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. */ reduceRight<T, TResult>(fn: (elem: T, acc: TResult) => TResult, acc: TResult, list: T[]): TResult; reduceRight<T, TResult>(fn: (elem: T, acc: TResult) => TResult): (acc: TResult, list: T[]) => TResult; reduceRight<T, TResult>(fn: (elem: T, acc: TResult) => TResult, acc: TResult): (list: T[]) => TResult; /** * Similar to `filter`, except that it keeps only values for which the given predicate * function returns falsy. */ reject<T>(fn: (value: T) => boolean): Filter<T>; reject<T>(fn: (value: T) => boolean, list: T[]): T[]; reject<T>(fn: (value: T) => boolean, obj: Dictionary<T>): Dictionary<T>; /** * Removes the sub-list of `list` starting at index `start` and containing `count` elements. */ remove<T>(start: number, count: number, list: T[]): T[]; remove<T>(start: number): (count: number, list: T[]) => T[]; remove<T>(start: number, count: number): (list: T[]) => T[]; /** * Returns a fixed list of size n containing a specified identical value. */ repeat<T>(a: T, n: number): T[]; repeat<T>(a: T): (n: number) => T[]; /** * Replace a substring or regex match in a string with a replacement. */ replace(pattern: RegExp | string, replacement: string, str: string): string; replace(pattern: RegExp | string, replacement: string): (str: string) => string; replace(pattern: RegExp | string): (replacement: string) => (str: string) => string; /** * Returns a new list with the same elements as the original list, just in the reverse order. */ reverse<T>(list: T[]): T[]; /** * Scan is similar to reduce, but returns a list of successively reduced values from the left. */ scan<T, TResult>(fn: (acc: TResult, elem: T) => any, acc: TResult, list: T[]): TResult[]; scan<T, TResult>(fn: (acc: TResult, elem: T) => any, acc: TResult): (list: T[]) => TResult[]; scan<T, TResult>(fn: (acc: TResult, elem: T) => any): (acc: TResult, list: T[]) => TResult[]; /** * Returns the result of "setting" the portion of the given data structure focused by the given lens to the * given value. */ set<T, U>(lens: Lens, a: U, obj: T): T; set<U>(lens: Lens, a: U): <T>(obj: T) => T; set(lens: Lens): <T, U>(a: U, obj: T) => T; /** * Returns the elements from `xs` starting at `a` and ending at `b - 1`. */ slice(a: number, b: number, list: string): string; slice<T>(a: number, b: number, list: T[]): T[]; slice(a: number, b: number): <T>(list: string | T[]) => string | T[]; slice(a: number): <T>(b: number, list: string | T[]) => string | T[]; /** * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero * if they are equal. */ sort<T>(fn: (a: T, b: T) => number, list: T[]): T[]; sort<T>(fn: (a: T, b: T) => number): (list: T[]) => T[]; /** * Sorts the list according to a key generated by the supplied function. */ sortBy<T>(fn: (a: T) => Ord, list: T[]): T[]; sortBy(fn: (a: any) => Ord): <T>(list: T[]) => T[]; /** * Sorts a list according to a list of comparators. */ sortWith<T>(fns: Array<((a: T, b: T) => number)>, list: T[]): T[]; sortWith<T>(fns: Array<((a: T, b: T) => number)>): (list: T[]) => T[]; /** * Splits a string into an array of strings based on the given * separator. */ split(sep: string | RegExp): (str: string) => string[]; split(sep: string | RegExp, str: string): string[]; /** * Splits a given list or string at a given index. */ splitAt<T>(index: number, list: T): T[]; splitAt(index: number): <T>(list: T) => T[]; splitAt<T>(index: number, list: T[]): T[][]; splitAt(index: number): <T>(list: T[]) => T[][]; /** * Splits a collection into slices of the specified length. */ splitEvery<T>(a: number, list: T[]): T[][]; splitEvery(a: number): <T>(list: T[]) => T[][]; /** * Takes a list and a predicate and returns a pair of lists with the following properties: * - the result of concatenating the two output lists is equivalent to the input list; * - none of the elements of the first output list satisfies the predicate; and * - if the second output list is non-empty, its first element satisfies the predicate. */ splitWhen<T, U>(pred: (val: T) => boolean, list: U[]): U[][]; splitWhen<T>(pred: (val: T) => boolean): <U>(list: U[]) => U[][]; /** * Checks if a list starts with the provided values */ startsWith(a: string, list: string): boolean; startsWith(a: string): (list: string) => boolean; startsWith<T>(a: T | T[], list: T[]): boolean; startsWith<T>(a: T | T[]): (list: T[]) => boolean; /** * Subtracts two numbers. Equivalent to `a - b` but curried. */ subtract(a: number, b: number): number; subtract(a: number): (b: number) => number; /** * Adds together all the elements of a list. */ sum(list: number[]): number; /** * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. */ symmetricDifference<T>(list1: T[], list2: T[]): T[]; symmetricDifference<T>(list: T[]): <T>(list: T[]) => T[]; /** * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. * Duplication is determined according to the value returned by applying the supplied predicate to two list elements. */ symmetricDifferenceWith<T>(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; symmetricDifferenceWith<T>(pred: (a: T, b: T) => boolean): CurriedFunction2<T[], T[], T[]>; /** * A function that always returns true. Any passed in parameters are ignored. */ T(): boolean; /** * Returns all but the first element of a list or string. */ tail<T>(list: T[]): T[]; tail(list: string): string; /** * Returns a new list containing the first `n` elements of the given list. If * `n > * list.length`, returns a list of `list.length` elements. */ take<T>(n: number, xs: T[]): T[]; take(n: number, xs: string): string; take<T>(n: number): { (xs: string): string; (xs: T[]): T[]; }; /** * Returns a new list containing the last n elements of the given list. If n > list.length, * returns a list of list.length elements. */ takeLast<T>(n: number, xs: T[]): T[]; takeLast(n: number, xs: string): string; takeLast(n: number): { <T>(xs: T[]): T[]; (xs: string): string; }; /** * Returns a new list containing the last n elements of a given list, passing each value * to the supplied predicate function, and terminating when the predicate function returns * false. Excludes the element that caused the predicate function to fail. The predicate * function is passed one argument: (value). */ takeLastWhile<T>(pred: (a: T) => boolean, list: T[]): T[]; takeLastWhile<T>(pred: (a: T) => boolean): <T>(list: T[]) => T[]; /** * Returns a new list containing the first `n` elements of a given list, passing each value * to the supplied predicate function, and terminating when the predicate function returns * `false`. */ takeWhile<T>(fn: (x: T) => boolean, list: T[]): T[]; takeWhile<T>(fn: (x: T) => boolean): (list: T[]) => T[]; /** * The function to call with x. The return value of fn will be thrown away. */ tap<T>(fn: (a: T) => any, value: T): T; tap<T>(fn: (a: T) => any): (value: T) => T; /** * Determines whether a given string matches a given regular expression. */ test(regexp: RegExp, str: string): boolean; test(regexp: RegExp): (str: string) => boolean; /** * Calls an input function `n` times, returning an array containing the results of those * function calls. */ times<T>(fn: (i: number) => T, n: number): T[]; times<T>(fn: (i: number) => T): (n: number) => T[]; /** * The lower case version of a string. */ toLower(str: string): string; /** * Converts an object into an array of key, value arrays. * Only the object's own properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. */ toPairs<F, S>(obj: { [k: string]: S } | { [k: number]: S }): Array<[F, S]>; /** * Converts an object into an array of key, value arrays. * The object's own properties and prototype properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. */ toPairsIn<F, S>(obj: { [k: string]: S } | { [k: number]: S }): Array<[F, S]>; /** * Returns the string representation of the given value. eval'ing the output should * result in a value equivalent to the input value. Many of the built-in toString * methods do not satisfy this requirement. * * If the given value is an [object Object] with a toString method other than * Object.prototype.toString, this method is invoked with no arguments to produce the * return value. This means user-defined constructor functions can provide a suitable * toString method. */ toString<T>(val: T): string; /** * The upper case version of a string. */ toUpper(str: string): string; /** * Initializes a transducer using supplied iterator function. Returns a single item by iterating through the * list, successively calling the transformed iterator function and passing it an accumulator value and the * current value from the array, and then passing the result to the next call. */ transduce<T, U>(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[], list: T[]): U; transduce<T, U>(xf: (arg: T[]) => T[]): (fn: (acc: U[], val: U) => U[], acc: T[], list: T[]) => U; transduce<T, U>(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[]): (acc: T[], list: T[]) => U; transduce<T, U>(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[]): (list: T[]) => U; /** * Transposes the rows and columns of a 2D list. When passed a list of n lists of length x, returns a list of x lists of length n. */ transpose<T>(list: T[][]): T[][]; /** * Maps an Applicative-returning function over a Traversable, then uses * sequence to transform the resulting Traversable of Applicative into * an Applicative of Traversable. */ traverse<T, U, A>(of: (a: U[]) => A, fn: (t: T) => U, list: T[]): A; traverse<T, U, A>(of: (a: U[]) => A, fn: (t: T) => U): (list: T[]) => A; traverse<T, U, A>(of: (a: U[]) => A): (fn: (t: T) => U, list: T[]) => A; /** * Removes (strips) whitespace from both ends of the string. */ trim(str: string): string; /** * tryCatch takes two functions, a tryer and a catcher. The returned function evaluates the tryer; if it does * not throw, it simply returns the result. If the tryer does throw, the returned function evaluates the catcher * function and returns its result. Note that for effective composition with this function, both the tryer and * catcher functions must return the same type of results. */ tryCatch<T>(tryer: (...args: any[]) => T, catcher: (...args: any[]) => T): (...args: any[]) => T; /** * Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', * 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them * all as 'Object'. */ type(val: any): 'Object' | 'Number' | 'Boolean' | 'String' | 'Null' | 'Array' | 'RegExp' | 'Function' | 'Undefined'; /** * Takes a function fn, which takes a single array argument, and returns a function which: * - takes any number of positional arguments; * - passes these arguments to fn as an array; and * - returns the result. * In other words, R.unapply derives a variadic function from a function which takes an array. * R.unapply is the inverse of R.apply. */ unapply<T>(fn: (args: any[]) => T): (...args: any[]) => T; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. * Any extraneous parameters will not be passed to the supplied function. */ unary<T>(fn: (a: T, ...args: any[]) => any): (a: T) => any; /** * Returns a function of arity n from a (manually) curried function. */ uncurryN<T>(len: number, fn: (a: any) => any): (...a: any[]) => T; /** * Builds a list from a seed value. Accepts an iterator function, which returns either false * to stop iteration or an array of length 2 containing the value to add to the resulting * list and the seed to be used in the next call to the iterator function. */ unfold<T, TResult>(fn: (seed: T) => [TResult, T] | false, seed: T): TResult[]; unfold<T, TResult>(fn: (seed: T) => [TResult, T] | false): (seed: T) => TResult[]; /** * Combines two lists into a set (i.e. no duplicates) composed of the * elements of each list. */ union<T>(as: T[], bs: T[]): T[]; union<T>(as: T[]): (bs: T[]) => T[]; /** * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is * determined according to the value returned by applying the supplied predicate to two list elements. */ unionWith<T>(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; unionWith<T>(pred: (a: T, b: T) => boolean): CurriedFunction2<T[], T[], T[]>; /** * Returns a new list containing only one copy of each element in the original list. */ uniq<T>(list: T[]): T[]; /** * Returns a new list containing only one copy of each element in the original list, * based upon the value returned by applying the supplied function to each list element. * Prefers the first item if the supplied function produces the same value on two items. * R.equals is used for comparison. */ uniqBy<T, U>(fn: (a: T) => U, list: T[]): T[]; uniqBy<T, U>(fn: (a: T) => U): (list: T[]) => T[]; /** * Returns a new list containing only one copy of each element in the original list, based upon the value * returned by applying the supplied predicate to two list elements. */ uniqWith<T, U>(pred: (x: T, y: T) => boolean, list: T[]): T[]; uniqWith<T, U>(pred: (x: T, y: T) => boolean): (list: T[]) => T[]; /** * Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, * the function will return the result of calling the whenFalseFn function with the same argument. If the * predicate is satisfied, the argument is returned as is. */ unless<T, U>(pred: (a: T) => boolean, whenFalseFn: (a: T) => U, obj: T): U; unless<T, U>(pred: (a: T) => boolean, whenFalseFn: (a: T) => U): (obj: T) => U; /** * Returns a new list by pulling every item at the first level of nesting out, and putting * them in a new array. */ unnest<T>(x: T[][] | T[]): T[]; /** * Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as * the initial value. It does so by applying the transformation until the predicate is satisfied, at which point * it returns the satisfactory value. */ until<T, U>(pred: (val: T) => boolean, fn: (val: T) => U, init: U): U; until<T, U>(pred: (val: T) => boolean, fn: (val: T) => U): (init: U) => U; /** * Returns a new copy of the array with the element at the provided index replaced with the given value. */ update<T>(index: number, value: T, list: T[]): T[]; update<T>(index: number, value: T): (list: T[]) => T[]; /** * Accepts a function fn and a list of transformer functions and returns a new curried function. * When the new function is invoked, it calls the function fn with parameters consisting of the * result of calling each supplied handler on successive arguments to the new function. * * If more arguments are passed to the returned function than transformer functions, those arguments * are passed directly to fn as additional parameters. If you expect additional arguments that don't * need to be transformed, although you can ignore them, it's best to pass an identity function so * that the new function reports the correct arity. */ useWith(fn: ((...a: any[]) => any), transformers: Array<((...a: any[]) => any)>): (...a: any[]) => any; /** * Returns a list of all the enumerable own properties of the supplied object. * Note that the order of the output array is not guaranteed across * different JS platforms. */ values<T extends object, K extends keyof T>(obj: T): Array<T[K]>; /** * Returns a list of all the properties, including prototype properties, of the supplied * object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. */ valuesIn<T>(obj: any): T[]; /** * Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which * portion of the data structure is visible. */ view<T, U>(lens: Lens): (obj: T) => U; view<T, U>(lens: Lens, obj: T): U; /** * Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function * will return the result of calling the whenTrueFn function with the same argument. If the predicate is not satisfied, * the argument is returned as is. */ when<T, U>(pred: (a: T) => boolean, whenTrueFn: (a: T) => U, obj: T): U; when<T, U>(pred: (a: T) => boolean, whenTrueFn: (a: T) => U): (obj: T) => U; /** * Takes a spec object and a test object and returns true if the test satisfies the spec. * Any property on the spec that is not a function is interpreted as an equality * relation. * * If the spec has a property mapped to a function, then `where` evaluates the function, passing in * the test object's value for the property in question, as well as the whole test object. * * `where` is well suited to declarativley expressing constraints for other functions, e.g., * `filter`, `find`, `pickWith`, etc. */ where<T, U>(spec: T, testObj: U): boolean; where<T>(spec: T): <U>(testObj: U) => boolean; where<ObjFunc2, U>(spec: ObjFunc2, testObj: U): boolean; where<ObjFunc2>(spec: ObjFunc2): <U>(testObj: U) => boolean; /** * Takes a spec object and a test object; returns true if the test satisfies the spec, * false otherwise. An object satisfies the spec if, for each of the spec's own properties, * accessing that property of the object gives the same value (in R.eq terms) as accessing * that property of the spec. */ whereEq<T, U>(spec: T, obj: U): boolean; whereEq<T>(spec: T): <U>(obj: U) => boolean; /** * Returns a new list without values in the first argument. R.equals is used to determine equality. * Acts as a transducer if a transformer is given in list position. */ without<T>(list1: T[], list2: T[]): T[]; without<T>(list1: T[]): (list2: T[]) => T[]; /** * Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing * either before the internal function is called or with its results. */ wrap(fn: (...a: any[]) => any, wrapper: (...a: any[]) => any): (...a: any[]) => any; /** * Creates a new list out of the two supplied by creating each possible pair from the lists. */ xprod<K, V>(as: K[], bs: V[]): Array<KeyValuePair<K, V>>; xprod<K>(as: K[]): <V>(bs: V[]) => Array<KeyValuePair<K, V>>; /** * Creates a new list out of the two supplied by pairing up equally-positioned items from * both lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. */ zip<K, V>(list1: K[], list2: V[]): Array<KeyValuePair<K, V>>; zip<K>(list1: K[]): <V>(list2: V[]) => Array<KeyValuePair<K, V>>; /** * Creates a new object out of a list of keys and a list of values. */ // TODO: Dictionary<T> as a return value is to specific, any seems to loose zipObj<T>(keys: string[], values: T[]): { [index: string]: T }; zipObj(keys: string[]): <T>(values: T[]) => { [index: string]: T }; /** * Creates a new list out of the two supplied by applying the function to each * equally-positioned pair in the lists. */ zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult, list1: T[], list2: U[]): TResult[]; zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult, list1: T[]): (list2: U[]) => TResult[]; zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult): (list1: T[], list2: U[]) => TResult[]; } } export = R; export as namespace R;
AbraaoAlves/DefinitelyTyped
types/ramda/index.d.ts
TypeScript
mit
92,922
module.exports = { 'baseURL': process.env.BASEURL ? process.env.BASEURL.replace(/\/$/, '') : 'http://localhost:4000', 'waitTime': isNaN(parseInt(process.env.TIMEOUT, 10)) ? 5000 : parseInt(process.env.TIMEOUT, 10), 'before': function() { /* eslint-disable no-console */ console.log('WaitTime set to', this.waitTime); console.log('BaseURL set to', this.baseURL); /* eslint-enable no-console */ }, 'API Reference: AvaTax: REST v1 (verify number of endpoints)': function(browser) { const expectedNumberOfApiEndpoints = 4; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/tax/v1/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.assert.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: REST v1 (getTax fill sample data)': function(browser) { /* eslint-disable quotes */ /* eslint-disable quote-props */ const expectedRequest = {"Commit": "false", "Client": "AvaTaxSample", "CompanyCode": "CINC", "CustomerCode": "ABC4335", "DocCode": "INV001", "DocType": "SalesOrder", "DocDate": "2014-01-01", "Addresses": [{"AddressCode": "01", "Line1": "45 Fremont Street", "Line2": "Suite 100", "Line3": "ATTN Accounts Payable", "City": "Chicago", "Region": "IL", "Country": "US", "PostalCode": "60602"}], "Lines": [{"LineNo": "1", "DestinationCode": "01", "OriginCode": "02", "ItemCode": "N543", "TaxCode": "NT", "Description": "Red Size 7 Widget", "Qty": "1", "Amount": "10"}]}; const expectedResponse = {"DocCode": "INV001", "DocDate": "2014-01-01", "TotalAmount": "10", "TotalDiscount": "0", "TotalExemption": "10", "TotalTaxable": "0", "TotalTax": "0", "TotalTaxCalculated": "0", "TaxDate": "2014-01-01", "TaxLines": [{"LineNo": "1", "TaxCode": "NT", "Taxability": "true", "BoundaryLevel": "Zip5", "Taxable": "0", "Rate": "0", "Tax": "0", "Discount": "0", "TaxCalculated": "0", "Exemption": "10", "TaxDetails": [{"Taxable": "0", "Rate": "0", "Tax": "0", "Region": "IL", "Country": "US", "JurisType": "State", "JurisName": "ILLINOIS", "JurisCode": "17", "TaxName": "IL STATE TAX"}]}], "TaxAddresses": [{"Address": "45 Fremont Street", "AddressCode": "01", "City": "Chicago", "Country": "US", "PostalCode": "60602", "Region": "IL", "TaxRegionId": "2062953", "JurisCode": "1703114000", "Latitude": "41.882906", "Longitude": "-87.629373"}], "ResultCode": "Success"}; /* eslint-enable quotes */ /* eslint-enable quote-props */ browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/tax/v1/') .waitForElementVisible('[data-reactroot]', this.waitTime) .waitForElementVisible('#getTax-console', this.waitTime) .click('#getTax-console') .waitForElementVisible('#getTax-console-body', this.waitTime) .click('#getTax-console-body .fill-sample-data') .waitForElementVisible('#getTax-console-body .console-req-container .code-snippet span:first-of-type', this.waitTime) .getText('#getTax-console-body .console-req-container .code-snippet', function(req) { /* eslint-disable no-invalid-this */ const request = JSON.parse(req.value); this.verify.equal(JSON.stringify(request), JSON.stringify(expectedRequest)); /* eslint-enable no-invalid-this */ }) .click('#getTax-console-body .submit') .waitForElementVisible('#getTax-console-body .console-res-container .code-snippet span:first-of-type', this.waitTime) .getText('#getTax-console-body .console-res-container .code-snippet', function(res) { /* eslint-disable no-invalid-this */ const response = JSON.parse(res.value); response.Timestamp = undefined; this.verify.equal(JSON.stringify(response), JSON.stringify(expectedResponse)); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: REST v2 (verify number of endpoints)': function(browser) { // NOTE: THESE NOW ALL EXIST ON SUB 'TAG' PAGES const expectedNumberOfApiEndpoints = 0; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/tax/v2/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.verify.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: SOAP (verify number of endpoints)': function(browser) { const expectedNumberOfApiEndpoints = 11; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/tax/soap/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.verify.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: BatchSvc SOAP (verify number of endpoints)': function(browser) { const expectedNumberOfApiEndpoints = 9; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/batch/soap/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.verify.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: AccountSvc SOAP (verify number of endpoints)': function(browser) { const expectedNumberOfApiEndpoints = 2; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/account/soap/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.verify.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); }, 'API Reference: AvaTax: Onboarding (verify number of endpoints)': function(browser) { const expectedNumberOfApiEndpoints = 8; browser .maximizeWindow() .url(this.baseURL + '/avatax/api-reference/onboarding/v1/') .waitForElementVisible('[data-reactroot]', this.waitTime) .elements('css selector', '.endpoint-summary', function(result) { /* eslint-disable no-invalid-this */ this.verify.equal(result.value.length, expectedNumberOfApiEndpoints, 'expected ' + expectedNumberOfApiEndpoints + ' endpoints, received ' + result.value.length); /* eslint-enable no-invalid-this */ }) .end(); } };
JoeSava/developer-dot
_test/browser/api-reference/avatax.js
JavaScript
mit
8,117
// Copyright © Microsoft Corporation. All Rights Reserved. // This code released under the terms of the // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) //***************************************************************************** // MSDN Reference Link: http://msdn.microsoft.com/library/aa480470.aspx //***************************************************************************** #include "stdafx.h" #include "PromptForCredential.h" #include "AutoGdiObject.h" #include "AutoPasswordBstr.h" #include "AutoPasswordBuffer.h" #include "Strings.h" //***************************************************************************** // // Initializes a new instance of the PromptForCredential class. // //***************************************************************************** WinCredentials::PromptForCredential::PromptForCredential() : m_targetName(String::Empty), m_userName(String::Empty) { // Do nothing } //***************************************************************************** // // Deletes the resources held by the object, optionally confirming the // credential with the operating system. // //***************************************************************************** WinCredentials::PromptForCredential::~PromptForCredential() { if (!m_disposed) { delete m_password; m_password = nullptr; delete m_banner; m_banner = nullptr; if (SaveChecked && ExpectConfirmation && !m_confirmed) { pin_ptr<const wchar_t> pinnedTargetName = PtrToStringChars(m_targetName); ::CredUIConfirmCredentials(pinnedTargetName, FALSE); } m_disposed = true; } Debug::Assert(nullptr == m_password); } //***************************************************************************** // // Gets or sets the target name that is used to identify the credential when // storing and retrieving it. It is also used as part of the title and message // text on the dialog box if these are not overridden. // //***************************************************************************** String^ WinCredentials::PromptForCredential::TargetName::get() { CheckNotDisposed(); return m_targetName; } void WinCredentials::PromptForCredential::TargetName::set(String^ value) { CheckNotDisposed(); if (nullptr == value) { throw gcnew ArgumentNullException("value"); } m_targetName = value; } //***************************************************************************** // // Gets or sets the error code to allow the dialog box to accommodate certain // errors. // //***************************************************************************** int WinCredentials::PromptForCredential::ErrorCode::get() { CheckNotDisposed(); return m_errorCode; } void WinCredentials::PromptForCredential::ErrorCode::set(int value) { CheckNotDisposed(); m_errorCode = value; } //***************************************************************************** // // Gets or sets the user name entered by the user. The dialog box will be // prefilled with the initial value. // //***************************************************************************** String^ WinCredentials::PromptForCredential::UserName::get() { CheckNotDisposed(); return m_userName; } void WinCredentials::PromptForCredential::UserName::set(String^ value) { CheckNotDisposed(); if (nullptr == value) { throw gcnew ArgumentNullException("value"); } if (CREDUI_MAX_USERNAME_LENGTH < value->Length) { throw gcnew ArgumentOutOfRangeException("value"); } m_userName = value; } //***************************************************************************** // // Gets or sets the password entered by the user. The dialog box will be // prefilled with the initial value. // //***************************************************************************** Security::SecureString^ WinCredentials::PromptForCredential::Password::get() { CheckNotDisposed(); if (nullptr == m_password) { m_password = gcnew Security::SecureString; } return m_password; } void WinCredentials::PromptForCredential::Password::set(Security::SecureString^ value) { CheckNotDisposed(); if (nullptr == value) { throw gcnew ArgumentNullException("value"); } if (m_password != value) { delete m_password; m_password = value; } } //***************************************************************************** // // Gets or sets a value indicating whether the save check box is checked. This // value is ignored unless the ShowSaveCheckBox property is set to true. // //***************************************************************************** bool WinCredentials::PromptForCredential::SaveChecked::get() { CheckNotDisposed(); return m_saveChecked; } void WinCredentials::PromptForCredential::SaveChecked::set(bool value) { CheckNotDisposed(); m_saveChecked = value; } //***************************************************************************** // // Gets or sets the message displayed on the dialog box. If the message is an // empty string, the dialog box contains a default message including the // target name. // //***************************************************************************** String^ WinCredentials::PromptForCredential::Message::get() { CheckNotDisposed(); return m_message ? m_message : String::Empty; } void WinCredentials::PromptForCredential::Message::set(String^ value) { CheckNotDisposed(); if (nullptr == value) { throw gcnew ArgumentNullException("value"); } if (CREDUI_MAX_MESSAGE_LENGTH < value->Length) { throw gcnew ArgumentOutOfRangeException("value"); } m_message = value; } //***************************************************************************** // // Gets or sets the dialog box title. If the title is an empty string, the // dialog box uses a default title including the target name. // //***************************************************************************** String^ WinCredentials::PromptForCredential::Title::get() { CheckNotDisposed(); return m_title ? m_title : String::Empty; } void WinCredentials::PromptForCredential::Title::set(String^ value) { CheckNotDisposed(); if (nullptr == value) { throw gcnew ArgumentNullException("value"); } if (CREDUI_MAX_CAPTION_LENGTH < value->Length) { throw gcnew ArgumentOutOfRangeException("value"); } m_title = value; } //***************************************************************************** // // Gets or sets a banner bitmap to display in the dialog box. If a bitmap is // not provided, the dialog box displays a default bitmap. The bitmap size is // limited to 320 x 60 pixels. // //***************************************************************************** Drawing::Bitmap^ WinCredentials::PromptForCredential::Banner::get() { CheckNotDisposed(); return m_banner; } void WinCredentials::PromptForCredential::Banner::set(Drawing::Bitmap^ value) { CheckNotDisposed(); if (value != m_banner) { delete m_banner; m_banner = value; } } //***************************************************************************** // // The dialog box should be displayed even if a matching credential exists in // the user’s credential set. // //***************************************************************************** bool WinCredentials::PromptForCredential::AlwaysShowUI::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_ALWAYS_SHOW_UI & m_flags); } void WinCredentials::PromptForCredential::AlwaysShowUI::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_ALWAYS_SHOW_UI); } //***************************************************************************** // // The dialog box will automatically add the target name as the authority in // the user name if the user doesn’t specify an authority. This property is // only used with generic credentials as user name completion is always used // for Windows credentials. // //***************************************************************************** bool WinCredentials::PromptForCredential::CompleteUserName::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_COMPLETE_USERNAME & m_flags); } void WinCredentials::PromptForCredential::CompleteUserName::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_COMPLETE_USERNAME); } //***************************************************************************** // // The dialog box should not store the credential in the user’s credential // set. The Save check box is not displayed unless the ShowSaveCheckBox // property is set to true. // //***************************************************************************** bool WinCredentials::PromptForCredential::DoNotPersist::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_DO_NOT_PERSIST & m_flags); } void WinCredentials::PromptForCredential::DoNotPersist::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_DO_NOT_PERSIST); } //***************************************************************************** // // Certificate or smart card credentials will not be displayed in the User // name combo box. Only generic and password credentials will be present. // //***************************************************************************** bool WinCredentials::PromptForCredential::ExcludeCertificates::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_EXCLUDE_CERTIFICATES & m_flags); } void WinCredentials::PromptForCredential::ExcludeCertificates::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_EXCLUDE_CERTIFICATES); } //***************************************************************************** // // The credential manager expects that you will validate the credentials // before it stores them. This avoids invalid credentials from being added to // the user’s credential set. // //***************************************************************************** bool WinCredentials::PromptForCredential::ExpectConfirmation::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_EXPECT_CONFIRMATION & m_flags); } void WinCredentials::PromptForCredential::ExpectConfirmation::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_EXPECT_CONFIRMATION); } //***************************************************************************** // // The entered credentials are considered application-specific. // //***************************************************************************** bool WinCredentials::PromptForCredential::GenericCredentials::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_GENERIC_CREDENTIALS & m_flags); } void WinCredentials::PromptForCredential::GenericCredentials::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_GENERIC_CREDENTIALS); } //***************************************************************************** // // The dialog box displays a balloon tip indicating that a logon attempt was // unsuccessful, suggesting that the password may be incorrect. // //***************************************************************************** bool WinCredentials::PromptForCredential::IncorrectPassword::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_INCORRECT_PASSWORD & m_flags); } void WinCredentials::PromptForCredential::IncorrectPassword::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_INCORRECT_PASSWORD); } //***************************************************************************** // // The dialog box will not display the Save check box but will behave as // though it were shown and checked. // //***************************************************************************** bool WinCredentials::PromptForCredential::Persist::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_PERSIST & m_flags); } void WinCredentials::PromptForCredential::Persist::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_PERSIST); } //***************************************************************************** // // The user name combo box is populated with the names of the local // administrator accounts. If this property is not set, the dialog box // populates the combo box with the user names from the user’s credential set. // //***************************************************************************** bool WinCredentials::PromptForCredential::RequestAdministrator::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_REQUEST_ADMINISTRATOR & m_flags); } void WinCredentials::PromptForCredential::RequestAdministrator::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_REQUEST_ADMINISTRATOR); } //***************************************************************************** // // The user name combo box is populated with available certificates and the // user is not able to enter a user name. // //***************************************************************************** bool WinCredentials::PromptForCredential::RequireCertificate::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_REQUIRE_CERTIFICATE & m_flags); } void WinCredentials::PromptForCredential::RequireCertificate::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_REQUIRE_CERTIFICATE); } //***************************************************************************** // // The user name combo box is populated with available smart cards and the // user is not able to enter a user name. // //***************************************************************************** bool WinCredentials::PromptForCredential::RequireSmartCard::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_REQUIRE_SMARTCARD & m_flags); } void WinCredentials::PromptForCredential::RequireSmartCard::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_REQUIRE_SMARTCARD); } //***************************************************************************** // // The dialog box will display the check box despite the fact that it will not // actually persist the credential. This is useful for applications that need // to manage credential storage manually. // //***************************************************************************** bool WinCredentials::PromptForCredential::ShowSaveCheckBox::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX & m_flags); } void WinCredentials::PromptForCredential::ShowSaveCheckBox::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX); } //***************************************************************************** // // The user name field is read-only, allowing only a password to be entered. // //***************************************************************************** bool WinCredentials::PromptForCredential::UserNameReadOnly::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_KEEP_USERNAME & m_flags); } void WinCredentials::PromptForCredential::UserNameReadOnly::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_KEEP_USERNAME); } //***************************************************************************** // // The dialog box will ensure that the entered user name uses a valid format. // This property is only used with generic credentials as user name validation // is always used for Windows credentials. // //***************************************************************************** bool WinCredentials::PromptForCredential::ValidateUserName::get() { CheckNotDisposed(); return 0 != (CREDUI_FLAGS_VALIDATE_USERNAME & m_flags); } void WinCredentials::PromptForCredential::ValidateUserName::set(bool value) { CheckNotDisposed(); Flag(value, CREDUI_FLAGS_VALIDATE_USERNAME); } //***************************************************************************** // // Shows the dialog box. // //***************************************************************************** Windows::Forms::DialogResult WinCredentials::PromptForCredential::ShowDialog() { CheckNotDisposed(); return ShowDialog(nullptr); } //***************************************************************************** // // Shows the dialog box using the specified owner window. // //***************************************************************************** Windows::Forms::DialogResult WinCredentials::PromptForCredential::ShowDialog(Windows::Forms::IWin32Window^ owner) { CheckNotDisposed(); CREDUI_INFO info = { sizeof (CREDUI_INFO) }; if (nullptr != owner) { info.hwndParent = static_cast<HWND>(owner->Handle.ToPointer()); } AutoGdiObject<HBITMAP> bitmap; if (nullptr != m_banner) { bitmap.m_handle = static_cast<HBITMAP>(m_banner->GetHbitmap().ToPointer()); } info.hbmBanner = bitmap.m_handle; pin_ptr<const wchar_t> pinnedMessage = nullptr; if (nullptr != m_message && 0 < m_message->Length) { pinnedMessage = PtrToStringChars(m_message); info.pszMessageText = pinnedMessage; } pin_ptr<const wchar_t> pinnedTitle = nullptr; if (nullptr != m_title && 0 < m_title->Length) { pinnedTitle = PtrToStringChars(m_title); info.pszCaptionText = pinnedTitle; } pin_ptr<const wchar_t> pinnedTargetName = PtrToStringChars(m_targetName); wchar_t userName[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 }; int index = 0; for each (wchar_t element in m_userName) { userName[index++] = element; } AutoPasswordBuffer<CREDUI_MAX_PASSWORD_LENGTH + 1> password; if (nullptr != m_password && 0 < m_password->Length) { AutoPasswordBstr bstrPassword; bstrPassword.m_bstr = static_cast<BSTR>(Runtime::InteropServices::Marshal::SecureStringToBSTR(m_password).ToPointer()); wcscpy_s(password.m_buffer, CREDUI_MAX_PASSWORD_LENGTH, bstrPassword.m_bstr); } BOOL saveChecked = m_saveChecked; DWORD result = ::CredUIPromptForCredentials(&info, pinnedTargetName, 0, // reserved m_errorCode, userName, CREDUI_MAX_USERNAME_LENGTH + 1, password.m_buffer, CREDUI_MAX_PASSWORD_LENGTH + 1, &saveChecked, m_flags); Windows::Forms::DialogResult dialogResult = Windows::Forms::DialogResult::None; switch (result) { case NO_ERROR: { m_userName = Runtime::InteropServices::Marshal::PtrToStringUni(IntPtr(userName)); m_password = gcnew Security::SecureString(password.m_buffer, static_cast<int>(wcslen(password.m_buffer))); m_saveChecked = 0 != saveChecked; dialogResult = Windows::Forms::DialogResult::OK; break; } case ERROR_CANCELLED: { dialogResult = Windows::Forms::DialogResult::Cancel; break; } default: { throw gcnew ComponentModel::Win32Exception(result); } } return dialogResult; } //***************************************************************************** // // Confirms the validity of the previously collected credential. // //***************************************************************************** void WinCredentials::PromptForCredential::ConfirmCredentials() { CheckNotDisposed(); pin_ptr<const wchar_t> pinnedTargetName = PtrToStringChars(m_targetName); DWORD result = ::CredUIConfirmCredentials(pinnedTargetName, TRUE); m_confirmed = true; if (NO_ERROR != result) { throw gcnew ComponentModel::Win32Exception(result); } } //***************************************************************************** // // This private method is used to set or clear the bitmask of flags. // //***************************************************************************** void WinCredentials::PromptForCredential::Flag(bool add, DWORD flag) { if (add) { m_flags |= flag; } else { m_flags &= ~flag; } } //***************************************************************************** // // This private method is called by all the public members to check that the // object has not been disposed. // //***************************************************************************** void WinCredentials::PromptForCredential::CheckNotDisposed() { if (m_disposed) { throw gcnew ObjectDisposedException(String::Empty, Strings::Get("ObjectDisposedException.Message")); } }
adamdriscoll/TfsIntegrationPlatform
IntegrationPlatform/Core/WinCredentials/PromptForCredential.cpp
C++
mit
21,472
import time time.sleep(0.25) contents = clipboard.get_selection() retCode, abbr = dialog.input_dialog("New Abbreviation", "Choose an abbreviation for the new phrase") if retCode == 0: if len(contents) > 20: title = contents[0:17] + "..." else: title = contents folder = engine.get_folder("My Phrases") engine.create_abbreviation(folder, title, abbr, contents)
andresgomezvidal/autokey_scripts
data/Scripts/Sample_Scripts/Abbreviation from selection.py
Python
mit
391
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Z.EntityFramework.Plus; namespace Z.Test.EntityFramework.Plus { public partial class QueryFilter_DbSet_AsNoFilter { [TestMethod] public void WithGlobalManagerFilter_SingleFilter_Enabled() { TestContext.DeleteAll(x => x.Inheritance_Interface_Entities); TestContext.Insert(x => x.Inheritance_Interface_Entities, 10); using (var ctx = new TestContext()) { QueryFilterHelper.CreateGlobalManagerFilter(false, enableFilter1: true); QueryFilterManager.InitilizeGlobalFilter(ctx); Assert.AreEqual(45, ctx.Inheritance_Interface_Entities.AsNoFilter().Sum(x => x.ColumnInt)); QueryFilterHelper.ClearGlobalManagerFilter(); } } } }
zzzprojects/EntityFramework-Plus
src/test/Z.Test.EntityFramework.Plus.EF6/QueryFilter/DbSet_AsNoFilter/WithGlobalManagerFilter/SingleFilter_Enabled.cs
C#
mit
1,419
require File.expand_path('../example_setup', __FILE__) require 'flipper' require 'flipper/adapters/memory' adapter = Flipper::Adapters::Memory.new flipper = Flipper.new(adapter) # Some class that represents what will be trying to do something class User attr_reader :id def initialize(id) @id = id end # Must respond to flipper_id alias_method :flipper_id, :id end # checking a bunch gate = Flipper::Gates::PercentageOfActors.new feature_name = "data_migration" percentage_enabled = 10 total = 20_000 enabled = [] (1..total).each do |id| user = User.new(id) if gate.open?(user, percentage_enabled, feature_name: feature_name) enabled << user end end p actual: enabled.size, expected: total * (percentage_enabled * 0.01) # checking one user = User.new(1) p user_1_enabled: Flipper::Gates::PercentageOfActors.new.open?(user, percentage_enabled, feature_name: feature_name)
gdavison/flipper
examples/percentage_of_actors_enabled_check.rb
Ruby
mit
904
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Behat\Context\Ui\Admin; use Behat\Behat\Context\Context; use Sylius\Behat\Page\Admin\ExchangeRate\CreatePageInterface; use Sylius\Behat\Page\Admin\ExchangeRate\IndexPageInterface; use Sylius\Behat\Page\Admin\ExchangeRate\UpdatePageInterface; use Sylius\Component\Currency\Model\ExchangeRateInterface; use Webmozart\Assert\Assert; /** * @author Jan Góralski <jan.goralski@lakion.com> */ final class ManagingExchangeRatesContext implements Context { /** * @var CreatePageInterface */ private $createPage; /** * @var IndexPageInterface */ private $indexPage; /** * @var UpdatePageInterface */ private $updatePage; /** * @param CreatePageInterface $createPage * @param IndexPageInterface $indexPage * @param UpdatePageInterface $updatePage */ public function __construct( CreatePageInterface $createPage, IndexPageInterface $indexPage, UpdatePageInterface $updatePage ) { $this->createPage = $createPage; $this->indexPage = $indexPage; $this->updatePage = $updatePage; } /** * @Given I want to add a new exchange rate */ public function iWantToAddNewExchangeRate() { $this->createPage->open(); } /** * @Given /^I want to edit (this exchange rate)$/ * @When /^I am editing (this exchange rate)$/ */ public function iWantToEditThisExchangeRate(ExchangeRateInterface $exchangeRate) { $this->updatePage->open(['id' => $exchangeRate->getId()]); } /** * @When I am browsing exchange rates of the store * @When I browse exchange rates of the store */ public function iWantToBrowseExchangeRatesOfTheStore() { $this->indexPage->open(); } /** * @When /^I specify its ratio as (-?[0-9\.]+)$/ * @When I don't specify its ratio */ public function iSpecifyItsRatioAs($ratio = null) { $this->createPage->specifyRatio($ratio); } /** * @When I choose :currencyCode as the source currency */ public function iChooseAsSourceCurrency($currencyCode) { $this->createPage->chooseSourceCurrency($currencyCode); } /** * @When I choose :currencyCode as the target currency */ public function iChooseAsTargetCurrency($currencyCode) { $this->createPage->chooseTargetCurrency($currencyCode); } /** * @When I( try to) add it */ public function iAddIt() { $this->createPage->create(); } /** * @When I change ratio to :ratio */ public function iChangeRatioTo($ratio) { $this->updatePage->changeRatio((float)$ratio); } /** * @When I save my changes */ public function iSaveMyChanges() { $this->updatePage->saveChanges(); } /** * @When I delete the exchange rate between :sourceCurrencyName and :targetCurrencyName */ public function iDeleteTheExchangeRateBetweenAnd($sourceCurrencyName, $targetCurrencyName) { $this->indexPage->open(); $this->indexPage->deleteResourceOnPage([ 'sourceCurrency' => $sourceCurrencyName, 'targetCurrency' => $targetCurrencyName, ]); } /** * @When I choose :currencyName as a currency filter */ public function iChooseCurrencyAsACurrencyFilter($currencyName) { $this->indexPage->chooseCurrencyFilter($currencyName); } /** * @When I filter */ public function iFilter() { $this->indexPage->filter(); } /** * @Then I should see :count exchange rates on the list */ public function iShouldSeeExchangeRatesOnTheList($count = 0) { $this->assertCountOfExchangeRatesOnTheList($count); } /** * @Then I should( still) see one exchange rate on the list */ public function iShouldSeeOneExchangeRateOnTheList() { $this->indexPage->open(); $this->assertCountOfExchangeRatesOnTheList(1); } /** * @Then the exchange rate with ratio :ratio between :sourceCurrency and :targetCurrency should appear in the store */ public function theExchangeRateBetweenAndShouldAppearInTheStore($ratio, $sourceCurrency, $targetCurrency) { $this->indexPage->open(); $this->assertExchangeRateWithRatioIsOnTheList($ratio, $sourceCurrency, $targetCurrency); } /** * @Then I should (also) see an exchange rate between :sourceCurrencyName and :targetCurrencyName on the list */ public function iShouldSeeAnExchangeRateBetweenAndOnTheList($sourceCurrencyName, $targetCurrencyName) { $this->assertExchangeRateIsOnList($sourceCurrencyName, $targetCurrencyName); } /** * @Then it should have a ratio of :ratio */ public function thisExchangeRateShouldHaveRatioOf($ratio) { Assert::eq( $ratio, $this->updatePage->getRatio(), 'Exchange rate\'s ratio should be %s, but is %s instead.' ); } /** * @Then /^(this exchange rate) should no longer be on the list$/ */ public function thisExchangeRateShouldNoLongerBeOnTheList(ExchangeRateInterface $exchangeRate) { $this->assertExchangeRateIsNotOnTheList( $exchangeRate->getSourceCurrency()->getName(), $exchangeRate->getTargetCurrency()->getName() ); } /** * @Then the exchange rate between :sourceCurrencyName and :targetCurrencyName should not be added */ public function theExchangeRateBetweenAndShouldNotBeAdded($sourceCurrencyName, $targetCurrencyName) { $this->indexPage->open(); $this->assertExchangeRateIsNotOnTheList($sourceCurrencyName, $targetCurrencyName); } /** * @Then /^(this exchange rate) should have a ratio of ([0-9\.]+)$/ */ public function thisExchangeRateShouldHaveARatioOf(ExchangeRateInterface $exchangeRate, $ratio) { $sourceCurrencyName = $exchangeRate->getSourceCurrency()->getName(); $targetCurrencyName = $exchangeRate->getTargetCurrency()->getName(); $this->assertExchangeRateWithRatioIsOnTheList($ratio, $sourceCurrencyName, $targetCurrencyName); } /** * @Then I should see that the source currency is disabled */ public function iShouldSeeThatTheSourceCurrencyIsDisabled() { Assert::true( $this->updatePage->isSourceCurrencyDisabled(), 'The source currency is not disabled.' ); } /** * @Then I should see that the target currency is disabled */ public function iShouldSeeThatTheTargetCurrencyIsDisabled() { Assert::true( $this->updatePage->isTargetCurrencyDisabled(), 'The target currency is not disabled.' ); } /** * @Then /^I should be notified that ([^"]+) is required$/ */ public function iShouldBeNotifiedThatIsRequired($element) { Assert::same( $this->createPage->getValidationMessage($element), sprintf('Please enter exchange rate %s.', $element) ); } /** * @Then I should be notified that the ratio must be greater than zero */ public function iShouldBeNotifiedThatRatioMustBeGreaterThanZero() { Assert::same($this->createPage->getValidationMessage('ratio'), 'The ratio must be greater than 0.'); } /** * @Then I should be notified that source and target currencies must differ */ public function iShouldBeNotifiedThatSourceAndTargetCurrenciesMustDiffer() { $expectedMessage = 'The source and target currencies must differ.'; $this->assertFormHasValidationMessage($expectedMessage); } /** * @Then I should be notified that the currency pair must be unique */ public function iShouldBeNotifiedThatTheCurrencyPairMustBeUnique() { $expectedMessage = 'The currency pair must be unique.'; $this->assertFormHasValidationMessage($expectedMessage); } /** * @param string $sourceCurrencyName * @param string $targetCurrencyName * * @throws \InvalidArgumentException */ private function assertExchangeRateIsOnList($sourceCurrencyName, $targetCurrencyName) { Assert::true( $this->indexPage->isSingleResourceOnPage([ 'sourceCurrency' => $sourceCurrencyName, 'targetCurrency' => $targetCurrencyName, ]), sprintf( 'An exchange rate with source currency %s and target currency %s was not found on the list.', $sourceCurrencyName, $targetCurrencyName ) ); } /** * @param float $ratio * @param string $sourceCurrencyName * @param string $targetCurrencyName * * @throws \InvalidArgumentException */ private function assertExchangeRateWithRatioIsOnTheList($ratio, $sourceCurrencyName, $targetCurrencyName) { Assert::true( $this->indexPage->isSingleResourceOnPage([ 'ratio' => $ratio, 'sourceCurrency' => $sourceCurrencyName, 'targetCurrency' => $targetCurrencyName, ]), sprintf( 'An exchange rate between %s and %s with a ratio of %s has not been found on the list.', $sourceCurrencyName, $targetCurrencyName, $ratio ) ); } /** * @param string $sourceCurrencyName * @param string $targetCurrencyName * * @throws \InvalidArgumentException */ private function assertExchangeRateIsNotOnTheList($sourceCurrencyName, $targetCurrencyName) { Assert::false( $this->indexPage->isSingleResourceOnPage([ 'sourceCurrency' => $sourceCurrencyName, 'targetCurrency' => $targetCurrencyName, ]), sprintf( 'An exchange rate with source currency %s and target currency %s has been found on the list.', $sourceCurrencyName, $targetCurrencyName ) ); } /** * @param int $count * * @throws \InvalidArgumentException */ private function assertCountOfExchangeRatesOnTheList($count) { $actualCount = $this->indexPage->countItems(); Assert::same( $actualCount, (int) $count, 'Expected %2$d exchange rates to be on the list, but found %d instead.' ); } /** * @param string $expectedMessage * * @throws \InvalidArgumentException */ private function assertFormHasValidationMessage($expectedMessage) { Assert::true( $this->createPage->hasFormValidationError($expectedMessage), sprintf( 'The validation message "%s" was not found on the page.', $expectedMessage ) ); } }
Lowlo/Sylius
src/Sylius/Behat/Context/Ui/Admin/ManagingExchangeRatesContext.php
PHP
mit
11,347
#!/usr/bin/env node /* The MIT License (MIT) Copyright (c) 2007-2013 Einar Lielmanis and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Js-Beautify Command-line for node.js ------------------------------------- Written by Daniel Stockman (daniel.stockman@gmail.com) */ var debug = process.env.DEBUG_JSBEAUTIFY || process.env.JSBEAUTIFY_DEBUG ? function() { console.error.apply(console, arguments); } : function() {}; var fs = require('fs'), cc = require('config-chain'), beautify = require('../index'), mkdirp = require('mkdirp'), nopt = require('nopt'), path = require('path'), knownOpts = { // Beautifier "indent_size": Number, "indent_char": String, "indent_level": Number, "indent_with_tabs": Boolean, "preserve_newlines": Boolean, "max_preserve_newlines": Number, "space_in_paren": Boolean, "space_in_empty_paren": Boolean, "jslint_happy": Boolean, "space_after_anon_function": Boolean, // TODO: expand-strict is obsolete, now identical to expand. Remove in future version "brace_style": ["collapse", "expand", "end-expand", "expand-strict", "none"], "break_chained_methods": Boolean, "keep_array_indentation": Boolean, "unescape_strings": Boolean, "wrap_line_length": Number, "e4x": Boolean, "end_with_newline": Boolean, // CSS-only "selector_separator_newline": Boolean, "newline_between_rules": Boolean, // HTML-only "max_char": Number, // obsolete since 1.3.5 "unformatted": [String, Array], "indent_inner_html": [Boolean], "indent_scripts": ["keep", "separate", "normal"], // CLI "version": Boolean, "help": Boolean, "files": [path, Array], "outfile": path, "replace": Boolean, "quiet": Boolean, "type": ["js", "css", "html"], "config": path }, // dasherizeShorthands provides { "indent-size": ["--indent_size"] } // translation, allowing more convenient dashes in CLI arguments shortHands = dasherizeShorthands({ // Beautifier "s": ["--indent_size"], "c": ["--indent_char"], "l": ["--indent_level"], "t": ["--indent_with_tabs"], "p": ["--preserve_newlines"], "m": ["--max_preserve_newlines"], "P": ["--space_in_paren"], "E": ["--space_in_empty_paren"], "j": ["--jslint_happy"], "a": ["--space_after_anon_function"], "b": ["--brace_style"], "B": ["--break_chained_methods"], "k": ["--keep_array_indentation"], "x": ["--unescape_strings"], "w": ["--wrap_line_length"], "X": ["--e4x"], "n": ["--end_with_newline"], // CSS-only "L": ["--selector_separator_newline"], "N": ["--newline_between_rules"], // HTML-only "W": ["--max_char"], // obsolete since 1.3.5 "U": ["--unformatted"], "I": ["--indent_inner_html"], "S": ["--indent_scripts"], // non-dasherized hybrid shortcuts "good-stuff": [ "--keep_array_indentation", "--keep_function_indentation", "--jslint_happy" ], "js": ["--type", "js"], "css": ["--type", "css"], "html": ["--type", "html"], // CLI "v": ["--version"], "h": ["--help"], "f": ["--files"], "o": ["--outfile"], "r": ["--replace"], "q": ["--quiet"] // no shorthand for "config" }); function verifyExists(fullPath) { return fs.existsSync(fullPath) ? fullPath : null; } function findRecursive(dir, fileName) { var fullPath = path.join(dir, fileName); var nextDir = path.dirname(dir); var result = verifyExists(fullPath); if (!result && (nextDir !== dir)) { result = findRecursive(nextDir, fileName); } return result; } function getUserHome() { return process.env.HOME || process.env.USERPROFILE; } // var cli = require('js-beautify/cli'); cli.interpret(); var interpret = exports.interpret = function(argv, slice) { var parsed = nopt(knownOpts, shortHands, argv, slice); if (parsed.version) { console.log(require('../../package.json').version); process.exit(0); } else if (parsed.help) { usage(); process.exit(0); } var cfg = cc( parsed, cleanOptions(cc.env('jsbeautify_'), knownOpts), parsed.config, findRecursive(process.cwd(), '.jsbeautifyrc'), verifyExists(path.join(getUserHome() || "", ".jsbeautifyrc")), __dirname + '/../config/defaults.json' ).snapshot; try { // Verify arguments checkType(cfg); checkFiles(cfg); debug(cfg); // Process files synchronously to avoid EMFILE error cfg.files.forEach(processInputSync, { cfg: cfg }); } catch (ex) { debug(cfg); // usage(ex); console.error(ex); console.error('Run `' + getScriptName() + ' -h` for help.'); process.exit(1); } }; // interpret args immediately when called as executable if (require.main === module) { interpret(); } function usage(err) { var scriptName = getScriptName(); var msg = [ scriptName + '@' + require('../../package.json').version, '', 'CLI Options:', ' -f, --file Input file(s) (Pass \'-\' for stdin)', ' -r, --replace Write output in-place, replacing input', ' -o, --outfile Write output to file (default stdout)', ' --config Path to config file', ' --type [js|css|html] ["js"]', ' -q, --quiet Suppress logging to stdout', ' -h, --help Show this help', ' -v, --version Show the version', '', 'Beautifier Options:', ' -s, --indent-size Indentation size [4]', ' -c, --indent-char Indentation character [" "]' ]; switch (scriptName.split('-').shift()) { case "js": msg.push(' -l, --indent-level Initial indentation level [0]'); msg.push(' -t, --indent-with-tabs Indent with tabs, overrides -s and -c'); msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)'); msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]'); msg.push(' -P, --space-in-paren Add padding spaces within paren, ie. f( a, b )'); msg.push(' -E, --space-in-empty-paren Add a single space inside empty paren, ie. f( )'); msg.push(' -j, --jslint-happy Enable jslint-stricter mode'); msg.push(' -a, --space-after-anon-function Add a space before an anonymous function\'s parens, ie. function ()'); msg.push(' -b, --brace-style [collapse|expand|end-expand|none] ["collapse"]'); msg.push(' -B, --break-chained-methods Break chained method calls across subsequent lines'); msg.push(' -k, --keep-array-indentation Preserve array indentation'); msg.push(' -x, --unescape-strings Decode printable characters encoded in xNN notation'); msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]'); msg.push(' -X, --e4x Pass E4X xml literals through untouched'); msg.push(' --good-stuff Warm the cockles of Crockford\'s heart'); msg.push(' -n, --end_with_newline End output with newline'); break; case "html": msg.push(' -b, --brace-style [collapse|expand|end-expand] ["collapse"]'); msg.push(' -I, --indent-inner-html Indent body and head sections. Default is false.'); msg.push(' -S, --indent-scripts [keep|separate|normal] ["normal"]'); msg.push(' -w, --wrap-line-length Wrap lines at next opportunity after N characters [0]'); msg.push(' -p, --preserve-newlines Preserve line-breaks (--no-preserve-newlines disables)'); msg.push(' -m, --max-preserve-newlines Number of line-breaks to be preserved in one chunk [10]'); msg.push(' -U, --unformatted List of tags (defaults to inline) that should not be reformatted'); break; case "css": msg.push(' -L, --selector-separator-newline Add a newline between multiple selectors.') msg.push(' -N, --newline-between-rules Add a newline between CSS rules.') } if (err) { msg.push(err); msg.push(''); console.error(msg.join('\n')); } else { console.log(msg.join('\n')); } } // main iterator, {cfg} passed as thisArg of forEach call function processInputSync(filepath) { var data = '', config = this.cfg, outfile = config.outfile, input; // -o passed with no value overwrites if (outfile === true || config.replace) { outfile = filepath; } if (filepath === '-') { input = process.stdin; input.resume(); input.setEncoding('utf8'); input.on('data', function(chunk) { data += chunk; }); input.on('end', function() { makePretty(data, config, outfile, writePretty); }); } else { var dir = path.dirname(outfile); mkdirp.sync(dir); data = fs.readFileSync(filepath, 'utf8'); makePretty(data, config, outfile, writePretty); } } function makePretty(code, config, outfile, callback) { try { var fileType = getOutputType(outfile, config.type); var pretty = beautify[fileType](code, config); callback(null, pretty, outfile, config); } catch (ex) { callback(ex); } } function writePretty(err, pretty, outfile, config) { if (err) { console.error(err); process.exit(1); } if (outfile) { try { fs.writeFileSync(outfile, pretty, 'utf8'); logToStdout('beautified ' + path.relative(process.cwd(), outfile), config); } catch (ex) { onOutputError(ex); } } else { process.stdout.write(pretty); } } // workaround the fact that nopt.clean doesn't return the object passed in :P function cleanOptions(data, types) { nopt.clean(data, types); return data; } // error handler for output stream that swallows errors silently, // allowing the loop to continue over unwritable files. function onOutputError(err) { if (err.code === 'EACCES') { console.error(err.path + " is not writable. Skipping!"); } else { console.error(err); process.exit(0); } } // turn "--foo_bar" into "foo-bar" function dasherizeFlag(str) { return str.replace(/^\-+/, '').replace(/_/g, '-'); } // translate weird python underscored keys into dashed argv, // avoiding single character aliases. function dasherizeShorthands(hash) { // operate in-place Object.keys(hash).forEach(function(key) { // each key value is an array var val = hash[key][0]; // only dasherize one-character shorthands if (key.length === 1 && val.indexOf('_') > -1) { hash[dasherizeFlag(val)] = val; } }); return hash; } function getOutputType(outfile, configType) { if (outfile && /\.(js|css|html)$/.test(outfile)) { return outfile.split('.').pop(); } return configType; } function getScriptName() { return path.basename(process.argv[1]); } function checkType(parsed) { var scriptType = getScriptName().split('-').shift(); debug("executable type:", scriptType); var parsedType = parsed.type; debug("parsed type:", parsedType); if (!parsedType) { debug("type defaulted:", scriptType); parsed.type = scriptType; } } function checkFiles(parsed) { var argv = parsed.argv; if (!parsed.files) { parsed.files = []; } else { if (argv.cooked.indexOf('-') > -1) { // strip stdin path eagerly added by nopt in '-f -' case parsed.files.some(removeDashedPath); } } if (argv.remain.length) { // assume any remaining args are files argv.remain.forEach(function(f) { parsed.files.push(path.resolve(f)); }); } if ('string' === typeof parsed.outfile && !parsed.files.length) { // use outfile as input when no other files passed in args parsed.files.push(parsed.outfile); // operation is now an implicit overwrite parsed.replace = true; } if (argv.original.indexOf('-') > -1) { // ensure '-' without '-f' still consumes stdin parsed.files.push('-'); } if (!parsed.files.length) { throw 'Must define at least one file.'; } debug('files.length ' + parsed.files.length); parsed.files.forEach(testFilePath); return parsed; } function removeDashedPath(filepath, i, arr) { var found = filepath.lastIndexOf('-') === (filepath.length - 1); if (found) { arr.splice(i, 1); } return found; } function testFilePath(filepath) { try { if (filepath !== "-") { fs.statSync(filepath); } } catch (err) { throw 'Unable to open path "' + filepath + '"'; } } function logToStdout(str, config) { if (typeof config.quiet === "undefined" || !config.quiet) { console.log(str); } }
J2TeaM/js-beautify
js/lib/cli.js
JavaScript
mit
14,890
DEBUG = True DISCOVERY_SERVICE_URL = 'localhost:6100/discoveryservice'
pwgn/microtut
commentservice/settings.py
Python
mit
72
# This file is a part of Redmin Agile (redmine_agile) plugin, # Agile board plugin for redmine # # Copyright (C) 2011-2015 RedmineCRM # http://www.redminecrm.com/ # # redmine_agile is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # redmine_agile is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with redmine_agile. If not, see <http://www.gnu.org/licenses/>. module RedmineAgile module Hooks class ViewsIssuesHook < Redmine::Hook::ViewListener def view_issues_sidebar_issues_bottom(context={}) context[:controller].send(:render_to_string, { :partial => 'agile_boards/issues_sidebar', :locals => context }) + context[:controller].send(:render_to_string, { :partial => "agile_charts/agile_charts", :locals => context }) end end end end
cema-sp/docker-redmine
to_data/plugins/redmine_agile/lib/redmine_agile/hooks/views_issues_hook.rb
Ruby
mit
1,258
var util = require('util'); /** * @param options {Object} A data blob parsed from a query string or JSON * response from the Asana API * @option {String} error The string code identifying the error. * @option {String} [error_uri] A link to help and information about the error. * @option {String} [error_description] A description of the error. * @constructor */ function OauthError(options) { /* jshint camelcase:false */ Error.call(this); if (typeof(options) !== 'object' || !options.error) { throw new Error('Invalid Oauth error: ' + options); } this.code = options.error; this.description = options.error_description || null; this.uri = options.error_uri || null; } util.inherits(OauthError, Error); module.exports = OauthError;
Asana/node-asana
lib/auth/oauth_error.js
JavaScript
mit
761
# encoding: utf-8 """Definition of french pronoun related features""" from __future__ import unicode_literals PERSONAL = "personal" SPECIAL_PERSONAL = "special_personal" SNUMERAL = "snumeral" POSSESSIVE = "possessive" DEMONSTRATIV = "demonstrativ" RELATIVE = "relative" INTERROGATIVE = "interrogative" INDEFINITE = "indefinite"
brouberol/pynlg
pynlg/lexicon/feature/pronoun/fr.py
Python
mit
332
package chart import ( "errors" "fmt" "io" "math" "github.com/golang/freetype/truetype" ) // StackedBar is a bar within a StackedBarChart. type StackedBar struct { Name string Width int Values []Value } // GetWidth returns the width of the bar. func (sb StackedBar) GetWidth() int { if sb.Width == 0 { return 50 } return sb.Width } // StackedBarChart is a chart that draws sections of a bar based on percentages. type StackedBarChart struct { Title string TitleStyle Style Width int Height int DPI float64 Background Style Canvas Style XAxis Style YAxis Style BarSpacing int Font *truetype.Font defaultFont *truetype.Font Bars []StackedBar Elements []Renderable } // GetDPI returns the dpi for the chart. func (sbc StackedBarChart) GetDPI(defaults ...float64) float64 { if sbc.DPI == 0 { if len(defaults) > 0 { return defaults[0] } return DefaultDPI } return sbc.DPI } // GetFont returns the text font. func (sbc StackedBarChart) GetFont() *truetype.Font { if sbc.Font == nil { return sbc.defaultFont } return sbc.Font } // GetWidth returns the chart width or the default value. func (sbc StackedBarChart) GetWidth() int { if sbc.Width == 0 { return DefaultChartWidth } return sbc.Width } // GetHeight returns the chart height or the default value. func (sbc StackedBarChart) GetHeight() int { if sbc.Height == 0 { return DefaultChartWidth } return sbc.Height } // GetBarSpacing returns the spacing between bars. func (sbc StackedBarChart) GetBarSpacing() int { if sbc.BarSpacing == 0 { return 100 } return sbc.BarSpacing } // Render renders the chart with the given renderer to the given io.Writer. func (sbc StackedBarChart) Render(rp RendererProvider, w io.Writer) error { if len(sbc.Bars) == 0 { return errors.New("Please provide at least one bar.") } r, err := rp(sbc.GetWidth(), sbc.GetHeight()) if err != nil { return err } if sbc.Font == nil { defaultFont, err := GetDefaultFont() if err != nil { return err } sbc.defaultFont = defaultFont } r.SetDPI(sbc.GetDPI(DefaultDPI)) canvasBox := sbc.getAdjustedCanvasBox(r, sbc.getDefaultCanvasBox()) sbc.drawBars(r, canvasBox) sbc.drawXAxis(r, canvasBox) sbc.drawYAxis(r, canvasBox) sbc.drawTitle(r) for _, a := range sbc.Elements { a(r, canvasBox, sbc.styleDefaultsElements()) } return r.Save(w) } func (sbc StackedBarChart) drawBars(r Renderer, canvasBox Box) { xoffset := canvasBox.Left for _, bar := range sbc.Bars { sbc.drawBar(r, canvasBox, xoffset, bar) xoffset += (sbc.GetBarSpacing() + bar.GetWidth()) } } func (sbc StackedBarChart) drawBar(r Renderer, canvasBox Box, xoffset int, bar StackedBar) int { barSpacing2 := sbc.GetBarSpacing() >> 1 bxl := xoffset + barSpacing2 bxr := bxl + bar.GetWidth() normalizedBarComponents := Values(bar.Values).Normalize() yoffset := canvasBox.Top for index, bv := range normalizedBarComponents { barHeight := int(math.Ceil(bv.Value * float64(canvasBox.Height()))) barBox := Box{ Top: yoffset, Left: bxl, Right: bxr, Bottom: Math.MinInt(yoffset+barHeight, canvasBox.Bottom-DefaultStrokeWidth), } Draw.Box(r, barBox, bv.Style.InheritFrom(sbc.styleDefaultsStackedBarValue(index))) yoffset += barHeight } return bxr } func (sbc StackedBarChart) drawXAxis(r Renderer, canvasBox Box) { if sbc.XAxis.Show { axisStyle := sbc.XAxis.InheritFrom(sbc.styleDefaultsAxes()) axisStyle.WriteToRenderer(r) r.MoveTo(canvasBox.Left, canvasBox.Bottom) r.LineTo(canvasBox.Right, canvasBox.Bottom) r.Stroke() r.MoveTo(canvasBox.Left, canvasBox.Bottom) r.LineTo(canvasBox.Left, canvasBox.Bottom+DefaultVerticalTickHeight) r.Stroke() cursor := canvasBox.Left for _, bar := range sbc.Bars { barLabelBox := Box{ Top: canvasBox.Bottom + DefaultXAxisMargin, Left: cursor, Right: cursor + bar.GetWidth() + sbc.GetBarSpacing(), Bottom: sbc.GetHeight(), } if len(bar.Name) > 0 { Draw.TextWithin(r, bar.Name, barLabelBox, axisStyle) } axisStyle.WriteToRenderer(r) r.MoveTo(barLabelBox.Right, canvasBox.Bottom) r.LineTo(barLabelBox.Right, canvasBox.Bottom+DefaultVerticalTickHeight) r.Stroke() cursor += bar.GetWidth() + sbc.GetBarSpacing() } } } func (sbc StackedBarChart) drawYAxis(r Renderer, canvasBox Box) { if sbc.YAxis.Show { axisStyle := sbc.YAxis.InheritFrom(sbc.styleDefaultsAxes()) axisStyle.WriteToRenderer(r) r.MoveTo(canvasBox.Right, canvasBox.Top) r.LineTo(canvasBox.Right, canvasBox.Bottom) r.Stroke() r.MoveTo(canvasBox.Right, canvasBox.Bottom) r.LineTo(canvasBox.Right+DefaultHorizontalTickWidth, canvasBox.Bottom) r.Stroke() ticks := Sequence.Float64(1.0, 0.0, 0.2) for _, t := range ticks { axisStyle.GetStrokeOptions().WriteToRenderer(r) ty := canvasBox.Bottom - int(t*float64(canvasBox.Height())) r.MoveTo(canvasBox.Right, ty) r.LineTo(canvasBox.Right+DefaultHorizontalTickWidth, ty) r.Stroke() axisStyle.GetTextOptions().WriteToRenderer(r) text := fmt.Sprintf("%0.0f%%", t*100) tb := r.MeasureText(text) Draw.Text(r, text, canvasBox.Right+DefaultYAxisMargin+5, ty+(tb.Height()>>1), axisStyle) } } } func (sbc StackedBarChart) drawTitle(r Renderer) { if len(sbc.Title) > 0 && sbc.TitleStyle.Show { Draw.TextWithin(r, sbc.Title, sbc.Box(), sbc.styleDefaultsTitle()) } } func (sbc StackedBarChart) getDefaultCanvasBox() Box { return sbc.Box() } func (sbc StackedBarChart) getAdjustedCanvasBox(r Renderer, canvasBox Box) Box { var totalWidth int for _, bar := range sbc.Bars { totalWidth += bar.GetWidth() + sbc.GetBarSpacing() } if sbc.XAxis.Show { xaxisHeight := DefaultVerticalTickHeight axisStyle := sbc.XAxis.InheritFrom(sbc.styleDefaultsAxes()) axisStyle.WriteToRenderer(r) cursor := canvasBox.Left for _, bar := range sbc.Bars { if len(bar.Name) > 0 { barLabelBox := Box{ Top: canvasBox.Bottom + DefaultXAxisMargin, Left: cursor, Right: cursor + bar.GetWidth() + sbc.GetBarSpacing(), Bottom: sbc.GetHeight(), } lines := Text.WrapFit(r, bar.Name, barLabelBox.Width(), axisStyle) linesBox := Text.MeasureLines(r, lines, axisStyle) xaxisHeight = Math.MaxInt(linesBox.Height()+(2*DefaultXAxisMargin), xaxisHeight) } } return Box{ Top: canvasBox.Top, Left: canvasBox.Left, Right: canvasBox.Left + totalWidth, Bottom: sbc.GetHeight() - xaxisHeight, } } return Box{ Top: canvasBox.Top, Left: canvasBox.Left, Right: canvasBox.Left + totalWidth, Bottom: canvasBox.Bottom, } } // Box returns the chart bounds as a box. func (sbc StackedBarChart) Box() Box { dpr := sbc.Background.Padding.GetRight(10) dpb := sbc.Background.Padding.GetBottom(50) return Box{ Top: 20, Left: 20, Right: sbc.GetWidth() - dpr, Bottom: sbc.GetHeight() - dpb, } } func (sbc StackedBarChart) styleDefaultsStackedBarValue(index int) Style { return Style{ StrokeColor: GetAlternateColor(index), StrokeWidth: 3.0, FillColor: GetAlternateColor(index), } } func (sbc StackedBarChart) styleDefaultsTitle() Style { return sbc.TitleStyle.InheritFrom(Style{ FontColor: DefaultTextColor, Font: sbc.GetFont(), FontSize: sbc.getTitleFontSize(), TextHorizontalAlign: TextHorizontalAlignCenter, TextVerticalAlign: TextVerticalAlignTop, TextWrap: TextWrapWord, }) } func (sbc StackedBarChart) getTitleFontSize() float64 { effectiveDimension := Math.MinInt(sbc.GetWidth(), sbc.GetHeight()) if effectiveDimension >= 2048 { return 48 } else if effectiveDimension >= 1024 { return 24 } else if effectiveDimension >= 512 { return 18 } else if effectiveDimension >= 256 { return 12 } return 10 } func (sbc StackedBarChart) styleDefaultsAxes() Style { return Style{ StrokeColor: DefaultAxisColor, Font: sbc.GetFont(), FontSize: DefaultAxisFontSize, FontColor: DefaultAxisColor, TextHorizontalAlign: TextHorizontalAlignCenter, TextVerticalAlign: TextVerticalAlignTop, TextWrap: TextWrapWord, } } func (sbc StackedBarChart) styleDefaultsElements() Style { return Style{ Font: sbc.GetFont(), } }
nicholasjackson/bench
vendor/github.com/wcharczuk/go-chart/stacked_bar_chart.go
GO
mit
8,263
package helpers import ( "testing" "github.com/stretchr/testify/assert" "gitlab.com/gitlab-org/gitlab-ci-multi-runner/common" "gitlab.com/gitlab-org/gitlab-ci-multi-runner/helpers" "os" ) var downloaderCredentials = common.BuildCredentials{ ID: 1000, Token: "test", URL: "test", } func TestArtifactsDownloaderRequirements(t *testing.T) { helpers.MakeFatalToPanic() cmd := ArtifactsDownloaderCommand{} assert.Panics(t, func() { cmd.Execute(nil) }) } func TestArtifactsDownloaderNotFound(t *testing.T) { network := &testNetwork{ downloadState: common.DownloadNotFound, } cmd := ArtifactsDownloaderCommand{ BuildCredentials: downloaderCredentials, network: network, } assert.Panics(t, func() { cmd.Execute(nil) }) assert.Equal(t, 1, network.downloadCalled) } func TestArtifactsDownloaderForbidden(t *testing.T) { network := &testNetwork{ downloadState: common.DownloadForbidden, } cmd := ArtifactsDownloaderCommand{ BuildCredentials: downloaderCredentials, network: network, } assert.Panics(t, func() { cmd.Execute(nil) }) assert.Equal(t, 1, network.downloadCalled) } func TestArtifactsDownloaderRetry(t *testing.T) { network := &testNetwork{ downloadState: common.DownloadFailed, } cmd := ArtifactsDownloaderCommand{ BuildCredentials: downloaderCredentials, network: network, retryHelper: retryHelper{ Retry: 2, }, } assert.Panics(t, func() { cmd.Execute(nil) }) assert.Equal(t, 3, network.downloadCalled) } func TestArtifactsDownloaderSucceeded(t *testing.T) { network := &testNetwork{ downloadState: common.DownloadSucceeded, } cmd := ArtifactsDownloaderCommand{ BuildCredentials: downloaderCredentials, network: network, } os.Remove(artifactsTestArchivedFile) fi, _ := os.Stat(artifactsTestArchivedFile) assert.Nil(t, fi) cmd.Execute(nil) assert.Equal(t, 1, network.downloadCalled) fi, _ = os.Stat(artifactsTestArchivedFile) assert.NotNil(t, fi) }
soiff/gitlab-ci-multi-runner
commands/helpers/artifacts_downloader_test.go
GO
mit
1,990
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ 'use strict'; var _cssPluginGlobal = this; var CSSBuildLoaderPlugin; (function (CSSBuildLoaderPlugin) { var global = (_cssPluginGlobal || {}); /** * Known issue: * - In IE there is no way to know if the CSS file loaded successfully or not. */ var BrowserCSSLoader = /** @class */ (function () { function BrowserCSSLoader() { this._pendingLoads = 0; } BrowserCSSLoader.prototype.attachListeners = function (name, linkNode, callback, errorback) { var unbind = function () { linkNode.removeEventListener('load', loadEventListener); linkNode.removeEventListener('error', errorEventListener); }; var loadEventListener = function (e) { unbind(); callback(); }; var errorEventListener = function (e) { unbind(); errorback(e); }; linkNode.addEventListener('load', loadEventListener); linkNode.addEventListener('error', errorEventListener); }; BrowserCSSLoader.prototype._onLoad = function (name, callback) { this._pendingLoads--; callback(); }; BrowserCSSLoader.prototype._onLoadError = function (name, errorback, err) { this._pendingLoads--; errorback(err); }; BrowserCSSLoader.prototype._insertLinkNode = function (linkNode) { this._pendingLoads++; var head = document.head || document.getElementsByTagName('head')[0]; var other = head.getElementsByTagName('link') || head.getElementsByTagName('script'); if (other.length > 0) { head.insertBefore(linkNode, other[other.length - 1]); } else { head.appendChild(linkNode); } }; BrowserCSSLoader.prototype.createLinkTag = function (name, cssUrl, externalCallback, externalErrorback) { var _this = this; var linkNode = document.createElement('link'); linkNode.setAttribute('rel', 'stylesheet'); linkNode.setAttribute('type', 'text/css'); linkNode.setAttribute('data-name', name); var callback = function () { return _this._onLoad(name, externalCallback); }; var errorback = function (err) { return _this._onLoadError(name, externalErrorback, err); }; this.attachListeners(name, linkNode, callback, errorback); linkNode.setAttribute('href', cssUrl); return linkNode; }; BrowserCSSLoader.prototype._linkTagExists = function (name, cssUrl) { var i, len, nameAttr, hrefAttr, links = document.getElementsByTagName('link'); for (i = 0, len = links.length; i < len; i++) { nameAttr = links[i].getAttribute('data-name'); hrefAttr = links[i].getAttribute('href'); if (nameAttr === name || hrefAttr === cssUrl) { return true; } } return false; }; BrowserCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { if (this._linkTagExists(name, cssUrl)) { externalCallback(); return; } var linkNode = this.createLinkTag(name, cssUrl, externalCallback, externalErrorback); this._insertLinkNode(linkNode); }; return BrowserCSSLoader; }()); var NodeCSSLoader = /** @class */ (function () { function NodeCSSLoader() { this.fs = require.nodeRequire('fs'); } NodeCSSLoader.prototype.load = function (name, cssUrl, externalCallback, externalErrorback) { var contents = this.fs.readFileSync(cssUrl, 'utf8'); // Remove BOM if (contents.charCodeAt(0) === NodeCSSLoader.BOM_CHAR_CODE) { contents = contents.substring(1); } externalCallback(contents); }; NodeCSSLoader.BOM_CHAR_CODE = 65279; return NodeCSSLoader; }()); // ------------------------------ Finally, the plugin var CSSPlugin = /** @class */ (function () { function CSSPlugin(cssLoader) { this.cssLoader = cssLoader; } CSSPlugin.prototype.load = function (name, req, load, config) { config = config || {}; var myConfig = config['vs/css'] || {}; global.inlineResources = myConfig.inlineResources; global.inlineResourcesLimit = myConfig.inlineResourcesLimit || 5000; var cssUrl = req.toUrl(name + '.css'); this.cssLoader.load(name, cssUrl, function (contents) { // Contents has the CSS file contents if we are in a build if (config.isBuild) { CSSPlugin.BUILD_MAP[name] = contents; CSSPlugin.BUILD_PATH_MAP[name] = cssUrl; } load({}); }, function (err) { if (typeof load.error === 'function') { load.error('Could not find ' + cssUrl + ' or it was empty'); } }); }; CSSPlugin.prototype.write = function (pluginName, moduleName, write) { // getEntryPoint is a Monaco extension to r.js var entryPoint = write.getEntryPoint(); // r.js destroys the context of this plugin between calling 'write' and 'writeFile' // so the only option at this point is to leak the data to a global global.cssPluginEntryPoints = global.cssPluginEntryPoints || {}; global.cssPluginEntryPoints[entryPoint] = global.cssPluginEntryPoints[entryPoint] || []; global.cssPluginEntryPoints[entryPoint].push({ moduleName: moduleName, contents: CSSPlugin.BUILD_MAP[moduleName], fsPath: CSSPlugin.BUILD_PATH_MAP[moduleName], }); write.asModule(pluginName + '!' + moduleName, 'define([\'vs/css!' + entryPoint + '\'], {});'); }; CSSPlugin.prototype.writeFile = function (pluginName, moduleName, req, write, config) { if (global.cssPluginEntryPoints && global.cssPluginEntryPoints.hasOwnProperty(moduleName)) { var fileName = req.toUrl(moduleName + '.css'); var contents = [ '/*---------------------------------------------------------', ' * Copyright (c) Microsoft Corporation. All rights reserved.', ' *--------------------------------------------------------*/' ], entries = global.cssPluginEntryPoints[moduleName]; for (var i = 0; i < entries.length; i++) { if (global.inlineResources) { contents.push(Utilities.rewriteOrInlineUrls(entries[i].fsPath, entries[i].moduleName, moduleName, entries[i].contents, global.inlineResources === 'base64', global.inlineResourcesLimit)); } else { contents.push(Utilities.rewriteUrls(entries[i].moduleName, moduleName, entries[i].contents)); } } write(fileName, contents.join('\r\n')); } }; CSSPlugin.prototype.getInlinedResources = function () { return global.cssInlinedResources || []; }; CSSPlugin.BUILD_MAP = {}; CSSPlugin.BUILD_PATH_MAP = {}; return CSSPlugin; }()); CSSBuildLoaderPlugin.CSSPlugin = CSSPlugin; var Utilities = /** @class */ (function () { function Utilities() { } Utilities.startsWith = function (haystack, needle) { return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle; }; /** * Find the path of a file. */ Utilities.pathOf = function (filename) { var lastSlash = filename.lastIndexOf('/'); if (lastSlash !== -1) { return filename.substr(0, lastSlash + 1); } else { return ''; } }; /** * A conceptual a + b for paths. * Takes into account if `a` contains a protocol. * Also normalizes the result: e.g.: a/b/ + ../c => a/c */ Utilities.joinPaths = function (a, b) { function findSlashIndexAfterPrefix(haystack, prefix) { if (Utilities.startsWith(haystack, prefix)) { return Math.max(prefix.length, haystack.indexOf('/', prefix.length)); } return 0; } var aPathStartIndex = 0; aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, '//'); aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'http://'); aPathStartIndex = aPathStartIndex || findSlashIndexAfterPrefix(a, 'https://'); function pushPiece(pieces, piece) { if (piece === './') { // Ignore return; } if (piece === '../') { var prevPiece = (pieces.length > 0 ? pieces[pieces.length - 1] : null); if (prevPiece && prevPiece === '/') { // Ignore return; } if (prevPiece && prevPiece !== '../') { // Pop pieces.pop(); return; } } // Push pieces.push(piece); } function push(pieces, path) { while (path.length > 0) { var slashIndex = path.indexOf('/'); var piece = (slashIndex >= 0 ? path.substring(0, slashIndex + 1) : path); path = (slashIndex >= 0 ? path.substring(slashIndex + 1) : ''); pushPiece(pieces, piece); } } var pieces = []; push(pieces, a.substr(aPathStartIndex)); if (b.length > 0 && b.charAt(0) === '/') { pieces = []; } push(pieces, b); return a.substring(0, aPathStartIndex) + pieces.join(''); }; Utilities.commonPrefix = function (str1, str2) { var len = Math.min(str1.length, str2.length); for (var i = 0; i < len; i++) { if (str1.charCodeAt(i) !== str2.charCodeAt(i)) { break; } } return str1.substring(0, i); }; Utilities.commonFolderPrefix = function (fromPath, toPath) { var prefix = Utilities.commonPrefix(fromPath, toPath); var slashIndex = prefix.lastIndexOf('/'); if (slashIndex === -1) { return ''; } return prefix.substring(0, slashIndex + 1); }; Utilities.relativePath = function (fromPath, toPath) { if (Utilities.startsWith(toPath, '/') || Utilities.startsWith(toPath, 'http://') || Utilities.startsWith(toPath, 'https://')) { return toPath; } // Ignore common folder prefix var prefix = Utilities.commonFolderPrefix(fromPath, toPath); fromPath = fromPath.substr(prefix.length); toPath = toPath.substr(prefix.length); var upCount = fromPath.split('/').length; var result = ''; for (var i = 1; i < upCount; i++) { result += '../'; } return result + toPath; }; Utilities._replaceURL = function (contents, replacer) { // Use ")" as the terminator as quotes are oftentimes not used at all return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, function (_) { var matches = []; for (var _i = 1; _i < arguments.length; _i++) { matches[_i - 1] = arguments[_i]; } var url = matches[0]; // Eliminate starting quotes (the initial whitespace is not captured) if (url.charAt(0) === '"' || url.charAt(0) === '\'') { url = url.substring(1); } // The ending whitespace is captured while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) { url = url.substring(0, url.length - 1); } // Eliminate ending quotes if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') { url = url.substring(0, url.length - 1); } if (!Utilities.startsWith(url, 'data:') && !Utilities.startsWith(url, 'http://') && !Utilities.startsWith(url, 'https://')) { url = replacer(url); } return 'url(' + url + ')'; }); }; Utilities.rewriteUrls = function (originalFile, newFile, contents) { return this._replaceURL(contents, function (url) { var absoluteUrl = Utilities.joinPaths(Utilities.pathOf(originalFile), url); return Utilities.relativePath(newFile, absoluteUrl); }); }; Utilities.rewriteOrInlineUrls = function (originalFileFSPath, originalFile, newFile, contents, forceBase64, inlineByteLimit) { var fs = require.nodeRequire('fs'); var path = require.nodeRequire('path'); return this._replaceURL(contents, function (url) { if (/\.(svg|png)$/.test(url)) { var fsPath = path.join(path.dirname(originalFileFSPath), url); var fileContents = fs.readFileSync(fsPath); if (fileContents.length < inlineByteLimit) { global.cssInlinedResources = global.cssInlinedResources || []; var normalizedFSPath = fsPath.replace(/\\/g, '/'); if (global.cssInlinedResources.indexOf(normalizedFSPath) >= 0) { // console.warn('CSS INLINING IMAGE AT ' + fsPath + ' MORE THAN ONCE. CONSIDER CONSOLIDATING CSS RULES'); } global.cssInlinedResources.push(normalizedFSPath); var MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png'; var DATA = ';base64,' + fileContents.toString('base64'); if (!forceBase64 && /\.svg$/.test(url)) { // .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris var newText = fileContents.toString() .replace(/"/g, '\'') .replace(/</g, '%3C') .replace(/>/g, '%3E') .replace(/&/g, '%26') .replace(/#/g, '%23') .replace(/\s+/g, ' '); var encodedData = ',' + newText; if (encodedData.length < DATA.length) { DATA = encodedData; } } return '"data:' + MIME + DATA + '"'; } } var absoluteUrl = Utilities.joinPaths(Utilities.pathOf(originalFile), url); return Utilities.relativePath(newFile, absoluteUrl); }); }; return Utilities; }()); CSSBuildLoaderPlugin.Utilities = Utilities; (function () { var cssLoader = null; var isElectron = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions['electron'] !== 'undefined'); if (typeof process !== 'undefined' && process.versions && !!process.versions.node && !isElectron) { cssLoader = new NodeCSSLoader(); } else { cssLoader = new BrowserCSSLoader(); } define('vs/css', new CSSPlugin(cssLoader)); })(); })(CSSBuildLoaderPlugin || (CSSBuildLoaderPlugin = {}));
Krzysztof-Cieslak/vscode
src/vs/css.build.js
JavaScript
mit
17,970
namespace SIL.XForge.WebApi.Server.Dtos { public class ParatextProjectDto { public string Id { get; set; } public string Name { get; set; } public string LanguageTag { get; set; } public string LanguageName { get; set; } } }
sillsdev/web-scriptureforge
src/netcore-api/SIL.XForge.WebApi.Server/Dtos/ParatextProjectDto.cs
C#
mit
269
DEMO.App.factory("utilitiesService", ["$http", function ($http) { "use strict"; var getQueryStringValue = function (name) { try { var args = window.location.search.substring(1).split("&"); var r = ""; for (var i = 0; i < args.length; i++) { var n = args[i].split("="); if (n[0] == name) r = decodeURIComponent(n[1]); } return r; } catch (err) { return 'undefined'; } }; return { getQueryStringValue: getQueryStringValue }; }]);
dafunkphenomenon/dev
JSLinkModule/JSLinkModule/Scripts/app/services/utilities.js
JavaScript
mit
618
'use strict'; var grunt = require('grunt'); var fs = require('fs'); var rimraf = require('rimraf'); var mkdirp = require('mkdirp'); var flow = require('nue').flow; var as = require('nue').as; var _h = require('./testHelpers'); var throwOrDone = _h.throwOrDone; var output = _h.fixtures('output'); var istanbul = require('istanbul'); var helper = require('../tasks/helpers').init(grunt); var isparta = require('isparta'); /* * ======== A Handy Little Nodeunit Reference ======== * https://github.com/caolan/nodeunit */ exports['istanbul'] = { setUp : function(done) { flow(function() { mkdirp(output(), this.async(as(1))); }, throwOrDone(done))(); }, tearDown : function(done) { rimraf(output(), done); }, 'instrument' : function(test) { test.expect(3); var fixtures = _h.fixtures('instrument'); helper.instrument([ fixtures('hello.js') ], { basePath : output(), flatten : true }, flow(function read() { fs.stat(fixtures('hello.js'), this.async(as(1))); fs.stat(output('hello.js'), this.async(as(1))); }, function(src, dest) { test.equal(true, src.isFile()); test.equal(src.isFile(), dest.isFile()); test.equal(true, src.size < dest.size); this.next(); }, throwOrDone(test.done.bind(test)))); }, 'customInstrument': function(test) { test.expect(3); var fixtures = _h.fixtures('instrument'); helper.instrument([ fixtures('hello.es6') ], { basePath : output(), flatten : true, instrumenter: isparta.Instrumenter }, flow(function read() { fs.stat(fixtures('hello.es6'), this.async(as(1))); fs.stat(output('hello.es6'), this.async(as(1))); }, function(src, dest) { test.equal(true, src.isFile()); test.equal(src.isFile(), dest.isFile()); test.equal(true, src.size < dest.size); this.next(); }, throwOrDone(test.done.bind(test)))); }, 'storeCoverage' : function(test) { test.expect(1); var fixtures = _h.fixtures('storeCoverage'); var cov = JSON.parse('{ "aaa":1, "bbb":2, "ccc":3 }'); helper.storeCoverage(cov, { dir : output(), json : 'coverage.json' }, flow(function read() { fs.readFile(output('coverage.json'), 'utf8', this.async(as(1))); }, function assert(txt) { test.deepEqual(cov, JSON.parse(txt)); this.next(); }, throwOrDone(test.done.bind(test)))); }, 'makeReport' : function(test) { test.expect(2); var fixtures = _h.fixtures('makeReport'); helper.makeReport([ fixtures('coverage.json') ], { type : 'lcov', dir : output(), print : 'none' }, flow(function read() { fs.readFile(output('lcov.info'), 'utf8', this.async(as(1))); fs.readFile(output('lcov-report/index.html'), 'utf8', this.async(as(1))); }, function assert(lcov, html) { test.ok(lcov); test.ok(html); this.next(); }, throwOrDone(test.done.bind(test)))); }, 'makeReport.reporters' : function(test) { test.expect(4); var fixtures = _h.fixtures('makeReport'); var textNotWritten = true; var TextReport = istanbul.Report.create('text').constructor; var writeTextReport = TextReport.prototype.writeReport; TextReport.prototype.writeReport = function() { textNotWritten = false; }; var textSummaryWritten = false; var TextSummaryReport = istanbul.Report.create('text-summary').constructor; var writeTextSummaryReport = TextSummaryReport.prototype.writeReport; TextSummaryReport.prototype.writeReport = function() { textSummaryWritten = true; }; helper.makeReport([ fixtures('coverage.json') ], { reporters : { lcov : {dir : output()}, text : false, 'text-summary' : true }, print : 'none' }, flow(function read() { fs.readFile(output('lcov.info'), 'utf8', this.async(as(1))); fs.readFile(output('lcov-report/index.html'), 'utf8', this.async(as(1))); }, function assert(lcov, html) { TextReport.prototype.writeReport = writeTextReport; TextSummaryReport.prototype.writeReport = writeTextSummaryReport; test.ok(lcov); test.ok(html); test.ok(textNotWritten); test.ok(textSummaryWritten); this.next(); }, throwOrDone(test.done.bind(test)))); } };
acvetkov/grunt-istanbul
test/istanbul_test.js
JavaScript
mit
4,311
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.maxifier.mxcache; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; /** * This is just a marker annotation that says that this method should not be deleted or modified because it is * a part of public API of MxCache. * * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ @Retention(value = RetentionPolicy.SOURCE) @Target(value = {METHOD, TYPE, CONSTRUCTOR, FIELD, PARAMETER}) @Documented public @interface PublicAPI { }
akochurov/mxcache
mxcache-runtime/src/main/java/com/maxifier/mxcache/PublicAPI.java
Java
mit
684
/** * @author mr.doob / http://mrdoob.com/ */ THREE.SoftwareRenderer = function () { console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); var canvas = document.createElement( 'canvas' ); var context = canvas.getContext( '2d' ); var imagedata = context.getImageData( 0, 0, canvas.width, canvas.height ); var data = imagedata.data; var canvasWidth = canvas.width; var canvasHeight = canvas.height; var canvasWidthHalf = canvasWidth / 2; var canvasHeightHalf = canvasHeight / 2; var edges = [ new Edge(), new Edge(), new Edge() ]; var span = new Span(); var projector = new THREE.Projector(); this.domElement = canvas; this.autoClear = true; this.setSize = function ( width, height ) { canvas.width = width; canvas.height = height; canvasWidth = canvas.width; canvasHeight = canvas.height; canvasWidthHalf = width / 2; canvasHeightHalf = height / 2; imagedata = context.getImageData( 0, 0, width, height ); data = imagedata.data; }; this.clear = function () { for ( var i = 3, l = data.length; i < l; i += 4 ) { data[ i ] = 0; } }; this.render = function ( scene, camera ) { var m, ml, element, material, dom, v1x, v1y; if ( this.autoClear ) this.clear(); var renderData = projector.projectScene( scene, camera ); var elements = renderData.elements; elements.sort( function painterSort( a, b ) { return a.z - b.z; } ); for ( var e = 0, el = elements.length; e < el; e ++ ) { var element = elements[ e ]; if ( element instanceof THREE.RenderableFace3 ) { var v1 = element.v1.positionScreen; var v2 = element.v2.positionScreen; var v3 = element.v3.positionScreen; drawTriangle( v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, 0xff0000, v2.x * canvasWidthHalf + canvasWidthHalf, - v2.y * canvasHeightHalf + canvasHeightHalf, 0x00ff00, v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, 0x0000ff ) } else if ( element instanceof THREE.RenderableFace4 ) { var v1 = element.v1.positionScreen; var v2 = element.v2.positionScreen; var v3 = element.v3.positionScreen; var v4 = element.v4.positionScreen; drawTriangle( v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, 0xff0000, v2.x * canvasWidthHalf + canvasWidthHalf, - v2.y * canvasHeightHalf + canvasHeightHalf, 0x00ff00, v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, 0x0000ff ); drawTriangle( v3.x * canvasWidthHalf + canvasWidthHalf, - v3.y * canvasHeightHalf + canvasHeightHalf, 0x0000ff, v4.x * canvasWidthHalf + canvasWidthHalf, - v4.y * canvasHeightHalf + canvasHeightHalf, 0xff00ff, v1.x * canvasWidthHalf + canvasWidthHalf, - v1.y * canvasHeightHalf + canvasHeightHalf, 0xff0000 ); } } context.putImageData( imagedata, 0, 0 ); }; function drawPixel( x, y, r, g, b ) { var offset = ( x + y * canvasWidth ) * 4; if ( x < 0 || y < 0 ) return; if ( x > canvasWidth || y > canvasHeight ) return; if ( data[ offset + 3 ] ) return; data[ offset ] = r; data[ offset + 1 ] = g; data[ offset + 2 ] = b; data[ offset + 3 ] = 255; } /* function drawRectangle( x1, y1, x2, y2, color ) { var r = color >> 16 & 255; var g = color >> 8 & 255; var b = color & 255; var xmin = Math.min( x1, x2 ) >> 0; var xmax = Math.max( x1, x2 ) >> 0; var ymin = Math.min( y1, y2 ) >> 0; var ymax = Math.max( y1, y2 ) >> 0; for ( var y = ymin; y < ymax; y ++ ) { for ( var x = xmin; x < xmax; x ++ ) { drawPixel( x, y, r, g, b ); } } } */ function drawTriangle( x1, y1, color1, x2, y2, color2, x3, y3, color3 ) { // http://joshbeam.com/articles/triangle_rasterization/ edges[ 0 ].set( x1, y1, color1, x2, y2, color2 ); edges[ 1 ].set( x2, y2, color2, x3, y3, color3 ); edges[ 2 ].set( x3, y3, color3, x1, y1, color1 ); var maxLength = 0; var longEdge = 0; // find edge with the greatest length in the y axis for ( var i = 0; i < 3; i ++ ) { var length = ( edges[ i ].y2 - edges[ i ].y1 ); if ( length > maxLength ) { maxLength = length; longEdge = i; } } var shortEdge1 = ( longEdge + 1 ) % 3; var shortEdge2 = ( longEdge + 2 ) % 3; drawSpans( edges[ longEdge ], edges[ shortEdge1 ] ); drawSpans( edges[ longEdge ], edges[ shortEdge2 ] ); } function drawSpans( e1, e2 ) { var e1ydiff = e1.y2 - e1.y1; if ( e1ydiff === 0 ) return; var e2ydiff = e2.y2 - e2.y1; if ( e2ydiff === 0 ) return; var e1xdiff = e1.x2 - e1.x1; var e2xdiff = e2.x2 - e2.x1; var e1colordiffr = e1.r2 - e1.r1; var e1colordiffg = e1.g2 - e1.g1; var e1colordiffb = e1.b2 - e1.b1; var e2colordiffr = e2.r2 - e2.r1; var e2colordiffg = e2.g2 - e2.g1; var e2colordiffb = e2.b2 - e2.b1; var factor1 = ( e2.y1 - e1.y1 ) / e1ydiff; var factorStep1 = 1 / e1ydiff; var factor2 = 0; var factorStep2 = 1 / e2ydiff; for ( var y = e2.y1; y < e2.y2; y ++ ) { span.set( e1.x1 + ( e1xdiff * factor1 ), e1.r1 + e1colordiffr * factor1, e1.g1 + e1colordiffg * factor1, e1.b1 + e1colordiffb * factor1, e2.x1 + ( e2xdiff * factor2 ), e2.r1 + e2colordiffr * factor2, e2.g1 + e2colordiffg * factor2, e2.b1 + e2colordiffb * factor2 ); var xdiff = span.x2 - span.x1; if ( xdiff > 0 ) { var colordiffr = span.r2 - span.r1; var colordiffg = span.g2 - span.g1; var colordiffb = span.b2 - span.b1; var factor = 0; var factorStep = 1 / xdiff; for ( var x = span.x1; x < span.x2; x ++ ) { var r = span.r1 + colordiffr * factor; var g = span.g1 + colordiffg * factor; var b = span.b1 + colordiffb * factor; drawPixel( x, y, r, g, b ); factor += factorStep; } } factor1 += factorStep1; factor2 += factorStep2; } } function Edge() { this.x1 = 0; this.y1 = 0; this.x2 = 0; this.y2 = 0; this.r1 = 0; this.g1 = 0; this.b1 = 0; this.r2 = 0; this.g2 = 0; this.b2 = 0; this.set = function ( x1, y1, color1, x2, y2, color2 ) { if ( y1 < y2 ) { this.x1 = x1 >> 0; this.y1 = y1 >> 0; this.x2 = x2 >> 0; this.y2 = y2 >> 0; this.r1 = color1 >> 16 & 255; this.g1 = color1 >> 8 & 255; this.b1 = color1 & 255; this.r2 = color2 >> 16 & 255; this.g2 = color2 >> 8 & 255; this.b2 = color2 & 255; } else { this.x1 = x2 >> 0; this.y1 = y2 >> 0; this.x2 = x1 >> 0; this.y2 = y1 >> 0; this.r1 = color2 >> 16 & 255; this.g1 = color2 >> 8 & 255; this.b1 = color2 & 255; this.r2 = color1 >> 16 & 255; this.g2 = color1 >> 8 & 255; this.b2 = color1 & 255; } } } function Span() { this.x1 = 0; this.x2 = 0; this.r1 = 0; this.g1 = 0; this.b1 = 0; this.r2 = 0; this.g2 = 0; this.b2 = 0; this.set = function ( x1, r1, g1, b1, x2, r2, g2, b2 ) { if ( x1 < x2 ) { this.x1 = x1 >> 0; this.x2 = x2 >> 0; this.r1 = r1; this.g1 = g1; this.b1 = b1; this.r2 = r2; this.g2 = g2; this.b2 = b2; } else { this.x1 = x2 >> 0; this.x2 = x1 >> 0; this.r1 = r2; this.g1 = g2; this.b1 = b2; this.r2 = r1; this.g2 = g1; this.b2 = b1; } } } };
juhnowski/J_and_K_Softlabs
httpdocs/js/renderers/SoftwareRenderer.js
JavaScript
mit
7,441
var NWM = function() { // Known layouts this.layouts = { tile: tile, wide: wide, grid: grid }; // monitors this.monitors = [ ]; this.windows = { }; // counter this.counter = 1; }; NWM.prototype.addMonitor = function (monitor) { this.monitors.push(new Monitor(this, monitor)); }; NWM.prototype.addWindow = function () { var id = this.counter++; // create new div $('<div id="w'+id+'" class="win">#'+id+'</div>').appendTo('#monitor'); // bind to enternotify var self = this; $('#w'+id).bind('mouseenter', function() { self.enterNotify({ id: id }); }); // add to management this.windows[id] = new Window(id); }; NWM.prototype.removeWindow = function(id) { delete this.windows[id]; $('#w'+id).remove(); if(Object.keys(nwm.windows).length > 0) { nwm.focusWindow(nwm.windows[Math.min.apply(Math, Object.keys(nwm.windows))].id); } }; NWM.prototype.focusWindow = function(id) { this.monitors[0].focused_window = id; $('.focus').removeClass('focus'); $('#w'+id).addClass('focus'); }; NWM.prototype.enterNotify = function(event) { this.focusWindow(event.id); }; NWM.prototype.rearrange = function() { this.monitors.forEach(function(monitor) { monitor.workspaces[0].rearrange(); }); }; NWM.prototype.nextLayout = function(name) { var keys = Object.keys(this.layouts); var pos = keys.indexOf(name); // Wrap around the array return (keys[pos+1] ? keys[pos+1] : keys[0] ); };
ellis/nwm
test/nwm.js
JavaScript
mit
1,458
import kol.Error as Error from GenericRequest import GenericRequest from kol.manager import PatternManager from kol.util import Report class SendMessageRequest(GenericRequest): def __init__(self, session, message): super(SendMessageRequest, self).__init__(session) self.url = session.serverURL + "sendmessage.php?toid=" self.requestData['action'] = 'send' self.requestData['pwd'] = session.pwd self.requestData['towho'] = message["userId"] self.requestData['message'] = message["text"] # Add the items to the message. if "items" in message and len(message["items"]) > 0: i = 1 for item in message["items"]: self.requestData['whichitem%s' % i] = item["id"] self.requestData['howmany%s' % i] = item["quantity"] i += 1 # Add meat to the message. if "meat" in message: self.requestData["sendmeat"] = message["meat"] else: self.requestData["sendmeat"] = 0 def parseResponse(self): hardcoreRoninPattern = PatternManager.getOrCompilePattern('userInHardcoreRonin') ignoringPattern = PatternManager.getOrCompilePattern('userIgnoringUs') notEnoughItemsPattern = PatternManager.getOrCompilePattern('notEnoughItemsToSend') sentMessagePattern = PatternManager.getOrCompilePattern('messageSent') trendyPattern = PatternManager.getOrCompilePattern('kmailNotSentUserTrendy') ignoringUserPattern = PatternManager.getOrCompilePattern('weAreIgnoringUser') if hardcoreRoninPattern.search(self.responseText): raise Error.Error("Unable to send items or meat. User is in hardcore or ronin.", Error.USER_IN_HARDCORE_RONIN) elif ignoringPattern.search(self.responseText): raise Error.Error("Unable to send message. User is ignoring us.", Error.USER_IS_IGNORING) elif notEnoughItemsPattern.search(self.responseText): raise Error.Error("You don't have enough of one of the items you're trying to send.", Error.ITEM_NOT_FOUND) elif trendyPattern.search(self.responseText): raise Error.Error("Unable to send items or meat. User is too trendy.", Error.USER_IN_HARDCORE_RONIN) elif ignoringUserPattern.search(self.responseText): raise Error.Error("Unable to send message. We are ignoring the other player.", Error.USER_IS_IGNORING) elif sentMessagePattern.search(self.responseText) == None: Report.alert("system", "Received unknown response when attempting to send a message.") Report.alert("system", self.responseText) raise Error.Error("Unknown error", Error.REQUEST_FATAL)
KevZho/buffbot
kol/request/SendMessageRequest.py
Python
mit
2,734
define({ "queries": "Truy vấn", "addNew": "Thêm Mới", "newQuery": "Truy vấn Mới", "queryLayer": "Lớp Truy vấn", "setSource": "Thiết lập", "setDataSource": "Thiết lập Nguồn Dữ liệu", "name": "Tên", "querySource": "Nguồn dữ liệu", "queryName": "Tên tác vụ", "queryDefinition": "Định nghĩa Bộ lọc", "resultsSetting": "Thiết lập Kết quả", "symbolSetting": "Thiết lập Ký hiệu", "resultSettingTip": "Xác định nội dung và cách thức hiển thị kết quả đầu ra.", "resultItemTitle": "Tiêu đề của từng mục kết quả", "resultItemContent": "Các thuộc tính của trường này sẽ hiển thị", "fieldsSetTip": "Chọn các trường mà bạn muốn hiển thị. Chọn một trường để cập nhật bí danh, thứ tự và định dạng của trường đó.", "addField": "Thêm Trường", "visibility": "Khả năng hiển thị", "alias": "Bí danh", "specialType": "Loại đặc biệt", "actions": "Các hành động", "none": "Không có", "link": "Liên kết", "image": "Hình ảnh", "noField": "Không có trường nào", "operationalLayerTip": "Thêm kết quả như lớp hoạt động", "setLayerSymbolTip": "Thiết lập ký hiệu cho kết quả truy vấn: ", "setSelectedSymbolTip": "Thiết lập ký hiệu của đối tượng được chọn.", "notUseFilter": "Không sử dụng bộ lọc", "setSourceTip": "Vui lòng thiết lập nguồn truy vấn.", "setFilterTip": "Vui lòng thiết lập bộ lọc chính xác.", "ok": "OK", "cancel": "Hủy", "noFilterTip": "Nếu biểu thức bộ lọc không được xác định, tác vụ truy vấn này sẽ liệt kê tất cả các đối tượng trong nguồn dữ liệu đã chỉ định.", "relationships": "Mối quan hệ", "addRelationshipLayer": "Thêm Mối Quan hệ Mới", "relatedTo": "Liên quan đến", "selectOption": "Vui lòng chọn..", "resultItemSorting": "Sắp xếp Mục Kết quả", "field": "Trường", "sortingOrder": "Thứ tự", "configureFieldsTip": "Vui lòng cấu hình các trường dùng để sắp xếp truy vấn.", "setSortingFields": "Thiết lập Trường Sắp xếp", "ascending": "Tăng dần", "descending": "Giảm dần", "sortBy": "Sắp xếp theo", "thenBy": "Sau đó theo", "addTask": "Thêm Tác vụ", "noTasksTip": "Không có truy vấn được cấu hình. Nhấp vào \"${newQuery}\" để thêm một truy vấn mới.", "infoText": "Thông tin", "filters": "Bộ lọc", "results": "Kết quả", "optionsText": "Tùy chọn", "summaryText": "Tóm tắt", "attributeFilter": "Bộ lọc thuộc tính", "attributeFilterTip": "Xác định biểu thức thuộc tính sử dụng trong tiện ích để lọc lớp truy vấn.", "defineWhereClause": "Xác định mệnh đề where cho truy vấn.", "noExpressionDefinedTip": "Không có biểu thức nào được xác định. Tất cả bản ghi sẽ được trả về.", "setExpressions": "Thiết lập Biểu thức", "spatialFilter": "Bộ lọc không gian", "spatialFilterTip": "Chọn bộ lọc không gian sẽ sẵn có cho người dùng cuối.", "defaultOption": "Mặc định", "useCurrentExtentTip": "Chỉ trả về đối tượng trong phạm vi bản đồ hiện tại", "useDrawGraphicTip": "Chỉ trả về các đối tượng giao cắt với hình dạng đã được vẽ trên bản đồ", "useFeaturesTip": "Chỉ trả về đối tượng có mối quan hệ về không gian với đối tượng trong lớp khác", "noSpatialLimitTip": "Trả về đối tượng trong phạm vi đầy đủ của bản đồ", "drawingTools": "Chọn công cụ vẽ", "bufferSettings": "Bật tùy chọn vùng đệm", "defaultDistance": "Khoảng cách mặc định", "bufferDistance": "Khoảng cách vùng đệm", "defaultUnit": "Đơn vị mặc định", "miles": "Dặm", "kilometers": "Kilômét", "feet": "Feet", "meters": "Mét", "yards": "Thước", "nauticalMiles": "Hải lý", "availableSpatialRelationships": "Chọn quy tắc mối quan hệ không gian", "setSpatialRelationships": "Thiết lập Mối quan hệ Không gian", "availability": "Mức độ khả dụng", "relationship": "Mối quan hệ", "label": "Nhãn", "intersect": "giao cắt", "contain": "bao gồm", "areContainedIn": "được bao gồm trong", "cross": "gạch ngang", "envelopeIntersect": "đường bao giao cắt", "overlap": "xếp chồng", "areOverlapped": "bị xếp chồng", "touch": "chạm", "within": "bên trong", "areWithin": "ở bên trong", "indexIntersect": "chỉ số giao cắt", "itemTitle": "Tiêu đề Mục", "displayFields": "Trường Hiển thị", "sortingFields": "Phân loại các mục kết quả", "setDisplayFields": "Thiết lập Trường Hiển thị", "symbol": "Ký hiệu", "setSymbol": "Sử dụng ký hiệu tùy chỉnh", "changeSymbolAtRuntime": "Cho phép thay đổi ký hiệu khi đang thực hiện", "serviceSymbolTip": "Sử dụng các ký hiệu do lớp xác định", "exportTip": "Cho phép xuất kết quả", "keepResultsTip": "Lưu kết quả trên bản đồ sau khi đóng tiện ích", "queryRelatedRecords": "Bản ghi liên quan đến truy vấn", "createLayerForTaskTip": "Chỉ định cách tác vụ truy vấn tạo lớp", "oneLayerForTaskTip": "Ghi đè lớp mỗi lần thực hiện truy vấn", "multipleLayerForTaskTip": "Tạo lớp mới mỗi lần thực hiện truy vấn", "makeDefault": "Đặt làm mặc định", "icon": "Biểu tượng", "newTask": "Tác vụ Mới", "addTaskTip": "Thêm một hoặc nhiều quy vấn vào tiện ích và cấu hình các thông số cho mỗi quy vấn.", "webMapPopupTip": "Sử dụng cấu hình pop-up của lớp trong bản đồ web", "customPopupTip": "Định cấu hình nội dung tùy chỉnh", "showResultsSetActions": "Hiện các tác vụ cho kết quả đã đặt", "zoomTo": "Phóng tới", "openAttributeTable": "Mở trong Bảng Thuộc tính", "content": "Nội dung", "displaySQLTip": "Hiển thị biểu thức SQL cho người dùng cuối", "useLayerDefaultSymbol": "Sử dụng ký hiệu mặc định của lớp", "setCustomIcon": "Đặt ký hiệu tùy chỉnh", "layerDefaultSymbolTip": "Sử dụng ký hiệu mặc định của lớp", "uploadImage": "Tải ảnh lên", "attributeCriteira": "Tiêu chí thuộc tính", "specifyFilterAtRuntimeTip": "Người dùng sẽ phải chỉ định tham số cho biểu thức này.", "value": "GIÁ TRỊ", "hideLayersTip": "Tắt lớp kết quả truy vấn khi tiện ích bị đóng." });
cmccullough2/cmv-wab-widgets
wab/2.3/widgets/Query/setting/nls/vi/strings.js
JavaScript
mit
6,905
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceHighlighting { [UseExportProvider] public class InteractiveBraceHighlightingTests { private static IEnumerable<T> Enumerable<T>(params T[] array) => array; private static async Task<IEnumerable<ITagSpan<BraceHighlightTag>>> ProduceTagsAsync( TestWorkspace workspace, ITextBuffer buffer, int position) { var producer = new BraceHighlightingViewTaggerProvider( workspace.ExportProvider.GetExportedValue<IThreadingContext>(), workspace.GetService<IBraceMatchingService>(), workspace.GetService<IForegroundNotificationService>(), AsynchronousOperationListenerProvider.NullProvider); var context = new TaggerContext<BraceHighlightTag>( buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(), buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, position)); await producer.GetTestAccessor().ProduceTagsAsync(context); return context.tagSpans; } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)] public async Task TestCurlies() { var code = "public class C {\r\n}"; using var workspace = TestWorkspace.CreateCSharp(code, parseOptions: Options.Script); var buffer = workspace.Documents.First().GetTextBuffer(); // Before open curly var result = await ProduceTagsAsync(workspace, buffer, 14); Assert.True(result.IsEmpty()); // At open curly result = await ProduceTagsAsync(workspace, buffer, 15); Assert.True(result.Select(ts => ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(15, 16), Span.FromBounds(18, 19)))); // After open curly result = await ProduceTagsAsync(workspace, buffer, 16); Assert.True(result.IsEmpty()); // At close curly result = await ProduceTagsAsync(workspace, buffer, 18); Assert.True(result.IsEmpty()); // After close curly result = await ProduceTagsAsync(workspace, buffer, 19); Assert.True(result.Select(ts => ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(15, 16), Span.FromBounds(18, 19)))); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)] public async Task TestTouchingItems() { var code = "public class C {\r\n public void Goo(){}\r\n}"; using var workspace = TestWorkspace.CreateCSharp(code, Options.Script); var buffer = workspace.Documents.First().GetTextBuffer(); // Before open curly var result = await ProduceTagsAsync(workspace, buffer, 35); Assert.True(result.Select(ts => ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(35, 36), Span.FromBounds(36, 37)))); // At open curly result = await ProduceTagsAsync(workspace, buffer, 36); Assert.True(result.IsEmpty()); // After open curly result = await ProduceTagsAsync(workspace, buffer, 37); Assert.True(result.Select(ts => ts.Span.Span).SetEquals( Enumerable(Span.FromBounds(35, 36), Span.FromBounds(36, 37), Span.FromBounds(37, 38), Span.FromBounds(38, 39)))); // At close curly result = await ProduceTagsAsync(workspace, buffer, 38); Assert.True(result.IsEmpty()); // After close curly result = await ProduceTagsAsync(workspace, buffer, 39); Enumerable(Span.FromBounds(37, 38), Span.FromBounds(38, 39)); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)] public async Task TestAngles() { var code = "/// <summary>Goo</summary>\r\npublic class C<T> {\r\n void Goo() {\r\n bool a = b < c;\r\n bool d = e > f;\r\n }\r\n} "; using var workspace = TestWorkspace.CreateCSharp(code, parseOptions: Options.Script); var buffer = workspace.Documents.First().GetTextBuffer(); // Before open angle of generic var result = await ProduceTagsAsync(workspace, buffer, 42); Assert.True(result.Select(ts => ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(42, 43), Span.FromBounds(44, 45)))); // After close angle of generic result = await ProduceTagsAsync(workspace, buffer, 45); Assert.True(result.Select(ts => ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(42, 43), Span.FromBounds(44, 45)))); async Task assertNoTags(int position, char expectedChar) { Assert.Equal(expectedChar, buffer.CurrentSnapshot[position]); result = await ProduceTagsAsync(workspace, buffer, position); Assert.True(result.IsEmpty()); result = await ProduceTagsAsync(workspace, buffer, position + 1); Assert.True(result.IsEmpty()); } // Doesn't highlight angles of XML doc comments var xmlTagStartPosition = 4; await assertNoTags(xmlTagStartPosition, '<'); var xmlTagEndPosition = 12; await assertNoTags(xmlTagEndPosition, '>'); var xmlEndTagStartPosition = 16; await assertNoTags(xmlEndTagStartPosition, '<'); var xmlEndTagEndPosition = 25; await assertNoTags(xmlEndTagEndPosition, '>'); // Doesn't highlight operators var openAnglePosition = 15 + buffer.CurrentSnapshot.GetLineFromLineNumber(3).Start; await assertNoTags(openAnglePosition, '<'); var closeAnglePosition = 15 + buffer.CurrentSnapshot.GetLineFromLineNumber(4).Start; await assertNoTags(closeAnglePosition, '>'); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)] public async Task TestSwitch() { var code = @" class C { void M(int variable) { switch (variable) { case 0: break; } } } "; using var workspace = TestWorkspace.CreateCSharp(code, parseOptions: Options.Script); var buffer = workspace.Documents.First().GetTextBuffer(); // At switch open paren var result = await ProduceTagsAsync(workspace, buffer, 62); AssertEx.Equal(Enumerable(new Span(62, 1), new Span(71, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // After switch open paren result = await ProduceTagsAsync(workspace, buffer, 83); Assert.True(result.IsEmpty()); // At switch close paren result = await ProduceTagsAsync(workspace, buffer, 71); Assert.True(result.IsEmpty()); // After switch close paren result = await ProduceTagsAsync(workspace, buffer, 72); AssertEx.Equal(Enumerable(new Span(62, 1), new Span(71, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // At switch open curly result = await ProduceTagsAsync(workspace, buffer, 82); AssertEx.Equal(Enumerable(new Span(82, 1), new Span(138, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); // After switch open curly result = await ProduceTagsAsync(workspace, buffer, 83); Assert.True(result.IsEmpty()); // At switch close curly result = await ProduceTagsAsync(workspace, buffer, 138); Assert.True(result.IsEmpty()); // After switch close curly result = await ProduceTagsAsync(workspace, buffer, 139); AssertEx.Equal(Enumerable(new Span(82, 1), new Span(138, 1)), result.Select(ts => ts.Span.Span).OrderBy(s => s.Start)); } } }
diryboy/roslyn
src/EditorFeatures/CSharpTest/Interactive/BraceMatching/InteractiveBraceHighlightingTests.cs
C#
mit
8,866
using System; using System.IO; using System.Security.Cryptography; using System.Text; class EncryptingStream { const string EncryptionKey = "ABCDEFGH"; const string FilePath = "../../encrypted.txt"; static void Main() { SaveEncrypted("Hello world", EncryptionKey, FilePath); string result = Decrypt(EncryptionKey, FilePath); Console.WriteLine(result); } static string Decrypt(string key, string path) { var fileStream = new FileStream(path, FileMode.Open); using (fileStream) { var cryptoProvider = new DESCryptoServiceProvider(); cryptoProvider.Key = Encoding.ASCII.GetBytes(key); cryptoProvider.IV = Encoding.ASCII.GetBytes(key); var cryptoStream = new CryptoStream(fileStream, cryptoProvider.CreateDecryptor(), CryptoStreamMode.Read); using (cryptoStream) { using (var reader = new StreamReader(cryptoStream)) { return reader.ReadToEnd(); } } } } static void SaveEncrypted(string text, string key, string path) { var destinationStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); using (destinationStream) { var cryptoProvider = new DESCryptoServiceProvider(); cryptoProvider.Key = Encoding.ASCII.GetBytes(key); cryptoProvider.IV = Encoding.ASCII.GetBytes(key); CryptoStream cryptoStream = new CryptoStream(destinationStream, cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write); using (cryptoStream) { byte[] data = Encoding.ASCII.GetBytes(text); cryptoStream.Write(data, 0, data.Length); } } } }
Rusev12/Software-University-SoftUni
C# Advanced/Streams - Lab/Crypto-Stream/EncryptingStream.cs
C#
mit
1,889
# -*- coding: utf-8 -*- # # openMVG documentation build configuration file, created by # sphinx-quickstart on Wed Oct 30 11:05:58 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # on_rtd is whether we are on readthedocs.org import os on_rtd = os.environ.get('READTHEDOCS', None) == 'True' # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'openMVG' copyright = u'2014, OpenMVG authors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.7' # The full version, including alpha/beta/rc tags. release = '0.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_themes",] if not on_rtd: # only import and set the theme if we're building docs locally html_theme = 'armstrong' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = "openMVG library" # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = True # If false, no index is generated. html_use_index = True # If true, the index is split into individual pages for each letter. html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'openMVGdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'openMVG.tex', u'openMVG Documentation', u'Pierre MOULON \\& Bruno DUISIT', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'openmvg', u'openMVG Documentation', [u'openMVG authors'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'openMVG', u'openMVG Documentation', u'openMVG authors', 'openMVG', 'an open Multiple View Geometry library.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'openMVG' epub_author = u'openMVG authors' epub_publisher = u'Pierre MOULON & Bruno DUISIT & Fabien CASTAN' epub_copyright = u'2013-2014, openMVG authors' # The basename for the epub file. It defaults to the project name. #epub_basename = u'openMVG' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True
Smozeley/openMVG
docs/sphinx/rst/conf.py
Python
mit
10,634
module RKelly module Nodes class BinaryNode < Node attr_reader :left def initialize(left, right) super(right) @left = left end end %w[Subtract LessOrEqual GreaterOrEqual Add Multiply NotEqual DoWhile Switch LogicalAnd UnsignedRightShift Modulus While NotStrictEqual Less With In Greater BitOr StrictEqual LogicalOr BitXOr LeftShift Equal BitAnd InstanceOf Divide RightShift].each do |node| const_set "#{node}Node", Class.new(BinaryNode) end end end
mat-mo/arch-pkgs
ruby-rkelly-remix/pkg/ruby-rkelly-remix/usr/lib/ruby/gems/2.1.0/gems/rkelly-remix-0.0.6/lib/rkelly/nodes/binary_node.rb
Ruby
mit
531
/* * The MIT License * * Copyright 2013 Oleg Nenashev, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.ownership.nodes; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; import java.util.Collections; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; /** * Data-bound wrapper for slave ownership initialization. * @author Oleg Nenashev * @see OwnerNodeProperty */ public class NodeOwnerWrapper { private final OwnershipDescription description; @DataBoundConstructor public NodeOwnerWrapper(@CheckForNull String primaryOwner) { description = StringUtils.isBlank(primaryOwner) ? OwnershipDescription.DISABLED_DESCR : new OwnershipDescription(true, primaryOwner, Collections.<String>emptyList()); } @Nonnull public OwnershipDescription getDescription() { return description; } }
jordancoll/ownership-plugin
src/main/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/NodeOwnerWrapper.java
Java
mit
2,090
package stream.flarebot.flarebot.database; public class RedisMessage { private final String messageID; private final String authorID; private final String channelID; private final String guildID; private final String content; private final long timestamp; public RedisMessage(String messageID, String authorID, String channelID, String guildID, String content, long timestamp) { this.messageID = messageID; this.authorID = authorID; this.channelID = channelID; this.guildID = guildID; this.content = content; this.timestamp = timestamp; } public String getMessageID() { return messageID; } public String getAuthorID() { return authorID; } public String getChannelID() { return channelID; } public String getGuildID() { return guildID; } public String getContent() { return content; } public long getTimestamp() { return timestamp; } }
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/database/RedisMessage.java
Java
mit
1,020
<?php /* * This file is part of the Doctrine\OrientDB package. * * (c) Alessandro Nadalin <alessandro.nadalin@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * This is a central point to manage SQL statements dealing with properties. * * @package Doctrine\OrientDB * @subpackage Query * @author Alessandro Nadalin <alessandro.nadalin@gmail.com> */ namespace Doctrine\OrientDB\Query\Command; use Doctrine\OrientDB\Query\Command; class Property extends Command implements PropertyInterface { /** * Builds a new statement setting the $property to manipulate. * * @param <type> $property */ public function __construct($property) { parent::__construct(); $this->setProperty($property); } /** * Sets the class of the property. * * @param string $class * @return Property */ public function on($class) { $this->setToken('Class', $class); return $this; } /** * Sets the $property in the query. * * @param string $property */ protected function setProperty($property) { $this->setToken('Property', $property); } }
ruleant/orientdb-odm
src/Doctrine/OrientDB/Query/Command/Property.php
PHP
mit
1,291
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" namespace FallbackLayer { ITraversalShaderBuilder *RaytracingProgramFactory::NewTraversalShaderBuilder(AccelerationStructureLayoutType type) { switch (type) { case BVH2: return new BVHTraversalShaderBuilder(m_DxilShaderPatcher); default: ThrowInternalFailure(E_INVALIDARG); return nullptr; } } IRaytracingProgram *RaytracingProgramFactory::NewRaytracingProgram(ProgramTypes programType, const StateObjectCollection &stateObjectCollection) { switch (programType) { case RaytracingProgramFactory::UberShader: return new UberShaderRaytracingProgram(m_pDevice, m_DxilShaderPatcher, stateObjectCollection); default: ThrowInternalFailure(E_INVALIDARG); return nullptr; } } IRaytracingProgram *RaytracingProgramFactory::GetRaytracingProgram( const StateObjectCollection &stateObjectCollection) { ProgramTypes programType = DetermineBestProgram(stateObjectCollection); TraversalShader traversalShader; m_spTraversalShaderBuilder->Compile(stateObjectCollection.IsUsingAnyHit || stateObjectCollection.IsUsingIntersection, traversalShader); memcpy((void *)&stateObjectCollection.m_traversalShader, &traversalShader.m_TraversalShaderDxilLib, sizeof(stateObjectCollection.m_traversalShader)); return NewRaytracingProgram(programType, stateObjectCollection); } RaytracingProgramFactory::RaytracingProgramFactory(ID3D12Device *pDevice) : m_pDevice(pDevice) { m_spTraversalShaderBuilder.reset(NewTraversalShaderBuilder(m_DefaultAccelerationStructureLayoutType)); } RaytracingProgramFactory::ProgramTypes RaytracingProgramFactory::DetermineBestProgram( const StateObjectCollection &stateObjectCollection) { UNREFERENCED_PARAMETER(stateObjectCollection); return UberShader; } }
baesky/DirectX-Graphics-Samples
Libraries/D3D12RaytracingFallback/src/RayTracingProgramFactory.cpp
C++
mit
2,439
var gulp = require('gulp'); var inquirer = require('inquirer'); var fs = require('fs'); var getDirectories = require('../util/getDirectories'); var config = require('../config'); gulp.task('set-user-choices', function(done) { var prompts = [{ type: 'confirm', name: 'packageToJPT', message: 'Do you want to package to JPT?', default: false }]; var graphicChoices = getDirectories('graphics'); if (graphicChoices.length > 1) { prompts.unshift({ type: 'list', name: 'graphicName', message: 'Choose a graphic', choices: graphicChoices }); } inquirer.prompt(prompts, function(answers) { var chosenGraphic = answers.graphicName || graphicChoices[0]; var graphicType = JSON.parse(fs.readFileSync('graphics/' + chosenGraphic + '/graphicType.json', {encoding: 'utf8'})).graphicType; if (!answers.packageToJPT && graphicType === 'igraphic') { config.setUserChoice('graphic', chosenGraphic); config.setUserChoice('graphicTemplate', '-' + 'regular'); done(); } else { config.setUserChoice('graphic', chosenGraphic); config.setUserChoice('packageToJpt', answers.packageToJPT); config.setUserChoice('graphicTemplate', ''); done(); } }); });
BostonGlobe/schoolbuses
gulp/tasks/setUserChoices.js
JavaScript
mit
1,237
import time import pytest from redis.client import Redis from redis.exceptions import LockError, LockNotOwnedError from redis.lock import Lock from .conftest import _get_client @pytest.mark.onlynoncluster class TestLock: @pytest.fixture() def r_decoded(self, request): return _get_client(Redis, request=request, decode_responses=True) def get_lock(self, redis, *args, **kwargs): kwargs["lock_class"] = Lock return redis.lock(*args, **kwargs) def test_lock(self, r): lock = self.get_lock(r, "foo") assert lock.acquire(blocking=False) assert r.get("foo") == lock.local.token assert r.ttl("foo") == -1 lock.release() assert r.get("foo") is None def test_lock_token(self, r): lock = self.get_lock(r, "foo") self._test_lock_token(r, lock) def test_lock_token_thread_local_false(self, r): lock = self.get_lock(r, "foo", thread_local=False) self._test_lock_token(r, lock) def _test_lock_token(self, r, lock): assert lock.acquire(blocking=False, token="test") assert r.get("foo") == b"test" assert lock.local.token == b"test" assert r.ttl("foo") == -1 lock.release() assert r.get("foo") is None assert lock.local.token is None def test_locked(self, r): lock = self.get_lock(r, "foo") assert lock.locked() is False lock.acquire(blocking=False) assert lock.locked() is True lock.release() assert lock.locked() is False def _test_owned(self, client): lock = self.get_lock(client, "foo") assert lock.owned() is False lock.acquire(blocking=False) assert lock.owned() is True lock.release() assert lock.owned() is False lock2 = self.get_lock(client, "foo") assert lock.owned() is False assert lock2.owned() is False lock2.acquire(blocking=False) assert lock.owned() is False assert lock2.owned() is True lock2.release() assert lock.owned() is False assert lock2.owned() is False def test_owned(self, r): self._test_owned(r) def test_owned_with_decoded_responses(self, r_decoded): self._test_owned(r_decoded) def test_competing_locks(self, r): lock1 = self.get_lock(r, "foo") lock2 = self.get_lock(r, "foo") assert lock1.acquire(blocking=False) assert not lock2.acquire(blocking=False) lock1.release() assert lock2.acquire(blocking=False) assert not lock1.acquire(blocking=False) lock2.release() def test_timeout(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) assert 8 < r.ttl("foo") <= 10 lock.release() def test_float_timeout(self, r): lock = self.get_lock(r, "foo", timeout=9.5) assert lock.acquire(blocking=False) assert 8 < r.pttl("foo") <= 9500 lock.release() def test_blocking_timeout(self, r): lock1 = self.get_lock(r, "foo") assert lock1.acquire(blocking=False) bt = 0.2 sleep = 0.05 lock2 = self.get_lock(r, "foo", sleep=sleep, blocking_timeout=bt) start = time.monotonic() assert not lock2.acquire() # The elapsed duration should be less than the total blocking_timeout assert bt > (time.monotonic() - start) > bt - sleep lock1.release() def test_context_manager(self, r): # blocking_timeout prevents a deadlock if the lock can't be acquired # for some reason with self.get_lock(r, "foo", blocking_timeout=0.2) as lock: assert r.get("foo") == lock.local.token assert r.get("foo") is None def test_context_manager_raises_when_locked_not_acquired(self, r): r.set("foo", "bar") with pytest.raises(LockError): with self.get_lock(r, "foo", blocking_timeout=0.1): pass def test_high_sleep_small_blocking_timeout(self, r): lock1 = self.get_lock(r, "foo") assert lock1.acquire(blocking=False) sleep = 60 bt = 1 lock2 = self.get_lock(r, "foo", sleep=sleep, blocking_timeout=bt) start = time.monotonic() assert not lock2.acquire() # the elapsed timed is less than the blocking_timeout as the lock is # unattainable given the sleep/blocking_timeout configuration assert bt > (time.monotonic() - start) lock1.release() def test_releasing_unlocked_lock_raises_error(self, r): lock = self.get_lock(r, "foo") with pytest.raises(LockError): lock.release() def test_releasing_lock_no_longer_owned_raises_error(self, r): lock = self.get_lock(r, "foo") lock.acquire(blocking=False) # manually change the token r.set("foo", "a") with pytest.raises(LockNotOwnedError): lock.release() # even though we errored, the token is still cleared assert lock.local.token is None def test_extend_lock(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) assert 8000 < r.pttl("foo") <= 10000 assert lock.extend(10) assert 16000 < r.pttl("foo") <= 20000 lock.release() def test_extend_lock_replace_ttl(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) assert 8000 < r.pttl("foo") <= 10000 assert lock.extend(10, replace_ttl=True) assert 8000 < r.pttl("foo") <= 10000 lock.release() def test_extend_lock_float(self, r): lock = self.get_lock(r, "foo", timeout=10.0) assert lock.acquire(blocking=False) assert 8000 < r.pttl("foo") <= 10000 assert lock.extend(10.0) assert 16000 < r.pttl("foo") <= 20000 lock.release() def test_extending_unlocked_lock_raises_error(self, r): lock = self.get_lock(r, "foo", timeout=10) with pytest.raises(LockError): lock.extend(10) def test_extending_lock_with_no_timeout_raises_error(self, r): lock = self.get_lock(r, "foo") assert lock.acquire(blocking=False) with pytest.raises(LockError): lock.extend(10) lock.release() def test_extending_lock_no_longer_owned_raises_error(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) r.set("foo", "a") with pytest.raises(LockNotOwnedError): lock.extend(10) def test_reacquire_lock(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) assert r.pexpire("foo", 5000) assert r.pttl("foo") <= 5000 assert lock.reacquire() assert 8000 < r.pttl("foo") <= 10000 lock.release() def test_reacquiring_unlocked_lock_raises_error(self, r): lock = self.get_lock(r, "foo", timeout=10) with pytest.raises(LockError): lock.reacquire() def test_reacquiring_lock_with_no_timeout_raises_error(self, r): lock = self.get_lock(r, "foo") assert lock.acquire(blocking=False) with pytest.raises(LockError): lock.reacquire() lock.release() def test_reacquiring_lock_no_longer_owned_raises_error(self, r): lock = self.get_lock(r, "foo", timeout=10) assert lock.acquire(blocking=False) r.set("foo", "a") with pytest.raises(LockNotOwnedError): lock.reacquire() @pytest.mark.onlynoncluster class TestLockClassSelection: def test_lock_class_argument(self, r): class MyLock: def __init__(self, *args, **kwargs): pass lock = r.lock("foo", lock_class=MyLock) assert type(lock) == MyLock
mozillazg/redis-py-doc
tests/test_lock.py
Python
mit
7,948
define([ 'extensions/views/view' ], function (View) { var TabView = View.extend({ initialize: function () { View.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:activeIndex', this.setActiveTab, this); }, events: { 'click nav a': 'onTabClick' }, onTabClick: function (event) { var activeIndex = this.$el.find('a').index(event.currentTarget); this.model.set('activeIndex', activeIndex); event.preventDefault(); }, setActiveTab: function () { var activeIndex = this.model.get('activeIndex'), listItems = this.$el.find('li'), sections = this.$el.find('section'); listItems.removeClass('active'); sections.removeClass('active'); listItems.eq(activeIndex).addClass('active'); sections.eq(activeIndex).addClass('active'); }, render: function () { this.setActiveTab(); } }); return TabView; });
alphagov/spotlight
app/client/views/visualisations/tab.js
JavaScript
mit
968
from django.apps import AppConfig class DownloadConfig(AppConfig): name = 'download'
abhijithanilkumar/ns-3-AppStore
src/download/apps.py
Python
mit
91
# This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # DEAP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with DEAP. If not, see <http://www.gnu.org/licenses/>. # example which maximizes the sum of a list of integers # each of which can be 0 or 1 import random from deap import base from deap import creator from deap import tools creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox = base.Toolbox() # Attribute generator: define 'attr_bool' to be an attribute ('gene') # which corresponds to integers sampled uniformly # from the range [0,1] (i.e. 0 or 1 with equal # probability) toolbox.register("attr_bool", random.randint, 0, 1) # Structure initializers: define 'individual' to be an individual # consisting of 100 'attr_bool' elements ('genes') toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100) # define the population to be a list of 'individual's toolbox.register("population", tools.initRepeat, list, toolbox.individual) # the goal ('fitness') function to be maximized def evalOneMax(individual): return sum(individual), #---------- # Operator registration #---------- # register the goal / fitness function toolbox.register("evaluate", evalOneMax) # register the crossover operator toolbox.register("mate", tools.cxTwoPoint) # register a mutation operator with a probability to # flip each attribute/gene of 0.05 toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) # operator for selecting individuals for breeding the next # generation: each individual of the current generation # is replaced by the 'fittest' (best) of three individuals # drawn randomly from the current generation. toolbox.register("select", tools.selTournament, tournsize=3) #---------- def main(): random.seed(64) # create an initial population of 300 individuals (where # each individual is a list of integers) pop = toolbox.population(n=300) # CXPB is the probability with which two individuals # are crossed # # MUTPB is the probability for mutating an individual # # NGEN is the number of generations for which the # evolution runs CXPB, MUTPB, NGEN = 0.5, 0.2, 40 print("Start of evolution") # Evaluate the entire population fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(pop)) # Begin the evolution for g in range(NGEN): print("-- Generation %i --" % g) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals offspring = list(map(toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): # cross two individuals with probability CXPB if random.random() < CXPB: toolbox.mate(child1, child2) # fitness values of the children # must be recalculated later del child1.fitness.values del child2.fitness.values for mutant in offspring: # mutate an individual with probability MUTPB if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(invalid_ind)) # The population is entirely replaced by the offspring pop[:] = offspring # Gather all the fitnesses in one list and print the stats fits = [ind.fitness.values[0] for ind in pop] length = len(pop) mean = sum(fits) / length sum2 = sum(x*x for x in fits) std = abs(sum2 / length - mean**2)**0.5 print(" Min %s" % min(fits)) print(" Max %s" % max(fits)) print(" Avg %s" % mean) print(" Std %s" % std) print("-- End of (successful) evolution --") best_ind = tools.selBest(pop, 1)[0] print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values)) if __name__ == "__main__": main()
GrimRanger/GeneticAlgorithm
helps/deap/deap-master/examples/ga/onemax.py
Python
mit
5,221
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'sentimentalizer' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| end
gveltri/sentimentalizer
spec/spec_helper.rb
Ruby
mit
365
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HOST_HPP_20100618 #define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HOST_HPP_20100618 // Copyright 2010 (c) Dean Michael Berris. // Copyright 2010 (c) Sinefunc, Inc. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) namespace boost { namespace network { namespace http { template <class Tag> struct basic_request; namespace impl { template <class Tag> struct host_wrapper { basic_request<Tag> const& message_; explicit host_wrapper(basic_request<Tag> const& message) : message_(message) {} typedef typename basic_request<Tag>::string_type string_type; operator string_type() { return message_.host(); } }; } // namespace impl template <class Tag> inline impl::host_wrapper<Tag> host(basic_request<Tag> const& request) { return impl::host_wrapper<Tag>(request); } } // namespace http } // namespace network } // namespace boost #endif // BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HOST_HPP_20100618
demonsaw/Code
ds4/code/0_cppnetlib/boost/network/protocol/http/message/wrappers/host.hpp
C++
mit
1,062
require 'hiera_puppet' module Puppet::Parser::Functions newfunction(:hiera_array, :type => :rvalue, :arity => -2,:doc => "Returns all matches throughout the hierarchy --- not just the first match --- as a flattened array of unique values. If any of the matched values are arrays, they're flattened and included in the results. The function can be called in one of three ways: 1. Using 1 to 3 arguments where the arguments are: 'key' [String] Required The key to lookup. 'default` [Any] Optional A value to return when there's no match for `key`. Optional `override` [Any] Optional An argument in the third position, providing a data source to consult for matching values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesn't find a matching key in the named override data source, it will continue to search through the rest of the hierarchy. 2. Using a 'key' and an optional 'override' parameter like in #1 but with a block to provide the default value. The block is called with one parameter (the key) and should return the value. This option can only be used with the 3x future parser or from 4.0.0. 3. Like #1 but with all arguments passed in an array. If any matched value is a hash, puppet will raise a type mismatch error. More thorough examples of `hiera` are available at: <http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions> ") do |*args| key, default, override = HieraPuppet.parse_args(args) HieraPuppet.lookup(key, default, self, override, :array) end end
thejonanshow/my-boxen
vendor/bundle/ruby/2.3.0/gems/puppet-3.8.7/lib/puppet/parser/functions/hiera_array.rb
Ruby
mit
1,668
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.RecoveryServices.Backup; using Newtonsoft.Json; using System.Linq; /// <summary> /// Additional information on Azure IaaS VM specific backup item. /// </summary> public partial class AzureIaaSVMProtectedItemExtendedInfo { /// <summary> /// Initializes a new instance of the /// AzureIaaSVMProtectedItemExtendedInfo class. /// </summary> public AzureIaaSVMProtectedItemExtendedInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// AzureIaaSVMProtectedItemExtendedInfo class. /// </summary> /// <param name="oldestRecoveryPoint">The oldest backup copy available /// for this backup item.</param> /// <param name="recoveryPointCount">Number of backup copies available /// for this backup item.</param> /// <param name="policyInconsistent">Specifies if backup policy /// associated with the backup item is inconsistent.</param> public AzureIaaSVMProtectedItemExtendedInfo(System.DateTime? oldestRecoveryPoint = default(System.DateTime?), int? recoveryPointCount = default(int?), bool? policyInconsistent = default(bool?)) { OldestRecoveryPoint = oldestRecoveryPoint; RecoveryPointCount = recoveryPointCount; PolicyInconsistent = policyInconsistent; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the oldest backup copy available for this backup item. /// </summary> [JsonProperty(PropertyName = "oldestRecoveryPoint")] public System.DateTime? OldestRecoveryPoint { get; set; } /// <summary> /// Gets or sets number of backup copies available for this backup /// item. /// </summary> [JsonProperty(PropertyName = "recoveryPointCount")] public int? RecoveryPointCount { get; set; } /// <summary> /// Gets or sets specifies if backup policy associated with the backup /// item is inconsistent. /// </summary> [JsonProperty(PropertyName = "policyInconsistent")] public bool? PolicyInconsistent { get; set; } } }
ScottHolden/azure-sdk-for-net
src/SDKs/RecoveryServices.Backup/Management.RecoveryServices.Backup/Generated/Models/AzureIaaSVMProtectedItemExtendedInfo.cs
C#
mit
2,941
<?php declare(strict_types=1); namespace DI\Definition\Dumper; use DI\Definition\Definition; use DI\Definition\ObjectDefinition; use DI\Definition\ObjectDefinition\MethodInjection; use ReflectionException; /** * Dumps object definitions to string for debugging purposes. * * @since 4.1 * @author Matthieu Napoli <matthieu@mnapoli.fr> */ class ObjectDefinitionDumper { /** * Returns the definition as string representation. */ public function dump(ObjectDefinition $definition) : string { $className = $definition->getClassName(); $classExist = class_exists($className) || interface_exists($className); // Class if (! $classExist) { $warning = '#UNKNOWN# '; } else { $class = new \ReflectionClass($className); $warning = $class->isInstantiable() ? '' : '#NOT INSTANTIABLE# '; } $str = sprintf(' class = %s%s', $warning, $className); // Lazy $str .= \PHP_EOL . ' lazy = ' . var_export($definition->isLazy(), true); if ($classExist) { // Constructor $str .= $this->dumpConstructor($className, $definition); // Properties $str .= $this->dumpProperties($definition); // Methods $str .= $this->dumpMethods($className, $definition); } return sprintf('Object (' . \PHP_EOL . '%s' . \PHP_EOL . ')', $str); } private function dumpConstructor(string $className, ObjectDefinition $definition) : string { $str = ''; $constructorInjection = $definition->getConstructorInjection(); if ($constructorInjection !== null) { $parameters = $this->dumpMethodParameters($className, $constructorInjection); $str .= sprintf(\PHP_EOL . ' __construct(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $parameters); } return $str; } private function dumpProperties(ObjectDefinition $definition) : string { $str = ''; foreach ($definition->getPropertyInjections() as $propertyInjection) { $value = $propertyInjection->getValue(); $valueStr = $value instanceof Definition ? (string) $value : var_export($value, true); $str .= sprintf(\PHP_EOL . ' $%s = %s', $propertyInjection->getPropertyName(), $valueStr); } return $str; } private function dumpMethods(string $className, ObjectDefinition $definition) : string { $str = ''; foreach ($definition->getMethodInjections() as $methodInjection) { $parameters = $this->dumpMethodParameters($className, $methodInjection); $str .= sprintf(\PHP_EOL . ' %s(' . \PHP_EOL . ' %s' . \PHP_EOL . ' )', $methodInjection->getMethodName(), $parameters); } return $str; } private function dumpMethodParameters(string $className, MethodInjection $methodInjection) : string { $methodReflection = new \ReflectionMethod($className, $methodInjection->getMethodName()); $args = []; $definitionParameters = $methodInjection->getParameters(); foreach ($methodReflection->getParameters() as $index => $parameter) { if (array_key_exists($index, $definitionParameters)) { $value = $definitionParameters[$index]; $valueStr = $value instanceof Definition ? (string) $value : var_export($value, true); $args[] = sprintf('$%s = %s', $parameter->getName(), $valueStr); continue; } // If the parameter is optional and wasn't specified, we take its default value if ($parameter->isOptional()) { try { $value = $parameter->getDefaultValue(); $args[] = sprintf( '$%s = (default value) %s', $parameter->getName(), var_export($value, true) ); continue; } catch (ReflectionException $e) { // The default value can't be read through Reflection because it is a PHP internal class } } $args[] = sprintf('$%s = #UNDEFINED#', $parameter->getName()); } return implode(\PHP_EOL . ' ', $args); } }
PHP-DI/PHP-DI
src/Definition/Dumper/ObjectDefinitionDumper.php
PHP
mit
4,409
// Type definitions for node-ipc 9.1 // Project: http://riaevangelist.github.io/node-ipc/ // Definitions by: Arvitaly <https://github.com/arvitaly>, gjurgens <https://github.com/gjurgens> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> import { Socket } from "net"; declare namespace NodeIPC { class IPC { /** * Set these variables in the ipc.config scope to overwrite or set default values */ config: Config; /** * https://www.npmjs.com/package/node-ipc#log */ log(...args: any[]): void; /** * https://www.npmjs.com/package/node-ipc#connectto * Used for connecting as a client to local Unix Sockets and Windows Sockets. * This is the fastest way for processes on the same machine to communicate * because it bypasses the network card which TCP and UDP must both use. * @param id is the string id of the socket being connected to. * The socket with this id is added to the ipc.of object when created. * @param path is the path of the Unix Domain Socket File, if the System is Windows, * this will automatically be converted to an appropriate pipe with the same information as the Unix Domain Socket File. * If not set this will default to ipc.config.socketRoot+ipc.config.appspace+id * @param callback this is the function to execute when the socket has been created */ connectTo(id: string, path?: string, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#connectto * Used for connecting as a client to local Unix Sockets and Windows Sockets. * This is the fastest way for processes on the same machine to communicate * because it bypasses the network card which TCP and UDP must both use. * @param id is the string id of the socket being connected to. * The socket with this id is added to the ipc.of object when created. * @param callback this is the function to execute when the socket has been created */ connectTo(id: string, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#connecttonet * Used to connect as a client to a TCP or TLS socket via the network card. * This can be local or remote, if local, it is recommended that you use the Unix * and Windows Socket Implementaion of connectTo instead as it is much faster since it avoids the network card altogether. * For TLS and SSL Sockets see the node-ipc TLS and SSL docs. * They have a few additional requirements, and things to know about and so have their own doc. * @param id is the string id of the socket being connected to. For TCP & TLS sockets, * this id is added to the ipc.of object when the socket is created with a reference to the socket * @param host is the host on which the TCP or TLS socket resides. * This will default to ipc.config.networkHost if not specified * @param port the port on which the TCP or TLS socket resides * @param callback this is the function to execute when the socket has been created */ connectToNet(id: string, host?: string, port?: number, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#connecttonet * Used to connect as a client to a TCP or TLS socket via the network card. * This can be local or remote, if local, it is recommended that you use the Unix * and Windows Socket Implementaion of connectTo instead as it is much faster since it avoids the network card altogether. * For TLS and SSL Sockets see the node-ipc TLS and SSL docs. * They have a few additional requirements, and things to know about and so have their own doc. * @param id is the string id of the socket being connected to. For TCP & TLS sockets, * this id is added to the ipc.of object when the socket is created with a reference to the socket * @param callback this is the function to execute when the socket has been created */ connectToNet(id: string, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#connecttonet * Used to connect as a client to a TCP or TLS socket via the network card. * This can be local or remote, if local, it is recommended that you use the Unix * and Windows Socket Implementaion of connectTo instead as it is much faster since it avoids the network card altogether. * For TLS and SSL Sockets see the node-ipc TLS and SSL docs. * They have a few additional requirements, and things to know about and so have their own doc. * @param id is the string id of the socket being connected to. * For TCP & TLS sockets, this id is added to the ipc.of object when the socket is created with a reference to the socket * @param host is the host on which the TCP or TLS socket resides. This will default to ipc.config.networkHost if not specified * @param port the port on which the TCP or TLS socket resides * @param callback this is the function to execute when the socket has been created */ connectToNet(id: string, hostOrPort: number | string, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#disconnect * Used to disconnect a client from a Unix, Windows, TCP or TLS socket. * The socket and its refrence will be removed from memory and the ipc.of scope. * This can be local or remote. UDP clients do not maintain connections and so there are no Clients and this method has no value to them * @param id is the string id of the socket from which to disconnect */ disconnect(id: string): void; /** * https://www.npmjs.com/package/node-ipc#serve * Used to create local Unix Socket Server or Windows Socket Server to which Clients can bind. * The server can emit events to specific Client Sockets, or broadcast events to all known Client Sockets * @param path This is the path of the Unix Domain Socket File, if the System is Windows, * this will automatically be converted to an appropriate pipe with the same information as the Unix Domain Socket File. * If not set this will default to ipc.config.socketRoot+ipc.config.appspace+id * @param callback This is a function to be called after the Server has started. * This can also be done by binding an event to the start event like ipc.server.on('start',function(){}); */ serve(path: string, callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#serve * Used to create local Unix Socket Server or Windows Socket Server to which Clients can bind. * The server can emit events to specific Client Sockets, or broadcast events to all known Client Sockets * @param callback This is a function to be called after the Server has started. * This can also be done by binding an event to the start event like ipc.server.on('start',function(){}); */ serve(callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#serve * Used to create local Unix Socket Server or Windows Socket Server to which Clients can bind. * The server can emit events to specific Client Sockets, or broadcast events to all known Client Sockets */ serve(callback: null): void; /** * https://www.npmjs.com/package/node-ipc#servenet * @param host If not specified this defaults to the first address in os.networkInterfaces(). * For TCP, TLS & UDP servers this is most likely going to be 127.0.0.1 or ::1 * @param port The port on which the TCP, UDP, or TLS Socket server will be bound, this defaults to 8000 if not specified * @param UDPType If set this will create the server as a UDP socket. 'udp4' or 'udp6' are valid values. * This defaults to not being set. When using udp6 make sure to specify a valid IPv6 host, like ::1 * @param callback Function to be called when the server is created */ serveNet(host?: string, port?: number, UDPType?: "udp4" | "udp6", callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#servenet * @param UDPType If set this will create the server as a UDP socket. 'udp4' or 'udp6' are valid values. * This defaults to not being set. When using udp6 make sure to specify a valid IPv6 host, like ::1 * @param callback Function to be called when the server is created */ serveNet(UDPType: "udp4" | "udp6", callback?: () => void): void; /** * https://www.npmjs.com/package/node-ipc#servenet * @param callback Function to be called when the server is created * @param port The port on which the TCP, UDP, or TLS Socket server will be bound, this defaults to 8000 if not specified */ serveNet(callbackOrPort: EmptyCallback | number): void; /** * https://www.npmjs.com/package/node-ipc#servenet * @param host If not specified this defaults to the first address in os.networkInterfaces(). * For TCP, TLS & UDP servers this is most likely going to be 127.0.0.1 or ::1 * @param port The port on which the TCP, UDP, or TLS Socket server will be bound, this defaults to 8000 if not specified * @param callback Function to be called when the server is created */ serveNet(host: string, port: number, callback?: () => void): void; /** * This is where socket connection refrences will be stored when connecting to them as a client via the ipc.connectTo * or iupc.connectToNet. They will be stored based on the ID used to create them, eg : ipc.of.mySocket */ of: any; /** * This is a refrence to the server created by ipc.serve or ipc.serveNet */ server: Server; } type EmptyCallback = () => void; interface Client { /** * triggered when a JSON message is received. The event name will be the type string from your message * and the param will be the data object from your message eg : { type:'myEvent',data:{a:1}} */ on(event: string, callback: (...args: any[]) => void): Client; /** * triggered when an error has occured */ on(event: "error", callback: (err: any) => void): Client; /** * connect - triggered when socket connected * disconnect - triggered by client when socket has disconnected from server * destroy - triggered when socket has been totally destroyed, no further auto retries will happen and all references are gone */ on(event: "connect" | "disconnect" | "destroy", callback: () => void): Client; /** * triggered by server when a client socket has disconnected */ on(event: "socket.disconnected", callback: (socket: Socket, destroyedSocketID: string) => void): Client; /** * triggered when ipc.config.rawBuffer is true and a message is received */ on(event: "data", callback: (buffer: Buffer) => void): Client; emit(event: string, value?: any): Client; /** * Unbind subscribed events */ off(event: string, handler: any): Client; } interface Server extends Client { /** * start serving need top call serve or serveNet first to set up the server */ start(): void; /** * close the server and stop serving */ stop(): void; emit(value: any): Client; emit(event: string, value: any): Client; emit(socket: Socket | SocketConfig, event: string, value?: any): Server; emit(socketConfig: Socket | SocketConfig, value?: any): Server; broadcast(event: string, value?: any): Client; } interface SocketConfig { address?: string; port?: number; } interface Config { /** * Default: 'app.' * Used for Unix Socket (Unix Domain Socket) namespacing. * If not set specifically, the Unix Domain Socket will combine the socketRoot, appspace, * and id to form the Unix Socket Path for creation or binding. * This is available incase you have many apps running on your system, you may have several sockets with the same id, * but if you change the appspace, you will still have app specic unique sockets */ appspace: string; /** * Default: '/tmp/' * The directory in which to create or bind to a Unix Socket */ socketRoot: string; /** * Default: os.hostname() * The id of this socket or service */ id: string; /** * Default: 'localhost' * The local or remote host on which TCP, TLS or UDP Sockets should connect * Should resolve to 127.0.0.1 or ::1 see the table below related to this */ networkHost: string; /** * Default: 8000 * The default port on which TCP, TLS, or UDP sockets should connect */ networkPort: number; /** * Default: 'utf8' * the default encoding for data sent on sockets. Mostly used if rawBuffer is set to true. * Valid values are : ascii utf8 utf16le ucs2 base64 hex */ encoding: "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "hex"; /** * Default: false * If true, data will be sent and received as a raw node Buffer NOT an Object as JSON. * This is great for Binary or hex IPC, and communicating with other processes in languages like C and C++ */ rawBuffer: boolean; /** * Default: false * Synchronous requests. Clients will not send new requests until the server answers */ sync: boolean; /** * Default: false * Turn on/off logging default is false which means logging is on */ silent: boolean; /** * Default: true * Turn on/off util.inspect colors for ipc.log */ logInColor: boolean; /** * Default: 5 * Set the depth for util.inspect during ipc.log */ logDepth: number; /** * Default: console.log * The function which receives the output from ipc.log; should take a single string argument */ logger(msg: string): void; /** * Default: 100 * This is the max number of connections allowed to a socket. It is currently only being set on Unix Sockets. * Other Socket types are using the system defaults */ maxConnections: number; /** * Default: 500 * This is the time in milliseconds a client will wait before trying to reconnect to a server if the connection is lost. * This does not effect UDP sockets since they do not have a client server relationship like Unix Sockets and TCP Sockets */ retry: number; /* */ /** * Default: false * if set, it represents the maximum number of retries after each disconnect before giving up * and completely killing a specific connection */ maxRetries: boolean | number; /** * Default: false * Defaults to false meaning clients will continue to retry to connect to servers indefinitely at the retry interval. * If set to any number the client will stop retrying when that number is exceeded after each disconnect. * If set to true in real time it will immediately stop trying to connect regardless of maxRetries. * If set to 0, the client will NOT try to reconnect */ stopRetrying: boolean; /** * Default: true * Defaults to true meaning that the module will take care of deleting the IPC socket prior to startup. * If you use node-ipc in a clustered environment where there will be multiple listeners on the same socket, * you must set this to false and then take care of deleting the socket in your own code. */ unlink: boolean; /** * Primarily used when specifying which interface a client should connect through. * see the socket.connect documentation in the node.js api https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener */ interfaces: { /** * Default: false */ localAddress?: boolean; /** * Default: false */ localPort?: boolean; /** * Default: false */ family?: boolean; /** * Default: false */ hints?: boolean; /** * Default: false */ lookup?: boolean; }; tls: { rejectUnauthorized?: boolean; public?: string; private?: string; }; } } declare const RootIPC: NodeIPC.IPC & { IPC: new () => NodeIPC.IPC }; export = RootIPC;
georgemarshall/DefinitelyTyped
types/node-ipc/index.d.ts
TypeScript
mit
17,692
StartTest(function(t) { t.getHarness([ 'testfiles/601_siesta_ui_failing.t.js' ]); t.diag('Verify no layouts occur due to assertion added to its store'); var before = 0; var getLayoutCount = function () { var count = 0 Ext.each(Ext.ComponentQuery.query('container'), function(c) { count += c.layoutCounter; }); count } t.chain( { waitFor : 'rowsVisible', args : 'testgrid' }, function (next) { t.waitForHarnessEvent('testsuiteend', next) t.doubleClick('testgrid => .x-grid-row', function () {}) }, function (next) { before = getLayoutCount() var testgrid = Ext.ComponentQuery.query('testgrid')[0]; // Adding an assertion should not cause a relayout, same goes for view refresh testgrid.store.tree.getNodeById('testfiles/601_siesta_ui_failing.t.js').get('test').pass("some assertion") // Updating a test record should not cause a relayout, same goes for view refresh testgrid.getRootNode().firstChild.set('title', 'foo'); t.is(getLayoutCount(), before, 'No layouts caused by test') } ); });
arthurakay/AppInspector
app/test/siesta-2.0.5-lite/tests/siesta_ui/605_siesta_ui_nbr_layouts.t.js
JavaScript
mit
1,298
import gym import gym.wrappers import gym.envs import gym.spaces import traceback import logging try: from gym.wrappers.monitoring import logger as monitor_logger monitor_logger.setLevel(logging.WARNING) except Exception as e: traceback.print_exc() import os import os.path as osp from rllab.envs.base import Env, Step from rllab.core.serializable import Serializable from rllab.spaces.box import Box from rllab.spaces.discrete import Discrete from rllab.spaces.product import Product from rllab.misc import logger def convert_gym_space(space): if isinstance(space, gym.spaces.Box): return Box(low=space.low, high=space.high) elif isinstance(space, gym.spaces.Discrete): return Discrete(n=space.n) elif isinstance(space, gym.spaces.Tuple): return Product([convert_gym_space(x) for x in space.spaces]) else: raise NotImplementedError class CappedCubicVideoSchedule(object): # Copied from gym, since this method is frequently moved around def __call__(self, count): if count < 1000: return int(round(count ** (1. / 3))) ** 3 == count else: return count % 1000 == 0 class FixedIntervalVideoSchedule(object): def __init__(self, interval): self.interval = interval def __call__(self, count): return count % self.interval == 0 class NoVideoSchedule(object): def __call__(self, count): return False class GymEnv(Env, Serializable): def __init__(self, env_name, record_video=True, video_schedule=None, log_dir=None, record_log=True, force_reset=False): if log_dir is None: if logger.get_snapshot_dir() is None: logger.log("Warning: skipping Gym environment monitoring since snapshot_dir not configured.") else: log_dir = os.path.join(logger.get_snapshot_dir(), "gym_log") Serializable.quick_init(self, locals()) env = gym.envs.make(env_name) self.env = env self.env_id = env.spec.id assert not (not record_log and record_video) if log_dir is None or record_log is False: self.monitoring = False else: if not record_video: video_schedule = NoVideoSchedule() else: if video_schedule is None: video_schedule = CappedCubicVideoSchedule() self.env = gym.wrappers.Monitor(self.env, log_dir, video_callable=video_schedule, force=True) self.monitoring = True self._observation_space = convert_gym_space(env.observation_space) logger.log("observation space: {}".format(self._observation_space)) self._action_space = convert_gym_space(env.action_space) logger.log("action space: {}".format(self._action_space)) self._horizon = env.spec.tags['wrapper_config.TimeLimit.max_episode_steps'] self._log_dir = log_dir self._force_reset = force_reset @property def observation_space(self): return self._observation_space @property def action_space(self): return self._action_space @property def horizon(self): return self._horizon def reset(self): if self._force_reset and self.monitoring: from gym.wrappers.monitoring import Monitor assert isinstance(self.env, Monitor) recorder = self.env.stats_recorder if recorder is not None: recorder.done = True return self.env.reset() def step(self, action): next_obs, reward, done, info = self.env.step(action) return Step(next_obs, reward, done, **info) def render(self): self.env.render() def terminate(self): if self.monitoring: self.env._close() if self._log_dir is not None: print(""" *************************** Training finished! You can upload results to OpenAI Gym by running the following command: python scripts/submit_gym.py %s *************************** """ % self._log_dir)
brain-research/mirage-rl-qprop
rllab/envs/gym_env.py
Python
mit
4,134
class AuthenticationProvider < ActiveRecord::Base belongs_to :user validates :user_id, :uid, :provider, :token, presence: true validates :uid, uniqueness: true end
askl56/github-awards
app/models/authentication_provider.rb
Ruby
mit
173
<?php /* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace WellCommerce\Component\DataSet\Conditions\Condition; use WellCommerce\Component\DataSet\Conditions\AbstractCondition; /** * Class In * * @author Adam Piotrowski <adam@wellcommerce.org> */ final class In extends AbstractCondition { protected $operator = 'in'; public function getValue() { return !is_array($this->value) ? (array)$this->value : $this->value; } }
diversantvlz/WellCommerce
src/WellCommerce/Component/DataSet/Conditions/Condition/In.php
PHP
mit
698
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraint; /** * @Annotation * @Target({"PROPERTY", "METHOD", "ANNOTATION"}) * * @author Bernhard Schussek <bschussek@gmail.com> */ #[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class Choice extends Constraint { public const NO_SUCH_CHOICE_ERROR = '8e179f1b-97aa-4560-a02f-2a8b42e49df7'; public const TOO_FEW_ERROR = '11edd7eb-5872-4b6e-9f12-89923999fd0e'; public const TOO_MANY_ERROR = '9bd98e49-211c-433f-8630-fd1c2d0f08c3'; protected static $errorNames = [ self::NO_SUCH_CHOICE_ERROR => 'NO_SUCH_CHOICE_ERROR', self::TOO_FEW_ERROR => 'TOO_FEW_ERROR', self::TOO_MANY_ERROR => 'TOO_MANY_ERROR', ]; public $choices; public $callback; public $multiple = false; public $strict = true; public $min; public $max; public $message = 'The value you selected is not a valid choice.'; public $multipleMessage = 'One or more of the given values is invalid.'; public $minMessage = 'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.'; public $maxMessage = 'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.'; /** * {@inheritdoc} */ public function getDefaultOption() { return 'choices'; } public function __construct( $choices = null, $callback = null, bool $multiple = null, bool $strict = null, int $min = null, int $max = null, string $message = null, string $multipleMessage = null, string $minMessage = null, string $maxMessage = null, $groups = null, $payload = null, array $options = [] ) { if (\is_array($choices) && \is_string(key($choices))) { $options = array_merge($choices, $options); } elseif (null !== $choices) { $options['value'] = $choices; } parent::__construct($options, $groups, $payload); $this->callback = $callback ?? $this->callback; $this->multiple = $multiple ?? $this->multiple; $this->strict = $strict ?? $this->strict; $this->min = $min ?? $this->min; $this->max = $max ?? $this->max; $this->message = $message ?? $this->message; $this->multipleMessage = $multipleMessage ?? $this->multipleMessage; $this->minMessage = $minMessage ?? $this->minMessage; $this->maxMessage = $maxMessage ?? $this->maxMessage; } }
Nyholm/symfony
src/Symfony/Component/Validator/Constraints/Choice.php
PHP
mit
2,859
import { Component, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements AfterViewInit { ngAfterViewInit(): void { this.myComboBox1.add(this.myComboBox1).on('select', (event: any): void => { if (event.args) { let country = event.args.item.label; let source; if (country === 'Japan') { source = this.JapaneseCities; } else if (country === 'UK') { source = this.UKCities; } else { source = this.USACities; } this.myComboBox2.jqxComboBox({ source: source }); this.myComboBox2Min.jqxComboBox({ source: source }); } }); } countries: string[] = ['Japan', 'UK', 'USA']; JapaneseCities: string[] = ['Kobe', 'Kyoto', 'Tokyo']; UKCities: string[] = ['Brighton', 'Glasgow', 'London']; USACities: string[] = ['Boston', 'Los Angeles', 'Minneapolis']; myComboBox1; myComboBox1Min; myComboBox2; myComboBox2Min; tools: string = 'combobox | combobox'; initTools = (type: string, index: number, tool: any, menuToolIninitialization: any): any => { switch (index) { case 0: tool.jqxComboBox({ width: 150, source: this.countries, selectedIndex: 0, promptText: 'Select a country...' }); if (menuToolIninitialization === false) { this.myComboBox1 = tool; } else { this.myComboBox1Min = tool; } break; case 1: tool.jqxComboBox({ width: 150, source: this.JapaneseCities, selectedIndex: 0, promptText: 'Select a city...' }); if (menuToolIninitialization === false) { this.myComboBox2 = tool; } else { this.myComboBox2Min = tool; } break; } } }
luissancheza/sice
js/jqwidgets/demos/angular/app/toolbar/cascadingcomboboxesintoolbar/app.component.ts
TypeScript
mit
2,286