text:
<?php

namespace Siwapp\InvoiceBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

use Siwapp\CoreBundle\Form\AbstractInvoiceType;
use Siwapp\InvoiceBundle\Entity\Item;
use Siwapp\InvoiceBundle\Form\ItemType;

class InvoiceType extends AbstractInvoiceType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('draft', 'hidden')
            ->add('closed', 'hidden')
            ->add('sent_by_email', 'hidden')
            ->add('number')
            ->add('recurring_invoice_id', 'hidden')
            ->add('issue_date', 'date', array('widget' => 'single_text'))
            ->add('due_date', 'date', array('widget' => 'single_text'))
        ;

        $builder->add('items', 'collection', array(
            'type' => new ItemType(),
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
        ));
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Siwapp\InvoiceBundle\Entity\Invoice',
        );
    }

    public function getName()
    {
        return 'siwapp_invoicebundle_invoicetype';
    }
}


text:
In this lab you will provision two GCE instances running Ubuntu 16.04. These instances will be used to provision a two node Kubernetes cluster.

## Provision 2 GCE instances

### Provision Ubuntu using the gcloud CLI

#### node0

```
gcloud compute instances create node0 \
 --image-project ubuntu-os-cloud \
 --image ubuntu-1510-wily-v20160405 \
 --boot-disk-size 200GB \
 --machine-type n1-standard-1 \
 --can-ip-forward
```

#### node1

```
gcloud compute instances create node1 \
 --image-project ubuntu-os-cloud \
 --image ubuntu-1510-wily-v20160405 \
 --boot-disk-size 200GB \
 --machine-type n1-standard-1 \
 --can-ip-forward
```

#### Verify

```
gcloud compute instances list
```

redpajama_set_name: RedPajamaGithub


text:
<?php namespace App\Http\Controllers\Subasta;
use App\Subasta;
use App\Http\Controllers\System\SystemController;
use App\Puja;
use App\User;
use QrCode;
use App\Http\Controllers\Controller;

class View extends Controller {

	public function __construct()
	{
		$this->middleware('auth', [ 'except' => [ 'index', 'show' ] ]);
	}

	public function show($id)
	{

		$subasta = Subasta::find($id);
		SystemController::checkSubasta($subasta->id);
		$pujas = Puja::select('users.name','pujas.cantidad','pujas.fecha','pujas.id_usuario')

		->where('pujas.id_subasta',$id)->join('users','pujas.id_usuario','=','users.id')
		->orderBy('pujas.cantidad', 'DESC')
		->get();
		$user = User::find($subasta->id_user_vendedor);

		return view('subasta.view', compact('subasta','user','pujas','pujas8'));
	}

}


text:
Git Basics

Local Repository

Life without Git

$ ls -l
img/
css/
js/
index.html

$ git status
fatal: Not a git repository (or any of the parent directories): .git

Local Repository

Create Local Repository

$ git init .

$ ls -la
.git  <=======  Git Local Repo
img/
css/
js/
index.html

Local Repository

Untracked

$ git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#	css/
#	img/
#	index.html
#	js/
nothing added to commit but untracked files present (use "git add" to track)

Local Repository

Track and Stage

$ git add .  <====== "." everything in current dir

$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#	new file:   css/sample
#	new file:   img/sample
#	new file:   index.html
#	new file:   js/sample
#

Local Repository

Commit!!

$ git commit -m "My First Commit"

$ git status
# On branch master
nothing to commit, working directory clean

Local Repository

Change Code

$ edit index.html  <============== CHANGE FILE
$ edit about.html  <============== NEW FILE

$ git status
# Changes not staged for commit:
#	modified:   index.html
#
# Untracked files:
#	about.html
no changes added to commit (use "git add" and/or "git commit -a")

index.html: Tracked ... NOT Staged

about.html: NOT Tracked ... NOT Staged

Local Repository

Stage and Track

$ git add index.html  < ============== Stage

$ git add about.html  < ============== Track and Stage

$ git status
# Changes to be committed:
#	new file:   about.html
#	modified:   index.html

Not Commited Yet!!

Local Repository

My Second Commit

$ git commit -m "Added About page"

$ git status
# On branch master
nothing to commit, working directory clean

Local Repository

When to Stage and When to Commit?

Stage when file reach working state

Commit when project reach working state

Recap with Graphs

Fancy Graphs

Time Machine

... or what if I commit my code!

git log

$ git log

commit e78205f5b61fa5ef8f94af7bae5a5783bb8a0625
Author: Rayed Alrashed <rayed@example.com>
Date:   Tue Mar 12 23:28:54 2013 +0000

Added About page

commit 45b30fc4324e116db551845e588c9086aa26a625
Author: Rayed Alrashed <rayed@example.com>
Date:   Wed Mar 27 06:28:02 2013 +0000

My first commit

What?
When?
Who?
ID

Travel to the Past

$ git checkout 45b30fc4324e116db551845e588c9086aa26a625

$ ls -l
.git
img/
css/
js/
index.html  > ==== Our OLD index
    > ==== about.html gone!

Warning: You can't change the past ...

 ... may be in a parallel universe
 (AKA branch)

Return to the Present

$ git checkout master

$ ls -l
.git
img/
css/
js/
index.html  > ==== Latest index
about.html  > ==== about.html is Back

What Changed

Show code changes between 2 commits

$ git diff 45b30fc4324e116db551845e588c9086aa26a625

--- a/about.html
+++ b/about.html
@@ -1 +1 @@
-<h1>About Us</h1>
+<h1>About the Company</h1>


text:
package org.wso2.developerstudio.eclipse.capp.core.artifacts.manager;

public interface IServerRole {
	public String getServerRoleName();
	public String getServerRoleDescription();
}


text:
/* ------------------------------------------------------------------------- */
/*
 *  example_smtp.cpp
 *
 *  Copyright (c) 2004 - 2008, clown. All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *    - Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    - Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    - No names of its contributors may be used to endorse or promote
 *      products derived from this software without specific prior written
 *      permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 *  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  Last-modified: Fri 14 Nov 2008 02:55:00 JST
 */
/* ------------------------------------------------------------------------- */
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include "clx/smtp.h"
#include "clx/date_time.h"

/* ------------------------------------------------------------------------- */
/*
 *  sendmail
 *
 *  From, To, Cc, Bcc, Subject, '¨'æ'Ñ–{•¶'ð"o˜^'µ'Ä'¨'«Cƒ[ƒ‹'—MŽž
 *  'ɐ®Œ`'µ'Ä'—M'·'邽'߂̃Nƒ‰ƒXD
 */
/* ------------------------------------------------------------------------- */
enum { mailto = 0, mailcc, mailbcc };
class sendmail {
public:
	typedef char char_type;
	typedef std::basic_string<char_type> string_type;
	typedef std::list<string_type> mailing_list;

	sendmail() : to_(), cc_(), bcc_(),
		from_(), subject_(), message_() {}

	virtual ~sendmail() {}

	sendmail& add(const string_type& addr, int type = mailto) {
		switch (type) {
		case mailto:
			to_.push_back(addr);
			break;
		case mailcc:
			cc_.push_back(addr);
			break;
		case mailbcc:
			bcc_.push_back(addr);
			break;
		default:
			break;
		}

		return *this;
	}

	sendmail& from(const string_type& addr) {
		from_ = addr;
		return *this;
	}

	sendmail& subject(const string_type& s) {
		subject_ = s;
		return *this;
	}

	sendmail& message(const string_type& s) {
		message_ = s;
		return *this;
	}

	template <class OutputStream>
	void operator()(OutputStream& sout) {
		std::basic_stringstream<char_type> ss;
		clx::date_time now;
		ss << "Date: " << now.to_string<char>("%a, %d %b %Y %H:%M:%S +0900") << "\r\n";
		ss << "From: " << from_ << "\r\n";

		if (!to_.empty()) {
			ss << "To: ";
			this->xmake(ss, to_);
		}

		if (!cc_.empty()) {
			ss << "Cc: ";
			this->xmake(ss, cc_);
		}

		if (!bcc_.empty()) {
			ss << "Bcc: ";
			this->xmake(ss, bcc_);
		}

		ss << "Subject: " << subject_ << "\r\n";
		ss << "\r\n";
		ss << message_ << "\r\n";
		ss << ".\r\n";

		sout << ss.str();
	}

private:
	mailing_list to_;
	mailing_list cc_;
	mailing_list bcc_;

	string_type from_;
	string_type subject_;
	string_type message_;

	template <class OutputStream, class MailingList>
	void xmake(OutputStream& sout, const MailingList& lst) {
		if (lst.size() == 1) sout << lst.front() << "\r\n";
		else {
			for (typename MailingList::const_iterator pos = lst.begin(); pos != lst.end(); ++pos) {
				sout << *pos << ", ";
			}
			sout << "\r\n";
		}
	}
};

/* ------------------------------------------------------------------------- */
/*
 *  main
 *
 *  Subject 'Æ–{•¶'ÍŒˆ'ß'¤'¿DCc 'Í From 'ÉŽw'肳'ꂽƒAƒhƒŒƒX'ðŽw'è'·'éD
 */
/* ------------------------------------------------------------------------- */
int main(int argc, char* argv[]) {
	if (argc < 6) {
		std::cerr << "usage " << argv[0] << " host id pass from to" << std::endl;
		std::exit(-1);
	}

	std::string from(argv[4]);
	std::string to(argv[5]);

	sendmail f;

	f.from(from);
	f.add(to, mailto);
	f.add(from, mailcc);
	f.subject(std::string("SMTP test mail"));
	f.message(std::string("This is a test mail for clx::smtp class."));

	try {
		clx::smtp session(argv[1], 25);
		session.login(argv[2], argv[3]);

		std::list<std::string> lst;
		lst.push_back(to);		// To
		lst.push_back(from);	// Cc
		session.mail(from, lst, f);
		session.finish();
	}
	catch (clx::smtp_error& e) {
		std::cerr << e.code() << ": " << e.what() << std::endl;
		std::exit(-1);
	}
	catch (clx::socket_error& e) {
		std::cerr << e.what() << std::endl;
		std::exit(-1);
	}
	catch (std::runtime_error& e) {
		std::cerr << e.what() << std::endl;
		std::exit(-1);
	}

	return 0;
}


text:
<?php

namespace InventarioBundle\Controller;

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

class SecurityController extends Controller
{
    public function loginAction()
    {
        $authenticationUtils = $this->get('security.authentication_utils');
        //Maneja los errores en el sistema de autentificacion
        $error = $authenticationUtils->getLastAuthenticationError();

        $lastUsername = $authenticationUtils->getLastUsername();

        //$lastActivo = $authenticationUtils->getLastEstaActivo();

        return $this->render('InventarioBundle:Security:login.html.twig', array('last_username' =>$lastUsername,
            'error'=> $error ));

    }

    public function loginCheckAction()
    {

    }
}


text:
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Security;

namespace SolarWinds.InformationService.Contract2
{
    [DataContract(Namespace = "http://schema.solarwinds.com/2007/08/IS")]
    public class UsernameCredentials : ServiceCredentials
    {
        private readonly string _username;
        private readonly string _password;

        public UsernameCredentials(string username, string password)
        {
            _username = username;
            _password = password;
        }

        public override CredentialType CredentialType
        {
            get { return CredentialType.Username; }
        }

        public override void ApplyTo(ChannelFactory channelFactory)
        {
            channelFactory.Endpoint.Address = new EndpointAddress(channelFactory.Endpoint.Address.Uri);

            channelFactory.Credentials.UserName.UserName = _username;
            channelFactory.Credentials.UserName.Password = _password;
            channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;

            channelFactory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new AllTrustingCertificateValidator();

        }
    }
}


text:
import * as toolkitHelper from 'helpers/toolkit';

export class RunningBalance {
  willInvoke() {
    return this.initializeRunningBalances();
  }

  shouldInvoke() {
    const applicationController = toolkitHelper.controllerLookup('application');
    return applicationController.get('selectedAccountId') !== null;
  }

  cleanup() {
    $('.ynab-grid-cell-toolkit-running-balance').remove();
  }

  insertHeader() {
    if ($('.ynab-grid-header .ynab-grid-cell-toolkit-running-balance').length) return;

    var $headerRow = $('.ynab-grid-header');
    var runningBalanceHeader = $('.ynab-grid-cell-inflow', $headerRow).clone();
    runningBalanceHeader.removeClass('ynab-grid-cell-inflow');
    runningBalanceHeader.addClass('ynab-grid-cell-toolkit-running-balance');
    runningBalanceHeader.text('RUNNING BALANCE').css('font-weight', 'normal');
    runningBalanceHeader.insertAfter($('.ynab-grid-cell-inflow', $headerRow));
    runningBalanceHeader.click((event) => {
      event.preventDefault();
      event.stopPropagation();
      $('.ynab-grid-cell-date', $headerRow).click();
    });

    if ($('.ynab-grid-body .ynab-grid-body-row-top .ynab-grid-cell-toolkit-running-balance').length) return;
    var $topRow = $('.ynab-grid-body-row-top');
    var topRowRunningBalance = $('.ynab-grid-cell-inflow', $topRow).clone();
    topRowRunningBalance.removeClass('ynab-grid-cell-inflow');
    topRowRunningBalance.addClass('ynab-grid-cell-toolkit-running-balance');
    topRowRunningBalance.insertAfter($('.ynab-grid-cell-inflow', $topRow));
  }

  handleSingleRenderColumn($appendToRows) {
    $appendToRows.each((index, row) => {
      if ($('.ynab-grid-cell-toolkit-running-balance', row).length === 0) {
        $('
')
          .insertAfter($('.ynab-grid-cell-inflow', row));
      }
    });
  }

  willInsertColumn() {
    const isSub = this.get('_debugContainerKey') === 'component:register/grid-sub';
    const isRow = this.get('_debugContainerKey') === 'component:register/grid-row';
    const isScheduled = this.get('_debugContainerKey') === 'component:register/grid-scheduled';
    const isRunningBalance = isSub || isRow || isScheduled;

    if (isRunningBalance) {
      const applicationController = toolkitHelper.controllerLookup('application');
      const selectedAccountId = applicationController.get('selectedAccountId');
      if (!selectedAccountId) { return; }

      const $currentRow = $(this.element);
      const currentRowRunningBalance = $('.ynab-grid-cell-inflow', $currentRow).clone();
      currentRowRunningBalance.removeClass('ynab-grid-cell-inflow');
      currentRowRunningBalance.addClass('ynab-grid-cell-toolkit-running-balance');

      const transaction = this.get('content');

      let runningBalance = transaction.__ynabToolKitRunningBalance;
      if (typeof runningBalance === 'undefined') {
        calculateRunningBalance(selectedAccountId);
        runningBalance = transaction.__ynabToolKitRunningBalance;
      }

      const currencySpan = $('.user-data', currentRowRunningBalance);
      if (runningBalance < 0) {
        currencySpan.addClass('user-data currency negative');
      } else if (runningBalance > 0) {
        currencySpan.addClass('user-data currency positive');
      } else {
        currencySpan.addClass('user-data currency zero');
      }

      if (transaction.get('parentEntityId') !== null) {
        currencySpan.text('');
      } else {
        currencySpan.text(ynabToolKit.shared.formatCurrency(runningBalance));
      }

      currentRowRunningBalance.insertAfter($('.ynab-grid-cell-inflow', $currentRow));
    } else {
      if ($('.ynab-grid-cell-toolkit-running-balance', this.element).length === 0) {
        $('
')
          .insertAfter($('.ynab-grid-cell-inflow', this.element));
      }
    }
  }

  initializeRunningBalances() {
    return ynab.YNABSharedLib.defaultInstance.entityManager.accountsCollection.forEach((account) => {
      return ynab.YNABSharedLib.defaultInstance.getBudgetViewModel_AccountTransactionsViewModel(account.entityId).
        then((accountViewModel) => {
          calculateRunningBalance(account.entityId);

          // can you believe it? YNAB has this really interestingly name field
          // on visibleTransactionDisplayItems that sounds exactly like what I need
          // if something changes in that list, you tell me about it, and I'll update
          // the running balance for the account make sure our users always see the fancy
          accountViewModel.get('visibleTransactionDisplayItems')
            .addObserver('anyItemChangedCounter', function () {
              calculateRunningBalance(account.entityId);
            });
        });
    });
  }
}

// Using ._result here bcause we can guarantee that we've already invoked the
// getBudgetViewModel_AccountTransactionsViewModel() function when we initialized
function calculateRunningBalance(accountId) {
  const accountsController = toolkitHelper.controllerLookup('accounts');
  const accountViewModel = ynab.YNABSharedLib.defaultInstance.
    getBudgetViewModel_AccountTransactionsViewModel(accountId)._result;

  const transactions = accountViewModel.get('visibleTransactionDisplayItems');
  const sorted = transactions.slice().sort((a, b) => {
    var propA = a.get('date');
    var propB = b.get('date');

    if (propA instanceof ynab.utilities.DateWithoutTime) propA = propA.getUTCTime();
    if (propB instanceof ynab.utilities.DateWithoutTime) propB = propB.getUTCTime();

    var res = Ember.compare(propA, propB);

    if (res === 0) {
      res = Ember.compare(a.getAmount(), b.getAmount());
      if (accountsController.get('sortAscending')) {
        return res;
      }

      return -res;
    }

    return res;
  });

  let runningBalance = 0;
  sorted.forEach((transaction) => {
    if (transaction.get('parentEntityId') !== null) {
      transaction.__ynabToolKitRunningBalance = runningBalance;
      return;
    }

    if (transaction.get('inflow')) {
      runningBalance += transaction.get('inflow');
    } else if (transaction.get('outflow')) {
      runningBalance -= transaction.get('outflow');
    }

    transaction.__ynabToolKitRunningBalance = runningBalance;
  });
}


text:
package org.apache.flink.runtime.executiongraph.failover.flip1.partitionrelease;

import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.runtime.scheduler.strategy.SchedulingExecutionVertex;
import org.apache.flink.runtime.scheduler.strategy.SchedulingPipelinedRegion;
import org.apache.flink.util.IterableUtils;

import java.util.Set;
import java.util.stream.Collectors;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Provides a virtual execution state of a {@link SchedulingPipelinedRegion}.
 *
 * <p>A pipelined region can be either finished or unfinished. It is finished iff. all its
 * executions have reached the finished state.
 */
class PipelinedRegionExecutionView {

    private final SchedulingPipelinedRegion pipelinedRegion;

    private final Set<ExecutionVertexID> unfinishedVertices;

    PipelinedRegionExecutionView(final SchedulingPipelinedRegion pipelinedRegion) {
        this.pipelinedRegion = checkNotNull(pipelinedRegion);
        this.unfinishedVertices =
                IterableUtils.toStream(pipelinedRegion.getVertices())
                        .map(SchedulingExecutionVertex::getId)
                        .collect(Collectors.toSet());
    }

    public boolean isFinished() {
        return unfinishedVertices.isEmpty();
    }

    public void vertexFinished(final ExecutionVertexID executionVertexId) {
        assertVertexInRegion(executionVertexId);
        unfinishedVertices.remove(executionVertexId);
    }

    public void vertexUnfinished(final ExecutionVertexID executionVertexId) {
        assertVertexInRegion(executionVertexId);
        unfinishedVertices.add(executionVertexId);
    }

    private void assertVertexInRegion(final ExecutionVertexID executionVertexId) {
        pipelinedRegion.getVertex(executionVertexId);
    }
}


text: from indicator import AticonfigIndicator


text:
<?php

namespace AppBundle\Repository;

/**
 * UserPriceRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserPriceRepository extends \Doctrine\ORM\EntityRepository
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".view.activity.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Search 'Joel'" />

    <TextView
        android:id="@+id/player"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp" />

    <FrameLayout
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="16dp" />
</LinearLayout>


text:
#ifndef INC_XlfCmdDesc_H
#define INC_XlfCmdDesc_H

/*!
\file XlfCmdDesc.h
\brief Declares class XlfCmdDesc.
*/

// $Id$

#include <xlw/XlfAbstractCmdDesc.h>

#if defined(_MSC_VER)
#pragma once
#endif

#if defined(DEBUG_HEADERS)
#pragma DEBUG_HEADERS
#endif

//! Encapsulates Excel C macro command.
/*!
Commands can be called from the tool bar and do not take any argument
*/
class EXCEL32_API XlfCmdDesc: public XlfAbstractCmdDesc
{
public:
  //! Ctor.
  XlfCmdDesc(const std::string& name, const std::string& alias, const std::string& comment);
  //! Dtor.
  ~XlfCmdDesc();
  //! Adds the command to an Excel menu bar.
  int AddToMenuBar(const std::string& menu, const std::string& text);
  //! Is the command already in a menu bar?
  bool IsAddedToMenuBar();
  //! Activates/Desactivates the check box next to the command menu.
  int Check(bool) const;

protected:
  //! Registers the command to Excel
  int DoRegister() const;

private:
  //! Menu in which the command is to be displayed.
  std::string menu_;
  //! Text in the menu.
  std::string text_;
};

#endif


text:
package DDG::Spice::Flights::Route;
# ABSTRACT: Shows information on flights

use strict;
use DDG::Spice;
use Text::Trim;

# cache responses for 5 minutes
spice proxy_cache_valid => "200 304 5m";

spice from => '(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)';
spice to => 'https://api.flightstats.com/flex/flightstatus/rest/v2/jsonp/route/status/$4/$5/arr/$6/$7/$8?hourOfDay=$9&utc=true&appId={{ENV{DDG_SPICE_FLIGHTS_API_ID}}}&appKey={{ENV{DDG_SPICE_FLIGHTS_APIKEY}}}&callback={{callback}}';

spice alt_to => {
	route_helper => {
		proxy_cache_valid => '200 304 5m',
		to => 'https://api.flightstats.com/flex/flightstatus/rest/v2/jsonp/route/status/$1/$2/$3/$4/$5/$6/?hourOfDay=$7&utc=true&appId={{ENV{DDG_SPICE_FLIGHTS_API_ID}}}&appKey={{ENV{DDG_SPICE_FLIGHTS_APIKEY}}}&callback={{callback}}',
		from => '(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)'
	}
};

my @triggers = ('airport', 'international', 'national', 'intl', 'regional');

# get the list of cities and their IATA airport codes
my (%citiesByName, %citiesByCode);

foreach my $line (share('cities.csv')->slurp) {

    # remove \n and separate line into fields
    chomp($line);
    my @line = split(/,/, $line);

    my $cityName = lc($line[3]);
    my $airportCode = lc($line[0]);

    # map city names to their airport codes; if this city name
    # already exists, append the new airport code to the end
    if (exists $citiesByName{$cityName}) {
        push($citiesByName{$cityName}, $airportCode);
    } else {
        $citiesByName{$cityName} = [$airportCode];
    }

    # map airport codes to city names
    $citiesByCode{$airportCode} = $cityName;

    # store both the city name and airport code as triggers
    push(@triggers, ($cityName, $airportCode));

    # remove common words from the airport name and add as a new key
    # that maps to the same airport code if the stripped airport name and the city name
    # are not identical
    my $strippedAirportName = lc($line[4]);

    if ($strippedAirportName ne $cityName) {
        if (exists $citiesByName{$strippedAirportName}) {
            push($citiesByName{$strippedAirportName}, $airportCode);
        } else {
            $citiesByName{$strippedAirportName} = [$airportCode];
        }

        push(@triggers, $strippedAirportName);
    }

}

# get the list of airlines and their ICAO codes
my %airlines = ();

foreach my $line (share('airlines.csv')->slurp) {

    # remove \n
    chomp($line);

    # associate airport name with its code
    my @line = split(/,/, $line);
    $airlines{lc($line[1])} = lc($line[0]);
}

triggers startend => @triggers;

# identifyCodes(...) looks at either side of a flight query
# and returns the airline and airport code, if found
#
# inputs:
#   [0] $query is the combined airline/city query that needs to be split
#   [1] $leftQuery is a boolean that indicates if $query is the source city
#   [2] $otherCity is the remainder of the original query on the other side of the
#       preposition
#
# outputs:
#   [0] array, ICAO airline codes
#   [1] array, originating IATA airport codes
#   [2] array, destination IATA airport codes
#   [3] source city
#   [4] destination city
#
# ICAO codes are supposed to be unique, while IATA codes do not have to be.
# As the ICAO codes are only used internally, mapping airlines to their ICAO codes
# makes filtering results easier. However, travelers usually always see an
# airport's IATA code (e.g., Los Angeles's IATA code is LAX, and its ICAO code is KLAX),
# so we will match airports by IATA.
sub identifyCodes {

    my ($query, $leftQuery, $otherCity) = @_;

    # split query into individual words
    # at least two words are required (1 for the airline and 1 for the city)
    my @query = split(/\s+/, $query);
    return if scalar(@query) < 2;

    # an ambiguous airline name may return multiple airline codes
    # collect all airline names that begin with the user's query
    my @airlineCodes = ();
    foreach (0..$#query-1) {

        # search query word by word; for example, if the query that we need to
        # parse is "boston to los angeles jetblue", then we check
        # 1) "los" "angeles jetblue"
        # 2) "los angeles" "jetblue"
        my $groupA = join(' ', @query[0..$_]);
        my $groupB = join(' ', @query[$_+1..($#query)]);

        for my $airlineName (keys %airlines) {

            push(@airlineCodes, uc($airlines{$airlineName}))
                if $leftQuery
                and index($airlineName, $groupA) == 0
                and (exists $citiesByName{$groupB} or exists $citiesByCode{$groupB});

            push(@airlineCodes, uc($airlines{$airlineName}))
                if !$leftQuery
                and index($airlineName, $groupB) == 0
                and (exists $citiesByName{$groupA} or exists $citiesByCode{$groupA});
        }

        # [airline][city][to][city]
        return (join(",", @airlineCodes), $citiesByName{$groupB}, $citiesByName{$otherCity}, $groupB, $otherCity)
            if @airlineCodes and $leftQuery and exists $citiesByName{$groupB} and exists $citiesByName{$otherCity};

        # [city][to][city][airline]
        return (join(",", @airlineCodes), $citiesByName{$otherCity}, $citiesByName{$groupA}, $otherCity, $groupA)
            if @airlineCodes and !$leftQuery and exists $citiesByName{$otherCity} and exists $citiesByName{$groupA};

        # [airline][airport code][to][airport code]
        return (join(",", @airlineCodes), [$groupB], [$otherCity], $groupB, $otherCity)
            if @airlineCodes and $leftQuery and exists $citiesByCode{$groupB} and exists $citiesByCode{$otherCity};

        # [airport code][to][airport code][airline]
        return (join(",", @airlineCodes), [$otherCity], [$groupA], $otherCity, $groupA)
            if @airlineCodes and !$leftQuery and exists $citiesByCode{$otherCity} and exists $citiesByCode{$groupA};

        # [airline][airport code][to][city]
        return (join(",", @airlineCodes), [$groupB], $citiesByName{$otherCity}, $groupB, $otherCity)
            if @airlineCodes and $leftQuery and exists $citiesByCode{$groupB} and exists $citiesByName{$otherCity};

        # [airline][city][to][airport code]
        return (join(",", @airlineCodes), $citiesByName{$groupB}, [$otherCity], $groupB, $otherCity)
            if @airlineCodes and $leftQuery and exists $citiesByName{$groupB} and exists $citiesByCode{$otherCity};

        # [airport code][to][city][airline]
        return (join(",", @airlineCodes), [$otherCity], $citiesByName{$groupA}, $otherCity, $groupA)
            if @airlineCodes and !$leftQuery and exists $citiesByCode{$otherCity} and exists $citiesByName{$groupA};

        # [city][to][airport code][airline]
        return (join(",", @airlineCodes), $citiesByName{$otherCity}, [$groupA], $otherCity, $groupA)
            if @airlineCodes and !$leftQuery and exists $citiesByName{$otherCity} and exists $citiesByCode{$groupA};
    }

    return;
}

handle query_lc => sub {

    # clean up input; strip periods and common words,
    # replace all other non-letters with a space, strip trailing spaces
    s/\b(airport|national|international|intl|regional)\b//g;
    s/\.//g;
    s/\b[^a-z]+\b/ /g;
    trim;

    # query must be in the form [airline][city][to][city] or [city][to][city][airline]
    my @query = split(/\s+to\s+/, $_);
    return if scalar(@query) != 2;

    # strip 'fligh(s) from' to allow more flexible queries
    $query[0] =~ s/\b(flights?|from)\b//g;

    trim($_) foreach @query;

    # get the current time, minus six hours
    my ($second, $minute, $hour, $dayOfMonth,
        $month, $year, $dayOfWeek, $dayOfYear, $daylightSavings) = gmtime(time - 21600);

    $month += 1;
    $year += 1900;

    my @flightCodes = ();

    # query format: [airline][city or airport code][to][city or airport code]
    if (exists $citiesByName{$query[1]} or exists $citiesByCode{$query[1]}) {
        @flightCodes = identifyCodes($query[0], 1, $query[1]);

    # query format: [city or airport code][to][city or airport code][airline]
    } elsif (exists $citiesByName{$query[0]} or exists $citiesByCode{$query[0]}) {
        @flightCodes = identifyCodes($query[1], 0, $query[0]);
    }

    return unless @flightCodes;

    # prepare strings for "more information at" links
    my $sourceCity = $flightCodes[3];
    my $destinationCity = $flightCodes[4];
    $sourceCity =~ s/\s+/+/g;
    $destinationCity =~ s/\s+/+/g;

    return ($flightCodes[0],
            join(",", map(uc, @{$flightCodes[1]})),
            join(",", map(uc, @{$flightCodes[2]})),
            uc($flightCodes[1][0]), uc($flightCodes[2][0]),
            $year, $month, $dayOfMonth, $hour,
            $sourceCity, $destinationCity
            );

};

1;


text:
//     NoFlo - Flow-Based Programming for JavaScript
//     (c) 2013-2020 Flowhub UG
//     (c) 2011-2012 Henri Bergius, Nemein
//     NoFlo may be freely distributed under the MIT license

/* eslint-disable no-underscore-dangle */
import debug from 'debug';
import IP from './IP';

const debugComponent = debug('noflo:component');

// Checks if a value is an Error
/**
 * @param {any} err
 * @returns {boolean}
 */
function isError(err) {
  return err instanceof Error
    || (Array.isArray(err) && (err.length > 0) && err[0] instanceof Error);
}

export default class ProcessOutput {
  /**
   * @param {import("./Ports").OutPorts} ports - Component outports
   * @param {import("./ProcessContext").default} context - Processing context
   */
  constructor(ports, context) {
    this.ports = ports;
    this.context = context;
    this.nodeInstance = this.context.nodeInstance;
    this.ip = this.context.ip;
    this.result = this.context.result;
    this.scope = this.context.scope;
  }

  // Sends an error object
  /**
   * @param {Error|Error[]} err
   * @returns {void}
   */
  error(err) {
    const errs = Array.isArray(err) ? err : [err];
    if (this.ports.ports.error
      && (this.ports.ports.error.isAttached() || !this.ports.ports.error.isRequired())) {
      if (errs.length > 1) { this.sendIP('error', new IP('openBracket')); }
      errs.forEach((e) => { this.sendIP('error', e); });
      if (errs.length > 1) { this.sendIP('error', new IP('closeBracket')); }
    } else {
      errs.forEach((e) => { throw e; });
    }
  }

  // Sends a single IP object to a port
  /**
   * @param {string} port - Port to send to
   * @param {IP|any} packet - IP or data to send
   * @returns {void}
   */
  sendIP(port, packet) {
    const ip = IP.isIP(packet) ? packet : new IP('data', packet);
    if ((this.scope !== null) && (ip.scope === null)) { ip.scope = this.scope; }

    if (!this.nodeInstance.outPorts.ports[port]) {
      throw new Error(`Node ${this.nodeInstance.nodeId} does not have outport ${port}`);
    }

    // eslint-disable-next-line max-len
    const portImpl = /** @type {import("./OutPort").default} */ (this.nodeInstance.outPorts.ports[port]);

    if (portImpl.isAddressable() && (ip.index === null)) {
      throw new Error(`Sending packets to addressable port ${this.nodeInstance.nodeId} ${port} requires specifying index`);
    }

    if (this.nodeInstance.isOrdered()) {
      this.nodeInstance.addToResult(this.result, port, ip);
      return;
    }
    if (!portImpl.options.scoped) {
      ip.scope = null;
    }
    portImpl.sendIP(ip);
  }

  // Sends packets for each port as a key in the map
  // or sends Error or a list of Errors if passed such
  /**
   * @param {Error|Array<Error>|Object<string, any>} outputMap
   */
  send(outputMap) {
    if (isError(outputMap)) {
      const errors = /** @type {Error|Array<Error>} */ (outputMap);
      this.error(errors);
      return;
    }

    /** @type {Array<string>} */
    const componentPorts = [];
    let mapIsInPorts = false;
    Object.keys(this.ports.ports).forEach((port) => {
      if ((port !== 'error') && (port !== 'ports') && (port !== '_callbacks')) { componentPorts.push(port); }
      if (!mapIsInPorts && (outputMap != null) && (typeof outputMap === 'object') && (Object.keys(outputMap).indexOf(port) !== -1)) {
        mapIsInPorts = true;
      }
    });

    if ((componentPorts.length === 1) && !mapIsInPorts) {
      this.sendIP(componentPorts[0], outputMap);
      return;
    }

    if ((componentPorts.length > 1) && !mapIsInPorts) {
      throw new Error('Port must be specified for sending output');
    }

    Object.keys(outputMap).forEach((port) => {
      const packet = outputMap[port];
      this.sendIP(port, packet);
    });
  }

  // Sends the argument via `send()` and marks activation as `done()`
  /**
   * @param {Error|Array<Error>|Object<string, any>} outputMap
   */
  sendDone(outputMap) {
    this.send(outputMap);
    this.done();
  }

  // Makes a map-style component pass a result value to `out`
  // keeping all IP metadata received from `in`,
  // or modifying it if `options` is provided
  /**
   * @param {any} data
   * @param {Object<string, any>} [options]
   */
  pass(data, options = {}) {
    if (!('out' in this.ports)) {
      throw new Error('output.pass() requires port "out" to be present');
    }
    const that = this;
    Object.keys(options).forEach((key) => {
      const val = options[key];
      that.ip[key] = val;
    });
    this.ip.data = data;
    this.sendIP('out', this.ip);
    this.done();
  }

  // Finishes process activation gracefully
  /**
   * @param {Error|Array<Error>} [error]
   */
  done(error) {
    this.result.__resolved = true;
    this.nodeInstance.activate(this.context);
    if (error) { this.error(error); }

    const isLast = () => {
      // We only care about real output sets with processing data
      const resultsOnly = this.nodeInstance.outputQ.filter((q) => {
        if (!q.__resolved) { return true; }
        if ((Object.keys(q).length === 2) && q.__bracketClosingAfter) {
          return false;
        }
        return true;
      });
      const pos = resultsOnly.indexOf(this.result);
      const len = resultsOnly.length;
      const {
        load,
      } = this.nodeInstance;
      if (pos === (len - 1)) { return true; }
      if ((pos === -1) && (load === (len + 1))) { return true; }
      if ((len <= 1) && (load === 1)) { return true; }
      return false;
    };
    if (this.nodeInstance.isOrdered() && isLast()) {
      // We're doing bracket forwarding. See if there are
      // dangling closeBrackets in buffer since we're the
      // last running process function.
      Object.keys(this.nodeInstance.bracketContext.in).forEach((port) => {
        const contexts = this.nodeInstance.bracketContext.in[port];
        if (!contexts[this.scope]) { return; }
        const nodeContext = contexts[this.scope];
        if (!nodeContext.length) { return; }
        const context = nodeContext[nodeContext.length - 1];
        // eslint-disable-next-line max-len
        const inPorts = /** @type {import("./InPort").default} */ (this.nodeInstance.inPorts.ports[context.source]);
        const buf = inPorts.getBuffer(context.ip.scope, context.ip.index);
        while (buf.length > 0 && buf[0].type === 'closeBracket') {
          const ip = inPorts.get(context.ip.scope, context.ip.index);
          const ctx = nodeContext.pop();
          ctx.closeIp = ip;
          if (!this.result.__bracketClosingAfter) { this.result.__bracketClosingAfter = []; }
          this.result.__bracketClosingAfter.push(ctx);
        }
      });
    }

    debugComponent(`${this.nodeInstance.nodeId} finished processing ${this.nodeInstance.load}`);

    this.nodeInstance.deactivate(this.context);
  }
}


text:
package org.apache.calcite.rel.externalize;

import org.apache.calcite.rel.RelNode;
import org.apache.calcite.sql.SqlExplainLevel;
import org.apache.calcite.util.Pair;
import org.apache.calcite.util.XmlOutput;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Callback for a relational expression to dump in XML format.
 */
public class RelXmlWriter extends RelWriterImpl {
  //~ Instance fields --------------------------------------------------------

  private final XmlOutput xmlOutput;
  boolean generic = true;

  //~ Constructors -----------------------------------------------------------

  // TODO jvs 23-Dec-2005:  honor detail level.  The current inheritance
  // structure makes this difficult without duplication; need to factor
  // out the filtering of attributes before rendering.

  public RelXmlWriter(PrintWriter pw, SqlExplainLevel detailLevel) {
    super(pw, detailLevel, true);
    xmlOutput = new XmlOutput(pw);
    xmlOutput.setGlob(true);
    xmlOutput.setCompact(false);
  }

  //~ Methods ----------------------------------------------------------------

  protected void explain_(
      RelNode rel,
      List<Pair<String, Object>> values) {
    if (generic) {
      explainGeneric(rel, values);
    } else {
      explainSpecific(rel, values);
    }
  }

  /**
   * Generates generic XML (sometimes called 'element-oriented XML'). Like
   * this:
   *
   *

   *
   * <RelNode id="1" type="Join">

   *   <Property name="condition">EMP.DEPTNO =
   * DEPT.DEPTNO</Property>

   *   <Inputs>

   *     <RelNode id="2" type="Project">

   *       <Property name="expr1">x +
   * y</Property>

   *       <Property
   * name="expr2">45</Property>

   *     </RelNode>

   *     <RelNode id="3" type="TableAccess">

   *       <Property
   * name="table">SALES.EMP</Property>

   *     </RelNode>

   *   </Inputs>

   * </RelNode>
   *

   *
   * @param rel    Relational expression
   * @param values List of term-value pairs
   */
  private void explainGeneric(
      RelNode rel,
      List<Pair<String, Object>> values) {
    String relType = rel.getRelTypeName();
    xmlOutput.beginBeginTag("RelNode");
    xmlOutput.attribute("type", relType);

    //xmlOutput.attribute("id", rel.getId() + "");
    xmlOutput.endBeginTag("RelNode");

    final List<RelNode> inputs = new ArrayList<RelNode>();
    for (Pair<String, Object> pair : values) {
      if (pair.right instanceof RelNode) {
        inputs.add((RelNode) pair.right);
        continue;
      }
      if (pair.right == null) {
        continue;
      }
      xmlOutput.beginBeginTag("Property");
      xmlOutput.attribute("name", pair.left);
      xmlOutput.endBeginTag("Property");
      xmlOutput.cdata(pair.right.toString());
      xmlOutput.endTag("Property");
    }
    xmlOutput.beginTag("Inputs", null);
    spacer.add(2);
    for (RelNode input : inputs) {
      input.explain(this);
    }
    spacer.subtract(2);
    xmlOutput.endTag("Inputs");
    xmlOutput.endTag("RelNode");
  }

  /**
   * Generates specific XML (sometimes called 'attribute-oriented XML'). Like
   * this:
   *
   *

   * <Join condition="EMP.DEPTNO = DEPT.DEPTNO">
   *   <Project expr1="x + y" expr2="42">
   *   <TableAccess table="SALES.EMPS">
   * </Join>
   *

   *
   * @param rel    Relational expression
   * @param values List of term-value pairs
   */
  private void explainSpecific(
      RelNode rel,
      List<Pair<String, Object>> values) {
    String tagName = rel.getRelTypeName();
    xmlOutput.beginBeginTag(tagName);
    xmlOutput.attribute("id", rel.getId() + "");

    for (Pair<String, Object> value : values) {
      if (value.right instanceof RelNode) {
        continue;
      }
      xmlOutput.attribute(
          value.left,
          value.right.toString());
    }
    xmlOutput.endBeginTag(tagName);
    spacer.add(2);
    for (RelNode input : rel.getInputs()) {
      input.explain(this);
    }
    spacer.subtract(2);
  }
}

// End RelXmlWriter.java


text:
package com.insightfullogic.multiinherit.reflection;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

import com.insightfullogic.multiinherit.common.ResolutionInfo;

class MultiInvocationHandler implements InvocationHandler {

	private final Map<Class<?>, Object> cache;
	private final Map<ResolutionInfo, Method> preferences;

	public MultiInvocationHandler(final Map<Class<?>, Object> lookup, final Map<ResolutionInfo, Method> preferences) {
		super();
		cache = lookup;
		this.preferences = preferences;
	}

	@Override
	public Object invoke(final Object proxy, Method method, final Object[] args) throws Throwable {
		final Method preferred = preferences.get(new ResolutionInfo(method));
		if (preferred != null) {
			method = preferred;
		}
		final Object obj = cache.get(method.getDeclaringClass());
		return method.invoke(obj, args);
	}

}


text:
<?php

namespace Application\Service;

use Application\Service\TargetRetrieve;
use Doctrine\ORM\EntityManager;

/**
 * Contains the data needed to retrieve an appointment.
 *
 * @package		Application\Service
 * @author		Blair <blair@kaaterskil.com>
 * @copyright	Copyright (c) 2009-2013 Kaaterskil Management, LLC
 * @version		$Id: TargetRetrieveAppointment.php 13 2013-08-05 22:53:55Z  $
 */
class TargetRetrieveAppointment extends TargetRetrieve {

	/**
	 * Constructor
	 *
	 * @param EntityManager $em
	 */
	public function __construct(EntityManager $em = null) {
		parent::__construct($em);
		$this->setClazz('Application\Model\AbstractAppointment');
	}
}
?>


text:
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.misc.Interval;

public abstract class Java9LexerBase extends Lexer
{
    public Java9LexerBase(CharStream input) {
	super(input);
    }

    public boolean Check1()
    {
        return Character.isJavaIdentifierStart(_input.LA(-1));
    }

    public boolean Check2()
    {
        return Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)));
    }

    public boolean Check3()
    {
        return Character.isJavaIdentifierPart(_input.LA(-1));
    }

    public boolean Check4()
    {
        return Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)));
    }
}


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

    <parent>
        <groupId>cz.voho.examples</groupId>
        <artifactId>libraries</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>spring-jdbc-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.190</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
module LessAccounting
  # Defines HTTP request methods
  module Request

    # Perform an HTTP GET request
    def get(path, params = {})
      request(:get, path, params)
    end

    # Perform an HTTP POST request
    def post(path, params = {})
      request(:post, path, params)
    end

    # Perfrom an HTTP PUT request
    def put(path, params = {})
      request(:put, path, params)
    end

    # Perform an HTTP DELETE request
    def delete(path, params = {})
      request(:delete, path, params)
    end

    private

    # Perform an HTTP request
    def request(method, path, params)
      response = connection.send(method) do |request|
        case method
        when :get
          request.url(path, params)
        when :put
          params.merge!({"_method" => 'put'})
          request.url(path,params)
        when :post
          request.url(path)
          request.body = params
        when :delete
          params.merge!({"_method" => 'delete'})
          request.url(path, params)
        end
      end

      Response.create(response.body)
    end

  end
end


text:
'use strict';

module.exports = function(Chart) {

	var helpers = Chart.helpers;

	function filterByPosition(array, position) {
		return helpers.where(array, function(v) {
			return v.position === position;
		});
	}

	function sortByWeight(array, reverse) {
		array.forEach(function(v, i) {
			v._tmpIndex_ = i;
			return v;
		});
		array.sort(function(a, b) {
			var v0 = reverse ? b : a;
			var v1 = reverse ? a : b;
			return v0.weight === v1.weight ?
				v0._tmpIndex_ - v1._tmpIndex_ :
				v0.weight - v1.weight;
		});
		array.forEach(function(v) {
			delete v._tmpIndex_;
		});
	}

	/**
	 * @interface ILayoutItem
	 * @prop {String} position - The position of the item in the chart layout. Possible values are
	 * 'left', 'top', 'right', 'bottom', and 'chartArea'
	 * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area
	 * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
	 * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
	 * @prop {Function} update - Takes two parameters: width and height. Returns size of item
	 * @prop {Function} getPadding -  Returns an object with padding on the edges
	 * @prop {Number} width - Width of item. Must be valid after update()
	 * @prop {Number} height - Height of item. Must be valid after update()
	 * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update
	 * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update
	 * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update
	 * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
	 */

	// The layout service is very self explanatory.  It's responsible for the layout within a chart.
	// Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
	// It is this service's responsibility of carrying out that layout.
	Chart.layoutService = {
		defaults: {},

		/**
		 * Register a box to a chart.
		 * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
		 * @param {Chart} chart - the chart to use
		 * @param {ILayoutItem} layoutItem - the item to add to be layed out
		 */
		addBox: function(chart, layoutItem) {
			if (!chart.boxes) {
				chart.boxes = [];
			}

			// Ensure that all layout items have a weight
			if (!layoutItem.weight) {
				layoutItem.weight = 0;
			}
			chart.boxes.push(layoutItem);
		},

		/**
		 * Remove a layoutItem from a chart
		 * @param {Chart} chart - the chart to remove the box from
		 * @param {Object} layoutItem - the item to remove from the layout
		 */
		removeBox: function(chart, layoutItem) {
			if (!chart.boxes) {
				return;
			}
			chart.boxes.splice(chart.boxes.indexOf(layoutItem), 1);
		},

		/**
		 * Fits boxes of the given chart into the given size by having each box measure itself
		 * then running a fitting algorithm
		 * @param {Chart} chart - the chart
		 * @param {Number} width - the width to fit into
		 * @param {Number} height - the height to fit into
		 */
		update: function(chart, width, height) {
			if (!chart) {
				return;
			}

			var layoutOptions = chart.options.layout;
			var padding = layoutOptions ? layoutOptions.padding : null;

			var leftPadding = 0;
			var rightPadding = 0;
			var topPadding = 0;
			var bottomPadding = 0;

			if (!isNaN(padding)) {
				// options.layout.padding is a number. assign to all
				leftPadding = padding;
				rightPadding = padding;
				topPadding = padding;
				bottomPadding = padding;
			} else {
				leftPadding = padding.left || 0;
				rightPadding = padding.right || 0;
				topPadding = padding.top || 0;
				bottomPadding = padding.bottom || 0;
			}

			var leftBoxes = filterByPosition(chart.boxes, 'left');
			var rightBoxes = filterByPosition(chart.boxes, 'right');
			var topBoxes = filterByPosition(chart.boxes, 'top');
			var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
			var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');

			// Sort boxes by weight. A higher weight is further away from the chart area
			sortByWeight(leftBoxes, true);
			sortByWeight(rightBoxes, false);
			sortByWeight(topBoxes, true);
			sortByWeight(bottomBoxes, false);

			// Essentially we now have any number of boxes on each of the 4 sides.
			// Our canvas looks like the following.
			// The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
			// B1 is the bottom axis
			// There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
			// These locations are single-box locations only, when trying to register a chartArea location that is already taken,
			// an error will be thrown.
			//
			// |----------------------------------------------------|
			// |                  T1 (Full Width)                   |
			// |----------------------------------------------------|
			// |    |    |                 T2                  |    |
			// |    |----|-------------------------------------|----|
			// |    |    | C1 |                           | C2 |    |
			// |    |    |----|                           |----|    |
			// |    |    |                                     |    |
			// | L1 | L2 |           ChartArea (C0)            | R1 |
			// |    |    |                                     |    |
			// |    |    |----|                           |----|    |
			// |    |    | C3 |                           | C4 |    |
			// |    |----|-------------------------------------|----|
			// |    |    |                 B1                  |    |
			// |----------------------------------------------------|
			// |                  B2 (Full Width)                   |
			// |----------------------------------------------------|
			//
			// What we do to find the best sizing, we do the following
			// 1. Determine the minimum size of the chart area.
			// 2. Split the remaining width equally between each vertical axis
			// 3. Split the remaining height equally between each horizontal axis
			// 4. Give each layout the maximum size it can be. The layout will return it's minimum size
			// 5. Adjust the sizes of each axis based on it's minimum reported size.
			// 6. Refit each axis
			// 7. Position each axis in the final location
			// 8. Tell the chart the final location of the chart area
			// 9. Tell any axes that overlay the chart area the positions of the chart area

			// Step 1
			var chartWidth = width - leftPadding - rightPadding;
			var chartHeight = height - topPadding - bottomPadding;
			var chartAreaWidth = chartWidth / 2; // min 50%
			var chartAreaHeight = chartHeight / 2; // min 50%

			// Step 2
			var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length);

			// Step 3
			var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length);

			// Step 4
			var maxChartAreaWidth = chartWidth;
			var maxChartAreaHeight = chartHeight;
			var minBoxSizes = [];

			function getMinimumBoxSize(box) {
				var minSize;
				var isHorizontal = box.isHorizontal();

				if (isHorizontal) {
					minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight);
					maxChartAreaHeight -= minSize.height;
				} else {
					minSize = box.update(verticalBoxWidth, chartAreaHeight);
					maxChartAreaWidth -= minSize.width;
				}

				minBoxSizes.push({
					horizontal: isHorizontal,
					minSize: minSize,
					box: box,
				});
			}

			helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize);

			// If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
			var maxHorizontalLeftPadding = 0;
			var maxHorizontalRightPadding = 0;
			var maxVerticalTopPadding = 0;
			var maxVerticalBottomPadding = 0;

			helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) {
				if (horizontalBox.getPadding) {
					var boxPadding = horizontalBox.getPadding();
					maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left);
					maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right);
				}
			});

			helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) {
				if (verticalBox.getPadding) {
					var boxPadding = verticalBox.getPadding();
					maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top);
					maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom);
				}
			});

			// At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
			// be if the axes are drawn at their minimum sizes.
			// Steps 5 & 6
			var totalLeftBoxesWidth = leftPadding;
			var totalRightBoxesWidth = rightPadding;
			var totalTopBoxesHeight = topPadding;
			var totalBottomBoxesHeight = bottomPadding;

			// Function to fit a box
			function fitBox(box) {
				var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) {
					return minBox.box === box;
				});

				if (minBoxSize) {
					if (box.isHorizontal()) {
						var scaleMargin = {
							left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding),
							right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding),
							top: 0,
							bottom: 0
						};

						// Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
						// on the margin. Sometimes they need to increase in size slightly
						box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
					} else {
						box.update(minBoxSize.minSize.width, maxChartAreaHeight);
					}
				}
			}

			// Update, and calculate the left and right margins for the horizontal boxes
			helpers.each(leftBoxes.concat(rightBoxes), fitBox);

			helpers.each(leftBoxes, function(box) {
				totalLeftBoxesWidth += box.width;
			});

			helpers.each(rightBoxes, function(box) {
				totalRightBoxesWidth += box.width;
			});

			// Set the Left and Right margins for the horizontal boxes
			helpers.each(topBoxes.concat(bottomBoxes), fitBox);

			// Figure out how much margin is on the top and bottom of the vertical boxes
			helpers.each(topBoxes, function(box) {
				totalTopBoxesHeight += box.height;
			});

			helpers.each(bottomBoxes, function(box) {
				totalBottomBoxesHeight += box.height;
			});

			function finalFitVerticalBox(box) {
				var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) {
					return minSize.box === box;
				});

				var scaleMargin = {
					left: 0,
					right: 0,
					top: totalTopBoxesHeight,
					bottom: totalBottomBoxesHeight
				};

				if (minBoxSize) {
					box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin);
				}
			}

			// Let the left layout know the final margin
			helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox);

			// Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
			totalLeftBoxesWidth = leftPadding;
			totalRightBoxesWidth = rightPadding;
			totalTopBoxesHeight = topPadding;
			totalBottomBoxesHeight = bottomPadding;

			helpers.each(leftBoxes, function(box) {
				totalLeftBoxesWidth += box.width;
			});

			helpers.each(rightBoxes, function(box) {
				totalRightBoxesWidth += box.width;
			});

			helpers.each(topBoxes, function(box) {
				totalTopBoxesHeight += box.height;
			});
			helpers.each(bottomBoxes, function(box) {
				totalBottomBoxesHeight += box.height;
			});

			// We may be adding some padding to account for rotated x axis labels
			var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0);
			totalLeftBoxesWidth += leftPaddingAddition;
			totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0);

			var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0);
			totalTopBoxesHeight += topPaddingAddition;
			totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0);

			// Figure out if our chart area changed. This would occur if the dataset layout label rotation
			// changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
			// without calling `fit` again
			var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight;
			var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth;

			if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
				helpers.each(leftBoxes, function(box) {
					box.height = newMaxChartAreaHeight;
				});

				helpers.each(rightBoxes, function(box) {
					box.height = newMaxChartAreaHeight;
				});

				helpers.each(topBoxes, function(box) {
					if (!box.fullWidth) {
						box.width = newMaxChartAreaWidth;
					}
				});

				helpers.each(bottomBoxes, function(box) {
					if (!box.fullWidth) {
						box.width = newMaxChartAreaWidth;
					}
				});

				maxChartAreaHeight = newMaxChartAreaHeight;
				maxChartAreaWidth = newMaxChartAreaWidth;
			}

			// Step 7 - Position the boxes
			var left = leftPadding + leftPaddingAddition;
			var top = topPadding + topPaddingAddition;

			function placeBox(box) {
				if (box.isHorizontal()) {
					box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth;
					box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth;
					box.top = top;
					box.bottom = top + box.height;

					// Move to next point
					top = box.bottom;

				} else {

					box.left = left;
					box.right = left + box.width;
					box.top = totalTopBoxesHeight;
					box.bottom = totalTopBoxesHeight + maxChartAreaHeight;

					// Move to next point
					left = box.right;
				}
			}

			helpers.each(leftBoxes.concat(topBoxes), placeBox);

			// Account for chart width and height
			left += maxChartAreaWidth;
			top += maxChartAreaHeight;

			helpers.each(rightBoxes, placeBox);
			helpers.each(bottomBoxes, placeBox);

			// Step 8
			chart.chartArea = {
				left: totalLeftBoxesWidth,
				top: totalTopBoxesHeight,
				right: totalLeftBoxesWidth + maxChartAreaWidth,
				bottom: totalTopBoxesHeight + maxChartAreaHeight
			};

			// Step 9
			helpers.each(chartAreaBoxes, function(box) {
				box.left = chart.chartArea.left;
				box.top = chart.chartArea.top;
				box.right = chart.chartArea.right;
				box.bottom = chart.chartArea.bottom;

				box.update(maxChartAreaWidth, maxChartAreaHeight);
			});
		}
	};
};


text:
An uber-classy theme for JSONResume, now responsive.

## Usage

To first get started with this JSONResume theme, you'll need to have the JSONResume CLI installed. If you haven't already install it with `npm install -g resume-cli`. If this doesn't work, try `sudo npm install -g resume-cli`.

After this, you can get your resume.json ready by typing `resume init`. After hitting enter, your resume will be initialized and you can edit it and fill in the neccessary fields. Check out [the official resume-schema repository](https://github.com/jsonresume/resume-schema) for more information on filling these fields.

When you are finished with your resume, you may test it by yet again opening the command line and typing `resume serve --theme classy` to see how it looks with this theme. You can replace the word `classy` with other theme names too.

If you want a local copy of your resume, type in `resume export resumeName --theme classy`, and replace `resumeName` with the desired filename. You can export it in pdf and txt using the `--format` flag, like so:

```
resume export resume --format pdf --theme classy
```

However, if you wish to export it to the JSONResume Registry, use the command `resume publish` instead.

More details about the CLI and it's commands are available [here](https://github.com/jsonresume/resume-cli).

## Colophon

Thanks to the wonderful [Font Awesome](https://fontawesome.io) for their free-to-use icon font, and a big thank you to the JSONResume theme for their wonderful idea and helping me with a few issues on my part.


text:
namespace wasm {

namespace decode {

Queue::Queue()
    : MinPeekSize(32),
      EofFrozen(false),
      Status(StatusValue::Good),
      EofPtr(std::make_shared<BlockEob>()) {
  // Verify we have space for kErrorPageAddress and kUndefinedAddress.
  assert(PageSizeLog2 > 1);
  LastPage = FirstPage = std::make_shared<Page>(0);
  PageMap.push_back(LastPage);
}

void Queue::close() {
  if (!isEofFrozen()) {
    AddressType EofAddress = LastPage->getMaxAddress();
    freezeEof(EofAddress);
  }
  while (FirstPage)
    dumpFirstPage();
}

Queue::~Queue() {
  close();
}

AddressType Queue::currentSize() const {
  return EofPtr->getEobAddress();
}

AddressType Queue::fillSize() const {
  return LastPage->getMaxAddress();
}

AddressType Queue::actualSize() const {
  return LastPage->getMaxAddress() - FirstPage->getMinAddress();
}

AddressType Queue::getEofAddress() const {
  return EofPtr->getEobAddress();
}

void Queue::describe(FILE* Out) {
  fprintf(Out, "**** Queue %p ***\n", (void*)this);
  fprintf(Out, "First = %p, Last = %p\n", (void*)FirstPage.get(),
          (void*)LastPage.get());
  for (AddressType i = 0; i < PageMap.size(); ++i) {
    std::shared_ptr<Page> Pg = PageMap[i].lock();
    if (Pg)
      Pg->describe(Out);
    else
      fprintf(Out, "Page[%" PRIuMAX "] = nullptr", uintmax_t(i));
    fprintf(Out, "\n");
  }
  if (ErrorPage) {
    fputs("Error ", Out);
    ErrorPage->describe(Out);
  }
  fprintf(Out, "*****************\n");
}

void Queue::fail() {
  Status = StatusValue::Bad;
  EofPtr->setEobAddress(0);
}

std::shared_ptr<Page> Queue::getErrorPage() {
  if (ErrorPage)
    return ErrorPage;
  ErrorPage = std::make_shared<Page>(kErrorPageIndex);
  return ErrorPage;
}

std::shared_ptr<Page> Queue::getReadPage(AddressType& Address) const {
  AddressType Index = PageIndex(Address);
  if (Index >= PageMap.size())
    return const_cast<Queue*>(this)->readFillToPage(Index, Address);
  return getDefinedPage(Index, Address);
}

std::shared_ptr<Page> Queue::getWritePage(AddressType& Address) const {
  AddressType Index = PageIndex(Address);
  if (Index >= PageMap.size())
    return const_cast<Queue*>(this)->writeFillToPage(Index, Address);
  return getDefinedPage(Index, Address);
}

std::shared_ptr<Page> Queue::getCachedPage(AddressType& Address) {
  AddressType Index = PageIndex(Address);
  if (Index >= PageMap.size())
    return failThenGetErrorPage(Address);
  return getDefinedPage(Index, Address);
}

std::shared_ptr<Page> Queue::getDefinedPage(AddressType Index,
                                            AddressType& Address) const {
  assert(Index < PageMap.size());
  std::shared_ptr<Page> Pg = PageMap[Index].lock();
  if (Pg)
    return Pg;
  return const_cast<Queue*>(this)->failThenGetErrorPage(Address);
}

std::shared_ptr<Page> Queue::failThenGetErrorPage(AddressType& Address) {
  fail();
  Address = kErrorPageAddress;
  return getErrorPage();
}

bool Queue::appendPage() {
  AddressType NewPageIndex = LastPage->getPageIndex() + 1;
  if (NewPageIndex > kMaxPageIndex)
    return false;
  std::shared_ptr<Page> NewPage = std::make_shared<Page>(NewPageIndex);
  PageMap.push_back(NewPage);
  LastPage->Next = NewPage;
  LastPage = NewPage;
  return true;
}

void Queue::dumpFirstPage() {
  FirstPage = FirstPage->Next;
}

void Queue::dumpPreviousPages() {
  while (FirstPage.unique())
    dumpFirstPage();
}

bool Queue::readFill(AddressType Address) {
  return Address < LastPage->getMaxAddress();
}

bool Queue::writeFill(AddressType Address, AddressType WantedSize) {
  Address += WantedSize;
  // Expand till page exists.
  while (Address > LastPage->getMaxAddress()) {
    if (EofFrozen)
      return false;
    AddressType MaxLimit = LastPage->getMinAddress() + PageSize;
    if (Address >= MaxLimit) {
      LastPage->setMaxAddress(MaxLimit);
      if (!appendPage())
        return false;
    } else {
      LastPage->setMaxAddress(Address);
    }
  }
  return true;
}

std::shared_ptr<Page> Queue::readFillToPage(AddressType Index,
                                            AddressType& Address) {
  while (Index > LastPage->Index) {
    bool ReadFillNextPage = readFill(LastPage->getMinAddress() + PageSize);
    if (!ReadFillNextPage && Index > LastPage->Index) {
      // This should only happen if we reach eof. Verify,
      // If so, allow page wrap so that we can have a cursor pointing
      // to the eof position.
      if ((LastPage->getMinAddress() + PageSize != LastPage->getMaxAddress()) ||
          !appendPage())
        return failThenGetErrorPage(Address);
    }
  }
  return getDefinedPage(Index, Address);
}

std::shared_ptr<Page> Queue::writeFillToPage(AddressType Index,
                                             AddressType& Address) {
  while (Index > LastPage->Index) {
    bool WriteFillNextPage = writeFill(LastPage->getMinAddress(), PageSize);
    if (!WriteFillNextPage && Index > LastPage->Index) {
      // This should only happen if we reach eof. Verify,
      // If so, allow page wrap so that we can have a cursor pointing
      // to the eof position.
      if ((LastPage->getMinAddress() + PageSize != LastPage->getMaxAddress()) ||
          !appendPage())
        return failThenGetErrorPage(Address);
    }
  }
  return getDefinedPage(Index, Address);
}

AddressType Queue::readFromPage(AddressType& Address,
                                AddressType WantedSize,
                                PageCursor& Cursor) {
  // Start by read-filling if necessary.
  if (Address >= LastPage->getMaxAddress() && !readFill(Address))
    return 0;
  // Find page associated with Address.
  Cursor.CurPage = getCachedPage(Address);
  Cursor.setCurAddress(Address);
  dumpPreviousPages();
  // Compute largest contiguous range of elements available.
  if (Address + WantedSize > Cursor.getMaxAddress())
    WantedSize = Cursor.getMaxAddress() - Address;
  return WantedSize;
}

AddressType Queue::writeToPage(AddressType& Address,
                               AddressType WantedSize,
                               PageCursor& Cursor) {
  // Expand till page exists.
  if (!writeFill(Address, WantedSize))
    return 0;
  Cursor.CurPage = getCachedPage(Address);
  Cursor.setCurAddress(Address);
  dumpPreviousPages();
  // Compute largest contiguous range of bytes available.
  if (Address + WantedSize > Cursor.getMaxAddress())
    WantedSize = Cursor.getMaxAddress() - Address;
  return WantedSize;
}

void Queue::freezeEof(AddressType& Address) {
  assert(Address <= kMaxEofAddress && "WASM stream too big to process");
  if (EofFrozen && Address != EofPtr->getEobAddress()) {
    fail();
    Address = 0;
  }
  // This call zero-fills pages if writing hasn't reached Address yet.
  PageCursor Cursor(this);
  writeToPage(Address, 0, Cursor);
  EofPtr->setEobAddress(Address);
  EofFrozen = true;
  if (!isBroken(Cursor)) {
    Cursor.setMaxAddress(Address);
    // TODO(karlschimpf): If adding threads, make this update thread safe.
    // If any pages exist after Cursor, remove them.
    LastPage = Cursor.CurPage;
    if (Cursor.CurPage->Next)
      Cursor.CurPage->Next.reset();
  }
}

bool Queue::isBroken(const PageCursor& C) const {
  assert(C.CurPage);
  return C.CurPage->getPageIndex() >= kErrorPageIndex;
}

AddressType Queue::read(AddressType& Address,
                        uint8_t* ToBuf,
                        AddressType WantedSize) {
  AddressType Count = 0;
  PageCursor Cursor(this);
  while (WantedSize) {
    AddressType FoundSize = readFromPage(Address, WantedSize, Cursor);
    if (FoundSize == 0)
      return Count;
    uint8_t* FromBuf = Cursor.getBufferPtr();
    memcpy(ToBuf, FromBuf, FoundSize);
    Count += FoundSize;
    WantedSize -= FoundSize;
    Address += FoundSize;
  }
  return Count;
}

bool Queue::write(AddressType& Address,
                  uint8_t* FromBuf,
                  AddressType WantedSize) {
  PageCursor Cursor(this);
  while (WantedSize) {
    AddressType FoundSize = writeToPage(Address, WantedSize, Cursor);
    if (FoundSize == 0)
      return false;
    uint8_t* ToBuf = Cursor.getBufferPtr();
    memcpy(ToBuf, FromBuf, FoundSize);
    Address += FoundSize;
    WantedSize -= FoundSize;
  }
  return true;
}

}  // end of decode namespace

}  // end of wasm namespace


text:
using System;
using Newtonsoft.Json;

namespace sharepointpromagfgw1
{
	public class ToDoItem
	{
		public string Id { get; set; }

		[JsonProperty(PropertyName = "text")]
		public string Text { get; set; }

		[JsonProperty(PropertyName = "complete")]
		public bool Complete { get; set; }
	}
}


text:
package bridge;

public interface MessageLogger {
	void log(String msg) throws Exception;
}


text:
function include(src, callback) {
  var inc = document.createElement('script'),
    timer,
    interval = 100,
    retries = 10;
  function check() {
    var loaded =
      inc.readyState &&
      (inc.readyState == 'loaded' ||
        inc.readyState == 'complete' ||
        inc.readyState == 4);
    if (loaded || --retries <= 0) {
      timer = timer ? clearInterval(timer) : null;
      callback && callback({ loaded: loaded });
    }
  }
  timer = callback ? setInterval(check, interval) : undefined;
  inc.onload = inc.onreadystatechange = check;
  try {
    inc.src = src;
    document.getElementsByTagName('head')[0].appendChild(inc);
  } catch (exception) {
    timer = timer ? clearInterval(timer) : null;
    callback
      ? callback(exception)
      : console.log(src + ' include exception: ', exception);
  }
}

function fetch(url, cb) {
  console.info('fetching data from ' + url + '...');
  var cbName =
    '_whyd_callback_' +
    Date.now() +
    '_' +
    (window._whyd_counter = (window._whyd_counter || 0) + 1);
  window[cbName] = function (res) {
    cb(res);
    delete window[cbName];
  };
  include(url + (url.indexOf('?') == -1 ? '?' : '&') + 'callback=' + cbName);
}

fetch('/api/user', function (res) {
  var loggedUser = !!(res || {})._id && res;
  if (loggedUser) {
    document.body.className = (document.body.className || '') + 'loggedIn';
    document.body.innerHTML = 'logged in';
  }
});


text:
from kubernetes_py.utils import is_valid_string

class ConfigMapKeySelector(object):
    """
    http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_configmapkeyselector
    """

    def __init__(self, model=None):
        super(ConfigMapKeySelector, self).__init__()

        self._name = None
        self._key = None

        if model is not None:
            self._build_with_model(model)

    def _build_with_model(self, model=None):
        if "name" in model:
            self.name = model["name"]
        if "key" in model:
            self.key = model["key"]

    # ------------------------------------------------------------------------------------- name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, n=None):
        if not is_valid_string(n):
            raise SyntaxError("ConfigMapKeySelector: name: [ {} ] is invalid.".format(n))
        self._name = n

    # ------------------------------------------------------------------------------------- key

    @property
    def key(self):
        return self._key

    @key.setter
    def key(self, k=None):
        if not is_valid_string(k):
            raise SyntaxError("ConfigMapKeySelector: key: [ {} ] is invalid.".format(k))
        self._key = k

    # ------------------------------------------------------------------------------------- serialize

    def serialize(self):
        data = {}
        if self.name is not None:
            data["name"] = self.name
        if self.key is not None:
            data["key"] = self.key
        return data


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Ann. nat. 14. 1820

#### Original name
null

### Remarks
null


text: - Revision tags?


text:
Testing
=======

This project uses the most fabulous testing tools for Python:

-  `pytest`_
-  `pytest-cov`_
-  `pytest-pep8`_
-  `pytest-sugar`_
-  `flexmock`_
-  `betamax`_

Run tests
---------

Run tests simply by:

::

    python setup.py test

or (if you have installed dependencies):

::

    python -m pytest [options]
    pytest [options]

Betamax cassettes
-----------------

Betamax cassettes are stored in ``tests/fixtures/cassettes`` directory. If
you are not connected to the internet, Twitter API is not working and/or
you don't have own API credentials you will use (replay) them in order to
test API client.

If you want to run your own cassettes, you need to setup system
variables

-  ``API_KEY``
-  ``API_SECRET``

Your test command then might look like:

::

    API_KEY=<YOUR_API_KEY> API_SECRET=<YOUR_API_SECRET> \
    python setup.py test

For more information, enjoy reading `Betamax documentation`_.

.. _pytest: http://doc.pytest.org/
.. _pytest-cov: https://pypi.python.org/pypi/pytest-cov
.. _pytest-pep8: https://pypi.python.org/pypi/pytest-pep8
.. _pytest-sugar: https://pypi.python.org/pypi/pytest-sugar
.. _flexmock: http://flexmock.readthedocs.io/en/latest/
.. _betamax: http://betamax.readthedocs.io
.. _Betamax documentation: http://betamax.readthedocs.io/en/latest/introduction.html


text:
/*
 * File:   dwm_spi.c
 * Author: jonathan
 *
 * Created on June 9, 2015, 11:17 AM
 */

#include "dwm_spi.h"
#include "decadriver/instance.h"
#include <stdlib.h>
#include <spi.h>
#include <xc.h>

dwm_1000_status dwm_status;

chConfig_t chConfig[8] ={
                    //mode 1 - S1: 7 off, 6 off, 5 off
                    {
                        2,              // channel
                        DWT_PRF_16M,    // prf
                        DWT_BR_110K,    // datarate
                        3,             // preambleCode
                        DWT_PLEN_1024,  // preambleLength
                        DWT_PAC32,      // pacSize
                        1,       // non-standard SFD
                        (1025 + 64 - 32) //SFD timeout
                    },
                    //mode 2
                    {
                        2,              // channel
                        DWT_PRF_16M,    // prf
                        DWT_BR_6M8,    // datarate
                        3,             // preambleCode
                        DWT_PLEN_128,   // preambleLength
                        DWT_PAC8,       // pacSize
                        0,       // non-standard SFD
                        (129 + 8 - 8) //SFD timeout
                    },
                    //mode 3
                    {
                        2,              // channel
                        DWT_PRF_64M,    // prf
                        DWT_BR_110K,    // datarate
                        9,             // preambleCode
                        DWT_PLEN_1024,  // preambleLength
                        DWT_PAC32,      // pacSize
                        1,       // non-standard SFD
                        (1025 + 64 - 32) //SFD timeout
                    },
                    //mode 4
                    {
                        2,              // channel
                        DWT_PRF_64M,    // prf
                        DWT_BR_6M8,    // datarate
                        9,             // preambleCode
                        DWT_PLEN_128,   // preambleLength
                        DWT_PAC8,       // pacSize
                        0,       // non-standard SFD
                        (129 + 8 - 8) //SFD timeout
                    },
                    //mode 5
                    {
                        5,              // channel
                        DWT_PRF_16M,    // prf
                        DWT_BR_110K,    // datarate
                        3,             // preambleCode
                        DWT_PLEN_1024,  // preambleLength
                        DWT_PAC32,      // pacSize
                        1,       // non-standard SFD
                        (1025 + 64 - 32) //SFD timeout
                    },
                    //mode 6
                    {
                        5,              // channel
                        DWT_PRF_16M,    // prf
                        DWT_BR_6M8,    // datarate
                        3,             // preambleCode
                        DWT_PLEN_128,   // preambleLength
                        DWT_PAC8,       // pacSize
                        0,       // non-standard SFD
                        (129 + 8 - 8) //SFD timeout
                    },
                    //mode 7
                    {
                        5,              // channel
                        DWT_PRF_64M,    // prf
                        DWT_BR_110K,    // datarate
                        9,             // preambleCode
                        DWT_PLEN_1024,  // preambleLength
                        DWT_PAC32,      // pacSize
                        1,       // non-standard SFD
                        (1025 + 64 - 32) //SFD timeout
                    },
                    //mode 8
                    {
                        5,              // channel
                        DWT_PRF_64M,    // prf
                        DWT_BR_6M8,    // datarate
                        9,             // preambleCode
                        DWT_PLEN_128,   // preambleLength
                        DWT_PAC8,       // pacSize
                        0,       // non-standard SFD
                        (129 + 8 - 8) //SFD timeout
                    }
};

#if (DR_DISCOVERY == 0)
int instance_anchaddr = 0; //0 = 0xDECA020000000001; 1 = 0xDECA020000000002; 2 = 0xDECA020000000003
//Tag address list
uint64_t tagAddressList[3] =
{
     0xDECA010000001001,         // First tag
     0xDECA010000000002,         // Second tag
     0xDECA010000000003          // Third tag
} ;

//Anchor address list
uint64_t anchorAddressList[ANCHOR_LIST_SIZE] =
{
     0xDECA020000000001 ,       // First anchor
     0xDECA020000000002 ,       // Second anchor
     0xDECA020000000003 ,       // Third anchor
     0xDECA020000000004         // Fourth anchor
} ;

//ToF Report Forwarding Address
uint64_t forwardingAddress[1] =
{
     0xDECA030000000001
} ;

// ======================================================
//
//  Configure instance tag/anchor/etc... addresses
//
void addressconfigure(void)
{
    instanceAddressConfig_t ipc ;

    ipc.forwardToFRAddress = forwardingAddress[0];
    ipc.anchorAddress = anchorAddressList[instance_anchaddr];
    ipc.anchorAddressList = anchorAddressList;
    ipc.anchorListSize = ANCHOR_LIST_SIZE ;
    ipc.anchorPollMask = 0x1; //0x7;              // anchor poll mask

    ipc.sendReport = 1 ;  //1 => anchor sends TOF report to tag
    //ipc.sendReport = 2 ;  //2 => anchor sends TOF report to listener

    instancesetaddresses(&ipc);
}
#endif

uint8_t dwm_init(int mode)
{
    uint8_t result = 1;
    uint32_t devID ;
    instanceConfig_t instConfig;

    devID = dwt_readdevid();

    if (DWT_DEVICE_ID != devID) {
        return -1;
    }

    result = instance_init();
    if (0 > result) return(-1);

    instancesetrole(mode);

    instance_init_s(mode);
    int dr_mode = 2; //TODO: check to see what this does?

    instConfig.channelNumber = chConfig[dr_mode].channel ;
    instConfig.preambleCode = chConfig[dr_mode].preambleCode ;
    instConfig.pulseRepFreq = chConfig[dr_mode].prf ;
    instConfig.pacSize = chConfig[dr_mode].pacSize ;
    instConfig.nsSFD = chConfig[dr_mode].nsSFD ;
    instConfig.sfdTO = chConfig[dr_mode].sfdTO ;
    instConfig.dataRate = chConfig[dr_mode].datarate ;
    instConfig.preambleLen = chConfig[dr_mode].preambleLength ;

    instance_config(&instConfig) ;                  // Set operating channel etc
#if (DR_DISCOVERY == 0)
    addressconfigure() ;                            // set up initial payload configuration
#endif
    instancesettagsleepdelay(POLL_SLEEP_DELAY, BLINK_SLEEP_DELAY); //set the Tag sleep time

    // NOTE: this is the delay between receiving the blink and sending the ranging init message
    // The anchor ranging init response delay has to match the delay the tag expects
    // the tag will then use the ranging response delay as specified in the ranging init message
    // use this to set the long blink response delay (e.g. when ranging with a PC anchor that wants to use the long response times != 150ms)
    instancesetblinkreplydelay(FIXED_REPLY_DELAY);
//    instancesetblinkreplydelay(FIXED_LONG_BLINK_RESPONSE_DELAY);

    //set the default response delays
    instancesetreplydelay(FIXED_REPLY_DELAY, 0);

    dwt_setleds(1);

    return result;
}

/**
 * This function is the low level function used by the decaWave DWM1000 API
 */
int writetospi( uint16_t headerLength,
                const uint8_t *headerBuffer,
                uint32_t bodylength,
                const uint8_t *bodyBuffer)
{
    nSELECT = 0;
    write_data_SPI(headerBuffer, headerLength);
    write_data_SPI(bodyBuffer, bodylength);
    nSELECT = 1;
    return DWT_SUCCESS;
}

/**
 * This function is the low level function used by the decaWave DWM1000 API
 */
 int readfromspi( uint16_t	headerLength,
                const uint8_t *headerBuffer,
                uint32_t readlength,
                uint8_t *readBuffer)
 {
    nSELECT = 0;
    write_data_SPI(headerBuffer, headerLength);
    read_data_SPI(readlength, readBuffer);
    nSELECT = 1;
    return DWT_SUCCESS;
 }

/**
 * Reads num_bytes of data from the device
 */
void read_data_SPI(uint16_t num_bytes, uint8_t* rec)
{
    uint16_t cur_byte;
    for(cur_byte=0;cur_byte<num_bytes;cur_byte++){
        SPI2BUF = 0x00;
        while(!SPI2STATbits.SPIRBF);
        rec[cur_byte] = SPI2BUF;
    }
}

/**
 * Writes num_bytes of data to the device
 */
void write_data_SPI(const uint8_t* data, uint16_t num_bytes)
{
    uint16_t cur_byte;
    uint8_t blahRead;
    for(cur_byte=0;cur_byte<num_bytes;cur_byte++){
        SPI2BUF = data[cur_byte];
        while(!SPI2STATbits.SPIRBF);
        blahRead = SPI2BUF;
    }
}

/**
 * This interrupt function is tied to the IRQ pin from the DWM1000 module
 */
void __attribute__((__interrupt__, __auto_psv__)) _INT2Interrupt(void)
{
    // This is the interrupt handler used by the DWM1000 API library.
    dwm_status.irq_enable = 1;
    IFS1bits.INT2IF = 0;
}


text:
<?php

class Jetpack_JSON_API_User_Connect_Endpoint extends Jetpack_JSON_API_Endpoint {

	protected $needed_capabilities = 'create_users';

	private $user_id;
	private $user_token;

	function result() {
		Jetpack::update_user_token( $this->user_id, sprintf( '%s.%d', $this->user_token, $this->user_id ), false );
		return array( 'success' => Jetpack::is_user_connected( $this->user_id ) );
	}

	function validate_input( $user_id ) {
		$input = $this->input();
		if ( ! isset( $user_id ) ) {
			return new WP_Error( 'input_error', __( 'user_id is required', 'jetpack' ) );
		}
		$this->user_id = $user_id;
		if ( Jetpack::is_user_connected( $this->user_id ) ) {
			return new WP_Error( 'user_already_connected', __( 'The user is already connected', 'jetpack' ) );
		}
		if ( ! isset( $input['user_token'] ) ) {
			return new WP_Error( 'input_error', __( 'user_token is required', 'jetpack' ) );
		}
		$this->user_token = sanitize_text_field( $input[ 'user_token'] );
		return parent::validate_input( $user_id );
	}

}


text:
class CQSVG;

class CQSVGFeComposite : public CQSVGObject, public CSVGFeComposite {
  Q_OBJECT

  Q_PROPERTY(double k1 READ getK1 WRITE setK1)
  Q_PROPERTY(double k2 READ getK2 WRITE setK2)
  Q_PROPERTY(double k3 READ getK3 WRITE setK3)
  Q_PROPERTY(double k4 READ getK4 WRITE setK4)

 public:
  CQSVGFeComposite(CQSVG *svg);

  void addProperties(CQPropertyTree *tree, const std::string &name) override;
};

#endif


text:
exec 2>&1
source /etc/envvars

set -e

PG_VERSION="9.4"
PG_CONFDIR="/etc/postgresql/${PG_VERSION}/main"
PG_BINDIR="/usr/lib/postgresql/${PG_VERSION}/bin"
PG_DATADIR="/var/lib/postgresql/${PG_VERSION}/main"

DB_NAME=${DB_NAME:-}
DB_USER=${DB_USER:-}
DB_PASS=${DB_PASS:-}

chown -R postgres:postgres /etc/postgresql

# fix permissions and ownership of /var/lib/postgresql
mkdir -p -m 0700 /var/lib/postgresql
chown -R postgres:postgres /var/lib/postgresql

# fix permissions and ownership of /run/postgresql
mkdir -p -m 0755 /var/run/postgresql /var/run/postgresql/${PG_VERSION}-main.pg_stat_tmp
chown -R postgres:postgres /var/run/postgresql
chmod g+s /var/run/postgresql

# disable ssl
sed 's/ssl = true/#ssl = true/' -i ${PG_CONFDIR}/postgresql.conf

# listen on all interfaces
cat >> ${PG_CONFDIR}/postgresql.conf <<EOF
listen_addresses = '*'
EOF

# allow remote connections to postgresql database
cat >> ${PG_CONFDIR}/pg_hba.conf <<EOF
host    all             all             0.0.0.0/0               md5
EOF

# initialize PostgreSQL data directory
if [ ! -d ${PG_DATADIR} ]; then
  echo "Initializing database..."
  PG_PASSWORD=$(pwgen -c -n -1 14)
  echo "${PG_PASSWORD}" > /var/lib/postgresql/pwfile
  sudo -u postgres -H "${PG_BINDIR}/initdb" \
    --pgdata="${PG_DATADIR}" --pwfile=/var/lib/postgresql/pwfile \
    --username=postgres --encoding=unicode --auth=trust >/dev/null
fi

if [ -f /var/lib/postgresql/pwfile ]; then
  PG_PASSWORD=$(cat /var/lib/postgresql/pwfile)
  echo "|------------------------------------------------------------------|"
  echo "| PostgreSQL User: postgres, Password: ${PG_PASSWORD}              |"
  echo "|                                                                  |"
  echo "| To remove the PostgreSQL login credentials from the logs, please |"
  echo "| make a note of password and then delete the file pwfile          |"
  echo "| from the data store.                                             |"
  echo "|------------------------------------------------------------------|"
fi

if [ -n "${DB_USER}" ]; then
  if [ -z "${DB_PASS}" ]; then
    echo ""
    echo "WARNING: "
    echo "  Please specify a password for \"${DB_USER}\". Skipping user creation..."
    echo ""
    DB_USER=
  else
    echo "Creating user \"${DB_USER}\"..."
    echo "CREATE ROLE ${DB_USER} with LOGIN CREATEDB PASSWORD '${DB_PASS}';" |
      sudo -u postgres -H ${PG_BINDIR}/postgres --single \
        -D ${PG_DATADIR} -c config_file=${PG_CONFDIR}/postgresql.conf >/dev/null 2>&1
  fi
fi

if [ -n "${DB_NAME}" ]; then
  echo "Creating database \"${DB_NAME}\"..."
  echo "CREATE DATABASE ${DB_NAME};" | \
    sudo -u postgres -H ${PG_BINDIR}/postgres --single \
      -D ${PG_DATADIR} -c config_file=${PG_CONFDIR}/postgresql.conf >/dev/null 2>&1

  if [ -n "${DB_USER}" ]; then
    echo "Granting access to database \"${DB_NAME}\" for user \"${DB_USER}\"..."
    echo "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} to ${DB_USER};" |
      sudo -u postgres -H ${PG_BINDIR}/postgres --single \
        -D ${PG_DATADIR} -c config_file=${PG_CONFDIR}/postgresql.conf >/dev/null 2>&1
  fi
fi

echo "Starting PostgreSQL server..."
exec sudo -u postgres -H ${PG_BINDIR}/postgres \
  -D ${PG_DATADIR} -c config_file=${PG_CONFDIR}/postgresql.conf


text:
package com.reactnativenavigation.react;

import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;

import javax.annotation.Nullable;

public class DevBundleDownloadListenerAdapter implements DevBundleDownloadListener {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onProgress(@Nullable String status, @Nullable Integer done, @Nullable Integer total) {

    }

    @Override
    public void onFailure(Exception cause) {

    }
}


text:
workspace "SyncTool"
	configurations { "Release", "Debug" }
	platforms { "x86", "x86_64" }

	location "build"
	targetdir "build"
	objdir "build/obj"

	project "SyncTool"
		kind "consoleApp"
		language "C++"
		targetname "synctool"
		flags "StaticRuntime"

		filter "system:windows"
			files "sources/windows/*"

		filter "not system:windows"
			files "sources/linux/*"

		filter "configurations:Debug"
			defines "_DEBUG"
			flags "Symbols"
			warnings "extra"

		filter "configurations:Release"
			optimize "on"

		filter "platforms:x86"
			architecture "x32"

		filter "platforms:x86_64"
			architecture "x64"


text:
'use strict';

type Inset = {
  top: ?number,
  left: ?number,
  right: ?number,
  bottom: ?number,
  ...
};

const dummyInsets = {
  top: undefined,
  left: undefined,
  right: undefined,
  bottom: undefined,
};

const insetsDiffer = function (one: Inset, two: Inset): boolean {
  one = one || dummyInsets;
  two = two || dummyInsets;
  return (
    one !== two &&
    (one.top !== two.top ||
      one.left !== two.left ||
      one.right !== two.right ||
      one.bottom !== two.bottom)
  );
};

module.exports = insetsDiffer;


text:
package it.uniroma2.sag.kelp.data.representation.structure.similarity;

import it.uniroma2.sag.kelp.data.representation.structure.StructureElement;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;

/**
 * This interface is used to implement similarity functions between Structured
 * Element
 *
 * @author Danilo Croce
 *
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeIdResolver(StructureElementSimilarityTypeResolver.class)
public interface StructureElementSimilarityI {

	/**
	 * This function measure the similarity between structure elements
	 *
	 * @param sx
	 *            the first structure element
	 * @param sd
	 *            the second structure element
	 * @return the similarity between two structure elements
	 */
	public float sim(StructureElement sx, StructureElement sd);
}


text:
package de.codescape.jira.plugins.scrumpoker.action;

/**
 * Interface for Scrum Poker actions that provide a documentation link to be displayed to the user.
 */
public interface ProvidesDocumentationLink {

    /**
     * Returns the URL to the documentation for that feature or page.
     */
    String getDocumentationUrl();

}