text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>Class: InstantCache::Blob</title>

  <link rel="stylesheet" href="../rdoc.css" type="text/css" media="screen" />

          Home
          Classes
          Methods

In Files

lib/instantcache.rb

Parent

Object

Methods

::memcached_accessor

::memcached_reader

::new

#create_identity

#destroy!

#destroyed?

#get

#lock

#name

#read

#reset

#set

#to_s

#unlock

#write

Files

History.txt

LICENCE.txt

Manifest.txt

README.txt

Class/Module Index

        <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
        <fieldset>
          <legend>Quicksearch</legend>
          <input type="text" name="quicksearch" value=""
            class="quicksearch-field" />
        </fieldset>
        </form>

InstantCache

InstantCache::Blob

InstantCache::ConnexionLost

InstantCache::Counter

InstantCache::CounterIntegerOnly

InstantCache::Destroyed

InstantCache::Exception

InstantCache::IncompatibleType

InstantCache::IncompleteException

InstantCache::LockInconsistency

InstantCache::NoCache

InstantCache::SharedOnly

No matching classes.

InstantCache::Blob

The 'Blob' class is used to store data of arbitrary and opaque format
in the cache.  This is used for just about all cases except integer
counters, which have their own class.

Constants

RESET_VALUE

When a cached value of this type is reset or cleared, exactly what value is
used to do so?  This is overridden in subclasses as needed.

Attributes

            expiry[RW]

Memcache expiration (lifetime) for this entity.  Defaults to zero.

            identity[R]

When we lock a cell in the shared cache, we do so by creating another cell
with a related name, in which we store info about ourself so that problems
can be traced back to the correct thread/process/system.  That identity is
stored here.

            locked_by_us[R]

When we lock a memcached cell, not only do we hang our identity on a
interlock cell, but we record the fact locally.

            rawmode[R]

@rawmode is used to signal whether the object is a counter or not.
Counters require memcache raw mode in order for increment/decrement to
work; non-raw values are marshalled before storage and hence not atomically
accessible in a short instruction stream.

Public Class Methods

            memcached_accessor(symbol[,...])

            click to toggle source

            memcached_accessor(symbol[,...]) { |symbol| ... }

Description

Access method declarator for a read/write memcache-backed variable.

This declarator sets up several methods relating to the variable.  If the
name passed is <tt>:ivar</tt>, these methods are created for it:

ivar

Normal read accessor (e.g., <tt>obj.ivar</tt>). (See Blob#set)

ivar=

Normal write accessor (e.g., <tt>obj.ivar = 17</tt>). (See Blob#get)

ivar_reset

Resets the cache variable to the default 'uninitialised' value. (See Blob#reset)

ivar_expiry

Returns the current cache lifetime (default 0). (See Blob#expiry)

ivar_expiry=

Sets the cache lifetime. (See Blob#expiry=)

ivar_lock

Tries to get an exclusive lock on the variable. (See Blob#lock)

ivar_unlock

Unlocks the variable if locked. (See Blob#unlock)

ivar_destroyed?

Returns true if variable is disconnected from the cache and unusable. (See
Blob#destroyed?)

ivar_destroy!

Disconnects the variable from the cache and makes it unusable. (See Blob#destroy!)

Arguments

symbol

As with other Ruby accessor declarations, the argument list consists of one
or more variable names represented as symbols (e.g.,
<tt>:variablename</tt>).

{block}

If a block is supplied, its return value must be a string, which will be
used as the name of the memcached cell backing the variable.  The argument
to the block is the name of the variable as passed to the accessor
declaration.

Exceptions

None.

# File lib/instantcache.rb, line 285
def memcached_accessor(*args, &block) ; end

            memcached_reader(symbol[,...])

            click to toggle source

            memcached_reader(symbol[,...]) { |symbol| ... }

Description

Access method declarator for a read-only memcache-backed variable.

This declarator sets up several methods relating to the variable.  If the
name passed is <tt>:ivar</tt>, these methods are created for it:

ivar

Normal read accessor (e.g., <tt>obj.ivar</tt>). (See Blob#get)

ivar_reset

Resets the cache variable to the default 'uninitialised' value. (See Blob#reset)

ivar_expiry

Returns the current cache lifetime (default 0). (See Blob#expiry)

ivar_expiry=

Sets the cache lifetime. (See Blob#expiry=)

ivar_lock

Tries to get an exclusive lock on the variable. (See Blob#lock)

ivar_unlock

Unlocks the variable if locked. (See Blob#unlock)

ivar_destroyed?

Returns true if variable is disconnected from the cache and unusable. (See
Blob#destroyed?)

ivar_destroy!

Disconnects the variable from the cache and makes it unusable. (See Blob#destroy!)

Arguments

symbol

As with other Ruby accessor declarations, the argument list consists of one
or more variable names represented as symbols (e.g.,
<tt>:variablename</tt>).

{block}

If a block is supplied, its return value must be a string, which will be
used as the name of the memcached cell backing the variable.  The argument
to the block is the name of the variable as passed to the accessor
declaration.

Exceptions

None.

# File lib/instantcache.rb, line 339
def memcached_reader(*args, &block) ; end

            new([val])

            click to toggle source

Description

Constructor for a normal (i.e., non-counter) variable stored in
the cache.  This is not intended to be invoked directly except by Those Who
Know What They're Doing; rather, cached variables should be declared with
the accessor methods <tt>Blob#memcached_accessor</tt> (for read/write
access) and <tt>Blob#memcached_reader</tt> (for read-only).

Arguments

val

Value to be loaded into the cache cell. N.B.: If the cell in
question is shared, this will overwrite the current value if any!

Exceptions

None.

# File lib/instantcache.rb, line 398
def initialize(inival=nil)
  #
  # This method is defined in the Blob class, for which raw mode
  # is a no-no.  However, to allow simple subclassing, we only set
  # @rawmode if a potential subclass' #initialize hasn't done so.
  # Thus subclasses can get most of the setup work done with a
  # simple invocation of #super.
  #
  @rawmode ||= false
  @expiry = 0
  @locked_by_us = false
  #
  # Fill in our identity for purposes of lock ownership.
  #
  @identity = self.create_identity
  #
  # If we were given an initial value, go ahead and store it.
  # <b>N.B.:</b> If the cell in question is shared, this
  # <b>will</b> overwrite the current value if any!
  #
  self.set(inival) unless(inival.nil?)
end

Public Instance Methods

            create_identity()
            click to toggle source

Description

Create a string that should uniquely identify this instance and a way to
locate it.  This is stored in the interlock cell when we obtain exclusive
access to the main cached cell, so that we can be tracked down in case of
hangs or other problems.

This method can be overridden at need.

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 438
def create_identity
  raise Destroyed.new(self.name) if (self.destroyed?)
  idfmt = 'host[%s]:pid[%d]:thread[%d]:%s[%d]'
  idargs = []
  idargs << `hostname`.chomp.strip
  idargs << $$
  idargs << Thread.current.object_id
  idargs << self.class.name.sub(%^.*::!, '')
  idargs << self.object_id
  return idfmt % idargs
end

            destroy!()
            click to toggle source

Description

Marks this instance as destroyed – that is to say, any connexion
it has to any cached value is severed.  Any outstanding lock on the cache
entry is released.  This instance will no longer be usable.

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 535
def destroy!
  raise Destroyed.new(self.name) if (self.destroyed?)
  self.unlock
  self.instance_eval('def destroyed? ; return true ; end')
  return nil
end

            destroyed?()
            click to toggle source

Description

Returns true or false according to whether this variable instance has been
irrevocably disconnected from any value in the cache.

When the instance is destroyed, this method is redefined to return
true.

Arguments

None.

Exceptions

None.

# File lib/instantcache.rb, line 516
def destroyed?
  return false
end

            get()
            click to toggle source

Description

Fetch the value out of memcached.  Before being returned to the called, the
value is annotated with singleton methods intended to keep the cache
updated with any changes made to the value we're returning.

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 674
def get
  raise Destroyed.new(self.name) if (self.destroyed?)
  #
  # TODO: Another instance of poor-man's-cache-location; see #reset
  #
  value = InstantCache.cache.get(self.name, self.rawmode)
  begin
    #
    # Make a copy of the thing we fetched out of the cache.
    #
    value.clone
    #
    # Add a note to it about who we are (so that requests can be
    # appropriately directed).
    #
    value.instance_variable_set(:@_instantcache_owner, self)
    #
    # Add the singleton annotations.
    #
    InstantCache.enwrap(value)
  rescue
    #
    # If the value was something we couldn't clone, like a Fixnum,
    # it's inherently immutable and we don't need to add no
    # steenkin' singleton methods to it.  That's our position
    # ayup.
    #
  end
  return value
end

            Also aliased as: read

            lock => Boolean

            click to toggle source

Description

Try to obtain an interlock on the memcached cell.  If successful, returns
true – else, the cell is locked by someone else and we should proceed
accordingly.

N.B.: This makes use of the memcached convention that #add is a
no-op if the cell already exists; we use that to try to create the
interlock cell.

The return value is wither <tt>true</tt> if we obtained (or already
held) an exclusive lock, or <tt>false</tt> if we failed and/or
someone else has it locked exclusively.

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 587
def lock
  raise Destroyed.new(self.name) if (self.destroyed?)
  return true if (@locked_by_us)
  #
  # TODO: Another instance of poor-man's-cache-location; see #reset
  #
  sts = InstantCache.cache.add(self.lock_name, @identity)
  @locked_by_us = (sts.to_s =~ %^STORED!) ? true : false
  return @locked_by_us
end

            name()
            click to toggle source

Description

The name of the variable declared with #memcached_accessor and friends does
not necessarily equate to the name of the cell in the cache.  This
method is responsible for creating the latter; the name it returns is also
used to identify the interlock cell.

This method must be overridden by subclassing; there is no default
name syntax for the memcache cells.  (This is done automatically by the
<tt>memcached_xxx</tt> accessor declarations.)

Arguments

None.

Exceptions

<tt>RuntimeError</tt>

This method has not been overridden as required.

# File lib/instantcache.rb, line 497
def name
  raise RuntimeError.new('#name method must be defined in instance')
end

            read()
            click to toggle source

            Alias for: get

            reset => default reset value

            click to toggle source

Description

Reset the cache value to its default (typically zero or nil).

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 465
def reset
  raise Destroyed.new(self.name) if (self.destroyed?)
  rval = nil
  if (self.class.constants.include?('RESET_VALUE'))
    rval = self.class.const_get('RESET_VALUE')
  end
  #
  # TODO: This can mess with subclassing; need better way to find the cache
  #
  InstantCache.cache.set(self.name, rval, self.expiry, self.rawmode)
  return rval
end

            set(val_p)
            click to toggle source

Description

Store a value for the cell into the cache.  We need to remove any singleton
annotation methods before storing because the memcache gem can't handle
them (actually, Marshal#dump, which memcache uses, cannot handle them).

N.B.: We don't remove any annotations from the original
value; it might be altered again, in which case we'd want to update the
cache again.  This can lead to some odd situations; see the bug list.

Arguments

val_p

The new value to be stored.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 726
def set(val_p)
  raise Destroyed.new(self.name) if (self.destroyed?)
  begin
    val = val_p.clone
  rescue TypeError => e
    val = val_p
  end
  #
  InstantCache.unwrap(val)
  #
  # TODO: Another instance of poor-man's-cache-location; see #reset
  #
  # We use both memcache#add and memcache#set for completeness.
  #
  InstantCache.cache.add(self.name, val, self.expiry, self.rawmode)
  InstantCache.cache.set(self.name, val, self.expiry, self.rawmode)
  #
  # Return the value as fetched through our accessor; this ensures
  # the proper annotation.
  #
  return self.get
end

            Also aliased as: write

            to_s(*args)
            click to toggle source

Description

Return the string representaton of the value, not this instance. This is
part of our 'try to be transparent' sensitivity training.

Arguments

Any appropriate to the to_s method of
the underlying data's class.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

# File lib/instantcache.rb, line 764
def to_s(*args)
  raise Destroyed.new(self.name) if (self.destroyed?)
  return self.get.__send__(:to_s, *args)
end

            unlock => Boolean

            click to toggle source

Description

If we have the cell locked, unlock it by deleting the interlock cell
(allowing someone else's lock(#add)
to work).

This method returns <tt>true</tt> if we held the lock and have released it,
or false if we didn't own the lock or the cell isn't locked at all.

Arguments

None.

Exceptions

<tt>InstantCache::Destroyed</tt>

Cache value instance has been destroyed and is no longer usable. The value
in the cache is unaffected.

<tt>InstantCache::LockInconsistency</tt>

The state of the lock on the cell as stored in memcache differs from our
local understanding of things. Specifically, we show it as locked by us,
but the cache disagrees.

# File lib/instantcache.rb, line 628
def unlock
  raise Destroyed.new(self.name) if (self.destroyed?)
  #
  # TODO: Another instance of poor-man's-cache-location; see #reset
  #
  sts = InstantCache.cache.get(self.lock_name) || false
  if (@locked_by_us && (sts != @identity))
    #
    # If we show we have the lock, but the lock cell doesn't exist
    # (or isn't us), that's definitely an inconsistency.
    #
    e = LockInconsistency.new(self.lock_name,
                              @identity,
                              sts.inspect)
    raise e
  end
  return false unless (@locked_by_us)
  @locked_by_us = false
  #
  # TODO: Another instance of poor-man's-cache-location; see #reset
  #
  sts = InstantCache.cache.delete(self.lock_name)
  if (sts !~ %^DELETED!)
    e = LockInconsistency.new(self.lock_name,
                              '/DELETED/',
                              sts.inspect)
    raise e
  end
  return true
end

            write(val_p)
            click to toggle source

            Alias for: set

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
export function setToken (token) {
  return {
    type: 'SET_TOKEN',
    payload: token
  }
}

export function dntm() {
  return {
    type: 'DNTM'
  }
}

redpajama_set_name: RedPajamaGithub


text:
FROM ubuntu:latest

MAINTAINER knipferrc <knipferrc@gmail.com>

RUN apt-get update && apt-get install -y \
    curl \
    git \
    wget \
    sudo \
    nano \
    vim \
    python3 \
    python \
    build-essential \
    tar \
    locales

RUN locale-gen en_US.UTF-8

RUN curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - \
  && apt-get install nodejs -y \
  && curl https://install.meteor.com/ | sh \
  && wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh \
  && curl -O https://storage.googleapis.com/golang/go1.7.1.linux-amd64.tar.gz \
  && tar -xvf go1.7.1.linux-amd64.tar.gz \
  && mv go /usr/local \
  && rm -r go1.7.1.linux-amd64.tar.gz

RUN npm i -g create-react-app \
  && npm i -g firebase-tools

ENV PATH=$PATH:/usr/local/go/bin

RUN adduser --disabled-password --gecos '' devbox

USER devbox

RUN mkdir ~/work

WORKDIR /home/devbox/work

RUN meteor --version \
  && heroku version


text:
// Copyright 2014 The Cloud Input Tools Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Defines the global event target.
 */

goog.provide('i18n.input.common.events.GlobalEventTarget');

goog.require('goog.events.EventTarget');

/**
 * The global event target used to expose the events from Plugin level to
 * Controller level.
 *
 * @extends {goog.events.EventTarget}
 * @constructor
 */
i18n.input.common.events.GlobalEventTarget = function() {
  goog.base(this);
};
goog.inherits(i18n.input.common.events.GlobalEventTarget,
    goog.events.EventTarget);
goog.addSingletonGetter(i18n.input.common.events.GlobalEventTarget);


text:
package org.marketcetera.photon.internal.strategy.engine.ui.workbench;

import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.ICommonLabelProvider;
import org.marketcetera.photon.commons.ui.databinding.PropertyWatcher;
import org.marketcetera.photon.commons.ui.databinding.PropertyWatcher.IPropertiesChangedListener;
import org.marketcetera.photon.strategy.engine.ui.StrategyEngineStatusDecorator;
import org.marketcetera.photon.strategy.engine.ui.StrategyEnginesContentProvider;
import org.marketcetera.photon.strategy.engine.ui.StrategyEnginesLabelProvider;
import org.marketcetera.photon.strategy.engine.ui.workbench.StrategyEngineWorkbenchUI;
import org.marketcetera.util.misc.ClassVersion;

import com.google.common.collect.ImmutableSet;

/* $License$ */

/**
 * This label provider enhances {@link StrategyEnginesLabelProvider} to support
 * {@link ICommonLabelProvider}. It also hooks up label redecoration to the
 * content provider's elements.
 *
 * @author Will Horn
 * @version $Id: StrategyEnginesCommonLabelProvider.java 16154 2012-07-14 16:34:05Z colin $
 * @since 2.0.0
 */
@ClassVersion("$Id: StrategyEnginesCommonLabelProvider.java 16154 2012-07-14 16:34:05Z colin $")
public final class StrategyEnginesCommonLabelProvider extends StrategyEnginesLabelProvider implements
        ICommonLabelProvider {

    private final PropertyWatcher mDecorationPropertyWatcher = new PropertyWatcher(
            StrategyEngineStatusDecorator.PROPERTIES,
            new IPropertiesChangedListener() {
                @Override
                public void propertiesChanged(ImmutableSet<?> affectedElements) {
                    PlatformUI
                            .getWorkbench()
                            .getDecoratorManager()
                            .update(
                                    StrategyEngineWorkbenchUI.STRATEGY_ENGINES_STATUS_DECORATOR_ID);
                }
            });

    @Override
    public void init(ICommonContentExtensionSite aConfig) {
        final IObservableSet elements = ((StrategyEnginesContentProvider) aConfig
                .getExtension().getContentProvider()).getKnownElements();
        track(elements);
        mDecorationPropertyWatcher.watch(elements);
    }

    @Override
    public void restoreState(IMemento aMemento) {
    }

    @Override
    public void saveState(IMemento aMemento) {
    }

    @Override
    public String getDescription(Object anElement) {
        return getText(anElement);
    }

    @Override
    public void dispose() {
        mDecorationPropertyWatcher.dispose();
        super.dispose();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.eugenewyj</groupId>
        <artifactId>java9-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>service-prime-generic</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.eugenewyj</groupId>
            <artifactId>service-prime</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/main/org.eugene.service.prime.generic</sourceDirectory>
    </build>
</project>


text:
namespace MyGUI
{

	OpenGLESDataManager::OpenGLESDataManager() :
		mIsInitialise(false)
	{
	}

	void OpenGLESDataManager::initialise()
	{
		MYGUI_PLATFORM_ASSERT(!mIsInitialise, getClassTypeName() << " initialised twice");
		MYGUI_PLATFORM_LOG(Info, "* Initialise: " << getClassTypeName());

		MYGUI_PLATFORM_LOG(Info, getClassTypeName() << " successfully initialized");
		mIsInitialise = true;
	}

	void OpenGLESDataManager::shutdown()
	{
		MYGUI_PLATFORM_ASSERT(mIsInitialise, getClassTypeName() << " is not initialised");
		MYGUI_PLATFORM_LOG(Info, "* Shutdown: " << getClassTypeName());

		MYGUI_PLATFORM_LOG(Info, getClassTypeName() << " successfully shutdown");
		mIsInitialise = false;
	}

	IDataStream* OpenGLESDataManager::getData(const std::string& _name)
	{
		std::string filepath = getDataPath(_name);
		if (filepath.empty())
			return nullptr;

		std::ifstream* stream = new std::ifstream();
		stream->open(filepath.c_str(), std::ios_base::binary);

		if (!stream->is_open())
		{
			delete stream;
			return nullptr;
		}

		DataFileStream* data = new DataFileStream(stream);

		return data;
	}

	bool OpenGLESDataManager::isDataExist(const std::string& _name)
	{
		const VectorString& files = getDataListNames(_name);
		return files.size() == 1;
	}

	const VectorString& OpenGLESDataManager::getDataListNames(const std::string& _pattern)
	{
		static VectorString result;
		common::VectorWString wresult;
		result.clear();

		for (VectorArhivInfo::const_iterator item = mPaths.begin(); item != mPaths.end(); ++item)
		{
			common::scanFolder(wresult, (*item).name, (*item).recursive, MyGUI::UString(_pattern).asWStr(), false);
		}

		for (common::VectorWString::const_iterator item = wresult.begin(); item != wresult.end(); ++item)
		{
			result.push_back(MyGUI::UString(*item).asUTF8());
		}

		return result;
	}

	const std::string& OpenGLESDataManager::getDataPath(const std::string& _name)
	{
		static std::string path;
		VectorString result;
		common::VectorWString wresult;

		for (VectorArhivInfo::const_iterator item = mPaths.begin(); item != mPaths.end(); ++item)
		{
			common::scanFolder(wresult, (*item).name, (*item).recursive, MyGUI::UString(_name).asWStr(), true);
		}

		for (common::VectorWString::const_iterator item = wresult.begin(); item != wresult.end(); ++item)
		{
			result.push_back(MyGUI::UString(*item).asUTF8());
		}

		path = result.size() == 1 ? result[0] : "";
		return path;
	}

	void OpenGLESDataManager::addResourceLocation(const std::string& _name, bool _recursive)
	{
		ArhivInfo info;
		info.name = MyGUI::UString(_name).asWStr();
		info.recursive = _recursive;
		mPaths.push_back(info);
	}

} // namespace MyGUI


text:
module.exports = {
  extends: ["prettier"],
  parser: "babel-eslint",
  plugins: ["prettier", "flowtype"],
  rules: {
    "prettier/prettier": "error",
    "flowtype/define-flow-type": 1,
    "flowtype/use-flow-type": 1
  },
  settings: {
    flowtype: {
      onlyFilesWithFlowAnnotation: true
    }
  },
  globals: {
    advanceClock: false,
    afterEach: false,
    atom: false,
    beforeAll: false,
    beforeEach: false,
    describe: false,
    Event: false,
    expect: false,
    HTMLElement: false,
    HTMLInputElement: false,
    it: false,
    jasmine: false,
    spyOn: false,
    runs: false,
    xdescribe: false,
    setupBuses: false,
    waitsFor: false,
    waitsForPromise: false
  }
};


text:
package org.azizkhani.core.encryption;

import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256AndMD5 {
	public static String getSHA256(String input) {
		try {
				MessageDigest md = MessageDigest.getInstance("SHA-256");
				byte[] messageDigest = md.digest(input.getBytes());
				BigInteger number = new BigInteger(1, messageDigest);
				String hashtext = number.toString(16);
				// Now we need to zero pad it if you actually want the full 32 chars.
				while (hashtext.length() < 32) {
					hashtext = "0" + hashtext;
 					}
				return hashtext;         }
				catch (NoSuchAlgorithmException e) {
					throw new RuntimeException(e);
				}
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		System.out.println(getSHA256("admin"));

	}

}


text:
package chapter.three

import collection.JavaConversions.asScalaBuffer
import collection.mutable.Buffer

import java.awt.datatransfer.{ DataFlavor, SystemFlavorMap }

object ExerciseTen extends App {

  def imageFlavors(): Buffer[String] = {
    val flavors = SystemFlavorMap.getDefaultFlavorMap().asInstanceOf[SystemFlavorMap]

    flavors.getNativesForFlavor(DataFlavor.imageFlavor)
  }
}


text:
package android.content;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.ICancellationSignal;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;

import dalvik.system.CloseGuard;

import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * The public interface object used to interact with a {@link ContentProvider}. This is obtained by
 * calling {@link ContentResolver#acquireContentProviderClient}. This object must be released
 * using {@link #release} in order to indicate to the system that the {@link ContentProvider} is
 * no longer needed and can be killed to free up resources.
 *
 *
Note that you should generally create a new ContentProviderClient instance
 * for each thread that will be performing operations.  Unlike
 * {@link ContentResolver}, the methods here such as {@link #query} and
 * {@link #openFile} are not thread safe -- you must not call
 * {@link #release()} on the ContentProviderClient those calls are made from
 * until you are finished with the data they have returned.
 */
public class ContentProviderClient {
    private static final String TAG = "ContentProviderClient";

    @GuardedBy("ContentProviderClient.class")
    private static Handler sAnrHandler;

    private final ContentResolver mContentResolver;
    private final IContentProvider mContentProvider;
    private final String mPackageName;
    private final boolean mStable;

    private final CloseGuard mGuard = CloseGuard.get();

    private long mAnrTimeout;
    private NotRespondingRunnable mAnrRunnable;

    private boolean mReleased;

    /** {@hide} */
    ContentProviderClient(
            ContentResolver contentResolver, IContentProvider contentProvider, boolean stable) {
        mContentResolver = contentResolver;
        mContentProvider = contentProvider;
        mPackageName = contentResolver.mPackageName;
        mStable = stable;

        mGuard.open("release");
    }

    /** {@hide} */
    public void setDetectNotResponding(long timeoutMillis) {
        synchronized (ContentProviderClient.class) {
            mAnrTimeout = timeoutMillis;

            if (timeoutMillis > 0) {
                if (mAnrRunnable == null) {
                    mAnrRunnable = new NotRespondingRunnable();
                }
                if (sAnrHandler == null) {
                    sAnrHandler = new Handler(Looper.getMainLooper(), null, true /* async */);
                }
            } else {
                mAnrRunnable = null;
            }
        }
    }

    private void beforeRemote() {
        if (mAnrRunnable != null) {
            sAnrHandler.postDelayed(mAnrRunnable, mAnrTimeout);
        }
    }

    private void afterRemote() {
        if (mAnrRunnable != null) {
            sAnrHandler.removeCallbacks(mAnrRunnable);
        }
    }

    /** See {@link ContentProvider#query ContentProvider.query} */
    public @Nullable Cursor query(@NonNull Uri url, @Nullable String[] projection,
            @Nullable String selection, @Nullable String[] selectionArgs,
            @Nullable String sortOrder) throws RemoteException {
        return query(url, projection, selection,  selectionArgs, sortOrder, null);
    }

    /** See {@link ContentProvider#query ContentProvider.query} */
    public @Nullable Cursor query(@NonNull Uri url, @Nullable String[] projection,
            @Nullable String selection, @Nullable String[] selectionArgs,
            @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal)
                    throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            ICancellationSignal remoteCancellationSignal = null;
            if (cancellationSignal != null) {
                cancellationSignal.throwIfCanceled();
                remoteCancellationSignal = mContentProvider.createCancellationSignal();
                cancellationSignal.setRemote(remoteCancellationSignal);
            }
            return mContentProvider.query(mPackageName, url, projection, selection, selectionArgs,
                    sortOrder, remoteCancellationSignal);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#getType ContentProvider.getType} */
    public @Nullable String getType(@NonNull Uri url) throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.getType(url);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#getStreamTypes ContentProvider.getStreamTypes} */
    public @Nullable String[] getStreamTypes(@NonNull Uri url, @NonNull String mimeTypeFilter)
            throws RemoteException {
        Preconditions.checkNotNull(url, "url");
        Preconditions.checkNotNull(mimeTypeFilter, "mimeTypeFilter");

        beforeRemote();
        try {
            return mContentProvider.getStreamTypes(url, mimeTypeFilter);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#canonicalize} */
    public final @Nullable Uri canonicalize(@NonNull Uri url) throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.canonicalize(mPackageName, url);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#uncanonicalize} */
    public final @Nullable Uri uncanonicalize(@NonNull Uri url) throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.uncanonicalize(mPackageName, url);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#insert ContentProvider.insert} */
    public @Nullable Uri insert(@NonNull Uri url, @Nullable ContentValues initialValues)
            throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.insert(mPackageName, url, initialValues);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#bulkInsert ContentProvider.bulkInsert} */
    public int bulkInsert(@NonNull Uri url, @NonNull ContentValues[] initialValues)
            throws RemoteException {
        Preconditions.checkNotNull(url, "url");
        Preconditions.checkNotNull(initialValues, "initialValues");

        beforeRemote();
        try {
            return mContentProvider.bulkInsert(mPackageName, url, initialValues);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#delete ContentProvider.delete} */
    public int delete(@NonNull Uri url, @Nullable String selection,
            @Nullable String[] selectionArgs) throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.delete(mPackageName, url, selection, selectionArgs);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#update ContentProvider.update} */
    public int update(@NonNull Uri url, @Nullable ContentValues values, @Nullable String selection,
            @Nullable String[] selectionArgs) throws RemoteException {
        Preconditions.checkNotNull(url, "url");

        beforeRemote();
        try {
            return mContentProvider.update(mPackageName, url, values, selection, selectionArgs);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /**
     * See {@link ContentProvider#openFile ContentProvider.openFile}.  Note that
     * this does not
     * take care of non-content: URIs such as file:.  It is strongly recommended
     * you use the {@link ContentResolver#openFileDescriptor
     * ContentResolver.openFileDescriptor} API instead.
     */
    public @Nullable ParcelFileDescriptor openFile(@NonNull Uri url, @NonNull String mode)
            throws RemoteException, FileNotFoundException {
        return openFile(url, mode, null);
    }

    /**
     * See {@link ContentProvider#openFile ContentProvider.openFile}.  Note that
     * this does not
     * take care of non-content: URIs such as file:.  It is strongly recommended
     * you use the {@link ContentResolver#openFileDescriptor
     * ContentResolver.openFileDescriptor} API instead.
     */
    public @Nullable ParcelFileDescriptor openFile(@NonNull Uri url, @NonNull String mode,
            @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
        Preconditions.checkNotNull(url, "url");
        Preconditions.checkNotNull(mode, "mode");

        beforeRemote();
        try {
            ICancellationSignal remoteSignal = null;
            if (signal != null) {
                signal.throwIfCanceled();
                remoteSignal = mContentProvider.createCancellationSignal();
                signal.setRemote(remoteSignal);
            }
            return mContentProvider.openFile(mPackageName, url, mode, remoteSignal, null);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /**
     * See {@link ContentProvider#openAssetFile ContentProvider.openAssetFile}.
     * Note that this does not
     * take care of non-content: URIs such as file:.  It is strongly recommended
     * you use the {@link ContentResolver#openAssetFileDescriptor
     * ContentResolver.openAssetFileDescriptor} API instead.
     */
    public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri url, @NonNull String mode)
            throws RemoteException, FileNotFoundException {
        return openAssetFile(url, mode, null);
    }

    /**
     * See {@link ContentProvider#openAssetFile ContentProvider.openAssetFile}.
     * Note that this does not
     * take care of non-content: URIs such as file:.  It is strongly recommended
     * you use the {@link ContentResolver#openAssetFileDescriptor
     * ContentResolver.openAssetFileDescriptor} API instead.
     */
    public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri url, @NonNull String mode,
            @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
        Preconditions.checkNotNull(url, "url");
        Preconditions.checkNotNull(mode, "mode");

        beforeRemote();
        try {
            ICancellationSignal remoteSignal = null;
            if (signal != null) {
                signal.throwIfCanceled();
                remoteSignal = mContentProvider.createCancellationSignal();
                signal.setRemote(remoteSignal);
            }
            return mContentProvider.openAssetFile(mPackageName, url, mode, remoteSignal);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#openTypedAssetFile ContentProvider.openTypedAssetFile} */
    public final @Nullable AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull Uri uri,
            @NonNull String mimeType, @Nullable Bundle opts)
                    throws RemoteException, FileNotFoundException {
        return openTypedAssetFileDescriptor(uri, mimeType, opts, null);
    }

    /** See {@link ContentProvider#openTypedAssetFile ContentProvider.openTypedAssetFile} */
    public final @Nullable AssetFileDescriptor openTypedAssetFileDescriptor(@NonNull Uri uri,
            @NonNull String mimeType, @Nullable Bundle opts, @Nullable CancellationSignal signal)
                    throws RemoteException, FileNotFoundException {
        Preconditions.checkNotNull(uri, "uri");
        Preconditions.checkNotNull(mimeType, "mimeType");

        beforeRemote();
        try {
            ICancellationSignal remoteSignal = null;
            if (signal != null) {
                signal.throwIfCanceled();
                remoteSignal = mContentProvider.createCancellationSignal();
                signal.setRemote(remoteSignal);
            }
            return mContentProvider.openTypedAssetFile(
                    mPackageName, uri, mimeType, opts, remoteSignal);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#applyBatch ContentProvider.applyBatch} */
    public @NonNull ContentProviderResult[] applyBatch(
            @NonNull ArrayList<ContentProviderOperation> operations)
                    throws RemoteException, OperationApplicationException {
        Preconditions.checkNotNull(operations, "operations");

        beforeRemote();
        try {
            return mContentProvider.applyBatch(mPackageName, operations);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /** See {@link ContentProvider#call(String, String, Bundle)} */
    public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
            @Nullable Bundle extras) throws RemoteException {
        Preconditions.checkNotNull(method, "method");

        beforeRemote();
        try {
            return mContentProvider.call(mPackageName, method, arg, extras);
        } catch (DeadObjectException e) {
            if (!mStable) {
                mContentResolver.unstableProviderDied(mContentProvider);
            }
            throw e;
        } finally {
            afterRemote();
        }
    }

    /**
     * Call this to indicate to the system that the associated {@link ContentProvider} is no
     * longer needed by this {@link ContentProviderClient}.
     * @return true if this was release, false if it was already released
     */
    public boolean release() {
        synchronized (this) {
            if (mReleased) {
                throw new IllegalStateException("Already released");
            }
            mReleased = true;
            mGuard.close();
            if (mStable) {
                return mContentResolver.releaseProvider(mContentProvider);
            } else {
                return mContentResolver.releaseUnstableProvider(mContentProvider);
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        if (mGuard != null) {
            mGuard.warnIfOpen();
        }
    }

    /**
     * Get a reference to the {@link ContentProvider} that is associated with this
     * client. If the {@link ContentProvider} is running in a different process then
     * null will be returned. This can be used if you know you are running in the same
     * process as a provider, and want to get direct access to its implementation details.
     *
     * @return If the associated {@link ContentProvider} is local, returns it.
     * Otherwise returns null.
     */
    public @Nullable ContentProvider getLocalContentProvider() {
        return ContentProvider.coerceToLocalContentProvider(mContentProvider);
    }

    /** {@hide} */
    public static void releaseQuietly(ContentProviderClient client) {
        if (client != null) {
            try {
                client.release();
            } catch (Exception ignored) {
            }
        }
    }

    private class NotRespondingRunnable implements Runnable {
        @Override
        public void run() {
            Log.w(TAG, "Detected provider not responding: " + mContentProvider);
            mContentResolver.appNotRespondingViaProvider(mContentProvider);
        }
    }
}


text:
<?php declare(strict_types=1);

namespace Granam\Integer\Exceptions;

interface Exception extends \Granam\Number\Exceptions\Exception
{

}


text:
package Paws::MachineLearning::DescribeTagsOutput;
  use Moose;
  has ResourceId => (is => 'ro', isa => 'Str');
  has ResourceType => (is => 'ro', isa => 'Str');
  has Tags => (is => 'ro', isa => 'ArrayRef[Paws::MachineLearning::Tag]');

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::MachineLearning::DescribeTagsOutput

=head1 ATTRIBUTES

=head2 ResourceId => Str

The ID of the tagged ML object.

=head2 ResourceType => Str

The type of the tagged ML object.

Valid values are: C<"BatchPrediction">, C<"DataSource">, C<"Evaluation">, C<"MLModel">
=head2 Tags => ArrayRef[L<Paws::MachineLearning::Tag>]

A list of tags associated with the ML object.

=head2 _request_id => Str

=cut

1;


text:
require 'spec_helper.rb'
require 'base64'

describe Rack::OAuth2::Server::Token do
  let(:request) { Rack::MockRequest.new app }
  let(:app) do
    Rack::OAuth2::Server::Token.new do |request, response|
      response.access_token = Rack::OAuth2::AccessToken::Bearer.new(access_token: 'access_token')
    end
  end
  let(:params) do
    {
      grant_type: 'authorization_code',
      client_id: 'client_id',
      code: 'authorization_code',
      redirect_uri: 'http://client.example.com/callback'
    }
  end
  subject { request.post('/token', params: params) }

  context 'when multiple client credentials are given' do
    context 'when different credentials are given' do
      let(:env) do
        Rack::MockRequest.env_for(
          '/token',
          'HTTP_AUTHORIZATION' => "Basic #{Base64.encode64('client_id2:client_secret')}",
          params: params
        )
      end
      it 'should fail with unsupported_grant_type' do
        status, headers, response = app.call(env)
        status.should == 400
        response.first.should include '"error":"invalid_request"'
      end
    end

    context 'when same credentials are given' do
      let(:env) do
        Rack::MockRequest.env_for(
          '/token',
          'HTTP_AUTHORIZATION' => "Basic #{Base64.encode64('client_id:client_secret')}",
          params: params
        )
      end
      it 'should ignore duplicates' do
        status, headers, response = app.call(env)
        status.should == 200
      end
    end
  end

  context 'when unsupported grant_type is given' do
    before do
      params.merge!(grant_type: 'unknown')
    end
    its(:status)       { should == 400 }
    its(:content_type) { should == 'application/json' }
    its(:body)         { should include '"error":"unsupported_grant_type"' }
  end

  [:client_id, :grant_type].each do |required|
    context "when #{required} is missing" do
      before do
        params.delete_if do |key, value|
          key == required
        end
      end
      its(:status)       { should == 400 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"error":"invalid_request"' }
    end
  end

  context 'when client_id is given via JWT client assertion' do
    before do
      require 'json/jwt'
      params[:client_assertion] = JSON::JWT.new(
        sub: params[:client_id]
        # NOTE: actual client_assertion should have more claims.
      ).sign('client_secret').to_s
      params[:client_assertion_type] = Rack::OAuth2::URN::ClientAssertionType::JWT_BEARER
      params.delete(:client_id)
    end

    context 'when client_assertion is invalid JWT' do
      before do
        params[:client_assertion] = 'invalid-jwt'
      end
      its(:status)       { should == 400 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"error":"invalid_request"' }
    end

    context 'when client_assertion_type is missing' do
      before do
        params.delete(:client_assertion_type)
      end
      its(:status)       { should == 400 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"error":"invalid_request"' }
    end

    context 'when client_assertion_type is unknown' do
      before do
        params[:client_assertion_type] = 'unknown'
      end
      its(:status)       { should == 400 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"error":"invalid_request"' }
    end

    context 'when client_assertion issuer is different from client_id' do
      before do
        params[:client_id] = 'another_client_id'
      end
      its(:status)       { should == 400 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"error":"invalid_request"' }
    end

    context 'otherwise' do
      its(:status)       { should == 200 }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include '"access_token":"access_token"' }
    end
  end

  Rack::OAuth2::Server::Token::ErrorMethods::DEFAULT_DESCRIPTION.each do |error, default_message|
    status = if error == :invalid_client
      401
    else
      400
    end
    context "when #{error}" do
      let(:app) do
        Rack::OAuth2::Server::Token.new do |request, response|
          request.send "#{error}!"
        end
      end
      its(:status)       { should == status }
      its(:content_type) { should == 'application/json' }
      its(:body)         { should include "\"error\":\"#{error}\"" }
      its(:body)         { should include "\"error_description\":\"#{default_message}\"" }
      if error == :invalid_client
        its(:headers)    { should include 'WWW-Authenticate' }
      end
    end
  end

  context 'when skip_www_authenticate option is specified on invalid_client' do
    let(:app) do
      Rack::OAuth2::Server::Token.new do |request, response|
        request.invalid_client!(
          Rack::OAuth2::Server::Token::ErrorMethods::DEFAULT_DESCRIPTION[:invalid_client],
          skip_www_authenticate: true
        )
      end
    end
    its(:headers) { should_not include 'WWW-Authenticate' }
  end

  context 'when responding' do
    context 'when access_token is missing' do
      let(:app) do
        Rack::OAuth2::Server::Token.new
      end
      it do
        expect { request.post('/', params: params) }.to raise_error AttrRequired::AttrMissing
      end
    end
  end

  describe 'extensibility' do
    before do
      require 'rack/oauth2/server/token/extension/example'
    end

    subject { app }
    let(:env) do
      Rack::MockRequest.env_for(
        '/token',
        params: params
      )
    end
    let(:request) { Rack::OAuth2::Server::Token::Request.new env }
    its(:extensions) { should == [Rack::OAuth2::Server::Token::Extension::Example] }

    describe 'JWT assertion' do
      let(:params) do
        {
          grant_type: 'urn:ietf:params:oauth:grant-type:example',
          assertion: 'header.payload.signature'
        }
      end

      it do
        app.send(
          :grant_type_for, request
        ).should == Rack::OAuth2::Server::Token::Extension::Example
      end
    end
  end
end


text:
body {
	padding-top: 50px;
}

.navbar-inverse .navbar-brand {
	color: #ccc;
	font-size: 24px;
}

.navbar-inverse .navbar-brand:hover {
	color: #ddd;
}

.navbar-inverse .navbar-brand:focus, .navbar-inverse .navbar-brand:hover {
	color: #ccc;
}

.navbar-inverse .navbar-nav>li>a:focus, .navbar-inverse .navbar-nav>li>a:hover {
	background-color: lightblue;
}

.navbar-inverse .navbar-collapse, .navbar-inverse .navbar-form {
	border-color: #efefef;
}

.annotation-instructions {
	margin-bottom: 15px;
	width: calc(100% - 160px);
	float: left;
}

.annotation-count {
	text-transform: uppercase;
	font-size: 0.8em;
	color: #666;
}

#toggle-annotations {
	width: 140px;
	float: right;
	background-size: 100%;
	margin-bottom: 15px;
	cursor: pointer;
	text-align: center;
	border: 1px solid #ccc;
	padding: 6px;
}

#toggle-annotations.annotations-visible {

}

.jumbotron {
	padding: 20px;
}

.panel-user, .panel-votes {
	margin: 1rem;
}

.panel-user {
	float: left;
	margin-right: 2rem;
}

.panel-user > .user-icon {
	border: 0.25rem #ccc solid;
	min-height: 5rem;
	width: 5rem;
	margin: 0 auto;
}

.user-comment {
	margin-top: .6rem;
}

.panel-votes {
	float: right;
	margin-left: 2rem;
	width: 3rem;
}

.panel-user > p.glyphicon, .panel-votes > a > p.glyphicon {
	font-size: 1.5em;
	display: block;
}

p.glyphicon {
	padding: .3rem;
}
.panel-user > p.glyphicon {
	padding: 1rem;
	font-size: 2em;
}

.panel-user > .user-name {
	font-size: 1.0rem;
	margin: 0.5rem;
}

.panel-votes > a {
	text-decoration: none;
	color: #999;
}
.panel-votes > a:hover {
	text-decoration: none;
	color: #000;
}

.gloss-image p.caption, .gloss-image p.credit {
	font-size: 1.0em;
	margin-top: 0.5em;
	display: inline-block;
}

.gloss-image p.caption {

}

.gloss-image p.credit {
	color: #ccc;
	display: inline;
}
.gloss-image p.credit a {
	color: #99e;
}

.navbar-inverse {
	background-color: #fff;
	border-color: #efefef;
}

.navbar-inverse .navbar-toggle {
	border-color: #ccc;
}

.navbar-inverse .navbar-toggle .icon-bar {
	background-color: #ccc;
}

.navbar-inverse .navbar-toggle:focus, .navbar-inverse .navbar-toggle:hover {
	background-color: #fff;
}

canvas.annotorious-item {
	-webkit-filter: blur(5px);
	mix-blend-mode: screen;
}


text:
<?php
namespace Sainsburys\HttpService\Components\ErrorHandling\Exceptions;

interface ExceptionWithHttpStatus
{
    public function getHttpStatusCode(): int;
}


text:
package siesta

// RequestWriter is used to decouple the message header/metadata writing from the actual message.
// It is able to accept a request and encode/write it according to Kafka Wire Protocol format
// adding the correlation id and client id to the request.
type RequestWriter struct {
	correlationId int32
	clientId      string
	request       Request
}

// Creates a new RequestWriter holding the correlation id, client id and the actual request.
func NewRequestWriter(correlationId int32, clientId string, request Request) *RequestWriter {
	return &RequestWriter{
		correlationId: correlationId,
		clientId:      clientId,
		request:       request,
	}
}

// Returns the size in bytes needed to write this request, including the length field. This value will be used when allocating memory for a byte array.
func (this *RequestWriter) Size() int32 {
	encoder := NewSizingEncoder()
	this.Write(encoder)
	return encoder.Size()
}

// Writes itself into a given Encoder.
func (this *RequestWriter) Write(encoder Encoder) {
	// write the size of request excluding the length field with length 4
	encoder.WriteInt32(encoder.Size() - 4)
	encoder.WriteInt16(this.request.Key())
	encoder.WriteInt16(this.request.Version())
	encoder.WriteInt32(this.correlationId)
	encoder.WriteString(this.clientId)
	this.request.Write(encoder)
}

// A generic interface for any request issued to Kafka. Must be able to identify and write itself.
type Request interface {
	// Writes the Request to the given Encoder.
	Write(Encoder)

	// Returns the Kafka API key for this Request.
	Key() int16

	// Returns the Kafka request version for backwards compatibility.
	Version() int16
}

// A generic interface for any response received from Kafka. Must be able to read itself.
type Response interface {
	// Read the Response from the given Decoder. May return a DecodingError if the response is invalid.
	Read(Decoder) *DecodingError
}

// A DecodingError is an error that also holds the information about why it happened.
type DecodingError struct {
	err    error
	reason string
}

// Creates a new DecodingError with a given error message and reason.
func NewDecodingError(err error, reason string) *DecodingError {
	return &DecodingError{err, reason}
}

// Returns the error message for this DecodingError.
func (this *DecodingError) Error() error {
	return this.err
}

// Returns the reason for this DecodingError.
func (this *DecodingError) Reason() string {
	return this.reason
}


text:
package org.apache.velocity.tools.generic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.velocity.tools.config.DefaultKey;

/**
 * SortTool allows a user to sort a collection (or array, iterator, etc)
 * on any arbitary set of properties exposed by the objects contained
 * within the collection.
 *
 *
The sort tool is specifically designed to use within a #foreach
 * but you may find other uses for it.

 *
 *
The sort tool can handle all of the collection types supported by
 * #foreach and the same constraints apply as well as the following.
 * Every object in the collection must support the set of properties
 * selected to sort on. Each property which is to be sorted on must
 * return one of the follow:
 *

 *
Primitive type: e.g. int, char, long etc

 *
Standard Object: e.g. String, Integer, Long etc

 *
Object which implements the Comparable interface.

 *

 *

 *
 *
During the sort operation all properties are compared by calling
 * compareTo() with the exception of Strings for which
 * compareToIgnoreCase() is called.

 *
 *
The sort is performed by calling Collections.sort() after
 * marshalling the collection to sort into an appropriate collection type.
 * The original collection will not be re-ordered; a new list containing
 * the sorted elements will always be returned.

 *
 *
The tool is used as follows:
 *

 * Single Property Sort
 * #foreach($obj in $sorter.sort($objects, "name"))
 *   $obj.name Ordinal= $obj.ordinal
 * #end
 * End
 *
 * Multiple Property Sort
 * #foreach($obj in $sorter.sort($objects, ["name", "ordinal"]))
 *   $obj.name, $obj.ordinal
 * #end
 * End
 *

 *
 * The sort method takes two parameters a collection and a property name
 * or an array of property names. The property names and corresponding
 * methods must conform to java bean standards since commons-beanutils
 * is used to extract the property values.

 *
 *
By default the sort tool sorts ascending, you can override this by
 * adding a sort type suffix to any property name.

 *
 *
The supported suffixes are:
 *

 * For ascending
 * :asc
 * For descending
 * :desc
 *
 * Example
 * #foreach($obj in $sorter.sort($objects, ["name:asc", "ordinal:desc"]))
 *   $obj.name, $obj.ordinal
 * #end
 *

 *
 *
This will sort first by Name in ascending order and then by Ordinal
 * in descending order, of course you could have left the :asc off of the
 * 'Name' property as ascending is always the default.

 *
 *

 * Example tools.xml config (if you want to use this with VelocityView):
 * <tools>
 *   <toolbox scope="application">
 *     <tool class="org.apache.velocity.tools.generic.SortTool"/>
 *   </toolbox>
 * </tools>
 *

 *
 * @author S. Brett Sutton
 * @author Nathan Bubna
 * @since VelocityTools 1.2
 * @version $Id: SortTool.java 564672 2007-08-10 16:50:04Z nbubna $
 */
@DefaultKey("sorter")
public class SortTool
{

    public Collection sort(Collection collection)
    {
        return sort(collection, (List)null);
    }

    public Collection sort(Object[] array)
    {
        return sort(array, (List)null);
    }

    public Collection sort(Map map)
    {
        return sort(map, (List)null);
    }

    /**
     * Sorts the collection on a single property.
     *
     * @param object the collection to be sorted.
     * @param property the property to sort on.
     */
    public Collection sort(Object object, String property)
    {
        List properties = new ArrayList(1);
        properties.add(property);

        if (object instanceof Collection)
        {
            return sort((Collection)object, properties);
        }
        else if (object instanceof Object[])
        {
            return sort((Object[])object, properties);
        }
        else if (object instanceof Map)
        {
            return sort((Map)object, properties);
        }
        // the object type is not supported
        return null;
    }

    public Collection sort(Collection collection, List properties)
    {
        List list = new ArrayList(collection.size());
        list.addAll(collection);
        return internalSort(list, properties);
    }

    public Collection sort(Map map, List properties)
    {
        return sort(map.values(), properties);
    }

    public Collection sort(Object[] array, List properties)
    {
        return internalSort(Arrays.asList(array), properties);
    }

    protected Collection internalSort(List list, List properties)
    {
        try
        {
            if (properties == null)
            {
                Collections.sort(list);
            } else {
                Collections.sort(list, new PropertiesComparator(properties));
            }
            return list;
        }
        catch (Exception e)
        {
            //TODO: log this
            return null;
        }
    }

    /**
     * Does all of the comparisons
     */
    public static class PropertiesComparator
        implements Comparator, java.io.Serializable
    {
        private static final int TYPE_ASCENDING = 1;
        private static final int TYPE_DESCENDING = -1;

        public static final String TYPE_ASCENDING_SHORT = "asc";
        public static final String TYPE_DESCENDING_SHORT = "desc";

        List properties;
        int[] sortTypes;

        public PropertiesComparator(List props)
        {
            // copy the list so we can safely drop :asc and :desc suffixes
            this.properties = new ArrayList(props.size());
            this.properties.addAll(props);

            // determine ascending/descending
            sortTypes = new int[properties.size()];

            for (int i = 0; i < properties.size(); i++)
            {
                if (properties.get(i) == null)
                {
                    throw new IllegalArgumentException("Property " + i
                            + "is null, sort properties may not be null.");
                }

                // determine if the property contains a sort type
                // e.g "Name:asc" means sort by property Name ascending
                String prop = properties.get(i).toString();
                int colonIndex = prop.indexOf(':');
                if (colonIndex != -1)
                {
                    String sortType = prop.substring(colonIndex + 1);
                    properties.set(i, prop.substring(0, colonIndex));

                    if (TYPE_ASCENDING_SHORT.equalsIgnoreCase(sortType))
                    {
                        sortTypes[i] = TYPE_ASCENDING;
                    }
                    else if (TYPE_DESCENDING_SHORT.equalsIgnoreCase(sortType))
                    {
                        sortTypes[i] = TYPE_DESCENDING;
                    }
                    else
                    {
                        //FIXME: log this
                        // invalide property sort type. use default instead.
                        sortTypes[i] = TYPE_ASCENDING;
                    }
                }
                else
                {
                    // default sort type is ascending.
                    sortTypes[i] = TYPE_ASCENDING;
                }
            }
        }

        public int compare(Object lhs, Object rhs)
        {
            for (int i = 0; i < properties.size(); i++)
            {
                int comparison = 0;
                String property = (String)properties.get(i);

                // properties must be comparable
                Comparable left = getComparable(lhs, property);
                Comparable right = getComparable(rhs, property);

                if (left == null && right != null)
                {
                    // find out how right feels about left being null
                    comparison = right.compareTo(null);
                    // and reverse that (if it works)
                    comparison *= -1;
                }
                else if (left instanceof String)
                {
                    //TODO: make it optional whether or not case is ignored
                    comparison = ((String)left).compareToIgnoreCase((String)right);
                }
                else if (left != null)
                {
                    comparison = left.compareTo(right);
                }

                // return the first difference we find
                if (comparison != 0)
                {
                    // multiplied by the sort direction, of course
                    return comparison * sortTypes[i];
                }
            }
            return 0;
        }
    }

    /**
     * Safely retrieves the comparable value for the specified property
     * from the specified object. Subclasses that wish to perform more
     * advanced, efficient, or just different property retrieval methods
     * should override this method to do so.
     */
    protected static Comparable getComparable(Object object, String property)
    {
        try
        {
            return (Comparable)PropertyUtils.getProperty(object, property);
        }
        catch (Exception e)
        {
            throw new IllegalArgumentException("Could not retrieve comparable value for '"
                                               + property + "' from " + object + ": " + e);
        }
    }

}


text:
import functools
import json

import botocore.exceptions
import jsonschema
import pkg_resources
import yaml

from quilt3.data_transfer import get_bytes_and_effective_pk

from .. import util
from ..backends import PackageRegistry

@functools.lru_cache(maxsize=None)
def _get_conf_validator():
    schema = json.loads(pkg_resources.resource_string(__name__, 'config-1.schema.json'))
    return jsonschema.Draft7Validator(schema).validate

SUPPORTED_META_SCHEMAS = {
    'http://json-schema.org/draft-07/schema#': jsonschema.Draft7Validator,
}

def _schema_load_object_hook(o):
    if '$ref' in o:
        raise util.QuiltException("Currently we don't support $ref in schema.")
    return o

_load_schema_json = json.JSONDecoder(object_hook=_schema_load_object_hook).decode

class WorkflowValidator:
    def __init__(self, config: dict, physical_key: util.PhysicalKey):
        """
        Args:
            config: validated workflow config or `None` if there is no config
            physical_key: from where config was loaded
        """
        self.config = config
        self.physical_key = physical_key

    @classmethod
    def load(cls, pk: util.PhysicalKey):
        data = None
        try:
            data, pk = get_bytes_and_effective_pk(pk)
        except FileNotFoundError:
            pass
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] != 'NoSuchKey':
                raise util.QuiltException(f"Couldn't load workflows config. {e}.")
        if data is None:
            return

        try:
            # TODO: raise if objects contain duplicate properties
            config = yaml.safe_load(data.decode())
        except yaml.YAMLError as e:
            raise util.QuiltException("Couldn't parse workflows config as YAML.") from e
        conf_validator = _get_conf_validator()
        try:
            conf_validator(config)
        except jsonschema.ValidationError as e:
            raise util.QuiltException(f'Workflows config failed validation: {e.message}.') from e

        return cls(config, pk)

    def validate(self, workflow, meta, message):
        if workflow is ...:
            workflow = self.config.get('default_workflow')

        result = {
            'id': workflow,
            'config': str(self.physical_key),
        }
        if workflow is None:
            if self.config.get('is_workflow_required', True):
                raise util.QuiltException('Workflow required, but none specified.')
            return result

        workflows_data = self.config['workflows']
        if workflow not in workflows_data:
            raise util.QuiltException(f'There is no {workflow!r} workflow in config.')
        workflow_data = workflows_data[workflow]
        metadata_schema_id = workflow_data.get('metadata_schema')
        if metadata_schema_id:
            schemas = self.config.get('schemas', {})
            if metadata_schema_id not in schemas:
                raise util.QuiltException(f'There is no {metadata_schema_id!r} in schemas.')
            schema_url = schemas[metadata_schema_id]['url']
            try:
                schema_pk = util.PhysicalKey.from_url(schema_url)
            except util.URLParseError as e:
                raise util.QuiltException(f"Couldn't parse URL {schema_url!r}. {e}.")
            if schema_pk.is_local() and not self.physical_key.is_local():
                raise util.QuiltException(f"Local schema {str(schema_pk)!r} can't be used on the remote registry.")

            handled_exception = (OSError if schema_pk.is_local() else botocore.exceptions.ClientError)
            try:
                schema_data, schema_pk_to_store = get_bytes_and_effective_pk(schema_pk)
            except handled_exception as e:
                raise util.QuiltException(f"Couldn't load schema at {schema_pk}. {e}.")
            try:
                schema = _load_schema_json(schema_data.decode())
            except json.JSONDecodeError as e:
                raise util.QuiltException(f"Couldn't parse {schema_pk} as JSON. {e}.")

            validator_cls = jsonschema.Draft7Validator
            if isinstance(schema, dict) and '$schema' in schema:
                meta_schema = schema['$schema']
                if not isinstance(meta_schema, str):
                    raise util.QuiltException('$schema must be a string.')
                validator_cls = SUPPORTED_META_SCHEMAS.get(meta_schema)
                if validator_cls is None:
                    raise util.QuiltException(f"Unsupported meta-schema: {meta_schema}.")
            try:
                jsonschema.validate(meta, schema, cls=validator_cls)
            except jsonschema.ValidationError as e:
                raise util.QuiltException(f"Metadata failed validation: {e.message}.")
            result['schemas'] = {metadata_schema_id: str(schema_pk_to_store)}
        if workflow_data.get('is_message_required', False) and not message:
            raise util.QuiltException('Commit message is required by workflow, but none was provided.')

        return result

def validate(*, registry: PackageRegistry, workflow, meta, message):
    # workflow is ... => no workflow provided by user;
    # workflow is None => don't use any workflow.
    if not (workflow in (None, ...) or isinstance(workflow, str)):
        raise TypeError

    workflow_validator = registry.get_workflow_validator()
    if workflow_validator is None:
        if workflow is ...:
            return
        raise util.QuiltException(f'{workflow!r} workflow is specified, but no workflows config exist.')

    return workflow_validator.validate(workflow, meta, message)


text:
//
// This file is part of nuBScript Project
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//

/* -------------------------------------------------------------------------- */

#include "nu_expr_parser.h"
#include "nu_basic_defs.h"
#include "nu_expr_bin.h"
#include "nu_expr_empty.h"
#include "nu_expr_function.h"
#include "nu_expr_literal.h"
#include "nu_expr_subscrop.h"
#include "nu_expr_syntax_tree.h"
#include "nu_expr_unary_op.h"
#include "nu_expr_var.h"
#include "nu_variant.h"

/* -------------------------------------------------------------------------- */

namespace nu {

/* -------------------------------------------------------------------------- */

expr_any_t::handle_t expr_parser_t::compile(expr_tknzr_t& tknzr)
{
    token_list_t tl;

    // Split expression in tokens
    tknzr.get_tknlst(tl);

    // Create a syntax tree
    expr_syntax_tree_t est;

    // Finally parse the expression tree in order to generate
    // an executable object
    convert_subscription_brackets(tl);
    tl = est(tl);
    return parse(tl);
}

/* -------------------------------------------------------------------------- */

expr_any_t::handle_t expr_parser_t::compile(token_list_t tl, size_t expr_pos)
{
    expr_syntax_tree_t est;
    convert_subscription_brackets(tl);
    tl = est(tl);
    return parse(tl);
}

/* -------------------------------------------------------------------------- */

variant_t::type_t expr_parser_t::get_type(const token_t& t)
{
    switch (t.type()) {
    case tkncl_t::INTEGRAL:
        return variant_t::type_t::LONG64;

    case tkncl_t::REAL:
        return variant_t::type_t::DOUBLE;

    case tkncl_t::STRING_LITERAL:
        return variant_t::type_t::STRING;

    default:
        break;
    }

    if (t.type() == tkncl_t::IDENTIFIER
        && (t.identifier() == "true" || t.identifier() == "false")) {
        return variant_t::type_t::BOOLEAN;
    }

    return variant_t::type_t::UNDEFINED;
}

/* -------------------------------------------------------------------------- */

expr_any_t::handle_t expr_parser_t::parse_operand(token_list_t& tl)
{
    // An empty list generates an empty expression
    if (tl.empty())
        return expr_any_t::handle_t(std::make_shared<expr_empty_t>());

    reduce_brackets(tl);

    token_t t(*tl.begin());

    switch (t.type()) {
    case tkncl_t::OPERATOR:

        // ++<identifier> / --<identifier>
        if (tl.size() > 1 && (tl[0].identifier() == NUBSCRIPT_OP_INC
                                 || tl[0].identifier() == NUBSCRIPT_OP_DEC)
            && tl[1].type() == tkncl_t::IDENTIFIER) {
            auto ret_handle
                = std::make_shared<expr_unary_op_t>(tl[0].identifier(),
                    std::make_shared<expr_var_t>(tl[1].identifier()));

            tl.data().erase(tl.begin(), tl.begin() + 2);

            return tl.empty() ? ret_handle : parse(tl, ret_handle);
        }

        break;

    case tkncl_t::IDENTIFIER:

        // <identifier>+"(" => function
        if (tl.size() > 1 && tl[1].type() == tkncl_t::SUBEXP_BEGIN) {
            std::string function_name = tl.begin()->identifier();
            func_args_t function_args;

            size_t size = 0;

            if (tl.size() > 2 && tl[2].type() == tkncl_t::SUBEXP_END) {
                size = 3;
            } else {
                // Splits the parameters list in listes of tokens
                auto params = tl.get_parameters(
                    { NUBSCRIPT_BEGIN_SUBEXPR_OP, tkncl_t::SUBEXP_BEGIN },
                    { NUBSCRIPT_END_SUBEXPR_OP, tkncl_t::SUBEXP_END },
                    { NUBSCRIPT_PARAM_SEP, tkncl_t::OPERATOR });

                // size here starts from 2.
                // One is identifier and one is "("
                size = 2;

                // Parse each parameter
                for (auto par : params) {
                    auto param_tl = par;
                    size += par.size() + 1;

                    reduce_brackets(param_tl);

                    expr_any_t::handle_t arg(parse(param_tl));
                    function_args.push_back(arg);
                }
            }

            // Remove from original list token parsed
            tl.data().erase(tl.begin(), tl.begin() + size);

            expr_any_t::handle_t ret_handle = nullptr;

            if (function_name.size() > 1
                && *function_name.rbegin() == NUBSCRIPT_BEGIN_SUBSCR) {
                ret_handle = std::make_shared<expr_subscrop_t>(
                    function_name.substr(0, function_name.size() - 1),
                    function_args);

            } else {
                // Create an executable object for the parsed function
                ret_handle = std::make_shared<expr_function_t>(
                    function_name, function_args);
            }

            // Check if we have other to parse
            // YES: call recursively parse()
            // NO : return the handle to executable object
            return tl.empty() ? ret_handle : parse(tl, ret_handle);
        } else {
            std::string id = t.identifier();
            expr_any_t::handle_t ret_handle;

            if (id == "true") {
                tl.data().erase(tl.begin());

                ret_handle = expr_any_t::handle_t(
                    std::make_shared<expr_literal_t>(variant_t(true)));
            } else if (id == "false") {
                tl.data().erase(tl.begin());

                ret_handle = expr_any_t::handle_t(
                    std::make_shared<expr_literal_t>(variant_t(false)));
            }
            // 0xnnnnnn  (hexadecimal value)
            else if (id.size() > 2 && id.c_str()[0] == '&'
                && toupper(id.c_str()[1]) == 'H') {
                tl.data().erase(tl.begin());

                std::string hex = id.substr(2, id.size() - 2);
                int n = 0;
                sscanf(hex.c_str(), "%x", &n);

                ret_handle = expr_any_t::handle_t(
                    std::make_shared<expr_literal_t>(variant_t(n)));
            } else {
                std::string id = t.identifier();

                if (id.size() > 1 && *id.rbegin() == NUBSCRIPT_BEGIN_SUBSCR)
                    id = id.substr(0, id.size() - 1);

                if (!variable_t::is_valid_name(id, false)) {
                    syntax_error(t.expression(), t.position(),
                        "\"" + id + "\" is an invalid identifier");
                }

                tl.data().erase(tl.begin());

                ret_handle
                    = expr_any_t::handle_t(std::make_shared<expr_var_t>(id));
            }

            return tl.empty() ? ret_handle : parse(tl, ret_handle);
        }

        break;

    // numerical token
    case tkncl_t::INTEGRAL:
    case tkncl_t::REAL:
    case tkncl_t::STRING_LITERAL:
        do {
            // Remove token from tl
            tl.data().erase(tl.begin());

            // Generates a literal using a "variant" instance
            // for the executable object
            expr_any_t::handle_t ret_handle(std::make_shared<expr_literal_t>(
                variant_t(t.identifier(), get_type(t))));

            // Check if we have other to parse
            // YES: call recursively parse()
            // NO : return the handle to executable object
            return tl.empty() ? ret_handle : parse(tl, ret_handle);
        } while (0);

    case tkncl_t::SUBEXP_BEGIN:

        // this is a sub expression
        if (tl.size() >= 3) {
            token_list_t rtl = tl.sublist(
                tkncl_t::SUBEXP_BEGIN, tkncl_t::SUBEXP_END, 0, false);

            tl.data().erase(tl.begin(), tl.begin() + rtl.size());

            // simplify "(((....)))"
            reduce_brackets(rtl);

            // Parse the sub-expression
            auto h(parse(rtl));

            // Check if we have other to parse
            // YES: call recursively parse()
            // NO : return the handle to executable object
            return tl.empty() ? h : parse(tl, h);
        } else {
            return expr_any_t::handle_t(std::make_shared<expr_empty_t>());
        }

        break;

    default:
        break;
    }

    return expr_any_t::handle_t(std::make_shared<expr_empty_t>());
}

/* -------------------------------------------------------------------------- */

bool expr_parser_t::parse_operator(token_list_t& tl, std::string& value)
{
    if (tl.empty())
        return false;

    token_t t(*tl.begin());

    if (t.type() != tkncl_t::OPERATOR)
        return false;

    value = t.identifier();
    tl.data().erase(tl.begin());

    return true;
}

/* -------------------------------------------------------------------------- */

expr_any_t::handle_t expr_parser_t::parse(
    token_list_t& tl, expr_any_t::handle_t first_param)
{
    fix_real_numbers(tl);

    if (!first_param)
        first_param = parse_operand(tl);

    if (!first_param)
        return nullptr;

    if (tl.empty())
        return first_param;

    reduce_brackets(tl);

    std::string op;
    expr_any_t::handle_t second_param;

    auto err = !parse_operator(tl, op);
    syntax_error_if(err, NUBSCRIPT_ERROR_STR__SYNTAXERROR);

    second_param = parse_operand(tl);
    syntax_error_if(!second_param, NUBSCRIPT_ERROR_STR__SYNTAXERROR);

    if (op == ".") {
        return expr_any_t::handle_t(
            std::make_shared<expr_struct_access_t>(first_param, second_param));
    }

    // resolve built-in operator implementation
    auto operator_implementation = global_operator_tbl_t::get_instance()[op];

    // create the expression object using built-in
    // operator_implementation semantic
    return expr_any_t::handle_t(std::make_shared<expr_bin_t>(
        operator_implementation, first_param, second_param));
}

/* -------------------------------------------------------------------------- */

void expr_parser_t::fix_real_numbers(token_list_t& rtl)
{
    auto tl_size = rtl.size();

    if (tl_size < 3)
        return;

    token_list_t tl(std::move(rtl));
    rtl.clear();

    for (decltype(tl_size) i = 0; i < tl_size; ++i) {
        auto tk = tl[i];

        if (tk.type() == tkncl_t::REAL) {
            const std::string& id = tk.identifier();

            if (!id.empty()
                && ::toupper(id.c_str()[id.size() - 1])
                    == NUBSCRIPT_EXPONENT_SYMB
                && i < (tl_size - 1)) {
                const auto& tkop = tl[i + 1];

                if (tkop.type() == tkncl_t::OPERATOR
                    && (tkop.identifier() == "+" || tkop.identifier() == "-")
                    && i < (tl_size - 2)) {
                    const auto& tkn = tl[i + 2];

                    if (tkn.type() == tkncl_t::INTEGRAL) {
                        std::string new_id = tk.identifier() + tkop.identifier()
                            + tkn.identifier();

                        tk.set_identifier(new_id, nu::token_t::case_t::LOWER);

                        i += 2;
                    }
                }
            }
        }

        rtl += tk;
    }
}

/* -------------------------------------------------------------------------- */

void expr_parser_t::reduce_brackets(token_list_t& rtl)
{
    // simplify "(((....)))"
    while (rtl.size() > 2 && rtl.begin()->type() == tkncl_t::SUBEXP_BEGIN
        && (rtl.end() - 1)->type() == tkncl_t::SUBEXP_END) {
        auto substr
            = rtl.sublist(tkncl_t::SUBEXP_BEGIN, tkncl_t::SUBEXP_END, 0, false);

        if (substr.size() == (rtl.size())) {
            --rtl; // remove head token
            rtl--; // remove tail token
        } else {
            break;
        }
    }
}

/* -------------------------------------------------------------------------- */

void expr_parser_t::convert_subscription_brackets(token_list_t& rtl)
{
    token_t* token_prev = nullptr;

    for (size_t i = 0; i < rtl.size(); ++i) {
        auto& token = rtl[i];

        if (i > 0)
            token_prev = &rtl[i - 1];

        if (token.type() == tkncl_t::SUBSCR_BEGIN) {
            if (token_prev) {
                auto id = token_prev->identifier();

                if (!id.empty() && *id.rbegin() != NUBSCRIPT_BEGIN_SUBSCR) {
                    id.push_back(NUBSCRIPT_BEGIN_SUBSCR);
                    token_prev->set_identifier(id, nu::token_t::case_t::LOWER);
                }
            }

            token.set_type(tkncl_t::SUBEXP_BEGIN);

            if (token.identifier() == NUBSCRIPT_BEGIN_SUBSCR_OP)
                token.set_identifier(
                    NUBSCRIPT_BEGIN_SUBEXPR_OP, nu::token_t::case_t::LOWER);
        }

        else if (token.type() == tkncl_t::SUBSCR_END) {
            token.set_type(tkncl_t::SUBEXP_END);

            if (token.identifier() == NUBSCRIPT_END_SUBSCR_OP)
                token.set_identifier(
                    NUBSCRIPT_END_SUBEXPR_OP, nu::token_t::case_t::LOWER);
        }
    }
}

/* -------------------------------------------------------------------------- */

} // namespace

/* -------------------------------------------------------------------------- */


text:
<?php

/**
 * Need eptBase
 */
include_once(realpath(dirname(__FILE__)).'/eptBaseExtensive.php');
include_once(realpath(dirname(__FILE__)).'/eptPerson.php');
include_once(realpath(dirname(__FILE__)).'/Person/eptEmployee.php');
include_once(realpath(dirname(__FILE__)).'/Person/eptCustomer.php');
include_once(realpath(dirname(__FILE__)).'/eptStore.php');
include_once(realpath(dirname(__FILE__)).'/eptItem.php');

/**
 * Class of contact infomation
 *
 * This is a test class for ezpdo
 *
 * @author Oak Nauhygon <ezpdo4php@gmail.com>
 * @version $Revision$ $Date: 2006-01-25 06:52:21 -0500 (Wed, 25 Jan 2006) $
 * @package ezpdo_t
 * @subpackage ezpdo_t.bookstore
 */
class eptSale extends eptBaseExtensive {

    const BOOK = 0;
    const MULTIMEDIA = 1;
    const OTHER = 2;

    /**
     * Type of the sale
     * @var int
     * @orm integer(2)
     */
    public $type;

    /**
     * Time of the sale
     * @var datetime
     * @orm datetime
     */
    public $datetime;

    /**
     * Amount of the sale
     * @var string
     * @orm decimal(5,2)
     */
    public $amount;

    /**
     * Store of the sale
     * @var eptStore
     * @orm has one eptStore inverse(sales)
     */
    public $store;

    /**
     * Employee of the sale
     * @var eptEmployee
     * @orm has one eptEmployee inverse(sales)
     */
    public $employee;

    /**
     * Customer of the sale
     * @var eptCustomer
     * @orm has one eptCustomer inverse(sales)
     */
    public $customer;

    /**
     * Item of the sale
     * @var eptItem
     * @orm has one eptItem inverse(sale)
     */
    public $item;

    public function __construct($type = '') {
        parent::__construct();
        if ($type == '') {
            $this->type = eptSale::OTHER;
        } else {
            $this->type = $type;
        }
    }

}

?>


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jitsi.impl.neomedia.device;

/**
 * Manages the list of active (currently plugged-in) playback devices and
 * manages user preferences between all known devices (previously and actually
 * plugged-in).
 *
 * @author Vincent Lucas
 */
public class PlaybackDevices
    extends Devices
{
    /**
     * The property of the playback devices.
     */
    public static final String PROP_DEVICE = "playbackDevice";

    /**
     * Initializes the playback device list management.
     *
     * @param audioSystem The audio system managing this playback device list.
     */
    public PlaybackDevices(AudioSystem audioSystem)
    {
        super(audioSystem);
    }

    /**
     * Returns the property of the capture devices.
     *
     * @return The property of the capture devices.
     */
    protected String getPropDevice()
    {
        return PROP_DEVICE;
    }
}


text:
<?php namespace Neomerx\Samples\JsonApi\Application;

use \Closure;
use \Neomerx\JsonApi\Document\Link;
use \Neomerx\JsonApi\Encoder\Encoder;
use \Neomerx\Samples\JsonApi\Models\Post;
use \Neomerx\Samples\JsonApi\Models\Site;
use \Neomerx\Samples\JsonApi\Models\Author;
use \Neomerx\Samples\JsonApi\Models\Comment;
use \Neomerx\JsonApi\Encoder\EncoderOptions;
use \Neomerx\Samples\JsonApi\Schemas\PostSchema;
use \Neomerx\Samples\JsonApi\Schemas\SiteSchema;
use \Neomerx\Samples\JsonApi\Schemas\AuthorSchema;
use \Neomerx\Samples\JsonApi\Schemas\CommentSchema;
use \Neomerx\JsonApi\Encoder\Parameters\EncodingParameters;

/**
 * @package Neomerx\Samples\JsonApi
 */
class EncodeSamples
{
    /**
     * Get basic usage.
     *
     * @return string
     */
    public function getBasicExample()
    {
        $author = Author::instance('123', 'John', 'Dow');

        $encoder = Encoder::instance([
            Author::class => AuthorSchema::class,
        ], new EncoderOptions(JSON_PRETTY_PRINT, 'http://example.com/api/v1'));

        $result = $encoder->encodeData($author);

        return $result;
    }

    /**
     * Get how objects are put to 'included'.
     *
     * @return string
     */
    public function getIncludedObjectsExample()
    {
        $author   = Author::instance('123', 'John', 'Dow');
        $comments = [
            Comment::instance('456', 'Included objects work as easy as basic ones', $author),
            Comment::instance('789', 'Let\'s try!', $author),
        ];
        $post     = Post::instance('321', 'Included objects', 'Yes, it is supported', $author, $comments);
        $site     = Site::instance('1', 'JSON API Samples', [$post]);

        $encoder = Encoder::instance([
            Author::class  => AuthorSchema::class,
            Comment::class => CommentSchema::class,
            Post::class    => PostSchema::class,
            Site::class    => SiteSchema::class
        ], new EncoderOptions(JSON_PRETTY_PRINT, 'http://example.com'));

        $result = $encoder->encodeData($site);

        return $result;
    }

    /**
     * Get sparse and field set filters.
     *
     * @return string
     */
    public function getSparseAndFieldSetsExample()
    {
        $author   = Author::instance('123', 'John', 'Dow');
        $comments = [
            Comment::instance('456', 'Included objects work as easy as basic ones', $author),
            Comment::instance('789', 'Let\'s try!', $author),
        ];
        $post = Post::instance('321', 'Included objects', 'Yes, it is supported', $author, $comments);
        $site = Site::instance('1', 'JSON API Samples', [$post]);

        $options = new EncodingParameters([
            // Paths to be included. Note 'posts.comments' will not be shown.
            'posts.author'
        ], [
            // Attributes and relationships that should be shown
            'sites'  => ['name', 'posts'],
            'posts'  => ['author'],
            'people' => ['first_name'],
        ]);

        SiteSchema::$isShowCustomLinks = false;
        $encoder = Encoder::instance([
            Author::class  => AuthorSchema::class,
            Comment::class => CommentSchema::class,
            Post::class    => PostSchema::class,
            Site::class    => SiteSchema::class
        ], new EncoderOptions(JSON_PRETTY_PRINT));

        $result = $encoder->encodeData($site, $options);

        return $result;
    }

    /**
     * Get sparse and field set filters.
     *
     * @return string
     */
    public function getTopLevelMetaAndLinksExample()
    {
        $author = Author::instance('123', 'John', 'Dow');
        $meta   = [
            "copyright" => "Copyright 2015 Example Corp.",
            "authors"   => [
                "Yehuda Katz",
                "Steve Klabnik",
                "Dan Gebhardt"
            ]
        ];
        $links  = [
            Link::FIRST => new Link('http://example.com/people?first', null, true),
            Link::LAST  => new Link('http://example.com/people?last', null, true),
            Link::PREV  => new Link('http://example.com/people?prev', null, true),
            Link::NEXT  => new Link('http://example.com/people?next', null, true),
        ];

        $encoder = Encoder::instance([
            Author::class  => AuthorSchema::class,
            Comment::class => CommentSchema::class,
            Post::class    => PostSchema::class,
            Site::class    => SiteSchema::class
        ], new EncoderOptions(JSON_PRETTY_PRINT, 'http://example.com'));

        $result = $encoder->withLinks($links)->withMeta($meta)->encodeData($author);

        return $result;
    }

    /**
     * Get how schema could change dynamically.
     *
     * @return array
     */
    public function getDynamicSchemaExample()
    {
        $site = Site::instance('1', 'JSON API Samples', []);

        $encoder = Encoder::instance([
            Site::class => SiteSchema::class,
        ], new EncoderOptions(JSON_PRETTY_PRINT));

        SiteSchema::$isShowCustomLinks = false;
        $noLinksResult = $encoder->encodeData($site);

        SiteSchema::$isShowCustomLinks = true;
        $withLinksResult = $encoder->encodeData($site);

        return [
            $noLinksResult,
            $withLinksResult,
        ];
    }

    /**
     * Run performance test for many times for small nested resources.
     *
     * @param int $iterations
     *
     * @return mixed
     */
    public function runPerformanceTestForSmallNestedResources($iterations)
    {
        $closure = function () use ($iterations) {
            $options = new EncodingParameters(
                ['posts.author'],
                ['sites' => ['name'], 'people' => ['first_name']]
            );
            $encoder = Encoder::instance([
                Author::class  => AuthorSchema::class,
                Comment::class => CommentSchema::class,
                Post::class    => PostSchema::class,
                Site::class    => SiteSchema::class
            ]);

            for ($index = 0; $index < $iterations; ++$index) {
                $rand = rand();

                $author   = Author::instance('123', 'John' . $rand, 'Dow' . $rand);
                $comments = [
                    Comment::instance('456', 'Included objects work as easy as basic ones' . $rand, $author),
                    Comment::instance('789', 'Let\'s try!' . $rand, $author),
                ];
                $post = Post::instance('321', 'Included objects' . $rand, 'Yes, it is supported', $author, $comments);
                $site = Site::instance('1', 'JSON API Samples' . $rand, [$post]);

                $encoder
                    ->withLinks([Link::SELF => new Link('http://example.com/sites/1?' . $rand, null, true)])
                    ->withMeta(['some' => ['meta' => 'information' . $rand]])
                    ->encodeData($site, $options);
            }
        };

        $timeSpent = null;
        $this->getTime($closure, $timeSpent);

        return $timeSpent;
    }

    /**
     * Run performance test one time for big collection of resources.
     *
     * @param int $numberOfItems
     *
     * @return mixed
     */
    public function runPerformanceTestForBigCollection($numberOfItems)
    {
        $closure = function() use ($numberOfItems) {
            $sites = [];
            for ($index = 0; $index < $numberOfItems; ++$index) {
                $rand = rand();

                $author   = Author::instance('123', 'John' . $rand, 'Dow' . $rand);
                $comments = [
                    Comment::instance('456', 'Included objects work as easy as basic ones' . $rand, $author),
                    Comment::instance('789', 'Let\'s try!' . $rand, $author),
                ];
                $post = Post::instance('321', 'Included objects' . $rand, 'Yes, it is supported', $author, $comments);
                $site = Site::instance('1', 'JSON API Samples' . $rand, [$post]);

                $sites[] = $site;
            }

            $options = new EncodingParameters(
                ['posts.author', 'posts.comments'],
                ['sites' => ['name'], 'people' => ['first_name']]
            );
            $encoder = Encoder::instance([
                Author::class  => AuthorSchema::class,
                Comment::class => CommentSchema::class,
                Post::class    => PostSchema::class,
                Site::class    => SiteSchema::class
            ]);

            $encoder->encodeData($sites, $options);
        };

        $timeSpent = null;
        $this->getTime($closure, $timeSpent);

        return $timeSpent;
    }

    /**
     * @param Closure $closure
     * @param float   &$time
     *
     * @return mixed
     */
    private function getTime(Closure $closure, &$time)
    {
        $time_start = microtime(true);
        try {
            return $closure();
        } finally {
            $time_end = microtime(true);
            $time     = $time_end - $time_start;
        }
    }
}