text:
import datetime
from twisted.trial import unittest
from twisted.internet import task
from twisted.internet.interfaces import IReactorTime
from zope.interface import implements

from txtorcon.addrmap import AddrMap
from txtorcon.interface import IAddrListener

class AddrMapTests(unittest.TestCase):
    implements(IAddrListener)

    fmt = '%Y-%m-%d %H:%M:%S'

    def test_parse(self):
        """
        Make sure it's parsing things properly.
        """

        now = datetime.datetime.now() + datetime.timedelta(seconds=10)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
        # we need to not-barf on extra args as per control-spec.txt
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s" FOO=bar BAR=baz' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
        am = AddrMap()
        am.update(line)
        addr = am.find('www.example.com')

        self.assertTrue(addr.ip == '72.30.2.43' or addr.ip.exploded == '72.30.2.43')
        # maybe not the most robust, should convert to
        # seconds-since-epoch instead? the net result of the parsing
        # is we've rounded to seconds...
        self.assertEqual(addr.expires.ctime(), nowutc.ctime())

        line = 'www.example.com 72.30.2.43 "%s" "%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
        am.update(line)
        self.assertEqual(addr.expires.ctime(), nowutc.ctime())

        # this will have resulted in an expiry call, which we need to
        # cancel to keep the reactor clean. for consistency, we use
        # the IReactorTime interface from AddrMap
        am.scheduler.getDelayedCalls()[0].cancel()

    def test_expires(self):
        """
        Test simply expiry case
        """

        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        now = datetime.datetime.now() + datetime.timedelta(seconds=10)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))

        am.update(line)

        self.assertTrue('www.example.com' in am.addr)
        # advance time past when the expiry should have occurred
        clock.advance(10)
        self.assertTrue('www.example.com' not in am.addr)

    def test_expires_never(self):
        """
        Test a NEVER expires line, as in what we'd get a startup for a
        configured address-mapping.
        """

        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        line = 'www.example.com 72.30.2.43 "NEVER"'
        am.update(line)

        self.assertTrue('www.example.com' in am.addr)
        self.assertEqual(len(clock.getDelayedCalls()), 0)

    def test_expires_old(self):
        """
        Test something that expires before "now"
        """

        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        now = datetime.datetime.now() + datetime.timedelta(seconds=-10)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=-10)
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))

        am.update(line)
        self.assertTrue('www.example.com' in am.addr)
        # arguably we shouldn't even have put this in the map maybe,
        # but the reactor needs to iterate before our expiry callback
        # gets called (right away) which is simulated by the
        # clock.advance call
        clock.advance(0)
        self.assertTrue('www.example.com' not in am.addr)

    def test_expires_with_update(self):
        """
        This test updates the expiry time and checks that we properly
        delay our expiry callback.
        """
        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        # now do an actual update to an existing Addr entry.
        now = datetime.datetime.now() + datetime.timedelta(seconds=10)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
        am.update(line)
        self.assertTrue(am.find('www.example.com'))

        # the update
        now = datetime.datetime.now() + datetime.timedelta(seconds=20)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=20)
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))
        am.update(line)
        self.assertTrue('www.example.com' in am.addr)

        # advance time by the old expiry value and we should still
        # find the entry
        clock.advance(10)
        self.assertTrue('www.example.com' in am.addr)

        # ...but advance past the new expiry (another 10 seconds) and
        # it should vanish
        clock.advance(10)
        self.assertTrue('www.example.com' not in am.addr)

    def test_8596_cached_1(self):
        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        line = 'example.com 192.0.2.1 NEVER CACHED="YES"'
        am.update(line)

        self.assertTrue('example.com' in am.addr)
        self.assertEqual(len(clock.getDelayedCalls()), 0)

    def test_8596_cached_2(self):
        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        line = 'example.com 192.0.43.10 "2013-04-03 22:29:11" EXPIRES="2013-04-03 20:29:11" CACHED="NO"'
        am.update(line)

        self.assertTrue('example.com' in am.addr)
        self.assertEqual(len(clock.getDelayedCalls()), 1)

    def test_8596_cached_3(self):
        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)

        line = 'example.invalid <error> "2013-04-03 08:28:52" error=yes EXPIRES="2013-04-03 06:28:52" CACHE="NO"'
        am.update(line)

        self.assertTrue('example.invalid' not in am.addr)
        self.assertEqual(len(clock.getDelayedCalls()), 0)

    def addrmap_expired(self, name):
        self.expires.append(name)

    def addrmap_added(self, addr):
        self.addrmap.append(addr)

    def test_double_add_listener(self):
        am = AddrMap()
        am.add_listener(self)
        am.add_listener(self)

        self.assertEqual(1, len(am.listeners))

    def test_listeners(self):
        self.expires = []
        self.addrmap = []

        clock = task.Clock()
        am = AddrMap()
        am.scheduler = IReactorTime(clock)
        am.add_listener(self)

        now = datetime.datetime.now() + datetime.timedelta(seconds=10)
        nowutc = datetime.datetime.utcnow() + datetime.timedelta(seconds=10)
        line = 'www.example.com 72.30.2.43 "%s" EXPIRES="%s"' % (now.strftime(self.fmt), nowutc.strftime(self.fmt))

        am.update(line)

        # see if our listener got an update
        a = am.find('www.example.com')
        self.assertEqual(self.addrmap, [a])

        # advance time past when the expiry should have occurred
        clock.advance(10)

        # check that our listener got an expires event
        self.assertEqual(self.expires, ['www.example.com'])


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ProtectedPKIMessageBuilder (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.cert.cmp

Class ProtectedPKIMessageBuilder

java.lang.Object

org.bouncycastle.cert.cmp.ProtectedPKIMessageBuilder

public class ProtectedPKIMessageBuilder
extends java.lang.Object

Builder for creating a protected PKI message.

Constructor Summary

Constructors

Constructor and Description

ProtectedPKIMessageBuilder(org.bouncycastle.asn1.x509.GeneralName sender,
                          org.bouncycastle.asn1.x509.GeneralName recipient)

Commence a message with the header version CMP_2000.

ProtectedPKIMessageBuilder(int pvno,
                          org.bouncycastle.asn1.x509.GeneralName sender,
                          org.bouncycastle.asn1.x509.GeneralName recipient)

Commence a message with a specific header type.

Method Summary

Methods

Modifier and Type
Method and Description

ProtectedPKIMessageBuilder
addCMPCertificate(X509CertificateHolder extraCert)

Add an "extra certificate" to the message.

ProtectedPKIMessageBuilder
addGeneralInfo(org.bouncycastle.asn1.cmp.InfoTypeAndValue genInfo)

Add a generalInfo data record to the header of the new message.

ProtectedPKIMessage
build(ContentSigner signer)

Build a protected PKI message which has MAC based integrity protection.

ProtectedPKIMessage
build(MacCalculator macCalculator)

Build a protected PKI message which has MAC based integrity protection.

ProtectedPKIMessageBuilder
setBody(org.bouncycastle.asn1.cmp.PKIBody body)

Set the body for the new message

ProtectedPKIMessageBuilder
setFreeText(org.bouncycastle.asn1.cmp.PKIFreeText freeText)

Include a human-readable message in the new message.

ProtectedPKIMessageBuilder
setMessageTime(java.util.Date time)

Set the creation time for the new message.

ProtectedPKIMessageBuilder
setRecipKID(byte[] kid)

Set the recipient key identifier for the key to be used to verify the new message.

ProtectedPKIMessageBuilder
setRecipNonce(byte[] nonce)

Set the recipient nonce field on the new message.

ProtectedPKIMessageBuilder
setSenderKID(byte[] kid)

Set the sender key identifier for the key used to protect the new message.

ProtectedPKIMessageBuilder
setSenderNonce(byte[] nonce)

Set the sender nonce field on the new message.

ProtectedPKIMessageBuilder
setTransactionID(byte[] tid)

Set the identifier for the transaction the new message will belong to.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ProtectedPKIMessageBuilder

public ProtectedPKIMessageBuilder(org.bouncycastle.asn1.x509.GeneralName sender,
                          org.bouncycastle.asn1.x509.GeneralName recipient)

Commence a message with the header version CMP_2000.

Parameters:

sender - message sender.

recipient - intended recipient.

ProtectedPKIMessageBuilder

public ProtectedPKIMessageBuilder(int pvno,
                          org.bouncycastle.asn1.x509.GeneralName sender,
                          org.bouncycastle.asn1.x509.GeneralName recipient)

Commence a message with a specific header type.

Parameters:

pvno - the version CMP_1999 or CMP_2000.

sender - message sender.

recipient - intended recipient.

Method Detail

setTransactionID

public ProtectedPKIMessageBuilder setTransactionID(byte[] tid)

Set the identifier for the transaction the new message will belong to.

Parameters:

tid - the transaction ID.

Returns:

the current builder instance.

setFreeText

public ProtectedPKIMessageBuilder setFreeText(org.bouncycastle.asn1.cmp.PKIFreeText freeText)

Include a human-readable message in the new message.

Parameters:

freeText - the contents of the human readable message,

Returns:

the current builder instance.

addGeneralInfo

public ProtectedPKIMessageBuilder addGeneralInfo(org.bouncycastle.asn1.cmp.InfoTypeAndValue genInfo)

Add a generalInfo data record to the header of the new message.

Parameters:

genInfo - the generalInfo data to be added.

Returns:

the current builder instance.

setMessageTime

public ProtectedPKIMessageBuilder setMessageTime(java.util.Date time)

Set the creation time for the new message.

Parameters:

time - the message creation time.

Returns:

the current builder instance.

setRecipKID

public ProtectedPKIMessageBuilder setRecipKID(byte[] kid)

Set the recipient key identifier for the key to be used to verify the new message.

Parameters:

kid - a key identifier.

Returns:

the current builder instance.

setRecipNonce

public ProtectedPKIMessageBuilder setRecipNonce(byte[] nonce)

Set the recipient nonce field on the new message.

Parameters:

nonce - a NONCE, typically copied from the sender nonce of the previous message.

Returns:

the current builder instance.

setSenderKID

public ProtectedPKIMessageBuilder setSenderKID(byte[] kid)

Set the sender key identifier for the key used to protect the new message.

Parameters:

kid - a key identifier.

Returns:

the current builder instance.

setSenderNonce

public ProtectedPKIMessageBuilder setSenderNonce(byte[] nonce)

Set the sender nonce field on the new message.

Parameters:

nonce - a NONCE, typically 128 bits of random data.

Returns:

the current builder instance.

setBody

public ProtectedPKIMessageBuilder setBody(org.bouncycastle.asn1.cmp.PKIBody body)

Set the body for the new message

Parameters:

body - the message body.

Returns:

the current builder instance.

addCMPCertificate

public ProtectedPKIMessageBuilder addCMPCertificate(X509CertificateHolder extraCert)

Add an "extra certificate" to the message.

Parameters:

extraCert - the extra certificate to add.

Returns:

the current builder instance.

build

public ProtectedPKIMessage build(MacCalculator macCalculator)
                          throws CMPException

Build a protected PKI message which has MAC based integrity protection.

Parameters:

macCalculator - MAC calculator.

Returns:

the resulting protected PKI message.

Throws:

CMPException - if the protection MAC cannot be calculated.

build

public ProtectedPKIMessage build(ContentSigner signer)
                          throws CMPException

Build a protected PKI message which has MAC based integrity protection.

Parameters:

signer - the ContentSigner to be used to calculate the signature.

Returns:

the resulting protected PKI message.

Throws:

CMPException - if the protection signature cannot be calculated.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
DOWNLOAD_PREFIX = "/tmp/apks/"
from app import App
import urllib
from multiprocessing.pool import Pool
import os
__author__ = 'hqdvista'
def download_applist(apps):
    """
    :type apps: list(App)
    """
    pool = Pool(processes=10)
    pool.map(download_single_app, apps)
    pool.close()

def download_single_app(app):
    """
    :type app: App
    """
    pth = DOWNLOAD_PREFIX + os.sep + app.vendor
    if not os.path.exists(pth):
        os.makedirs(pth)
    filepath = pth + os.sep + app.packageName + ".apk"
    urllib.urlretrieve(app.download_url, filepath)
    print '''%s downloaded.''' % app.packageName
    return filepath


text:
/** @file common.h
 *
 * @brief Defines common macros and structures used by the Intel Cilk Plus
 * runtime.
 *
 *  @ingroup common
 */

/** @defgroup common Common Definitions
 *  Macro, structure, and class definitions used elsewhere in the runtime.
 *  @{
 */

#ifndef INCLUDED_CILK_COMMON
#define INCLUDED_CILK_COMMON

#ifdef __cplusplus
/** Namespace for all Cilk definitions that can be included in user code.
 */
namespace cilk {

    /** Namespace for definitions that are primarily intended for use
     *  in other Cilk definitions.
     */
    namespace internal {}
}
#endif

/** Cilk library version = 1.01
 */
#define CILK_LIBRARY_VERSION 102

#ifdef __cplusplus
#   include <cassert>
#else
#   include <assert.h>
#endif

/**
 * Prefix standard library function and type names with __STDNS in order to
 * get correct lookup in both C and C++.
 */
#ifdef __cplusplus
#   define __STDNS std::
#else
#   define __STDNS
#endif

/**
 * @def CILK_EXPORT
 * Define export of runtime functions from shared library.
 * Should be exported only from cilkrts*.dll/cilkrts*.so
 * @def CILK_EXPORT_DATA
 * Define export of runtime data from shared library.
 */
#ifdef _WIN32
#   ifdef IN_CILK_RUNTIME
#       define CILK_EXPORT      __declspec(dllexport)
#       define CILK_EXPORT_DATA __declspec(dllexport)
#   else
#       define CILK_EXPORT      __declspec(dllimport)
#       define CILK_EXPORT_DATA __declspec(dllimport)
#   endif  /* IN_CILK_RUNTIME */
#elif defined(__CYGWIN__) || defined(__APPLE__) || defined(_DARWIN_C_SOURCE)
#   define CILK_EXPORT      /* nothing */
#   define CILK_EXPORT_DATA /* nothing */
#else /* Unix/gcc */
#   if defined(IN_CILK_RUNTIME) && defined(HAVE_ATTRIBUTE_VISIBILITY)
#       define CILK_EXPORT      __attribute__((visibility("protected")))
#       define CILK_EXPORT_DATA __attribute__((visibility("protected")))
#   else
#       define CILK_EXPORT      /* nothing */
#       define CILK_EXPORT_DATA /* nothing */
#   endif  /* IN_CILK_RUNTIME */
#endif /* Unix/gcc */

/**
 * @def __CILKRTS_BEGIN_EXTERN_C
 * Macro to denote the start of a section in which all names have "C" linkage.
 * That is, none of the names are to be mangled.
 * @see __CILKRTS_END_EXTERN_C
 * @see __CILKRTS_EXTERN_C
 *
 * @def __CILKRTS_END_EXTERN_C
 * Macro to denote the end of a section in which all names have "C" linkage.
 * That is, none of the names are to be mangled.
 * @see __CILKRTS_BEGIN_EXTERN_C
 * @see __CILKRTS_EXTERN_C
 *
 * @def __CILKRTS_EXTERN_C
 * Macro to prefix a single definition which has "C" linkage.
 * That is, the defined name is not to be mangled.
 * @see __CILKRTS_BEGIN_EXTERN_C
 * @see __CILKRTS_END_EXTERN_C
 */
#ifdef __cplusplus
#   define __CILKRTS_BEGIN_EXTERN_C     extern "C" {
#   define __CILKRTS_END_EXTERN_C       }
#   define __CILKRTS_EXTERN_C           extern "C"
#else
#   define __CILKRTS_BEGIN_EXTERN_C
#   define __CILKRTS_END_EXTERN_C
#   define __CILKRTS_EXTERN_C
#endif

/**
 * OS-independent macro to specify a function which is known to not throw
 * an exception.
 */
#ifdef __cplusplus
#   ifdef _WIN32
#       define __CILKRTS_NOTHROW __declspec(nothrow)
#   else /* Unix/gcc */
#       define __CILKRTS_NOTHROW __attribute__((nothrow))
#   endif /* Unix/gcc */
#else
#   define __CILKRTS_NOTHROW /* nothing */
#endif /* __cplusplus */

/** Cache alignment. (Good enough for most architectures.)
 */
#define __CILKRTS_CACHE_LINE__ 64

/**
 * Macro to specify alignment of a data member in a structure.
 * Because of the way that gcc's alignment attribute is defined, @a n must
 * be a numeric literal, not just a compile-time constant expression.
 */
#ifdef _WIN32
#   define CILK_ALIGNAS(n) __declspec(align(n))
#else /* Unix/gcc */
#   define CILK_ALIGNAS(n) __attribute__((__aligned__(n)))
#endif

/**
 * Macro to specify cache-line alignment of a data member in a structure.
 */
#define __CILKRTS_CACHE_ALIGN CILK_ALIGNAS(__CILKRTS_CACHE_LINE__)

/**
 * Macro to specify a class as being at least as strictly aligned as some
 * type on Windows. gcc does not provide a way of doing this, so on Unix,
 * this just specifies the largest natural type alignment. Put the macro
 * between the `class` keyword and the class name:
 *
 *      class CILK_ALIGNAS_TYPE(foo) bar { ... };
 */
#ifdef _WIN32
#   define CILK_ALIGNAS_TYPE(t) __declspec(align(__alignof(t)))
#else /* Unix/gcc */
#   define CILK_ALIGNAS_TYPE(t) __attribute__((__aligned__))
#endif

/**
 * @def CILK_API(RET_TYPE)
 * A function called explicitly by the programmer.
 * @def CILK_ABI(RET_TYPE)
 * A function called by compiler-generated code.
 * @def CILK_ABI_THROWS(RET_TYPE)
 * An ABI function that may throw an exception
 *
 * Even when these are the same definitions, they should be separate macros so
 * that they can be easily found in the code.
 */

#ifdef _WIN32
#   define CILK_API(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW __cdecl
#   define CILK_ABI(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW __cdecl
#   define CILK_ABI_THROWS(RET_TYPE) CILK_EXPORT RET_TYPE __cdecl
#else
#   define CILK_API(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW
#   define CILK_ABI(RET_TYPE) CILK_EXPORT RET_TYPE __CILKRTS_NOTHROW
#   define CILK_ABI_THROWS(RET_TYPE) CILK_EXPORT RET_TYPE
#endif

/**
 * __CILKRTS_ASSERT should be defined for debugging only, otherwise it
 * interferes with vectorization.  Since NDEBUG is not reliable (it must be
 * set by the user), we must use a platform-specific detection of debug mode.
 */
#if defined(_WIN32) && defined(_DEBUG)
    /* Windows debug */
#   define __CILKRTS_ASSERT(e) assert(e)
#elif (! defined(_WIN32)) && ! defined(__OPTIMIZE__)
    /* Unix non-optimized */
#   define __CILKRTS_ASSERT(e) assert(e)
#elif defined __cplusplus
    /* C++ non-debug */
#   define __CILKRTS_ASSERT(e) static_cast<void>(0)
#else
    /* C non-debug */
#   define __CILKRTS_ASSERT(e) ((void) 0)
#endif

/**
 * OS-independent macro to specify a function that should be inlined
 */
#ifdef __cpluspus
    // C++
#   define __CILKRTS_INLINE inline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    // C99
#   define __CILKRTS_INLINE static inline
#elif defined(_MSC_VER)
    // C89 on Windows
#   define __CILKRTS_INLINE __inline
#else
    // C89 on GCC-compatible systems
#   define __CILKRTS_INLINE extern __inline__
#endif

/**
 * Functions marked as CILK_EXPORT_AND_INLINE have both
 * inline versions defined in the Cilk API, as well as
 * non-inlined versions that are exported (for
 * compatibility with previous versions that did not
 * inline the functions).
 */
#ifdef COMPILING_CILK_API_FUNCTIONS
#   define CILK_EXPORT_AND_INLINE  CILK_EXPORT
#else
#   define CILK_EXPORT_AND_INLINE  __CILKRTS_INLINE
#endif

/**
 * Try to determine if compiler supports rvalue references.
 */
#if defined(__cplusplus) && !defined(__CILKRTS_RVALUE_REFERENCES)
#   if __cplusplus >= 201103L // C++11
#       define __CILKRTS_RVALUE_REFERENCES 1
#   elif defined(__GXX_EXPERIMENTAL_CXX0X__)
#       define __CILKRTS_RVALUE_REFERENCES 1
#   elif __cplusplus >= 199711L && __cplusplus < 201103L
        // Compiler recognizes a language version prior to C++11
#   elif __INTEL_COMPILER == 1200 && defined(__STDC_HOSTED__)
        // Intel compiler version 12.0
        // __cplusplus has a non-standard definition.  In the absence of a
        // proper definition, look for the C++0x macro, __STDC_HOSTED__.
#       define __CILKRTS_RVALUE_REFERENCES 1
#   elif __INTEL_COMPILER > 1200 && defined(CHAR16T)
        // Intel compiler version >= 12.1
        // __cplusplus has a non-standard definition.  In the absence of a
        // proper definition, look for the Intel macro, CHAR16T
#       define __CILKRTS_RVALUE_REFERENCES 1
#   endif
#endif

/*
 * Include stdint.h to define the standard integer types.
 *
 * Unfortunately Microsoft doesn't provide stdint.h until Visual Studio 2010,
 * so use our own definitions until those are available
 */

#if ! defined(_MSC_VER) || (_MSC_VER >= 1600)
#   include <stdint.h>
#else
#   ifndef __MS_STDINT_TYPES_DEFINED__
#       define __MS_STDINT_TYPES_DEFINED__
        typedef signed char int8_t;
        typedef short int16_t;
        typedef int int32_t;
        typedef __int64 int64_t;

        typedef unsigned char uint8_t;
        typedef unsigned short uint16_t;
        typedef unsigned int uint32_t;
        typedef unsigned __int64 uint64_t;
#   endif  /* __MS_STDINT_TYPES_DEFINED__ */
#endif  /* ! defined(_MSC_VER) || (_MSC_VER >= 1600) */

/**
 * @brief Application Binary Interface version of the Cilk runtime library.
 *
 * The ABI version is determined by the compiler used.  An object file
 * compiled with a higher ABI version is not compatible with a library that is
 * compiled with a lower ABI version.  An object file compiled with a lower
 * ABI version, however, can be used with a library compiled with a higher ABI
 * version unless otherwise stated.
 */
#ifndef __CILKRTS_ABI_VERSION
#   ifdef IN_CILK_RUNTIME
#       define __CILKRTS_ABI_VERSION 1
#   elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER <= 1200)
        // Intel compilers prior to version 12.1 support only ABI 0
#       define __CILKRTS_ABI_VERSION 0
#   else
        // Non-Intel compiler or Intel compiler after version 12.0.
#       define __CILKRTS_ABI_VERSION 1
#   endif
#endif

// These structs are exported because the inlining of
// the internal version of API methods require a worker
// structure as parameter.
__CILKRTS_BEGIN_EXTERN_C
    /// Worker struct, exported for inlined API methods
    /// @ingroup api
    struct __cilkrts_worker;

    /// Worker struct, exported for inlined API methods
    /// @ingroup api
    typedef struct __cilkrts_worker __cilkrts_worker;

    /// Worker struct pointer, exported for inlined API methods
    /// @ingroup api
    typedef struct __cilkrts_worker *__cilkrts_worker_ptr;

    /// Fetch the worker out of TLS.
    CILK_ABI(__cilkrts_worker_ptr) __cilkrts_get_tls_worker(void);

    /// void *, defined to work around complaints from the compiler
    /// about using __declspec(nothrow) after the "void *" return type
    typedef void * __cilkrts_void_ptr;

__CILKRTS_END_EXTERN_C

#if __CILKRTS_ABI_VERSION >= 1
// Pedigree API is available only for compilers that use ABI version >= 1.

/** Pedigree information kept in the worker and stack frame.
 *  @ingroup api
 */
typedef struct __cilkrts_pedigree
{
    /** Rank at start of spawn helper. Saved rank for spawning functions */
    uint64_t rank;

    /** Link to next in chain */
    const struct __cilkrts_pedigree *parent;
} __cilkrts_pedigree;

#endif // __CILKRTS_ABI_VERSION >= 1

/// @}

#endif /* INCLUDED_CILK_COMMON */


text:
require 'savon'
require 'savon/mock/spec_helper'

shared_examples_for 'tnt calculator' do

  let(:calculator) { subject.class.new }

  # include the helper module
  include Savon::SpecHelper

  # set Savon in and out of mock mode
  before(:all) { savon.mock!   }
  after(:all)  { savon.unmock! }

  before do
    address = FactoryGirl.build(:address, zipcode: '17209420')
    # use authentication token for save the customer's CGC
    user = FactoryGirl.build(:user)
    user.authentication_token = '12345678900'
    @variant = FactoryGirl.build(:variant, weight: 1, height: 5, width: 15, depth: 20)
    @order = FactoryGirl.build(:order_with_shipments, ship_address: address, user: user)

    line_item = FactoryGirl.build(:line_item, variant: @variant, price: 100, order: @order)
    @order.line_items << line_item

    # stock location
    @stock_location = FactoryGirl.build(:stock_location, zipcode: '08465312')

    # shipment
    @shipment = FactoryGirl.build(:shipment, order: @order, stock_location: @stock_location)
    @shipment.inventory_units << FactoryGirl.build(:inventory_unit, variant: @variant, order: @order,
                                                   line_item: line_item, shipment: @shipment)

    # package
    @package = @shipment.to_package
    @package.add @shipment.inventory_units.first

    @params = {in0: {login: 'teste@email.com',
                     senha: 'password',
                     nr_identif_cliente_rem: '1234678900000',
                     nr_inscricao_estadual_remetente: '344028650118',
                     nr_identif_cliente_dest: '12345678900',
                     tp_situacao_tributaria_remetente: 'CO',
                     tp_pessoa_remetente: 'J',
                     tp_pessoa_destinatario: 'F',
                     tp_situacao_tributaria_destinatario: 'NC',
                     cep_origem: '08465312',
                     cep_destino: '17209420',
                     vl_mercadoria: '100.0',
                     ps_real: '1.0',
                     tp_servico: calculator.shipping_method,
                     tp_frete: 'C',
                     cd_divisao_cliente: 1}}

    # set the value of tnt config
    Spree::TntMercurioConfig.email          = @params[:in0][:login]
    Spree::TntMercurioConfig.password       = @params[:in0][:senha]
    Spree::TntMercurioConfig.division       = 1
    Spree::TntMercurioConfig.cgc            = @params[:in0][:nr_identif_cliente_rem]
    Spree::TntMercurioConfig.state_registry = @params[:in0][:nr_inscricao_estadual_remetente]
    Spree::TntMercurioConfig.customer_field = 'authentication_token'
  end

  after do
    # set default for preferences
    Spree::TntMercurioConfig.email          = nil
    Spree::TntMercurioConfig.password       = nil
    Spree::TntMercurioConfig.division       = nil
    Spree::TntMercurioConfig.cgc            = nil
    Spree::TntMercurioConfig.state_registry = nil
    Spree::TntMercurioConfig.type_cgc       = 'J'
    Spree::TntMercurioConfig.tax_situation  = 'CO'
    Spree::TntMercurioConfig.billet_type    = 'C'
    Spree::TntMercurioConfig.additional_value = 0
    Spree::TntMercurioConfig.additional_days  = 0
    Spree::TntMercurioConfig.customer_field   = ''
  end

  context 'compute_package' do

    it 'should calculate the price and delivery time' do

      fixture = File.read('spec/fixtures/calcula_frete/success_response.xml')

      savon.expects(:calcula_frete).with(message: @params).returns(fixture)
      response = calculator.compute_package(@package)

      expect(response[:cost]).to eq(69.29)
      expect(calculator.delivery_time).to eq(3)

    end

    it 'should possible add days to delivery time' do
      Spree::TntMercurioConfig.additional_days = 5

      fixture = File.read('spec/fixtures/calcula_frete/success_response.xml')

      savon.expects(:calcula_frete).with(message: @params).returns(fixture)
      calculator.compute_package(@package)

      expect(calculator.delivery_time).to eq(8)

      # set value default after test
      Spree::TntMercurioConfig.additional_days = 0
    end

    it 'should possible add some value to price' do
      Spree::TntMercurioConfig.additional_value = 10.0

      fixture = File.read('spec/fixtures/calcula_frete/success_response.xml')

      savon.expects(:calcula_frete).with(message: @params).returns(fixture)
      response = calculator.compute_package(@package)

      expect(response[:cost]).to eq(79.29)

      # set value default after test
      Spree::TntMercurioConfig.additional_value = 0
    end

  end

  context 'invalid data' do

    it 'should return false when the variant has nil/zero weight' do
      # set 0 to variant weight
      @variant.weight = 0

      fixture = File.read('spec/fixtures/calcula_frete/error_response.xml')

      savon.expects(:calcula_frete).with(message: @params).returns(fixture)
      response = calculator.compute_package(@package)

      expect(response).to eq Hash.new
    end

    it 'should return false if the credentials are invalid' do
      @params[:in0][:login] = ''
      @params[:in0][:senha] = ''
      @params[:in0][:nr_identif_cliente_rem] = ''
      @params[:in0][:nr_inscricao_estadual_remetente] = ''

      Spree::TntMercurioConfig.email = ''
      Spree::TntMercurioConfig.password = ''
      Spree::TntMercurioConfig.cgc = ''
      Spree::TntMercurioConfig.state_registry = ''

      fixture = File.read('spec/fixtures/calcula_frete/invalid_credentials.xml')

      savon.expects(:calcula_frete).with(message: @params).returns(fixture)

      response = calculator.compute_package(@package)

      expect(response).to eq Hash.new
    end
  end

  context 'using information of previuos order' do

    let(:previous_order) { create(:shipped_order) }
    let(:shipping_method) { create(:shipping_method, name: 'TNT') }
    let!(:shipping_calculator) { create(:calculator,
                                        calculable: shipping_method,
                                        type: "Spree::Calculator::Shipping::TntMercurio#{calculator.shipping_method}") }

    before do
      create(:shipping_rate, shipment: previous_order.shipments.first, cost: 15,
             delivery_time: 5, shipping_method: shipping_method, selected: 1)

      # New Order
      user = create(:user, authentication_token: '12345678900')
      @new_order = create(:order, line_items: previous_order.line_items,
                      ship_address: previous_order.ship_address, user: user)
      stock_location = create(:stock_location, zipcode: '08465312')
      shipment = create(:shipment, order: @new_order, stock_location: stock_location)
      @new_package = shipment.to_package

      @new_params = {in0: {login: 'teste@email.com',
                           senha: 'password',
                           nr_identif_cliente_rem: '1234678900000',
                           nr_inscricao_estadual_remetente: '344028650118',
                           nr_identif_cliente_dest: '12345678900',
                           tp_situacao_tributaria_remetente: 'CO',
                           tp_pessoa_remetente: 'J',
                           tp_pessoa_destinatario: 'F',
                           tp_situacao_tributaria_destinatario: 'NC',
                           cep_origem: '08465312',
                           cep_destino: @new_order.ship_address.zipcode,
                           vl_mercadoria: @new_order.total.to_s,
                           ps_real: @new_package.weight.to_s,
                           tp_servico: calculator.shipping_method,
                           tp_frete: 'C',
                           cd_divisao_cliente: 1}}
    end

    it 'should use information of previous orders when request to TNT fails' do
      fixture = File.read('spec/fixtures/calcula_frete/error_response.xml')
      savon.expects(:calcula_frete).with(message: @new_params).returns(fixture)
      response = calculator.compute_package(@new_package)

      expect(response[:cost]).to eq 15
      expect(response[:delivery_time]).to eq 5
    end

  end

end


text:
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_controller {

	public function index() {
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'required');

		if ($this->form_validation->run() === false) {

			$data = array(
	           'main_content' => 'login_form',
	        );
			$this->load->view('includes/template', $data);

		} else {

			$username = $this->input->post('username');
			$password = $this->input->post('password');
			$this->load->model('membership_model');
			$result = $this->membership_model->get_user($username, $password);

			if ($result === true) {

				redirect('members_section');

			} else {

				$data = array(
		           'main_content' => 'login_form',
		           'error_message' => 'Invalid Username and Passowrd'
		        );
				$this->load->view('includes/template', $data);

			}

		}

	}
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/baremetalsolution/v2/nfs_share.proto

namespace Google\Cloud\BareMetalSolution\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Message for requesting a list of NFS shares.
 *
 * Generated from protobuf message google.cloud.baremetalsolution.v2.ListNfsSharesRequest
 */
class ListNfsSharesRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. Parent value for ListNfsSharesRequest.
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $parent = '';
    /**
     * Requested page size. The server might return fewer items than requested.
     * If unspecified, server will pick an appropriate default.
     *
     * Generated from protobuf field int32 page_size = 2;
     */
    private $page_size = 0;
    /**
     * A token identifying a page of results from the server.
     *
     * Generated from protobuf field string page_token = 3;
     */
    private $page_token = '';
    /**
     * List filter.
     *
     * Generated from protobuf field string filter = 4;
     */
    private $filter = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $parent
     *           Required. Parent value for ListNfsSharesRequest.
     *     @type int $page_size
     *           Requested page size. The server might return fewer items than requested.
     *           If unspecified, server will pick an appropriate default.
     *     @type string $page_token
     *           A token identifying a page of results from the server.
     *     @type string $filter
     *           List filter.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Baremetalsolution\V2\NfsShare::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. Parent value for ListNfsSharesRequest.
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Required. Parent value for ListNfsSharesRequest.
     *
     * Generated from protobuf field string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setParent($var)
    {
        GPBUtil::checkString($var, True);
        $this->parent = $var;

        return $this;
    }

    /**
     * Requested page size. The server might return fewer items than requested.
     * If unspecified, server will pick an appropriate default.
     *
     * Generated from protobuf field int32 page_size = 2;
     * @return int
     */
    public function getPageSize()
    {
        return $this->page_size;
    }

    /**
     * Requested page size. The server might return fewer items than requested.
     * If unspecified, server will pick an appropriate default.
     *
     * Generated from protobuf field int32 page_size = 2;
     * @param int $var
     * @return $this
     */
    public function setPageSize($var)
    {
        GPBUtil::checkInt32($var);
        $this->page_size = $var;

        return $this;
    }

    /**
     * A token identifying a page of results from the server.
     *
     * Generated from protobuf field string page_token = 3;
     * @return string
     */
    public function getPageToken()
    {
        return $this->page_token;
    }

    /**
     * A token identifying a page of results from the server.
     *
     * Generated from protobuf field string page_token = 3;
     * @param string $var
     * @return $this
     */
    public function setPageToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->page_token = $var;

        return $this;
    }

    /**
     * List filter.
     *
     * Generated from protobuf field string filter = 4;
     * @return string
     */
    public function getFilter()
    {
        return $this->filter;
    }

    /**
     * List filter.
     *
     * Generated from protobuf field string filter = 4;
     * @param string $var
     * @return $this
     */
    public function setFilter($var)
    {
        GPBUtil::checkString($var, True);
        $this->filter = $var;

        return $this;
    }

}


text:
package io.vertigo.workflow.data;

import java.util.List;

import io.vertigo.core.definition.Definition;
import io.vertigo.core.definition.DefinitionSpace;
import io.vertigo.core.definition.SimpleDefinitionProvider;
import io.vertigo.dynamo.domain.metamodel.DataType;
import io.vertigo.dynamo.domain.metamodel.Domain;
import io.vertigo.dynamo.domain.metamodel.DtDefinition;
import io.vertigo.util.ListBuilder;

/**
 * Provides the definitions for the DummyDtObject used in unit tests .
 * @author xdurand
 */
public class MyDummyDtObjectProvider implements SimpleDefinitionProvider {

	@Override
	public List<Definition> provideDefinitions(final DefinitionSpace definitionSpace) {
		final Domain domainDummyId = Domain.builder("DO_X_DUMMY_ID", DataType.Long).build();
		final Domain domainDummyCode = Domain.builder("DO_X_DUMMY_CODE", DataType.String).build();
		final Domain domainDummyLabel = Domain.builder("DO_X_DUMMY_LABEL", DataType.String).build();

		final DtDefinition wfDummyObjectDtDefinition = DtDefinition.builder("DT_MY_DUMMY_DT_OBJECT")
				.addIdField("ID", "id", domainDummyId)
				.addDataField("ENTITY", "entity", domainDummyCode, true, true)
				.addDataField("DIVISION", "division", domainDummyCode, true, true)
				.addDataField("NOM", "nom", domainDummyLabel, true, true)
				.build();

		return new ListBuilder<Definition>()
				.add(domainDummyId)
				.add(domainDummyCode)
				.add(domainDummyLabel)
				.add(wfDummyObjectDtDefinition)
				.build();
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diplodina linariae Gutner

### Remarks
null


text:
FROM metocean/aroha
MAINTAINER Greg Chalmers <g.chalmers@metocean.co.nz>

ADD . /install/
RUN /install/install.sh
CMD ["/sbin/initsh"]


text:
'use strict';

/**
 * Module Dependencies
 */

var User          = require('../models/User');
var async         = require('async');
var crypto        = require('crypto');
var config        = require('../config/config');
var passport      = require('passport');
var nodemailer    = require('nodemailer');
var LoginAttempt  = require('../models/LoginAttempt');

/**
 * User Controller
 */

module.exports.controller = function (app) {

/**
 * GET /login
 * Render login page
 */

  app.get('/login', function (req, res) {
    // Check if user is already logged in
    if (req.user) {
      req.flash('info', { msg: 'You are already logged in!' });
      return res.redirect('/api');
    }
    // Turn off login form if too many attempts
    var tooManyAttempts = req.session.tooManyAttempts || false;
    req.session.tooManyAttempts = null;
    // Render Login form
    res.render('account/login', {
      tooManyAttempts: tooManyAttempts,
      url: req.url
    });
  });

/**
 * POST /login
 * Log the user in
 */

  app.post('/login', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the data
     */

    workflow.on('validate', function () {

      // Validate the form fields
      req.assert('email', 'Your email cannot be empty.').notEmpty();
      req.assert('email', 'Your email is not valid').isEmail();
      req.assert('password', 'Your password cannot be blank').notEmpty();
      req.assert('password', 'Your password must be at least 4 characters long.').len(4);

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('/login');
      }

      // next step
      workflow.emit('abuseFilter');
    });

    /**
     * Step 2: Prevent brute force login hacking
     */

    workflow.on('abuseFilter', function () {

      var getIpCount = function (done) {
        var conditions = { ip: req.ip };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var getIpUserCount = function (done) {
        var conditions = { ip: req.ip, user: req.body.email.toLowerCase() };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var asyncFinally = function (err, results) {
        if (err) {
          return workflow.emit('exception', err);
        }

        if (results.ip >= config.loginAttempts.forIp || results.ipUser >= config.loginAttempts.forUser) {
          req.flash('error', { msg: 'You\'ve reached the maximum number of login attempts. Please try again later or reset your password.' });
          req.session.tooManyAttempts = true;
          return res.redirect('/login');
        }
        else {
          workflow.emit('authenticate');
        }

      };

      async.parallel({ ip: getIpCount, ipUser: getIpUserCount }, asyncFinally);
    });

    /**
     * Step 3: Authenticate the user
     */

    workflow.on('authenticate', function () {

      // Authenticate the user
      passport.authenticate('local', function (err, user, info) {
        if (err) {
          req.flash('error', { msg: err.message });
          return res.redirect('back');
        }

        if (!user) {

          // Update abuse count
          var fieldsToSet = { ip: req.ip, user: req.body.email };
          LoginAttempt.create(fieldsToSet, function (err, doc) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            } else {
              // User Not Found (Return)
              req.flash('error', { msg: info.message });
              return res.redirect('/login');
            }
          });

        } else {

          // update the user's record with login timestamp
          user.activity.last_logon = Date.now();
          user.save(function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            }
          });

          // Log user in
          req.logIn(user, function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            }

            // Send user on their merry way
            if (req.session.attemptedURL) {
              var redirectURL = req.session.attemptedURL;
              delete req.session.attemptedURL;
              res.redirect(redirectURL);
            } else {
              res.redirect('/api');
            }

          });

        }

      })(req, res, next);

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

/**
 * GET /logout
 * Log the user out
 */

  app.get('/logout', function (req, res) {
    // Augment Logout to handle enhanced security
    delete req.session.passport.secondFactor;
    req.logout();
    res.redirect('/');
  });

  /**
   * GET /verify/:id/:token
   * Verify the user after signup
   */

  app.get('/verify/:id/:token', function (req, res) {

    // Create a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the user and token
     */

    workflow.on('validate', function () {

      // Get the user using their ID and token
      User.findOne({ _id: req.params.id, verifyToken: req.params.token }, function (err, user) {
        if (err) {
          req.flash('error', { msg: err.message });
          req.flash('warning', { msg: 'Your account verification is invalid or has expired.' });
          return res.redirect('/');
        }

        if (!user) {
          req.flash('warning', { msg: 'Your password reset request is invalid or has expired.' });
          return res.redirect('/');
        } else {

          // Let's verify the user!
          user.verified = true;
          user.verifyToken = undefined;
          user.activity.last_logon = Date.now();

          // update the user record
          user.save(function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            }

            // next step
            workflow.emit('sendWelcomeEmail', user);
          });
        }
      });
    });

    /**
     * Step 2: Send them a welcome email
     */

    workflow.on('sendWelcomeEmail', function (user) {

      // Create reusable transporter object using SMTP transport
      var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
          user: config.gmail.user,
          pass: config.gmail.password
        }
      });

      // Render HTML to send using .jade mail template (just like rendering a page)
      res.render('mail/welcome', {
        name:          user.profile.name,
        mailtoName:    config.smtp.name,
        mailtoAddress: config.smtp.address,
        blogLink:      req.protocol + '://' + req.headers.host, // + '/blog',
        forumLink:     req.protocol + '://' + req.headers.host  // + '/forum'
      }, function (err, html) {
        if (err) {
          return (err, null);
        }
        else {

          // Now create email text (multiline string as array FTW)
          var text = [
            'Hello ' + user.profile.name + '!',
            'We would like to welcome you as our newest member!',
            'Thanks so much for using our services! If you have any questions, or suggestions, feel free to email us here at ' + config.smtp.address + '.',
            'If you want to get the latest scoop check out our blog and our forums.',
            '  - The ' + config.smtp.name + ' team'
          ].join('\n\n');

          // Create email
          var mailOptions = {
            to:       user.profile.name + ' <' + user.email + '>',
            from:     config.smtp.name + ' <' + config.smtp.address + '>',
            subject:  'Welcome to ' + app.locals.application + '!',
            text:     text,
            html:     html
          };

          // Send email
          transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
              req.flash('error', { msg: err });
            } // else {
              // console.log('Message sent: ' + info.response);
            // }
          });

        }
      });

      // next step
      workflow.emit('logUserIn', user);
    });

    /**
     * Step 3: Log them in
     */

    workflow.on('logUserIn', function (user) {

      // log the user in
      req.logIn(user, function (err) {
        if (err) {
          req.flash('error', { msg: err.message });
          return res.redirect('back');
        }
        req.flash('info', { msg: 'Your account verification is completed!' });
        res.redirect('/api');
      });

      // WORKFLOW COMPLETED
    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

  /**
   * GET /signup
   * Render signup page
   */

  app.get('/signup', function (req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    res.render('account/signup', {
      url: req.url
    });
  });

  /**
   * POST /signup
   * Process a *regular* signup
   */

  app.post('/signup', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('name', 'Your name cannot be empty.').notEmpty();
      req.assert('email', 'Your email cannot be empty.').notEmpty();
      req.assert('email', 'Your email is not valid.').isEmail();
      req.assert('password', 'Your password cannot be empty.').notEmpty();
      req.assert('confirmPassword', 'Your password confirmation cannot be empty.').notEmpty();
      req.assert('password', 'Your password must be at least 4 characters long.').len(4);
      req.assert('confirmPassword', 'Your passwords do not match.').equals(req.body.password);

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('back');
      }

      // next step
      workflow.emit('verification');
    });

    /**
     * Step 2: Account verification step
     */

    workflow.on('verification', function () {

      var verified;
      var verifyToken;

      if (config.verificationRequired) {
        verified = false;
        // generate verification token
        crypto.randomBytes(25, function (err, buf) {
          verifyToken = buf.toString('hex');
          // next step
          workflow.emit('createUser', verified, verifyToken);
        });
      } else {
        verified = true;
        verifyToken = null;
        // next step
        workflow.emit('createUser', verified, verifyToken);
      }

    });

    /**
     * Step 3: Create a new account
     */

    workflow.on('createUser', function (verified, verifyToken) {

      // create user
      var user = new User({
        'profile.name': req.body.name.trim(),
        email:          req.body.email.toLowerCase(),
        password:       req.body.password,
        verifyToken:    verifyToken,
        verified:       verified
      });

      // save user
      user.save(function (err) {
        if (err) {
          if (err.code === 11000) {
            req.flash('error', { msg: 'An account with that email address already exists!' });
            req.flash('info', { msg: 'You should sign in with that account.' });
          }
          return res.redirect('back');
        } else {
          if (config.verificationRequired) {
            // next step (4a)
            workflow.emit('sendValidateEmail', user, verifyToken);
          } else {
            // next step (4b)
            workflow.emit('sendWelcomeEmail', user);
          }
        }
      });

    });

    /**
     * Step 4a: Send them a validate email
     */

    workflow.on('sendValidateEmail', function (user, verifyToken) {

      // Create reusable transporter object using SMTP transport
      var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
          user: config.gmail.user,
          pass: config.gmail.password
        }
      });

      // Render HTML to send using .jade mail template (just like rendering a page)
      res.render('mail/accountVerification', {
        name:          user.profile.name,
        mailtoName:    config.smtp.name,
        validateLink:  req.protocol + '://' + req.headers.host + '/verify/' + user.id + '/' + verifyToken
      }, function (err, html) {
        if (err) {
          return (err, null);
        }
        else {

          // Now create email text (multiline string as array FTW)
          var text = [
            'Hello ' + user.profile.name + '!',
            'Welcome to ' + app.locals.application + '!  Here is a special link to activate your new account:',
            req.protocol + '://' + req.headers.host + '/verify/' + user.id + '/' + user.verifyToken,
            '  - The ' + config.smtp.name + ' team'
          ].join('\n\n');

          // Create email
          var mailOptions = {
            to:       user.profile.name + ' <' + user.email + '>',
            from:     config.smtp.name + ' <' + config.smtp.address + '>',
            subject:  'Activate your new ' + app.locals.application + ' account',
            text:     text,
            html:     html
          };

          // Send email
          transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
              req.flash('error', { msg: err });
            } // else {
              // console.log('Message sent: ' + info.response);
            // }
          });

        }
      });

      req.flash('info', { msg: 'Please check your email to verify your account. Thanks for signing up!' });
      res.redirect('/signup');

      // WORKFLOW COMPLETED

    });

    /**
     * Step 4b: Send them a welcome email
     */

    workflow.on('sendWelcomeEmail', function (user) {

      // Create reusable transporter object using SMTP transport
      var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
          user: config.gmail.user,
          pass: config.gmail.password
        }
      });

      // Render HTML to send using .jade mail template (just like rendering a page)
      res.render('mail/welcome', {
        name:          user.profile.name,
        mailtoName:    config.smtp.name,
        mailtoAddress: config.smtp.address,
        blogLink:      req.protocol + '://' + req.headers.host, // + '/blog',
        forumLink:     req.protocol + '://' + req.headers.host  // + '/forum'
      }, function (err, html) {
        if (err) {
          return (err, null);
        }
        else {

          // Now create email text (multiline string as array FTW)
          var text = [
            'Hello ' + user.profile.name + '!',
            'We would like to welcome you as our newest member!',
            'Thanks so much for using our services! If you have any questions, or suggestions, feel free to email us here at ' + config.smtp.address + '.',
            'If you want to get the latest scoop check out our blog and our forums.',
            '  - The ' + config.smtp.name + ' team'
          ].join('\n\n');

          // Create email
          var mailOptions = {
            to:       user.profile.name + ' <' + user.email + '>',
            from:     config.smtp.name + ' <' + config.smtp.address + '>',
            subject:  'Welcome to ' + app.locals.application + '!',
            text:     text,
            html:     html
          };

          // Send email
          transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
              req.flash('error', { msg: err });
            } // else {
              // console.log('Message sent: ' + info.response);
            // }
          });

        }
      });

      // next step
      workflow.emit('logUserIn', user);
    });

    /**
     * Step 5: Log them in
     */

    workflow.on('logUserIn', function (user) {

      // log the user in
      req.logIn(user, function (err) {
        if (err) {
          req.flash('error', { msg: err.message });
          return res.redirect('back');
        }
        // send the right welcome message
        if (config.twoFactor) {
          req.flash('warning', { msg: 'Welcome! We recommend turning on enhanced security in account settings.' });
          res.redirect('/api');
        } else {
          req.flash('info', { msg: 'Thanks for signing up! You rock!' });
          res.redirect('/api');
        }

      });

      // WORKFLOW COMPLETED

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

  /**
   * GET /signupsocial
   * Confirm social email address
   */

  app.get('/signupsocial', function (req, res) {
    res.render('account/signupsocial', {
      url: req.url,
      email: ''
    });
  });

  /**
   * POST /signupsocial
   * Process a *Social* signup & confirm email address
   */

  app.post('/signupsocial', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the form fields
     */

    workflow.on('validate', function () {

      // Check for form errors
      req.assert('email', 'Your email cannot be empty.').notEmpty();
      req.assert('email', 'Your email is not valid.').isEmail();

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('/signupsocial');
      }

      // next step
      workflow.emit('duplicateEmailCheck');
    });

    /**
     * Step 2: Make sure the email address is unique
     */

    workflow.on('duplicateEmailCheck', function () {

      // Make sure we have a unique email address!
      User.findOne({ email: req.body.email.toLowerCase() }, function (err, user) {
        if (err) {
          req.flash('error', { msg: err.msg });
          return res.redirect('/signupsocial');
        }
        if (user) {
          req.flash('error', { msg: 'Sorry that email address has already been used!' });
          req.flash('info', { msg: 'You can sign in with that account and link this provider, or you can create a new account by entering a different email address.' });
          return res.redirect('/signupsocial');
        } else {
          // next step
          workflow.emit('createUser');
        }
      });

    });

    /**
     * Step 4: Create a new account
     */

    workflow.on('createUser', function () {

      var newUser = req.session.socialProfile;
      var user = new User();

      user.verified         = true;  // social users don't require verification
      user.email            = req.body.email.toLowerCase();
      user.profile.name     = newUser.profile.name;
      user.profile.gender   = newUser.profile.gender;
      user.profile.location = newUser.profile.location;
      user.profile.website  = newUser.profile.website;
      user.profile.picture  = newUser.profile.picture;

      if (newUser.source === 'twitter') {
        user.twitter = newUser.id;
        user.tokens.push({ kind: 'twitter', token: newUser.token, tokenSecret: newUser.tokenSecret });

      } else if (newUser.source === 'facebook') {
        user.facebook = newUser.id;
        user.tokens.push({ kind: 'facebook', accessToken: newUser.accessToken, refreshToken: newUser.refreshToken });

      } else if (newUser.source === 'github') {
        user.github = newUser.id;
        user.tokens.push({ kind: 'github', accessToken: newUser.accessToken, refreshToken: newUser.refreshToken });

      } else if (newUser.source === 'google') {
        user.google = newUser.id;
        user.tokens.push({ kind: 'google', accessToken: newUser.accessToken, refreshToken: newUser.refreshToken });
      }

      // save user
      user.save(function (err) {
        if (err) {
          if (err.code === 11000) {
            req.flash('error', { msg: 'An account with that email already exists!' });
          }
          return res.redirect('/signupsocial');
        } else {
          // next step
          workflow.emit('sendWelcomeEmail', user);
        }
      });

    });

    /**
     * Step 5: Send them a welcome email
     */

    workflow.on('sendWelcomeEmail', function (user) {

      // Create reusable transporter object using SMTP transport
      var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
          user: config.gmail.user,
          pass: config.gmail.password
        }
      });

      // Render HTML to send using .jade mail template (just like rendering a page)
      res.render('mail/welcome', {
        name:          user.profile.name,
        mailtoName:    config.smtp.name,
        mailtoAddress: config.smtp.address,
        blogLink:      req.protocol + '://' + req.headers.host, // + '/blog',
        forumLink:     req.protocol + '://' + req.headers.host  // + '/forum'
      }, function (err, html) {
        if (err) {
          return (err, null);
        }
        else {

          // Now create email text (multiline string as array FTW)
          var text = [
            'Hello ' + user.profile.name + '!',
            'We would like to welcome you as our newest member!',
            'Thanks so much for using our services! If you have any questions, or suggestions, feel free to email us here at ' + config.smtp.address + '.',
            'If you want to get the latest scoop check out our blog and our forums.',
            '  - The ' + config.smtp.name + ' team'
          ].join('\n\n');

          // Create email
          var mailOptions = {
            to:       user.profile.name + ' <' + user.email + '>',
            from:     config.smtp.name + ' <' + config.smtp.address + '>',
            subject:  'Welcome to ' + app.locals.application + '!',
            text:     text,
            html:     html
          };

          // Send email
          transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
              req.flash('error', { msg: err });
            } // else {
              // console.log('Message sent: ' + info.response);
            // }
          });

        }
      });

      // next step
      workflow.emit('logUserIn', user);
    });

    /**
     * Step 6: Log them in
     */

    workflow.on('logUserIn', function (user) {

      // log the user in
      req.logIn(user, function (err) {
        if (err) {
          return next(err);
        }
        req.flash('info', { msg: 'Thanks for signing up! You rock!' });
        res.redirect('/api');
      });

    });

    /**
     * Initiate the workflow
     */

    workflow.emit('validate');

  });

  /**
   * Facebook Authentication
   */

  app.get('/auth/facebook',
    passport.authenticate('facebook', {
      callbackURL: '/auth/facebook/callback'
    })
  );

  app.get('/auth/facebook/callback', function (req, res, next) {
    passport.authenticate('facebook', {
      callbackURL: '/auth/facebook/callback',
      failureRedirect: '/login'
    }, function (err, user, info) {

      // Check for data
      if (!info || !info.profile) {
        req.flash('error', { msg: 'We have no data. Something went wrong!' });
        return res.redirect('/login');
      }

      // Do we already have a user with this Facebook ID?
      // If so, then it's just a login - timestamp it.
      User.findOne({ facebook: info.profile._json.id }, function (err, justLogin) {
        if (err) {
          return next(err);
        }
        if (justLogin) {
          // Update the user's record with login timestamp
          justLogin.activity.last_logon = Date.now();
          justLogin.save(function (err) {
            if (err) {
              return next(err);
            }
            // Log the user in
            req.login(justLogin, function (err) {
              if (err) {
                return next(err);
              }

              // Send user on their merry way
              if (req.session.attemptedURL) {
                var redirectURL = req.session.attemptedURL;
                delete req.session.attemptedURL;
                return res.redirect(redirectURL);
              } else {
                return res.redirect('/api');
              }

            });
          });
        } else {
          // Brand new Facebook user!
          // Save their profile data into the session
          var newSocialUser               = {};

          newSocialUser.source            = 'facebook';
          newSocialUser.id                = info.profile._json.id;
          newSocialUser.accessToken       = info.accessToken;
          newSocialUser.refreshToken      = info.refreshToken;
          newSocialUser.email             = info.profile._json.email;

          newSocialUser.profile           = {};

          newSocialUser.profile.name      = info.profile._json.name;
          newSocialUser.profile.gender    = info.profile._json.gender;
          newSocialUser.profile.location  = info.profile._json.location.name;
          newSocialUser.profile.website   = info.profile._json.link;
          newSocialUser.profile.picture   = 'https://graph.facebook.com/' + info.profile.id + '/picture?type=large';

          req.session.socialProfile = newSocialUser;
          res.render('account/signupsocial', { email: newSocialUser.email });
        }
      });

    })(req, res, next);
  });

  /**
   * Github Authentication
   */

  app.get('/auth/github',
    passport.authenticate('github', {
      callbackURL: '/auth/github/callback'
    })
  );

  app.get('/auth/github/callback', function (req, res, next) {
    passport.authenticate('github', {
      callbackURL: '/auth/github/callback',
      failureRedirect: '/login'
    }, function (err, user, info) {
      if (!info || !info.profile) {
        req.flash('error', { msg: 'We have no data. Something went wrong!' });
        return res.redirect('/login');
      }

      // Do we already have a user with this GitHub ID?
      // If so, then it's just a login - timestamp it.
      User.findOne({ github: info.profile._json.id }, function (err, justLogin) {
        if (err) {
          return next(err);
        }
        if (justLogin) {
          // Update the user's record with login timestamp
          justLogin.activity.last_logon = Date.now();
          justLogin.save(function (err) {
            if (err) {
              return next(err);
            }
            // Log the user in
            req.login(justLogin, function (err) {
              if (err) {
                return next(err);
              }

              // Send user on their merry way
              if (req.session.attemptedURL) {
                var redirectURL = req.session.attemptedURL;
                delete req.session.attemptedURL;
                return res.redirect(redirectURL);
              } else {
                return res.redirect('/api');
              }

            });
          });
        } else {
          // Brand new GitHub user!
          // Save their profile data into the session
          var newSocialUser               = {};

          newSocialUser.source            = 'github';
          newSocialUser.id                = info.profile._json.id;
          newSocialUser.accessToken       = info.accessToken;
          newSocialUser.refreshToken      = info.refreshToken;
          newSocialUser.email             = info.profile._json.email;

          newSocialUser.profile           = {};

          newSocialUser.profile.name      = info.profile._json.name;
          newSocialUser.profile.gender    = ''; // No gender from Github
          newSocialUser.profile.location  = info.profile._json.location;
          newSocialUser.profile.website   = info.profile._json.html_url;
          newSocialUser.profile.picture   = info.profile._json.avatar_url;

          req.session.socialProfile = newSocialUser;
          res.render('account/signupsocial', { email: newSocialUser.email });
        }
      });

    })(req, res, next);
  });

  /**
   * Google Authentication
   */

  app.get('/auth/google',
    passport.authenticate('google', {
      callbackURL: '/auth/google/callback'
    })
  );

  app.get('/auth/google/callback', function (req, res, next) {
    passport.authenticate('google', {
      callbackURL: '/auth/google/callback',
      failureRedirect: '/login'
    }, function (err, user, info) {
      if (!info || !info.profile) {
        req.flash('error', { msg: 'We have no data. Something went wrong!' });
        return res.redirect('/login');
      }

      // Do we already have a user with this Google ID?
      // If so, then it's just a login - timestamp it.
      User.findOne({ google: info.profile._json.id }, function (err, justLogin) {
        if (err) {
          return next(err);
        }
        if (justLogin) {
          // Update the user's record with login timestamp
          justLogin.activity.last_logon = Date.now();
          justLogin.save(function (err) {
            if (err) {
              return next(err);
            }
            // Log the user in
            req.login(justLogin, function (err) {
              if (err) {
                return next(err);
              }

              // Send user on their merry way
              if (req.session.attemptedURL) {
                var redirectURL = req.session.attemptedURL;
                delete req.session.attemptedURL;
                return res.redirect(redirectURL);
              } else {
                return res.redirect('/api');
              }

            });
          });
        } else {
          // Brand new Google user!
          // Save their profile data into the session
          var newSocialUser               = {};

          newSocialUser.source            = 'google';
          newSocialUser.id                = info.profile.id;
          newSocialUser.accessToken       = info.accessToken;
          newSocialUser.refreshToken      = info.refreshToken;
          newSocialUser.email             = info.profile._json.email;

          newSocialUser.profile           = {};

          newSocialUser.profile.name      = info.profile._json.name;
          newSocialUser.profile.gender    = info.profile._json.gender;
          newSocialUser.profile.location  = ''; // No location from Google
          newSocialUser.profile.website   = info.profile._json.link;
          newSocialUser.profile.picture   = info.profile._json.picture;

          req.session.socialProfile = newSocialUser;
          res.render('account/signupsocial', { email: newSocialUser.email });
        }
      });

    })(req, res, next);
  });

  /**
   * Twitter Authentication
   */

  app.get('/auth/twitter',
    passport.authenticate('twitter', {
      callbackURL: '/auth/twitter/callback'
    })
  );

  app.get('/auth/twitter/callback', function (req, res, next) {
    passport.authenticate('twitter', {
      callbackURL: '/auth/twitter/callback',
      failureRedirect: '/login'
    }, function (err, user, info) {
      if (!info || !info.profile) {
        req.flash('error', { msg: 'We have no data. Something went wrong!' });
        return res.redirect('/login');
      }

      // Do we already have a user with this Twitter ID?
      // If so, then it's just a login - timestamp it.
      User.findOne({ twitter: info.profile._json.id }, function (err, justLogin) {
        if (err) {
          return next(err);
        }
        if (justLogin) {
          // Update the user's record with login timestamp
          justLogin.activity.last_logon = Date.now();
          justLogin.save(function (err) {
            if (err) {
              return next(err);
            }
            // Log the user in
            req.login(justLogin, function (err) {
              if (err) {
                return next(err);
              }

              // Send user on their merry way
              if (req.session.attemptedURL) {
                var redirectURL = req.session.attemptedURL;
                delete req.session.attemptedURL;
                return res.redirect(redirectURL);
              } else {
                return res.redirect('/api');
              }

            });
          });
        } else {
          // Brand new Twitter user!
          // Save their profile data into the session
          var newSocialUser               = {};

          newSocialUser.source            = 'twitter';
          newSocialUser.id                = info.profile.id;
          newSocialUser.token             = info.token;
          newSocialUser.tokenSecret       = info.tokenSecret;
          newSocialUser.email             = '';  // Twitter does not provide email addresses

          newSocialUser.profile           = {};

          newSocialUser.profile.name      = info.profile._json.name;
          newSocialUser.profile.gender    = '';  // No gender from Twitter either
          newSocialUser.profile.location  = info.profile._json.location || '';
          // // Twitter may or may not provide a URL
          if (typeof info.profile._json.entities.url !== 'undefined') {
            newSocialUser.profile.website = info.profile._json.entities.url.urls[0].expanded_url;
          } else {
            newSocialUser.profile.website = '';
          }
          newSocialUser.profile.picture   = info.profile._json.profile_image_url;

          req.session.socialProfile = newSocialUser;
          res.render('account/signupsocial', { email: newSocialUser.email });
        }
      });

    })(req, res, next);
  });

};


text:
import C;
LINK_CLSID = '{00021401-0000-0000-C000-000000000046}';

VALID_SHOW_COMMAND_VALUES = {
  1: 'SW_SHOWNORMAL',
  3: 'SW_SHOWMAXIMIZED',
  7: 'SW_SHOWMINNOACTIVE',
};

VALID_HOTKEY_LOWBYTE_VALUES = {
  0x90: 'NumLock',
  0x91: 'ScrollLock',
};
for i in range(0x30, 0x3A):
  VALID_HOTKEY_LOWBYTE_VALUES[i] = chr(i); # 0 - 9
for i in range(0x41, 0x5B):
  VALID_HOTKEY_LOWBYTE_VALUES[i] = chr(i); # A - Z
for i in range(1, 25):
  VALID_HOTKEY_LOWBYTE_VALUES[i + 0x6F] = 'F%d' % i; # F1 - F24 (!)

# bitflags_LinkFlags
def bitflags_LinkFlags(stream, offset, max_size, parent, name):
  result = C.BITFIELD(stream, offset, max_size, parent, name, \
      ('Reserved',                                5),
      ('KeepLocalIDListForUNCTarget',             1),
      ('PreferEnvironmentPath',                   1),
      ('UnaliasOnSave',                           1),
      ('AllowLinkToLink',                         1),
      ('DisableKnownFolderAlias',                 1),
      ('DisableKnownFolderTracking',              1),
      ('DisableLinkPathTracking',                 1),
      ('EnableTargetMetadata',                    1),
      ('ForceNoLinkTrack',                        1),
      ('RunWithShimLayer',                        1),
      ('Unused2',                                 1),
      ('NoPidlAlis',                              1),
      ('HasExpIcon',                              1),
      ('RunAsUser',                               1),
      ('HasDarwinID',                             1),
      ('Unused1',                                 1),
      ('RunInSeperateProcess',                    1),
      ('HasExpString',                            1),
      ('ForceNoLinkInfo',                         1),
      ('IsUnicode',                               1),
      ('HasIconLocation',                         1),
      ('HasArguments',                            1),
      ('HasWorkingDir',                           1),
      ('HasRelativePath',                         1),
      ('HasName',                                 1),
      ('HasLinkInfo',                             1),
      ('HasLinkTargetIDList',                     1)
  );
  result.dump_simplified = True;
  if result._Unused1.value != 0:
    result._Unused1.warnings.append('Expected value to be 0');
  if result._Unused2.value != 0:
    result._Unused2.warnings.append('Expected value to be 0');
  if result._Reserved.value != 0:
    result._Reserved.warnings.append('Expected value to be 0');
  return result;

# bitflags_FileAttributes
def bitflags_FileAttributes(stream, offset, max_size, parent, name):
  result = C.BITFIELD(stream, offset, max_size, parent, name, \
      ('Unused',                                  17),
      ('FILE_ATTRIBUTE_ENCRYPTED',                1),
      ('FILE_ATTRIBUTE_NOT_CONTENT_INDEXED',      1),
      ('FILE_ATTRIBUTE_OFFLINE',                  1),
      ('FILE_ATTRIBUTE_COMPRESSED',               1),
      ('FILE_ATTRIBUTE_REPARSE_POINT',            1),
      ('FILE_ATTRIBUTE_SPARSE_FILE',              1),
      ('FILE_ATTRIBUTE_TEMPORARY',                1),
      ('FILE_ATTRIBUTE_NORMAL',                   1),
      ('Reserved2',                               1),
      ('FILE_ATTRIBUTE_ARCHIVE',                  1),
      ('FILE_ATTRIBUTE_DIRECTORY',                1),
      ('Reserved1',                               1),
      ('FILE_ATTRIBUTE_SYSTEM',                   1),
      ('FILE_ATTRIBUTE_HIDDEN',                   1),
      ('FILE_ATTRIBUTE_READONLY',                 1)
  );
  result.dump_simplified = True;
  if result._Reserved1.value != 0:
    result._Reserved1.warnings.append('Expected value to be 0');
  if result._Reserved2.value != 0:
    result._Reserved2.warnings.append('Expected value to be 0');
  return result;

# struct_HotKeyFlags
def struct_HotKeyFlags(stream, offset, max_size, parent, name):
  result = C.STRUCT(stream, offset, max_size, parent, name, \
      'HotKeyFlags', \
      ('LowByte',          C.BYTE),
      ('HighByte',         {C.BITFIELD: (
          ('Reserved',             5),
          ('HOTKEYF_ALT',          1),
          ('HOTKEYF_CONTROL',      1),
          ('HOTKEYF_SHIFT',        1),
      )})
  );
  if results._LowByte.value in VALID_HOTKEY_LOWBYTE_VALUES:
    result._LowByte.notes.append( \
        VALID_HOTKEY_LOWBYTE_VALUES[result._LowByte.value]);
  else:
    result._LowByte.warnings.append('Unrecognized value');
  if results._HighByte._Reserved.value > 0:
    results._HighByte._Reserved.warnings.append('Expected value to be 0');
  return result;

# http://download.microsoft.com/download/B/0/B/B0B199DB-41E6-400F-90CD-C350D0C14A53/%5BMS-SHLLINK%5D.pdf
def struct_SHELL_LINK_HEADER(stream, offset, max_size, parent, name):
  import C;
  from struct_GUID import struct_GUID;
  result = C.STRUCT(stream, offset, max_size, parent, name, \
      'LNK_HEADER', \
      ('HeaderSize',          C.DWORD),
      ('LinkCLSID',           struct_GUID),
      ('LinkFlags',           bitflags_LinkFlags),
      ('FileAttributes',      bitflags_FileAttributes),
      ('CreationTime',        C.QWORD),
      ('AccessTime',          C.QWORD),
      ('WriteTime',           C.QWORD),
      ('FileSize',            C.UINT),
      ('IconIndex',           C.INT),
      ('ShowCommand',         C.UINT),
      ('HotKey',              C.WORD),
      ('Reserved1',           C.WORD),
      ('Reserved2',           C.DWORD),
      ('Reserved3',           C.DWORD)
  );
  if result._HeaderSize.value != 0x4C:
    result._HeaderSize.warnings.append(
        'expected value to be 0x4C');
  if result._LinkCLSID.string_value != LINK_CLSID:
    result._LinkCLSID.warnings.append('expected value to be "%s"' % LINK_CLSID);

  if result._ShowCommand.value in VALID_SHOW_COMMAND_VALUES:
    result._ShowCommand.notes.append( \
        VALID_SHOW_COMMAND_VALUES[result._ShowCommand.value]);
  else:
    valid_values = VALID_SHOW_COMMAND_VALUES.keys()
    valid_values = '%s or %s' % \
        (', '.join(valid_values[:-1]), valid_values[-1]);
    result._ShowCommand.warnings.append( \
        'Expected value to be %s' % valid_values);

  if result._Reserved1.value != 0:
    result._Reserved1.warnings.append('Expected value to be 0');
  if result._Reserved2.value != 0:
    result._Reserved2.warnings.append('Expected value to be 0');
  return result;


text:
using System.Collections.Generic;

namespace Hangfire.SQLite
{
    public interface IPersistentJobQueueMonitoringApi
    {
        IEnumerable<string> GetQueues();
        IEnumerable<int> GetEnqueuedJobIds(string queue, int from, int perPage);
        IEnumerable<int> GetFetchedJobIds(string queue, int from, int perPage);
        EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue);
    }
}


text:
from discord.ext import commands
import random
import discord

class Hug:
    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    async def hug(self, context, member: discord.Member):
        """Hug your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        hug = "**{0} gave {1} a hug!**"

        choices = ['http://i.imgur.com/sW3RvRN.gif', 'http://i.imgur.com/gdE2w1x.gif', 'http://i.imgur.com/zpbtWVE.gif', 'http://i.imgur.com/ZQivdm1.gif', 'http://i.imgur.com/MWZUMNX.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)

def setup(bot):
    n = Hug(bot)
    bot.add_cog(n)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TeamSpark.AzureDay.WebSite.Localization.App.Service.Speaker {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class OKrakovetskyi {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal OKrakovetskyi() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TeamSpark.AzureDay.WebSite.Localization.App.Service.Speaker.OKrakovetskyi", typeof(OKrakovetskyi).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to I am CEO of DevRain Solutions, IT company from Ukraine. We specialize in web, cloud and mobile solutions (.NET, Xamarin, iOS, Android). In 2013 my company got "Lead partner in creating mobile solutions on Windows Phone 8 platform" award from Microsoft Ukraine.
        ///I am a Microsoft Regional Director during last 8 years and Microsoft Most Valuable Professional during last 6 years. Also I was nominated as Telerik Developer Expert for several years and got "The Best Professional in Software Architecture" Ukrainian [rest of string was truncated]";.
        /// </summary>
        public static string Bio {
            get {
                return ResourceManager.GetString("Bio", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Oleksandr.
        /// </summary>
        public static string FirstName {
            get {
                return ResourceManager.GetString("FirstName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Krakovetskyi.
        /// </summary>
        public static string LastName {
            get {
                return ResourceManager.GetString("LastName", resourceCulture);
            }
        }
    }
}


text:
from collections import deque

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        if not root:
            return ''
        queue = deque()
        queue.append(root)
        res = ''
        while len(queue):
            node = queue.popleft()
            if not node:
                res += 'n '
                continue
            res += (str(node.val) + ' ')
            queue.append(node.left)
            queue.append(node.right)

        return res

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if data == '':
            return None
        queue = deque()
        values = data.split()
        root = TreeNode(int(values[0]))
        queue.append(root)

        i = 1

        while i < len(values):
            parent = queue.popleft()
            if values[i] != 'n':
                left = TreeNode(int(values[i]))
                parent.left = left
                queue.append(left)

            i += 1

            if values[i] != 'n':
                right = TreeNode(int(values[i]))
                parent.right = right
                queue.append(right)

            i += 1

        return root


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("业务逻辑层-Maticsoft.Net.SystemFramework")]
[assembly: AssemblyDescription("Maticsoft.Net.SystemFramework 示例项目源码")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("李天平")]
[assembly: AssemblyProduct("http://www.maticsoft.com")]
[assembly: AssemblyCopyright("Copyright (C)Maticsoft 2004-2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]


text:
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
 * Contains EWSType_SubscribeResponseMessageType.
 */

/**
 * Represents the status and result of a single Subscribe Operation request.
 *
 * @package php-ews\Types
 *
 * @todo Extend EWSType_ResponseMessageType.
 */
class EWSType_SubscribeResponseMessageType extends EWSType
{
    /**
     * Currently unused and reserved for future use.
     *
     * This element contains a value of 0.
     *
     * @since Exchange 2007
     *
     * @var integer
     */
    public $DescriptiveLinkKey;

    /**
     * Provides a text description of the status of the response.
     *
     * @since Exchange 2007
     *
     * @var string
     */
    public $MessageText;

    /**
     * Provides additional error response information.
     *
     * @since Exchange 2007
     *
     * @var string
     *
     * @todo Determine if we can use SimpleXML or DOMDocument here.
     */
    public $MessageXml;

    /**
     * Describes the status of the response.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ResponseClassType
     */
    public $ResponseClass;

    /**
     * Provides an error code that identifies the specific error that the
     * request encountered.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ResponseCodeType
     */
    public $ResponseCode;

    /**
     * Represents the identifier for a subscription.
     *
     * @since Exchange 2007
     *
     * @var string
     */
    public $SubscriptionId;

    /**
     * Watermark property
     *
     * @since Exchange 2007
     *
     * @var string
     */
    public $Watermark;
}


text:
import {isStream as objectIsStream} from 'is-stream';
import objectIsObservable from 'is-observable';

// RxJS@6 symbol (https://github.com/sindresorhus/is-observable/issues/1#issuecomment-387843191)
const symbolObservable = typeof Symbol === 'function' && Symbol.observable || '@@observable';		// eslint-disable-line no-mixed-operators

export const isObservable = object => Boolean(object && object[symbolObservable] && object === object[symbolObservable]()) || objectIsObservable(object);
export const isListr = object => Boolean(object && object.setRenderer && object.add && object.run);
export const isStream = object => objectIsStream(object) && !isObservable(object);


text:
<!DOCTYPE html>

  <meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Tutorials — XID+ 3.0.0 documentation</title>
      <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
      <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="XID+ Example Run Script" href="notebooks/examples/XID%2Bexample_run_script.html" />
    <link rel="prev" title="Installation" href="intro.html" />

             XID+

                3.0.0

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

User Guide:

A Generative Probabilistic Framework

Installation

Docker

Tutorials

XID+ Example Run Script

XID+ Example Output Analysis

Large Fields

Beyond Positional Priors

API documentation

          XID+

 »

Tutorials

             View page source

Tutorials¶

The following tutorials explain how to:

Run XID+ on SPIRE maps

Carry out analysis on output

Both are taken from Jupyter notebooks available in the package directory

XID+ Example Run Script

XID+ SPIRE

XID+ Example Output Analysis

Posterior replicated data

Joint Posterior Analysis of sources

Posterior Predictive checking and Bayesian P-value maps

Creating Catalogues

Check table

         Previous
        Next

© Copyright 2022, Peter Hurley.

  Built with Sphinx using a
    theme
    provided by Read the Docs.


text:
/**
 * @file Manage actions for deploy commands
 * @since 1.6.0
 * @author kyungmi.k@samsung.com
 * @module Deploy/command
 */

define([
    'dijit/Dialog',
    'dojo/i18n!./nls/resource',
    'webida-lib/app',
    'webida-lib/plugins/command-system/system/command-system',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client',
    './dialog-controller'
], function (
    Dialog,
    i18n,
    ide,
    commandSystem,
    genetic,
    Logger,
    dialogController
) {
    'use strict';

    var logger = new Logger();
    logger.off();

    var Command = commandSystem.Command;

    function PluginSettingCommand(id) {
        PluginSettingCommand.id = id;
    }
    genetic.inherits(PluginSettingCommand, Command, {
        execute : function () {
            return new Promise(function (resolve) {
                dialogController.openDialog();
                resolve();
            });
        }
    });

    return {
        PluginSettingCommand: PluginSettingCommand
    };
});


text:
var wrapper = require('../util/callbackWrapper.js'),
  WebSocketServer = require('ws').Server,
  Logger = require('../util/logger.js'),
  Context = require('../context/context.js'),
  Connection = require('../connections/connection.js'),
  shared = require('./shared.js'),
  p = require('jpromise');

function Server(options) {
  options = options || {};
  var logger = options.logger || new Logger(options.logLevel, options);
  var events = {};
  var contexts = [];
  var useMap = {};
  var wss;
  //setup common things
  shared(this, useMap, events, logger);

  this.listen = function(options, callback) {
    dfd = wrapper(callback);
    //throw an error if we don't have an object with a port for option
    if (!options || typeof options !== 'object' || (!options.port && !options.server)) {
      throw new Error('an options object with at least a port must be provided');
    }

    wss = new WebSocketServer(options, function() {
      dfd.resolve();
    });

    wss.on('connection', function(ws) {
      logger.debug('recieved connection');
      var context = new Context(ws, logger, useMap, events, Connection, function(c) {
        contexts.splice(contexts.indexOf(c), 1);
      });
      events.connection(context.connection);
      contexts.push(context);
    });

    return dfd.promise();
  };

  this.close = function(code, reason, callback) {
    logger.info('closing all connections');
    var dfd = wrapper(callback);
    dfds = [];
    for (var x in contexts) {
      var d = new p();
      dfds.push(d);
      try {
        logger.debug('closing', contexts[x].id);
        contexts[x].connection.close(code, reason);
        d.resolve();
      } catch (err) {
        d.reject(err);
      }
    }
    p.when(dfds).done(function() {
      wss.close();
      dfd.resolve();
    }).fail(function(err) {
      wss.close();
      dfd.reject(err);
    });
    return dfd.promise();
  };

};
exports = module.exports = Server;


text:
import shift
from shift import shiftnd,shift2d
from correlate2d import correlate2d
from fast_ffts import get_ffts
from upsample import dftups,upsample_image
from smooth_tools import smooth