text:
"""
Created on Fri Apr 21 20:54:53 2017

@author: pnbrown
"""

import steem as st
from datetime import datetime,timedelta
import time
import json
import logging
import sys

import util.db as db
import util.validators as val
import util.constants as const
import util.confirmation as conf

DB = db.Mist_DB()
logging.basicConfig(filename='ops.log',
                    level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s')
logging.getLogger("urllib3.util.retry").setLevel(logging.ERROR)
logging.getLogger("urllib3.connectionpool").setLevel(logging.ERROR)

try :
    with open('config.json') as cfgfile :
        cfg = json.load(cfgfile)
except FileNotFoundError :
    cfg = {'confirmer-account':'',
           'confirmer_key':'',
           'nodes':[''],
           'confirm_message':'',
           'confirmation_active':True,
           'vote_on_valid_confs':True}
    with open('config.json','w') as cfgfile :
        json.dump(cfg,cfgfile)
    raise FileNotFoundError('Please populate config.json file with relevant values')

try :
    confirmer_account = cfg['confirmer-account']
    confirmer_key = cfg['confirmer_key']
    nodes = cfg['nodes']
    confirm_message = cfg['confirm_message']
    confirmation_active = bool(cfg['confirmation_active'])
    vote_on_valid_confs = bool(cfg['vote_on_valid_confs'])
except KeyError as er:
    raise KeyError('You may have an outdated version of the config.json file. Back yours up, delete it, and try again!')

if nodes==[''] :
    if confirmer_key == '' :
        s = st.Steem()
    else :
        s = st.Steem(keys = [confirmer_key])
else :
    if confirmer_key == '' :
        s = st.Steem(nodes=nodes)
    else :
        s = st.Steem(nodes=nodes,keys=[confirmer_key])
steem = s.steemd
#steem = stm.steemd
bc = st.blockchain.Blockchain(s)

confirmation_wait_time = 21 # seconds
confirmation_wait_timedelta = timedelta(seconds=confirmation_wait_time)
last_confirmation_time = datetime.utcnow() - confirmation_wait_timedelta
block_interval = 3 # seconds

if len(sys.argv) > 1 :
    startup_behavior = sys.argv[1]
else :
    startup_behavior = 'normal'

if startup_behavior == 'replay-from-genesis' : # load pregenesis, overwrite db
    DB.from_json(fname='db_pregenesis.json',overwrite_local=True)
    DB.save()
elif startup_behavior == 'replay-from-0' :
    DB._reset()
elif startup_behavior == 'normal' :
    pass

last_parsed_block = DB.last_parsed_block()

while True : # can't proceed without this, so loop until we get it
    try :
        last_irr_block = s.last_irreversible_block_num
    except TypeError :
        pass
    else :
        break
next_irr_check_time = datetime.utcnow() + timedelta(seconds=block_interval)

activate_voting = vote_on_valid_confs and (confirmer_key!='')
v = conf.Voter(confirmer_account,s,active=activate_voting)

run = True
if run :
    try :
        while True :
            if last_parsed_block < last_irr_block :
#                print(str(last_parsed_block+1))
                with const.DelayedKeyboardInterrupt() : # don't let a SIGINT interrupt in the middle of a block
                    block = s.get_block(last_parsed_block + 1)
#                    print(this_block)
                    try :
                        trxs = zip(block['transactions'],block['transaction_ids'])
                    except TypeError as er :
                        logging.exception("block number: " + str(last_parsed_block + 1))
                        time.sleep(1)
                        continue # don't do anything in this loop; skip back and get a good block
                    this_block = last_parsed_block + 1
                    for trx,trxid in trxs :
                        for op in trx['operations'] :
                            if DB.active() :
                                mist_op = val.parseOP(op,trxid,DB) # check if it's properly formatted
                                if mist_op is not None :
                                    op_is_valid = DB.add_op(mist_op) # adds if it's valid
                                    print(str(mist_op) + " valid: " + str(op_is_valid))
                                    if op_is_valid :
                                        logging.info(str(mist_op))
                                    if op_is_valid and mist_op['type'] != 'confirmation' :
                                        DB.enqueue_for_confirmation(mist_op,op)
                                    if op_is_valid and mist_op['type'] == 'confirmation' :
                                        # then op is a confirm comment and we should consider voting it
                                        v.mark_for_voting(op)
                                if DB.genesis_active() :
                                    if DB.past_genesis_interval(this_block) :
                                        DB.deactivate_genesis()
                                    else :
                                        # watch for reblogs of genesis post
                                        if op[0] == 'custom_json' :
                                            payload = json.loads( op[1]['json'])
                                            if payload[0] == 'reblog' :
                                                if payload[1]['author'] == const.GENESIS_ACCOUNT :
                                                    if payload[1]['permlink'] == 'genesis-'+const.TOKEN_NAME :
                                                        if DB.is_eligible(payload[1]['account']) :
                                                            DB.credit_genesis(payload[1]['account'])
                                try :
                                    v.vote() # votes for others' confirms if voting is active
                                except TypeError as er :
                                    logging.exception("block number: " + str(last_parsed_block + 1))
                                    # this handles the random steem library NoneType problems
                            else : # if not active, we're pre-genesis
                                if op[0] == 'comment' :
                                    if not DB.is_eligible(op[1]['author']) : # eligibility
                                        DB.increment_comment_count(op[1]['author'])
                                    if op[1]['author'] == const.GENESIS_ACCOUNT: # watch for genesis activation
                                        if op[1]['title'] == 'genesis-'+const.TOKEN_NAME :
                                            DB.activate_genesis(this_block)
                                            DB.activate()
                                            DB.credit_genesis(const.GENESIS_ACCOUNT)
                    last_parsed_block += 1
                    DB.update_last_block(last_parsed_block)
                    if last_parsed_block%const.SAVE_INTERVAL == 0 :
                        DB.save()
                        v.save()
                    if last_parsed_block%100000 == 0 :
                        print(last_parsed_block)
                if confirmation_active and DB.active() :
                    if (datetime.utcnow() - last_confirmation_time) > confirmation_wait_timedelta :
                        confirm = DB.get_next_confirmation()
                        if confirm is not None :
#                            print('want to confirm this: ' + str(confirm[1]))
                            conf.confirm_op(confirm[0],confirm[1],s,confirmer_account,confirm_message)
                            last_confirmation_time = datetime.utcnow()
            elif datetime.utcnow() > next_irr_check_time :
                try :
                    last_irr_block = s.last_irreversible_block_num
                except TypeError :
                    print('problem getting block number; will try again')
                next_irr_check_time = datetime.utcnow() + timedelta(seconds=block_interval)
            else :
                sleeptime = 1+(next_irr_check_time-datetime.utcnow()).seconds
                time.sleep(sleeptime)
    except KeyboardInterrupt:
        with const.DelayedKeyboardInterrupt() :
            DB.save()
            v.save()
        print("And Done.")


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'coveralls'
Coveralls.wear!('rails')

require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'sidekiq/testing'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.expand_path("../support/**/*.rb", __FILE__)].each {|f| require f}

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.include ActionView::Helpers::TextHelper

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = false

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  #config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"

  config.before(:suite) do
    ActiveRecord::Base.connection.execute "SET client_min_messages TO warning;"
    DatabaseCleaner.clean_with :truncation
    I18n.locale = :pt
    I18n.default_locale = :pt
  end

  config.before(:each) do
    if example.metadata[:type] == :feature
      DatabaseCleaner.strategy = :truncation
    else
      DatabaseCleaner.strategy = :transaction
    end
    DatabaseCleaner.start
    ActionMailer::Base.deliveries.clear
    RoutingFilter.active = false # Because this issue: https://github.com/svenfuchs/routing-filter/issues/36
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  # Stubs and configuration
  config.before(:each) do
    CatarseMailchimp::API.stub(:subscribe).and_return(true)
    CatarseMailchimp::API.stub(:unsubscribe).and_return(true)
    PaperTrail.controller_info = {}
    PaperTrail.whodunnit = nil
    Project.any_instance.stub(:store_image_url).and_return('http://www.store_image_url.com')
    ProjectObserver.any_instance.stub(:after_create)
    UserObserver.any_instance.stub(:after_create)
    Project.any_instance.stub(:download_video_thumbnail)
    CatarseMailchimp::API.stub(:subscribe)
    CatarseMailchimp::API.stub(:unsubscribe)
    Notification.stub(:create_notification)
    Notification.stub(:create_notification_once)
    Calendar.any_instance.stub(:fetch_events_from)
    Blog.stub(:fetch_last_posts).and_return([])
    [Projects::BackersController, Users::BackersController, UsersController, UnsubscribesController, ProjectsController, ExploreController].each do |c|
      c.any_instance.stub(:render_facebook_sdk)
      c.any_instance.stub(:render_facebook_like)
      c.any_instance.stub(:render_twitter)
      c.any_instance.stub(:display_uservoice_sso)
    end
    Configuration[:base_domain] = 'localhost'
    ::Configuration['email_contact'] = 'foo@bar.com'
  end
end

redpajama_set_name: RedPajamaGithub


text:
class PagesController < ApplicationController
  include ActionView::Helpers::TagHelper

  # We use this constraint to make the route less "greedy" by restricting the
  # wildcard to valid page slugs.
  module Constraint
    def self.matches?(request)
      catalog = Catalog.not_deactivated.where(:slug => request[:catalog_slug]).first!
      slug = request[:slug]
      catalog.pages.exists?(:slug => slug)
    end
  end

  include ControlsCatalog

  def show
    slug = request[:slug]
    @page = catalog.pages.where(:slug => slug).first!
    render :show
  end

  def items
    slug = request[:slug]
    page = catalog.pages.where(:slug => slug).first!
    container = page.containers.find(request[:container_id])
    catalog = page.catalog
    item_type = catalog.item_types.where(:id => container.item_type).first!
    sort_field = container.sort_field_id.present? ? Field.find(container.sort_field_id) : item_type.items.first.primary_field
    @list = ::ItemList::Filter.new(
      :item_type => item_type,
      :page => params[:page],
      sort_type: container.sort,
      sort_field: sort_field,
      sort: params[:sort] || Container::Sort.direction(container.sort)
    )

    formatted_sorted_items = @list.items.map { |item| helpers.formatted_item_for_line(item, list: @list, sort_field: sort_field) }
    render json: helpers.group_items_for_line(formatted_sorted_items, sort_field: sort_field)
  end

  protected

  def track
    track_event("catalog_front")
  end
end


text:
#if !defined(_HIJACK_ERROR_H)
#define _HIJACK_ERROR_H

int SetError(HIJACK *, int);
void ClearError(HIJACK *);

#endif


text:
ver=$(curl -Ls -o /dev/null -w %{url_effective} https://github.com/adobe/brackets/releases/latest)
ver=$(echo $ver | awk '{ver=substr($0, 56); print ver;}')
echo $ver
while :
do
	read -p "You are going to install Brackets. Is your system 32-bit or 64 bit? [32/64/back/exit] (default: 64) " bit
	if test "$bit" = ""
		then br="64"
	fi
	case $bit in

		# Dependencies: libgcrypt11
		32|64) if test "$bit" = "64"
			then wget http://ftp.debian.org/debian/pool/main/libg/libgcrypt11/libgcrypt11_1.5.0-5+deb7u3_amd64.deb
		elif test "$bit" = "32"
			then wget http://ftp.debian.org/debian/pool/main/libg/libgcrypt11/libgcrypt11_1.5.0-5+deb7u3_i386.deb
		fi
		sudo dpkg -i libgcrypt11_1.5.0-5+deb7u3_*.deb
		rm libgcrypt11_1.5.0-5+deb7u3_*.deb

		# Brackets installation
		wget https://github.com/adobe/brackets/releases/download/release-$ver%2Beb4/Brackets.$ver.Extract.$bit-bit.deb
		sudo dpkg -i Brackets.$ver.Extract.$bit-bit.deb
		rm Brackets.$ver.Extract.$bit-bit.deb
		echo Brackets $ver $bit-bit installed!
		break;;

		back) break;;
		exit*) exit;;
		*) echo Invalid answer.;;
	esac
done


text:
package tutorial_1;

import java.util.Scanner;

public class ChessLauncher {
  public static void main(String args[]) {
    tutorial_1.HighScore scores = new tutorial_1.HighScore();
    Scanner scanner = new Scanner(System.in);
    int choice;
    do {
      System.out.println("\n" +
        "1. Play Chess\n" +
        "2. Exit\n" +
        "\n" +
        "Enter choice: ");
      try {
        choice = scanner.nextInt();
      } catch (Exception e) {
        scanner.nextLine();
        choice = 50;
      }
      switch (choice) {
        case 1:
          tutorial_1.Chess.main(scores);
          break;
        case 2:
          break;
        default:
          System.out.println("Unknown Choice! Please try again!");
      }
    } while (choice != 2);
  }
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.collection
package immutable

import generic._
import mutable.{Builder, StringBuilder, LazyBuilder, ListBuffer}
import scala.annotation.tailrec

/** The class `Stream` implements lazy lists where elements
 *  are only evaluated when they are needed. Here is an example:
 *
 *  {{{
 *  object Main extends Application {
 *
 *    def from(n: Int): Stream[Int] =
 *      Stream.cons(n, from(n + 1))
 *
 *    def sieve(s: Stream[Int]): Stream[Int] =
 *      Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 }))
 *
 *    def primes = sieve(from(2))
 *
 *    primes take 10 print
 *  }
 *  }}}
 *
 *  @tparam A    the type of the elements contained in this stream.
 *
 *  @author Martin Odersky, Matthias Zenger
 *  @version 1.1 08/08/03
 *  @since   2.8
 *  @define Coll Stream
 *  @define coll stream
 *  @define orderDependent
 *  @define orderDependentFold
 */
abstract class Stream[+A] extends LinearSeq[A]
                             with GenericTraversableTemplate[A, Stream]
                             with LinearSeqOptimized[A, Stream[A]] {
self =>
  override def companion: GenericCompanion[Stream] = Stream

  import scala.collection.{Traversable, Iterable, Seq, IndexedSeq}

  /** is this stream empty? */
  def isEmpty: Boolean

  /** The first element of this stream
   *  @throws Predef.NoSuchElementException if the stream is empty.
   */
  def head: A

  /** A stream consisting of the remaining elements of this stream after the first one.
   *  @throws Predef.UnsupportedOperationException if the stream is empty.
   */
  def tail: Stream[A]

  /** Is the tail of this stream defined? */
  protected def tailDefined: Boolean

  // Implementation of abstract method in Traversable

  // New methods in Stream

  /** The stream resulting from the concatenation of this stream with the argument stream.
   *  @param rest   The stream that gets appended to this stream
   *  @return       The stream containing elements of this stream and the traversable object.
   */
  def append[B >: A](rest: => Traversable[B]): Stream[B] =
    if (isEmpty) rest.toStream else new Stream.Cons(head, tail append rest)

  /** Forces evaluation of the whole stream and returns it. */
  def force: Stream[A] = {
    var these = this
    while (!these.isEmpty) these = these.tail
    this
  }

  /** Prints elements of this stream one by one, separated by commas. */
  def print() { print(", ") }

  /** Prints elements of this stream one by one, separated by `sep`.
   *  @param sep   The separator string printed between consecutive elements.
   */
  def print(sep: String) {
    def loop(these: Stream[A], start: String) {
      Console.print(start)
      if (these.isEmpty) Console.print("empty")
      else {
        Console.print(these.head)
        loop(these.tail, sep)
      }
    }
    loop(this, "")
  }

  override def length: Int = {
    var len = 0
    var left = this
    while (!left.isEmpty) {
      len += 1
      left = left.tail
    }
    len
  }

  /** It's an imperfect world, but at least we can bottle up the
   *  imperfection in a capsule.
   */
  @inline private def asThat[That](x: AnyRef): That     = x.asInstanceOf[That]
  @inline private def asStream[B](x: AnyRef): Stream[B] = x.asInstanceOf[Stream[B]]

  // Overridden methods from Traversable

  override def toStream: Stream[A] = this

  override def hasDefiniteSize = {
    def loop(s: Stream[A]): Boolean = s.isEmpty || s.tailDefined && loop(s.tail)
    loop(this)
  }

  /** Create a new stream which contains all elements of this stream
   *  followed by all elements of Traversable `that`.
   *  @note It's subtle why this works. We know that if the target type
   *  of the Builder That is either a Stream, or one of its supertypes, or undefined,
   *  then StreamBuilder will be chosen for the implicit.
   *  we recognize that fact and optimize to get more laziness.
   */
  override def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
    // we assume there is no other builder factory on streams and therefore know that That = Stream[A]
    asThat[That](
      if (isEmpty) that.toStream
      else new Stream.Cons(head, asStream[A](tail ++ that))
    )

  /**
   * Create a new stream which contains all intermediate results of applying the operator
   * to subsequent elements left to right.
   * @note This works because the target type of the Builder That is a Stream.
   */
  override final def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
    asThat[That](
      if (isEmpty) Stream(z)
      else new Stream.Cons(z, asStream[B](tail.scanLeft(op(z, head))(op)))
    )

  /** Returns the stream resulting from applying the given function
   *  `f` to each element of this stream.
   *
   *  @param f function to apply to each element.
   *  @return  f(a0), ..., f(an) if this
   *           sequence is a0, ..., an.
   */
  override final def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
    asThat[That](
      if (isEmpty) Stream.Empty
      else new Stream.Cons(f(head), asStream[B](tail map f))
    )

  /** Applies the given function `f` to each element of
   *  this stream, then concatenates the results.
   *
   *  @param f  the function to apply on each element.
   *  @param bf $bfinfo
   *  @return  f(a0) ::: ... ::: f(an) if
   *           this stream is [a0, ..., an].
   */
  override final def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
    // we assume there is no other builder factory on streams and therefore know that That = Stream[B]
    // optimisations are not for speed, but for functionality
    // see tickets #153, #498, #2147, and corresponding tests in run/ (as well as run/stream_flatmap_odds.scala)
    asThat[That](
      if (isEmpty) Stream.Empty
      else {
        // establish !prefix.isEmpty || nonEmptyPrefix.isEmpty
        var nonEmptyPrefix = this
        var prefix = f(nonEmptyPrefix.head).toStream
        while (!nonEmptyPrefix.isEmpty && prefix.isEmpty) {
          nonEmptyPrefix = nonEmptyPrefix.tail
          if(!nonEmptyPrefix.isEmpty)
            prefix = f(nonEmptyPrefix.head).toStream
        }

        if (nonEmptyPrefix.isEmpty) Stream.empty
        else prefix append asStream[B](nonEmptyPrefix.tail flatMap f)
      }
    )

  /** Returns all the elements of this stream that satisfy the
   *  predicate p. The order of the elements is preserved.
   *
   *  @param p the predicate used to filter the stream.
   *  @return the elements of this stream satisfying p.
   */
  override final def filter(p: A => Boolean): Stream[A] = {
    // optimization: drop leading prefix of elems for which f returns false
    var rest = this dropWhile (!p(_))
    if (rest.isEmpty) Stream.Empty
    else new Stream.Cons(rest.head, rest.tail filter p)
  }

  override final def withFilter(p: A => Boolean): StreamWithFilter = new StreamWithFilter(p)

  /** A lazier implementation of WithFilter than TraversableLike's.
   */
  final class StreamWithFilter(p: A => Boolean) extends WithFilter(p) {
    override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
      def tailMap = asStream[B](tail withFilter p map f)
      asThat[That](
        if (isEmpty) Stream.Empty
        else if (p(head)) new Stream.Cons(f(head), tailMap)
        else tailMap
      )
    }

    override def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
      def tailFlatMap = asStream[B](tail withFilter p flatMap f)
      asThat[That](
        if (isEmpty) Stream.Empty
        else if (p(head)) f(head).toStream append tailFlatMap
        else tailFlatMap
      )
    }

    override def foreach[B](f: A => B) =
      for (x <- self)
        if (p(x)) f(x)

    override def withFilter(q: A => Boolean): StreamWithFilter =
      new StreamWithFilter(x => p(x) && q(x))
  }

  /** Apply the given function f to each element of this linear sequence
   *  (while respecting the order of the elements).
   *
   *  @param f the treatment to apply to each element.
   *  @note  Overridden here as final to trigger tail-call optimization, which replaces
   *         'this' with 'tail' at each iteration. This is absolutely necessary
   *         for allowing the GC to collect the underlying stream as elements are
   *         consumed.
   */
  @tailrec
  override final def foreach[B](f: A => B) {
    if (!this.isEmpty) {
      f(head)
      tail.foreach(f)
    }
  }

  /** Stream specialization of foldLeft which allows GC to collect
   *  along the way.
   */
  @tailrec
  override final def foldLeft[B](z: B)(op: (B, A) => B): B = {
    if (this.isEmpty) z
    else tail.foldLeft(op(z, head))(op)
  }

  /** Returns all the elements of this stream that satisfy the
   *  predicate p. The order of the elements is preserved.
   *
   *  @param p the predicate used to filter the stream.
   *  @return the elements of this stream satisfying p.
   */
  override def partition(p: A => Boolean): (Stream[A], Stream[A]) = (filter(p(_)), filterNot(p(_)))

  /** Returns a stream formed from this stream and the specified stream
   *  that by associating each element of the former with
   *  the element at the same position in the latter.
   *  If one of the two streams is longer than the other, its remaining elements are ignored.
   *
   *  @return     Stream({a0,b0}, ...,
   *              {amin(m,n),bmin(m,n))} when
   *              Stream(a0, ..., am)
   *              zip Stream(b0, ..., bn) is invoked.
   */
  override final def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Stream[A], (A1, B), That]): That =
    // we assume there is no other builder factory on streams and therefore know that That = Stream[(A1, B)]
    asThat[That](
      if (this.isEmpty || that.isEmpty) Stream.Empty
      else new Stream.Cons((this.head, that.head), asStream[(A1, B)](this.tail zip that.tail))
    )

  /** Zips this iterable with its indices. `s.zipWithIndex` is equivalent to
   *  `s zip s.indices`
   */
  override def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Stream[A], (A1, Int), That]): That =
    this.zip[A1, Int, That](Stream.from(0))

  /** Write all defined elements of this iterable into given string builder.
   *  The written text begins with the string start and is finished by the string
   *  end. Inside, the string representations of defined elements (w.r.t.
   *  the method toString()) are separated by the string
   *  sep. The method will not force evaluation of undefined elements. A
   *  tail of such elements will be represented by a "?" instead.
   */
  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
    def loop(pre: String, these: Stream[A]) {
      if (these.isEmpty) b append end
      else {
        b append pre append these.head
        if (these.tailDefined) loop(sep, these.tail)
        else b append sep append "?" append end
      }
    }
    b append start
    loop("", this)
    b
  }

  override def mkString(start: String, sep: String, end: String): String = {
    this.force
    super.mkString(start, sep, end)
  }

  override def mkString(sep: String): String = {
    this.force
    super.mkString(sep)
  }

  override def mkString: String = {
    this.force
    super.mkString
  }

  override def toString = super.mkString(stringPrefix + "(", ", ", ")")

  /** Returns the n first elements of this stream, or else the whole
   *  stream, if it has less than n elements.
   *
   *  @param n the number of elements to take.
   *  @return the n first elements of this stream.
   */
  override def take(n: Int): Stream[A] =
    if (n <= 0 || isEmpty) Stream.Empty
    else new Stream.Cons(head, if (n == 1) Stream.empty else tail take (n-1))

  /** A substream starting at index `from`
   *  and extending up to (but not including) index `until`.
   *
   *  @note This is equivalent to (but possibly more efficient than)
   *  c.drop(from).take(to - from)
   *
   *  @param start   The index of the first element of the returned subsequence
   *  @param end     The index of the element following the returned subsequence
   *  @throws IndexOutOfBoundsException if from < 0
   *          or length < from + len
   *  @note  Might return different results for different runs, unless this iterable is ordered
   */
  override def slice(start: Int, end: Int): Stream[A] = {
    var len = end
    if (start > 0) len -= start
    drop(start) take len
  }

  /** The stream without its last element.
   *  @throws Predef.UnsupportedOperationException if the stream is empty.
   */
  override def init: Stream[A] =
    if (isEmpty) super.init
    else if (tail.isEmpty) Stream.Empty
    else new Stream.Cons(head, tail.init)

  /** Returns the rightmost n elements from this iterable.
   *  @param n the number of elements to take
   */
  override def takeRight(n: Int): Stream[A] = {
    var these: Stream[A] = this
    var lead = this drop n
    while (!lead.isEmpty) {
      these = these.tail
      lead = lead.tail
    }
    these
  }

  // there's nothing we can do about dropRight, so we just keep the definition in LinearSeq

  /** Returns the longest prefix of this stream whose elements satisfy
   *  the predicate p.
   *
   *  @param p the test predicate.
   */
  override def takeWhile(p: A => Boolean): Stream[A] =
    if (!isEmpty && p(head)) new Stream.Cons(head, tail takeWhile p)
    else Stream.Empty

  /** Returns the longest suffix of this iterable whose first element
   *  does not satisfy the predicate p.
   *
   *  @param p the test predicate.
   */
  override def dropWhile(p: A => Boolean): Stream[A] = {
    var these: Stream[A] = this
    while (!these.isEmpty && p(these.head)) these = these.tail
    these
  }

  /** Builds a new stream from this stream in which any duplicates (wrt to ==) removed.
   *  Among duplicate elements, only the first one is retained in the result stream
   */
  override def distinct: Stream[A] =
    if (isEmpty) this
    else new Stream.Cons(head, tail.filter(head !=).distinct)

  /** Returns a new sequence of given length containing the elements of this sequence followed by zero
   *  or more occurrences of given elements.
   */
  override def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
    def loop(len: Int, these: Stream[A]): Stream[B] =
      if (these.isEmpty) Stream.fill(len)(elem)
      else new Stream.Cons(these.head, loop(len - 1, these.tail))

    asThat[That](loop(len, this))
// was:    if (bf.isInstanceOf[Stream.StreamCanBuildFrom[_]]) loop(len, this).asInstanceOf[That]
//    else super.padTo(len, elem)
  }

  /** A list consisting of all elements of this list in reverse order.
   */
  override def reverse: Stream[A] = {
    var result: Stream[A] = Stream.Empty
    var these = this
    while (!these.isEmpty) {
      val r = Stream.consWrapper(result).#::(these.head)
      r.tail // force it!
      result = r
      these = these.tail
    }
    result
  }

  override def flatten[B](implicit asTraversable: A => /*<:<!!!*/ Traversable[B]): Stream[B] = {
    def flatten1(t: Traversable[B]): Stream[B] =
      if (!t.isEmpty)
        new Stream.Cons(t.head, flatten1(t.tail))
      else
        tail.flatten

    if (isEmpty)
      Stream.empty
    else
      flatten1(asTraversable(head))
  }

  /** Defines the prefix of this object's toString representation as ``Stream''.
   */
  override def stringPrefix = "Stream"
}

/**
 * The object Stream provides helper functions
 * to manipulate streams.
 *
 * @author Martin Odersky, Matthias Zenger
 * @version 1.1 08/08/03
 * @since   2.8
 */
object Stream extends SeqFactory[Stream] {

  /** The factory for streams.
   *  @note Methods such as map/flatMap will not invoke the Builder factory,
   *        but will return a new stream directly, to preserve laziness.
   *        The new stream is then cast to the factory's result type.
   *        This means that every CanBuildFrom that takes a
   *        Stream as its From type parameter must yield a stream as its result parameter.
   *        If that assumption is broken, cast errors might result.
   */
  class StreamCanBuildFrom[A] extends GenericCanBuildFrom[A]

  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Stream[A]] = new StreamCanBuildFrom[A]

  /** Creates a new builder for a stream */
  def newBuilder[A]: Builder[A, Stream[A]] = new StreamBuilder[A]

  import scala.collection.{Iterable, Seq, IndexedSeq}

  /** A builder for streams
   *  @note This builder is lazy only in the sense that it does not go downs the spine
   *        of traversables that are added as a whole. If more laziness can be achieved,
   *        this builder should be bypassed.
   */
  class StreamBuilder[A] extends scala.collection.mutable.LazyBuilder[A, Stream[A]] {
    def result: Stream[A] = parts.toStream flatMap (_.toStream)
  }

  object Empty extends Stream[Nothing] {
    override def isEmpty = true
    override def head = throw new NoSuchElementException("head of empty stream")
    override def tail = throw new UnsupportedOperationException("tail of empty stream")
    def tailDefined = false
  }

  /** The empty stream */
  override def empty[A]: Stream[A] = Empty

  /** A stream consisting of given elements */
  override def apply[A](xs: A*): Stream[A] = xs.toStream

  /** A wrapper class that adds `#::` for cons and `#:::` for concat as operations
   *  to streams.
   */
  class ConsWrapper[A](tl: => Stream[A]) {
    def #::(hd: A): Stream[A] = new Stream.Cons(hd, tl)
    def #:::(prefix: Stream[A]): Stream[A] = prefix append tl
  }

  /** A wrapper method that adds `#::` for cons and `#::: for concat as operations
   *  to streams.
   */
  implicit def consWrapper[A](stream: => Stream[A]): ConsWrapper[A] =
    new ConsWrapper[A](stream)

  /** An extractor that allows to pattern match streams with `#::`.
   */
  object #:: {
    def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] =
      if (xs.isEmpty) None
      else Some((xs.head, xs.tail))
  }

  @deprecated("use #:: instead") lazy val lazy_:: = #::

  /** An alternative way of building and matching Streams using Stream.cons(hd, tl).
   */
  object cons {

    /** A stream consisting of a given first element and remaining elements
     *  @param hd   The first element of the result stream
     *  @param tl   The remaining elements of the result stream
     */
    def apply[A](hd: A, tl: => Stream[A]) = new Cons(hd, tl)

    /** Maps a stream to its head and tail */
    def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] = #::.unapply(xs)
  }

  /** A lazy cons cell, from which streams are built. */
  @serializable @SerialVersionUID(-602202424901551803L)
  final class Cons[+A](hd: A, tl: => Stream[A]) extends Stream[A] {
    override def isEmpty = false
    override def head = hd
    private[this] var tlVal: Stream[A] = _
    def tailDefined = tlVal ne null
    override def tail: Stream[A] = {
      if (!tailDefined) { tlVal = tl }
      tlVal
    }
  }

  /** An infinite stream that repeatedly applies a given function to a start value.
   *
   *  @param start the start value of the stream
   *  @param f     the function that's repeatedly applied
   *  @return      the stream returning the infinite sequence of values `start, f(start), f(f(start)), ...`
   */
  def iterate[A](start: A)(f: A => A): Stream[A] = new Cons(start, iterate(f(start))(f))

  override def iterate[A](start: A, len: Int)(f: A => A): Stream[A] =
    iterate(start)(f) take len

  /**
   * Create an infinite stream starting at start
   * and incrementing by step step
   *
   * @param start the start value of the stream
   * @param step the increment value of the stream
   * @return the stream starting at value start.
   */
  def from(start: Int, step: Int): Stream[Int] =
    new Cons(start, from(start+step, step))

  /**
   * Create an infinite stream starting at start
   * and incrementing by 1.
   *
   * @param start the start value of the stream
   * @return the stream starting at value start.
   */
  def from(start: Int): Stream[Int] = from(start, 1)

  /**
   * Create an infinite stream containing the given element expression (which is computed for each
   * occurrence)
   *
   * @param elem the element composing the resulting stream
   * @return the stream containing an infinite number of elem
   */
  def continually[A](elem: => A): Stream[A] = new Cons(elem, continually(elem))

  override def fill[A](n: Int)(elem: => A): Stream[A] =
    if (n <= 0) Empty else new Cons(elem, fill(n-1)(elem))

  override def tabulate[A](n: Int)(f: Int => A): Stream[A] = {
    def loop(i: Int) =
      if (i >= n) Empty else new Cons(f(i), tabulate(i+1)(f))
    loop(0)
  }

  override def range(start: Int, end: Int, step: Int): Stream[Int] =
    if (if (step < 0) start <= end else end <= start) Empty
    else new Cons(start, range(start + step, end, step))

  /** A stream containing all elements of a given iterator, in the order they are produced.
   *  @param it   The iterator producing the stream's elements
   */
  @deprecated("use it.toStream instead")
  def fromIterator[A](it: Iterator[A]): Stream[A] = it.toStream

  /** The concatenation of a sequence of streams
   */
  @deprecated("use xs.flatten instead")
  def concat[A](xs: Iterable[Stream[A]]): Stream[A] = concat(xs.iterator)

  /** The concatenation of all streams returned by an iterator
   */
  @deprecated("use xs.toStream.flatten instead")
  def concat[A](xs: Iterator[Stream[A]]): Stream[A] = xs.toStream.flatten //(conforms[Stream[A], scala.collection.Traversable[A]])

  /**
   * Create a stream with element values
   * vn+1 = step(vn)
   * where v0 = start
   * and elements are in the range between start (inclusive)
   * and end (exclusive)
   * @param start the start value of the stream
   * @param end the end value of the stream
   * @param step the increment function of the stream, must be monotonically increasing or decreasing
   * @return the stream starting at value start.
   */
  @deprecated("use `iterate' instead.")
  def range(start: Int, end: Int, step: Int => Int): Stream[Int] =
    iterate(start, end - start)(step)

  /**
   * Create an infinite stream containing the given element.
   *
   * @param elem the element composing the resulting stream
   * @return the stream containing an infinite number of elem
   */
  @deprecated("use `continually' instead")
  def const[A](elem: A): Stream[A] = cons(elem, const(elem))

  /** Create a stream containing several copies of an element.
   *
   *  @param n    the length of the resulting stream
   *  @param elem the element composing the resulting stream
   *  @return     the stream composed of n elements all equal to elem
   */
  @deprecated("use fill(n, elem) instead")
  def make[A](n: Int, elem: A): Stream[A] = fill(n)(elem)
}


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	"context"

	v1alpha1 "github.com/libopenstorage/stork/pkg/apis/stork/v1alpha1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeSchedulePolicies implements SchedulePolicyInterface
type FakeSchedulePolicies struct {
	Fake *FakeStorkV1alpha1
}

var schedulepoliciesResource = schema.GroupVersionResource{Group: "stork.libopenstorage.org", Version: "v1alpha1", Resource: "schedulepolicies"}

var schedulepoliciesKind = schema.GroupVersionKind{Group: "stork.libopenstorage.org", Version: "v1alpha1", Kind: "SchedulePolicy"}

// Get takes name of the schedulePolicy, and returns the corresponding schedulePolicy object, and an error if there is any.
func (c *FakeSchedulePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.SchedulePolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(schedulepoliciesResource, name), &v1alpha1.SchedulePolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.SchedulePolicy), err
}

// List takes label and field selectors, and returns the list of SchedulePolicies that match those selectors.
func (c *FakeSchedulePolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.SchedulePolicyList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(schedulepoliciesResource, schedulepoliciesKind, opts), &v1alpha1.SchedulePolicyList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1alpha1.SchedulePolicyList{ListMeta: obj.(*v1alpha1.SchedulePolicyList).ListMeta}
	for _, item := range obj.(*v1alpha1.SchedulePolicyList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested schedulePolicies.
func (c *FakeSchedulePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(schedulepoliciesResource, opts))
}

// Create takes the representation of a schedulePolicy and creates it.  Returns the server's representation of the schedulePolicy, and an error, if there is any.
func (c *FakeSchedulePolicies) Create(ctx context.Context, schedulePolicy *v1alpha1.SchedulePolicy, opts v1.CreateOptions) (result *v1alpha1.SchedulePolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(schedulepoliciesResource, schedulePolicy), &v1alpha1.SchedulePolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.SchedulePolicy), err
}

// Update takes the representation of a schedulePolicy and updates it. Returns the server's representation of the schedulePolicy, and an error, if there is any.
func (c *FakeSchedulePolicies) Update(ctx context.Context, schedulePolicy *v1alpha1.SchedulePolicy, opts v1.UpdateOptions) (result *v1alpha1.SchedulePolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(schedulepoliciesResource, schedulePolicy), &v1alpha1.SchedulePolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.SchedulePolicy), err
}

// Delete takes name of the schedulePolicy and deletes it. Returns an error if one occurs.
func (c *FakeSchedulePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(schedulepoliciesResource, name), &v1alpha1.SchedulePolicy{})
	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeSchedulePolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(schedulepoliciesResource, listOpts)

	_, err := c.Fake.Invokes(action, &v1alpha1.SchedulePolicyList{})
	return err
}

// Patch applies the patch and returns the patched schedulePolicy.
func (c *FakeSchedulePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.SchedulePolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(schedulepoliciesResource, name, pt, data, subresources...), &v1alpha1.SchedulePolicy{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.SchedulePolicy), err
}


text:
\begin{figure}[H]

    \hspace{-1.5cm}
    \noindent\makebox[\textwidth]{
        \centering
        %\includegraphics[width=0.8\textwidth]{../../sympy/catalan/coloured.pdf}

        % using *angle* property to rotate it is difficult to properly align it
        % in order to have a "real" matrix representation.
        \includegraphics[width=15cm, height=15cm, keepaspectratio=true]{../sympy/fibonacci/fibonacci-standard-handle-negatives-centered-colouring-127-rows-mod2-partitioning-triangle.pdf}
    }

    % this 'particular' line is necessary to use `displaymath' environment
    % into the caption environment, togheter with the inclusion of
    % `caption' package. See here for more explanation:
    % http://stackoverflow.com/questions/2716227/adding-an-equation-or-formula-to-a-figure-caption-in-latex
    \captionsetup{singlelinecheck=off}
    \caption[$\mathcal{F}_{\stackrel{\circ}{\equiv_{2}}}$]{ $\mathcal{F}_{\stackrel{\circ}{\equiv_{2}}}$ }

    \label{fig:fibonacci-standard-handle-negatives-centered-colouring-127-rows-mod2-partitioning-triangle}

\end{figure}


text:
#include <irtkRegistration.h>

// Used as temporary memory for transformed intensities
extern irtkGreyImage *_tmpImage;

// Used as temporary memory for metric
extern irtkSimilarityMetric *_tmpMetricA, *_tmpMetricB;

// Used as lookup table for transformed coordinates up to level n-1.  This
// lookup table needs to be calculated only once for each image resolution
// level.
extern float *_mffdLookupTable;

// Used as lookup table for transformed coordinates including level n. This
// lookup table needs to be calculated each time a control point has been
// modified.
extern float *_affdLookupTable;

// Used as lookup table for the contribution of each control point. This
// lookup table needs to be calculated only once.
extern float *_localLookupTable;

void irtkImageFreeFormRegistration2D::GuessParameter()
{
  int i;
  double xsize, ysize, zsize, spacing;

  if ((_target == NULL) || (_source == NULL)) {
    cerr << "irtkImageFreeFormRegistration2D::GuessParameter: Target and source image not found" << endl;
    exit(1);
  }

  // Default parameters for registration
  _NumberOfLevels     = 3;
  _NumberOfBins       = 64;

  // Default parameters for optimization
  _SimilarityMeasure  = NMI;
  _OptimizationMethod = GradientDescent;
  _Epsilon            = 0.0001;

  // Read target pixel size
  _target->GetPixelSize(&xsize, &ysize, &zsize);

  // Use xsize as spacing
  spacing = xsize;

  // Default target parameters
  _TargetBlurring[0]      = GuessResolution(xsize, ysize) / 2.0;
  _TargetResolution[0][0] = GuessResolution(xsize, ysize);
  _TargetResolution[0][1] = GuessResolution(xsize, ysize);
  _TargetResolution[0][2] = zsize;

  for (i = 1; i < _NumberOfLevels; i++) {
    _TargetBlurring[i]      = _TargetBlurring[i-1] * 2;
    _TargetResolution[i][0] = _TargetResolution[i-1][0] * 2;
    _TargetResolution[i][1] = _TargetResolution[i-1][1] * 2;
    _TargetResolution[i][2] = zsize;
  }

  // Read source pixel size
  _source->GetPixelSize(&xsize, &ysize, &zsize);

  // Default source parameters
  _SourceBlurring[0]      = GuessResolution(xsize, ysize, zsize) / 2.0;
  _SourceResolution[0][0] = GuessResolution(xsize, ysize);
  _SourceResolution[0][1] = GuessResolution(xsize, ysize);
  _SourceResolution[0][2] = zsize;

  for (i = 1; i < _NumberOfLevels; i++) {
    _SourceBlurring[i]      = _SourceBlurring[i-1] * 2;
    _SourceResolution[i][0] = _SourceResolution[i-1][0] * 2;
    _SourceResolution[i][1] = _SourceResolution[i-1][1] * 2;
    _SourceResolution[i][2] = zsize;
  }

  // Default parameters for non-rigid registration
  _Lambda1            = 0;
  _Lambda2            = 0;
  _Lambda3            = 0;
  _DX                 =_target->GetX() * spacing / 10.0;
  _DY                 =_target->GetX() * spacing / 10.0;
  _DZ                 = 1;
  _Subdivision        = true;

  // Remaining parameters
  for (i = 0; i < _NumberOfLevels; i++) {
    _NumberOfIterations[i] = 10;
    _NumberOfSteps[i]      = 4;
    _LengthOfSteps[i]      = _DX / 8.0 * pow(2.0, i);
  }

  // Try to guess padding by looking at voxel values in all eight corners of the volume:
  // If all values are the same we assume that they correspond to the padding value
  _TargetPadding = MIN_GREY;
  if ((_target->Get(_target->GetX()-1, 0, 0)                 == _target->Get(0, 0, 0)) &&
      (_target->Get(0, _target->GetY()-1, 0)                 == _target->Get(0, 0, 0)) &&
      (_target->Get(_target->GetX()-1, _target->GetY()-1, 0) == _target->Get(0, 0, 0))) {
    _TargetPadding = _target->Get(0, 0, 0);
  }
}

double irtkImageFreeFormRegistration2D::Evaluate()
{
  // Image coordinates
  int i, j;
  // World coordinates
  double x, y, z;
  // Pointer to reference data
  irtkGreyPixel *ptr2target;
  irtkGreyPixel *ptr2tmp;
  float *ptr;

  // Print debugging information
  this->Debug("irtkImageFreeFormRegistration2D::Evaluate");

  // Initialize histogram
  _metric->Reset();

  // Loop over all voxels in the target (reference) volume
  ptr2target = _target->GetPointerToVoxels();
  ptr2tmp    = _tmpImage->GetPointerToVoxels();
  ptr        = _mffdLookupTable;;
  for (j = 0; j < _target->GetY(); j++) {
    for (i = 0; i < _target->GetX(); i++) {
      // Check whether reference point is valid
      if (*ptr2target >= 0) {
        x = i;
        y = j;
        z = 0;
        _target->ImageToWorld(x, y, z);
        _affd->LocalDisplacement(x, y, z);
        x += ptr[0];
        y += ptr[1];
        _source->WorldToImage(x, y, z);
        // Check whether transformed point is inside volume
        if ((x > _source_x1) && (x < _source_x2) &&
            (y > _source_y1) && (y < _source_y2)) {
          // Add sample to metric
          *ptr2tmp =  round(_interpolator->EvaluateInside(x, y, 0));
          _metric->Add(*ptr2target, *ptr2tmp);
        } else {
          *ptr2tmp = -1;
        }
      }
      // Increment pointers to next voxel
      ptr2tmp++;
      ptr2target++;
      ptr += 3;
    }
  }

  // Evaluate similarity measure
  double similarity = _metric->Evaluate();

  // Add penalty for smoothness
  if (this->_Lambda1 > 0) {
    similarity += this->_Lambda1*this->SmoothnessPenalty();
  }
  // Add penalty for volume preservation
  if (this->_Lambda2 > 0) {
    similarity += this->_Lambda2*this->VolumePreservationPenalty();
  }
  // Add penalty for topology preservation
  if (this->_Lambda3 > 0) {
    similarity += this->_Lambda3*this->TopologyPreservationPenalty();
  }

  // Return similarity measure + penalty terms
  return similarity;
}

double irtkImageFreeFormRegistration2D::EvaluateDerivative(int index, double step)
{
  float *ptr;
  double bi, bj, bk, dx, dy, p[3];
  int i, j, i1, i2, j1, j2, k1, k2, dim;
  irtkPoint p1, p2;
  irtkGreyPixel *ptr2target, *ptr2tmp;

  // Print debugging information
  this->Debug("irtkImageFreeFormRegistration2D::EvaluateDerivative(int, double)");

  // Initialize metrics for forward and backward derivative steps
  _tmpMetricA->ResetAndCopy(_metric);
  _tmpMetricB->ResetAndCopy(_metric);

  // Calculate bounding box of control point in world coordinates
  _affd->BoundingBoxCP(index, p1, p2);
  _target->WorldToImage(p1);
  _target->WorldToImage(p2);

  // Calculate bounding box of control point in image coordinates
  _affd->BoundingBoxImage(_target, index, i1, j1, k1, i2, j2, k2, 1.0 / _SpeedupFactor);

  // Calculate incremental changes in lattice coordinates when looping
  // over target
  dx = (FFDLOOKUPTABLESIZE-1)/(p2._x-p1._x);
  dy = (FFDLOOKUPTABLESIZE-1)/(p2._y-p1._y);

  // Calculate whether this DOF corresponds to x, y or z-displacement
  dim = int(index / (_affd->GetX()*_affd->GetY()*_affd->GetZ()));

  // Loop over all voxels in the target (reference) volume
  bk = step * _localLookupTable[FFDLOOKUPTABLESIZE/2];
  for (j = j1; j <= j2; j++) {
    ptr2target = _target->GetPointerToVoxels(i1, j, 0);
    ptr        = &(_affdLookupTable[3*_target->VoxelToIndex(i1, j, 0)]);
    bj = bk * _localLookupTable[round(dy*(j-p1._y))];
    ptr2tmp  = _tmpImage->GetPointerToVoxels(i1, j, 0);
    for (i = i1; i <= i2; i++) {

      // Check whether reference point is valid
      if (*ptr2target >= 0) {
        bi = bj * _localLookupTable[round(dx*(i-p1._x))];

        // Delete old samples from both metrics
        if (*ptr2tmp != -1) {
          _tmpMetricA->Delete(*ptr2target, *ptr2tmp);
          _tmpMetricB->Delete(*ptr2target, *ptr2tmp);
        }

        p[0] = ptr[0];
        p[1] = ptr[1];
        p[2] = ptr[2];
        p[dim] += bi;

        // Convert transformed point to image coordinates
        _source->WorldToImage(p[0], p[1], p[2]);

        // Check whether transformed point is inside volume
        if ((p[0] > _source_x1) && (p[0] < _source_x2) &&
            (p[1] > _source_y1) && (p[1] < _source_y2)) {

          // Add sample to metric
          _tmpMetricA->Add(*ptr2target, round(_interpolator->EvaluateInside(p[0], p[1], 0)));
        }

        p[0] = ptr[0];
        p[1] = ptr[1];
        p[2] = ptr[2];
        p[dim] -= bi;

        // Convert transformed point to image coordinates
        _source->WorldToImage(p[0], p[1], p[2]);

        // Check whether transformed point is inside volume
        if ((p[0] > _source_x1) && (p[0] < _source_x2) &&
            (p[1] > _source_y1) && (p[1] < _source_y2)) {

          // Add sample to metric
          _tmpMetricB->Add(*ptr2target, round(_interpolator->EvaluateInside(p[0], p[1], 0)));
        }
      }

      // Increment pointers to next voxel
      ptr2target++;
      ptr2tmp++;
      ptr += 3;
    }
  }

  // Save value of DOF for which we calculate the derivative
  double dof = _affd->Get(index);

  // Evaluate similarity measure
  double similarityA = _tmpMetricA->Evaluate();

  // Add penalties
  _affd->Put(index, dof + step);

  // Smoothness
  if (this->_Lambda1 > 0) {
    similarityA += this->_Lambda1*this->SmoothnessPenalty(index);
  }
  // Volume preservation
  if (this->_Lambda2 > 0) {
    similarityA += this->_Lambda2*this->VolumePreservationPenalty(index);
  }
  // Topology preservation
  if (this->_Lambda3 > 0) {
    similarityA += this->_Lambda3*this->TopologyPreservationPenalty(index);
  }

  // Evaluate similarity measure
  double similarityB = _tmpMetricB->Evaluate();

  // Add penalties
  _affd->Put(index, dof - step);

  // Smoothness
  if (this->_Lambda1 > 0) {
    similarityB += this->_Lambda1*this->SmoothnessPenalty(index);
  }
  // Volume preservation
  if (this->_Lambda2 > 0) {
    similarityB += this->_Lambda2*this->VolumePreservationPenalty(index);
  }
  // Topology preservation
  if (this->_Lambda3 > 0) {
    similarityB += this->_Lambda3*this->TopologyPreservationPenalty(index);
  }

  // Restore value of DOF for which we calculate the derivative
  _affd->Put(index, dof);

  return similarityA - similarityB;
}


text:
package org.wso2.carbon.priority.executors.services;

/**
 * This is a dummy service interface which is used to enforce the
 * Synapse Application Deployer service startup order
 */
public interface PriorityExeDeployerService {
}


text:
package org.immutables.mongo.fixture.criteria;

import org.bson.BsonDocument;
import org.immutables.mongo.fixture.MongoAsserts;
import org.immutables.mongo.fixture.MongoContext;
import org.immutables.mongo.repository.Repositories;
import org.junit.Rule;
import org.junit.Test;

import static org.immutables.check.Checkers.check;

/**
 * Comparing queries generated directly by criteria.
 */
public class QueryTest {

  @Rule
  public final MongoContext context = MongoContext.create();

  private final PersonRepository repository = new PersonRepository(context.setup());

  @Test
  public void query() {
    final PersonRepository.Criteria criteria = repository.criteria();

    repository.find(criteria)
            .orderByAliases()
            .orderByNameDesceding();

    validate(criteria.name("foo"), BsonDocument.parse("{\"name\":\"foo\"}"));
    validate(criteria.name("foo").age(8), BsonDocument.parse("{\"name\":\"foo\", \"age\": 8}"));
    validate(criteria.name("foo").ageLessThan(8), BsonDocument.parse("{\"name\":\"foo\", \"age\": {\"$lt\": 8}}"));
    validate(criteria.ageLessThan(8).ageNot(5),
            BsonDocument.parse("{\"$and\": [{\"age\":{ \"$lt\": 8}}, {\"age\": {\"$ne\": 5}} ] }"));
    // pass as-is without optimizations
    validate(criteria.name("foo").name("bar"),
            BsonDocument.parse("{\"$and\": [{\"name\": \"foo\"}, {\"name\": \"bar\"}]}"));
    validate(criteria.name("foo").name("bar").name("qux"),
            BsonDocument.parse("{\"$and\": [{\"name\": \"foo\"}, {\"name\": \"bar\"}, {\"name\":\"qux\"}]}"));
    validate(criteria.name("foo").or().nameNot("bar"),
            BsonDocument.parse("{\"$or\": [{\"name\": \"foo\"}, {\"name\": {\"$ne\": \"bar\"}} ] }"));
    validate(criteria.nameIn("foo", "bar").name("bar"),
            BsonDocument.parse("{\"$and\":[ {\"name\": {\"$in\": [\"foo\", \"bar\"]}}, {\"name\": \"bar\"} ] }"));

    validate(criteria.name("foo").age(22).or().name("bar").age(33),
            BsonDocument.parse("{\"$or\": [" +
                    "{\"name\": \"foo\", \"age\": 22}, " +
                    "{\"name\": \"bar\", \"age\": 33}" +
                    "]}"));
  }

  /**
   * Converts given {@code criteria} to bson and compares with {@code expected}.
   *
   * @param criteria existing criteria to be sent to mogno (usually mongo query)
   * @param expected expected query (as bson)
   */
  private static void validate(Repositories.Criteria criteria, BsonDocument expected) {
    BsonDocument actual = MongoAsserts.extractQuery(criteria);
    check(actual).is(expected);
  }
}


text:
In harbor.cfg, make sure the attribute ```ui_url_protocol``` is set to ```https```, and the attributes ```ssl_cert``` and ```ssl_cert_key``` are pointed to valid certificates.  For more information about generating https certificate please refer to:  [Configuring HTTPS for Harbor](configure_https.md)

### Copy Root Certificate
Suppose the Harbor instance is hosted on a machine ```192.168.0.5```
If you are using a self-signed cetificate, make sure to copy the CA root cert to ```/etc/docker/certs.d/192.168.0.5/``` and ```~/.docker/tls/192.168.0.5:4443/```

### Enable Docker Content Trust
It can be done via setting envrironment variables:

```
export DOCKER_CONTENT_TRUST=1
export DOCKER_CONTENT_TRUST_SERVER=https://192.168.0.5:4443
```

### Set alias for notary (optional)
Because by default the local directory for storing meta files for notary client is different from docker client.  If you want to use notary client to manipulate the keys/meta files generated by Docker Content Trust, please set the alias to reduce the effort:

```
alias notary="notary -s https//192.168.0.5:4443 -d ~/.docker/trust --tlscacert  /etc/docker/certs.d/192.168.0.5/ca.crt"

```


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.IO;

using Sce.Atf;
using Sce.Atf.Dom;
using Sce.Atf.Applications;
using Sce.Atf.Adaptation;

using Sce.Atf.VectorMath;

using LevelEditorCore;

using ResourceLister = LevelEditorCore.ResourceLister;
using ViewTypes = Sce.Atf.Rendering.ViewTypes;

namespace RenderingInterop
{

    /// <summary>
    /// Thumbnail resolver for image resources</summary>
    [Export(typeof(IInitializable))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ResourcePreview : IInitializable
    {
        public ResourcePreview()
        {

            m_controlInfo = new ControlInfo(
                "Resource Preview".Localize(),
                "Preview selected 3d resource".Localize(),
                StandardControlGroup.Hidden);
        }

        #region IInitializable Members

        void IInitializable.Initialize()
        {
            if (m_resourceLister == null) return;

            m_resourceLister.SelectionChanged += resourceLister_SelectionChanged;
            m_renderSurface = new NativeViewControl();
            m_controlHostService.RegisterControl(m_renderSurface, m_controlInfo, null);
            Init();

        }

        #endregion

        private void resourceLister_SelectionChanged(object sender, EventArgs e)
        {
            if (m_game == null) return; // Init();

            m_game.RootGameObjectFolder.GameObjects.Clear();
            m_renderSurface.Invalidate();

            Uri resourceUri = m_resourceLister.LastSelected;
            if (resourceUri == null) return;

            IResource resource = m_resourceService.Load(resourceUri);
            var gob = m_resourceConverterService.Convert(resource) as IGameObject;

            if (gob != null)
            {
                m_game.RootGameObjectFolder.GameObjects.Add(gob);
                m_renderSurface.ResetCamera = true;
                m_renderSurface.Render();
                m_controlInfo.Name = "Resource Preview: ".Localize() + Path.GetFileName(resourceUri.LocalPath);
            }
            else
            {
                m_controlInfo.Name = "Resource Preview".Localize();
            }
        }

        private void Init()
        {
            // if (m_game != null)
            //     return;
            //
            // NativeObjectAdapter curLevel = GameEngine.GetGameLevel();
            // try
            // {
            //     // create new document by creating a Dom node of the root type defined by the schema
            //     DomNode rootNode = new DomNode(m_schemaLoader.GameType, m_schemaLoader.GameRootElement);
            //     INameable nameable = rootNode.As<INameable>();
            //     nameable.Name = "Game";
            //     NativeObjectAdapter gameLevel = rootNode.Cast<NativeObjectAdapter>();
            //     GameEngine.CreateObject(gameLevel);
            //     GameEngine.SetGameLevel(gameLevel);
            //     gameLevel.UpdateNativeOjbect();
            //     NativeDocumentAdapter gworld = rootNode.Cast<NativeDocumentAdapter>();
            //     m_game = rootNode.Cast<IGame>();
            //     IGameObjectFolder rootFolder = m_game.RootGameObjectFolder;
            //     m_renderSurface.Game = m_game;
            //     m_renderSurface.GameEngineProxy = m_gameEngine;
            //
            // }
            // finally
            // {
            //     GameEngine.SetGameLevel(curLevel);
            // }
            //
            //
            // m_mainWindow.Closed += delegate
            // {
            //     GameEngine.DestroyObject(m_game.Cast<NativeObjectAdapter>());
            //     m_renderSurface.Dispose();
            // };
        }

        // [Import(AllowDefault = false)]
        // private ISchemaLoader m_schemaLoader = null;
        //
        // [Import(AllowDefault = false)]
        // private IMainWindow m_mainWindow = null;

        [Import(AllowDefault = true)]
        private ResourceLister m_resourceLister = null;

        [Import(AllowDefault = false)]
        private IResourceService m_resourceService = null;

        [Import(AllowDefault = false)]
        private ResourceConverterService m_resourceConverterService = null;

        [Import(AllowDefault = false)]
        private ControlHostService m_controlHostService = null;

        // [Import(AllowDefault = false)]
        // private IGameEngineProxy m_gameEngine;

        private NativeViewControl m_renderSurface;
        private IGame m_game;

        private readonly ControlInfo m_controlInfo;

        private class NativeViewControl : ViewControl
        {

            public NativeViewControl()
            {
                ClientSize = new Size(16, 16);
                // if (!GameEngine.IsInError)
                // {
                //     swapChainId = GameEngine.GetObjectTypeId("SwapChain");
                //     SurfaceId = GameEngine.CreateObject(0, 0, swapChainId, this.Handle, IntPtr.Size);
                //     SizePropId = GameEngine.GetObjectPropertyId(swapChainId, "Size");
                //     GameEngine.SetObjectProperty(swapChainId, 0, SurfaceId, SizePropId, ClientSize);
                //     BkgColorPropId = GameEngine.GetObjectPropertyId(swapChainId, "BkgColor");
                //     GameEngine.SetObjectProperty(swapChainId, 0, SurfaceId, BkgColorPropId, BackColor);
                // }

                m_renderState = new RenderState();
                m_renderState.RenderFlag = GlobalRenderFlags.Solid | GlobalRenderFlags.Textured | GlobalRenderFlags.Lit;
                m_renderState.WireFrameColor = Color.DarkBlue;
                m_renderState.SelectionColor = Color.FromArgb(66, 255, 161);
                BackColor = SystemColors.ControlDark;

                #region Context menu
                GlobalRenderFlags[] flags = new GlobalRenderFlags[]
                {
                    GlobalRenderFlags.Solid,
                    GlobalRenderFlags.WireFrame,
                    GlobalRenderFlags.Textured,
                    GlobalRenderFlags.RenderBackFace,
                    GlobalRenderFlags.Lit
                };
                ContextMenuStrip cntx = new ContextMenuStrip();
                foreach (var flag in flags)
                {
                    ToolStripMenuItem item =
                        new ToolStripMenuItem(flag.ToString());
                    item.Tag = flag;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        ToolStripMenuItem menu = (ToolStripMenuItem)sender;
                        RenderState.RenderFlag = RenderState.RenderFlag ^ (GlobalRenderFlags)menu.Tag;
                        this.Invalidate();
                    };

                    cntx.Items.Add(item);
                }

                cntx.Items.Add(new ToolStripSeparator());
                ToolStripMenuItem views = new ToolStripMenuItem("View");
                cntx.Items.Add(views);
                views.DropDownOpening += delegate
                {
                    foreach (ToolStripMenuItem item in views.DropDownItems)
                    {
                        item.Checked = (ViewType == (ViewTypes)item.Tag);
                    }
                };

                foreach (var val in Enum.GetValues(typeof(ViewTypes)))
                {
                    ViewTypes viewtype = (ViewTypes)val;
                    ToolStripMenuItem item = new ToolStripMenuItem(viewtype.ToString());
                    item.Tag = viewtype;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
                        this.ViewType = (ViewTypes)menuItem.Tag;
                    };

                    views.DropDownItems.Add(item);
                }

                cntx.Opening += delegate
                {
                    GlobalRenderFlags renderflags = RenderState.RenderFlag;
                    foreach (ToolStripItem item in cntx.Items)
                    {
                        if (item is ToolStripSeparator) break;
                        ((ToolStripMenuItem)item).Checked = (renderflags & (GlobalRenderFlags)item.Tag) != 0;
                    }
                };

                ContextMenuStrip = cntx;
                #endregion
            }

            public bool ResetCamera
            {
                get;
                set;
            }

            public IGameEngineProxy GameEngineProxy
            {
                get;
                set;
            }
            public IGame Game
            {
                get;
                set;
            }
            // public ulong SurfaceId
            // {
            //     get;
            //     private set;
            // }

            public RenderState RenderState
            {
                get { return m_renderState; }
            }

            protected override void OnBackColorChanged(EventArgs e)
            {
                base.OnBackColorChanged(e);
                // if (swapChainId != 0)
                // {
                //     GameEngine.SetObjectProperty(swapChainId, 0, SurfaceId, BkgColorPropId, BackColor);
                // }
            }

            protected override void OnSizeChanged(EventArgs e)
            {
                base.OnSizeChanged(e);
                Size sz = ClientSize;
                //if (!GameEngine.IsInError && SurfaceId != 0 && sz.Width > 0 && sz.Height > 0)
                //{
                //    GameEngine.SetObjectProperty(swapChainId, 0, SurfaceId, SizePropId, sz);
                    Camera.Aspect = (float)sz.Width / (float)sz.Height;
                //}
            }
            protected override void Dispose(bool disposing)
            {
                // GameEngine.DestroyObject(0, SurfaceId, swapChainId);
                // SurfaceId = 0;
                if (disposing)
                {
                    m_renderState.Dispose();
                }
                base.Dispose(disposing);
            }

            protected override void OnPaint(PaintEventArgs e)
            {
                if (GameEngine.IsInError)
                {
                    e.Graphics.Clear(BackColor);
                    if (GameEngine.IsInError)
                        e.Graphics.DrawString(GameEngine.CriticalError, Font, Brushes.Red, 1, 1);
                    return;
                }
                Render();
            }

            // render the scene.
            public override void Render()
            {
            }

            /// <summary>
            /// Raises the <see cref="E:System.Windows.Forms.Control.MouseDown"></see> event.
            /// </summary>
            /// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.</param>
            protected override void OnMouseDown(MouseEventArgs e)
            {
                Focus();
                CameraController.MouseDown(this, e);
                base.OnMouseDown(e);
            }

            /// <summary>
            /// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove"></see> event.
            /// </summary>
            /// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.</param>
            protected override void OnMouseMove(MouseEventArgs e)
            {
                CameraController.MouseMove(this, e);
                base.OnMouseMove(e);
            }

            /// <summary>
            /// Raises the <see cref="E:System.Windows.Forms.Control.MouseUp"></see> event.
            /// </summary>
            /// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.</param>
            protected override void OnMouseUp(MouseEventArgs e)
            {
                CameraController.MouseUp(this, e);
                base.OnMouseUp(e);
            }

            private RenderState m_renderState;
            // private readonly uint swapChainId;
            // private readonly uint SizePropId;
            // private readonly uint BkgColorPropId;
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
    <actions/>
    <description></description>
    <keepDependencies>false</keepDependencies>
    <properties>
        <jenkins.model.BuildDiscarderProperty>
            <strategy class="hudson.tasks.LogRotator">
                <daysToKeep>-1</daysToKeep>
                <numToKeep>10</numToKeep>
                <artifactDaysToKeep>-1</artifactDaysToKeep>
                <artifactNumToKeep>-1</artifactNumToKeep>
            </strategy>
        </jenkins.model.BuildDiscarderProperty>
    </properties>
    <scm class="hudson.scm.NullSCM"/>
    <canRoam>true</canRoam>
    <disabled>false</disabled>
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
    <triggers/>
    <concurrentBuild>false</concurrentBuild>
    <customWorkspace>/root/.jenkins/workspace/{{project_slug|lower}}</customWorkspace>
    <builders>
        <hudson.tasks.Shell>
            <command>chmod +x ci/it.sh && ./ci/it.sh</command>
        </hudson.tasks.Shell>
    </builders>
    <publishers>
        <hudson.tasks.BuildTrigger>
            <childProjects>Deploy_{{project_slug}}</childProjects>
            <threshold>
                <name>SUCCESS</name>
                <ordinal>0</ordinal>
                <color>BLUE</color>
                <completeBuild>true</completeBuild>
            </threshold>
        </hudson.tasks.BuildTrigger>
        <hudson.plugins.emailext.ExtendedEmailPublisher plugin="email-ext@2.44">
            <recipientList>$DEFAULT_RECIPIENTS</recipientList>
            <configuredTriggers>
                <hudson.plugins.emailext.plugins.trigger.FailureTrigger>
                    <email>
                        <subject>$PROJECT_DEFAULT_SUBJECT</subject>
                        <body>$PROJECT_DEFAULT_CONTENT</body>
                        <recipientProviders>
                            <hudson.plugins.emailext.plugins.recipients.DevelopersRecipientProvider/>
                        </recipientProviders>
                        <attachmentsPattern></attachmentsPattern>
                        <attachBuildLog>false</attachBuildLog>
                        <compressBuildLog>false</compressBuildLog>
                        <replyTo>$PROJECT_DEFAULT_REPLYTO</replyTo>
                        <contentType>project</contentType>
                    </email>
                </hudson.plugins.emailext.plugins.trigger.FailureTrigger>
            </configuredTriggers>
            <contentType>default</contentType>
            <defaultSubject>$DEFAULT_SUBJECT</defaultSubject>
            <defaultContent>$DEFAULT_CONTENT</defaultContent>
            <attachmentsPattern></attachmentsPattern>
            <presendScript>$DEFAULT_PRESEND_SCRIPT</presendScript>
            <postsendScript>$DEFAULT_POSTSEND_SCRIPT</postsendScript>
            <attachBuildLog>false</attachBuildLog>
            <compressBuildLog>false</compressBuildLog>
            <replyTo>$DEFAULT_REPLYTO</replyTo>
            <saveOutput>false</saveOutput>
            <disabled>false</disabled>
        </hudson.plugins.emailext.ExtendedEmailPublisher>
    </publishers>
    <buildWrappers/>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;

namespace MiniHttp.Server
{
    public class RouteDefinition
    {
        public Regex MatchExpression { get; private set; }
        public RequestHandler Handler { get; private set; }

        public RouteDefinition(Regex matchExpression, RequestHandler handler)
        {
            MatchExpression = matchExpression;
            Handler = handler;
        }

        public bool TryRoute(RequestContext context)
        {
            var match = MatchExpression.Match(context.Url.PathAndQuery);
            if (match.Success)
            {
                if (Handler(context))
                    return true;
            }
            return false;
        }
    }
}


text:
#ifndef XENIA_KERNEL_FS_DEVICES_DISC_IMAGE_FILE_H_
#define XENIA_KERNEL_FS_DEVICES_DISC_IMAGE_FILE_H_

#include "xenia/common.h"
#include "xenia/kernel/objects/xfile.h"

namespace xe {
namespace kernel {
namespace fs {

class DiscImageEntry;

class DiscImageFile : public XFile {
 public:
  DiscImageFile(KernelState* kernel_state, Mode desired_access,
                DiscImageEntry* entry);
  ~DiscImageFile() override;

  const std::string& path() const override;
  const std::string& absolute_path() const override;
  const std::string& name() const override;

  X_STATUS QueryInfo(XFileInfo* out_info) override;
  X_STATUS QueryDirectory(XDirectoryInfo* out_info, size_t length,
                          const char* file_name, bool restart) override;
  X_STATUS QueryVolume(XVolumeInfo* out_info, size_t length) override;
  X_STATUS QueryFileSystemAttributes(XFileSystemAttributeInfo* out_info,
                                     size_t length) override;

 protected:
  X_STATUS ReadSync(void* buffer, size_t buffer_length, size_t byte_offset,
                    size_t* out_bytes_read) override;

 private:
  DiscImageEntry* entry_;
};

}  // namespace fs
}  // namespace kernel
}  // namespace xe

#endif  // XENIA_KERNEL_FS_DEVICES_DISC_IMAGE_FILE_H_


text:
from spacy.en import English
from spacy.attrs import LOWER, LIKE_URL, LIKE_EMAIL

import numpy as np

def tokenize(texts, max_length, skip=-2, attr=LOWER, merge=False, nlp=None,
             **kwargs):
    """ Uses spaCy to quickly tokenize text and return an array
    of indices.

    This method stores a global NLP directory in memory, and takes
    up to a minute to run for the time. Later calls will have the
    tokenizer in memory.

    Parameters
    ----------
    text : list of unicode strings
        These are the input documents. There can be multiple sentences per
        item in the list.
    max_length : int
        This is the maximum number of words per document. If the document is
        shorter then this number it will be padded to this length.
    skip : int, optional
        Short documents will be padded with this variable up until max_length.
    attr : int, from spacy.attrs
        What to transform the token to. Choice must be in spacy.attrs, and =
        common choices are (LOWER, LEMMA)
    merge : int, optional
        Merge noun phrases into a single token. Useful for turning 'New York'
        into a single token.
    nlp : None
        A spaCy NLP object. Useful for not reinstantiating the object multiple
        times.
    kwargs : dict, optional
        Any further argument will be sent to the spaCy tokenizer. For extra
        speed consider setting tag=False, parse=False, entity=False, or
        n_threads=8.

    Returns
    -------
    arr : 2D array of ints
        Has shape (len(texts), max_length). Each value represents
        the word index.
    vocab : dict
        Keys are the word index, and values are the string. The pad index gets
        mapped to None

    >>> sents = [u"Do you recall a class action lawsuit", u"hello zombo.com"]
    >>> arr, vocab = tokenize(sents, 10, merge=True)
    >>> arr.shape[0]
    2
    >>> arr.shape[1]
    10
    >>> w2i = {w: i for i, w in vocab.iteritems()}
    >>> arr[0, 0] == w2i[u'do']  # First word and its index should match
    True
    >>> arr[0, 1] == w2i[u'you']
    True
    >>> arr[0, -1]  # last word in 0th document is a pad word
    -2
    >>> arr[0, 4] == w2i[u'class action lawsuit']  # noun phrase is tokenized
    True
    >>> arr[1, 1]  # The URL token is thrown out
    -2
    """
    if nlp is None:
        nlp = English()
    data = np.zeros((len(texts), max_length), dtype='int32')
    data[:] = skip
    bad_deps = ('amod', 'compound')
    for row, doc in enumerate(nlp.pipe(texts, **kwargs)):
        if merge:
            # from the spaCy blog, an example on how to merge
            # noun phrases into single tokens
            for phrase in doc.noun_chunks:
                # Only keep adjectives and nouns, e.g. "good ideas"
                while len(phrase) > 1 and phrase[0].dep_ not in bad_deps:
                    phrase = phrase[1:]
                if len(phrase) > 1:
                    # Merge the tokens, e.g. good_ideas
                    phrase.merge(phrase.root.tag_, phrase.text,
                                 phrase.root.ent_type_)
                # Iterate over named entities
                for ent in doc.ents:
                    if len(ent) > 1:
                        # Merge them into single tokens
                        ent.merge(ent.root.tag_, ent.text, ent.label_)
        dat = doc.to_array([attr, LIKE_EMAIL, LIKE_URL]).astype('int32')
        if len(dat) > 0:
            dat = dat.astype('int32')
            msg = "Negative indices reserved for special tokens"
            assert dat.min() >= 0, msg
            # Replace email and URL tokens
            idx = (dat[:, 1] > 0) | (dat[:, 2] > 0)
            dat[idx] = skip
            length = min(len(dat), max_length)
            data[row, :length] = dat[:length, 0].ravel()
    uniques = np.unique(data)
    vocab = {v: nlp.vocab[v].lower_ for v in uniques if v != skip}
    vocab[skip] = '<SKIP>'
    return data, vocab

if __name__ == "__main__":
    import doctest
    doctest.testmod()


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Formal extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('miscellaneous');
        $this->load->helper('security');
        $this->load->model('formal_model');
        validate_login($this->session->userdata('logged_in'));
        recalculate_uploaded_documents();
    }

    public function index() {
        $data['title'] = 'Aplicativo de Cargue de Documentos - Educacion Formal';
        $data['documents_formal_user'] = $this->formal_model->get_documents_formal_user($this->session->userdata("INSCRIPCION_PIN"));
        $data['content'] = 'formal/add';

        $data['modalidades'] = get_dropdown($this->formal_model->get_modalidades(), 'MODALIDAD_ID', 'MODALIDAD_NOMBRE');

        $data['template_config'] = array(
            'signin' => 0,
            'menu' => 1,
            'bootstrap-theme' => 0,
            'jquery' => 1,
            'validate' => 1,
            'bootstrapjs' => 1
        );

        $this->load->view('template/template', $data);
    }

    public function insert() {
        date_default_timezone_set('America/Bogota');
        //echo '
' . print_r($this->input->post()) . '
';

        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('
', '
');

        $this->form_validation->set_rules('UNIVERSIDAD', 'UNIVERSIDAD', 'required|trim');
        $this->form_validation->set_rules('TITULO', 'TITULO', 'required|min_length[2]|trim');
        $this->form_validation->set_rules('FECHA_TERMINACION', 'Fecha Terminación', 'required|trim');
        $this->form_validation->set_rules('FECHA_GRADO', 'Fecha Grado', 'required|trim');

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

            $data['title'] = 'Aplicativo de Cargue de Documentos - Educacion Formal';
            $data['documents_particles_user'] = $this->formal_model->get_documents_particles_user($this->session->userdata("INSCRIPCION_PIN"));
            $data['content'] = 'formal/add';

            $data['modalidades'] = get_dropdown($this->formal_model->get_modalidades(), 'MODALIDAD_ID', 'MODALIDAD_NOMBRE');

            $data['template_config'] = array(
                'signin' => 0,
                'menu' => 1,
                'bootstrap-theme' => 0,
                'jquery' => 1,
                'validate' => 1,
                'bootstrapjs' => 1
            );

            $this->load->view('template/template', $data);
        } else {

            $TIPO_DOCUMENTO_ID = '2';
            $FECHA = date("Y_m_d_H_i_s");

            $config['upload_path'] = 'images/documentos';
            $config['allowed_types'] = 'pdf';
            $config['encrypt_name'] = FALSE;
            $config['max_size'] = '2000';
            $FINE_NAME = $this->session->userdata("CONVOCATORIA_ID") . '_' . $this->session->userdata("INSCRIPCION_PIN") . '_' . $TIPO_DOCUMENTO_ID . '_' . $FECHA;
            $config['file_name'] = $FINE_NAME;
            $this->load->library('upload', $config);

            $field_name = "userfile";

            if (!$this->upload->do_upload($field_name)) {
                $error = $this->upload->display_errors();
                $this->session->set_flashdata(array('message' => strip_tags($error), 'message_type' => 'danger'));
                redirect('formal', 'refresh');
            } else {

                $upload_data = $this->upload->data();
                $pdf_name = $upload_data['file_name'];

                $data = array(
                    'INSCRIPCION_PIN' => $this->session->userdata("INSCRIPCION_PIN"),
                    'TIPO_DOCUMENTO_ID' => $TIPO_DOCUMENTO_ID,
                    'DOCUMENTO_NOMBRE' => $FINE_NAME,
                    'DOCUMENTO_FECHA' => $FECHA,
                    'DOCUMENTO_ESTADO' => '1',
                    'MODALIDAD_ID' => addslashes($this->input->post('MODALIDAD_ID', TRUE)),
                    'SEMESTRE' => addslashes($this->input->post('SEMESTRE', TRUE)),
                    'GRADUADO' => addslashes($this->input->post('GRADUADO', TRUE)),
                    'EXTRANGERO' => addslashes($this->input->post('EXTRANGERO', TRUE)),
                    'UNIVERSIDAD' => addslashes($this->input->post('UNIVERSIDAD', TRUE)),
                    'TITULO' => addslashes($this->input->post('TITULO', TRUE)),
                    'FECHA_TERMINACION' => addslashes($this->input->post('FECHA_TERMINACION', TRUE)),
                    'FECHA_GRADO' => addslashes($this->input->post('FECHA_GRADO', TRUE)),
                );
                $insert = $this->formal_model->insert_document($data);
                if ($insert) {
                    $this->session->set_flashdata(array('message' => 'Documento cargado con exito.', 'message_type' => 'info'));
                    redirect('formal', 'refresh');
                } else {
                    $this->session->set_flashdata(array('message' => 'Error al insertar el documento', 'message_type' => 'error'));
                    redirect('formal', 'refresh');
                }
            }
        }
    }

    public function view_document($DOCUMENTO_ID) {
        $DOCUMENTO_ID = deencrypt_id($DOCUMENTO_ID);
        $document = $this->formal_model->get_document_user($this->session->userdata("INSCRIPCION_PIN"), $DOCUMENTO_ID);
        $file = $document[0]->DOCUMENTO_NOMBRE . '.pdf';
        header('Content-type: application/pdf');
        header('Content-Disposition: inline; filename="' . $document[0]->INSCRIPCION_PIN . '_' . $document[0]->DOCUMENTO_FOLIO . '.pdf"');
        @readfile('images/documentos/' . $file);
    }

    public function delete_document($DOCUMENTO_ID) {
        $DOCUMENTO_ID = deencrypt_id($DOCUMENTO_ID);
        $this->formal_model->delete_document_user($this->session->userdata("INSCRIPCION_PIN"), $DOCUMENTO_ID);
        $this->session->set_flashdata(array('message' => 'Documento Eliminado con Exito', 'message_type' => 'info'));
        redirect('formal', 'refresh');
    }

}


text:
<bill session="110" type="h" number="382" updated="2009-01-08T17:31:41-05:00">
	<status><introduced date="1168405200" datetime="2007-01-10"/></status>

	<introduced date="1168405200" datetime="2007-01-10"/>
	<titles>
		<title type="short" as="introduced">Municipal Deposit Insurance Protection Act of 2007</title>
		<title type="official" as="introduced">To amend the Federal Deposit Insurance Act with respect to municipal deposits.</title>
	</titles>
	<sponsor id="400150"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1168405200" datetime="2007-01-10"><text>Referred to the House Committee on Financial Services.</text></action>
		<action date="1176264000" datetime="2007-04-11"><text>Referred to the Subcommittee on Financial Institutions and Consumer Credit.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	1/10/2007--Introduced.<br/>Municipal Deposit Insurance Protection Act of 2007 - Amends the Federal Deposit Insurance Act to set $2 million as the maximum amount of insurance for in-state municipal depositor accounts held by an insured depository institution.
	</summary>
</bill>


text:
package de.saxsys.mvvmfx.utils.mapping.accessorfunctions;

import java.util.function.BiConsumer;

/**
 * A functional interface to define a setter method of type {@link Double}.
 *
 * @param <M>
 *            the generic type of the model.
 */
@FunctionalInterface
public interface DoubleSetter<M> extends BiConsumer<M, Double> {

	/**
	 * @param model
	 *            the model instance.
	 * @param value
	 *            the new value to be set.
	 */
	@Override
	void accept(M model, Double value);
}


text:
package org.hisp.dhis.cache;

import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Provides cache builder to build instances.
 *
 * @author Ameen Mohamed
 *
 */
public class DefaultCacheProvider implements CacheProvider
{
    private DhisConfigurationProvider configurationProvider;

    private RedisTemplate<String, ?> redisTemplate;

    /**
     * Creates a new {@link CacheBuilder} that can be used to build a cache that
     * stores the valueType specified.
     *
     *
     * @param valueType The class type of values to be stored in cache.
     * @return A cache builder instance for the specified value type. Returns a
     *         {@link CacheBuilder}
     */
    public <V> CacheBuilder<V> newCacheBuilder( Class<V> valueType )
    {
        return new CacheBuilder<V>( redisTemplate, configurationProvider );
    }

    @Autowired
    public void setConfigurationProvider( DhisConfigurationProvider configurationProvider )
    {
        this.configurationProvider = configurationProvider;
    }

    @Autowired( required = false )
    public void setRedisTemplate( RedisTemplate<String, ?> redisTemplate )
    {
        this.redisTemplate = redisTemplate;
    }

}


text:
from http.server import *
import socket
import sys
import os

HOST = 'localhost'
port = 4567

Handler = SimpleHTTPRequestHandler

def run(server_class=HTTPServer, handler_class=Handler):
    server_address = (HOST, port)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

def main():
  run()
  print(len(sys.argv))
  print(sys.argv[0])
  print(__file__)
  print(os.path.dirname(os.path.realpath(__file__)))

main()


text:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Kemel.Orm.NQuery.Storage.Column;
using Kemel.Orm.NQuery.Storage.Value;
using Kemel.Orm.NQuery.Storage.Constraint;

namespace Kemel.Orm.NQuery.Storage.Constraint
{

    public class ConditionExpression
    {

        private StoredColumn objColumn = null;
        public StoredColumn Column
        {
            get { return this.objColumn; }
            set { this.objColumn = value; }
        }

        private ComparisonOperator objComparison = ComparisonOperator.Equal;
        public ComparisonOperator Comparison
        {
            get { return this.objComparison; }
            set { this.objComparison = value; }
        }

        private StoredValue objValue = null;
        public StoredValue Value
        {
            get { return this.objValue; }
            set { this.objValue = value; }
        }

    }

}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S13.2.1_A5_T2;
* @section: 13.2.1;
* @assertion: Closures are admitted;
* @description: Returning a function that approximates the derivative of f
* using an interval of dx, which should be appropriately small;
*/

// Return a function that approximates the derivative of f
// using an interval of dx, which should be appropriately small.
function derivative(f, dx) {
    return function(x) {
      return (f(x + dx) - f(x)) / dx;
    };
}

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (Math.abs(derivative(Math.sin, 0.0001)(0) - derivative(Math.sin, 0.0001)(2*Math.PI)) >= 1/65536.0) {
	$ERROR('#1: Math.abs(derivative(Math.sin, 0.0001)(0) - derivative(Math.sin, 0.0001)(2*Math.PI)) <= 1/65536.0');
}
//
//////////////////////////////////////////////////////////////////////////////


text:
pub mod parse;
pub mod ast;
pub mod ptr;

pub mod syntax {
    pub use parse;
    pub use ast;
}

pub mod visit;
pub mod visitor_impl;


text:
This repository contains the 'rtcomm' node.js Module. This module extends the real-time communications services of the WebSphere Liberty profile. Currently, the service extensions represented in
this library include :

1. RtcConnector: Provides the ability to monitor all events related to the rtcomm protocol including session and presence events.
2. 3PCC (Third party call control):  Providers the ability to initiate a 3rd party calls.

This module relies on both a message broker for sending (publishing) and receiving messages and the WebSphere Liberty rtcomm-1.0 feature to deliver these services. This node.js module is simply a client to these services. It can subscribe and receive RtcConnector related events and it can initiate a 3rd party call between two endpoints
that are both registered with the WebSphere Liberty server.

##Install
```
npm install rtcomm

Note: specific releases of this repository can be installed via the following command:
npm install rtcomm@<version>

See the wiki page for what versions have been tested with specific versions of the
WebSphere Liberty profile.
```

This module relies on the following:

1. An MQTT broker for publishing and receiving messages.
2. An Rtcomm server that supports Rtcomm 3rd party calling and/or event monitoring.

**MQTT Broker examples:**

There are many MQTT brokers on the market, both publicaly accessible and

Because Liberty does not currently include native support for an MQTT message broker, this feature requires an external broker. Many options of MQTT message brokers exist in the market today. Here is a list of some of the more commonly used MQTT message brokers:

[IBM MessageSight](http://www-03.ibm.com/software/products/en/messagesight)
[WebSphere MQ Telemetry](http://www-03.ibm.com/software/products/en/wmq-telemetry)
[Mosquitto](http://mosquitto.org/) (open source MQTT broker)

A quick options for demonstrations and testing this module is tcp://broker.mqttdashboard.com:1883.
The MQTT Dashboard is an open, publicly accessible MQTT broker.

**Rtcomm server example:**

The WebSphere Liberty profile beta extended package which can be downloaded from:
https://developer.ibm.com/wasdev/downloads/liberty-profile-beta/

##Documentation

There are three parts to the documentation of this module:

1. The Rtcomm services protocol that is implemented by this module: [rtcomm.service.proto.spec.md](/rtcomm.service.proto.spec.md)
2. The API specification for this module: [rtcomm.service.api.spec.md](/rtcomm.service.api.spec.md)
3. The Presence events are defined on: [rtcomm.signaling.proto.md](https://github.com/WASdev/lib.rtcomm.clientjs/blob/master/rtcomm.signaling.proto.spec.md)

##Testing

This module relies on Mocha for testing and utilizes the Mosca MQTT broker. Instructions for running the test:

1. From the root rtcomm-node director type: npm install
2. Run mocha: ./node_modules/.bin/mocha


text:
package apple.authenticationservices.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

/**
 * [@enum] ASCredentialIdentityStoreErrorCode
 * [@constant] ASCredentialIdentityStoreErrorCodeInternalError The operation failed due to an internal error.
 * [@constant] ASCredentialIdentityStoreErrorCodeStoreDisabled The operation failed because the credential identity
 * store is disabled.
 * [@constant] ASCredentialIdentityStoreErrorCodeStoreBusy The operation failed because the credential identity store is
 * busy. Attempt the operation again at a later time.
 */
@Generated
public final class ASCredentialIdentityStoreErrorCode {
    @Generated
    private ASCredentialIdentityStoreErrorCode() {
    }

    @Generated @NInt public static final long InternalError = 0x0000000000000000L;
    @Generated @NInt public static final long StoreDisabled = 0x0000000000000001L;
    @Generated @NInt public static final long StoreBusy = 0x0000000000000002L;
}


text:
package org.freeeed.mail;

import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;

/**
 * Not used right now
 * This will work for MBOX, but one still needs to do one's own parsing
 * of TO, CC, BCC fields, so we will do it later
 * @author mark
 */
public class Mstor {

    public static void main(String[] args) {
        Session session = Session.getDefaultInstance(new Properties());
        try {
            Store store = session.getStore(new URLName("mstor:test-data/readpst/Sent"));
            store.connect();
            // read messages from Inbox..
            Folder inbox = store.getDefaultFolder();
            inbox.open(Folder.READ_ONLY);
            Folder [] folders = inbox.list();
            System.out.println("folder count: " + folders.length);
            Message[] messages = inbox.getMessages();
            System.out.println("message count: " + messages.length);
            try {
                for (int i = 0, n = messages.length; i < n; i++) {
                    System.out.println(i + ": " + messages[i].getFrom()[0]
                            + "\t" + messages[i].getSubject());
                    messages[i].writeTo(System.out);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace(System.out);
            }
            inbox.close(false); // expunges all deleted messages if this flag is true
            store.close();
        } catch (MessagingException me) {
            me.printStackTrace(System.out);
        }
    }
}


text:
require "rails-assets-growl/version"

require "rails-assets-jquery"

module RailsAssetsGrowl

  def self.gem_path
    Pathname(File.realpath(__FILE__)).join('../..')
  end

  def self.gem_spec
    Gem::Specification::load(
      gem_path.join("rails-assets-growl.gemspec").to_s
    )
  end

  def self.load_paths
    gem_path.join('app/assets').each_child.to_a
  end

  def self.dependencies
    [
      RailsAssetsJquery
    ]
  end

  if defined?(Rails)
    class Engine < ::Rails::Engine
      # Rails -> use app/assets directory.
    end
  end

end

class RailsAssets
  @components ||= []

  class << self
    attr_accessor :components

    def load_paths
      components.flat_map(&:load_paths)
    end
  end
end

RailsAssets.components << RailsAssetsGrowl


text:
using System.Diagnostics;
using System.Text.Json.Serialization;

namespace HueApi.Models
{
  [DebuggerDisplay("{Name} {Archetype}")]
  public class Metadata
  {
    [JsonPropertyName("name")]
    public string Name { get; set; } = default!;

    [JsonPropertyName("archetype")]
    public string? Archetype { get; set; }

    [JsonPropertyName("image")]
    public ResourceIdentifier? Image { get; set; }
  }
}


text:
@class EvolutionManager;

@protocol EvolutionDelegate <NSObject>

@required
- (void)evolutionManager:(EvolutionManager *)evolutionManager didCompetedGeneration:(NSUInteger)generation fittestOrganism:(Organism *)fittestOrganism offspring:(NSArray *)offspring nextGeneration:(NSArray *)nextGeneration;

@end

@interface EvolutionManager : NSObject

@property (nonatomic, weak) id <EvolutionDelegate> delegate;

@property (nonatomic, strong) Population *population;

@property (nonatomic) NSUInteger currentGeneration;

@property (nonatomic) enum CrossoverMethod crossoverMethod;
@property (nonatomic) NSUInteger tournamentSize;
@property (nonatomic) CGFloat elitismPercentage;
@property (nonatomic) CGFloat mutationRate;

- (instancetype)initWithPopulation:(Population *)population;

- (void)proceedWithSelectionAndBreeding;

@end