text:
#ifndef __wcecompat__STDIO_H__
#define __wcecompat__STDIO_H__

#include "stddef.h"
//#include "sys/types.h"	/* size_t */
#include "stdarg.h"

#ifdef __cplusplus
extern "C" {
#endif

// STDIO constant defns
#define _MAX_PATH    MAX_PATH

// EOF constants
#define EOF  (-1)
#define WEOF (wint_t)(0xFFFF)

// Seek method constants
#define SEEK_CUR    1
#define SEEK_END    2
#define SEEK_SET    0

// mode constants for _setmode()
#define _O_TEXT     0x4000  /* file mode is text (translated) */
#define _O_BINARY   0x8000  /* file mode is binary (untranslated) */

// FILE is an opaque handle in Win CE. Users have no access to the internals
#ifndef _FILE_DEFINED
typedef unsigned char FILE;
#define _FILE_DEFINED
#endif

#if _INTEGRAL_MAX_BITS >= 64
typedef __int64 fpos_t;
#else
typedef long fpos_t;
#endif

// Std handle defns
#define stdin  _getstdfilex(0)
#define stdout _getstdfilex(1)
#define stderr _getstdfilex(2)

// ANSI String formatting functions
_CRTIMP int    __cdecl sscanf(const char *, const char *, ...);
_CRTIMP int    __cdecl sprintf(char *, const char *, ...);
_CRTIMP int    __cdecl vsprintf(char *, const char *, va_list);
_CRTIMP int    __cdecl _snprintf(char *, size_t, const char *, ...);
_CRTIMP int    __cdecl _vsnprintf(char *, size_t, const char *, va_list);

// Always present since wsprintfW (used by kernel) redirects to these
_CRTIMP int __cdecl swprintf(wchar_t *, const wchar_t *, ...);
_CRTIMP int __cdecl vswprintf(wchar_t *, const wchar_t *, va_list);
_CRTIMP int __cdecl _snwprintf(wchar_t *, size_t, const wchar_t *, ...);
_CRTIMP int __cdecl _vsnwprintf(wchar_t *, size_t, const wchar_t *, va_list);

// WIDE String formatting functions
_CRTIMP int __cdecl swscanf(const wchar_t *, const wchar_t *, ...);

// ANSI Stdin/Out functions & macros
_CRTIMP int    __cdecl scanf(const char *, ...);
_CRTIMP int    __cdecl printf(const char *, ...);
_CRTIMP int    __cdecl vprintf(const char *, va_list);
_CRTIMP int    __cdecl getchar(void);
_CRTIMP char * __cdecl gets(char *);
_CRTIMP int    __cdecl putchar(int);
_CRTIMP int    __cdecl puts(const char *);

// ANSI functions for Stdin/out and/or general buffered file handling
_CRTIMP int    __cdecl fgetc(FILE *);
_CRTIMP char * __cdecl fgets(char *, int, FILE *);
_CRTIMP int    __cdecl fputc(int, FILE *);
_CRTIMP int    __cdecl fputs(const char *, FILE *);
_CRTIMP int    __cdecl ungetc(int, FILE *);

// ANSI functions for general buffered file handling
_CRTIMP FILE * __cdecl fopen(const char *, const char *);
_CRTIMP FILE*  __cdecl fdopen(int, const char *);
_CRTIMP int    __cdecl fscanf(FILE *, const char *, ...);
_CRTIMP int    __cdecl fprintf(FILE *, const char *, ...);
_CRTIMP int    __cdecl vfprintf(FILE *, const char *, va_list);

#define getc(_stream)     fgetc(_stream)
#define putc(_i, _stream) fputc(_i, _stream)

// functions for general buffered file handling in either ANSI or Wide
_CRTIMP FILE*  __cdecl _getstdfilex(int);
_CRTIMP int    __cdecl fclose(FILE *);
_CRTIMP int    __cdecl _fcloseall(void);
_CRTIMP size_t __cdecl fread(void *, size_t, size_t, FILE *);
_CRTIMP size_t __cdecl fwrite(const void *, size_t, size_t, FILE *);
_CRTIMP int    __cdecl fflush(FILE *);
_CRTIMP int    __cdecl _flushall(void);
_CRTIMP int    __cdecl feof(FILE *);
_CRTIMP int    __cdecl ferror(FILE *);
_CRTIMP void   __cdecl clearerr(FILE *);
_CRTIMP int    __cdecl fgetpos(FILE *, fpos_t *);
_CRTIMP int    __cdecl fsetpos(FILE *, const fpos_t *);
_CRTIMP int    __cdecl fseek(FILE *, long, int);
_CRTIMP long   __cdecl ftell(FILE *);
_CRTIMP int    __cdecl _fileno(FILE *);
_CRTIMP int    __cdecl _setmode(int fd, int mode);
_CRTIMP FILE*  __cdecl _wfdopen(void*, const wchar_t*);
_CRTIMP FILE*  __cdecl _wfreopen(const wchar_t *path, const wchar_t *mode, FILE *stream);
// old names
#define fcloseall _fcloseall
#define fileno    _fileno
#define flushall  _flushall

// WIDE Stdin/Out functions & macros
_CRTIMP int __cdecl wscanf(const wchar_t *, ...);
_CRTIMP int __cdecl wprintf(const wchar_t *, ...);
_CRTIMP int __cdecl vwprintf(const wchar_t *, va_list);
_CRTIMP wint_t __cdecl getwchar(void);
_CRTIMP wint_t __cdecl putwchar(wint_t);
_CRTIMP wchar_t * __cdecl _getws(wchar_t *);
_CRTIMP int __cdecl _putws(const wchar_t *);

// WIDE functions for Stdin/out and/or general buffered file handling
_CRTIMP wint_t __cdecl fgetwc(FILE *);
_CRTIMP wint_t __cdecl fputwc(wint_t, FILE *);
_CRTIMP wint_t __cdecl ungetwc(wint_t, FILE *);
_CRTIMP wchar_t * __cdecl fgetws(wchar_t *, int, FILE *);
_CRTIMP int __cdecl fputws(const wchar_t *, FILE *);

#define getwc(_stm)             fgetwc(_stm)
#define putwc(_c,_stm)          fputwc(_c,_stm)

// WIDE functions for general buffered file handling
_CRTIMP FILE * __cdecl _wfopen(const wchar_t *, const wchar_t *);
_CRTIMP int __cdecl fwscanf(FILE *, const wchar_t *, ...);
_CRTIMP int __cdecl fwprintf(FILE *, const wchar_t *, ...);
_CRTIMP int __cdecl vfwprintf(FILE *, const wchar_t *, va_list);

#define BUFSIZ (512)

void perror(const char *prefix);

#ifndef _IOFBF
#define _IOFBF	0
#endif
#ifndef _IOLBF
#define _IOLBF	1
#endif
#ifndef _IONBF
#define _IONBF	2
#endif

#ifndef FILENAME_MAX
#define FILENAME_MAX 260
#endif

int setbuf (FILE* stream, char* buffer);
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);

#ifdef __cplusplus
}
#endif

#endif /* __wcecompat__STDIO_H__ */


text:
IMCOMM_RET      imcomm_im_signon(void *handle, const char *sn, const char *pw);
IMCOMM_RET      bos_signon_phase2(void *handle, unsigned const char *server, unsigned const char *cookie, uint16_t cookie_len);
void            handle_srv_migration(void *handle, uint8_t * data, uint16_t len);
void            bos_md5snac(void *handle, uint8_t * data, uint16_t len);
IMCOMM_RET      flap_send(void *handle, uint8_t channel, unsigned char *packet, size_t len, int updateidle);
struct MultiPacket *MultiPktInit(void);
void            MultiPktFree(struct MultiPacket * h);
void            flap_addToMulti(struct MultiPacket * mpkt, uint8_t channel, unsigned char *packet, size_t len, int updateidle);
IMCOMM_RET      flap_sendMulti(void *handle, struct MultiPacket * pktlist);
IMCOMM_RET      flap_sendAct(void *handle, uint8_t channel, unsigned char *packet, size_t len, int updateidle);
IMCOMM_RET      flap_sendnext(void *handle);
IMCOMM_RET      flap_sendpkt(void *handle, uint8_t channel, pkt_t * pkt, int updateidle);
IMCOMM_RET      flap_decode(void *handle, unsigned char *header, unsigned char *data);
void           *imcomm_create_handle(void);
int             imcomm_delete_handle_now(void *vhandle);
int             imcomm_delete_handle(void *vhandle);
int             imcomm_delete_handle_only(void *vhandle);
void            imcomm_delete_buddylist(struct IMComm_BuddyList * buddylist);
void            imcomm_delete_familieslist(struct IMComm_Families * families);
void            imcomm_set_oscar_port(void *handle, uint16_t port);
void           *imcomm_create_child_handle(void *parent);
void            remove_deleted_handles(void);
void            imcomm_set_proxy(void *handle, int type, char *proxyserver, uint16_t proxyport);
void            imcomm_register_callback(void *handle, int event, void (*ptr) ());
IMCOMM_RET      imcomm_select(int nfds, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout);
int             imcomm_internal_add_buddy(void *handle, char *sn, const unsigned long idletime, const unsigned long onlinetime, int isaway);
void            imcomm_update_buddy_times(void *handle, const char *sn, int type, unsigned long value);
void            imcomm_update_buddy_away(void *handle, const char *sn, int isaway);
void            imcomm_internal_delete_buddy(void *handle, const char *sn);
char           *imcomm_simplify_sn(const char *sn);
void            imcomm_set_idle_time(void *handle, uint32_t idlesecs);
void            imcomm_set_profile(void *handle, char *profile);
void            imcomm_set_invisible(void *handle, int inv);
void            imcomm_set_away(void *handle, char *msg);
void            imcomm_set_unaway(void *handle);
int             imcomm_compare_nicks(void *handle, const char *s1, const char *s2);
uint16_t        imcomm_get_max_message_size(void *handle);
int             getbyteorder(void);
pkt_t          *pkt_init(size_t len);
void            pkt_zero(pkt_t * pkt);
void            pkt_free(pkt_t * pkt);
void            pkt_freeP(pkt_t * pkt);
pkt_t          *pkt_initP(uint8_t * data, uint16_t len);
size_t          pkt_empty(pkt_t * pkt);
size_t          pkt_getoffset(pkt_t * pkt);
void            pkt_skip(pkt_t * pkt, size_t skipnum);
void            pkt_setoffset(pkt_t * pkt, size_t offset);
int             pkt_end(pkt_t * pkt);
IMCOMM_RET      pkt_add8(pkt_t * pkt, uint8_t data);
IMCOMM_RET      pkt_add16(pkt_t * pkt, uint16_t val);
IMCOMM_RET      pkt_add32(pkt_t * pkt, uint32_t val);
IMCOMM_RET      pkt_addraw(pkt_t * pkt, uint8_t * data, size_t len);
uint8_t         pkt_get8(pkt_t * pkt);
uint16_t        pkt_get16(pkt_t * pkt);
uint32_t        pkt_get32(pkt_t * pkt);
uint8_t        *pkt_getraw(pkt_t * pkt, size_t len);
uint8_t        *pkt_getstr(pkt_t * pkt, size_t len);
void            pkt_dump(pkt_t * pkt);
int             connect_socks5(void *handle, char *host, uint16_t port);
int             connect_https(void *handle, char *host, uint16_t port);
IMCOMM_RET      snac_decode(void *handle, uint8_t * data, uint16_t len);
void            snac_addToMulti(void *handle, struct MultiPacket * mpkt, uint16_t family, uint16_t subtype, unsigned char *data, uint16_t len, int updateidle);
IMCOMM_RET      snac_send(void *handle, uint16_t family, uint16_t subtype, unsigned char *data, uint16_t len, int updateidle);
IMCOMM_RET      snac_sendpkt(void *handle, uint8_t family, uint8_t subtype, pkt_t * pkt, int updateidle);
IMCOMM_RET      snac_send_versions(void *handle);
IMCOMM_RET      snac_request_limits(void *handle);
IMCOMM_RET      snac_ack_srv_pause(void *handle, uint8_t * data, size_t len);
IMCOMM_RET      snac_get_srv_families(void *handle, uint8_t * data, size_t len);
IMCOMM_RET      snac_ack_limits(void *handle, unsigned char *data, size_t len);
IMCOMM_RET      snac_multireq(void *handle);
IMCOMM_RET      snac_get_privacy_rights(void *handle, uint8_t * data, uint16_t len);
IMCOMM_RET      snac_set_location_info(void *handle);
IMCOMM_RET      snac_send_icbm_params(void *handle, uint16_t channel, uint16_t max_msg_size);
IMCOMM_RET      snac_ssi_activate(void *handle);
IMCOMM_RET      snac_ssi_get_list(void *handle, uint8_t * data, uint16_t len);
IMCOMM_RET      snac_send_cli_update(void *handle);
IMCOMM_RET      multi_ssiact_cliready(void *handle);
IMCOMM_RET      snac_send_cli_ready(void *handle);
size_t          count_tlv(unsigned char *data, size_t len);
size_t          count_tlv_pkt(pkt_t * tp);
TLVLIST        *tlv_split(unsigned char *data, size_t len, size_t numtlv);
void            clear_tlv_list(TLVLIST * tlvlist);
uint32_t        four_to_32(unsigned char *value);
uint16_t        two_to_16(unsigned char *value);
IMCOMM_RET      snac_get_incoming_im(void *handle, uint8_t * data, uint16_t len);
IMCOMM_RET      snac_get_signoff(void *handle, uint8_t * data, uint16_t len);
IMCOMM_RET      snac_get_signon(void *handle, uint8_t * data, uint16_t len);
void            snac_get_user_info(void *handle, uint8_t * data, uint16_t len);
void            imcomm_im_send_message(void *handle, const char *whom, const char *msg, int automsg);
void            imcomm_request_awayprofile(void *handle, char *sn);
void            imcomm_request_profile(void *handle, char *sn);
void            imcomm_request_awaymsg(void *handle, char *sn);
void            imcomm_request_massawaymsg(void *handle, char **sns, int num);
void            imcomm_addtobuddylist(void *handle, char *sn, uint16_t id, uint16_t group_id);
uint16_t        imcomm_get_next_id(void *handle);
void            imcomm_im_add_buddy(void *handle, char *sn);
void            imcomm_im_remove_buddy(void *handle, const char *sn);
void            snac_request_new_service(void *handle, uint16_t service);
void            snac_new_subconnection(void *handle, unsigned char *data, uint16_t len);
void            imcomm_upload_icon(void *handle, uint8_t * data, uint16_t icon_len);
void            snac_finish_buddy_icon(void *handle);

redpajama_set_name: RedPajamaGithub


text:
CREATE PROCEDURE traderecord_put(IN order_buy_ INT, IN order_sell_ INT, IN price_ INT, IN quantity_ INT)
BEGIN
    INSERT INTO `TradeRecord`(`order_buy`, `order_sell`, `price`, `quantity`)
    VALUES (order_buy_, order_sell_, price_, quantity_);
END


text:
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.UI;
using Frapid.Areas;
using Frapid.Areas.Caching;

namespace Frapid.Dashboard.Controllers
{
    [AllowAnonymous]
    public class ResourceController : FrapidController
    {
        [FileOutputCache(Duration = 60*60*24, Location = OutputCacheLocation.Any)]
        [Route("dashboard/resources/{*resource}")]
        public ActionResult Get(string resource = "")
        {
            if (string.IsNullOrWhiteSpace(resource))
            {
                return this.HttpNotFound();
            }

            string directory = "~/Tenants/{0}/Areas/Frapid.Dashboard/Resources/";
            directory = string.Format(CultureInfo.InvariantCulture, directory, this.Tenant);
            directory = HostingEnvironment.MapPath(directory);

            if (directory == null)
            {
                return this.HttpNotFound();
            }

            string path = Path.Combine(directory, resource);

            if (!System.IO.File.Exists(path))
            {
                return this.HttpNotFound();
            }

            string mimeType = MimeMapping.GetMimeMapping(path);
            return this.File(path, mimeType);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>mbed utilities: Namespace List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

mbed utilities

Utilities that can be added to an mbed project using "mbed add git@github.com:wdwalker/wdwalker-mbed"

Namespace List

Here is a list of all documented namespaces with brief descriptions:

[detail level 123]

 ▼Nwdwalker	Utilities from https://github.com/wdwalker

 ▼Nmbed	Utilities for mbed

 Ndisplay	Utilities for LCD displays

 Nperipherals	Support for specific SPI and I2C peripherals available in the market

 Nstepper	Utilities for stepper motors

<address class="footer">
Generated by

 1.8.12
</address>


text:
import { storiesOf } from "@storybook/react"
import React from "react"

import Button, { ButtonState } from "../Buttons/Default"
import FacebookButton from "../Buttons/Facebook"
import GhostButton from "../Buttons/Ghost"
import InvertedButton from "../Buttons/Inverted"
import TwitterButton from "../Buttons/Twitter"

storiesOf("Components/Buttons", module)
  .add("Default Button", () => {
    return (

          <Button>Button</Button>
          <Button disabled>Button</Button>

          <Button state={ButtonState.Success}>Button</Button>
          <Button state={ButtonState.Success} disabled>Button</Button>

          <Button state={ButtonState.Failure}>Button</Button>
          <Button state={ButtonState.Failure} disabled>Button</Button>

    )
  })
  .add("Inverted Button", () => {
    return (

          <InvertedButton>Inverted Button</InvertedButton>
          <InvertedButton disabled>Button</InvertedButton>

    )
  })
  .add("Ghost Button", () => {
    return (

          <GhostButton>Ghost Button</GhostButton>
          <GhostButton disabled>Button</GhostButton>

    )
  })
  .add("Block Button", () => {
    return <Button block>Block Button</Button>
  })
  .add("Facebook Button", () => {
    return <FacebookButton />
  })
  .add("Twitter Button", () => {
    return <TwitterButton />
  })


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// 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.
//
//==============================================================================
//
// Author: Mike Brasher (mbrasher@bmc.com)
//
// Modified By: Carol Ann Krug Graves, Hewlett-Packard Company
//                  (carolann_graves@hp.com)
//              David Dillard, VERITAS Software Corp.
//                  (david.dillard@veritas.com)
//
//%/////////////////////////////////////////////////////////////////////////////

#include <cstdio>
#include "CIMPropertyRep.h"
#include "Indentor.h"
#include "CIMName.h"
#include "CIMScope.h"
#include "XmlWriter.h"
#include "MofWriter.h"
#include "DeclContext.h"

PEGASUS_USING_STD;

PEGASUS_NAMESPACE_BEGIN

CIMPropertyRep::CIMPropertyRep()
{
}

CIMPropertyRep::CIMPropertyRep(
    const CIMPropertyRep& x,
    Boolean propagateQualifiers)
    :
    Sharable(),
    _name(x._name),
    _value(x._value),
    _arraySize(x._arraySize),
    _referenceClassName(x._referenceClassName),
    _classOrigin(x._classOrigin),
    _propagated(x._propagated)
{
    if (propagateQualifiers)
	x._qualifiers.cloneTo(_qualifiers);
}

CIMPropertyRep::CIMPropertyRep(
    const CIMName& name,
    const CIMValue& value,
    Uint32 arraySize,
    const CIMName& referenceClassName,
    const CIMName& classOrigin,
    Boolean propagated)
    :
    _name(name), _value(value), _arraySize(arraySize),
    _referenceClassName(referenceClassName), _classOrigin(classOrigin),
    _propagated(propagated)
{
    // ensure name is not null
    if(name.isNull())
    {
        throw UninitializedObjectException();
    }

    if((arraySize != 0) && (!value.isArray() || value.getArraySize() != arraySize))
    {
        throw TypeMismatchException();
    }

    // if referenceClassName exists, must be CIMType REFERENCE.
    if (!referenceClassName.isNull())
    {
        if (_value.getType() != CIMTYPE_REFERENCE)
        {
            throw TypeMismatchException();
        }
    }

    // Can a property be of reference type with a null referenceClassName?
    // The DMTF says yes if it is a property of an instance; no if it is a
    // property of a class.  We'll allow it here, but check in the CIMClass
    // addProperty() method.
}

CIMPropertyRep::~CIMPropertyRep()
{
}

void CIMPropertyRep::setName(const CIMName& name)
{
    // ensure name is not null
    if(name.isNull())
    {
        throw UninitializedObjectException();
    }

    _name = name;
}

void CIMPropertyRep::setClassOrigin(const CIMName& classOrigin)
{
    _classOrigin = classOrigin;
}

void CIMPropertyRep::resolve(
    DeclContext* declContext,
    const CIMNamespaceName& nameSpace,
    Boolean isInstancePart,
    const CIMConstProperty& inheritedProperty,
    Boolean propagateQualifiers)
{
    PEGASUS_ASSERT(!inheritedProperty.isUninitialized());

    // Check the type:

    if (!inheritedProperty.getValue().typeCompatible(_value))
    {
        if (!(
            (inheritedProperty.getValue().getType() == CIMTYPE_OBJECT) &&
            (_value.getType() == CIMTYPE_STRING) &&
            (_qualifiers.find(CIMName("EmbeddedObject")) != PEG_NOT_FOUND) &&
            (inheritedProperty.getValue().isArray() == _value.isArray())
            ))
        {
            throw TypeMismatchException();
        }
    }

    // Validate the qualifiers of the property (according to
    // superClass's property with the same name). This method
    // will throw an exception if the validation fails.

    CIMScope scope = CIMScope::PROPERTY;

    if (_value.getType() == CIMTYPE_REFERENCE)
	scope = CIMScope::REFERENCE;

    // Test the reference class name against the inherited property
    if (_value.getType() == CIMTYPE_REFERENCE)
    {
        CIMName inheritedReferenceClassName = inheritedProperty.getReferenceClassName();
        CIMName referenceClassName;
        if(!_referenceClassName.isNull() && !_value.isNull())
        {
            CIMObjectPath valuePath;
            _value.get(valuePath);
            referenceClassName = valuePath.getClassName();
            bool found = _referenceClassName.equal(referenceClassName);
            while(!found)
            {
                CIMClass referenceClass = declContext->lookupClass(nameSpace, referenceClassName);
                if(referenceClass.isUninitialized())
                {
                    throw PEGASUS_CIM_EXCEPTION(
                      CIM_ERR_NOT_FOUND, referenceClassName.getString());
                }
                referenceClassName = referenceClass.getSuperClassName();
                if(referenceClassName.isNull())
                    throw TypeMismatchException();

                found = inheritedReferenceClassName.equal(referenceClassName);
            }
        }
        else if(!_referenceClassName.isNull())
        {
            referenceClassName = _referenceClassName;
        }
        else if(!_value.isNull())
        {
            CIMObjectPath valuePath;
            _value.get(valuePath);
            referenceClassName = valuePath.getClassName();
        }

        if(!referenceClassName.isNull())
        {
            bool found = inheritedReferenceClassName.equal(referenceClassName);
            while(!found)
            {
                CIMClass referenceClass = declContext->lookupClass(nameSpace, referenceClassName);
                if(referenceClass.isUninitialized())
                {
                    throw PEGASUS_CIM_EXCEPTION(
                        CIM_ERR_NOT_FOUND, referenceClassName.getString());
                }
                referenceClassName = referenceClass.getSuperClassName();
                if(referenceClassName.isNull())
                    throw TypeMismatchException();

                found = inheritedReferenceClassName.equal(referenceClassName);
            }
        }
    }

    _qualifiers.resolve(
	declContext,
	nameSpace,
	scope,
	isInstancePart,
	inheritedProperty._rep->_qualifiers,
	propagateQualifiers);

    _classOrigin = inheritedProperty.getClassOrigin();
}

void CIMPropertyRep::resolve(
    DeclContext* declContext,
    const CIMNamespaceName& nameSpace,
    Boolean isInstancePart,
    Boolean propagateQualifiers)
{
    CIMQualifierList dummy;

    CIMScope scope = CIMScope::PROPERTY;

    if (_value.getType() == CIMTYPE_REFERENCE)
	scope = CIMScope::REFERENCE;

    _qualifiers.resolve(
	declContext,
	nameSpace,
	scope,
	isInstancePart,
	dummy,
	propagateQualifiers);
}

static const char* _toString(Boolean x)
{
    return x ? "true" : "false";
}

void CIMPropertyRep::toXml(Array<char>& out) const
{
    if (_value.isArray())
    {
	out << "<PROPERTY.ARRAY";

	out << " NAME=\"" << _name << "\" ";

    // If the property array type is CIMObject, then
    //   encode the property in CIM-XML as a string array with the EMBEDDEDOBJECT attribute
    //   (there is not currently a CIM-XML "object" datatype)
    // else
    //   output the real type
    if (_value.getType() == CIMTYPE_OBJECT)
    {
        Array<CIMObject> a;
        _value.get(a);
        out << " TYPE=\"string\"";
        // If the Embedded Object is an instance, always add the EMBEDDEDOBJECT attribute.
        if (a.size() > 0 && a[0].isInstance())
            out << " EMBEDDEDOBJECT=\"object\"";
        // Else the Embedded Object is a class, always add the EmbeddedObject qualifier.
        // Note that if the macro PEGASUS_SNIA_INTEROP_COMPATIBILITY is defined, then
        // the EmbeddedObject qualifier will always be added, whether it's a class or
        // an instance.
#ifndef PEGASUS_SNIA_INTEROP_COMPATIBILITY
        else
        {
#endif
            if (_qualifiers.find(CIMName("EmbeddedObject")) == PEG_NOT_FOUND)
            {
                // Note that _qualifiers is not defined as const, and neither is add(),
                // but this method toXml() *is* const. However, in this case we really
                // do want to add the EmbeddedObject qualifier, so we cast away the
                // implied const-ness of _qualifiers.
                ((CIMQualifierList)_qualifiers).add(CIMQualifier(CIMName("EmbeddedObject"), true));
            }
#ifndef PEGASUS_SNIA_INTEROP_COMPATIBILITY
        }
#endif
    }
    else
    {
        out << " TYPE=\"" << cimTypeToString (_value.getType ()) << "\"";
    }

    if (_arraySize)
	{
	    char buffer[32];
	    sprintf(buffer, "%d", _arraySize);
	    out << " ARRAYSIZE=\"" << buffer << "\"";
	}

	if (!_classOrigin.isNull())
	    out << " CLASSORIGIN=\"" << _classOrigin << "\"";

	if (_propagated != false)
	    out << " PROPAGATED=\"" << _toString(_propagated) << "\"";

	out << ">\n";

	_qualifiers.toXml(out);

	XmlWriter::appendValueElement(out, _value);

	out << "</PROPERTY.ARRAY>\n";
    }
    else if (_value.getType() == CIMTYPE_REFERENCE)
    {
	out << "<PROPERTY.REFERENCE";

	out << " NAME=\"" << _name << "\" ";

        if (!_referenceClassName.isNull())
        {
            out << " REFERENCECLASS=\"" << _referenceClassName << "\"";
        }

	if (!_classOrigin.isNull())
	    out << " CLASSORIGIN=\"" << _classOrigin << "\"";

	if (_propagated != false)
	    out << " PROPAGATED=\"" << _toString(_propagated) << "\"";

	out << ">\n";

	_qualifiers.toXml(out);

	XmlWriter::appendValueElement(out, _value);

	out << "</PROPERTY.REFERENCE>\n";
    }
    else
    {
	out << "<PROPERTY";
	out << " NAME=\"" << _name << "\" ";

	if (!_classOrigin.isNull())
	    out << " CLASSORIGIN=\"" << _classOrigin << "\"";

	if (_propagated != false)
	    out << " PROPAGATED=\"" << _toString(_propagated) << "\"";

    // If the property type is CIMObject, then
    //   encode the property in CIM-XML as a string with the EMBEDDEDOBJECT attribute
    //   (there is not currently a CIM-XML "object" datatype)
    // else
    //   output the real type
    if (_value.getType() == CIMTYPE_OBJECT)
    {
        CIMObject a;
        _value.get(a);
        out << " TYPE=\"string\"";
        // If the Embedded Object is an instance, always add the EMBEDDEDOBJECT attribute.
        if (a.isInstance())
            out << " EMBEDDEDOBJECT=\"object\"";
        // Else the Embedded Object is a class, always add the EmbeddedObject qualifier.
        // Note that if the macro PEGASUS_SNIA_INTEROP_COMPATIBILITY is defined, then
        // the EmbeddedObject qualifier will always be added, whether it's a class or
        // an instance.
#ifndef PEGASUS_SNIA_INTEROP_COMPATIBILITY
        else
        {
#endif
            if (_qualifiers.find(CIMName("EmbeddedObject")) == PEG_NOT_FOUND)
            {
                // Note that _qualifiers is not defined as const, and neither is add(),
                // but this method toXml() *is* const. However, in this case we really
                // do want to add the EmbeddedObject qualifier, so we cast away the
                // implied const-ness of _qualifiers.
                ((CIMQualifierList)_qualifiers).add(CIMQualifier(CIMName("EmbeddedObject"), true));
            }
#ifndef PEGASUS_SNIA_INTEROP_COMPATIBILITY
        }
#endif
    }
    else
    {
        out << " TYPE=\"" << cimTypeToString (_value.getType ()) << "\"";
    }

	out << ">\n";

	_qualifiers.toXml(out);

	XmlWriter::appendValueElement(out, _value);

	out << "</PROPERTY>\n";
    }
}

/** toMof - returns the MOF for the CIM Property Object in the parameter.
    The BNF for the property MOF is:
    <pre>
    propertyDeclaration     = 	[ qualifierList ] dataType propertyName
				[ array ] [ defaultValue ] ";"

    array 		    = 	"[" [positiveDecimalValue] "]"

    defaultValue 	    = 	"=" initializer
    </pre>
    Format with qualifiers on one line and declaration on another. Start
    with newline but none at the end.
*/
void CIMPropertyRep::toMof(Array<char>& out) const  //ATTNKS:
{
    //Output the qualifier list
    if (_qualifiers.getCount())
	out << "\n";
    _qualifiers.toMof(out);

    // Output the Type and name on a new line
    out << "\n" << cimTypeToString (_value.getType ()) << " " << _name;

    // If array put the Array indicator "[]" and possible size after name.
    if (_value.isArray())
    {
	if (_arraySize)
	{
	    char buffer[32];
	    sprintf(buffer, "[%d]", _arraySize);
	    out << buffer;
	}
	else
	    out << "[]";
    }

    // If the property value is not Null, add value after "="
    if (!_value.isNull())
    {
	out << " = ";
	if (_value.isArray())
	{
	    // Insert any property values
	    MofWriter::appendValueElement(out, _value);
	}
	else if (_value.getType() == CIMTYPE_REFERENCE)
	{
	    MofWriter::appendValueElement(out, _value);
	}
	else
	{
	    MofWriter::appendValueElement(out, _value);
	}
    }
    // Close the property MOF
    out << ";";

}

Boolean CIMPropertyRep::identical(const CIMPropertyRep* x) const
{
    if (!_name.equal (x->_name))
	return false;

    if (_value != x->_value)
	return false;

    if (!_referenceClassName.equal (x->_referenceClassName))
	return false;

    if (!_qualifiers.identical(x->_qualifiers))
	return false;

    if (!_classOrigin.equal (x->_classOrigin))
	return false;

    if (_propagated != x->_propagated)
	return false;

    return true;
}

void CIMPropertyRep::setValue(const CIMValue& value)
{
    // CIMType of value is immutable:

    if (!value.typeCompatible(_value))
	throw TypeMismatchException();

    if (_arraySize && _arraySize != value.getArraySize())
	throw TypeMismatchException();

    _value = value;
}

PEGASUS_NAMESPACE_END


text:
package org.apache.mahout.utils.vectors;

import java.util.Iterator;
import java.util.Random;

import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.common.iterator.CountingIterator;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.function.DoubleFunction;

public final class RandomVectorIterable implements Iterable<Vector> {

  public enum VectorType {DENSE, SPARSE}

  private final int numItems;
  private final VectorType type;

  public RandomVectorIterable() {
    this(100, VectorType.SPARSE);
  }

  public RandomVectorIterable(int numItems) {
    this(numItems, VectorType.SPARSE);
  }

  public RandomVectorIterable(int numItems, VectorType type) {
    this.numItems = numItems;
    this.type = type;
  }

  @Override
  public Iterator<Vector> iterator() {
    return Iterators.transform(
        new CountingIterator(numItems),
        new Function<Integer, Vector>() {
          private final Random random = RandomUtils.getRandom();
          @Override
          public Vector apply(Integer dummy) {
            Vector result =
                type == VectorType.SPARSE ? new RandomAccessSparseVector(numItems) : new DenseVector(numItems);
            result.assign(new DoubleFunction() {
              @Override
              public double apply(double ignored) {
                return random.nextDouble();
              }
            });
            return result;
          }
        });
  }

}


text:
"""Contains the logic for `aq show service`."""

from sqlalchemy.orm import joinedload, subqueryload, undefer, contains_eager

from aquilon.worker.broker import BrokerCommand  # pylint: disable=W0611
from aquilon.aqdb.model import Service, ServiceInstance
from aquilon.worker.dbwrappers.host import hostname_to_host
from aquilon.worker.formats.service_instance import ServiceInstanceList
from aquilon.worker.formats.service import ServiceList

class CommandShowService(BrokerCommand):

    def render(self, session, server, client, **arguments):
        instance = arguments.get("instance", None)
        dbserver = server and hostname_to_host(session, server) or None
        dbclient = client and hostname_to_host(session, client) or None
        if dbserver:
            q = session.query(ServiceInstance)
            if instance:
                q = q.filter_by(name=instance)
            q = q.join(Service)
            q = q.reset_joinpoint()
            q = q.join('servers')
            q = q.filter_by(host=dbserver)
            q = q.order_by(Service.name, ServiceInstance.name)
            return ServiceInstanceList(q.all())
        elif dbclient:
            service_instances = dbclient.services_used
            if instance:
                service_instances = [si for si in service_instances if si.name == instance]
            return ServiceInstanceList(service_instances)
        else:
            # Try to load as much as we can as bulk queries since loading the
            # objects one by one is much more expensive
            q = session.query(Service)
            q = q.join(ServiceInstance)
            q = q.options(contains_eager('instances'))
            q = q.options(subqueryload('archetypes'))
            q = q.options(subqueryload('personalities'))
            q = q.options(undefer('instances._client_count'))
            q = q.options(subqueryload('instances.personality_service_map'))
            q = q.options(subqueryload('instances.servers'))
            q = q.options(joinedload('instances.servers.host'))
            q = q.options(joinedload('instances.servers.host.machine'))
            q = q.options(subqueryload('instances.service_map'))
            q = q.options(joinedload('instances.service_map.location'))
            q = q.options(subqueryload('instances.personality_service_map'))
            q = q.options(joinedload('instances.personality_service_map.location'))
            q = q.order_by(Service.name, ServiceInstance.name)
            return ServiceList(q.all())


text:
(function($){
	var controller = new Controller();

	controller.buildPage = function(){
		// get the first page
		this.queryData({'page':1}, 'get-article-list', $.proxy(this.creatArticleList, this));
	};

	controller.bindMyPageHander = function(){
		var self = this;
		 $('#article-paging').twbsPagination({

			 totalPages: $('#article-paging').attr('page-number'),
			 first:'<<',
			 prev:'<',
			 next:'>',
			 last:'>>',

		     onPageClick: function (event, page) {
		    	 self.queryData({'page':page}, 'get-article-list', $.proxy(self.creatArticleList, self));
		     }
		 });
	};
	controller.bindDeleteEvents = function(){
		$("[action=delete]").on('click', $.proxy(this.deleteArticle, this));
	};

	controller.deleteArticle = function(e){
		var id = $(e.target).data('id');
		bootbox.confirm("确定删除文章吗?", $.proxy(function(result){
			if(result){
				this.saveToServer('delete-article?id='+id);
			}
		},this));
	};

	controller.creatArticleList = function(data){

		if($('#ul-list').attr('auth') == "true"){
		     data.auth = true;
		}
		for(i = 0; i < data.length; i++){
			if(data[i].type == 1){
				data[i].typeClass="article-type-solon";
				data[i].typeName = "双隆公告";

			}
			else{
				data[i].typeClass="article-type-media";
				data[i].typeName = "媒体报告"
			}
		}
		var self = this;
		$.get('/resources/template/article-list.tmpl').done(function(html){

		    var template = Hogan.compile(html);
		    html = template.render({articles: data});
		    $('#ul-list').empty();
		    $('#ul-list').append(html);
		    if(data.auth){
		    	$('#ul-list').append('
新建文章
');
		    }

		    $.proxy(self.bindDeleteEvents, self)();

		});

	};

	controller.initialize();

})(jQuery);


text:
package com.nilhcem.fakesmtp.gui;

import com.nilhcem.fakesmtp.core.ArgsHandler;
import com.nilhcem.fakesmtp.core.Configuration;
import com.nilhcem.fakesmtp.core.exception.UncaughtExceptionHandler;
import com.nilhcem.fakesmtp.gui.listeners.MainWindowListener;
import com.nilhcem.fakesmtp.model.UIModel;
import com.nilhcem.fakesmtp.server.SMTPServerHandler;
import org.slf4j.LoggerFactory;

import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import org.slf4j.Logger;

/**
 * Provides the main window of the application.
 *
 * @author Nilhcem
 * @since 1.0
 */
public final class MainFrame {

	private static final Logger LOGGER = LoggerFactory.getLogger(MainFrame.class);

	private final JFrame mainFrame = new JFrame(Configuration.INSTANCE.get("application.title"));
	private final MenuBar menu = new MenuBar(this);
	private final MainPanel panel = new MainPanel(menu);

	/**
	 * Creates the main window and makes it visible.
	 *

	 * First, assigns the main panel to the default uncaught exception handler to display exceptions in this panel.

	 * Before creating the main window, the application will have to set some elements, such as:
	 *

	 *

	 *
The minimum and default size;

	 *
The menu bar and the main panel;

	 *
An icon image;

	 *
A shutdown hook to stop the server, once the main window is closed.

	 *

	 *

	 * The icon of the application is a modified version from the one provided in "{@code WebAppers.com}"
	 * (Creative Commons Attribution 3.0 License).
	 *

	 */
	public MainFrame() {
		((UncaughtExceptionHandler) Thread.getDefaultUncaughtExceptionHandler()).setParentComponent(panel.get());
		Dimension frameSize = new Dimension(Integer.parseInt(Configuration.INSTANCE.get("application.min.width")),
			Integer.parseInt(Configuration.INSTANCE.get("application.min.height")));

		Image iconImage = Toolkit.getDefaultToolkit().getImage(
			getClass().getResource(Configuration.INSTANCE.get("application.icon.path")));

		MainWindowListener windowListener = new MainWindowListener(this);

		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				close();
			}
		});

		mainFrame.addWindowStateListener(windowListener); // used for TrayIcon
		mainFrame.setSize(frameSize);
		mainFrame.setMinimumSize(frameSize);

		mainFrame.setJMenuBar(menu.get());
		mainFrame.getContentPane().add(panel.get());
		mainFrame.setLocationRelativeTo(null); // Center main frame
		mainFrame.setIconImage(iconImage);

		// Add shutdown hook to stop server if enabled
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				SMTPServerHandler.INSTANCE.stopServer();
			}
		});

		// Restore last saved smtp port (if not overridden by the user)
		String smtpPort = ArgsHandler.INSTANCE.getPort();
		if (smtpPort == null) {
			smtpPort = Configuration.INSTANCE.get("smtp.default.port");
		}
		panel.getPortText().setText(smtpPort);

		// Restore last emails directory (if not overridden by the user)
		String emailsDir = ArgsHandler.INSTANCE.getOutputDirectory();
		if (emailsDir == null) {
			emailsDir = Configuration.INSTANCE.get("emails.default.dir");
		}
		if (emailsDir != null && !emailsDir.isEmpty()) {
			panel.getSaveMsgTextField().get().setText(emailsDir);
			UIModel.INSTANCE.setSavePath(emailsDir);
		}

		mainFrame.setVisible(true);
	}

	public void close() {
		LOGGER.debug("Closing the application and saving the configuration");

		Configuration.INSTANCE.set("smtp.default.port", panel.getPortText().get().getText());
		Configuration.INSTANCE.set("emails.default.dir", panel.getSaveMsgTextField().get().getText());

		try {
			Configuration.INSTANCE.saveToUserProfile();
		} catch (IOException ex) {
			LOGGER.error("Could not save configuration", ex);
		}
		// Check for SMTP server running and stop it
		if (SMTPServerHandler.INSTANCE.getSmtpServer().isRunning()) {
			SMTPServerHandler.INSTANCE.getSmtpServer().stop();
		}

		mainFrame.dispose();
	}
}


text:
using System;
using MobileTemplate.Core.Extensions;
using Xamarin.Forms;

namespace MobileTemplate.Core.Pages.ThemeSample
{
    public class CustomThemeSamplePage : ContentPage, IDisposable
    {
        public CustomThemeSamplePage()
        {
            Title = "Custom Theme Sample";
            Content = new CustomThemeSampleView();
        }

        public void Dispose()
        {
            this.DisposeContent();
            this.DisposeBindingContext();
        }
    }
}


text:
#include "type/ImageAttributes.hpp"
#include "file/File.hpp"

class Bmp
{
public:
	enum { HEADER_SIZE = 54, DIB_HEADER_SIZE = 40 };

	typedef struct Header
	{
		uint16_t id;
		uint32_t fileSize;
		uint32_t reserved;
		uint32_t dataOffset;
		uint32_t dibHeaderSize;
		uint32_t width;
		uint32_t height;
		uint16_t planes;
		uint16_t bitsPrePixel;
		uint32_t compression;
		uint32_t imageSize;
		uint32_t xPixelsPerMeter;
		uint32_t yPixelsPerMeter;
		uint32_t colorsInColorTable;
		uint32_t importantColorCount;
	} Header;

	Bmp() = default;
	Bmp(const char *fileName);
	Bmp(const char *fileName, const SizeU &size, uint8_t channel = 3);

	~Bmp();

	void open(const char *fileName);
	void open(const char *fileName, const SizeU &size, uint8_t channel = 3);

	void close();

	void read(ImageAttributes &attributes);
	void write(ImageAttributes &attributes);

	uint32_t getWidth() const { return header.width; }
	uint32_t getHeight() const { return header.height; }

	SizeU getSize() const { return SizeU(getWidth(), getHeight()); }

	uint8_t getChannel() const { return (uint8_t)(header.bitsPrePixel / 8); }

private:
	uint32_t getPadding() const { return header.width % 4; }
	uint32_t getLineStep() const { return header.width * (uint32_t)getChannel(); }
	void readHeader();
	void writeHeader();
	void fillHeader(const char buffer[HEADER_SIZE]);
	void createDefaultHeader(const SizeU &size, uint8_t channel);

	Header header;
	File file;
};

#endif


text:
#include <memory>
#include <string>

#include "pybind11/embed.h"
#include "ExecutePythonProcessor.h"
#include "PythonProcessor.h"

namespace org::apache::nifi::minifi::python {

namespace core = org::apache::nifi::minifi::core;

PythonProcessor::PythonProcessor(core::Processor* proc) {
  processor_ = dynamic_cast<python::processors::ExecutePythonProcessor*>(proc);
  gsl_Expects(processor_);
}

void PythonProcessor::setSupportsDynamicProperties() {
  processor_->setSupportsDynamicProperties();
}

void PythonProcessor::setDecription(const std::string &desc) {
  processor_->setDescription(desc);
}

void PythonProcessor::addProperty(const std::string &name, const std::string &description, const std::string &defaultvalue, bool required, bool el) {
  processor_->addProperty(name, description, defaultvalue, required, el);
}

}  // namespace org::apache::nifi::minifi::python


text:
define("ghost/controllers/modals/upload",
  ["exports"],
  function(__exports__) {
    "use strict";

    var UploadController = Ember.Controller.extend({
        acceptEncoding: 'image/*',
        actions: {
            confirmAccept: function () {
                var self = this;

                this.get('model').save().then(function (model) {
                    self.notifications.showSuccess('Saved');
                    return model;
                }).catch(function (err) {
                    self.notifications.showErrors(err);
                });
            },

            confirmReject: function () {
                return false;
            }
        }
    });

    __exports__["default"] = UploadController;
  });


text:
from mkcrowbar.commands.install import *
from mkcrowbar.commands.prepare import *
from mkcrowbar.commands.checks import *
from mkcrowbar.commands.setup import *
from mkcrowbar.commands.repos import *


text:
package com.webcohesion.enunciate.metadata.rs;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Ryan Heaton
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( { ElementType.METHOD, ElementType.TYPE } )
public @interface ResourceGroup {

    /**
     * The label for the resource group.
     *
     * @return The label for the resource group.
     */
    String value();

}


text:
handle=structmsg.createDispatcher()
result=structmsg.initDispatcher(handle)

function sendIMsg(handle)
  structmsg.uartReceiveCb(handle,string.char(tonumber("57",16)),1)
  structmsg.uartReceiveCb(handle,string.char(tonumber("00",16)),1)
  structmsg.uartReceiveCb(handle,string.char(tonumber("4D",16)),1)
  structmsg.uartReceiveCb(handle,string.char(tonumber("00",16)),1)
  structmsg.uartReceiveCb(handle,string.char(tonumber("00",16)),1)
  structmsg.uartReceiveCb(handle,string.char(tonumber("08",16)),1)
  structmsg.uartReceiveCb(handle,string.char(73),1)
  structmsg.uartReceiveCb(handle,string.char(10),1)
--  structmsg.uartReceiveCb(handle,string.char(tonumber("10",16)),1)
end

  echo=0
  dataBits=8
  baud=115200
  uart.setup(0, baud, dataBits, uart.PARITY_NONE, uart.STOPBITS_1, echo)
  eol="\n"
  uart.on("data", 1,
    function(data)
      structmsg.uartReceiveCb(handle,data,1)
--      sendIMsg(handle)
    end
  ,0)


text:
(function () {
    'use strict';

    // This helper adds a class that shows a loading state.
    angular
        .module('BH')
        .directive('ngGoogleplace', ngGoogleplace);

    ngGoogleplace.$inject = ['GoogleplaceService'];

    function ngGoogleplace(GoogleplaceService) {
        var directive = {
            link: link,
            restrict: 'A',
            controller: ngGoogleplaceController,
            controllerAs: 'gc',
            bindToController: true
        };
        function link(scope, element, attrs, model) {

            var options = {
                types: [],
                componentRestrictions: {
                    'country': 'au'
                }
            };
            var autocomplete = new google.maps.places.Autocomplete(element[0], options);
            $(document).on('keydown', element[0], function(e) {
                if (e.which == 13) {
                    $(element[0]).show();
                    return false;
                }
            });
            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                //var place = autocomplete.getPlace();
                GoogleplaceService.updateAddress(autocomplete);
            });

            scope.$on('broadcast.google.setBounds', function (event, args) {
                autocomplete.setBounds(args);
            });

        }
        return directive;
    }

    ngGoogleplaceController.$inject = ['$scope', '$http','GoogleplaceService'];

    function ngGoogleplaceController($scope, $http,GoogleplaceService) {
        var gc = this;

        gc.geolocate = function () {
            // Bias the autocomplete object to the user's geographical location,
            // as supplied by the browser's 'navigator.geolocation' object.
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var geolocation = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };
                    var circle = new google.maps.Circle({
                        center: geolocation,
                        radius: position.coords.accuracy
                    });
                    GoogleplaceService.setBounds(circle.getBounds());
                });
            }
        };

        // Watch for event from another module.
        $scope.$on('broadcast.google.updateAddress', function (event, args) {

        });
    }
})();


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/back_forward_cache_browsertest.h"

#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/shell/browser/shell.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/back_forward_cache_not_restored_reasons.mojom-blink.h"
namespace content {
using NotRestoredReason = BackForwardCacheMetrics::NotRestoredReason;
using NotRestoredReasons =
    BackForwardCacheCanStoreDocumentResult::NotRestoredReasons;

class BackForwardCacheBrowserTestWithNotRestoredReasons
    : public BackForwardCacheBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    EnableFeatureAndSetParams(
        blink::features::kBackForwardCacheSendNotRestoredReasons, "", "");
    BackForwardCacheBrowserTest::SetUpCommandLine(command_line);
  }
};

using ReasonsMatcher = testing::Matcher<
    const blink::mojom::BackForwardCacheNotRestoredReasonsPtr&>;
using SameOriginMatcher = testing::Matcher<
    const blink::mojom::SameOriginBfcacheNotRestoredDetailsPtr&>;
ReasonsMatcher BackForwardCacheBrowserTest::MatchesNotRestoredReasons(
    const testing::Matcher<blink::mojom::BFCacheBlocked>& blocked,
    const SameOriginMatcher* same_origin_details) {
  return testing::Pointee(testing::AllOf(
      testing::Field("blocked",
                     &blink::mojom::BackForwardCacheNotRestoredReasons::blocked,
                     blocked),
      testing::Field(
          "same_origin_details",
          &blink::mojom::BackForwardCacheNotRestoredReasons::
              same_origin_details,
          same_origin_details
              ? *same_origin_details
              : testing::Property(
                    "is_null",
                    &blink::mojom::SameOriginBfcacheNotRestoredDetailsPtr::
                        is_null,
                    true))));
}

SameOriginMatcher BackForwardCacheBrowserTest::MatchesSameOriginDetails(
    const testing::Matcher<std::string>& id,
    const testing::Matcher<std::string>& name,
    const testing::Matcher<std::string>& src,
    const testing::Matcher<std::string>& url,
    const std::vector<testing::Matcher<std::string>>& reasons,
    const std::vector<ReasonsMatcher>& children) {
  return testing::Pointee(testing::AllOf(
      testing::Field(
          "id", &blink::mojom::SameOriginBfcacheNotRestoredDetails::id, id),
      testing::Field("name",
                     &blink::mojom::SameOriginBfcacheNotRestoredDetails::name,
                     name),
      testing::Field(
          "src", &blink::mojom::SameOriginBfcacheNotRestoredDetails::src, src),
      testing::Field(
          "url", &blink::mojom::SameOriginBfcacheNotRestoredDetails::url, url),
      testing::Field(
          "reasons",
          &blink::mojom::SameOriginBfcacheNotRestoredDetails::reasons,
          testing::UnorderedElementsAreArray(reasons)),
      testing::Field(
          "children",
          &blink::mojom::SameOriginBfcacheNotRestoredDetails::children,
          testing::ElementsAreArray(children))));
}

// NotRestoredReasons are not reported when the page is successfully restored
// from back/forward cache.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       NotReportedWhenRestored) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
  // 1) Navigate to A.
  ASSERT_TRUE(NavigateToURL(shell(), url_a));
  RenderFrameHostImplWrapper rfh_a(current_frame_host());

  // 2) Navigate to B.
  ASSERT_TRUE(NavigateToURL(shell(), url_b));

  // 3) Navigate back.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  ExpectRestored(FROM_HERE);
  // Expect that NotRestoredReasons are not reported at all.
  EXPECT_TRUE(current_frame_host()->NotRestoredReasonsForTesting().is_null());
}

// NotRestoredReasons are reset after each navigation.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       ReasonsResetForEachNavigation) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
  // 1) Navigate to A and use dummy blocking feature.
  ASSERT_TRUE(NavigateToURL(shell(), url_a));
  RenderFrameHostImplWrapper rfh_a(current_frame_host());
  rfh_a->UseDummyStickyBackForwardCacheDisablingFeatureForTesting();
  std::string rfh_a_url = rfh_a->GetLastCommittedURL().spec();

  // 2) Navigate to B.
  ASSERT_TRUE(NavigateToURL(shell(), url_b));
  RenderFrameHostImplWrapper rfh_b(current_frame_host());

  // 3) Navigate back.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  ExpectNotRestored({NotRestoredReason::kBlocklistedFeatures},
                    {blink::scheduler::WebSchedulerTrackedFeature::kDummy}, {},
                    {}, {}, FROM_HERE);
  // Expect that NotRestoredReasons are reported.
  auto rfh_a_details = MatchesSameOriginDetails(
      /*id=*/"", /*name=*/"", /*src=*/"",
      /*url=*/rfh_a_url, /*reasons=*/{"Dummy"}, /*children=*/{});
  auto rfh_a_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kYes, &rfh_a_details);
  EXPECT_THAT(current_frame_host()->NotRestoredReasonsForTesting(),
              rfh_a_result);
  EXPECT_TRUE(rfh_b->IsInBackForwardCache());

  // 4) Navigate forward.
  ASSERT_TRUE(HistoryGoForward(web_contents()));
  ExpectRestored(FROM_HERE);
  // Expect that NotRestoredReasons are not reported at all.
  EXPECT_TRUE(current_frame_host()->NotRestoredReasonsForTesting().is_null());
}

// Frame attributes are only reported when the document is same origin with main
// document. Also test that the details for cross-origin subtree are masked.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       FrameAttributesAreReportedIfSameOrigin) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(a,b(a))"));
  GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));
  // 1) Navigate to A(A,B(A)).
  ASSERT_TRUE(NavigateToURL(shell(), url_a));
  // rfh_a_1(rfh_a_2,rfh_b(rfh_a_3))
  RenderFrameHostImplWrapper rfh_a_1(current_frame_host());
  RenderFrameHostImplWrapper rfh_a_2(
      rfh_a_1->child_at(0)->current_frame_host());
  RenderFrameHostImplWrapper rfh_b(rfh_a_1->child_at(1)->current_frame_host());
  RenderFrameHostImplWrapper rfh_a_3(rfh_b->child_at(0)->current_frame_host());
  std::string rfh_a_1_url = rfh_a_1->GetLastCommittedURL().spec();
  std::string rfh_a_2_url = rfh_a_2->GetLastCommittedURL().spec();

  rfh_a_3->UseDummyStickyBackForwardCacheDisablingFeatureForTesting();

  // cross_site_iframe_factory.html gives frames ids but they are not globally
  // unique, so replace them with unique ids so that there will be no
  // duplicates.
  EXPECT_TRUE(ExecJs(rfh_a_1.get(), R"(
    let frames = document.getElementsByTagName('iframe');
    frames[0].id = 'rfh_a_2_id';
    frames[0].name = 'rfh_a_2_name';
    frames[1].id = 'rfh_b_id';
    frames[1].name = 'rfh_b_name';
  )"));
  // 2) Navigate to C.
  ASSERT_TRUE(NavigateToURL(shell(), url_c));

  // 3) Navigate back.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  ExpectNotRestored({NotRestoredReason::kBlocklistedFeatures},
                    {blink::scheduler::WebSchedulerTrackedFeature::kDummy}, {},
                    {}, {}, FROM_HERE);

  // Expect that id and name are masked for |rfh_b|, but reported for |rfh_a_2|.
  // Note that |rfh_a_3| is masked because it's a child of |rfh_b|.
  auto rfh_a_2_details = MatchesSameOriginDetails(
      /*id=*/"rfh_a_2_id", /*name=*/"rfh_a_2_name", /*src=*/rfh_a_2_url,
      /*url=*/rfh_a_2_url, /*reasons=*/{}, /*children=*/{});
  auto rfh_b_result =
      MatchesNotRestoredReasons(blink::mojom::BFCacheBlocked::kYes, nullptr);
  auto rfh_a_2_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kNo, &rfh_a_2_details);
  auto rfh_a_1_details = MatchesSameOriginDetails(
      /*id=*/"", /*name=*/"", /*src=*/"", /*url=*/rfh_a_1_url,
      /*reasons=*/{},
      /*children=*/{rfh_a_2_result, rfh_b_result});
  auto rfh_a_1_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kNo, &rfh_a_1_details);

  EXPECT_THAT(current_frame_host()->NotRestoredReasonsForTesting(),
              rfh_a_1_result);
}

// All the blocking reasons should be reported including subframes'.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       AllBlockingFramesAreReported) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(a,a(a))"));
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
  // 1) Navigate to A(A,A(A)) and use dummy blocking feature in the main frame
  // and subframes.
  ASSERT_TRUE(NavigateToURL(shell(), url_a));
  // rfh_a_1(rfh_a_2, rfh_a_3(rfh_a_4))
  RenderFrameHostImplWrapper rfh_a_1(current_frame_host());
  RenderFrameHostImplWrapper rfh_a_2(
      rfh_a_1->child_at(0)->current_frame_host());
  RenderFrameHostImplWrapper rfh_a_3(
      rfh_a_1->child_at(1)->current_frame_host());
  RenderFrameHostImplWrapper rfh_a_4(
      rfh_a_3->child_at(0)->current_frame_host());
  std::string rfh_a_1_url = rfh_a_1->GetLastCommittedURL().spec();
  std::string rfh_a_2_url = rfh_a_2->GetLastCommittedURL().spec();
  std::string rfh_a_3_url = rfh_a_3->GetLastCommittedURL().spec();
  std::string rfh_a_4_url = rfh_a_4->GetLastCommittedURL().spec();

  rfh_a_1->UseDummyStickyBackForwardCacheDisablingFeatureForTesting();
  rfh_a_2->UseDummyStickyBackForwardCacheDisablingFeatureForTesting();
  rfh_a_4->UseDummyStickyBackForwardCacheDisablingFeatureForTesting();

  // 2) Navigate to B.
  ASSERT_TRUE(NavigateToURL(shell(), url_b));

  // 3) Navigate back.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  ExpectNotRestored({NotRestoredReason::kBlocklistedFeatures},
                    {blink::scheduler::WebSchedulerTrackedFeature::kDummy}, {},
                    {}, {}, FROM_HERE);

  auto rfh_a_2_details = MatchesSameOriginDetails(
      /*id=*/"child-0", /*name=*/"", /*src=*/rfh_a_2_url, /*url=*/rfh_a_2_url,
      /*reasons=*/{"Dummy"},
      /*children=*/{});
  auto rfh_a_2_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kYes, &rfh_a_2_details);
  auto rfh_a_4_details = MatchesSameOriginDetails(
      /*id=*/"child-0", /*name=*/"", /*src=*/rfh_a_4_url, /*url=*/rfh_a_4_url,
      /*reasons=*/{"Dummy"},
      /*children=*/{});
  auto rfh_a_4_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kYes, &rfh_a_4_details);
  auto rfh_a_3_details = MatchesSameOriginDetails(
      /*id=*/"child-1", /*name=*/"", /*src=*/rfh_a_3_url, /*url=*/rfh_a_3_url,
      /*reasons=*/{}, /*children=*/
      {rfh_a_4_result});
  auto rfh_a_3_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kNo, &rfh_a_3_details);
  auto rfh_a_1_details = MatchesSameOriginDetails(
      /*id=*/"", /*name=*/"", /*src=*/"", /*url=*/rfh_a_1_url,
      /*reasons=*/{"Dummy"},
      /*children=*/{rfh_a_2_result, rfh_a_3_result});
  auto rfh_a_1_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kYes, &rfh_a_1_details);
  EXPECT_THAT(current_frame_host()->NotRestoredReasonsForTesting(),
              rfh_a_1_result);
}

// NotRestoredReasons are not reported for same document navigation.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       NotReportedForSameDocumentNavigation) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a_1(embedded_test_server()->GetURL(
      "a.com", "/accessibility/html/a-name.html"));
  GURL url_a_2(embedded_test_server()->GetURL(
      "a.com", "/accessibility/html/a-name.html#id"));
  // 1) Navigate to A.
  EXPECT_TRUE(NavigateToURL(shell(), url_a_1));
  // 2) Do a same-document navigation.
  EXPECT_TRUE(NavigateToURL(shell(), url_a_2));
  // 3) Navigate back.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  ExpectOutcomeDidNotChange(FROM_HERE);
  // Expect that NotRestoredReasons are not reported at all.
  EXPECT_TRUE(current_frame_host()->NotRestoredReasonsForTesting().is_null());
}

// NotRestoredReasons are not reported for subframe navigation.
IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       SubframeNavigationDoesNotRecordMetrics) {
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL(
      "a.com", "/cross_site_iframe_factory.html?a(b)"));
  GURL url_c(embedded_test_server()->GetURL("c.com", "/title1.html"));

  // 1) Navigate to A(B).
  EXPECT_TRUE(NavigateToURL(shell(), url_a));
  RenderFrameHostImplWrapper rfh_a(current_frame_host());

  // 2) Navigate from B to C on the subframe.
  EXPECT_TRUE(NavigateFrameToURL(rfh_a->child_at(0), url_c));
  EXPECT_EQ(url_c,
            rfh_a->child_at(0)->current_frame_host()->GetLastCommittedURL());
  EXPECT_FALSE(rfh_a->IsInBackForwardCache());

  // 4) Go back from C to B on the subframe.
  ASSERT_TRUE(HistoryGoBack(web_contents()));
  EXPECT_TRUE(
      rfh_a->child_at(0)->current_frame_host()->GetLastCommittedURL().DomainIs(
          "b.com"));
  EXPECT_FALSE(rfh_a->IsInBackForwardCache());
  ExpectOutcomeDidNotChange(FROM_HERE);
  // NotRestoredReasons are not recorded.
  EXPECT_TRUE(current_frame_host()->NotRestoredReasonsForTesting().is_null());
}

IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTestWithNotRestoredReasons,
                       WindowOpen) {
  if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites())
    return;

  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
  GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));

  // 1) Navigate to A and open a popup.
  ASSERT_TRUE(NavigateToURL(shell(), url_a));
  RenderFrameHostImplWrapper rfh_a(current_frame_host());
  EXPECT_EQ(1u, rfh_a->GetSiteInstance()->GetRelatedActiveContentsCount());
  OpenPopup(rfh_a.get(), url_a, "");
  EXPECT_EQ(2u, rfh_a->GetSiteInstance()->GetRelatedActiveContentsCount());
  rfh_a->GetBackForwardCacheMetrics()->SetObserverForTesting(this);
  std::string rfh_a_url = rfh_a->GetLastCommittedURL().spec();

  // 2) Navigate to B. The previous document can't enter the BackForwardCache,
  // because of the popup.
  ASSERT_TRUE(NavigateToURLFromRenderer(rfh_a.get(), url_b));
  ASSERT_TRUE(rfh_a.WaitUntilRenderFrameDeleted());
  RenderFrameHostImplWrapper rfh_b(current_frame_host());
  EXPECT_EQ(2u, rfh_b->GetSiteInstance()->GetRelatedActiveContentsCount());

  // 3) Go back to A. The previous document can't enter the BackForwardCache,
  // because of the popup.
  ASSERT_TRUE(HistoryGoBack(web_contents()));

  ExpectNotRestored({NotRestoredReason::kRelatedActiveContentsExist,
                     NotRestoredReason::kBrowsingInstanceNotSwapped},
                    {},
                    {ShouldSwapBrowsingInstance::kNo_HasRelatedActiveContents},
                    {}, {}, FROM_HERE);
  // Make sure that the tree result also has the same reasons. BrowsingInstance
  // NotSwapped can only be known at commit time.
  EXPECT_THAT(
      GetTreeResult()->GetDocumentResult(),
      MatchesDocumentResult(
          NotRestoredReasons(NotRestoredReason::kRelatedActiveContentsExist,
                             NotRestoredReason::kBrowsingInstanceNotSwapped),
          BlockListedFeatures()));

  // Both reasons are recorded and sent to the renderer.
  // BrowsingInstanceNotSwapped is masked as internal error.
  auto rfh_a_details = MatchesSameOriginDetails(
      /*id=*/"", /*name=*/"", /*src=*/"", /*url=*/rfh_a_url,
      /*reasons=*/{"Related active contents", "Internal error"},
      /*children=*/{});
  auto rfh_a_result = MatchesNotRestoredReasons(
      blink::mojom::BFCacheBlocked::kYes, &rfh_a_details);
  EXPECT_THAT(current_frame_host()->NotRestoredReasonsForTesting(),
              rfh_a_result);
}

}  // namespace content


text:
"""This module contains an object that represents a Telegram Proximity Alert."""
from typing import Any, Optional, TYPE_CHECKING

from telegram import TelegramObject, User
from telegram.utils.types import JSONDict

if TYPE_CHECKING:
    from telegram import Bot

class ProximityAlertTriggered(TelegramObject):
    """
    This object represents the content of a service message, sent whenever a user in the chat
    triggers a proximity alert set by another user.

    Objects of this class are comparable in terms of equality. Two objects of this class are
    considered equal, if their :attr:`traveler`, :attr:`watcher` and :attr:`distance` are equal.

    Args:
        traveler (:class:`telegram.User`): User that triggered the alert
        watcher (:class:`telegram.User`): User that set the alert
        distance (:obj:`int`): The distance between the users

    Attributes:
        traveler (:class:`telegram.User`): User that triggered the alert
        watcher (:class:`telegram.User`): User that set the alert
        distance (:obj:`int`): The distance between the users

    """

    __slots__ = ('traveler', 'distance', 'watcher', '_id_attrs')

    def __init__(self, traveler: User, watcher: User, distance: int, **_kwargs: Any):
        self.traveler = traveler
        self.watcher = watcher
        self.distance = distance

        self._id_attrs = (self.traveler, self.watcher, self.distance)

    @classmethod
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['ProximityAlertTriggered']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['traveler'] = User.de_json(data.get('traveler'), bot)
        data['watcher'] = User.de_json(data.get('watcher'), bot)

        return cls(bot=bot, **data)


text:
package com.ameron32.apps.tapnotes.v2.ui.BASE;

/**
 * Created by klemeilleur on 4/21/2016.
 */
public interface MvpView {

}


text:
/*!
 @file    GoalPoint.h
 @brief    The definition of a BFSM point goal.
 */

#ifndef __GOAL_POINT_H__
#define __GOAL_POINT_H__

#include "MengeCore/BFSM/Goals/Goal.h"
#include "MengeCore/BFSM/Goals/GoalFactory.h"
#include "MengeCore/BFSM/fsmCommon.h"
#include "MengeCore/CoreConfig.h"

namespace Menge {

namespace BFSM {
/*!
 @brief    A simple point goal.  The goal is trivially this point.
 */
class MENGE_API PointGoal : public Goal {
 public:
  /*! Default constructor */
  PointGoal();

  /*!
   @brief    Full constructor.

   @param    p    The position of the goal.
   */
  PointGoal(const Vector2& p);

  /*!
   @brief    Full constructor - component-wise.

   @param    x    The x-position of the goal.
   @param    y    The x-position of the goal.
   */
  PointGoal(float x, float y);

  /*!
   @brief    Used by the plugin system to know what artifacts to associate with agents of this type.

   Every sub-class of must return a globally unique value if it should be associated with unique
   artifacts.
   */
  virtual std::string getStringId() const { return NAME; }

  /*! The unique identifier used to register this type with run-time components. */
  static const std::string NAME;
};

/*!
 @brief    Factory for the PointGoal.
 */
class MENGE_API PointGoalFactory : public GoalFactory {
 public:
  /*!
   @brief    The name of the goal type.

   The goal's name must be unique among all registered goals. Each goal factory must override this
   function.

   @returns  A string containing the unique goal name.
   */
  virtual const char* name() const { return PointGoal::NAME.c_str(); }

  /*!
   @brief    A description of the goal.

   Each goal factory must override this function.

   @returns  A string containing the goal description.
   */
  virtual const char* description() const {
    return "An agent goal consisting of a single point in two-dimensional space";
  };

 protected:
  /*!
   @brief    Create an instance of this class's goal.

   @returns    A pointer to a newly instantiated Goal class.
   */
  Goal* instance() const { return new PointGoal(); }

  /*!
   @brief    Given a pointer to a Goal instance, sets the appropriate fields from the provided XML
            node.

   @param    goal        A pointer to the goal whose attributes are to be set.
   @param    node        The XML node containing the action attributes.
   @param    behaveFldr  The path to the behavior file.  If the action references resources in the
                        file system, it should be defined relative to the behavior file location.
                        This is the folder containing that path.
   @returns  A boolean reporting success (true) or failure (false).
   */
  virtual bool setFromXML(Goal* goal, TiXmlElement* node, const std::string& behaveFldr) const;
};

}  // namespace BFSM
}  // namespace Menge

#endif  // __GOAL_POINT_H__


text:
/**
 * Constructor for JsSpeechRecognizer.
 * Sets a number of parameters to default values.
 */
function JsSpeechRecognizer() {

    // Constants
    this.RecordingEnum = { "NOT_RECORDING": 0, "TRAINING": 1, "RECOGNITION": 2, "KEYWORD_SPOTTING": 3, "KEYWORD_SPOTTING_NOISY": 4 };
    Object.freeze(this.RecordingEnum);
    this.RecognitionModel = { "TRAINED": 0, "AVERAGE": 1, "COMPOSITE": 2 };
    Object.freeze(this.RecognitionModel);

    // Variables for recording data
    this.recordingBufferArray = [];
    this.currentRecordingBuffer = [];
    this.wordBuffer = [];
    this.modelBuffer = [];
    this.groupedValues = [];
    this.keywordSpottingGroupBuffer = [];
    this.keywordSpottingRecordingBuffer = [];

    // The speech recognition model
    this.model = {};

    this.recordingState = this.RecordingEnum.NOT_RECORDING;
    this.useRecognitionModel = this.RecognitionModel.COMPOSITE;

    // Get an audio context
    this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();

    // Generate functions for keyword spotting
    this.findDistanceForKeywordSpotting = this.generateFindDistanceForKeywordSpotting(-1);
    this.findDistanceForKeywordSpotting0 = this.generateFindDistanceForKeywordSpotting(0);
    this.findDistanceForKeywordSpotting5 = this.generateFindDistanceForKeywordSpotting(5);
    this.findDistanceForKeywordSpotting15 = this.generateFindDistanceForKeywordSpotting(15);

    // Adjustable parameters

    // Create an analyser
    this.analyser = this.audioCtx.createAnalyser();
    this.analyser.minDecibels = -80;
    this.analyser.maxDecibels = -10;
    this.analyser.smoothingTimeConstant = 0;
    this.analyser.fftSize = 1024;

    // Create the scriptNode
    this.scriptNode = this.audioCtx.createScriptProcessor(this.analyser.fftSize, 1, 1);
    this.scriptNode.onaudioprocess = this.generateOnAudioProcess();

    // Parameters for the model calculation
    this.numGroups = 25;
    this.groupSize = 10;
    this.minPower = 0.01;

    // Keyword spotting parameters
    this.keywordSpottingMinConfidence = 0.50;
    this.keywordSpottingBufferCount = 80;
    this.keywordSpottingLastVoiceActivity = 0;
    this.keywordSpottingMaxVoiceActivityGap = 300;
    this.keywordSpottedCallback = null;

}

/**
 * Requests access to the microphone.
 * @public
 */
JsSpeechRecognizer.prototype.openMic = function() {

    var constraints = {
        "audio": true
    };

    navigator.getUserMedia(constraints, successCallback, errorCallback);

    var _this = this;
    // Acess to the microphone was granted
    function successCallback(stream) {
        _this.stream = stream;
        _this.source = _this.audioCtx.createMediaStreamSource(stream);

        _this.source.connect(_this.analyser);
        _this.analyser.connect(_this.scriptNode);

        // This is needed for chrome
        _this.scriptNode.connect(_this.audioCtx.destination);
    }

    function errorCallback(error) {
        console.error('navigator.getUserMedia error: ', error);
    }
};

/**
 * Returns false if the recognizer is not recording. True otherwise.
 * @public.
 */
JsSpeechRecognizer.prototype.isRecording = function() {
    return (this.recordingState !== this.RecordingEnum.NOT_RECORDING);
};

/**
 * Starts recording in TRAINING mode.
 * @public
 */
JsSpeechRecognizer.prototype.startTrainingRecording = function(curWord) {
    this.resetBuffers();
    this.recordingState = this.RecordingEnum.TRAINING;
    this.wordBuffer.push(curWord);
};

/**
 * Starts recording in RECOGNITION mode.
 * @public
 */
JsSpeechRecognizer.prototype.startRecognitionRecording = function() {
    this.resetBuffers();
    this.recordingState = this.RecordingEnum.RECOGNITION;
};

/**
 * Starts recording in KEYWORD_SPOTTING mode.
 * @public
 */
JsSpeechRecognizer.prototype.startKeywordSpottingRecording = function() {
    this.resetBuffers();
    this.recordingState = this.RecordingEnum.KEYWORD_SPOTTING;
};

/**
 * Starts a recording in KEYWORD_SPOTTING_NOISY mode.
 * @public
 */
JsSpeechRecognizer.prototype.startKeywordSpottingNoisyRecording = function() {
    this.resetBuffers();
    this.recordingState = this.RecordingEnum.KEYWORD_SPOTTING_NOISY;
};

/**
 * Stops recording.
 * @return {Number} the length of the training buffer.
 * @public
 */
JsSpeechRecognizer.prototype.stopRecording = function() {

    this.groupedValues = [].concat.apply([], this.groupedValues);
    this.normalizeInput(this.groupedValues);

    // If we are training we want to save to the recongition model buffer
    if (this.recordingState === this.RecordingEnum.TRAINING) {
        this.recordingBufferArray.push(this.currentRecordingBuffer.slice(0));
        this.modelBuffer.push(this.groupedValues.slice(0));
    }

    this.recordingState = this.RecordingEnum.NOT_RECORDING;

    return this.recordingBufferArray.length;
};

/**
 * Plays training audio for the specified index.
 * @param {Number} index
 * @public
 */
JsSpeechRecognizer.prototype.playTrainingBuffer = function(index) {
    this.playMonoAudio(this.recordingBufferArray[index]);
};

/**
 * Delete training data for the specified index.
 * @param {Number} index
 * @public
 */
JsSpeechRecognizer.prototype.deleteTrainingBuffer = function(index) {
    this.modelBuffer[index] = null;
};

/**
 * Play mono audio.
 * @param {Array} playBuffer
 * @public
 */
JsSpeechRecognizer.prototype.playMonoAudio = function(playBuffer) {

    var channels = 1;
    var frameCount = playBuffer.length;
    var myArrayBuffer = this.audioCtx.createBuffer(channels, frameCount, this.audioCtx.sampleRate);

    for (var channel = 0; channel < channels; channel++) {
        var nowBuffering = myArrayBuffer.getChannelData(channel);
        for (var i = 0; i < frameCount; i++) {
            nowBuffering[i] = playBuffer[i];
        }
    }

    var playSource = this.audioCtx.createBufferSource();
    playSource.buffer = myArrayBuffer;
    playSource.connect(this.audioCtx.destination);
    playSource.start();
};

/**
 * Returns an array of the top recognition hypotheses.
 * @param {Number} numResults
 * @return {Array}
 * @public
 */
JsSpeechRecognizer.prototype.getTopRecognitionHypotheses = function(numResults) {
    return this.findClosestMatch(this.groupedValues, numResults, this.model, this.findDistance);
};

/**
 * Method to generate the new speech recognition model from the training data.
 * @public
 */
JsSpeechRecognizer.prototype.generateModel = function() {

    var i = 0;
    var j = 0;
    var k = 0;
    var key = "";
    var averageModel = {};

    // Reset the model
    this.model = {};

    for (i = 0; i < this.wordBuffer.length; i++) {
        key = this.wordBuffer[i];
        this.model[key] = [];
    }

    for (i = 0; i < this.modelBuffer.length; i++) {
        if (this.modelBuffer[i] !== null) {
            key = this.wordBuffer[i];
            this.model[key].push(this.modelBuffer[i]);
        }
    }

    // If we are only using the trained entries, no need to anything else
    if (this.useRecognitionModel === this.RecognitionModel.TRAINED) {
        return;
    }

    // Average Model
    // Holds one entry for each key. That entry is the average of all the entries in the model
    for (key in this.model) {
        var average = [];
        for (i = 0; i < this.model[key].length; i++) {
            for (j = 0; j < this.model[key][i].length; j++) {
                average[j] = (average[j] || 0) + (this.model[key][i][j] / this.model[key].length);
            }
        }

        averageModel[key] = [];
        averageModel[key].push(average);
    }

    // Interpolation - Take the average of each pair of entries for a key and
    // add it to the average model
    for (key in this.model) {

        var averageInterpolation = [];
        for (k = 0; k < this.model[key].length; k++) {
            for (i = k + 1; i < this.model[key].length; i++) {

                averageInterpolation = [];
                for (j = 0; j < Math.max(this.model[key][k].length, this.model[key][i].length); j++) {
                    var entryOne = this.model[key][k][j] || 0;
                    var entryTwo = this.model[key][i][j] || 0;
                    averageInterpolation[j] = (entryOne + entryTwo) / 2;
                }

                averageModel[key].push(averageInterpolation);
            }
        }
    }

    if (this.useRecognitionModel === this.RecognitionModel.AVERAGE) {
        this.model = averageModel;
    } else if (this.useRecognitionModel === this.RecognitionModel.COMPOSITE) {
        // Merge the average model into the model
        for (key in this.model) {
            this.model[key] = this.model[key].concat(averageModel[key]);
        }
    }

};

// Private internal functions

/**
 * Resets the recording buffers.
 * @private
 */
JsSpeechRecognizer.prototype.resetBuffers = function() {
    this.currentRecordingBuffer = [];
    this.groupedValues = [];

    this.keywordSpottingGroupBuffer = [];
    this.keywordSpottingRecordingBuffer = [];
};

// Audio Processing functions

/**
 * Generates an audioProcess function.
 * @return {Function}
 * @private
 */
JsSpeechRecognizer.prototype.generateOnAudioProcess = function() {
    var _this = this;
    return function(audioProcessingEvent) {

        var i = 0;

        // If we aren't recording, don't do anything
        if (_this.recordingState === _this.RecordingEnum.NOT_RECORDING) {
            return;
        }

        // get the fft data
        var dataArray = new Uint8Array(_this.analyser.fftSize);
        _this.analyser.getByteFrequencyData(dataArray);

        // Find the max in the fft array
        var max = Math.max.apply(Math, dataArray);

        // If the max is zero ignore it.
        if (max === 0) {
            return;
        }

        // Get the audio data. For simplicity just take one channel
        var inputBuffer = audioProcessingEvent.inputBuffer;
        var leftChannel = inputBuffer.getChannelData(0);

        // Calculate the power
        var curFrame = new Float32Array(leftChannel);
        var power = 0;
        for (i = 0; i < curFrame.length; i++) {
            power += curFrame[i] * curFrame[i];
        }

        // Check for the proper power level
        if (power < _this.minPower) {
            return;
        }

        // Save the data for playback.
        Array.prototype.push.apply(_this.currentRecordingBuffer, curFrame);

        // Normalize and Group the frequencies
        var groups = [];

        for (i = 0; i < _this.numGroups; i++) {
            var peakGroupValue = 0;
            for (var j = 0; j < _this.groupSize; j++) {
                var curPos = (_this.groupSize * i) + j;

                // Keep the peak normalized value for this group
                if (dataArray[curPos] > peakGroupValue) {
                    peakGroupValue = dataArray[curPos];
                }

            }
            groups.push(peakGroupValue);
        }

        // Depending on the state, handle the data differently
        if (_this.recordingState === _this.RecordingEnum.KEYWORD_SPOTTING || _this.recordingState === _this.RecordingEnum.KEYWORD_SPOTTING_NOISY) {

            // Check if we should reset the buffers
            var now = new Date().getTime();
            if (now - _this.keywordSpottingLastVoiceActivity > _this.keywordSpottingMaxVoiceActivityGap) {
                _this.resetBuffers();
            }
            _this.keywordSpottingLastVoiceActivity = now;

            _this.keywordSpottingProcessFrame(groups, curFrame);
        } else {
            _this.groupedValues.push(groups);
        }

    };
};

/**
 * Process a new frame of data while in recording state KEYWORD_SPOTTING.
 * @param{Array} groups - the group data for the frame
 * @param{Array} curFrame - the raw audio data for the frame
 * @private
 */
JsSpeechRecognizer.prototype.keywordSpottingProcessFrame = function(groups, curFrame) {

    var computedLength;
    var key;
    var allResults = [];
    var recordingLength;
    var workingGroupBuffer = [];

    // Append to the keywordspotting buffer
    this.keywordSpottingGroupBuffer.push(groups);
    this.keywordSpottingGroupBuffer = [].concat.apply([], this.keywordSpottingGroupBuffer);

    // Trim the buffer if necessary
    computedLength = (this.keywordSpottingBufferCount * this.numGroups);
    if (this.keywordSpottingGroupBuffer.length > computedLength) {
        this.keywordSpottingGroupBuffer = this.keywordSpottingGroupBuffer.slice(this.keywordSpottingGroupBuffer.length - computedLength, this.keywordSpottingGroupBuffer.length);
    }

    // Save the audio data
    Array.prototype.push.apply(this.keywordSpottingRecordingBuffer, curFrame);

    // Trim the buffer if necessary
    computedLength = (this.keywordSpottingBufferCount * this.analyser.fftSize);
    if (this.keywordSpottingRecordingBuffer.length > computedLength) {
        this.keywordSpottingRecordingBuffer = this.keywordSpottingRecordingBuffer.slice(this.keywordSpottingRecordingBuffer.length - computedLength, this.keywordSpottingRecordingBuffer.length);
    }

    // Copy buffer, and normalize it, and use it to find the closest match
    workingGroupBuffer = this.keywordSpottingGroupBuffer.slice(0);
    this.normalizeInput(workingGroupBuffer);

    // Use the correct keyword spotting function
    if (this.recordingState === this.RecordingEnum.KEYWORD_SPOTTING_NOISY) {
        allResults = this.keywordDetectedNoisy(workingGroupBuffer);
    } else {
        allResults = this.keywordDetectedNormal(workingGroupBuffer);
    }

    // See if a keyword was spotted
    if (allResults !== null && allResults[0] !== undefined) {

        // Save the audio
        recordingLength = (allResults[0].frameCount / this.numGroups) * this.analyser.fftSize;

        if (recordingLength > this.keywordSpottingRecordingBuffer.length) {
            recordingLength = this.keywordSpottingRecordingBuffer.length;
        }

        allResults[0].audioBuffer = this.keywordSpottingRecordingBuffer.slice(this.keywordSpottingRecordingBuffer.length - recordingLength, this.keywordSpottingRecordingBuffer.length);

        this.resetBuffers();
        if (this.keywordSpottedCallback !== undefined && this.keywordSpottedCallback !== null) {
            this.keywordSpottedCallback(allResults[0]);
        }

    }

};

// Keyword spotting functions

/**
 * Analyzes a buffer to determine if a keyword has been found.
 * Will return an array if a keyword was found, null otherwise.
 *
 * @param {Array} workingGroupBuffer
 * @return {Array|null}
 * @private
 */
JsSpeechRecognizer.prototype.keywordDetectedNormal = function(workingGroupBuffer) {
    var allResults = {};

    allResults = this.findClosestMatch(workingGroupBuffer, 1, this.model, this.findDistanceForKeywordSpotting);

    if (allResults[0] !== undefined && allResults[0].confidence > this.keywordSpottingMinConfidence) {
        return allResults;
    }

    return null;
};

/**
 * Analyzes a buffer to determine if a keyword has been found.
 * Will return an array if a keyword was found, null otherwise.
 * Designed to adjust for different levels of noise.
 *
 * @param {Array} workingGroupBuffer
 * @return {Array|null}
 * @private
 */
JsSpeechRecognizer.prototype.keywordDetectedNoisy = function(workingGroupBuffer) {

    // TODO: Make it possible for a user to specify the number of keyword spotting functions
    // And change this duplicated code to a loop!

    var allResults15 = {};
    var allResults15MinConfidence = this.keywordSpottingMinConfidence;

    allResults15 = this.findClosestMatch(workingGroupBuffer, 1, this.model, this.findDistanceForKeywordSpotting15);

    if (allResults15[0].confidence <= allResults15MinConfidence) {
        return null;
    }

    var allResults5 = {};
    var allResults5MinConfidence = this.keywordSpottingMinConfidence - 0.1;

    allResults5 = this.findClosestMatch(workingGroupBuffer, 1, this.model, this.findDistanceForKeywordSpotting5);

    if (allResults5[0].confidence <= allResults5MinConfidence) {
        return null;
    }

    var allResults0 = {};
    var allResults0MinConfidence = this.keywordSpottingMinConfidence - 0.15;

    allResults0 = this.findClosestMatch(workingGroupBuffer, 1, this.model, this.findDistanceForKeywordSpotting0);

    if (allResults0[0].confidence <= allResults0MinConfidence) {
        return null;
    }

    // finally, run the normal check
    var allResults = {};

    allResults = this.findClosestMatch(workingGroupBuffer, 1, this.model, this.findDistanceForKeywordSpotting);

    // Calculate the minimum confidence
    var allResultsMinConfidence = this.keywordSpottingMinConfidence - 0.1 - (Math.max((allResults[0].noise * 1.25) - 1, 0) * 0.75);

    // Final check for returning the results
    if (allResults[0] !== undefined && allResults[0].confidence > allResultsMinConfidence) {
        return allResults;
    }

    return null;
};

// Calculation functions

/**
 * Normalizes an input array to a scale from 0 to 100.
 *
 * @param {Array} input
 * @private
 */
JsSpeechRecognizer.prototype.normalizeInput = function(input) {
    // Find the max in the fft array
    var max = Math.max.apply(Math, input);

    for (var i = 0; i < input.length; i++) {
        input[i] = Math.floor((input[i] / max) * 100);
    }
};

/**
 * Finds the closest matches for an input, for a specified model.
 * Uses specified findDistance function, or a default one.
 *
 * @param {Array} input
 * @param {Number} numResults
 * @param {Object} speechModel
 * @param {Function} findDistance
 * @return {Array}
 * @private
 */
JsSpeechRecognizer.prototype.findClosestMatch = function(input, numResults, speechModel, findDistanceFunction) {

    var i = 0;
    var key = "";
    var allResults = [];

    // If no findDistance function is defined, use the default
    if (findDistanceFunction === undefined) {
        findDistanceFunction = this.findDistanceFunction;
    }

    // Loop through all the keys in the model
    for (key in speechModel) {
        // Loop through all entries for that key
        for (i = 0; i < speechModel[key].length; i++) {

            var curDistance = findDistanceFunction(input, speechModel[key][i]);
            var curConfidence = this.calcConfidence(curDistance, speechModel[key][i]);
            var curNoise = this.calculateNoise(input, speechModel[key][i]);

            var newResult = {};
            newResult.match = key;
            newResult.confidence = curConfidence;
            newResult.noise = curNoise;
            newResult.frameCount = speechModel[key][i].length;
            allResults.push(newResult);
        }

    }

    allResults.sort(function(a, b) { return b.confidence - a.confidence; });

    if (numResults === -1) {
        return allResults;
    }

    return allResults.slice(0, numResults);
};

/**
 * Computes the sum of differances between an input and a modelEntry.
 *
 * @param {Array} input
 * @param {Array} modelEntry
 * @return {Number}
 * @private
 */
JsSpeechRecognizer.prototype.findDistance = function(input, modelEntry) {
    var i = 0;
    var distance = 0;

    for (i = 0; i < Math.max(input.length, modelEntry.length); i++) {
        var modelVal = modelEntry[i] || 0;
        var inputVal = input[i] || 0;
        distance += Math.abs(modelVal - inputVal);
    }

    return distance;
};

/**
 * Will generate a distanceForKeywordSpotting function.
 * The function will calculate differences for entries in the model that
 * are greater than the parameter modelEntryGreaterThanVal.
 *
 * @param {Number} modelEntryGreaterThanVal
 * @return {Function}
 * @private
 */
JsSpeechRecognizer.prototype.generateFindDistanceForKeywordSpotting = function(modelEntryGreaterThanVal) {

    /**
     * Calculates the keyword spotting distance an input is from a model entry.
     *
     * @param {Array} input
     * @param {Array} modelEntry
     * @return {Number}
     * @private
     */
    return function(input, modelEntry) {
        var i = 0;
        var distance = 0;

        // Compare from the end of the input, for modelEntry.length entries
        for (i = 1; i <= modelEntry.length; i++) {
            var modelVal = modelEntry[modelEntry.length - i] || 0;
            var inputVal = input[input.length - i] || 0;
            if (modelVal > modelEntryGreaterThanVal) {
                distance += Math.abs(modelVal - inputVal);
            }
        }

        return distance;
    };
};

/**
 * Calculates a confidence value based on the distance form a model entry.
 * Max confidence is 1, min is negative infinity.
 *
 * @param {Number} distance
 * @param {Array} modelEntry
 * @return {Number}
 * @private
 */
JsSpeechRecognizer.prototype.calcConfidence = function(distance, modelEntry) {
    var sum = 0;
    var i = 0;

    for (i = 0; i < modelEntry.length; i++) {
        sum += modelEntry[i];
    }

    return (1 - (distance / sum));
};

/**
 * Calculates how noisy an input is compared to a model entry.
 *
 * @param {Array} input
 * @param {Array} modelEntry
 * @return {Number}
 * @private
 */
JsSpeechRecognizer.prototype.calculateNoise = function(input, modelEntry) {
    var i = 0;
    var sumIn = 0;
    var sumEntry = 0;

    // Compare from the end of the input, for modelEntry.length entries
    for (i = 1; i <= modelEntry.length; i++) {
        var modelVal = modelEntry[modelEntry.length - i] || 0;
        var inputVal = input[input.length - i] || 0;
        sumIn += inputVal * inputVal;

        // TODO: Optimize by caching the calculation for the model
        sumEntry += modelVal * modelVal;
    }

    return (sumIn / sumEntry);
};


text:
from random import choice
import unittest

class RPSGame:
    gestures = ['rock', 'paper', 'scissors']
    player_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')]

    # the rules of the game
    def _evaluate(self, player_move, computer_move):
        if player_move == computer_move:
            return "Draw!"
        elif (player_move, computer_move) in RPSGame.player_wins:
            return "Player wins!"
        else:
            return "Computer wins!"

    # computer player
    def _computer_move(self):
        return choice(RPSGame.gestures)

    # verify player's input
    def _verify_move(self, player_move):
        if player_move not in RPSGame.gestures:
            raise Exception("Wrong input!")
        return player_move

    # play n rounds of the game against the computer
    def play(self, rounds=1):
        for i in range(rounds):
            player_move = self._verify_move(input("[rock,paper,scissors]: "))
            computer_move = self._computer_move()
            winner = self._evaluate(player_move, computer_move)
            print(20 * "-")
            print("You played: %s" % player_move)
            print("Computer played: %s" % computer_move)
            print(winner)
            print(20 * "-")

class RPSGameTests(unittest.TestCase):
    def setUp(self):
        self.rps = RPSGame()

    def test_evaluate(self):
        # 1. test for draw
        for g in RPSGame.gestures:
            self.assertEqual(self.rps._evaluate(g, g), 'Draw!')
        # 2. test for player victory
        for g1, g2 in RPSGame.player_wins:
            self.assertEqual(self.rps._evaluate(g1, g2), 'Player wins!')
        # note that we don't have to test for the conditions when
        # computer wins as there are no other possibilities

    def test_computer_move(self):
        moves = {'rock': 0, 'paper': 0, 'scissors': 0}
        n = 100000
        for i in range(n):
            cp = self.rps._computer_move()
            moves[cp] += 1
        for gesture in RPSGame.gestures:
            # 1. Due to the fact the fraction 1/3 is infinite
            # assertEqual will never equate to true (unless n
            # is infinite). Therefore, we need to test
            # for almost equal.
            # self.assertEqual(moves[gesture] / n, 1/3)
            # 2. Test for almost equal with the precision of
            # up to 2 decimal places.
            self.assertAlmostEqual(moves[gesture] / n, 1/3, 2)

    def test_verify_move(self):
        pairs = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')]
        for pair in pairs:
            self.assertEqual(self.rps._verify_move(pair[0]), pair[1])

        wrong_input = 'something'
        self.assertRaises(Exception, self.rps._verify_move, wrong_input)

if __name__ == '__main__':
    modes = ["test", "main"]
    switch = input("[test,main]: ")
    if switch == "test":
        unittest.main()
    else:
        rps = RPSGame()
        rps.play(rounds=3)


text:
module Graphics.Rendering.OpenGL.Raw.IBM.StaticData (
  -- * Enums
  gl_ALL_STATIC_DATA_IBM,
  gl_STATIC_VERTEX_ARRAY_IBM,
  -- * Functions
  glFlushStaticDataIBM
) where

import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions


text:
<?php
/**
 * Created by PhpStorm.
 * User: Jerome Roethlisberger
 * Date: 11.09.14
 * Time: 11:58
 */

namespace Model;
/**
 * Class PostModel
 *
 * Handling the database SQL Requests specific for the te data regarding the guest book posts.
 * As the Strict convention between controller and model, the model is responsible for
 * acquiring data from different tables in order to satisfy the controllers needs.
 * @package Model
 */
class PostModel extends Model
{
	/**
	 * The Constructor
 	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Get one distinct record of a table by its id
	 * @param $id
	 * @return mixed
	 */
	public function getOne($id)
	{
		$db = $this->getDb();
		$sql = 'SELECT
					p.id,
					p.subject,
					p.message,
					p.created,
					p.modified,
					p.published,
					p.author_id,
					u.name 	AS author_name,
					u.email AS author_email
				FROM post AS p
				LEFT JOIN user AS u ON p.author_id = u.id
				WHERE p.id = {id};';
		$fields = array(
			'id' => $id
		);
		$sql = $db->prepare($sql, $fields);
		$result = $db->query($sql);
		if (isset($result[0])) {
			return $result[0];
		} else {
			return null;
		}
	}

	/**
	 * gets all records of a table
	 * @return mixed
	 */
	public function getAll()
	{
		$db = $this->getDb();
		$sql =
		$sql = 'SELECT
					p.id,
					p.subject,
					p.message,
					p.published,
					p.created,
					p.modified,
					p.author_id,
					u.name as author_name,
					u.email as author_email
				FROM post AS p
				LEFT JOIN user AS u ON p.author_id = u.id
				ORDER BY p.id DESC;';
		$result = $db->query($sql);
		foreach ($result as $id => $post) {
			if (strlen($post['message']) > 60) {
				$result[$id]['message'] = substr($post['message'], 0, 60) . '\n ... Read more';
			}

		}
		return $result;
	}

	/**
	 * Gets the user alias author of a post
	 * @param int $id The author id
	 * @return null|array the author
	 */
	public function getAuthor($id)
	{
		$db = $this->getDb();
		$fields = array(
			'id' => $id
		);
		$sql = 'SELECT id, name, email
				FROM user
				WHERE id = {id};';
		$sql = $db->prepare($sql, $fields, false);
		$result = $db->query($sql);
		if (isset($result[0])) {
			return $result[0];
		} else {
			return null;
		}
	}

	/**
	 * Inserts a new guest book post
	 *
	 * @param array $fields
	 * @return bool|int|mixed
	 */
	public function create($fields)
	{
		$db = $this->getDb();
		$sql = 'INSERT INTO post (author_id, subject, message, published, created)
				VALUES ({author_id}, {subject}, {message}, {published}, {created});';
		$sql = $db->prepare($sql, $fields, true);
		return $db->exec($sql);
	}

	/**
	 * Updates a guest book post
	 * @param array $fields
	 * @return bool|int|mixed
	 */
	public function update($fields)
	{
		$db = $this->getDb();
		$sql = 'UPDATE post SET
				subject = {subject},
				message = {message},
				published = {published},
				modified = {modified}
				WHERE id = {id};';
		$sql = $db->prepare($sql, $fields);
		return $db->exec($sql);
	}

	/**
	 * Deletes a guest book post
	 * @param int $id
	 * @return bool|int|mixed
	 */
	public function delete($id)
	{
		//
		$db = $this->getDb();
		$sql = 'DELETE FROM post WHERE id = {id};';
		$fields = array(
			'id' => $id
		);
		$sql = $db->prepare($sql, $fields);
		return $db->exec($sql);
	}

	public function validate($data)
	{
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<SAXEvents>
  <startDocument/>
  <notation>
    <name>a</name>
    <systemID>a</systemID>
  </notation>
  <fatalError>unexpected character</fatalError>
  <endDocument/>
</SAXEvents>