text:
import uuid
from io import BytesIO
from urllib.parse import urlencode

import aiohttp
import pycurl
from bs4 import UnicodeDammit, BeautifulSoup
import re
import json

from falsy.loader.func import load
from falsy.netboy.curl_loop import CurlLoop
from falsy.netboy.utils import get_links, get_metas, get_images, get_scripts, get_text, setup_curl_for_get, \
    setup_curl_for_post
from falsy.netboy.utils import get_title, get_links2

# curl_easy_perform()
#     |
#     |--NAMELOOKUP
#     |--|--CONNECT
#     |--|--|--APPCONNECT
#     |--|--|--|--PRETRANSFER
#     |--|--|--|--|--STARTTRANSFER
#     |--|--|--|--|--|--TOTAL
#     |--|--|--|--|--|--REDIRECT

# def debug_function(debug_type, debug_msg):
#     print("debug(%d): %s" % (debug_type, debug_msg))
#
# def progress_function(download_t, download_d, upload_t, upload_d):
#     print('>'*40)
#     print("Total to download", download_t)
#     print("Total downloaded", download_d)
#     print("Total to upload", upload_t)
#     print("Total uploaded", upload_d)
# noprogress = p.get('noprogress', True)
# if noprogress is False:
#     c.setopt(c.NOPROGRESS, False)
#     xferinfo = p.get('XFERINFOFUNCTION')
#     if xferinfo:
#         c.setopt(c.XFERINFOFUNCTION, load(xferinfo))

# Single curl request:
async def get_request(payload, share=None):
    c = pycurl.Curl()
    data_buf = BytesIO()
    # header_buf = BytesIO()
    headers = {'count': 0, 'content': [{}]}
    try:
        setup_curl_for_get(c, payload, data_buf, headers, share)  # header_buf)

        with aiohttp.Timeout(payload.get('aiohttp_timeout', 60)):
            resp = await CurlLoop.handler_ready(c)
            charset = None
            if 'content-type' in headers:
                content_type = headers['content-type'].lower()
                match = re.search('charset=(\S+)', content_type)
                if match:
                    charset = match.group(1)
                    print('Decoding using %s' % charset)
            body = data_buf.getvalue()
            if len(body) == 0:
                data = ''
                charset = 'utf-8'
            else:
                if charset is None:
                    dammit = UnicodeDammit(body, ["utf-8", "gb2312", "gbk", "big5", "gb18030"], smart_quotes_to="html")
                    data = dammit.unicode_markup
                    charset = dammit.original_encoding
                else:
                    data = body.decode(charset, 'ignore')
            # headers.remove({})
            headers['content'] = [h for h in headers['content'] if len(h) > 0]
            soup_lxml = BeautifulSoup(data, 'lxml')
            soup_html = BeautifulSoup(data, 'html.parser')
            resp.update({
                'url': payload.get('url'),
                # 'soup': soup,
                'title': get_title(soup_lxml),
                'links': get_links(soup_lxml),
                'links2': get_links2(soup_lxml),
                'metas': get_metas(soup_lxml),
                'images': get_images(soup_lxml),
                'scripts': get_scripts(soup_lxml),
                'text': get_text(soup_html),
                'data': data,
                'headers': headers,
                'charset': charset,
                'spider': 'pycurl',
                'payload': payload,
            })
            post_func = payload.get('post_func')
            if post_func:
                post_func = load(post_func)
                resp = post_func(payload, resp)
            return resp
    finally:
        c.close()

async def post_request(payload, share=None):
    c = pycurl.Curl()
    data_buf = BytesIO()
    # header_buf = BytesIO()
    headers = {'count': 0, 'content': [{}]}
    try:
        setup_curl_for_post(c, payload, data_buf, headers, share)  # header_buf)

        with aiohttp.Timeout(payload.get('aiohttp_timeout', 60)):
            resp = await CurlLoop.handler_ready(c)
            # encoding = None
            # if 'content-type' in headers:
            #     content_type = headers['content-type'].lower()
            #     match = re.search('charset=(\S+)', content_type)
            #     if match:
            #         encoding = match.group(1)
            #         print('Decoding using %s' % encoding)
            body = data_buf.getvalue()
            encoding = 'utf-8'
            data = body.decode(encoding, 'ignore') if len(body) > 0 else ''

            # if encoding is None:
            #     dammit = UnicodeDammit(body, ["utf-8", "gb2312", "gbk", "big5", "gb18030"], smart_quotes_to="html")
            #     data = dammit.unicode_markup
            #     encoding = dammit.original_encoding
            # else:
            #     data = body.decode(encoding, 'ignore')
            # headers.remove({})
            headers['content'] = [h for h in headers['content'] if len(h) > 0]

            resp.update({
                # 'url': payload.get('url'),
                'data': data,
                'headers': headers,
                'encoding': encoding,
            })
            post_func = payload.get('post_func')
            if type(post_func) == str:
                post_func = load(post_func)
            if post_func:
                resp = post_func(payload, resp)
            # post_func = payload.get('post_func')
            # if post_func:
            #     post_func = load(post_func)
            #     resp = post_func(payload, resp)
            return resp
    finally:
        c.close()


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Yingdi Yu <yingdi@cs.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include <ndn-cpp-dev/ndn-cpp-config.h>

#include <fstream>
#include <sstream>

#include "../util/logging.hpp"

#include <ndn-cpp-dev/security/sec-tpm-osx.hpp>
#include <ndn-cpp-dev/security/public-key.hpp>

#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
#include <CoreServices/CoreServices.h>

using namespace std;

INIT_LOGGER("SecTpmOsx");

namespace ndn
{
  class SecTpmOsx::Impl {
  public:
    Impl(const std::string &keychainName)
      : keyChainName_ ("" == keychainName ?  "login.keychain" : keychainName)
    {
    }

    /**
     * convert NDN name of a key to internal name of the key
     * @param keyName the NDN name of the key
     * @param keyClass the class of the key
     * @return the internal key name
     */
    std::string
    toInternalKeyName(const Name & keyName, KeyClass keyClass);

    /**
     * Get key
     * @param keyName the name of the key
     * @param keyClass the class of the key
     * @returns pointer to the key
     */
    SecKeychainItemRef
    getKey(const Name & keyName, KeyClass keyClass);

    /**
     * convert keyType to MAC OS symmetric key key type
     * @param keyType
     * @returns MAC OS key type
     */
    const CFTypeRef
    getSymKeyType(KeyType keyType);

    /**
     * convert keyType to MAC OS asymmetirc key type
     * @param keyType
     * @returns MAC OS key type
     */
    const CFTypeRef
    getAsymKeyType(KeyType keyType);

    /**
     * convert keyClass to MAC OS key class
     * @param keyClass
     * @returns MAC OS key class
     */
    const CFTypeRef
    getKeyClass(KeyClass keyClass);

    /**
     * convert digestAlgo to MAC OS algorithm id
     * @param digestAlgo
     * @returns MAC OS algorithm id
     */
    const CFStringRef
    getDigestAlgorithm(DigestAlgorithm digestAlgo);

    /**
     * get the digest size of the corresponding algorithm
     * @param digestAlgo the digest algorithm
     * @return digest size
     */
    long
    getDigestSize(DigestAlgorithm digestAlgo);

    ///////////////////////////////////////////////
    // everything here is public, including data //
    ///////////////////////////////////////////////
  public:
    const std::string keyChainName_;
    SecKeychainRef keyChainRef_;
    SecKeychainRef originalDefaultKeyChain_;
  };

  SecTpmOsx::SecTpmOsx(const string & keychainName)
    : impl_(new Impl(keychainName))
  {
    OSStatus res = SecKeychainCreate(impl_->keyChainName_.c_str(), //Keychain path
				     0,                       //Keychain password length
				     NULL,                    //Keychain password
				     true,                    //User prompt
				     NULL,                    //Initial access of Keychain
				     &impl_->keyChainRef_);   //Keychain reference

    if (res == errSecDuplicateKeychain)
      res = SecKeychainOpen(impl_->keyChainName_.c_str(),
                            &impl_->keyChainRef_);

    if (res != errSecSuccess){
      _LOG_DEBUG("Fail to initialize keychain ref: " << res);
      throw Error("Fail to initialize keychain ref");
    }

    res = SecKeychainCopyDefault(&impl_->originalDefaultKeyChain_);

    res = SecKeychainSetDefault(impl_->keyChainRef_);
    if (res != errSecSuccess){
      _LOG_DEBUG("Fail to set default keychain: " << res);
      throw Error("Fail to set default keychain");
    }
  }

  SecTpmOsx::~SecTpmOsx(){
    //TODO: implement
  }

  void
  SecTpmOsx::generateKeyPairInTpm(const Name & keyName, KeyType keyType, int keySize)
  {

    if(doesKeyExistInTpm(keyName, KEY_CLASS_PUBLIC)){
      _LOG_DEBUG("keyName has existed");
      throw Error("keyName has existed");
    }

    string keyNameUri = impl_->toInternalKeyName(keyName, KEY_CLASS_PUBLIC);

    SecKeyRef publicKey, privateKey;

    CFStringRef keyLabel = CFStringCreateWithCString(NULL,
                                                     keyNameUri.c_str(),
                                                     kCFStringEncodingUTF8);

    CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
                                                             3,
                                                             &kCFTypeDictionaryKeyCallBacks,
                                                             NULL);

    CFDictionaryAddValue(attrDict, kSecAttrKeyType, impl_->getAsymKeyType(keyType));
    CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(NULL, kCFNumberIntType, &keySize));
    CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);

    OSStatus res = SecKeyGeneratePair((CFDictionaryRef)attrDict, &publicKey, &privateKey);

    CFRelease(publicKey);
    CFRelease(privateKey);

    if (res != errSecSuccess){
      _LOG_DEBUG("Fail to create a key pair: " << res);
      throw Error("Fail to create a key pair");
    }
  }

  void
  SecTpmOsx::generateSymmetricKeyInTpm(const Name & keyName, KeyType keyType, int keySize)
  {

    if(doesKeyExistInTpm(keyName, KEY_CLASS_SYMMETRIC))
        throw Error("keyName has existed!");

    string keyNameUri =  impl_->toInternalKeyName(keyName, KEY_CLASS_SYMMETRIC);

    CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                                0,
                                                                &kCFTypeDictionaryKeyCallBacks,
                                                                &kCFTypeDictionaryValueCallBacks);

    CFStringRef keyLabel = CFStringCreateWithCString(NULL,
                                                     keyNameUri.c_str(),
                                                     kCFStringEncodingUTF8);

    CFDictionaryAddValue(attrDict, kSecAttrKeyType, impl_->getSymKeyType(keyType));
    CFDictionaryAddValue(attrDict, kSecAttrKeySizeInBits, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &keySize));
    CFDictionaryAddValue(attrDict, kSecAttrIsPermanent, kCFBooleanTrue);
    CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);

    CFErrorRef error = NULL;

    SecKeyRef symmetricKey = SecKeyGenerateSymmetric(attrDict, &error);

    if (error)
        throw Error("Fail to create a symmetric key");
  }

  ptr_lib::shared_ptr<PublicKey>
  SecTpmOsx::getPublicKeyFromTpm(const Name & keyName)
  {
    _LOG_TRACE("OSXPrivateKeyStorage::getPublickey");

    SecKeychainItemRef publicKey = impl_->getKey(keyName, KEY_CLASS_PUBLIC);

    CFDataRef exportedKey;

    OSStatus res = SecItemExport(publicKey,
                                  kSecFormatOpenSSL,
                                  0,
                                  NULL,
                                  &exportedKey);

    return ptr_lib::make_shared<PublicKey>(CFDataGetBytePtr(exportedKey), CFDataGetLength(exportedKey));
  }

  Block
  SecTpmOsx::signInTpm(const uint8_t *data, size_t dataLength, const Name& keyName, DigestAlgorithm digestAlgorithm)
  {
    _LOG_TRACE("OSXPrivateKeyStorage::Sign");

    CFDataRef dataRef = CFDataCreateWithBytesNoCopy(NULL,
                                                    data,
                                                    dataLength,
                                                    kCFAllocatorNull
                                                    );

    SecKeyRef privateKey = (SecKeyRef)impl_->getKey(keyName, KEY_CLASS_PRIVATE);

    CFErrorRef error;
    SecTransformRef signer = SecSignTransformCreate((SecKeyRef)privateKey, &error);
    if (error) throw Error("Fail to create signer");

    // Set input
    Boolean set_res = SecTransformSetAttribute(signer,
                                               kSecTransformInputAttributeName,
                                               dataRef,
                                               &error);
    if (error) throw Error("Fail to configure input of signer");

    // Enable use of padding
    SecTransformSetAttribute(
                             signer,
                             kSecPaddingKey,
                             kSecPaddingPKCS1Key,
                             &error);
    if (error) throw Error("Fail to configure digest algorithm of signer");

    // Set padding type
    set_res = SecTransformSetAttribute(signer,
                                       kSecDigestTypeAttribute,
                                       impl_->getDigestAlgorithm(digestAlgorithm),
                                       &error);
    if (error) throw Error("Fail to configure digest algorithm of signer");

    // Set padding attribute
    long digestSize = impl_->getDigestSize(digestAlgorithm);
    set_res = SecTransformSetAttribute(signer,
                                       kSecDigestLengthAttribute,
                                       CFNumberCreate(NULL, kCFNumberLongType, &digestSize),
                                       &error);
    if (error) throw Error("Fail to configure digest size of signer");

    // Actually sign
    CFDataRef signature = (CFDataRef) SecTransformExecute(signer, &error);
    if (error) {
      CFShow(error);
      throw Error("Fail to sign data");
    }

    if (!signature) throw Error("Signature is NULL!\n");

    return Block(Tlv::SignatureValue,
                 ptr_lib::make_shared<Buffer>(CFDataGetBytePtr(signature), CFDataGetLength(signature)));
  }

  ConstBufferPtr
  SecTpmOsx::decryptInTpm(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym)
  {
    _LOG_TRACE("OSXPrivateKeyStorage::Decrypt");

    KeyClass keyClass;
    if(sym)
        keyClass = KEY_CLASS_SYMMETRIC;
    else
        keyClass = KEY_CLASS_PRIVATE;

    CFDataRef dataRef = CFDataCreate(NULL,
                                      reinterpret_cast<const unsigned char*>(data),
                                      dataLength
                                      );

    // _LOG_DEBUG("CreateData");

    SecKeyRef decryptKey = (SecKeyRef)impl_->getKey(keyName, keyClass);

    // _LOG_DEBUG("GetKey");

    CFErrorRef error;
    SecTransformRef decrypt = SecDecryptTransformCreate(decryptKey, &error);
    if (error) throw Error("Fail to create decrypt");

    Boolean set_res = SecTransformSetAttribute(decrypt,
                                               kSecTransformInputAttributeName,
                                               dataRef,
                                               &error);
    if (error) throw Error("Fail to configure decrypt");

    CFDataRef output = (CFDataRef) SecTransformExecute(decrypt, &error);
    if (error)
      {
        CFShow(error);
        throw Error("Fail to decrypt data");
      }
    if (!output) throw Error("Output is NULL!\n");

    return ptr_lib::make_shared<Buffer>(CFDataGetBytePtr(output), CFDataGetLength(output));
  }

  bool
  SecTpmOsx::setACL(const Name & keyName, KeyClass keyClass, int acl, const string & appPath)
  {
    SecKeychainItemRef privateKey = impl_->getKey(keyName, keyClass);

    SecAccessRef accRef;
    OSStatus acc_res = SecKeychainItemCopyAccess(privateKey, &accRef);

    CFArrayRef signACL = SecAccessCopyMatchingACLList(accRef,
                                                       kSecACLAuthorizationSign);

    SecACLRef aclRef = (SecACLRef) CFArrayGetValueAtIndex(signACL, 0);

    CFArrayRef appList;
    CFStringRef description;
    SecKeychainPromptSelector promptSelector;
    OSStatus acl_res = SecACLCopyContents(aclRef,
                                           &appList,
                                           &description,
                                           &promptSelector);

    CFMutableArrayRef newAppList = CFArrayCreateMutableCopy(NULL,
                                                            0,
                                                            appList);

    SecTrustedApplicationRef trustedApp;
    acl_res = SecTrustedApplicationCreateFromPath(appPath.c_str(),
                                                   &trustedApp);

    CFArrayAppendValue(newAppList, trustedApp);

    CFArrayRef authList = SecACLCopyAuthorizations(aclRef);

    acl_res = SecACLRemove(aclRef);

    SecACLRef newACL;
    acl_res = SecACLCreateWithSimpleContents(accRef,
                                              newAppList,
                                              description,
                                              promptSelector,
                                              &newACL);

    acl_res = SecACLUpdateAuthorizations(newACL, authList);

    acc_res = SecKeychainItemSetAccess(privateKey, accRef);

    return true;
  }

  // bool
  // OSXPrivateKeyStorage::verifyData(const Name & keyName, const Blob & pData, const Blob & pSig, DigestAlgorithm digestAlgo)
  // {
  //   _LOG_TRACE("OSXPrivateKeyStorage::Verify");

  //   CFDataRef dataRef = CFDataCreate(NULL,
  //                                     reinterpret_cast<const unsigned char*>(pData.buf()),
  //                                     pData.size());

  //   CFDataRef sigRef = CFDataCreate(NULL,
  //                                    reinterpret_cast<const unsigned char*>(pSig.buf()),
  //                                    pSig.size());

  //   SecKeyRef publicKey = (SecKeyRef)impl_->getKey(keyName, KEY_CLASS_PUBLIC);

  //   CFErrorRef error;
  //   SecTransformRef verifier = SecVerifyTransformCreate(publicKey, sigRef, &error);
  //   if (error) throw Error("Fail to create verifier");

  //   Boolean set_res = SecTransformSetAttribute(verifier,
  //                                              kSecTransformInputAttributeName,
  //                                              dataRef,
  //                                              &error);
  //   if (error) throw Error("Fail to configure input of verifier");

  //   set_res = SecTransformSetAttribute(verifier,
  //                                      kSecDigestTypeAttribute,
  //                                      impl_->getDigestAlgorithm(digestAlgo),
  //                                      &error);
  //   if (error) throw Error("Fail to configure digest algorithm of verifier");

  //   long digestSize = impl_->getDigestSize(digestAlgo);
  //   set_res = SecTransformSetAttribute(verifier,
  //                                      kSecDigestLengthAttribute,
  //                                      CFNumberCreate(NULL, kCFNumberLongType, &digestSize),
  //                                      &error);
  //   if (error) throw Error("Fail to configure digest size of verifier");

  //   CFBooleanRef result = (CFBooleanRef) SecTransformExecute(verifier, &error);
  //   if (error) throw Error("Fail to verify data");

  //   if (result == kCFBooleanTrue)
  //     return true;
  //   else
  //     return false;
  // }

  ConstBufferPtr
  SecTpmOsx::encryptInTpm(const Name & keyName, const uint8_t* data, size_t dataLength, bool sym)
  {
    _LOG_TRACE("OSXPrivateKeyStorage::Encrypt");

    KeyClass keyClass;
    if(sym)
        keyClass = KEY_CLASS_SYMMETRIC;
    else
        keyClass = KEY_CLASS_PUBLIC;

    CFDataRef dataRef = CFDataCreate(NULL,
                                      reinterpret_cast<const unsigned char*>(data),
                                      dataLength
                                      );

    SecKeyRef encryptKey = (SecKeyRef)impl_->getKey(keyName, keyClass);

    CFErrorRef error;
    SecTransformRef encrypt = SecEncryptTransformCreate(encryptKey, &error);
    if (error) throw Error("Fail to create encrypt");

    Boolean set_res = SecTransformSetAttribute(encrypt,
                                               kSecTransformInputAttributeName,
                                               dataRef,
                                               &error);
    if (error) throw Error("Fail to configure encrypt");

    CFDataRef output = (CFDataRef) SecTransformExecute(encrypt, &error);
    if (error) throw Error("Fail to encrypt data");

    if (!output) throw Error("Output is NULL!\n");

    return ptr_lib::make_shared<Buffer> (CFDataGetBytePtr(output), CFDataGetLength(output));
  }

  bool
  SecTpmOsx::doesKeyExistInTpm(const Name & keyName, KeyClass keyClass)
  {
    _LOG_TRACE("OSXPrivateKeyStorage::doesKeyExist");

    string keyNameUri = impl_->toInternalKeyName(keyName, keyClass);

    CFStringRef keyLabel = CFStringCreateWithCString(NULL,
                                                     keyNameUri.c_str(),
                                                     kCFStringEncodingUTF8);

    CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
                                                                3,
                                                                &kCFTypeDictionaryKeyCallBacks,
                                                                NULL);

    CFDictionaryAddValue(attrDict, kSecAttrKeyClass, impl_->getKeyClass(keyClass));
    CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);
    CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue);

    SecKeychainItemRef itemRef;
    OSStatus res = SecItemCopyMatching((CFDictionaryRef)attrDict, (CFTypeRef*)&itemRef);

    if(res == errSecItemNotFound)
      return true;
    else
      return false;

  }

  ////////////////////////////////
  // OSXPrivateKeyStorage::Impl //
  ////////////////////////////////

  SecKeychainItemRef
  SecTpmOsx::Impl::getKey(const Name & keyName, KeyClass keyClass)
  {
    string keyNameUri = toInternalKeyName(keyName, keyClass);

    CFStringRef keyLabel = CFStringCreateWithCString(NULL,
                                                     keyNameUri.c_str(),
                                                     kCFStringEncodingUTF8);

    CFMutableDictionaryRef attrDict = CFDictionaryCreateMutable(NULL,
                                                             5,
                                                             &kCFTypeDictionaryKeyCallBacks,
                                                             NULL);

    CFDictionaryAddValue(attrDict, kSecClass, kSecClassKey);
    CFDictionaryAddValue(attrDict, kSecAttrLabel, keyLabel);
    CFDictionaryAddValue(attrDict, kSecAttrKeyClass, getKeyClass(keyClass));
    CFDictionaryAddValue(attrDict, kSecReturnRef, kCFBooleanTrue);

    SecKeychainItemRef keyItem;

    OSStatus res = SecItemCopyMatching((CFDictionaryRef) attrDict, (CFTypeRef*)&keyItem);

    if(res != errSecSuccess){
      _LOG_DEBUG("Fail to find the key!");
      return NULL;
    }
    else
      return keyItem;
  }

  string
  SecTpmOsx::Impl::toInternalKeyName(const Name & keyName, KeyClass keyClass)
  {
    string keyUri = keyName.toUri();

    if(KEY_CLASS_SYMMETRIC == keyClass)
      return keyUri + "/symmetric";
    else
      return keyUri;
  }

  const CFTypeRef
  SecTpmOsx::Impl::getAsymKeyType(KeyType keyType)
  {
    switch(keyType){
    case KEY_TYPE_RSA:
      return kSecAttrKeyTypeRSA;
    default:
      _LOG_DEBUG("Unrecognized key type!")
      return NULL;
    }
  }

  const CFTypeRef
  SecTpmOsx::Impl::getSymKeyType(KeyType keyType)
  {
    switch(keyType){
    case KEY_TYPE_AES:
      return kSecAttrKeyTypeAES;
    default:
      _LOG_DEBUG("Unrecognized key type!")
      return NULL;
    }
  }

  const CFTypeRef
  SecTpmOsx::Impl::getKeyClass(KeyClass keyClass)
  {
    switch(keyClass){
    case KEY_CLASS_PRIVATE:
      return kSecAttrKeyClassPrivate;
    case KEY_CLASS_PUBLIC:
      return kSecAttrKeyClassPublic;
    case KEY_CLASS_SYMMETRIC:
      return kSecAttrKeyClassSymmetric;
    default:
      _LOG_DEBUG("Unrecognized key class!");
      return NULL;
    }
  }

  const CFStringRef
  SecTpmOsx::Impl::getDigestAlgorithm(DigestAlgorithm digestAlgo)
  {
    switch(digestAlgo){
    // case DIGEST_MD2:
    //   return kSecDigestMD2;
    // case DIGEST_MD5:
    //   return kSecDigestMD5;
    // case DIGEST_SHA1:
    //   return kSecDigestSHA1;
    case DIGEST_ALGORITHM_SHA256:
      return kSecDigestSHA2;
    default:
      _LOG_DEBUG("Unrecognized digest algorithm!");
      return NULL;
    }
  }

  long
  SecTpmOsx::Impl::getDigestSize(DigestAlgorithm digestAlgo)
  {
    switch(digestAlgo){
    case DIGEST_ALGORITHM_SHA256:
      return 256;
    // case DIGEST_SHA1:
    // case DIGEST_MD2:
    // case DIGEST_MD5:
    //   return 0;
    default:
      _LOG_DEBUG("Unrecognized digest algorithm! Unknown digest size");
      return -1;
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
layout: page
excerpt: "About Me..."
---

After 13 in the IT industry working on mainframe application development and project management, I am now into Analytics, Fintech and Blockchain.

## Current Interests and Projects:

- Machine Learning
- Data Mining
- Optimization
- Data Visualization


text:
<footer class="content-info">
  <div class="container">
    <?php dynamic_sidebar('sidebar-footer'); ?>
  </div>
</footer>


text:
<stores>
  <store>
    <name>test</name>
    <persistence>bdb</persistence>
    <description>Test store</description>
    <owners>harry@hogwarts.edu, hermoine@hogwarts.edu</owners>
    <routing-strategy>consistent-routing</routing-strategy>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>json</type>
      <schema-info version="0">{"id":"int32", "name":"string"}</schema-info>
    </key-serializer>
    <value-serializer>
      <type>avro-generic-versioned</type>
      <schema-info version="0">
      {"type": "record",
       "name": "myrec",
       "fields": [{ "name": "lname", "type": "string" },{"name":"age","type": "int"}]}
      </schema-info>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>

  <store>
    <name>test1</name>
    <persistence>bdb</persistence>
    <description>Test store</description>
    <owners>harry@hogwarts.edu, hermoine@hogwarts.edu</owners>
    <routing-strategy>consistent-routing</routing-strategy>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>json</type>
      <schema-info version="0">{"id":"int32", "name":"string"}</schema-info>
    </key-serializer>
    <value-serializer>
      <type>string</type>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>

  <store>
    <name>test2</name>
    <persistence>bdb</persistence>
    <description>Test store</description>
    <owners>harry@hogwarts.edu, hermoine@hogwarts.edu</owners>
    <routing-strategy>consistent-routing</routing-strategy>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
    </key-serializer>
    <value-serializer>
      <type>string</type>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>

  <store>
    <name>test3</name>
    <persistence>bdb</persistence>
    <description>Test store</description>
    <owners>harry@hogwarts.edu, hermoine@hogwarts.edu</owners>
    <routing-strategy>consistent-routing</routing-strategy>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>string</type>
    </key-serializer>
    <value-serializer>
      <type>json</type>
      <schema-info version="0">{"id":"int32", "name":"string"}</schema-info>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>

<store>
    <name>test4</name>
    <persistence>bdb</persistence>
    <description>Test store</description>
    <owners>harry@hogwarts.edu, hermoine@hogwarts.edu</owners>
    <routing-strategy>consistent-routing</routing-strategy>
    <routing>client</routing>
    <replication-factor>1</replication-factor>
    <required-reads>1</required-reads>
    <required-writes>1</required-writes>
    <key-serializer>
      <type>avro-generic-versioned</type>
      <schema-info version="0">
      {"type": "record",
       "name": "mykeyrec",
       "fields": [{ "name": "id", "type": "long" },{"name":"name","type": "string"}]}
      </schema-info>
    </key-serializer>
    <value-serializer>
      <type>avro-generic-versioned</type>
      <schema-info version="0">
      {
       "type":"array",
       "items":{"type": "record",
                "name": "myvaluerec",
                "fields": [{ "name": "skill", "type": "string" },{"name":"score","type": "float"},{"name":"isendorsed","type": "boolean"}]
               }
      }
      </schema-info>
    </value-serializer>
    <hinted-handoff-strategy>consistent-handoff</hinted-handoff-strategy>
  </store>

</stores>


text:
#ifndef _WIN32
#include <netdb.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#else
#include <Winsock2.h>
#include <ws2tcpip.h>
#endif

#include "common/u/usocket.h"
#include "common/errdbg/d_printf.h"
#include "common/u/uutils.h"

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int uSocketInit(sys_call_error_fun fun)
{
#ifdef _WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        sys_call_error2("WSAStartup", &err);
        return U_SOCKET_ERROR;
    }

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        if (WSACleanup() != 0) sys_call_error("WSACleanup");

        return U_SOCKET_ERROR;
    }

    return 0;
#else
    return 0;
#endif
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int uSocketCleanup(sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = WSACleanup();
    if (res != 0) sys_call_error("WSACleanup");
    return res;
#else
    return 0;
#endif
}

/* returns U_INVALID_SOCKET if failed */
USOCKET usocket(int af, int type, int protocol, sys_call_error_fun fun)
{
#ifdef _WIN32
    USOCKET res = socket(af, type, protocol);
    if (res == INVALID_SOCKET) sys_call_error("socket");
    return res;
#else
    int param = 1, res = 0;
    int sockfd = socket(af, type, protocol);
    if (sockfd == U_SOCKET_ERROR)
    {
        sys_call_error("socket");
        return U_INVALID_SOCKET;
    }

#if defined(DARWIN)  /// Under DARWIN this is the only way not to get damn SIGPIPE!
    res = setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &param, sizeof(int));
    if(-1 == res)
    {
        sys_call_error("setsockopt");
        close(sockfd);
        return U_INVALID_SOCKET;
    }
#endif /* DARWIN */

    return sockfd;
#endif
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int ubind_tcp(USOCKET s, unsigned short port, const char * addr, sys_call_error_fun fun)
{
    struct addrinfo hints, *hp;
    char buf[8];
#ifndef _WIN32
    int t_reuse = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &t_reuse, sizeof(int));
#endif

/* pay attention to getaddrinfo function. It creates addrinfo structure and it needs
 * to get port number as C-string (not as a number -- it leads to segfault) and it
 * also needs some additional options which are written in struct addrinfo hints.
 * addrinfo.ai_family and addrinfo.ai_socktype are obligatory in fact (though it isn't
 * mentioned anywhere) for correct work. Also pay attention to the fact that return codes
 * (of errors) are different in linux and freebsd and some options also may be different.
 * If something goes wrong it's convinient to get info on errors using special function
 * instead of trying to find error codes in sources: * const char *gai_strerror(int errcode);
 * You can find more info with "man getaddrinfo". */

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(addr, int2c_str((int)port, buf), &hints, &hp) != 0)
    {
        sys_call_error("getaddrinfo");
        return U_SOCKET_ERROR;
    }

    if (bind(s, (struct sockaddr *) hp->ai_addr, hp->ai_addrlen) != 0)
    {
        freeaddrinfo(hp);
        sys_call_error("bind");
        return U_SOCKET_ERROR;
    }

    freeaddrinfo(hp);
    return 0;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int uconnect_tcp(USOCKET s, unsigned short port, const char *hostname, sys_call_error_fun fun)
{
    struct addrinfo hints, *hp;
    /* 8 is enough for c-str for any port (and yes, 5 is not enough :)) */
    char buf[8];

    /*!TODO !FIXME  In new Sedna release there would be new mechanism of starting processes -- this
    check should be there   */
    const char * dest;
    const char * localhost = "localhost";
    if (strcmp (hostname, "0.0.0.0") == 0) {
        dest = localhost;
    } else {
        dest = hostname;
    }

    /* pay attention to getaddrinfo function. It creates addrinfo structure and it needs
     * to get port number as C-string (not as a number -- it leads to segfault) and it
     * also needs some additional options which are written in struct addrinfo hints.
     * addrinfo.ai_family and addrinfo.ai_socktype are obligatory in fact (though it isn't
     * mentioned anywhere) for correct work. Also pay attention to the fact that return codes
     * (of errors) are different in linux and freebsd and some options also may be different.
     * If something goes wrong it's convinient to get info on errors using special function
     * instead of trying to find error codes in sources: * const char *gai_strerror(int errcode);
     * You can find more info with "man getaddrinfo". */

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(dest, int2c_str((int) port, buf), &hints, &hp) != 0)
    {
        sys_call_error("getaddrinfo");
        return U_SOCKET_ERROR;
    }

    if (connect(s, (struct sockaddr *) hp->ai_addr, hp->ai_addrlen) != 0)
    {
        sys_call_error("connect");
        freeaddrinfo(hp);
        return U_SOCKET_ERROR;
    }
    freeaddrinfo(hp);
    return 0;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int usetsockopt(USOCKET s, int level, int optname, const void* optval, unsigned int optlen, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = setsockopt(s, level, optname, (const char*)optval, optlen);
#else
    int res = setsockopt(s, level, optname, optval, optlen);
#endif
    if (res == U_SOCKET_ERROR) sys_call_error("setsockopt");
    return res;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int ugetsockopt(USOCKET s, int level, int optname, void* optval, unsigned int optlen, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = getsockopt(s, level, optname, (char*)optval, &optlen);
#else
    int res = getsockopt(s, level, optname, optval, &optlen);
#endif
    if (res == U_SOCKET_ERROR) sys_call_error("getsockopt");
    return res;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int ulisten(USOCKET s, int backlog, sys_call_error_fun fun)
{
    int res = listen(s, backlog);
    if (res == U_SOCKET_ERROR) sys_call_error("listen");
    return res;
}

/* returns U_INVALID_SOCKET if failed */
USOCKET uaccept(USOCKET s, sys_call_error_fun fun)
{
#ifdef _WIN32
    int commonlen;
#else
    unsigned int commonlen;
#endif
    int res = 0, param = 1;
    struct sockaddr_in commonaddr;
    USOCKET socknew;

    memset(&commonaddr, 0, sizeof commonaddr);
    commonlen = sizeof commonaddr;
    socknew = accept(s, (struct sockaddr *) &commonaddr, &commonlen);
    if (socknew == U_INVALID_SOCKET)
    {
        sys_call_error("accept");
        return U_INVALID_SOCKET;
    }
#if defined(DARWIN)  /// Under DARWIN this is the only way not to get damn SIGPIPE!
    res = setsockopt(socknew, SOL_SOCKET, SO_NOSIGPIPE, &param, sizeof(int));
    if(-1 == res)
    {
        sys_call_error("setsockopt");
        close(socknew);
        return U_INVALID_SOCKET;
    }
#endif /* DARWIN */
    return socknew;
}

/* return value indicates number of bytes received
   returns zero if connection was gracefully closed
   returns U_SOCKET_ERROR in the case of error */
int urecv(USOCKET s, char *buf, size_t len, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res_len = recv(s, buf, (int)len, 0);
    if (res_len == U_SOCKET_ERROR) sys_call_error("recv");
    return res_len;
#else
    int res_len;

    while (1)
    {
        res_len = recv(s, buf, len, 0);

        if (res_len == U_SOCKET_ERROR)
            if (errno == EINTR)
                continue;
            else
            {
                sys_call_error("recv");
                return U_SOCKET_ERROR;
            }
        else
            return res_len;
    }
#endif
}

/* return value indicates number of bytes send
   returns U_SOCKET_ERROR in the case of error  */
int usend(USOCKET s, const char *buf, size_t len, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res_len;
    res_len = send(s, buf, (int)len, 0);
    if (res_len == U_SOCKET_ERROR)
    {
        sys_call_error("send");
        return U_SOCKET_ERROR;
    }

    return res_len;
#else
    int res_len;

    while (1)
    {
        res_len = send(s, buf, len, U_MSG_NOSIGNAL);
        if (res_len == U_SOCKET_ERROR)
            if (errno == EINTR)
                continue;
            else
            {
                sys_call_error("send");
                return U_SOCKET_ERROR;
            }
        else
            return res_len;
    }
#endif
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int uclose_socket(USOCKET s, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = closesocket(s);
#else
    int res = close(s);
#endif
    if (res == U_SOCKET_ERROR) sys_call_error("closesocket");
    return res;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int ushutdown_close_socket(USOCKET s, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = shutdown(s, SD_BOTH);
    if (res != 0)
    {
       sys_call_error("shutdown");
       return U_SOCKET_ERROR;
    }
    res = closesocket(s);
#else
    int res = shutdown(s, SHUT_RDWR);
    if (res != 0)
    {
       if(errno != ENOTCONN)
       {
           sys_call_error("shutdown");
           return U_SOCKET_ERROR;
       }
    }
    res = close(s);
#endif
    if (res == U_SOCKET_ERROR) sys_call_error("closesocket");
    return res;
}

/* returns zero if succeeded
   returns U_SOCKET_ERROR if failed */
int ushutdown_socket(USOCKET s, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = shutdown(s, SD_BOTH);
    if (res != 0)
    {
       sys_call_error("shutdown");
       return U_SOCKET_ERROR;
    }
    return res;
#else
    int res = shutdown(s, SHUT_RDWR);
    if (res != 0)
    {
       if(errno != ENOTCONN)
       {
           sys_call_error("shutdown");
           return U_SOCKET_ERROR;
       }
    }
    return res;
#endif
}

/* returns 1 (number of sockets ready to recv) if there is data pending in network connection
   returns 0 if timeout
   returns U_SOCKET_ERROR if failed */
int uselect_read(USOCKET s, struct timeval *timeout, sys_call_error_fun fun)
{
#ifdef _WIN32
    fd_set socks;
    int res = 0;

    FD_ZERO(&socks);
    FD_SET(s, &socks);
    res = select(1, &socks, (fd_set *) NULL, (fd_set *) NULL, timeout);
    if (res == U_SOCKET_ERROR) sys_call_error("select");
    return res;
#else
    fd_set socks;
    int res = 0;

    FD_ZERO(&socks);
    FD_SET(s, &socks);

    while (1)
    {
        res = select(s + 1, &socks, (fd_set *) NULL, (fd_set *) NULL, timeout);

        if (res == U_SOCKET_ERROR)
            if (errno == EINTR)
                continue;
            else
            {
                sys_call_error("select");
                return U_SOCKET_ERROR;
            }
        else
            return res;
    }
#endif
}

/* returns number of sockets ready to recv if there is data pending in network connection
		(s is changed and contains result)
   returns 0 if timeout
   returns U_SOCKET_ERROR if failed */
int uselect_read_arr(U_SSET *s, USOCKET maxfd, struct timeval *timeout, sys_call_error_fun fun)
{
#ifdef _WIN32
    int res = 0;

    res = select(1, s, (fd_set *) NULL, (fd_set *) NULL, timeout);
    if (res == U_SOCKET_ERROR) sys_call_error("select");

    return res;
#else
	int res = 0;

    while (1)
    {
        res = select(maxfd + 1, s, (fd_set *) NULL, (fd_set *) NULL, timeout);

        if (res == U_SOCKET_ERROR)
            if (errno == EINTR)
			{
                continue;
            }
            else
            {
                sys_call_error("select");
                return U_SOCKET_ERROR;
            }
        else
        	return res;
    }

#endif
}

/* retrieves the last socket error description */
const char *usocket_error_translator()
{
#ifdef _WIN32
    static char se_socket_error_buf[1024];

    if (!FormatMessage(
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        WSAGetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)se_socket_error_buf,
        1024,
        NULL ))
    {
        strcpy(se_socket_error_buf, "unknown error");
    }
    return se_socket_error_buf;
#else
    return strerror(errno);
#endif

}

/*  when connect has failed, utry_connect_again checks if it is reasonable to reconnect
    returns 1 if it is reasonable, zero if it is not */
int utry_connect_again()
{
#ifdef _WIN32
    int sock_error;
    sock_error = WSAGetLastError();
    if ((sock_error == WSAENETUNREACH) || (sock_error == WSAETIMEDOUT))
        return 1;
    else
        return 0;
#else
    int sock_error;
    sock_error = errno;
    if ((sock_error == ENETUNREACH) || (sock_error == ETIMEDOUT))
        return 1;
    else
        return 0;
#endif
}


text:
package org.hl7.fhir.dstu2016may.formats;

/**
 * Used in factory methods for parsers, for requesting a parser of a particular type
 * (see IWorkerContext)
 *
 * @author Grahame
 *
 */
public enum ParserType {
  /**
   * XML as specified in specification
   */
  XML,

  /**
   * JSON as specified in the specification
   */
  JSON,

  /**
   * XHTML - write narrative (generate if necessary). No read
   */
  XHTML,

   /**
   * RDF is not supported yet
   */
  RDF_TURTLE
}


text:
using CodeGenerator.Forms;
using CodeGenerator.Helpers.Project;

namespace CodeGenerator.Helpers
{
    public class FormFactory
    {
        public static ProjectForm CreateProjectForm()
        {
            return new ProjectForm(new ProjectManager());
        }

        public static SelectProjectForm CreateSelectProjectForm()
        {
            return new SelectProjectForm();
        }

        public static GenerateForm CreateGenerateForm()
        {
            return new GenerateForm();
        }

        public static TableObjectForm CreateTableObjectForm()
        {
            return new TableObjectForm();
        }
    }
}


text:
function findVariableNamesInSentences([str]) {
    let variables =[];
    let regex = /\b_([a-zA-Z0-9]+)\b/g;

    let match = regex.exec(str);

    while(match) {
        variables.push(match[1]);
        match = regex.exec(str);
    }

    console.log(variables.join(","));
}


text:
<?php

namespace Orchestra\OrchestraBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Orchestra\OrchestraBundle\Entity\SocialNetworkUser;
use Orchestra\OrchestraBundle\Form\SocialNetworkUserType;

/**
 * SocialNetworkUser controller.
 *
 */
class SocialNetworkUserController extends Controller
{
    /**
     * Lists all SocialNetworkUser entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('OrchestraOrchestraBundle:SocialNetworkUser')->findAll();

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Finds and displays a SocialNetworkUser entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OrchestraOrchestraBundle:SocialNetworkUser')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SocialNetworkUser entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to create a new SocialNetworkUser entity.
     *
     */
    public function newAction()
    {
        $entity = new SocialNetworkUser();
        $form   = $this->createForm(new SocialNetworkUserType(), $entity);

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a new SocialNetworkUser entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new SocialNetworkUser();
        $form = $this->createForm(new SocialNetworkUserType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('social_network_user_show', array('id' => $entity->getId())));
        }

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing SocialNetworkUser entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OrchestraOrchestraBundle:SocialNetworkUser')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SocialNetworkUser entity.');
        }

        $editForm = $this->createForm(new SocialNetworkUserType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing SocialNetworkUser entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OrchestraOrchestraBundle:SocialNetworkUser')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find SocialNetworkUser entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new SocialNetworkUserType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('social_network_user_edit', array('id' => $id)));
        }

        return $this->render('OrchestraOrchestraBundle:SocialNetworkUser:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a SocialNetworkUser entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('OrchestraOrchestraBundle:SocialNetworkUser')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find SocialNetworkUser entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('social_network_user'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
import Task from './task';

/**
 * Batch run tasks.
 * @param {Task[]} tasks - Batch run tasks.
 * @param {...*} params - Parameters for batch tasks.
 * @return {Promise} The tasks runner promise.
 *
 * @example
 * const task = new Task((resolve, reject) => resolve('test'));
 * all([task, task, task]).then(result => console.log(result)); // ['test', 'test', 'test']
 */
export default (tasks, ...params) => {
  if(!Array.isArray(tasks)) {
    throw new TypeError();
  }

  if(tasks.some(task => !(task instanceof Task))) {
    throw new TypeError();
  }

  return Promise.all(tasks.map(task => task.run(...params)));
};


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

namespace GamePad.Properties {
    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()]
    internal class Resources {

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

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

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

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GamePad.Properties.Resources", typeof(Resources).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)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayDown {
            get {
                object obj = ResourceManager.GetObject("_8WayDown", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayDownLeft {
            get {
                object obj = ResourceManager.GetObject("_8WayDownLeft", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayDownRight {
            get {
                object obj = ResourceManager.GetObject("_8WayDownRight", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayLeft {
            get {
                object obj = ResourceManager.GetObject("_8WayLeft", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayRight {
            get {
                object obj = ResourceManager.GetObject("_8WayRight", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayUp {
            get {
                object obj = ResourceManager.GetObject("_8WayUp", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayUpLeft {
            get {
                object obj = ResourceManager.GetObject("_8WayUpLeft", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _8WayUpRight {
            get {
                object obj = ResourceManager.GetObject("_8WayUpRight", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap a {
            get {
                object obj = ResourceManager.GetObject("a", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap b {
            get {
                object obj = ResourceManager.GetObject("b", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap blankimage {
            get {
                object obj = ResourceManager.GetObject("blankimage", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap down {
            get {
                object obj = ResourceManager.GetObject("down", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap downLeft {
            get {
                object obj = ResourceManager.GetObject("downLeft", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap downRight {
            get {
                object obj = ResourceManager.GetObject("downRight", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap ESC {
            get {
                object obj = ResourceManager.GetObject("ESC", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap EXIT {
            get {
                object obj = ResourceManager.GetObject("EXIT", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap EXIT2 {
            get {
                object obj = ResourceManager.GetObject("EXIT2", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap fullscreen {
            get {
                object obj = ResourceManager.GetObject("fullscreen", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap HotKey1 {
            get {
                object obj = ResourceManager.GetObject("HotKey1", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap HotKey2 {
            get {
                object obj = ResourceManager.GetObject("HotKey2", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap HotKey3 {
            get {
                object obj = ResourceManager.GetObject("HotKey3", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap HotKeyToggle {
            get {
                object obj = ResourceManager.GetObject("HotKeyToggle", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
        /// </summary>
        internal static System.Drawing.Icon icon {
            get {
                object obj = ResourceManager.GetObject("icon", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap left {
            get {
                object obj = ResourceManager.GetObject("left", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap menu {
            get {
                object obj = ResourceManager.GetObject("menu", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap Options {
            get {
                object obj = ResourceManager.GetObject("Options", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap right {
            get {
                object obj = ResourceManager.GetObject("right", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap select {
            get {
                object obj = ResourceManager.GetObject("select", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap SendKeyMode {
            get {
                object obj = ResourceManager.GetObject("SendKeyMode", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap start {
            get {
                object obj = ResourceManager.GetObject("start", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap up {
            get {
                object obj = ResourceManager.GetObject("up", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap upLeft {
            get {
                object obj = ResourceManager.GetObject("upLeft", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap upRight {
            get {
                object obj = ResourceManager.GetObject("upRight", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to 0x12.
        /// </summary>
        internal static string VK_TEST {
            get {
                return ResourceManager.GetString("VK_TEST", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap x {
            get {
                object obj = ResourceManager.GetObject("x", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap y {
            get {
                object obj = ResourceManager.GetObject("y", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}


text:
package archive

import (
	"context"
	"time"

	"go-common/app/interface/main/creative/model/archive"
	"go-common/app/interface/main/creative/model/game"
	"go-common/app/interface/main/creative/model/order"
	"go-common/app/service/main/archive/api"
	arcMdl "go-common/app/service/main/archive/model/archive"
	"go-common/library/ecode"
	"go-common/library/log"
	xtime "go-common/library/time"
)

// ExecuteOrders fn
func (s *Service) ExecuteOrders(c context.Context, mid int64, ip string) (orders []*order.Order, err error) {
	if orders, err = s.order.ExecuteOrders(c, mid, ip); err != nil {
		log.Error("s.order.ExecuteOrders mid(%d) err(%v)", mid, err)
		return
	}
	return
}

// Oasis for orders.
func (s *Service) Oasis(c context.Context, mid int64, ip string) (oa *order.Oasis, err error) {
	if oa, err = s.order.Oasis(c, mid, ip); err != nil {
		log.Error("s.order.Oasis mid(%d) err(%v)", mid, err)
		return
	}
	return
}

// ArcOrderGameInfo fn
// platform 1:android;2:ios
func (s *Service) ArcOrderGameInfo(c context.Context, aid int64, platform int, ip string) (gameInfo *game.Info, err error) {
	var (
		orderID, gameBaseID int64
		beginDate           xtime.Time
	)
	if orderID, _, gameBaseID, err = s.order.OrderByAid(c, aid); err != nil {
		log.Error("s.order.OrderByAid aid(%d)|ip(%s)|err(%+v)", aid, ip, err)
		err = ecode.NothingFound
		return
	}
	if gameBaseID == 0 || orderID == 0 {
		log.Error("s.order.OrderByAid aid(%d)|ip(%s) not found", aid, ip)
		err = ecode.NothingFound
		return
	}
	if gameInfo, err = s.game.Info(c, gameBaseID, platform, ip); err != nil {
		log.Error("s.game.Info aid(%d)|orderID(%d)|gameBaseID(%d)|ip(%s)|err(%+v)", aid, orderID, gameBaseID, ip, err)
		err = ecode.NothingFound
		return
	}
	if !gameInfo.IsOnline {
		log.Error("s.game.Info IsOnline is false aid(%d)|orderID(%d)|gameBaseID(%d)|ip(%s)|err(%+v)", aid, orderID, gameBaseID, ip, err)
		err = ecode.NothingFound
		return
	}
	if beginDate, err = s.order.LaunchTime(c, orderID, ip); err != nil {
		log.Error("s.order.LaunchTime aid(%d)|orderID(%d)|gameBaseID(%d)|ip(%s)|err(%+v)", aid, orderID, gameBaseID, ip, err)
		return
	}
	gameInfo.BeginDate = beginDate
	gameInfo.BaseID = gameBaseID
	return
}

// ArcCommercial fn
func (s *Service) ArcCommercial(c context.Context, aid int64, ip string) (cm *archive.Commercial, err error) {
	var (
		orderID, gameBaseID int64
		beginDate           xtime.Time
		a                   *api.Arc
		cache               = true
	)
	// try cache
	if cm, err = s.arc.ArcCMCache(c, aid); err != nil {
		err = nil
		cache = false
	} else if cm != nil {
		s.pCacheHit.Incr("cmarc_cache")
		cache = false
		return
	}
	s.pCacheMiss.Incr("cmarc_cache")
	// get archive
	a, err = s.arc.Archive(c, aid, ip)
	if err != nil {
		log.Error("arcCommercial aid(%d)|ip(%s)|err(%+v)", aid, ip, err)
		err = ecode.NothingFound
		return
	}
	if a == nil {
		log.Error("arcCommercial nil aid(%d)|ip(%s)|err(%+v)", aid, ip, err)
		err = ecode.NothingFound
		return
	}
	// add cache
	defer func() {
		if cache {
			s.addCache(func() {
				if cm == nil {
					cm = &archive.Commercial{}
				}
				s.arc.AddArcCMCache(context.Background(), aid, cm)
			})
		}
	}()
	// check order or porder
	if a.OrderID > 0 {
		// order
		if orderID, _, gameBaseID, err = s.order.OrderByAid(c, aid); err != nil {
			log.Error("arcCommercial aid(%d)|ip(%s)|error(%+v)", aid, ip, err)
			err = ecode.NothingFound
			return
		}
		if gameBaseID == 0 || orderID == 0 {
			log.Error("arcCommercial aid(%d)|ip(%s) not found", aid, ip)
			err = ecode.NothingFound
			return
		}
		if beginDate, err = s.order.LaunchTime(c, orderID, ip); err != nil {
			log.Error("arcCommercial get launch time failed. aid(%d)|orderID(%d)|gameBaseID(%d)|ip(%s)|error(%+v)", aid, orderID, gameBaseID, ip, err)
			return
		}
		// check time
		if time.Now().Unix() < beginDate.Time().Unix() {
			log.Error("arcCommercial launch time invalid. aid(%d)|orderID(%d)|gameBaseID(%d) beginDate(%+v)", aid, orderID, gameBaseID, beginDate)
			err = ecode.NothingFound
			return
		}
		cm = &archive.Commercial{}
		cm.AID = a.Aid
		cm.OrderID = orderID
		cm.GameID = gameBaseID
	} else if a.AttrVal(arcMdl.AttrBitIsPorder) == arcMdl.AttrYes {
		// porder
		var pd *archive.Porder
		if pd, err = s.arc.Porder(c, aid); err != nil {
			log.Error("arcCommercial aid(%d) error(%v)", aid, err)
			err = ecode.NothingFound
			return
		}
		if pd == nil {
			log.Error("arcCommercial porder not show aid(%d)", aid)
			err = ecode.CreativePorderForbidShowFront
			return
		}
		cm = &archive.Commercial{}
		cm.AID = a.Aid
		cm.POrderID = pd.ID
		cm.GameID = pd.BrandID
	} else {
		log.Error("arcCommercial is not commercial. aid(%d)|ip(%s)|", aid, ip)
		err = ecode.NothingFound
		return
	}
	return
}

// UpValidate func
func (s *Service) UpValidate(c context.Context, mid int64, ip string) (uv *order.UpValidate, err error) {
	if uv, err = s.order.UpValidate(c, mid, ip); err != nil {
		log.Error("s.order.UpValidate mid(%d)|ip(%s)|err(%v)", mid, ip, err)
	}
	return
}


text:
package codeu.chat.client.commandline;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import codeu.chat.client.core.Context;
import codeu.chat.client.core.ConversationContext;
import codeu.chat.client.core.MessageContext;
import codeu.chat.client.core.UserContext;

import codeu.chat.common.User;
import codeu.chat.util.Uuid;

import codeu.chat.util.Tokenizer;
import codeu.chat.util.Time;

import codeu.chat.common.ConversationHeader;

public final class Chat {

  // PANELS
  //
  // We are going to use a stack of panels to track where in the application
  // we are. The command will always be routed to the panel at the top of the
  // stack. When a command wants to go to another panel, it will add a new
  // panel to the top of the stack. When a command wants to go to the previous
  // panel all it needs to do is pop the top panel.
  private final Stack<Panel> panels = new Stack<>();
  private final Context context;

  public Chat(Context context) {
    this.panels.push(createRootPanel(context));
    this.context = context;
  }

  // HANDLE COMMAND
  //
  // Take a single line of input and parse a command from it. If the system
  // is willing to take another command, the function will return true. If
  // the system wants to exit, the function will return false.
  //
  public boolean handleCommand(String line) {
    final Tokenizer tokens;
    final String command;

    try {
      tokens = new Tokenizer(line.trim());
      command = tokens.hasNext() ? tokens.next() : "";
    }
    catch (IllegalArgumentException e) {
      // Catch any misformatting or unclear input here
      // and still continue processing future commands
      System.out.println("Misformatted Input: " + e.getMessage());
      return true;
    }

    // Because "exit", "back", and "version" are applicable to every panel, handle
    // those commands here to avoid having to implement them for each
    // panel.
    if ("exit".equals(command)) {
      // The user does not want to process any more commands
      return false;
    }

    // Do not allow the root panel to be removed.
    if ("back".equals(command) && panels.size() > 1) {
      panels.pop();
      return true;
    }

    // Returns the version of the server
    if ("version".equals(command)) {
      System.out.println("This is server version # " + context.Version());
      return true;
    }

    // Returns how long the server has been running
    if ("uptime".equals(command)) {
      System.out.println("Server has been running for " + Time.formatTimeString(context.Uptime()));
      return true;
    }

    if (panels.peek().handleCommand(command, tokens)) {
      // the command was handled
      return true;
    }

    // If we get to here it means that the command was not correctly handled
    // so we should let the user know. Still return true as we want to continue
    // processing future commands.
    System.out.println("ERROR: Unsupported command");
    return true;
  }

  // CREATE ROOT PANEL
  //
  // Create a panel for the root of the application. Root in this context means
  // the first panel and the only panel that should always be at the bottom of
  // the panels stack.
  //
  // The root panel is for commands that require no specific contextual information.
  // This is before a user has signed in. Most commands handled by the root panel
  // will be user selection focused.
  //
  private Panel createRootPanel(final Context context) {

    final Panel panel = new Panel();

    // HELP
    //
    // Add a command to print a list of all commands and their description when
    // the user for "help" while on the root panel.
    //
    panel.register("help", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("ROOT MODE");
        System.out.println("  u-list");
        System.out.println("    List all users.");
        System.out.println("  u-add <name>");
        System.out.println("    Add a new user with the given name.");
        System.out.println("  u-sign-in <name>");
        System.out.println("    Sign in as the user with the given name.");
        System.out.println("  uptime");
        System.out.println("    Display how long server has been running.");
        System.out.println("  version");
        System.out.println("    Display server version number.");
        System.out.println("  exit");
        System.out.println("    Exit the program.");
      }
    });

    // U-LIST (user list)
    //
    // Add a command to print all users registered on the server when the user
    // enters "u-list" while on the root panel.
    //
    panel.register("u-list", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        for (final UserContext user : context.allUsers()) {
          System.out.format(
              "USER %s (UUID:%s)\n",
              user.user.name,
              user.user.id);
        }
      }
    });

    // U-ADD (add user)
    //
    // Add a command to add and sign-in as a new user when the user enters
    // "u-add" while on the root panel.
    //
    panel.register("u-add", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (name.length() > 0) {
          if (context.create(name) == null) {
            System.out.println("ERROR: Failed to create new user");
          }
        } else {
          System.out.println("ERROR: Missing <username>");
        }
      }
    });

    // U-SIGN-IN (sign in user)
    //
    // Add a command to sign-in as a user when the user enters "u-sign-in"
    // while on the root panel.
    //
    panel.register("u-sign-in", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (name.length() > 0) {
          final UserContext user = findUser(name);
          if (user == null) {
            System.out.format("ERROR: Failed to sign in as '%s'\n", name);
          } else {
            panels.push(createUserPanel(user));
          }
        } else {
          System.out.println("ERROR: Missing <username>");
        }
      }

      // Find the first user with the given name and return a user context
      // for that user. If no user is found, the function will return null.
      private UserContext findUser(String name) {
        for (final UserContext user : context.allUsers()) {
          if (user.user.name.equals(name)) {
            return user;
          }
        }
        return null;
      }
    });

    // Now that the panel has all its commands registered, return the panel
    // so that it can be used.
    return panel;
  }

  private Panel createUserPanel(final UserContext user) {

    final Panel panel = new Panel();

    // HELP
    //
    // Add a command that will print a list of all commands and their
    // descriptions when the user enters "help" while on the user panel.
    //
    panel.register("help", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("USER MODE");
        System.out.println("  c-list");
        System.out.println("    List all conversations that the current user can interact with.");
        System.out.println("  c-add <title>");
        System.out.println("    Add a new conversation with the given title and join it as the current user.");
        System.out.println("  c-join <title>");
        System.out.println("    Join the conversation as the current user.");
        System.out.println("  u-follow <name>");
        System.out.println("    Follow a user to get updates on new user activity.");
        System.out.println("  u-unfollow <name>");
        System.out.println("    Unfollow a user to stop updates from user activity.");
        System.out.println("  c-follow <title>");
        System.out.println("    Follow a conversation to get updates on new messages.");
        System.out.println("  c-unfollow <title>");
        System.out.println("    Unfollow a conversation to stop updates from conversation.");
        System.out.println("  status-update");
        System.out.println("    Retrieve updates on users and conversations current user is following.");
        System.out.println("  info");
        System.out.println("    Display all info for the current user.");
        System.out.println("  uptime");
        System.out.println("    Display how long server has been running.");
        System.out.println("  version");
        System.out.println("    Display server version number.");
        System.out.println("  back");
        System.out.println("    Go back to ROOT MODE.");
        System.out.println("  exit");
        System.out.println("    Exit the program.");
      }
    });

    // C-LIST (list conversations)
    //
    // Add a command that will print all conversations when the user enters
    // "c-list" while on the user panel.
    //
    panel.register("c-list", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        for (final ConversationContext conversation : user.conversations()) {
          System.out.format(
              "CONVERSATION %s (UUID:%s)\n",
              conversation.conversation.title,
              conversation.conversation.id);
        }
      }
    });

    // C-ADD (add conversation)
    //
    // Add a command that will create and join a new conversation when the user
    // enters "c-add" while on the user panel.
    //
    panel.register("c-add", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (name.length() > 0) {
          final ConversationContext conversation = user.start(name);
          if (conversation == null) {
            System.out.println("ERROR: Failed to create new conversation");
          } else {
            panels.push(createConversationPanel(conversation));
          }
        } else {
          System.out.println("ERROR: Missing <title>");
        }
      }
    });

    // STATUS-UPDATE (status update)
    //
    // Add a command that will give users information on items they are following.
    //
    panel.register("status-update", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("Status Updates!");
        System.out.print(user.statusUpdate());
      }
    });

    // U-FOLLOW (follow user)
    //
    // Add a command that will follow user activity when the user enters
    // "u-follow" while on the user panel.
    //
    panel.register("u-follow", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
          return;
        }
        else if (name.length() < 0) {
          System.out.println("ERROR: Missing <username>");
          return;
        }
        else if (findUser(name) == null) {
          System.out.format("ERROR: Failed to follow '%s'\n", name);
          return;
        }

        final User userToBeFollowed = findUser(name);
        user.followUser(userToBeFollowed);
      }
      // Find the first user with the given name and return a user context
      // for that user. If no user is found, the function will return null.
      private User findUser(String name) {
        for (final UserContext context : context.allUsers()) {
          if (context.user.name.equals(name)) {
            return context.user;
          }
        }
        return null;
      }
    });

    // U-UNFOLLOW (follow user)
    //
    // Add a command that will unfollow user activity when the user enters
    // "u-unfollow" while on the user panel.
    //
    panel.register("u-unfollow", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
          return;
        }
        else if (name.length() < 0) {
          System.out.println("ERROR: Missing <username>");
          return;
        }
        else if (findUser(name) == null) {
          System.out.format("ERROR: Failed to follow '%s'\n", name);
          return;
        }

        final User userToBeUnfollowed = findUser(name);
        user.followUser(userToBeUnfollowed);
      }

      // Find the first user with the given name and return a user context
      // for that user. If no user is found, the function will return null.
      private User findUser(String name) {
        // TODO: fix the round trip method for an efficient lookup method
        for (final UserContext context : context.allUsers()) {
          if (context.user.name.equals(name)) {
            return context.user;
          }
        }
        return null;
      }
    });

    // C-UNFOLLOW (unfollow conversation)
    //
    // Add a command that will unfollow a conversation when the user enters
    // "c-unfollow" while on the user panel.
    //
    panel.register("c-unfollow", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
          return;
        }
        else if (name.length() < 0) {
          System.out.println("ERROR: Missing <title>");
          return;
        }
        else if (find(name) == null) {
          System.out.format("ERROR: No conversation with name '%s'\n", name);
          return;
        }

        final Uuid conversationID = find(name);
        user.unfollowConversation(conversationID);
      }

      // Find the first conversation with the given name and return its context.
      // If no conversation has the given name, this will return null.
      private Uuid find(String title) {
        for (final ConversationContext context : user.conversations()) {
          if (title.equals(context.conversation.title)) {
            return context.conversation.id;
          }
        }
        return null;
      }
    });

    // C-FOLLOW (follow conversation)
    //
    // Add a command that will follow a conversation when the user enters
    // "c-follow" while on the user panel.
    //
    panel.register("c-follow", new Panel.Command() {
      // TODO: add function to conversation to remove needed paramenter
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
          return;
        }
        else if (name.length() < 0) {
          System.out.println("ERROR: Missing <title>");
          return;
        }
        else if (find(name) == null) {
          System.out.format("ERROR: No conversation with name '%s'\n", name);
          return;
        }

        final Uuid conversationID = find(name);
        user.followConversation(conversationID);
      }

      // Find the first conversation with the given name and return its context.
      // If no conversation has the given name, this will return null.
      private Uuid find(String title) {
        for (final ConversationContext context : user.conversations()) {
          if (title.equals(context.conversation.title)) {
            return context.conversation.id;
          }
        }
        return null;
      }
    });

    // C-JOIN (join conversation)
    //
    // Add a command that will joing a conversation when the user enters
    // "c-join" while on the user panel.
    //
    panel.register("c-join", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (name.length() > 0) {
          final ConversationContext conversation = find(name);
          if (conversation == null) {
            System.out.format("ERROR: No conversation with name '%s'\n", name);
          } else {
            panels.push(createConversationPanel(conversation));
          }
        } else {
          System.out.println("ERROR: Missing <title>");
        }
      }

      // Find the first conversation with the given name and return its context.
      // If no conversation has the given name, this will return null.
      private ConversationContext find(String title) {
        for (final ConversationContext conversation : user.conversations()) {
          if (title.equals(conversation.conversation.title)) {
            return conversation;
          }
        }
        return null;
      }
    });

    // INFO
    //
    // Add a command that will print info about the current context when the
    // user enters "info" while on the user panel.
    //
    panel.register("info", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("User Info:");
        System.out.format("  Name : %s\n", user.user.name);
        System.out.format("  Id   : UUID:%s\n", user.user.id);
      }
    });

    // Now that the panel has all its commands registered, return the panel
    // so that it can be used.
    return panel;
  }

  private Panel createConversationPanel(final ConversationContext conversation) {

    final Panel panel = new Panel();

    // HELP
    //
    // Add a command that will print all the commands and their descriptions
    // when the user enters "help" while on the conversation panel.
    //
    panel.register("help", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("USER MODE");
        System.out.println("  m-list");
        System.out.println("    List all messages in the current conversation.");
        System.out.println("  m-add <message>");
        System.out.println("    Add a new message to the current conversation as the current user.");
        System.out.println("  toggle-permission <user> <permission> ...");
        System.out.println("    Toggle the permissions (member/admin/owner) of other users.");
        System.out.println("  add-bot <name>");
        System.out.println("    Add a bot to the conversation for some fun!");
        System.out.println("  info");
        System.out.println("    Display all info about the current conversation.");
        System.out.println("  uptime");
        System.out.println("    Display how long server has been running.");
        System.out.println("  version");
        System.out.println("    Display server version number.");
        System.out.println("  back");
        System.out.println("    Go back to USER MODE.");
        System.out.println("  exit");
        System.out.println("    Exit the program.");
      }
    });

    // ADD-BOT (adds bots)
    //
    // Add a command that will allow an interactive bot into the conversation!
    //
    panel.register("add-bot", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (name.length() > 0) {
          if (conversation.createBot(name) == null) {
            System.out.println("ERROR: Failed to create new bot");
          }
        } else {
          System.out.println("ERROR: Missing <username>");
        }
      }
    });

    // M-LIST (list messages)
    //
    // Add a command to print all messages in the current conversation when the
    // user enters "m-list" while on the conversation panel.
    //
    panel.register("m-list", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        if (conversation.getStatus().length() > 0) {
          System.out.println(conversation.getStatus());
          return;
        }

        System.out.println("--- start of conversation ---");
        try {
          for (MessageContext message = conversation.firstMessage();
                              message != null;
                              message = message.next()) {
            System.out.println();
            System.out.format("USER : %s\n", message.message.author);
            System.out.format("SENT : %s\n", message.message.creation);
            System.out.println();
            System.out.println(message.message.content);
            System.out.println();
          }
        }
        catch (Exception e) {
          System.out.println("You do not have permission to view this content");
        }
          System.out.println("---  end of conversation  ---");
        }
    });

    // M-ADD (add message)
    //
    // Add a command to add a new message to the current conversation when the
    // user enters "m-add" while on the conversation panel.
    //
    panel.register("m-add", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        if (conversation.getStatus().length() > 0) {
          System.out.println(conversation.getStatus());
          return;
        }

        final String message = args.hasNext() ? args.next().trim() : "";
        if (args.hasNext()) {
          System.out.println("ERROR: Too many arguments for command");
        }
        else if (message.length() > 0) {
          try {
            conversation.add(message);
          }
          catch (Exception ex) {
            System.out.println("You do not have permission to add new messages");
          }
        } else {
          System.out.println("ERROR: Messages must contain text");
        }
      }
    });

    // INFO
    //
    // Add a command to print info about the current conversation when the user
    // enters "info" while on the conversation panel.
    //
    panel.register("info", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        System.out.println("Conversation Info:");
        System.out.format("  Title : %s\n", conversation.conversation.title);
        System.out.format("  Id    : UUID:%s\n", conversation.conversation.id);
        System.out.format("  Owner : %s\n", conversation.conversation.owner);
      }
    });

    // TOGGLE-PERMISSION (user's permission to be changed) (permission)
    //
    // Add a command to allow authorized users to toggle permissions of other users
    //
    panel.register("toggle-permission", new Panel.Command() {
      @Override
      public void invoke(Tokenizer args) {
        final String name = args.hasNext() ? args.next().trim() : "";

        int permission = 0;

        while (args.hasNext()) {
          final String permissionString = args.hasNext() ? args.next().trim().toLowerCase() : "";
          switch (permissionString) {
            case "admin":  permission = permission ^ ConversationHeader.ADMIN_PERM;
                           break;
            case "member": permission = permission ^ ConversationHeader.MEMBER_PERM;
                           break;
            default:       System.out.println("ERROR: input is not a valid condition"); return;
          }
        }

        if (name.length() < 0) {
          System.out.println("ERROR: Missing argument");
          return;
        }
        else if (findUser(name) == null) {
          System.out.format("ERROR: Failed to find user '%s'\n", name);
          return;
        }

        final User permissionChangedUser = findUser(name);
        int permissionValue = conversation.togglePermission(permissionChangedUser.id, permission, conversation.conversation.id);
        if (permissionValue == -1) {
          System.out.println("You do not have permission to change other users.");
        }
        else {
          System.out.println(name + "'s status is now:" + conversation.conversation.formatPermission(permissionValue));
        }
      }

      private User findUser(String name) {
        for (final UserContext context : context.allUsers()) {
          if (context.user.name.equals(name)) {
            return context.user;
          }
        }
        return null;
      }
    });

    // Now that the panel has all its commands registered, return the panel
    // so that it can be used.
    return panel;
  }
}