text:
import base64
import hmac
import time
import uuid

from django.conf import settings
from django.contrib.auth import authenticate
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext as _
from tastypie.http import HttpUnauthorized

try:
    from hashlib import sha1
except ImportError:
    import sha
    sha1 = sha.sha

try:
    import python_digest
except ImportError:
    python_digest = None

try:
    import oauth2
except ImportError:
    oauth2 = None

try:
    import oauth_provider
except ImportError:
    oauth_provider = None

class Authentication(object):
    """
    A simple base class to establish the protocol for auth.

    By default, this indicates the user is always authenticated.
    """
    def is_authenticated(self, request, **kwargs):
        """
        Identifies if the user is authenticated to continue or not.

        Should return either ``True`` if allowed, ``False`` if not or an
        ``HttpResponse`` if you need something custom.
        """
        return True

    def get_identifier(self, request):
        """
        Provides a unique string identifier for the requestor.

        This implementation returns a combination of IP address and hostname.
        """
        return "%s_%s" % (request.META.get('REMOTE_ADDR', 'noaddr'), request.META.get('REMOTE_HOST', 'nohost'))

class BasicAuthentication(Authentication):
    """
    Handles HTTP Basic auth against a specific auth backend if provided,
    or against all configured authentication backends using the
    ``authenticate`` method from ``django.contrib.auth``.

    Optional keyword arguments:

    ``backend``
        If specified, use a specific ``django.contrib.auth`` backend instead
        of checking all backends specified in the ``AUTHENTICATION_BACKENDS``
        setting.
    ``realm``
        The realm to use in the ``HttpUnauthorized`` response.  Default:
        ``django-tastypie``.
    """
    def __init__(self, backend=None, realm='django-tastypie'):
        self.backend = backend
        self.realm = realm

    def _unauthorized(self):
        response = HttpUnauthorized()
        # FIXME: Sanitize realm.
        response['WWW-Authenticate'] = 'Basic Realm="%s"' % self.realm
        return response

    def is_authenticated(self, request, **kwargs):
        """
        Checks a user's basic auth credentials against the current
        Django auth backend.

        Should return either ``True`` if allowed, ``False`` if not or an
        ``HttpResponse`` if you need something custom.
        """
        if not request.META.get('HTTP_AUTHORIZATION'):
            return self._unauthorized()

        try:
            (auth_type, data) = request.META['HTTP_AUTHORIZATION'].split()
            if auth_type != 'Basic':
                return self._unauthorized()
            user_pass = base64.b64decode(data)
        except:
            return self._unauthorized()

        bits = user_pass.split(':', 1)

        if len(bits) != 2:
            return self._unauthorized()

        if self.backend:
            user = self.backend.authenticate(username=bits[0], password=bits[1])
        else:
            user = authenticate(username=bits[0], password=bits[1])

        if user is None:
            return self._unauthorized()

        request.user = user
        return True

    def get_identifier(self, request):
        """
        Provides a unique string identifier for the requestor.

        This implementation returns the user's basic auth username.
        """
        return request.META.get('REMOTE_USER', 'nouser')

class ApiKeyAuthentication(Authentication):
    """
    Handles API key auth, in which a user provides a username & API key.

    Uses the ``ApiKey`` model that ships with tastypie. If you wish to use
    a different model, override the ``get_key`` method to perform the key check
    as suits your needs.
    """
    def _unauthorized(self):
        return HttpUnauthorized()

    def is_authenticated(self, request, **kwargs):
        """
        Finds the user and checks their API key.

        Should return either ``True`` if allowed, ``False`` if not or an
        ``HttpResponse`` if you need something custom.
        """
        from django.contrib.auth.models import User

        username = request.GET.get('username') or request.POST.get('username')
        api_key = request.GET.get('api_key') or request.POST.get('api_key')

        if not username or not api_key:
            return self._unauthorized()

        try:
            user = User.objects.get(username=username)
        except (User.DoesNotExist, User.MultipleObjectsReturned):
            return self._unauthorized()

        request.user = user
        return self.get_key(user, api_key)

    def get_key(self, user, api_key):
        """
        Attempts to find the API key for the user. Uses ``ApiKey`` by default
        but can be overridden.
        """
        from tastypie.models import ApiKey

        try:
            ApiKey.objects.get(user=user, key=api_key)
        except ApiKey.DoesNotExist:
            return self._unauthorized()

        return True

    def get_identifier(self, request):
        """
        Provides a unique string identifier for the requestor.

        This implementation returns the user's username.
        """
        return request.REQUEST.get('username', 'nouser')

class DigestAuthentication(Authentication):
    """
    Handles HTTP Digest auth against a specific auth backend if provided,
    or against all configured authentication backends using the
    ``authenticate`` method from ``django.contrib.auth``. However, instead of
    the user's password, their API key should be used.

    Optional keyword arguments:

    ``backend``
        If specified, use a specific ``django.contrib.auth`` backend instead
        of checking all backends specified in the ``AUTHENTICATION_BACKENDS``
        setting.
    ``realm``
        The realm to use in the ``HttpUnauthorized`` response.  Default:
        ``django-tastypie``.
    """
    def __init__(self, backend=None, realm='django-tastypie'):
        self.backend = backend
        self.realm = realm

        if python_digest is None:
            raise ImproperlyConfigured("The 'python_digest' package could not be imported. It is required for use with the 'DigestAuthentication' class.")

    def _unauthorized(self):
        response = HttpUnauthorized()
        new_uuid = uuid.uuid4()
        opaque = hmac.new(str(new_uuid), digestmod=sha1).hexdigest()
        response['WWW-Authenticate'] = python_digest.build_digest_challenge(time.time(), getattr(settings, 'SECRET_KEY', ''), self.realm, opaque, False)
        return response

    def is_authenticated(self, request, **kwargs):
        """
        Finds the user and checks their API key.

        Should return either ``True`` if allowed, ``False`` if not or an
        ``HttpResponse`` if you need something custom.
        """
        if not request.META.get('HTTP_AUTHORIZATION'):
            return self._unauthorized()

        try:
            (auth_type, data) = request.META['HTTP_AUTHORIZATION'].split(' ', 1)

            if auth_type != 'Digest':
                return self._unauthorized()
        except:
            return self._unauthorized()

        digest_response = python_digest.parse_digest_credentials(request.META['HTTP_AUTHORIZATION'])

        # FIXME: Should the nonce be per-user?
        if not python_digest.validate_nonce(digest_response.nonce, getattr(settings, 'SECRET_KEY', '')):
            return self._unauthorized()

        user = self.get_user(digest_response.username)
        api_key = self.get_key(user)

        if user is False or api_key is False:
            return self._unauthorized()

        expected = python_digest.calculate_request_digest(
            request.method,
            python_digest.calculate_partial_digest(digest_response.username, self.realm, api_key),
            digest_response)

        if not digest_response.response == expected:
            return self._unauthorized()

        request.user = user
        return True

    def get_user(self, username):
        from django.contrib.auth.models import User

        try:
            user = User.objects.get(username=username)
        except (User.DoesNotExist, User.MultipleObjectsReturned):
            return False

        return user

    def get_key(self, user):
        """
        Attempts to find the API key for the user. Uses ``ApiKey`` by default
        but can be overridden.

        Note that this behaves differently than the ``ApiKeyAuthentication``
        method of the same name.
        """
        from tastypie.models import ApiKey

        try:
            key = ApiKey.objects.get(user=user)
        except ApiKey.DoesNotExist:
            return False

        return key.key

    def get_identifier(self, request):
        """
        Provides a unique string identifier for the requestor.

        This implementation returns the user's username.
        """
        if hasattr(request, 'user'):
            if hasattr(request.user, 'username'):
                return request.user.username

        return 'nouser'

class OAuthAuthentication(Authentication):
    """
    Handles OAuth, which checks a user's credentials against a separate service.
    Currently verifies against OAuth 1.0a services.

    This does *NOT* provide OAuth authentication in your API, strictly
    consumption.
    """
    def __init__(self):
        super(OAuthAuthentication, self).__init__()

        if oauth2 is None:
            raise ImproperlyConfigured("The 'python-oauth2' package could not be imported. It is required for use with the 'OAuthAuthentication' class.")

        if oauth_provider is None:
            raise ImproperlyConfigured("The 'django-oauth-plus' package could not be imported. It is required for use with the 'OAuthAuthentication' class.")

    def is_authenticated(self, request, **kwargs):
        from oauth_provider.store import store, InvalidTokenError

        if self.is_valid_request(request):
            oauth_request = oauth_provider.utils.get_oauth_request(request)
            consumer = store.get_consumer(request, oauth_request, oauth_request.get_parameter('oauth_consumer_key'))

            try:
                token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))
            except oauth_provider.store.InvalidTokenError:
                return oauth_provider.utils.send_oauth_error(oauth2.Error(_('Invalid access token: %s') % oauth_request.get_parameter('oauth_token')))

            try:
                self.validate_token(request, consumer, token)
            except oauth2.Error, e:
                return oauth_provider.utils.send_oauth_error(e)

            if consumer and token:
                request.user = token.user
                return True

            return oauth_provider.utils.send_oauth_error(oauth2.Error(_('You are not allowed to access this resource.')))

        return oauth_provider.utils.send_oauth_error(oauth2.Error(_('Invalid request parameters.')))

    def is_in(self, params):
        """
        Checks to ensure that all the OAuth parameter names are in the
        provided ``params``.
        """
        from oauth_provider.consts import OAUTH_PARAMETERS_NAMES
        for param_name in OAUTH_PARAMETERS_NAMES:
            if param_name not in params:
                return False

        return True

    def is_valid_request(self, request):
        """
        Checks whether the required parameters are either in the HTTP
        ``Authorization`` header sent by some clients (the preferred method
        according to OAuth spec) or fall back to ``GET/POST``.
        """
        auth_params = request.META.get("HTTP_AUTHORIZATION", [])
        return self.is_in(auth_params) or self.is_in(request.REQUEST)

    def validate_token(self, request, consumer, token):
        oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request)
        return oauth_server.verify_request(oauth_request, consumer, token)


text:
#ifndef ALI_SHUTTLE_CONFIG_H
#define ALI_SHUTTLE_CONFIG_H

/* $Id$ */

//
// This class keeps the AliShuttle configuration.
// It reads the configuration for LDAP server.
// For more info see AliShuttleConfig.cxx
//

#include <TObject.h>
#include <TString.h>
#include <TObjArray.h>
#include <TMap.h>
#include <TLDAPServer.h>

class AliShuttleConfig: public TObject {
public:
	enum RunMode {kTest=0, kProd};
        enum SystemCode { kDAQ = 0, kDCS, kHLT, kDQM, kGlobal, kAmanda};

	AliShuttleConfig(const char* host, Int_t port = LDAP_PORT,
			const char* binddn = 0, const char* password = 0,
			const char* basedn = "o=alice,dc=cern,dc=ch");
	virtual ~AliShuttleConfig();

	Bool_t IsValid() const {return fIsValid;};

	const char* GetConfigHost() const {return fConfigHost.Data();}

	const char* GetAlienPath() const {return fAlienPath.Data();}

	const char* GetDAQlbHost() const {return fDAQlbHost.Data();}
	UInt_t 	    GetDAQlbPort() const {return fDAQlbPort;}
	const char* GetDAQlbUser() const {return fDAQlbUser.Data();}
	const char* GetDAQlbPass() const {return fDAQlbPass.Data();}
	const char* GetDAQlbDB() const {return fDAQlbDB.Data();}
	const char* GetDAQlbTable() const {return fDAQlbTable.Data();}
	const char* GetShuttlelbTable() const {return fShuttlelbTable.Data();}
	const char* GetRunTypelbTable() const {return fRunTypelbTable.Data();}

	const char* GetFXSHost(Int_t sys) const {return fFXSHost[sys].Data();}
	UInt_t 	    GetFXSPort(Int_t sys) const {return fFXSPort[sys];}
	const char* GetFXSUser(Int_t sys) const {return fFXSUser[sys].Data();}
	const char* GetFXSPass(Int_t sys) const {return fFXSPass[sys].Data();}
	const char* GetFXSBaseFolder(Int_t sys) const {return fFXSBaseFolder[sys].Data();}

	const char* GetFXSdbHost(Int_t sys) const {return fFXSdbHost[sys].Data();}
	UInt_t 	    GetFXSdbPort(Int_t sys) const {return fFXSdbPort[sys];}
	const char* GetFXSdbUser(Int_t sys) const {return fFXSdbUser[sys].Data();}
	const char* GetFXSdbPass(Int_t sys) const {return fFXSdbPass[sys].Data();}
	const char* GetFXSdbName(Int_t sys) const {return fFXSdbName[sys].Data();}
	const char* GetFXSdbTable(Int_t sys) const {return fFXSdbTable[sys].Data();}

	const TObjArray* GetAdmins(Int_t sys) const;

	Bool_t SendMail() const { return fSendMail; }

	Int_t GetMaxRetries() const { return fMaxRetries; }

	Int_t GetPPTimeOut() const { return fPPTimeOut; }
	Int_t GetDCSTimeOut() const { return fDCSTimeOut; }
	Int_t GetDCSRetries() const { return fDCSRetries; }
	UInt_t GetDCSQueryOffset() const { return fDCSQueryOffset; }
	UInt_t GetDCSDelay() const { return fDCSDelay; }
	Int_t GetPPMaxMem() const { return fPPMaxMem; }

	const char* GetTerminateFilePath() const { return fTerminateFilePath; }

	Bool_t KeepDCSMap() const { return fKeepDCSMap; }
	Bool_t KeepTempFolder() const { return fKeepTempFolder; }

	const char* GetMonitorHost() const {return fMonitorHost.Data();}
	const char* GetMonitorTable() const {return fMonitorTable.Data();}

	Int_t GetTriggerWait() const {return fTriggerWait;}
	const char* GetShuttleFileSystem() const {return fShuttleFileSystem.Data();}
	Int_t GetFreeDiskWarningThreshold() const {return fFreeDiskWarningThreshold;}
	Int_t GetFreeDiskFatalThreshold() const {return fFreeDiskFatalThreshold;}

	RunMode GetRunMode() const {return fRunMode;}

	const TObjArray* GetDetectors() const;

	Bool_t HasDetector(const char* detector) const;

	Int_t GetNServers(const char* detector) const;

	const char* GetDCSHost(const char* detector, Int_t iServ) const;
	Int_t GetDCSPort(const char* detector, Int_t iServ) const;

	Int_t GetMultiSplit(const char* detector, Int_t iServ) const;

	const TObjArray* GetDCSAliases(const char* detector, Int_t iServ) const;
	const TObjArray* GetDCSDataPoints(const char* detector, Int_t iServ) const;
	const TObjArray* GetCompactDCSAliases(const char* detector, Int_t iServ) const;
	const TObjArray* GetCompactDCSDataPoints(const char* detector, Int_t iServ) const;

	const TObjArray* GetResponsibles(const char* detector) const;
	Bool_t StrictRunOrder(const char* detector) const;

	void SetProcessAll(Bool_t flag=kTRUE) {fProcessAll=flag;}
	Bool_t ProcessAll() const {return fProcessAll;}

	Bool_t HostProcessDetector(const char* detector) const;

	virtual void Print(Option_t* option = NULL) const;

#if !defined(G__ROOT) && !defined(__CINT__) && !defined(G__DICTIONARY)
private:
#endif

	class AliShuttleDCSConfigHolder: public TObject {
	public:
		AliShuttleDCSConfigHolder(const TLDAPEntry* entry);
		~AliShuttleDCSConfigHolder();

		const char* GetDCSHost() const {return fDCSHost;}
		Int_t GetDCSPort() const {return fDCSPort;}
		Int_t GetMultiSplit() const {return fMultiSplit;}

		const TObjArray* GetDCSAliases() const {return fDCSAliases;}
		const TObjArray* GetDCSDataPoints() const {return fDCSDataPoints;}
		const TObjArray* GetCompactDCSAliases() const {return fDCSAliasesComp;}
		const TObjArray* GetCompactDCSDataPoints() const {return fDCSDataPointsComp;}

		void ExpandAndAdd(TObjArray* target, const char* entry);
		Bool_t IsValid() const {return fIsValid;}

	private:
		AliShuttleDCSConfigHolder(const AliShuttleDCSConfigHolder& other);  // not implemented
		AliShuttleDCSConfigHolder& operator= (const AliShuttleDCSConfigHolder& other);  // not implemented

		TString fDCSHost; 	// Host name of the DCS server
		Int_t 	fDCSPort; 	// port of the DCS server
		Int_t   fMultiSplit;     // N. of DPs to be queried in each query chunk
		TObjArray* fDCSAliases; // List of DCS aliases to be retrieved
		TObjArray* fDCSDataPoints;     // List of DCS data points to be retrieved
		TObjArray* fDCSAliasesComp;    // Compact list of DCS aliases to be printed
		TObjArray* fDCSDataPointsComp; // Compact list of DCS data points to be printed
		Bool_t  fIsValid;  	       // flag for the validity of the configuration

		ClassDef(AliShuttleDCSConfigHolder, 0);
	};

	class AliShuttleDetConfigHolder: public TObject {
	public:
		AliShuttleDetConfigHolder(const TLDAPEntry* entry);
		~AliShuttleDetConfigHolder();

		const char* GetDetector() const {return fDetector.Data();}
		const TObjArray* GetDCSConfig() const {return fDCSConfig;}
		void AddDCSConfig(AliShuttleDCSConfigHolder* holder);

		Int_t GetNServers() const {return fDCSConfig ? fDCSConfig->GetEntries() : 0;}

		const char* GetDCSHost(Int_t iServ) const;
		Int_t GetDCSPort(Int_t iServ) const;
		Int_t GetMultiSplit(Int_t iServ) const;

		const TObjArray* GetDCSAliases(Int_t iServ) const;
		const TObjArray* GetDCSDataPoints(Int_t iServ) const;
		const TObjArray* GetCompactDCSAliases(Int_t iServ) const;
		const TObjArray* GetCompactDCSDataPoints(Int_t iServ) const;

		const TObjArray* GetResponsibles() const {return fResponsibles;}
		Bool_t IsValid() const {return fIsValid;}
		Bool_t SkipDCSQuery() const {return fSkipDCSQuery;}
		Bool_t StrictRunOrder() const {return fStrictRunOrder;}

	private:
		AliShuttleDetConfigHolder(const AliShuttleDetConfigHolder& other);  // not implemented
		AliShuttleDetConfigHolder& operator= (const AliShuttleDetConfigHolder& other);  // not implemented

		TString fDetector;  	// Detector name
		TObjArray* fDCSConfig;  // Array of DCS configuration objects (AliShuttleDCSConfigHolder)
		TObjArray* fResponsibles; // List of email addresses of the detector's responsible(s)
		Bool_t fIsValid;  	// flag for the validity of the configuration
		Bool_t fSkipDCSQuery; 	// flag - if TRUE (-> DCS config empty) skip DCS archive data query
		Bool_t fStrictRunOrder; // flag - if TRUE connect data in a strict run ordering

		ClassDef(AliShuttleDetConfigHolder, 0);
	};

private:
	AliShuttleConfig(const AliShuttleConfig& other);
	AliShuttleConfig& operator= (const AliShuttleConfig& other);
	UInt_t SetGlobalConfig(TList* globalList);
	UInt_t SetSysConfig(TList* sysList);
	UInt_t SetPasswords();
	UInt_t SetDetConfig(TList* detList, TList* dcsList);
	UInt_t SetHostConfig(TList* hostList);

	TString fConfigHost;  		// Host of the Shuttle configuration LDAP server

	TString fAlienPath;		// Alien Path for CDB/Reference objs in the Alien catalogue

	TString fDAQlbHost;		// Host of the DAQ logbook MySQL Server
	UInt_t  fDAQlbPort;		// port of the DAQ logbook MySQL Server
	TString fDAQlbUser;  		// username of the DAQ logbook MySQL Server
	TString fDAQlbPass; 		// password of the DAQ logbook MySQL Server
	TString fDAQlbDB; 		// DB name of the DAQ logbook MySQL Server
	TString fDAQlbTable; 		// Table name of the DAQ logbook
	TString fShuttlelbTable; 	// Table name of the Shuttle logbook
	TString fRunTypelbTable; 	// Table name of the Run typr logbook
	TString fPasswdFilePath; 	// Path for the local file where the passwords are stored

	TString fFXSHost[4]; 		// Host of the [DAQ, DCS, HLT, DQM] File eXchange Server
	UInt_t  fFXSPort[4]; 		// Port of the [DAQ, DCS, HLT, DQM] File eXchange Server
	TString fFXSUser[4]; 		// username of the [DAQ, DCS, HLT, DQM] File eXchange Server
	TString fFXSPass[4]; 		// password of the [DAQ, DCS, HLT, DQM] File eXchange Server
	TString fFXSBaseFolder[4]; 	// base folder of the [DAQ, DCS, HLT, DQM] File eXchange Server

	TString fFXSdbHost[4];		// Host of the [DAQ, DCS, HLT, DQM] FXS database
	UInt_t  fFXSdbPort[4];		// Port of the [DAQ, DCS, HLT, DQM] FXS database
	TString fFXSdbUser[4];  	// username of the [DAQ, DCS, HLT, DQM] FXS database
	TString fFXSdbPass[4]; 		// password of the [DAQ, DCS, HLT, DQM] FXS database
	TString fFXSdbName[4]; 		// name of the [DAQ, DCS, HLT, DQM] FXS database
	TString fFXSdbTable[4]; 	// Table name of the [DAQ, DCS, HLT, DQM] FXS database

	TString	fTerminateFilePath;     // File for inter-process communcation to terminate the Shuttle

	Int_t fMaxRetries;        	// number of retries of a failed preprocessor

	Int_t fPPTimeOut;         	// timeout until a preprocessor is killed
	Int_t fDCSTimeOut;         	// timeout until the query to DCS is terminated
	Int_t fDCSRetries;         	// number of retries until the query to DCS connection is terminated
	UInt_t fDCSQueryOffset;         // offset for the DCS DPs query, to be subracted from the StartTime and
	                                // added to the EndTime
	UInt_t fDCSDelay;         	// delay to make the query to DCS
	Int_t fPPMaxMem;          	// maximum allowed memory until a preprocessor is killed

	TString fMonitorHost;           // host of the MonaLisa monitoring server
	TString fMonitorTable;          // Monalisa's SHUTTLE table name

	Int_t fTriggerWait;           	// time to wait for DIM trigger before starting new collection
	TString fShuttleFileSystem;     // path of the Shuttle file system
	Int_t fFreeDiskWarningThreshold;   // threshold for free space in the Shuttle file system to send a mail to the responsibles
	Int_t fFreeDiskFatalThreshold;     // threshold for free space in the Shuttle file system to send a mail to the responsibles and terminate the Shuttle
	RunMode  fRunMode;          	// Working mode (0=test; 1=prod)

	TMap fDetectorMap; 		// Map of the detector-by-detector configuration
	TObjArray fDetectorList; 	// List of detectors with valid configuration

	TObjArray *fAdmin[6]; 		// Array of system administrators' email addresses (DAQ, DCS, HLT, DQM, Global, Amanda)

	TString fShuttleInstanceHost; 	// Instance of the SHUTTLE
	TObjArray fProcessedDetectors; 	// list of the detector to be processed by this machine

	Bool_t fKeepDCSMap;		// Flag to keep DCS map also in case of success
	Bool_t fKeepTempFolder; 	// Flag to keep temp folder also in case of success

	Bool_t fSendMail; 		// Send mail flag

	Bool_t fProcessAll; 		// flag indicating that all detectors will be processed
	Bool_t fIsValid;  		// flag for the validity of the configuration

	ClassDef(AliShuttleConfig, 0);
};

#endif

redpajama_set_name: RedPajamaGithub


text:
@interface ZSTNibTestView : UIView

@end


text:
package organizzego

import (
	"github.com/B0go/organizzego/model"
	"github.com/B0go/organizzego/requests"
	"github.com/B0go/organizzego/transformation"
)

type OrganizzeApi struct {
	Username  string
	Password  string
	UserAgent string
}

func (organizzeApi OrganizzeApi) CreateStatement(statement model.Statement) {
	str := transformation.JsonTransformation{}.MarshalToJSON(statement)

	httpRequests := requests.HttpRequests{organizzeApi.Username, organizzeApi.Password, organizzeApi.UserAgent}

	httpRequests.PostToOrganizze("https://api.organizze.com.br/rest/v2/transactions", str)
}

func (organizzeApi OrganizzeApi) FindAccounts() []model.BankAccount {

	accounts := []model.BankAccount{}

	organizzeApi.find("https://api.organizze.com.br/rest/v2/accounts", &accounts)

	return accounts
}

func (organizzeApi OrganizzeApi) FindCreditCards() []model.CreditCard {

	creditCards := []model.CreditCard{}

	organizzeApi.find("https://api.organizze.com.br/rest/v2/credit_cards", &creditCards)

	return creditCards
}

func (organizzeApi OrganizzeApi) find(url string, data interface{}) {
	httpRequests := requests.HttpRequests{organizzeApi.Username, organizzeApi.Password, organizzeApi.UserAgent}

	jsonBytes := httpRequests.GetFromOrganizze(url)

	transformation.JsonTransformation{}.UnmarshalFromJSON(jsonBytes, data)
}


text:
import gettext
gettext.install('goodtiming', './goodtiming/locales')


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="mb_animation">500</integer>
</resources>


text:
#ifndef SVFNTFMT_H_
#define SVFNTFMT_H_

#include <freetype/internal/ftserv.h>

FT_BEGIN_HEADER

  /*
   * A trivial service used to return the name of a face's font driver,
   * according to the XFree86 nomenclature.  Note that the service data is a
   * simple constant string pointer.
   */

#define FT_SERVICE_ID_FONT_FORMAT  "font-format"

#define FT_FONT_FORMAT_TRUETYPE  "TrueType"
#define FT_FONT_FORMAT_TYPE_1    "Type 1"
#define FT_FONT_FORMAT_BDF       "BDF"
#define FT_FONT_FORMAT_PCF       "PCF"
#define FT_FONT_FORMAT_TYPE_42   "Type 42"
#define FT_FONT_FORMAT_CID       "CID Type 1"
#define FT_FONT_FORMAT_CFF       "CFF"
#define FT_FONT_FORMAT_PFR       "PFR"
#define FT_FONT_FORMAT_WINFNT    "Windows FNT"

  /* */

FT_END_HEADER

#endif /* SVFNTFMT_H_ */

/* END */


text:
See the README.md files of the individual permutations:

akka-http
akka-http-slick-postgres


text: homebrew_cask 'google-hangouts'


text:
package org.yeastrc.xlink.www.file_import_proxl_xml_scans.struts_action_as_webservices;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;  import org.slf4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.yeastrc.xlink.base.file_import_proxl_xml_scans.enum_classes.ProxlXMLFileImportFileType;
import org.yeastrc.xlink.base.file_import_proxl_xml_scans.utils.Proxl_XML_ImporterWrkDirAndSbDrsCmmn;
import org.yeastrc.xlink.www.constants.WebServiceErrorMessageConstants;
import org.yeastrc.xlink.www.dao.ProjectDAO;
import org.yeastrc.xlink.www.dto.ProjectDTO;
import org.yeastrc.xlink.www.exceptions.ProxlWebappDataException;
import org.yeastrc.xlink.www.exceptions.ProxlWebappFileUploadFileSystemException;
import org.yeastrc.xlink.www.access_control.result_objects.WebSessionAuthAccessLevel;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.constants.ProxlXMLFileUploadMaxFileSizeConstants;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.constants.ProxlXMLFileUploadWebConstants;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.objects.ProxlUploadTempDataFileContents;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.utils.IsScanFileImportAllowedViaWebSubmit;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.utils.Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile;
import org.yeastrc.xlink.www.file_import_proxl_xml_scans.utils.Proxl_XML_Importer_Work_Directory_And_SubDirs_Web;
import org.yeastrc.xlink.www.user_session_management.UserSession;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result;
import org.yeastrc.xlink.www.access_control.access_control_main.GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId;
import com.fasterxml.jackson.databind.ObjectMapper;

///////   In Progress to pass file via the post contents (just getInputStream() instead of via multipart form)

//   The Java Submitter Pgm is successfully passing the cookie for the JSESSIONID so getSession returns the logged in user.
//
//   Next need to remove all the Multipart form processing and write from the InputStream directly to the final file on disk.
//   		(This is the way Limelight works)

/**
 * Upload
 *
 * This Struts Action should be considered a webservice as it returns JSON
 */
public class UploadFileForImportWebserviceAction extends Action {

	private static final Logger log = LoggerFactory.getLogger(  UploadFileForImportWebserviceAction.class );

	private static final int COPY_FILE_ARRAY_SIZE = 32 * 1024;

	//  Keep all these Strings in sync with the class SendToServerConstants in subdir proxl_submit_import

	public static final String UPLOAD_FILE_HEADER_NAME_UPLOAD_KEY = "X-Proxl-upload_key";
	public static final String UPLOAD_FILE_HEADER_NAME_PROJECT_ID = "X-Proxl-project_id";
	public static final String UPLOAD_FILE_HEADER_NAME_FILE_INDEX = "X-Proxl-file_index";
	public static final String UPLOAD_FILE_HEADER_NAME_FILE_TYPE = "X-Proxl-file_type";
	public static final String UPLOAD_FILE_HEADER_NAME_FILENAME = "X-Proxl-filename";

	/**
	 * Header name for uploaded file on submitting machine ( Java Canonical Path )
	 */
	public static final String UPLOAD_FILE_HEADER_NAME_UPLOADED_FILENAME_W_PATH_CANONICAL =
			"X-Proxl-uploadFileWPathCanonical";
	/**
	 * Header name for uploaded file on submitting machine ( Java Absolute Path )
	 */
	public static final String UPLOAD_FILE_HEADER_NAME_UPLOADED_FILENAME_W_PATH_ABSOLUTE =
			"X-Proxl-uploadFileWPathAbsolute";

	@Override
	public ActionForward execute( ActionMapping mapping,
			  ActionForm form,
			  HttpServletRequest request,
			  HttpServletResponse response ) throws Exception {

		//  	request.getParameter(...) only comes from the query string
//		String uploadType = request.getParameter( "uploadTypeQueryString" );
		String scanFileSuffix = null;
		File uploadFileTempSubDirForThisRequestFileObj = null;
		File uploadedFileOnDisk = null;
		ProxlXMLFileImportFileType fileType = null;
		String canonicalFilename_W_Path_OnSubmitMachine = null;
		String absoluteFilename_W_Path_OnSubmitMachine = null;
		int fileIndex = -1;
		int projectId = -1;
		long uploadKey = -1;
		long maxFileSize = -1;
		String maxFileSizeFormatted = null;
		try {
//			String requestURL = request.getRequestURL().toString();

			canonicalFilename_W_Path_OnSubmitMachine = request.getHeader( UPLOAD_FILE_HEADER_NAME_UPLOADED_FILENAME_W_PATH_CANONICAL );
			absoluteFilename_W_Path_OnSubmitMachine = request.getHeader( UPLOAD_FILE_HEADER_NAME_UPLOADED_FILENAME_W_PATH_ABSOLUTE );

			String uploadedFilename = request.getHeader( UPLOAD_FILE_HEADER_NAME_FILENAME );
			String fileIndexString = request.getHeader( UPLOAD_FILE_HEADER_NAME_FILE_INDEX );
			String fileTypeString = request.getHeader( UPLOAD_FILE_HEADER_NAME_FILE_TYPE );
			String projectIdString = request.getHeader( UPLOAD_FILE_HEADER_NAME_PROJECT_ID );
			String uploadKeyString = request.getHeader( UPLOAD_FILE_HEADER_NAME_UPLOAD_KEY );

			if ( StringUtils.isEmpty( uploadedFilename ) ) {
				log.error( "'filename' query parameter is not sent or is empty" );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( StringUtils.isEmpty( fileIndexString ) ) {
				log.error( "'file_index' query parameter is not sent or is empty" );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			try {
				fileIndex = Integer.parseInt( fileIndexString );
			} catch (Exception e ) {
				log.error( "'file_index' query parameter is not an integer: " + projectIdString );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( StringUtils.isEmpty( fileTypeString ) ) {
				log.error( "'file_type' query parameter is not sent or is empty" );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			int fileTypeInt = -1;
			try {
				fileTypeInt = Integer.parseInt( fileTypeString );
			} catch (Exception e ) {
				log.error( "'file_type' query parameter is not a valid value: " + fileTypeString );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			try {
				fileType = ProxlXMLFileImportFileType.fromValue( fileTypeInt );
			} catch (Exception e ) {
				log.error( "'file_type' query parameter is not a valid value: " + fileTypeString );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( fileType == ProxlXMLFileImportFileType.SCAN_FILE
					&& ( ! IsScanFileImportAllowedViaWebSubmit.getInstance().isScanFileImportAllowedViaWebSubmit() ) ) {
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
				importFileServletResponse.setStatusSuccess(false);
				importFileServletResponse.scanFileNotAllowed = true;

				OutputStream responseOutputStream = response.getOutputStream();
				// send the JSON response
				ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
				mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
				responseOutputStream.flush();
				responseOutputStream.close();
				throw new FailResponseSentException();
			}
			if ( StringUtils.isEmpty( projectIdString ) ) {
				log.error( "'project_id' query parameter is not sent or is empty" );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			try {
				projectId = Integer.parseInt( projectIdString );
			} catch (Exception e ) {
				log.error( "'project_id' query parameter is not an integer: " + projectIdString );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( StringUtils.isEmpty( uploadKeyString ) ) {
				log.error( "'upload_key' query parameter is not sent or is empty" );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			try {
				uploadKey = Long.parseLong( uploadKeyString );
			} catch (Exception e ) {
				log.error( "'upload_key' query parameter is not an integer: " + projectIdString );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( fileType == ProxlXMLFileImportFileType.SCAN_FILE ) {
				//  TODO  Only allow scan files if configured to allow upload scan files
				//  if not allow scan files, throw exception here with 400 error
			}
			if ( fileType == ProxlXMLFileImportFileType.PROXL_XML_FILE ) {
				maxFileSize = ProxlXMLFileUploadMaxFileSizeConstants.MAX_PROXL_XML_FILE_UPLOAD_SIZE;
				maxFileSizeFormatted = ProxlXMLFileUploadMaxFileSizeConstants.MAX_PROXL_XML_FILE_UPLOAD_SIZE_FORMATTED;
			} else if ( fileType == ProxlXMLFileImportFileType.SCAN_FILE ) {
				maxFileSize = ProxlXMLFileUploadMaxFileSizeConstants.MAX_SCAN_FILE_UPLOAD_SIZE;
				maxFileSizeFormatted = ProxlXMLFileUploadMaxFileSizeConstants.MAX_SCAN_FILE_UPLOAD_SIZE_FORMATTED;
			} else {
				String msg = "Unknown value for fileType: " + fileType;
				log.error( msg );
				throw new ProxlWebappFileUploadFileSystemException( msg );
			}

			//  Validate maxFileSize against reported upload size in header

			long uploadFileSizeInHeader = request.getContentLengthLong();

			if ( uploadFileSizeInHeader > maxFileSize ) {
				//  Return Error -  Status Code 400
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
				importFileServletResponse.setStatusSuccess(false);
				importFileServletResponse.setFileSizeLimitExceeded( true );
				importFileServletResponse.setMaxSize( maxFileSize );
				importFileServletResponse.setMaxSizeFormatted( maxFileSizeFormatted );
				OutputStream responseOutputStream = response.getOutputStream();
				// send the JSON response
				ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
				mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
				responseOutputStream.flush();
				responseOutputStream.close();
				throw new FailResponseSentException();
			}

			///////  Add additional checking of the filename for scan files
			if ( fileType == ProxlXMLFileImportFileType.SCAN_FILE ) {
				if ( uploadedFilename.endsWith( ProxlXMLFileUploadWebConstants.UPLOAD_SCAN_FILE_ALLOWED_SUFFIX_MZML ) ) {
					scanFileSuffix = ProxlXMLFileUploadWebConstants.UPLOAD_SCAN_FILE_ALLOWED_SUFFIX_MZML;
				} else if ( uploadedFilename.endsWith( ProxlXMLFileUploadWebConstants.UPLOAD_SCAN_FILE_ALLOWED_SUFFIX_MZXML ) ) {
					scanFileSuffix = ProxlXMLFileUploadWebConstants.UPLOAD_SCAN_FILE_ALLOWED_SUFFIX_MZXML;
				} else {
					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
					importFileServletResponse.setStatusSuccess(false);
					importFileServletResponse.scanFilenameSuffixNotValid = true;

					OutputStream responseOutputStream = response.getOutputStream();
					// send the JSON response
					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
					responseOutputStream.flush();
					responseOutputStream.close();
					throw new FailResponseSentException();
				}
			}
			//  Confirm projectId is in database
			Integer authShareableObjectId =	ProjectDAO.getInstance().getAuthShareableObjectIdForProjectId( projectId );
			if ( authShareableObjectId == null ) {
				// should never happen
				String msg = "Project id is not in database: " + projectId;
				log.error( msg );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId_Result accessAndSetupWebSessionResult =
					GetWebSessionAuthAccessLevelForProjectIds_And_NO_ProjectId.getSinglesonInstance().getAccessAndSetupWebSessionWithProjectId( projectId, request, response );
			UserSession userSession = accessAndSetupWebSessionResult.getUserSession();
			if ( accessAndSetupWebSessionResult.isNoSession() ) {
				//  No User session
				response.setStatus( WebServiceErrorMessageConstants.NO_SESSION_STATUS_CODE.getStatusCode() );
				response.setContentType( "text" );
				response.getWriter().print( WebServiceErrorMessageConstants.NO_SESSION_TEXT );
				throw new FailResponseSentException();
			}
			//  Test access to the project id
			WebSessionAuthAccessLevel authAccessLevel = accessAndSetupWebSessionResult.getWebSessionAuthAccessLevel();
			if ( ! authAccessLevel.isProjectOwnerAllowed() ) {
				//  No Access Allowed for this project id
				response.setStatus( WebServiceErrorMessageConstants.NOT_AUTHORIZED_STATUS_CODE.getStatusCode() );
				response.setContentType( "text" );
				response.getWriter().print( WebServiceErrorMessageConstants.NOT_AUTHORIZED_TEXT );
				throw new FailResponseSentException();
			}
			int authUserId = userSession.getAuthUserId();
			//  Confirm projectId is in database
			ProjectDTO projectDTO =	ProjectDAO.getInstance().getProjectDTOForProjectId( projectId );
			if ( projectDTO == null ) {
				// should never happen
				String msg = "Project id is not in database: " + projectId;
				log.error( msg );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( ( ! projectDTO.isEnabled() ) || ( projectDTO.isMarkedForDeletion() ) ) {
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				throw new FailResponseSentException();
			}
			if ( ( projectDTO.isProjectLocked() ) ) {
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
				importFileServletResponse.setStatusSuccess(false);
				importFileServletResponse.setProjectLocked(true);
				OutputStream responseOutputStream = response.getOutputStream();
				// send the JSON response
				ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
				mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
				responseOutputStream.flush();
				responseOutputStream.close();
				throw new FailResponseSentException();
			}
			File importer_Work_Directory = Proxl_XML_ImporterWrkDirAndSbDrsCmmn.getInstance().get_Proxl_XML_Importer_Work_Directory();
			//  Get the File object for the Base Subdir used to first store the files in this request
			String uploadFileTempDirString =
					Proxl_XML_Importer_Work_Directory_And_SubDirs_Web.getInstance().getDirForUploadFileTempDir();
			File uploadFileTempDir = new File( importer_Work_Directory, uploadFileTempDirString );
			if ( ! uploadFileTempDir.exists() ) {
				String msg = "uploadFileTempDir does not exist.  uploadFileTempDir: "
						+ uploadFileTempDir.getAbsolutePath();
				log.error( msg );
				throw new ProxlWebappFileUploadFileSystemException(msg);
			}
			uploadFileTempSubDirForThisRequestFileObj =
					Proxl_XML_Importer_Work_Directory_And_SubDirs_Web.getInstance()
					.getSubDirForUploadFileTempDir( authUserId, uploadKey, uploadFileTempDir );
			if ( ! uploadFileTempSubDirForThisRequestFileObj.exists() ) {
				String msg = "uploadFileTempSubDirForThisRequestFileObj does not exist exists: "
						+ uploadFileTempSubDirForThisRequestFileObj.getCanonicalPath();
				log.warn( msg );
				response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
				JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
				importFileServletResponse.setStatusSuccess(false);
				importFileServletResponse.setUploadKeyNotValid( true );
				OutputStream responseOutputStream = response.getOutputStream();
				// send the JSON response
				ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
				mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
				responseOutputStream.flush();
				responseOutputStream.close();
				throw new FailResponseSentException();
			}
			///   Create matching "data" file for uploaded file with data about the file.
			File dataFile =
					Proxl_XML_Importer_Work_Directory_And_SubDirs_Web.getInstance()
					.getDataFile( fileIndex, uploadFileTempSubDirForThisRequestFileObj );
			if ( dataFile.exists() ) {
				String msg = "dataFile already exists: " + dataFile.getCanonicalPath();
				log.warn( msg );
				throw new ProxlWebappFileUploadFileSystemException(msg);
			}

			//  File object to write incoming file to:  uploadedFileOnDisk
			//   Create the filename that the uploaded file will be saved as
			uploadedFileOnDisk =
					Proxl_XML_Importer_Work_Directory_And_SubDirs_Web.getInstance()
					.getUploadFile( scanFileSuffix, fileIndex, fileType, uploadFileTempSubDirForThisRequestFileObj );
			String uploadedFileOnDiskFilename = uploadedFileOnDisk.getName();

			//  Copy InputStream containing POST body into file on disk
			{
				long totalBytesCopied = 0;
				boolean fileTooLarge = false;

				try ( InputStream inputStreamFromPOSTLocal = request.getInputStream() ) {

					try ( FileOutputStream fos = new FileOutputStream( uploadedFileOnDisk )) {
						byte[] buf = new byte[ COPY_FILE_ARRAY_SIZE ];
						int len;
						while ((len = inputStreamFromPOSTLocal.read(buf)) != -1){
							if ( len > 0 ) {
								fos.write(buf, 0, len);
								totalBytesCopied += len;
								if ( totalBytesCopied > maxFileSize ) {

									fileTooLarge = true;
									break;
								}
							}
						}
					}
				}
				if ( fileTooLarge ) {

					if ( ! uploadedFileOnDisk.delete() ) {
						log.warn("Failed to delete upload file that is canceled since too large.  file: " + uploadedFileOnDisk.getAbsolutePath() );
					}
					//  Return Error -  Status Code 400
					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
					importFileServletResponse.setStatusSuccess(false);
					importFileServletResponse.setFileSizeLimitExceeded( true );
					importFileServletResponse.setMaxSize( maxFileSize );
					importFileServletResponse.setMaxSizeFormatted( maxFileSizeFormatted );
					OutputStream responseOutputStream = response.getOutputStream();
					// send the JSON response
					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
					responseOutputStream.flush();
					responseOutputStream.close();
					throw new FailResponseSentException();
				}
			}

			//  After have file uploaded:

			String searchNameInProxlXMLFile = null;
			if ( fileType == ProxlXMLFileImportFileType.PROXL_XML_FILE ) {
				//////   Validate that the user uploaded a Proxl XML file and get the "name" attr on root element
				try {
					//  Throws exception if not valid
					//  It will return null if there is no "name" attr on root element
					searchNameInProxlXMLFile =
							Minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile.getInstance()
							.minimal_Validate_ProxlXMLFile_AndGetSearchNameIfInFile( uploadedFileOnDisk );
				} catch ( ProxlWebappDataException e ) {
					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
					importFileServletResponse.setStatusSuccess(false);
					importFileServletResponse.proxlXMLFilerootXMLNodeIncorrect = true;
					//				private boolean proxlXMLFileFailsInitialParse;
					//				private boolean proxlXMLFilerootXMLNodeIncorrect;
					OutputStream responseOutputStream = response.getOutputStream();
					// send the JSON response
					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
					responseOutputStream.flush();
					responseOutputStream.close();
					throw new FailResponseSentException();
				} catch ( Exception e ) {
					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
					importFileServletResponse.setStatusSuccess(false);
					importFileServletResponse.proxlXMLFileFailsInitialParse = true;
					OutputStream responseOutputStream = response.getOutputStream();
					// send the JSON response
					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
					responseOutputStream.flush();
					responseOutputStream.close();
					throw new FailResponseSentException();
				}
			} else if ( fileType == ProxlXMLFileImportFileType.SCAN_FILE ) {
				//////   Validate that the user uploaded a mzML or mzXML file
//				try {
//
//					//  Throws exception if not valid
//
//					//  TODO  Need to code Scan File Validator
//
////					processUploadedScanFile_Validate( uploadedFileOnDisk );
//
//				} catch ( ProxlWebappDataException e ) {
//
//
//					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
//
//
//					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
//
//					importFileServletResponse.setStatusSuccess(false);
//
//					importFileServletResponse.scanFilerootXMLNodeIncorrect = true;
//
//					OutputStream responseOutputStream = response.getOutputStream();
//
//
//					// send the JSON response
//					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
//					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
//
//					responseOutputStream.flush();
//					responseOutputStream.close();
//
//					throw new FailResponseSentException();
//
//				} catch ( Exception e ) {
//
//
//					response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400  */ );
//
//
//					JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
//
//					importFileServletResponse.setStatusSuccess(false);
//
//					importFileServletResponse.proxlXMLFileFailsInitialParse = true;
//
//					OutputStream responseOutputStream = response.getOutputStream();
//
//
//					// send the JSON response
//					ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
//					mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
//
//					responseOutputStream.flush();
//					responseOutputStream.close();
//
//					throw new FailResponseSentException();
//
//				}
			} else {
				String msg = "Unknown value for fileType: " + fileType;
				log.error( msg );
				throw new ProxlWebappFileUploadFileSystemException( msg );
			}
			///   Create matching "data" file for uploaded file with data about the file.
			ProxlUploadTempDataFileContents proxlUploadTempDataFileContents = new ProxlUploadTempDataFileContents();
			proxlUploadTempDataFileContents.setUploadedFilename( uploadedFilename );
			proxlUploadTempDataFileContents.setSavedToDiskFilename( uploadedFileOnDiskFilename );
			proxlUploadTempDataFileContents.setFileIndex( fileIndex );
			proxlUploadTempDataFileContents.setFileType( fileType );
			proxlUploadTempDataFileContents.setSearchNameInProxlXMLFile( searchNameInProxlXMLFile );
			proxlUploadTempDataFileContents.setCanonicalFilename_W_Path_OnSubmitMachine( canonicalFilename_W_Path_OnSubmitMachine );
			proxlUploadTempDataFileContents.setAbsoluteFilename_W_Path_OnSubmitMachine( absoluteFilename_W_Path_OnSubmitMachine );
			//  Marshal (write) the object to the file
			JAXBContext jaxbContext = JAXBContext.newInstance( ProxlUploadTempDataFileContents.class );
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
			OutputStream outputStream = null;
			try {
				outputStream = new FileOutputStream( dataFile );
				marshaller.marshal( proxlUploadTempDataFileContents, outputStream );
			} catch ( Exception e ) {
				throw e;
			} finally {
				if ( outputStream != null ) {
					outputStream.close();
				}
			}
			JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
			importFileServletResponse.setStatusSuccess(true);
			OutputStream responseOutputStream = response.getOutputStream();
			// send the JSON response
			ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
			mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
			log.info( "Completed Uploads");
		} catch ( FailResponseSentException e ) {
			//  No longer delete dir
//			cleanupOnError( uploadFileTempSubDirForThisRequestFileObj );
		} catch (Throwable ex){
			log.error( "Exception: " + ex.toString(), ex );
			response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR /* 500  */ );
			JSON_Servlet_Response_Object importFileServletResponse = new JSON_Servlet_Response_Object();
			importFileServletResponse.setStatusSuccess(false);
			OutputStream responseOutputStream = response.getOutputStream();
			// send the JSON response
			ObjectMapper mapper = new ObjectMapper();  //  Jackson JSON library object
			mapper.writeValue( responseOutputStream, importFileServletResponse ); // where first param can be File, OutputStream or Writer
			responseOutputStream.flush();
			responseOutputStream.close();
			//  No longer delete dir
//			cleanupOnError( uploadFileTempSubDirForThisRequestFileObj );
		}

		return null;
	}

	/**
	 *
	 *
	 */
	private static class FailResponseSentException extends Exception {
		private static final long serialVersionUID = 1L;
	}

	/**
	 *
	 *
	 */
	private static class JSON_Servlet_Response_Object {
		private boolean statusSuccess;
		//  These are populated for FileSizeLimitExceededException exception
		private boolean fileSizeLimitExceeded;
		private long maxSize;
		private String maxSizeFormatted;
		private boolean uploadFile_fieldNameInvalid;
		private boolean uploadKeyNotValid;
		private boolean proxlXMLFileFailsInitialParse;
		private boolean proxlXMLFilerootXMLNodeIncorrect;
		private boolean scanFileNotAllowed;
		private boolean scanFilenameSuffixNotValid;
		private boolean scanFileFailsInitialParse;
		private boolean scanFilerootXMLNodeIncorrect;
		private boolean projectLocked;
		@SuppressWarnings("unused")
		public boolean isStatusSuccess() {
			return statusSuccess;
		}
		public void setStatusSuccess(boolean statusSuccess) {
			this.statusSuccess = statusSuccess;
		}
		@SuppressWarnings("unused")
		public boolean isFileSizeLimitExceeded() {
			return fileSizeLimitExceeded;
		}
		public void setFileSizeLimitExceeded(boolean fileSizeLimitExceeded) {
			this.fileSizeLimitExceeded = fileSizeLimitExceeded;
		}
		@SuppressWarnings("unused")
		public long getMaxSize() {
			return maxSize;
		}
		public void setMaxSize(long maxSize) {
			this.maxSize = maxSize;
		}
		@SuppressWarnings("unused")
		public String getMaxSizeFormatted() {
			return maxSizeFormatted;
		}
		public void setMaxSizeFormatted(String maxSizeFormatted) {
			this.maxSizeFormatted = maxSizeFormatted;
		}
		@SuppressWarnings("unused")
		public boolean isUploadFile_fieldNameInvalid() {
			return uploadFile_fieldNameInvalid;
		}
		@SuppressWarnings("unused")
		public boolean isProjectLocked() {
			return projectLocked;
		}
		public void setProjectLocked(boolean projectLocked) {
			this.projectLocked = projectLocked;
		}
		@SuppressWarnings("unused")
		public boolean isProxlXMLFileFailsInitialParse() {
			return proxlXMLFileFailsInitialParse;
		}
		@SuppressWarnings("unused")
		public void setProxlXMLFileFailsInitialParse(
				boolean proxlXMLFileFailsInitialParse) {
			this.proxlXMLFileFailsInitialParse = proxlXMLFileFailsInitialParse;
		}
		@SuppressWarnings("unused")
		public boolean isProxlXMLFilerootXMLNodeIncorrect() {
			return proxlXMLFilerootXMLNodeIncorrect;
		}
		@SuppressWarnings("unused")
		public void setProxlXMLFilerootXMLNodeIncorrect(
				boolean proxlXMLFilerootXMLNodeIncorrect) {
			this.proxlXMLFilerootXMLNodeIncorrect = proxlXMLFilerootXMLNodeIncorrect;
		}
		@SuppressWarnings("unused")
		public boolean isUploadKeyNotValid() {
			return uploadKeyNotValid;
		}
		public void setUploadKeyNotValid(boolean uploadKeyNotValid) {
			this.uploadKeyNotValid = uploadKeyNotValid;
		}
		@SuppressWarnings("unused")
		public boolean isScanFilenameSuffixNotValid() {
			return scanFilenameSuffixNotValid;
		}
		@SuppressWarnings("unused")
		public void setScanFilenameSuffixNotValid(boolean scanFilenameSuffixNotValid) {
			this.scanFilenameSuffixNotValid = scanFilenameSuffixNotValid;
		}
		@SuppressWarnings("unused")
		public boolean isScanFileFailsInitialParse() {
			return scanFileFailsInitialParse;
		}
		@SuppressWarnings("unused")
		public void setScanFileFailsInitialParse(boolean scanFileFailsInitialParse) {
			this.scanFileFailsInitialParse = scanFileFailsInitialParse;
		}
		@SuppressWarnings("unused")
		public boolean isScanFilerootXMLNodeIncorrect() {
			return scanFilerootXMLNodeIncorrect;
		}
		@SuppressWarnings("unused")
		public void setScanFilerootXMLNodeIncorrect(boolean scanFilerootXMLNodeIncorrect) {
			this.scanFilerootXMLNodeIncorrect = scanFilerootXMLNodeIncorrect;
		}
		@SuppressWarnings("unused")
		public boolean isScanFileNotAllowed() {
			return scanFileNotAllowed;
		}
		@SuppressWarnings("unused")
		public void setScanFileNotAllowed(boolean scanFileNotAllowed) {
			this.scanFileNotAllowed = scanFileNotAllowed;
		}
	}
}


text:
<!DOCTYPE html>

    <title>SIMILE Widgets | Exhibit | Examples | U.S. Presidents</title>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <link rel='stylesheet' href='http://www.simile-widgets.org/styles/common.css' type='text/css' />

    <link href="schema.js" type="application/json" rel="exhibit/data" />
    <link href="presidents.js" type="application/json" rel="exhibit/data" />

    <link rel="exhibit-extension" type="text/javascript" href="../api/extensions/time/time-extension.js" />

    <link rel="exhibit-extension" href="../api/extensions/map/map-extension.js" data-ex-apikey="AIzaSyCDO3EXWKJms5T38db48czFJZDunhYIzn8" />

    <link rel='stylesheet' href='styles.css' type='text/css' />

SIMILE Widgets

Exhibit

Demos

Examples: U.S. Presidents

US Presidents

Here is the Exhibit JSON data file.

                    Search:

                    Republican
                    Democratic

                    Other parties
                    Many parties
                    No party

Terms: ,

Religions:

Birth: ,

Death: ,

                <div data-ex-role="view"
                    data-ex-formats="date { mode: medium; show: date }"
                    data-ex-view-class="Timeline"
                    data-ex-label="Terms"
                    data-ex-proxy=".presidency"
                    data-ex-start=".inDate"
                    data-ex-end=".outDate"
                    data-ex-color-key=".party"
                    data-ex-color-coder="party-colors"
		    data-ex-autoposition="true"
                    data-ex-bubble-width="320"
                    data-ex-top-band-pixels-per-unit="400"
                    data-ex-select-coordinator="president"
                    data-ex-show-summary="false"
                    data-ex-timeline-height="170"
                    >

                    <div data-ex-role="view"
                        data-ex-view-class="Map"
                        data-ex-label="Birth Places with Photos"
			data-ex-mapheight="430"
                        data-ex-latlng=".birthLatLng"
                        data-ex-center="38.479394673276445, -115.361328125"
                        data-ex-zoom="3"
                        data-ex-bubble-width="200"
                        data-ex-icon=".imageURL"
                        data-ex-shape-width="60"
                        data-ex-shape-height="60"
                        data-ex-select-coordinator="president"
                        >

                    <div data-ex-role="view"
                        data-ex-view-class="Map"
                        data-ex-label="Death Places (by Party)"
                        data-ex-latlng=".deathLatLng"
                        data-ex-autoposition = "true"
                        data-ex-max-auto-zoom = "7"
                        data-ex-bubble-width="200"
                        data-ex-color-key=".party"
                        data-ex-color-coder="party-colors"
                        data-ex-select-coordinator="president"
                        >

                    <div data-ex-role="view"
                        data-ex-view-class="Tabular"
                        data-ex-label="Details"
                        data-ex-columns=".term, .label, .party, .presidency.inDate, .presidency.outDate, add(foreach(.presidency, date-range(.inDate, default(.outDate, now()), 'day'))), .birth, .death"
                        data-ex-column-labels="term, name, party, took office, left office, days in office, age of ascension, age"
                        data-ex-formats="date { mode: medium; show: date }"
                        data-ex-sort-column="3"
                        data-ex-sort-ascending="false"
                        data-ex-paginate="true"
                        data-ex-page-size="5"
                        >


text:
# include "Debug.h"
# include "ClassFile.h"
# include "AttributeInfo.h"

namespace JBC {

ConstantValueAttribute *ConstantValueAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Constant Value Attribute.\n");

	builder->NextShort(constant_value->index);

	return this;
}

ExceptionTableEntry *ExceptionTableEntry
		::EncodeEntry(ClassBuilder *builder) {
	debug_printf(level3, "Encoding Exception Table Entry.\n");

	builder->NextShort(start_pc);
	builder->NextShort(end_pc);
	builder->NextShort(handler_pc);
	builder->NextShort(catch_type);

	return this;
}

CodeAttribute *CodeAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Code Attribute.\n");

	// Maximums
	builder->NextShort(max_stack);
	builder->NextShort(max_locals);

	// Code
	builder->NextInt(code_length);
	builder->Next(code, code_length);
	debug_printf(level3, "Code length : %u.\n", code_length);

	// Exception Table
	length = exception_table.size();
	builder->NextShort(length);
	debug_printf(level3, "Code Exception table length : %hu.\n", length);
	for(unsigned idx = 0; idx < length; idx++) {
		debug_printf(level2, "Code Exception table entry %u :\n", idx);
		exception_table[idx]->EncodeEntry(builder);
	}

	// Attribute Table
	length = attributes.size();
	builder->NextShort(length);
	debug_printf(level3, "Code Attributes count : %hu.\n", length);
	for(unsigned idx = 0; idx < length; idx++) {
		debug_printf(level2, "Code Attribute %u :\n", idx);
		JBC::EncodeAttribute(builder, classFile, attributes[idx]);
	}

	return this;
}

StackMapTableAttribute *StackMapTableAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Stack Map Table Attribute.\n");

	length = entries.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		EncodeStackMapFrame(builder, classFile, entries[idx]);
	}

	return this;
}

ExceptionsAttribute *ExceptionsAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	uint16_t length;

	debug_printf(level3, "Encoding Exceptions Attribute.\n");

	length = exception_table.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		ConstantInfo *constant = exception_table[idx];
		builder->NextShort(constant->index);
	}

	return this;
}

InnerClassEntry *InnerClassEntry
		::EncodeEntry(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Inner Class Entry.\n");

	builder->NextShort(inner_class_info == NULL ? 0 : inner_class_info->index);
	builder->NextShort(outer_class_info == NULL ? 0 : outer_class_info->index);
	builder->NextShort(inner_class_name == NULL ? 0 : inner_class_name->index);
	builder->NextShort(inner_class_access_flags);

	return this;
}

InnerClassesAttribute *InnerClassesAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Inner Classes Attribute.\n");

	length = classes.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		classes[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

EnclosingMethodAttribute *EnclosingMethodAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Enclosing Method Attribute.\n");

	builder->NextShort(enclosing_class == NULL ? 0 : enclosing_class->index);
	builder->NextShort(enclosing_method == NULL ? 0 : enclosing_method->index);

	return this;
}

SignatureAttribute *SignatureAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Signature Attribute.\n");

	builder->NextShort(signature == NULL ? 0 : signature->index);

	return this;
}

SourceFileAttribute *SourceFileAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Souce File Attribute.\n");

	builder->NextShort(source_file == NULL ? 0 : source_file->index);

	return this;
}

SourceDebugExtensionAttribute *SourceDebugExtensionAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Source Debug Extension Attribute.\n");

	builder->Next(debug_extension, attribute_length);

	return this;
}

LineNumberTableEntry *LineNumberTableEntry
		::EncodeEntry(ClassBuilder *builder) {
	debug_printf(level3, "Encoding Line Number Table Entry.\n");

	builder->NextShort(start_pc);
	builder->NextShort(line_number);

	return this;
}

LineNumberTableAttribute *LineNumberTableAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *) {
	uint16_t length;

	debug_printf(level3, "Encoding Line Number Table Attribute.\n");

	length = line_number_table.size();
	debug_printf(level2, "Line Number Table length : %hu.\n", length);
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		line_number_table[idx]->EncodeEntry(builder);
	}

	return this;
}

LocalVariableTableEntry *LocalVariableTableEntry
		::EncodeEntry(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Local Variable Table Entry.\n");

	builder->NextShort(start_pc);
	builder->NextShort(length);

	builder->NextShort(name == NULL ? 0 : name->index);
	builder->NextShort(descriptor == NULL ? 0 : descriptor->index);

	builder->NextShort(index);

	return 0;
}

LocalVariableTableAttribute *LocalVariableTableAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	debug_printf(level3, "Encoding Local Variable Table Attribute.\n");

	uint16_t length;

	length = local_variable_table.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		local_variable_table[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

LocalVariableTypeTableEntry *LocalVariableTypeTableEntry
		::EncodeEntry(ClassBuilder *builder, ClassFile *) {
	debug_printf(level3, "Encoding Local Variable Type Table Entry.\n");

	builder->NextShort(start_pc);
	builder->NextShort(length);

	builder->NextShort(name == NULL ? 0 : name->index);
	builder->NextShort(signature == NULL ? 0 : signature->index);

	builder->NextShort(index);

	return this;
}

LocalVariableTypeTableAttribute *LocalVariableTypeTableAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Local Variable Type Table Attribute.\n");

	length = local_variable_type_table.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		local_variable_type_table[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

RuntimeAnnotationsAttribute *RuntimeAnnotationsAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Runtime Annotations Attribute.\n");

	length = annotations.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		annotations[idx]->EncodeEntry(builder, classFile);
	}

	return 0;
}

ParameterAnnotationsEntry *ParameterAnnotationsEntry
		::EncodeEntry(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Parameter Annotations Entry.\n");

	length = annotations.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		annotations[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

RuntimeParameterAnnotationsAttribute *RuntimeParameterAnnotationsAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Parameter Annotations Attribute.\n");

	length = parameter_annotations.size();
	builder->NextByte(length);

	for(unsigned idx = 0; idx < length; idx++) {
		parameter_annotations[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

AnnotationDefaultAttribute *AnnotationDefaultAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	debug_printf(level3, "Encoding Annotation Default Attribute.\n");

	EncodeElementValue(builder, classFile, default_value);

	return this;
}

BootstrapMethodEntry *BootstrapMethodEntry
		::EncodeEntry(ClassBuilder *builder, ClassFile *) {
	uint16_t length;

	debug_printf(level3, "Encoding Bootstrap Method Entry.\n");

	builder->NextShort(bootstrap_method_ref == NULL ? 0 :
			bootstrap_method_ref->index);
	length = bootstrap_arguments.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		ConstantInfo *info = bootstrap_arguments[idx];
		builder->NextShort(info == NULL ? 0 : info->index);
	}

	return this;
}

BootstrapMethodsAttribute *BootstrapMethodsAttribute
		::EncodeAttribute(ClassBuilder *builder, ClassFile *classFile) {
	uint16_t length;

	debug_printf(level3, "Encoding Bootstrap Methods Attribute.\n");

	length = bootstrap_methods.size();
	builder->NextShort(length);

	for(unsigned idx = 0; idx < length; idx++) {
		bootstrap_methods[idx]->EncodeEntry(builder, classFile);
	}

	return this;
}

int EncodeAttribute(ClassBuilder *builder, ClassFile *classFile, AttributeInfo *info) {
	debug_printf(level3, "Encoding Attribute.\n");

	builder->NextShort(info->name->index);
	builder->NextInt(info->attribute_length);
	info->EncodeAttribute(builder, classFile);

	return 0;
}

} /* JBC */


text:
package com.plugplayer.recivaremote.activities;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.plugplayer.plugplayer.upnp.ControlPointListener;
import com.plugplayer.plugplayer.upnp.PlugPlayerControlPoint;
import com.plugplayer.plugplayer.upnp.Renderer;
import com.plugplayer.plugplayer.upnp.Server;
import com.plugplayer.recivaremote.R;

public class ServersActivity extends ListActivity implements ControlPointListener
{
	Handler handler = new Handler();

	ServersListAdapter listAdapter;

	static ServersActivity me;

	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.servers );

		me = this;

		listAdapter = new ServersListAdapter( this );
		setListAdapter( listAdapter );

		final ListView lv = getListView();
		lv.setTextFilterEnabled( false );
		lv.setOnItemClickListener( new OnItemClickListener()
		{
			public void onItemClick( AdapterView<?> parent, View view, int position, long id )
			{
				Server device = (Server)lv.getItemAtPosition( position );

				// Not sure how this could have happened; perhaps a race condition?
				if ( device == null )
					return;

				device.updateAlive();

				if ( !device.isAlive() )
				{
					((BaseAdapter)getListAdapter()).notifyDataSetChanged();
					return;
				}

				PlugPlayerControlPoint.getInstance().setCurrentServer( null );
				PlugPlayerControlPoint.getInstance().setCurrentServer( device );

				BrowseActivityGroup.reset();
				Intent intent = new Intent( ServersActivity.this, BrowseActivityGroup.class );
				startActivity( intent );
			}
		} );

		PlugPlayerControlPoint controlPoint = PlugPlayerControlPoint.getInstance();
		if ( controlPoint == null )
		{
			Log.i( android.util.PlugPlayerUtil.DBG_TAG, "onCreate controlPoint is null, so instantiate it:plugplayer.ServersActivity" );
			controlPoint = new PlugPlayerControlPoint();
			controlPoint.start();
		}
		controlPoint.addControlPointListener( this );
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();

		PlugPlayerControlPoint controlPoint = PlugPlayerControlPoint.getInstance();
		if ( controlPoint != null )
			controlPoint.removeControlPointListener( this );
	}

	private class ServersListAdapter extends ArrayAdapter<Server>
	{
		public ServersListAdapter(Context context)
		{
			super(context,0);
			updateList();
		}

		public void updateList()
		{
			clear();

			PlugPlayerControlPoint controlPoint = PlugPlayerControlPoint.getInstance();
			for( Server s : controlPoint.getServerList() )
				add( s );
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			if ( convertView == null )
			{
				LayoutInflater vi = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
				convertView = vi.inflate( R.layout.server_list_item, null );
			}

			TextView t = (TextView)convertView.findViewById( R.id.title );
			ImageView i = (ImageView)convertView.findViewById( R.id.icon );

			Server s = getItem( position );
			s.loadIcon(i);
			t.setText( s.getName() );

			if ( s.isAlive() )
			{
				t.setTextColor( 0xFFFFFFFF );
			}
			else
			{
				t.setTextColor( 0x44FFFFFF );
			}

			return convertView;
		}
	}

	@Override
	public void mediaServerListChanged()
	{
		handler.post( new Runnable()
		{
			public void run()
			{
				listAdapter.updateList();
			}
		});
	}

	@Override
	public void mediaRendererChanged(Renderer newRenderer, Renderer oldRenderer)
	{
	}

	@Override
	public void mediaRendererListChanged()
	{
		Log.i(android.util.PlugPlayerUtil.DBG_TAG, "inside mediaRendererListChanged, no implementation:ServersActivity");
	}

	@Override
	public void mediaServerChanged(Server newServer, Server oldServer)
	{
	}

	@Override
	public void onErrorFromDevice(String error)
	{
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>About · Aissar Murad</title>
        <meta name="description" content="Things about me.">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="generator" content="Hugo 0.48" />
        <meta name="robots" content="index,follow">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta property="og:title" content="About">
<meta property="og:description" content="Things about me.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://example.com/page/about/">
        <link rel="stylesheet" href="https://example.comdist/styles.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin,cyrillic-ext,latin-ext,cyrillic">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

                                In English

        Blog

        About

About

Things about me.

About

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec dolor in magna lobortis egestas. Suspendisse eu erat tempor, tristique neque eu, convallis nulla. Curabitur vel bibendum lacus, at semper mauris. Suspendisse aliquet commodo ex, sed sagittis metus aliquam id. Maecenas feugiat rutrum lorem vel imperdiet. Nullam ornare lectus ut enim finibus, et porttitor mi tincidunt. Aenean lacinia, leo quis vehicula eleifend, quam libero sagittis erat, at euismod augue mauris et sapien. Sed id vehicula lectus, sit amet auctor ipsum. Nunc sed massa vel ex condimentum aliquam in a enim. Cras enim sem, tristique eu enim ac, congue commodo mi. Integer quis orci at dolor blandit eleifend.

School

Sed quis pulvinar nisi, sed dapibus lacus. Mauris tempus ex ut ipsum facilisis interdum. Integer feugiat urna sed feugiat tempor. Quisque dictum vestibulum feugiat. Nunc nec est volutpat lorem imperdiet egestas sit amet ut orci. Aliquam venenatis neque ipsum, a placerat lectus cursus at. Donec pellentesque tellus hendrerit faucibus posuere. Etiam gravida consequat lectus, volutpat consectetur velit convallis nec. Praesent sagittis luctus dignissim.

                        In English

                    © 2015 / Powered by Hugo

                    Ghostwriter theme By JollyGoodThemes
                    / Ported to Hugo By jbub


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <title></title>

        <base href="/">

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">

        <link rel="shortcut icon" href="favicon.png">

        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">

        <link rel="stylesheet" href="css/print.css" media="print">

        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">

        <link rel="stylesheet" href="fonts/fonts.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

1. Introduction

2. Part 1: Normalized Difference Indices

3. Part 2: Multi-spectral Image Classification

4. Part 3: Cleaning the Class Map

                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">

                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">

                        </button>

<button role="menuitem" class="theme" id="light">Light (default)</button>

<button role="menuitem" class="theme" id="rust">Rust</button>

<button role="menuitem" class="theme" id="coal">Coal</button>

<button role="menuitem" class="theme" id="navy">Navy</button>

<button role="menuitem" class="theme" id="ayu">Ayu</button>

                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">

                        </button>

GEOG3420 W22 Lab 4

                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>

Document not found (404)

This URL is invalid, sorry. Please use the navigation bar or search to continue.


text:
@interface CGHelper : NSObject

#pragma mark ConcentricArc

+(CGMutablePathRef)newConcentricArcPathAtPoint:(CGPoint)point withinnerRadius:(float)innerRadius outerRadius:(float)outerRadius startAngle:(float)startAngle endAngle:(float)endAngle CF_RETURNS_RETAINED;
+(void)fillConcentricArcAtPoint:(CGPoint)point withinnerRadius:(float)innerRadius outerRadius:(float)outerRadius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeConcentricArcAtPoint:(CGPoint)point withinnerRadius:(float)innerRadius outerRadius:(float)outerRadius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeConcentricArcAtPoint:(CGPoint)point withinnerRadius:(float)innerRadius outerRadius:(float)outerRadius startAngle:(float)startAngle endAngle:(float)endAngle width:(float)width color:(UIColor *)color;

#pragma mark Arc

+(CGMutablePathRef)newArcPathAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle CF_RETURNS_RETAINED;
+(void)fillArcAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeArcAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeArcAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle width:(float)width color:(UIColor *)color;

#pragma mark Slice

+(CGMutablePathRef)newSlicePathAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle CF_RETURNS_RETAINED;
+(void)fillSliceAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeSliceAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle color:(UIColor *)color;
+(void)strokeSliceAtPoint:(CGPoint)point withRadius:(float)radius startAngle:(float)startAngle endAngle:(float)endAngle width:(float)width color:(UIColor *)color;

#pragma mark Circle

+(CGMutablePathRef)newCirclePathAtPoint:(CGPoint)point withRadius:(float)radius CF_RETURNS_RETAINED;
+(void)fillCircleAtPoint:(CGPoint)point withRadius:(float)radius color:(UIColor *)color;
+(void)strokeCircleAtPoint:(CGPoint)point withRadius:(float)radius color:(UIColor *)color;
+(void)strokeCircleAtPoint:(CGPoint)point withRadius:(float)radius width:(float)width color:(UIColor *)color;

#pragma mark Text
+(void)drawText:(NSString *)text atPoint:(CGPoint)point font:(UIFont *)font color:(UIColor *)color;
@end


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("rxjs-compat/add/operator/exhaust");
//# sourceMappingURL=exhaust.js.map


text:
"""Top-level package for Kuna API wrapper."""

__author__ = """Dmytro Litvinov"""
__email__ = "me@dmytrolitvinov.com"
__version__ = "0.4.2"

from .kuna import KunaAPI, APIError  # noqa: F401


text:
/**
 * This file is a part of Kyte released under the MIT licence.
 * See the LICENCE file for more information
 */

#include "Thread.h"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "Thread.h"
#include "ITask.h"

namespace RG {
	Thread::Thread()
		: _CurrentTask(NULL)
	{}
	Thread::~Thread() {}

	void Thread::SetTask(ITask* task) {
		_CurrentTask = task;
	}

	ThreadRoutineRetValue_t Thread::PThreadDispatch(void* v_thr) {
		Thread* thr = (Thread*)v_thr;
		thr->Run();
		return NULL;
	}

	void Thread::Start() {
		pthread_attr_t thrAttr;
		pthread_attr_init(&thrAttr);
		pthread_create(&_Thread, &thrAttr, &PThreadDispatch, (void*)this);
		pthread_attr_destroy(&thrAttr);
	}
	void Thread::Run() {
		if (!_CurrentTask) {
			// printf("Thread::Run(): No task set!\n");
			return;
		}

		_CurrentTask->Run();
	}
	void Thread::Join() {
		void* retVal;
		pthread_join(_Thread, &retVal);
	}
}


text:
title: Date manipulation
id: 5966c21cf732a95f1b67dd28
challengeType: 5
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert(typeof add12Hours === "function", "<code>add12Hours</code> is a function.");'
  - text: ''
    testString: 'assert(typeof add12Hours(tests[0]) === "string", "<code>add12Hours(dateString)</code> should return a string.");'
  - text: ''
    testString: 'assert(add12Hours(tests[0]) === answers[0], "<code>add12Hours("" + tests[0] + "")</code> should return <code>"" + answers[0] + ""</code>");'
  - text: ''
    testString: 'assert(add12Hours(tests[1]) === answers[1], "Should handel day change. <code>add12Hours("" + tests[1] + "")</code> should return <code>"" + answers[1] + ""</code>");'
  - text: ''
    testString: 'assert(add12Hours(tests[2]) === answers[2], "Should handel month change in a leap years. <code>add12Hours("" + tests[2] + "")</code> should return <code>"" + answers[2] + ""</code>");'
  - text: ''
    testString: 'assert(add12Hours(tests[3]) === answers[3], "Should handel month change in a common years. <code>add12Hours("" + tests[3] + "")</code> should return <code>"" + answers[3] + ""</code>");'
  - text: ''
    testString: 'assert(add12Hours(tests[4]) === answers[4], "Should handel year change. <code>add12Hours("" + tests[4] + "")</code> should return <code>"" + answers[4] + ""</code>");'

```

## Challenge Seed

```js
function add12Hours (dateString) {
  // Good luck!
  return true;
}

```

### After Test

```js
console.info('after the test');
```

## Solution

```js
// solution required
```


text:
module.exports = (req, res) => {
  res.end('Hello from Lambda!');
};


text:
<?php

/**
 * Exceptions that can be thrown during the validation process
 *
 * @author johnj
 */
class SchumacherFM_Sqrl_Model_Trianglman_Sqrl_SqrlException extends \Exception
{
    const ENFORCE_IP_FAIL = 1;

    const SIGNED_URL_DOESNT_MATCH = 2;

    const NONCE_NOT_FOUND = 3;

    const SIGNATURE_NOT_VALID = 4;

    const EXPIRED_NONCE = 5;

    const DATABASE_NOT_CONFIGURED = 6;

    const DATABASE_EXCEPTION = 7;
}


text: from pyscf.gw.gw import GW


text:
package org.jboss.as.quickstarts.datagrid.carmart.session;

import org.infinispan.api.BasicCacheContainer;

/**
 *
 * Subclasses should create an instance of a cache manager (DefaultCacheManager, RemoteCacheManager, etc.)
 *
 * @author Martin Gencur
 *
 */
public interface CacheContainerProvider {

    public BasicCacheContainer getCacheContainer();

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.raptor.legacy.util;

import com.google.common.collect.ComparisonChain;
import com.google.common.util.concurrent.ExecutionList;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.log.Logger;

import javax.annotation.concurrent.ThreadSafe;

import java.util.Comparator;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

/**
 * This class is based on io.airlift.concurrent.BoundedExecutor
 */
@ThreadSafe
public class PrioritizedFifoExecutor<T extends Runnable>
{
    private static final Logger log = Logger.get(PrioritizedFifoExecutor.class);

    private final Queue<FifoRunnableTask<T>> queue;
    private final AtomicInteger queueSize = new AtomicInteger(0);
    private final AtomicLong sequenceNumber = new AtomicLong(0);
    private final Runnable triggerTask = this::executeOrMerge;

    private final ExecutorService executorService;
    private final int maxThreads;
    private final Comparator<T> taskComparator;

    public PrioritizedFifoExecutor(ExecutorService coreExecutor, int maxThreads, Comparator<T> taskComparator)
    {
        checkArgument(maxThreads > 0, "maxThreads must be greater than zero");

        this.taskComparator = requireNonNull(taskComparator, "taskComparator is null");
        this.executorService = requireNonNull(coreExecutor, "coreExecutor is null");
        this.maxThreads = maxThreads;
        this.queue = new PriorityBlockingQueue<>(maxThreads);
    }

    public ListenableFuture<Void> submit(T task)
    {
        FifoRunnableTask<T> fifoTask = new FifoRunnableTask<>(task, sequenceNumber.incrementAndGet(), taskComparator);
        queue.add(fifoTask);
        executorService.submit(triggerTask);
        return fifoTask;
    }

    private void executeOrMerge()
    {
        int size = queueSize.incrementAndGet();
        if (size > maxThreads) {
            return;
        }
        do {
            try {
                queue.poll().run();
            }
            catch (Throwable e) {
                log.error(e, "Task failed");
            }
        }
        while (queueSize.getAndDecrement() > maxThreads);
    }

    private static class FifoRunnableTask<T extends Runnable>
            extends FutureTask<Void>
            implements ListenableFuture<Void>, Comparable<FifoRunnableTask<T>>
    {
        private final ExecutionList executionList = new ExecutionList();
        private final T task;
        private final long sequenceNumber;
        private final Comparator<T> taskComparator;

        public FifoRunnableTask(T task, long sequenceNumber, Comparator<T> taskComparator)
        {
            super(requireNonNull(task, "task is null"), null);
            this.task = task;
            this.sequenceNumber = sequenceNumber;
            this.taskComparator = requireNonNull(taskComparator, "taskComparator is null");
        }

        @Override
        public void addListener(Runnable listener, Executor executor)
        {
            executionList.add(listener, executor);
        }

        @Override
        protected void done()
        {
            executionList.execute();
        }

        @Override
        public int compareTo(FifoRunnableTask<T> other)
        {
            return ComparisonChain.start()
                    .compare(this.task, other.task, taskComparator)
                    .compare(this.sequenceNumber, other.sequenceNumber)
                    .result();
        }

        @Override
        public boolean equals(Object o)
        {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            FifoRunnableTask<?> other = (FifoRunnableTask<?>) o;
            return Objects.equals(this.task, other.task) &&
                    Objects.equals(this.sequenceNumber, other.sequenceNumber);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(task, sequenceNumber);
        }
    }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/common', __FILE__)

describe "BasicObject" do
  it "raises NoMethodError for nonexistent methods after #method_missing is removed" do
    script = fixture __FILE__, "remove_method_missing.rb"
    ruby_exe(script).chomp.should == "NoMethodError"
  end

  it "raises NameError when referencing built-in constants" do
    lambda { class BasicObjectSpecs::BOSubclass; Kernel; end }.should raise_error(NameError)
  end

  it "does not define built-in constants (according to const_defined?)" do
    BasicObject.const_defined?(:Kernel).should be_false
  end

  it "does not define built-in constants (according to defined?)" do
    BasicObjectSpecs::BOSubclass.kernel_defined?.should be_nil
  end

  it "includes itself in its list of constants" do
    BasicObject.constants.should include(:BasicObject)
  end
end

describe "BasicObject metaclass" do
  before :each do
    @meta = class << BasicObject; self; end
  end

  it "is an instance of Class" do
    @meta.should be_an_instance_of(Class)
  end

  it "has Class as superclass" do
    @meta.superclass.should equal(Class)
  end

  it "contains methods for the BasicObject class" do
    @meta.class_eval do
      def rubyspec_test_method() :test end
    end

    BasicObject.rubyspec_test_method.should == :test
  end
end

describe "BasicObject instance metaclass" do
  before :each do
    @object = BasicObject.new
    @meta = class << @object; self; end
  end

  it "is an instance of Class" do
    @meta.should be_an_instance_of(Class)
  end

  it "has BasicObject as superclass" do
    @meta.superclass.should equal(BasicObject)
  end

  it "contains methods defined for the BasicObject instance" do
    @meta.class_eval do
      def test_method() :test end
    end

    @object.test_method.should == :test
  end
end

describe "BasicObject subclass" do
  it "contains Kernel methods when including Kernel" do
    obj = BasicObjectSpecs::BOSubclass.new

    obj.instance_variable_set(:@test, :value)
    obj.instance_variable_get(:@test).should == :value

    obj.send(:hash).should be_an_instance_of(Fixnum)
  end
end


text:
package main

import (
	"errors"
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	"os"
)

type StorageUtil struct {
	Bucket string
	Region string
	svc    *s3.S3
	ssn    *session.Session
}

func (this *StorageUtil) init() error {
	config := &aws.Config{}
	if this.Region != "" {
		config.Region = &this.Region
	}

	this.ssn = session.New(config)
	svc := s3.New(this.ssn)
	this.svc = svc
	if !this.isBucketExists(this.Bucket) {
		return errors.New(fmt.Sprintf("bucket %s not exists", this.Bucket))
	}

	return nil
}

func (this *StorageUtil) isBucketExists(name string) bool {
	input := &s3.HeadBucketInput{Bucket: &name}
	_, err := this.svc.HeadBucket(input)
	if err == nil {
		return true
	} else {
		return false
	}
}

func (this *StorageUtil) getFileInfo(fileName string) (*s3.HeadObjectOutput, error) {
	input := &s3.HeadObjectInput{Bucket: &this.Bucket, Key: &fileName}
	info, err := this.svc.HeadObject(input)
	return info, err
}

func (this *StorageUtil) upload(fileName string, fileLocation string, fingerPrint string) (string, error) {
	f, err := os.Open(fileLocation)
	defer f.Close()

	if err != nil {
		return "", err
	}

	metadata := map[string]*string{}
	metadata["fingerprint"] = &fingerPrint

	uploader := s3manager.NewUploader(this.ssn)

	result, err := uploader.Upload(&s3manager.UploadInput{
		Bucket:   &this.Bucket,
		Key:      &fileName,
		Body:     f,
		Metadata: metadata,
	})

	if err != nil {
		return "", err
	} else {
		return result.Location, nil
	}
}


text:
namespace Discord
{
    /// <summary>
    ///     Specifies the verification level the guild uses.
    /// </summary>
    public enum VerificationLevel
    {
        /// <summary>
        ///     Users have no additional restrictions on sending messages to this guild.
        /// </summary>
        None = 0,
        /// <summary>
        ///     Users must have a verified email on their account.
        /// </summary>
        Low = 1,
        /// <summary>
        ///     Users must fulfill the requirements of Low and be registered on Discord for at least 5 minutes.
        /// </summary>
        Medium = 2,
        /// <summary>
        ///     Users must fulfill the requirements of Medium and be a member of this guild for at least 10 minutes.
        /// </summary>
        High = 3,
        /// <summary>
        ///     Users must fulfill the requirements of High and must have a verified phone on their Discord account.
        /// </summary>
        Extreme = 4
    }
}


text:
var prefs;
function refresh_options() {
  chrome.storage.sync.get({
    defaultfontSize: 48,
    showAllMessages: false,
    showMyMessages: false,
    showUsername: false,
    pinWeixinTab: false,
    showNotifications: false,
    danmuDebug: false
  }, function(items) { prefs = items; });
}
refresh_options();
chrome.storage.onChanged.addListener(refresh_options);

// Global Variables
var activated = false;
var hb_timer;

// Toolbar Button
chrome.browserAction.onClicked.addListener(function(tab) {
  if (prefs.danmuDebug) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      var counter = 0;
      var timer = setInterval(function() {
        if (counter++ < 10) {
          chrome.tabs.sendMessage(tabs[0].id, {
            type: 'danmu',
            message: {user:{name: '弹幕测试'}, content:{text: randomString(), image: ''}}
          });
        }
        else {
          window.clearInterval(timer);
        }
      }, 500);
    });
  } else {
    if (activated) {
      chrome.tabs.create({
        url: 'http://aidistan.github.io/browser-weixin-danmu/helper.html'
      });
    }
    else {
      chrome.tabs.create({
        url: 'https://wx.qq.com/',
        pinned: prefs.pinWeixinTab
      });
    }
  }
});

// Recieve messages
chrome.runtime.onMessage.addListener(function(request) {
  if (request.type === 'weixin') {
    if (prefs.showAllMessages || request.message.room == 'inside') {
      chrome.runtime.sendMessage({
        type: 'notification',
        message: { title: '已捕获到消息', text: request.message.content.text }
      });

      if (request.message.user.isSelf && !prefs.showMyMessages) return;

      chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        if (tabs[0] !== undefined) {
          chrome.tabs.sendMessage(tabs[0].id, { type: 'danmu', message: request.message });
        }
      });
    }
  } else if (request.type === 'heartbeat') {
    if (activated) {
      window.clearTimeout(hb_timer);
    }
    else {
      hookup();
    }
    hb_timer = setTimeout(breakup, 5000);
  } else if (request.type === 'notification' && prefs.showNotifications) {
    chrome.notifications.create('notification', {
      type: "basic",
      iconUrl: 'data/icons/icon.png',
      title: request.message.title,
      message: request.message.text
    });
  }
});

function hookup() {
  chrome.runtime.sendMessage({
    type: 'notification',
    message: { title: '已登陆网页微信', text: '开始监听微信消息' }
  });
  activated = true;
  chrome.browserAction.setIcon({
    path: 'data/icons/icon-16.png'
  });
}

function breakup() {
  chrome.runtime.sendMessage({
    type: 'notification',
    message: { title: '已退出网页微信', text: '不再监听微信消息' }
  });
  activated = false;
  chrome.browserAction.setIcon({
    path: 'data/icons/icon-o-16.png'
  });
}

function randomString(len) {
  len = len || 32;
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy0z123456789';
  var maxPos = chars.length;
  var str = '';
  for (_i = 0; _i < len; _i++) {
    str += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return str;
}


text:
<?php

namespace Webburza\Sylius\ArticleBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * @Annotation
 */
class NotBlankIfActive extends NotBlank
{
    // ...
}