text:
'use strict';

(function() {
	// Tenants Controller Spec
	describe('Tenants Controller Tests', function() {
		// Initialize global variables
		var TenantsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Tenants controller.
			TenantsController = $controller('TenantsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Tenant object fetched from XHR', inject(function(Tenants) {
			// Create sample Tenant using the Tenants service
			var sampleTenant = new Tenants({
				name: 'New Tenant'
			});

			// Create a sample Tenants array that includes the new Tenant
			var sampleTenants = [sampleTenant];

			// Set GET response
			$httpBackend.expectGET('tenants').respond(sampleTenants);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.tenants).toEqualData(sampleTenants);
		}));

		it('$scope.findOne() should create an array with one Tenant object fetched from XHR using a tenantId URL parameter', inject(function(Tenants) {
			// Define a sample Tenant object
			var sampleTenant = new Tenants({
				name: 'New Tenant'
			});

			// Set the URL parameter
			$stateParams.tenantId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/tenants\/([0-9a-fA-F]{24})$/).respond(sampleTenant);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.tenant).toEqualData(sampleTenant);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Tenants) {
			// Create a sample Tenant object
			var sampleTenantPostData = new Tenants({
				name: 'New Tenant'
			});

			// Create a sample Tenant response
			var sampleTenantResponse = new Tenants({
				_id: '525cf20451979dea2c000001',
				name: 'New Tenant'
			});

			// Fixture mock form input values
			scope.name = 'New Tenant';

			// Set POST response
			$httpBackend.expectPOST('tenants', sampleTenantPostData).respond(sampleTenantResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Tenant was created
			expect($location.path()).toBe('/tenants/' + sampleTenantResponse._id);
		}));

		it('$scope.update() should update a valid Tenant', inject(function(Tenants) {
			// Define a sample Tenant put data
			var sampleTenantPutData = new Tenants({
				_id: '525cf20451979dea2c000001',
				name: 'New Tenant'
			});

			// Mock Tenant in scope
			scope.tenant = sampleTenantPutData;

			// Set PUT response
			$httpBackend.expectPUT(/tenants\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/tenants/' + sampleTenantPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid tenantId and remove the Tenant from the scope', inject(function(Tenants) {
			// Create new Tenant object
			var sampleTenant = new Tenants({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Tenants array and include the Tenant
			scope.tenants = [sampleTenant];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/tenants\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleTenant);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.tenants.length).toBe(0);
		}));
	});
}());


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banco.implementacion;

import banco.Cuenta;
import banco.CuentaDao;
import banco.ServicioCuenta;

/**
 *
 * @author jose maria
 */
public class ServicioCuentaImpl implements ServicioCuenta {

    private CuentaDao dao;

    public void setCuentaDao(CuentaDao dao) {
        this.dao = dao;
    }

    public Boolean concederPrestamo(Double cantidad, Long idCuenta) {
        Cuenta cuenta = dao.encontrarCuentaPorId(idCuenta);
        Integer periodoDeCalculoEstandar = 3;
        Double saldoMedio = cuenta.saldoMedio(periodoDeCalculoEstandar);
        return saldoMedio < cantidad ? false : true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace chr
{
  namespace gl
  {
    namespace draw
    {
      class Torus
      {
      public:
        Torus& setFrontFace(GLenum mode);
        Torus& setColor(const glm::vec4 &color);
        Torus& setColor(float r, float g, float b, float a);
        Torus& setSliceCount(int count);
        Torus& setLoopCount(int count);
        Torus& setInnerRadius(float radius);
        Torus& setOuterRadius(float radius);

        template<int V = XYZ, typename I = GLuint>
        void append(IndexedVertexBatch<V,I> &batch, const Matrix &matrix) const;

      protected:
        GLenum frontFace = chr::CCW;
        glm::vec4 color = {1, 1, 1, 1};
        int sliceCount = 5;
        int loopCount = 15;
        float innerRadius = 1;
        float outerRadius = 4;
      };
    }
  }
}


text:
import linkifyIt from 'linkify-it';
import tlds from 'tlds';

const linkify = linkifyIt();
linkify.tlds(tlds);

// Gets all the links in the text, and returns them via the callback
const linkStrategy = (contentBlock: Object, callback: Function) => {
  const links = linkify.match(contentBlock.get('text'));
  if (typeof links !== 'undefined' && links !== null) {
    for (let i = 0; i < links.length; i += 1) {
      callback(links[i].index, links[i].lastIndex);
    }
  }
};

export default linkStrategy;


text:
<!--
    The <highlightbar-sk> custom element declaration.

    Attributes:
      key:  The key of the highlighted trace.
      value: The value of the highlighted point on the trace.

    Methods:
      None.

    Events:
      None.
-->
<polymer-element name="highlightbar-sk" attributes="key value">
  <template>
    <style type="text/css" media="screen">
      #value {
        width: 6em;
        margin-left: 0.6em;
      }
    </style>
    <div horizontal layout>
      <paper-input flex disabled value="{{key}}" label="Highlighted Trace ID" id="name"></paper-input>
      <paper-input disabled value="{{value}}" label="Value" id="value"> </paper-input>
    </div>
  </template>
  <script>
    Polymer({
      ready: function() {
        this.key = this.key || '';
        this.value = this.value || '';
      },
    });
  </script>
</polymer-element>


text:
<?php

namespace Bitpay;

/**
 * Class PayoutInstruction
 * @package Bitpay
 */
class PayoutInstruction implements PayoutInstructionInterface
{
    /**
     * A transaction is unpaid when the payout in bitcoin has not yet occured.
     */
    const STATUS_UNPAID = 'unpaid';

    /**
     * A transaction is marked as paid once the payroll is complete and bitcoins are
     * sent to the recipient
     */
    const STATUS_PAID = 'paid';

    /**
     * @var string
     */
    protected $id;

    /**
     * @var array
     */
    protected $btc;

    /**
     * @var string
     */
    protected $label;

    /**
     * @var string
     */
    protected $address;

    /**
     * @var float
     */
    protected $amount;

    /**
     * @var string
     */
    protected $status;

    /**
     * @var array
     */
    protected $transactions = array();

    public function __construct()
    {
        $this->transactions = array();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the Bitpay ID for this payout instruction
     *
     * @param $id
     * @return $this
     */
    public function setId($id)
    {
        if (!empty($id)) {
            $this->id = trim($id);
        }
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Set the employers label for this instruction.
     * @param $label
     * @return $this
     */
    public function setLabel($label)
    {
        if (!empty($label)) {
            $this->label = trim($label);
        }

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * Set the bitcoin address for this instruction.
     * @param $address
     * @return $this
     */
    public function setAddress($address)
    {
        if (!empty($address)) {
            $this->address = trim($address);
        }

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * Set the amount for this instruction.
     * @param $amount
     * @return $this
     */
    public function setAmount($amount)
    {
        if (!empty($amount)) {
            $this->amount = $amount;
        }

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getBtc()
    {
        return $this->btc;
    }

    /**
     * Set BTC array (available once rates are set)
     * @param $btc
     * @return $this
     */
    public function setBtc($btc)
    {
        if (!empty($btc) && is_array($btc)) {
            $this->btc = $btc;
        }

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set the status for this instruction
     * @param $status
     * @return $this
     */
    public function setStatus($status)
    {
        if (!empty($status) && ctype_print($status)) {
            $this->status = trim($status);
        }

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getTransactions()
    {
        return $this->transactions;
    }

    /**
     * Add payout transaction to the
     * @param PayoutTransactionInterface $transaction
     * @return $this
     */
    public function addTransaction(PayoutTransactionInterface $transaction)
    {
        if (!empty($transaction)) {
            $this->transactions[] = $transaction;
        }

        return $this;
    }
}


text:
cert-manager is a Kubernetes addon to automate the management and issuance of
TLS certificates from various issuing sources.

It will ensure certificates are valid and up to date periodically, and attempt
to renew certificates at an appropriate time before expiry.

## Prerequisites

- Kubernetes 1.7+

## Installing the Chart

Full installation instructions, including details on how to configure extra
functionality in cert-manager can be found in the [getting started docs](https://cert-manager.readthedocs.io/en/latest/getting-started/).

To install the chart with the release name `my-release`:

```console
$ helm install --name my-release stable/cert-manager
```

In order to begin issuing certificates, you will need to set up a ClusterIssuer
or Issuer resource (for example, by creating a 'letsencrypt-staging' issuer).

More information on the different types of issuers and how to configure them
can be found in our documentation:

https://cert-manager.readthedocs.io/en/latest/reference/issuers.html

For information on how to configure cert-manager to automatically provision
Certificates for Ingress resources, take a look at the `ingress-shim`
documentation:

https://cert-manager.readthedocs.io/en/latest/reference/ingress-shim.html

> **Tip**: List all releases using `helm list`

## Uninstalling the Chart

To uninstall/delete the `my-release` deployment:

```console
$ helm delete my-release
```

The command removes all the Kubernetes components associated with the chart and deletes the release.

## Configuration

The following table lists the configurable parameters of the cert-manager chart and their default values.

| Parameter | Description | Default |
| --------- | ----------- | ------- |
| `image.repository` | Image repository | `quay.io/jetstack/cert-manager-controller` |
| `image.tag` | Image tag | `v0.4.0` |
| `image.pullPolicy` | Image pull policy | `IfNotPresent` |
| `replicaCount`  | Number of cert-manager replicas  | `1` |
| `createCustomResource` | Create CRD/TPR with this release | `true` |
| `clusterResourceNamespace` | Override the namespace used to store DNS provider credentials etc. for ClusterIssuer resources | Same namespace as cert-manager pod
| `leaderElection.Namespace` | Override the namespace used to store the ConfigMap for leader election | Same namespace as cert-manager pod
| `certificateResourceShortNames` | Custom aliases for Certificate CRD | `["cert", "certs"]` |
| `extraArgs` | Optional flags for cert-manager | `[]` |
| `extraEnv` | Optional environment variables for cert-manager | `[]` |
| `rbac.create` | If `true`, create and use RBAC resources | `true` |
| `serviceAccount.create` | If `true`, create a new service account | `true` |
| `serviceAccount.name` | Service account to be used. If not set and `serviceAccount.create` is `true`, a name is generated using the fullname template |  |
| `resources` | CPU/memory resource requests/limits | `requests: {cpu: 10m, memory: 32Mi}` |
| `nodeSelector` | Node labels for pod assignment | `{}` |
| `affinity` | Node affinity for pod assignment | `{}` |
| `tolerations` | Node tolerations for pod assignment | `[]` |
| `ingressShim.defaultIssuerName` | Optional default issuer to use for ingress resources |  |
| `ingressShim.defaultIssuerKind` | Optional default issuer kind to use for ingress resources |  |
| `ingressShim.defaultACMEChallengeType` | Optional default challenge type to use for ingresses using ACME issuers |  |
| `ingressShim.defaultACMEDNS01ChallengeProvider` | Optional default DNS01 challenge provider to use for ingresses using ACME issuers with DNS01 |  |
| `podAnnotations` | Annotations to add to the cert-manager pod | `{}` |
| `podDnsPolicy` | Optional cert-manager pod [DNS policy](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pods-dns-policy) |  |
| `podDnsConfig` | Optional cert-manager pod [DNS configurations](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pods-dns-config) |  |
| `podLabels` | Labels to add to the cert-manager pod | `{}` |
| `http_proxy` | Value of the `HTTP_PROXY` environment variable in the cert-manager pod | |
| `https_proxy` | Value of the `HTTPS_PROXY` environment variable in the cert-manager pod | |
| `no_proxy` | Value of the `NO_PROXY` environment variable in the cert-manager pod | |

Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`.

Alternatively, a YAML file that specifies the values for the above parameters can be provided while installing the chart. For example,

```console
$ helm install --name my-release -f values.yaml .
```
> **Tip**: You can use the default [values.yaml](values.yaml)

## Contributing

This chart is maintained at [github.com/jetstack/cert-manager](https://github.com/jetstack/cert-manager/tree/master/contrib/charts/cert-manager).


text:
#ifndef GEO_EARTH_ENTERPRISE_SRC_FUSION_AUTOINGEST_ASSETVERSION_H_
#define GEO_EARTH_ENTERPRISE_SRC_FUSION_AUTOINGEST_ASSETVERSION_H_

#include <algorithm>
#include "fusion/autoingest/AssetVersionRef.h"
#include "fusion/autoingest/.idl/AssetStorage.h"
#include "fusion/autoingest/AssetHandle.h"
#include "fusion/autoingest/MiscConfig.h"
#include "common/khFileUtils.h"
#include "StorageManager.h"
#include "CacheSizeCalculations.h"

// Used by child classes of AssetVersionImpl
class StateChangeException : public khException {
 public:
  const std::string location;
  StateChangeException(const std::string & msg, const std::string & loc) :
    khException(msg), location(loc) {}
};

// Helper structs for passing data about input and child states.
struct WaitingFor {
  std::uint32_t inputs;
  std::uint32_t children;
};

struct InputAndChildStateData {
  AssetDefs::State stateByInputs;
  AssetDefs::State stateByChildren;
  bool blockersAreOffline;
  WaitingFor waitingFor;
};

/******************************************************************************
 ***  AssetVersionImpl
 ***
 ***  Implementation for the AssetVersion base class.
 ***
 ***  Code should NOT use this (or any other *Impl) class directly. Instead
 ***  it should use the AssetVersion and derived AssetVersion
 ***  (RasterBlendAssetVersion, MosaicAssetVersion) handle classes.
 ***
 ***  AssetVersion ver = asset->CurrVersionRef();
 ***  if (ver) {
 ***     ... = ver->config.layers.size();
 ***  }
 ******************************************************************************/
class AssetVersionImpl : public AssetVersionStorage, public StorageManaged {
  friend class AssetImpl;
  friend class AssetHandle_<AssetVersionImpl>;

  // Illegal to copy an AssetVersionImpl
  AssetVersionImpl(const AssetVersionImpl&) = delete;
  AssetVersionImpl& operator=(const AssetVersionImpl&) = delete;
  AssetVersionImpl(const AssetVersionImpl&&) = delete;
  AssetVersionImpl& operator=(const AssetVersionImpl&&) = delete;

 public:
  static std::string GetPlaceholderAssetRegistryKey() { return "SourceAssetVersion"; }
  using Base = AssetVersionStorage;
  std::string XMLFilename() const { return XMLFilename(GetRef()); }
  std::string WorkingDir(void) const { return WorkingDir(GetRef()); }
  std::string WorkingFileRef(const std::string &fname) const {
    return WorkingDir() + fname;
  }

  virtual std::string GetName() const {   // Returns the name of the asset version, e.g., "CombinedRPAssetVersion"
    assert(false);
    return "";
  }

  // Note for future development: It would be good to change SerializeConfig to something like
  // GetConfig that would fill out a list of key/value pairs instead of dealing with XML directly
  virtual void SerializeConfig(khxml::DOMElement*) const {
    assert(false);
  }

  std::string WorkingFilename(const std::string &fname) const {
    return AssetDefs::AssetPathToFilename(WorkingFileRef(fname));
  }

 protected:
  // used by my intermediate derived classes since their calls to
  // my constructor will never actualy be used
  AssetVersionImpl(void) = default;

  AssetVersionImpl(const AssetVersionStorage &storage)
      : AssetVersionStorage(storage) { }

 public:
  virtual std::string PluginName(void) const = 0;
  virtual ~AssetVersionImpl(void) { }
  virtual bool IsLeaf(void) const { return false; }
  virtual std::string Logfile(void) const {
    std::string logfile = LogFilename(GetRef());
    return (!AssetDefs::Finished(state) || khExists(logfile)) ?
      logfile : std::string();
  }
  static std::string LogFilename(const AssetVersionRef &ref) {
    return AssetDefs::AssetPathToFilename(WorkingDir(ref) + "logfile");
  }

  bool CanRebuild(void) const {
    return ((state & (AssetDefs::Failed | AssetDefs::Canceled)) &&
            (subtype != "Source"));
  }
  bool CanCancel(void) const {
    return ((state & (AssetDefs::Waiting | AssetDefs::Queued |
                      AssetDefs::InProgress | AssetDefs::Blocked)) &&
            (subtype != "Source"));
  }
  bool CanClean(void) const {
    return (AssetDefs::CanOffline(state) && (subtype != "Source"));
  }
  bool CanSetBad(void) const {
    return (state == AssetDefs::Succeeded);
  }
  bool CanClearBad(void) const {
    return (state == AssetDefs::Bad);
  }

  virtual bool InputStatesAffectMyState(AssetDefs::State stateByInputs, bool blockedByOfflineInputs) const {assert(false); return true;}
  const SharedString & GetRef(void) const { return name; }
  std::string GetAssetRef(void) const {
    AssetVersionRef verref(name);
    return verref.AssetRef();
  }

  // determine amount of memory used by an AssetVersionImpl
  virtual std::uint64_t GetHeapUsage() const {
    return ::GetHeapUsage(name)
    + ::GetHeapUsage(type)
    + ::GetHeapUsage(subtype)
    + ::GetHeapUsage(state)
    + ::GetHeapUsage(progress)
    + ::GetHeapUsage(locked)
    + ::GetHeapUsage(inputs)
    + ::GetHeapUsage(children)
    + ::GetHeapUsage(parents)
    + ::GetHeapUsage(listeners)
    + ::GetHeapUsage(outfiles)
    + ::GetHeapUsage(meta)
    + ::GetHeapUsage(beginTime)
    + ::GetHeapUsage(progressTime)
    + ::GetHeapUsage(endTime)
    + ::GetHeapUsage(taskid)
    + ::GetHeapUsage(timestamp)
    + ::GetHeapUsage(filesize);
  }
  template <class outIter>
  outIter GetInputs(outIter oi) const {
    for (const auto &i : inputs) {
      oi++ = i;
    }
    return oi;
  }

  void GetInputFilenames(std::vector<std::string> &out) const;
  virtual void GetOutputFilenames(std::vector<std::string> &out) const = 0;
  virtual std::string GetOutputFilename(unsigned int i) const = 0;
  virtual void AfterLoad(void) { }
  virtual void DependentChildren(std::vector<SharedString> &) const {
    // No-op in base class. Sub-classes will override this
    // with children that must be operated on similarly to the
    // parent asset (ex: parent is canceled, so these children
    // must also be canceled.
  }
  virtual AssetDefs::State CalcStateByInputsAndChildren(const InputAndChildStateData &) const {
    assert(false); // Can only call from sub-classes
    return AssetDefs::Bad;
  }
  virtual AssetDefs::State OnStateChange(AssetDefs::State, AssetDefs::State) {
    assert(false);
    return AssetDefs::Bad;
  }
  virtual void WriteFatalLogfile(const std::string &, const std::string &) const throw() {
    assert(false);
  }
  virtual void ResetOutFiles(const std::vector<std::string> &) {
    assert(false);
  }
  virtual bool RecalcState(WaitingFor &) const {
    assert(false);
    return false;
  }
  virtual void SetAndPropagateState(AssetDefs::State) {
    assert(false);
  }

  // static helpers
  static std::string WorkingDir(const AssetVersionRef &ref);
  static std::string XMLFilename(const AssetVersionRef &ref) {
    return AssetDefs::AssetPathToFilename(WorkingDir(ref) +
                                          "khassetver.xml");
  }
  static std::string Filename(const std::string & ref) {
    std::string boundref = AssetVersionRef::Bind(ref);
    AssetVersionRef boundVerRef(boundref);
    return AssetVersionImpl::XMLFilename(boundVerRef);
  }
  static std::string Key(const SharedString & ref) {
    return AssetVersionRef::Bind(ref);
  }
  static bool ValidRef(const SharedString & ref) {
    if (ref.empty())
      return false;

    // bind the ref
    SharedString boundRef = AssetVersionRef::Bind(ref);
    AssetVersionRef boundVerRef(boundRef);

    if (boundVerRef.Version() == "0")
      return false;
    return true;
  }

  // Gets the database path, type and ref string for the given dbname.
  // This is useful for distinguishing specific types of databases and
  // dealing with short db names.
  // dbname: input database name. May be:
  //   1. short without version (e.g Databases/ExampleMap_Merc)
  //   2. short with version    (e.g Databases/ExampleMap_Merc?version=7)
  //   3. long (e.g /gevol/assets/Databases/
  //                ExampleMap_Merc.kmmdatabase/mapdb.kda/ver007/mapdb)
  // gedb_path: the output path of the gedb directory for the database.
  // db_type: the output string type of the db. One of:
  //          kMapDatabaseSubtype, kMercatorMapDatabaseSubtype, or
  //          kDatabaseSubtype
  // db_ref: the output asset version ref to the database
  // Returns whether it succeeded.
  // Warning: Use this only for Fusion side code and not for Server side code,
  //          because this depends on ASSET_ROOT which is set only on Fusion.
  static bool SimpleGetGedbPathAndType(const std::string& dbname,
                                       std::string* gedb_path,
                                       std::string* db_type,
                                       std::string* db_ref);

  static bool SimpleGetGedbPath(const std::string& dbname,
                                std::string* gedb_path) {
    std::string db_type;
    if (khIsAbspath(dbname)) {
      *gedb_path = khNormalizeDir(dbname, false);
      return khIsAbsoluteDbName(*gedb_path, &db_type);
    }
    std::string db_ref;
    return SimpleGetGedbPathAndType(dbname, gedb_path, &db_type, &db_ref);
  }

  // Like above but does additional checks to make sure db is suitable for
  // publishing. (e.g. it's not an old/unsupported format)
  static bool GetGedbPathAndType(const std::string& dbname,
                                 std::string* gedb_path,
                                 std::string* db_type,
                                 std::string* db_ref);

  static bool GetGedbPath(const std::string& dbname, std::string* gedb_path) {
    std::string db_type;
    if (khIsAbspath(dbname)) {
      *gedb_path = khNormalizeDir(dbname, false);
      return khIsAbsoluteDbName(*gedb_path, &db_type);
    }
    std::string db_ref;
    return GetGedbPathAndType(dbname, gedb_path, &db_type, &db_ref);
  }
};

// ****************************************************************************
// ***  AssetVersion & its specializations
// ****************************************************************************
typedef AssetHandle_<AssetVersionImpl> AssetVersion;

template <>
inline StorageManager<AssetVersionImpl>&
AssetVersion::storageManager(void)
{
  static StorageManager<AssetVersionImpl> storageManager(
      MiscConfig::Instance().VersionCacheSize, MiscConfig::Instance().LimitMemoryUtilization, MiscConfig::Instance().MaxVersionCacheMemorySize, MiscConfig::Instance().PrunePercentage, "version");
  return storageManager;
}

template <>
inline bool AssetVersion::Valid(void) const {
  if (handle) {
    return handle->type != AssetDefs::Invalid;
  } else {

    if (!AssetVersionImpl::ValidRef(ref))
      return false;

    try {
      DoBind(true /* check file & maybe not throw */, true /* add to cache */);
    } catch (...) {
      return false;
    }
    return handle && (handle->type != AssetDefs::Invalid);
  }
}

// ****************************************************************************
// ***  LeafAssetVersionImpl
// ****************************************************************************
class LeafAssetVersionImpl : public virtual AssetVersionImpl {
 protected:
  // Since I inherit virtually from AssetVersionImpl, all of my derived
  // classes will need to initialize it directly
  // This means that there's nothing for me to do
  LeafAssetVersionImpl(void) { }

 public:
  virtual bool IsLeaf(void) const { return true; }

  virtual void GetOutputFilenames(std::vector<std::string> &out) const {
    for (std::vector<std::string>::const_iterator o = outfiles.begin();
         o != outfiles.end(); ++o) {
      out.push_back(AssetDefs::AssetPathToFilename(*o));
    }
  }
  std::string GetOutputFilename(unsigned int i) const {
    if (i < outfiles.size()) {
      return AssetDefs::AssetPathToFilename(outfiles[i]);
    } else {
      return std::string();
    }
  }
};

// ****************************************************************************
// ***  CompositeAssetVersionImpl
// ****************************************************************************
class CompositeAssetVersionImpl : public virtual AssetVersionImpl {
 protected:
  // Since I inherit virtually from AssetVersionImpl, all of my derived
  // classes will need to initialize it directly
  // This means that there's nothing for me to do
  CompositeAssetVersionImpl(void) { }

 public:
  virtual std::string Logfile(void) const {
    // composite assets can only have a logfile if the plugin threw an
    // exception during the DelayedBuildChildren. So don't bother
    // stating the filesystem to look for a logfile unless we're failed.
    std::string logfile = LogFilename(GetRef());
    return ((state == AssetDefs::Failed) && khExists(logfile)) ?
                    logfile : std::string();
  }

  virtual void GetOutputFilenames(std::vector<std::string> &out) const;
  std::string GetOutputFilename(unsigned int i) const;
};

inline std::uint64_t GetHeapUsage(const AssetVersionImpl &version) {
  return version.GetHeapUsage();
}

#endif  // GEO_EARTH_ENTERPRISE_SRC_FUSION_AUTOINGEST_ASSETVERSION_H_


text:
export
    av_fifo_alloc,
    av_fifo_alloc_array,
    av_fifo_free,
    av_fifo_freep,
    av_fifo_reset,
    av_fifo_size,
    av_fifo_space,
    av_fifo_generic_peek_at,
    av_fifo_generic_peek,
    av_fifo_generic_read,
    av_fifo_generic_write,
    av_fifo_realloc2,
    av_fifo_grow,
    av_fifo_drain,
    av_fifo_peek2

function av_fifo_alloc(size::Integer)
    ccall((:av_fifo_alloc,libavutil),Ptr{AVFifoBuffer},(UInt32,),size)
end

function av_fifo_alloc_array(nmemb::Csize_t,size::Csize_t)
    ccall((:av_fifo_alloc_array,libavutil),Ptr{AVFifoBuffer},(Csize_t,Csize_t),nmemb,size)
end

function av_fifo_free(f)
    ccall((:av_fifo_free,libavutil),Void,(Ptr{AVFifoBuffer},),f)
end

function av_fifo_freep(f)
    ccall((:av_fifo_freep,libavutil),Void,(Ptr{Ptr{AVFifoBuffer}},),f)
end

function av_fifo_reset(f)
    ccall((:av_fifo_reset,libavutil),Void,(Ptr{AVFifoBuffer},),f)
end

function av_fifo_size(f)
    ccall((:av_fifo_size,libavutil),Cint,(Ptr{AVFifoBuffer},),f)
end

function av_fifo_space(f)
    ccall((:av_fifo_space,libavutil),Cint,(Ptr{AVFifoBuffer},),f)
end

function av_fifo_generic_peek_at(f,dest,offset::Integer,buf_size::Integer,func)
    ccall((:av_fifo_generic_peek_at,libavutil),Cint,(Ptr{AVFifoBuffer},Ptr{Void},Cint,Cint,Ptr{Void}),f,dest,offset,buf_size,func)
end

function av_fifo_generic_peek(f,dest,buf_size::Integer,func)
    ccall((:av_fifo_generic_peek,libavutil),Cint,(Ptr{AVFifoBuffer},Ptr{Void},Cint,Ptr{Void}),f,dest,buf_size,func)
end

function av_fifo_generic_read(f,dest,buf_size::Integer,func)
    ccall((:av_fifo_generic_read,libavutil),Cint,(Ptr{AVFifoBuffer},Ptr{Void},Cint,Ptr{Void}),f,dest,buf_size,func)
end

function av_fifo_generic_write(f,src,size::Integer,func)
    ccall((:av_fifo_generic_write,libavutil),Cint,(Ptr{AVFifoBuffer},Ptr{Void},Cint,Ptr{Void}),f,src,size,func)
end

function av_fifo_realloc2(f,size::Integer)
    ccall((:av_fifo_realloc2,libavutil),Cint,(Ptr{AVFifoBuffer},UInt32),f,size)
end

function av_fifo_grow(f,additional_space::Integer)
    ccall((:av_fifo_grow,libavutil),Cint,(Ptr{AVFifoBuffer},UInt32),f,additional_space)
end

function av_fifo_drain(f,size::Integer)
    ccall((:av_fifo_drain,libavutil),Void,(Ptr{AVFifoBuffer},Cint),f,size)
end

function av_fifo_peek2(f,offs::Integer)
    ccall((:av_fifo_peek2,libavutil),Ptr{UInt8},(Ptr{AVFifoBuffer},Cint),f,offs)
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function(){
    //Carga la partialView de registración en el modal PopUp
    /* $('#btnModalRegistracion').click(function(){
        $.ajax({
            type    : 'POST',
            url     : $('#urlRegistracionView').val(),
            cache   : false,
            success : function(data){
                if(data){
                    $('#modalLabel').text('');
                    $('#form-content').html(data);
                }
            }
        });
    });          */

    // Carga la partialView de login en el modal PoUp
    $('#btnModalLogin').click(function(){
        $.ajax({
            type    : 'POST',
            url     : $('#urlLoginView').val(),
            cache   : false,
            success : function(data){
                if(data){
                    $('#modalLabel').text('Ingresar a Músicos al Toque');
                        $('#form-content').html(data);
               }
            }
        });
    });

    $('#btnCerrarSession').click(function(){
        $.ajax({
            type    : 'POST',
            url     : $("#urlCerrarSession").val(),
            cache   : false,
            success : function(data){
                window.location.href = $('#urlHome').val();
            }
        });
    });
});


text:
package de.fuberlin.wiwiss.d2rq.algebra;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.fuberlin.wiwiss.d2rq.engine.BindingMaker;
import de.fuberlin.wiwiss.d2rq.expr.Disjunction;
import de.fuberlin.wiwiss.d2rq.expr.Expression;

/**
 * A group of {@link Relation}s that can be combined into a single
 * relation without changing the semantics of {@link de.fuberlin.wiwiss.d2rq.nodes.NodeMaker}s.
 *
 * Relations can be combined if they access the same database and
 * they contain exactly the same joins. If they both contain no joins,
 * they must contain only columns from the same table.
 *
 * Relations that just differ in their WHERE clause (condition)
 * can still be combined, but require that the new relation has the disjunction
 * (OR) of all conditions as a WHERE clause, and
 * the individual conditions must be added to the SELECT list
 * (as {@link ProjectionSpec}s) so that bindings are generated only
 * if that clause is TRUE
 *
 * TODO: Should check if the BindingMaker already has a condition?
 *
 * @author Richard Cyganiak (richard@cyganiak.de)
 */
public class CompatibleRelationGroup {

	public static Collection<CompatibleRelationGroup> groupNodeRelations(
			Collection<? extends NodeRelation> nodeRelations) {
		Collection<CompatibleRelationGroup> result = new ArrayList<CompatibleRelationGroup>();
		for (NodeRelation nodeRelation: nodeRelations) {
			addNodeRelation(nodeRelation, result);
		}
		return result;
	}

	private static void addNodeRelation(NodeRelation nodeRelation,
			Collection<CompatibleRelationGroup> groups) {
		for (CompatibleRelationGroup group: groups) {
			if (group.isCompatible(nodeRelation.baseRelation())) {
				group.addBindingMaker(
						nodeRelation.baseRelation(), BindingMaker.createFor(nodeRelation));
				return;
			}
		}
		CompatibleRelationGroup newGroup = new CompatibleRelationGroup();
		newGroup.addBindingMaker(
				nodeRelation.baseRelation(), BindingMaker.createFor(nodeRelation));
		groups.add(newGroup);
	}

	private final List<BiningMakerAndCondition> makers = new ArrayList<BiningMakerAndCondition>();
	private Relation firstBaseRelation = null;
	private boolean differentConditions = false;
	private boolean differentSoftConditions = false;
	private boolean allUnique = true;
	private int relationCounter = 0;
	private Set<ProjectionSpec> projections = new HashSet<ProjectionSpec>();
	private List<OrderSpec> longestOrderSpecs = new ArrayList<OrderSpec>();

	public boolean isCompatible(Relation otherRelation) {
		if (firstBaseRelation == null) {
			throw new IllegalStateException();
		}
		if (firstBaseRelation.database()==null || !firstBaseRelation.database().equals(otherRelation.database())) {
			return false;
		}
		if (!firstBaseRelation.joinConditions().equals(otherRelation.joinConditions())) {
			return false;
		}
		Set<RelationName> firstTables = firstBaseRelation.tables();
		Set<RelationName> secondTables = otherRelation.tables();
		if (!firstTables.equals(secondTables)) {
			return false;
		}
		for (RelationName tableName: firstTables) {
			if (!firstBaseRelation.aliases().originalOf(tableName).equals(
					otherRelation.aliases().originalOf(tableName))) {
				return false;
			}
		}
		if (!firstBaseRelation.projections().equals(otherRelation.projections())) {
			// Uniqueness doesn't matter if we project the same columns
			if (!firstBaseRelation.isUnique() || !otherRelation.isUnique()) {
				return false;
			}
		}
		// Compatible ordering?
		for (int i = 0; i < Math.min(longestOrderSpecs.size(), otherRelation.orderSpecs().size()); i++) {
			if (!longestOrderSpecs.get(i).equals(otherRelation.orderSpecs().get(i))) return false;
		}
		for (int i = longestOrderSpecs.size(); i < otherRelation.orderSpecs().size(); i++) {
			longestOrderSpecs.add(otherRelation.orderSpecs().get(i));
		}
		return true;
	}

	public void addRelation(Relation relation) {
		if (firstBaseRelation == null) {
			firstBaseRelation = relation;
			longestOrderSpecs.addAll(firstBaseRelation.orderSpecs());
		}
		if (!relation.condition().equals(firstBaseRelation.condition())) {
			differentConditions = true;
		}
		if (!relation.softCondition().equals(firstBaseRelation.softCondition())) {
			differentSoftConditions = true;
		}
		projections.addAll(relation.projections());
		allUnique = allUnique && relation.isUnique();
		relationCounter++;
	}

	public void addBindingMaker(Relation relation, BindingMaker bindingMaker) {
		addRelation(relation);
		makers.add(new BiningMakerAndCondition(bindingMaker,
				relation.condition(), relation.softCondition()));
	}

	public Relation baseRelation() {
		if (relationCounter == 1) {
			// Just one relation, return it unchanged
			return firstBaseRelation;
		}
		if (differentConditions) {
			// Multiple relations and different conditions, add the conditions
			// as boolean clauses to the SELECT list, and add a new condition
			// consisting of the disjunction (OR) of all conditions
			Set<Expression> allConditions = new HashSet<Expression>();
			Set<ProjectionSpec> projectionsAndConditions = new HashSet<ProjectionSpec>(projections);
			for (BiningMakerAndCondition maker: makers) {
				// If relations A and B have different soft conditions, we want to end up
				// with: (A.cond && A.soft) || (B.cond && B.soft)
				// This is more restrictive than the simpler alternative
				// (A.cond || B.cond) && (A.soft || B.soft), but requires turning
				// the soft conditions into hard conditions.
				allConditions.add(maker.conditionWithSoft());
				if (!maker.condition.isTrue()) {
					projectionsAndConditions.add(maker.conditionProjection());
				}
			}
			if (allConditions.isEmpty()) {
				allConditions.add(Expression.TRUE);
			}
			Disjunction.create(allConditions);
			return new RelationImpl(firstBaseRelation.database(),
					firstBaseRelation.aliases(),
					Disjunction.create(allConditions),
					Expression.TRUE,
					firstBaseRelation.joinConditions(),
					projectionsAndConditions,
					allUnique, longestOrderSpecs, firstBaseRelation.limit(), firstBaseRelation.limitInverse());
		} else {
			// Multiple relations with same condition
			Expression softCondition = firstBaseRelation.softCondition();
			if (differentSoftConditions) {
				Set<Expression> allSoftConditions = new HashSet<Expression>();
				for (BiningMakerAndCondition maker: makers) {
					allSoftConditions.add(maker.softCondition);
				}
				if (allSoftConditions.isEmpty()) {
					allSoftConditions.add(Expression.TRUE);
				}
				softCondition = Disjunction.create(allSoftConditions);
			}
			// return a new relation with all the projections
			return new RelationImpl(firstBaseRelation.database(),
					firstBaseRelation.aliases(),
					firstBaseRelation.condition(),
					softCondition,
					firstBaseRelation.joinConditions(),
					projections,
					allUnique, longestOrderSpecs, firstBaseRelation.limit(), firstBaseRelation.limitInverse());
		}
	}

	public Collection<BindingMaker> bindingMakers() {
		Collection<BindingMaker> results = new ArrayList<BindingMaker>();
		if (relationCounter == 1 || !differentConditions) {
			// Return list of unchanged triple makers
			for (BiningMakerAndCondition maker: makers) {
				if (maker.bMaker == null) continue;
				results.add(maker.bMaker);
			}
		} else {
			// Make binding makers conditional on the added boolean condition
			for (BiningMakerAndCondition maker: makers) {
				if (maker.bMaker == null) continue;
				if (maker.condition.isTrue()) {
					results.add(maker.bMaker);
				} else {
					results.add(maker.makeConditional());
				}
			}
		}
		return results;
	}

	private class BiningMakerAndCondition {
		private final BindingMaker bMaker;
		private final Expression condition;
		private final Expression softCondition;
		BiningMakerAndCondition(BindingMaker maker, Expression condition,
				Expression softCondition) {
			this.bMaker = maker;
			this.condition = condition;
			this.softCondition = softCondition;
		}
		private ProjectionSpec conditionProjection() {
			return new ExpressionProjectionSpec(
					firstBaseRelation.database().vendor().booleanExpressionToSimpleExpression(condition));
		}
		private BindingMaker makeConditional() {
			return bMaker.makeConditional(conditionProjection());
		}
		private Expression conditionWithSoft() {
			return condition.and(softCondition);
		}
	}
}


text:
namespace optimo {
namespace solvers {
/// Implements the Broyden–Fletcher–Goldfarb–Shanno algorithm

/// Implementation of the Broyden–Fletcher–Goldfarb–Shanno quasi newton
/// algorithm. This algorithm solves unconstrained problems. The implementation
/// can be summarized as follows:
/// 1. Compute a descent direction by computing
/// \f[
///  \mathbf{p}_k = -H_k \nabla f_0(\mathbf{x}_k)
/// \f]
/// 2. Compute a step size \f$ t_k \f$by a line search (Backtracking)
/// 3. Update: \f$ \mathbf{x}_{k+1} = \mathbf{x}_k + t_k \mathbf{p}_k \f$
/// 4. Set \f$ \mathbf{s}_k = t_k \mathbf{p}_k \f$
/// 5. Compute
/// \f[
/// \mathbf{y}_k = \nabla f_0(\mathbf{x}_{k+1}) - \nabla f_0(\mathbf{x}_k)
/// \f]
/// 4. Compute \f$ H_{k+1} \f$ as follows:
/// \f[
/// H_{k+1} = H_k + T_1 - T_2
/// \f]
/// where
/// \f{eqnarray*}{
/// T_1 &=& \alpha \frac{\mathbf{s}_k \mathbf{s}_k^T}{\beta^2} \\
/// T_2 &=&
///  \frac{H_k \mathbf{y}_k \mathbf{s}_k^T + \mathbf{s}_k \mathbf{y}_k^T H_k}
///   {\beta} \\
/// \alpha & = & \mathbf{s}_k^T \mathbf{y}_k + \mathbf{y}_k^T H_k\mathbf{y}_k \\
/// \beta & = & \mathbf{s}_k^T \mathbf{y} \\
/// \f}
/// and \f$ f_0 \f$ is the objective function. Further information can be found
/// in the Wikipedia
/// <a href="http://en.wikipedia.org/wiki/Broyden–Fletcher–Goldfarb–Shanno_algorithm">
/// article </a> of the BFGS this algoritm.
template <typename Scalar>
class BFGS : public Solver<Scalar> {
 public:
  // Constructor for BFGS Solver
  BFGS(void) { }

  // Destructor
  virtual ~BFGS(void) { }

  /// Solve the problem
  TERMINATION_TYPE
  operator()(const ProblemLS<Scalar>& problem,
             Eigen::Matrix<Scalar, Eigen::Dynamic, 1>* x,
             Scalar* min_value);

 protected:
  /// Line search: Implements a Backtracking algorithm
  Scalar line_search(const ObjectiveFunctorLS<Scalar>& objective,
                     const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& x,
                     const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& p,
                     const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& g);
};
}  // solvers
}  // optimo
#endif  // OPTIMO_SOLVERS_BFGS_API_H_


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2012 EMC Corp.
//
//	@filename:
//		CLogicalDifference.cpp
//
//	@doc:
//		Implementation of Difference operator
//---------------------------------------------------------------------------

#include "gpopt/operators/CLogicalDifference.h"

#include "gpos/base.h"

#include "gpopt/base/CKeyCollection.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CLogicalGbAgg.h"
#include "naucrates/statistics/CStatsPredUtils.h"

using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::CLogicalDifference
//
//	@doc:
//		Ctor - for pattern
//
//---------------------------------------------------------------------------
CLogicalDifference::CLogicalDifference(CMemoryPool *mp) : CLogicalSetOp(mp)
{
	m_fPattern = true;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::CLogicalDifference
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CLogicalDifference::CLogicalDifference(CMemoryPool *mp,
									   CColRefArray *pdrgpcrOutput,
									   CColRef2dArray *pdrgpdrgpcrInput)
	: CLogicalSetOp(mp, pdrgpcrOutput, pdrgpdrgpcrInput)
{
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::~CLogicalDifference
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CLogicalDifference::~CLogicalDifference()
{
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::DeriveMaxCard
//
//	@doc:
//		Derive max card
//
//---------------------------------------------------------------------------
CMaxCard
CLogicalDifference::DeriveMaxCard(CMemoryPool *,  // mp
								  CExpressionHandle &exprhdl) const
{
	// contradictions produce no rows
	if (exprhdl.DerivePropertyConstraint()->FContradiction())
	{
		return CMaxCard(0 /*ull*/);
	}

	return exprhdl.DeriveMaxCard(0);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::PopCopyWithRemappedColumns
//
//	@doc:
//		Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalDifference::PopCopyWithRemappedColumns(CMemoryPool *mp,
											   UlongToColRefMap *colref_mapping,
											   BOOL must_exist)
{
	CColRefArray *pdrgpcrOutput =
		CUtils::PdrgpcrRemap(mp, m_pdrgpcrOutput, colref_mapping, must_exist);
	CColRef2dArray *pdrgpdrgpcrInput = CUtils::PdrgpdrgpcrRemap(
		mp, m_pdrgpdrgpcrInput, colref_mapping, must_exist);

	return GPOS_NEW(mp) CLogicalDifference(mp, pdrgpcrOutput, pdrgpdrgpcrInput);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::PxfsCandidates
//
//	@doc:
//		Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalDifference::PxfsCandidates(CMemoryPool *mp) const
{
	CXformSet *xform_set = GPOS_NEW(mp) CXformSet(mp);
	(void) xform_set->ExchangeSet(CXform::ExfDifference2LeftAntiSemiJoin);
	return xform_set;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalDifference::PstatsDerive
//
//	@doc:
//		Derive statistics
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalDifference::PstatsDerive(CMemoryPool *mp, CExpressionHandle &exprhdl,
								 IStatisticsArray *	 // not used
) const
{
	GPOS_ASSERT(Esp(exprhdl) > EspNone);

	// difference is transformed into an aggregate over a LASJ,
	// we follow the same route to compute statistics
	CColRefSetArray *output_colrefsets = GPOS_NEW(mp) CColRefSetArray(mp);
	const ULONG size = m_pdrgpdrgpcrInput->Size();
	for (ULONG ul = 0; ul < size; ul++)
	{
		CColRefSet *pcrs =
			GPOS_NEW(mp) CColRefSet(mp, (*m_pdrgpdrgpcrInput)[ul]);
		output_colrefsets->Append(pcrs);
	}

	IStatistics *outer_stats = exprhdl.Pstats(0);
	IStatistics *inner_side_stats = exprhdl.Pstats(1);

	// construct the scalar condition for the LASJ
	CExpression *pexprScCond =
		CUtils::PexprConjINDFCond(mp, m_pdrgpdrgpcrInput);

	// compute the statistics for LASJ
	CColRefSet *outer_refs = exprhdl.DeriveOuterReferences();
	CStatsPredJoinArray *join_preds_stats =
		CStatsPredUtils::ExtractJoinStatsFromExpr(mp, exprhdl, pexprScCond,
												  output_colrefsets, outer_refs,
												  true	// is an LASJ
		);
	IStatistics *LASJ_stats =
		outer_stats->CalcLASJoinStats(mp, inner_side_stats, join_preds_stats,
									  true /* DoIgnoreLASJHistComputation */
		);

	// clean up
	pexprScCond->Release();
	join_preds_stats->Release();

	// computed columns
	ULongPtrArray *pdrgpulComputedCols = GPOS_NEW(mp) ULongPtrArray(mp);
	IStatistics *stats = CLogicalGbAgg::PstatsDerive(
		mp, LASJ_stats,
		(*m_pdrgpdrgpcrInput)[0],  // we group by the columns of the first child
		pdrgpulComputedCols,	   // no computed columns for set ops
		NULL					   // no keys, use all grouping cols
	);

	// clean up
	pdrgpulComputedCols->Release();
	LASJ_stats->Release();
	output_colrefsets->Release();

	return stats;
}

// EOF


text:
<?php

namespace Zend\Config;

/**
 * YAML Adapter for Zend_Config
 *
 * @category  Zend
 * @package   Zend_Config
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Yaml extends Config
{
    /**
     * Attribute name that indicates what section a config extends from
     */
    const EXTENDS_NAME = "_extends";

    /**
     * Whether to skip extends or not
     *
     * @var boolean
     */
    protected $_skipExtends = false;

    /**
     * What to call when we need to decode some YAML?
     *
     * @var callable
     */
    protected $_yamlDecoder = array(__CLASS__, 'decode');

    /**
     * Whether or not to ignore constants in parsed YAML
     * @var bool
     */
    protected static $_ignoreConstants = false;

    /**
     * Indicate whether parser should ignore constants or not
     *
     * @param  bool $flag
     * @return void
     */
    public static function setIgnoreConstants($flag)
    {
        self::$_ignoreConstants = (bool) $flag;
    }

    /**
     * Whether parser should ignore constants or not
     *
     * @return bool
     */
    public static function ignoreConstants()
    {
        return self::$_ignoreConstants;
    }

    /**
     * Get callback for decoding YAML
     *
     * @return callable
     */
    public function getYamlDecoder()
    {
        return $this->_yamlDecoder;
    }

    /**
     * Set callback for decoding YAML
     *
     * @param  callable $yamlDecoder the decoder to set
     * @return Zend_Config_Yaml
     */
    public function setYamlDecoder($yamlDecoder)
    {
        if (!is_callable($yamlDecoder)) {
            throw new Exception\InvalidArgumentException('Invalid parameter to setYamlDecoder() - must be callable');
        }

        $this->_yamlDecoder = $yamlDecoder;
        return $this;
    }

    /**
     * Loads the section $section from the config file encoded as YAML
     *
     * Sections are defined as properties of the main object
     *
     * In order to extend another section, a section defines the "_extends"
     * property having a value of the section name from which the extending
     * section inherits values.
     *
     * Note that the keys in $section will override any keys of the same
     * name in the sections that have been included via "_extends".
     *
     * Options may include:
     * - allow_modifications: whether or not the config object is mutable
     * - skip_extends: whether or not to skip processing of parent configuration
     * - yaml_decoder: a callback to use to decode the Yaml source
     *
     * @param  string  $yaml     YAML file to process
     * @param  mixed   $section Section to process
     * @param  boolean $options Whether modifiacations are allowed at runtime
     */
    public function __construct($yaml, $section = null, $options = false)
    {
        if (empty($yaml)) {
            throw new Exception\RuntimeException('Filename is not set');
        }

        $ignoreConstants    = $staticIgnoreConstants = self::ignoreConstants();
        $allowModifications = false;
        if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            foreach ($options as $key => $value) {
                switch (strtolower($key)) {
                    case 'allow_modifications':
                    case 'allowmodifications':
                        $allowModifications = (bool) $value;
                        break;
                    case 'skip_extends':
                    case 'skipextends':
                        $this->_skipExtends = (bool) $value;
                        break;
                    case 'ignore_constants':
                    case 'ignoreconstants':
                        $ignoreConstants = (bool) $value;
                        break;
                    case 'yaml_decoder':
                    case 'yamldecoder':
                        $this->setYamlDecoder($value);
                        break;
                    default:
                        break;
                }
            }
        }

        // read yaml file
        $this->_setErrorHandler();
        $content = file_get_contents($yaml, true);
        $errorMessages = $this->_restoreErrorHandler();
        if ($content === false) {
            $e = null;
            foreach ($errorMessages as $errMsg) {
                $e = new Exception\RuntimeException($errMsg, 0, $e);
            }
            $e = new Exception\RuntimeException("Can't read file '{$yaml}'", 0, $e);
            throw $e;
        }
        $yaml = $content;

        // Override static value for ignore_constants if provided in $options
        self::setIgnoreConstants($ignoreConstants);

        // Parse YAML
        $config = call_user_func($this->getYamlDecoder(), $yaml);

        // Reset original static state of ignore_constants
        self::setIgnoreConstants($staticIgnoreConstants);

        if (null === $config) {
            // decode failed
            throw new Exception\RuntimeException("Error parsing YAML data");
        }

        if (null === $section) {
            $dataArray = array();
            foreach ($config as $sectionName => $sectionData) {
                $dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
            }
            parent::__construct($dataArray, $allowModifications);
        } elseif (is_array($section)) {
            $dataArray = array();
            foreach ($section as $sectionName) {
                if (!isset($config[$sectionName])) {
                    throw new Exception\RuntimeException(sprintf('Section "%s" cannot be found', $section));
                }

                $dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
            }
            parent::__construct($dataArray, $allowModifications);
        } else {
            if (!isset($config[$section])) {
                throw new Exception\RuntimeException(sprintf('Section "%s" cannot be found', $section));
            }

            $dataArray = $this->_processExtends($config, $section);
            if (!is_array($dataArray)) {
                // Section in the yaml data contains just one top level string
                $dataArray = array($section => $dataArray);
            }
            parent::__construct($dataArray, $allowModifications);
        }

        $this->_loadedSection = $section;
    }

    /**
     * Helper function to process each element in the section and handle
     * the "_extends" inheritance attribute.
     *
     * @param  array            $data Data array to process
     * @param  string           $section Section to process
     * @param  array            $config  Configuration which was parsed yet
     * @return array
     * @throws Zend_Config_Exception When $section cannot be found
     */
    protected function _processExtends(array $data, $section, array $config = array())
    {
        if (!isset($data[$section])) {
            throw new Exception\RuntimeException(sprintf('Section "%s" cannot be found', $section));
        }

        $thisSection  = $data[$section];

        if (is_array($thisSection) && isset($thisSection[self::EXTENDS_NAME])) {
            $this->_assertValidExtend($section, $thisSection[self::EXTENDS_NAME]);

            if (!$this->_skipExtends) {
                $config = $this->_processExtends($data, $thisSection[self::EXTENDS_NAME], $config);
            }
            unset($thisSection[self::EXTENDS_NAME]);
        }

        $config = $this->_arrayMergeRecursive($config, $thisSection);

        return $config;
    }

    /**
     * Very dumb YAML parser
     *
     * Until we have Zend_Yaml...
     *
     * @param  string $yaml YAML source
     * @return array Decoded data
     */
    public static function decode($yaml)
    {
        $lines = explode("\n", $yaml);
        reset($lines);
        return self::_decodeYaml(0, $lines);
    }

    /**
     * Service function to decode YAML
     *
     * @param  int $currentIndent Current indent level
     * @param  array $lines  YAML lines
     * @return array|string
     */
    protected static function _decodeYaml($currentIndent, &$lines)
    {
        $config   = array();
        $inIndent = false;
        while (list($n, $line) = each($lines)) {
            $lineno = $n + 1;
            $line = rtrim(preg_replace("/#.*$/", "", $line));
            if (strlen($line) == 0) {
                continue;
            }
            if ($line[0] == '#') {
                // comment
                continue;
            }
            $indent = strspn($line, " ");

            // line without the spaces
            $line = trim($line);
            if (strlen($line) == 0) {
                continue;
            }

            if ($indent < $currentIndent) {
                // this level is done
                prev($lines);
                return $config;
            }

            if (!$inIndent) {
                $currentIndent = $indent;
                $inIndent      = true;
            }

            if (preg_match("/(\w+):\s*(.*)/", $line, $m)) {
                // key: value
                if (strlen($m[2])) {
                    // simple key: value
                    $value = rtrim(preg_replace("/#.*$/", "", $m[2]));
                    // Check for booleans and constants
                    if (preg_match('/^(t(rue)?|on|y(es)?)$/i', $value)) {
                        $value = true;
                    } elseif (preg_match('/^(f(alse)?|off|n(o)?)$/i', $value)) {
                        $value = false;
                    } elseif (!self::$_ignoreConstants) {
                        // test for constants
                        $value = self::_replaceConstants($value);
                    }
                } else {
                    // key: and then values on new lines
                    $value = self::_decodeYaml($currentIndent + 1, $lines);
                    if (is_array($value) && !count($value)) {
                        $value = "";
                    }
                }
                $config[$m[1]] = $value;
            } elseif ($line[0] == "-") {
                // item in the list:
                // - FOO
                if (strlen($line) > 2) {
                    $value = substr($line, 2);
                    if (preg_match('/^(t(rue)?|on|y(es)?)$/i', $value)) {
                        $value = true;
                    } elseif (preg_match('/^(f(alse)?|off|n(o)?)$/i', $value)) {
                        $value = false;
                    } elseif (!self::$_ignoreConstants) {
                         $value = self::_replaceConstants($value);
                    }
                    $config[] = $value;
                } else {
                    $config[] = self::_decodeYaml($currentIndent + 1, $lines);
                }
            } else {
                throw new Exception\RuntimeException(sprintf(
                    'Error parsing YAML at line %d - unsupported syntax: "%s"',
                    $lineno, $line
                ));
            }
        }
        return $config;
    }

    /**
     * Replace any constants referenced in a string with their values
     *
     * @param  string $value
     * @return string
     */
    protected static function _replaceConstants($value)
    {
        foreach (self::_getConstants() as $constant) {
            if (strstr($value, $constant)) {
                $value = str_replace($constant, constant($constant), $value);
            }
        }
        return $value;
    }

    /**
     * Get (reverse) sorted list of defined constant names
     *
     * @return array
     */
    protected static function _getConstants()
    {
        $constants = array_keys(get_defined_constants());
        rsort($constants, SORT_STRING);
        return $constants;
    }
}


text:
require 'spec_helper.rb'

feature "Viewing a ride", js: true do
  before do
    create :ride_to_lahti
    create :ride_to_helsinki
  end

  scenario "view one ride" do
    visit "/"

    click_on "John Doe"

    expect(page).to have_content("John Doe")
    expect(page).to have_content("Take me to Helsinki, please.")

    click_on "Back"

    expect(page).to     have_content("John Doe")
    expect(page).not_to have_content("Take me to Helsinki, please.")
  end
end


text:
package main.scala.plotting.old

import breeze.linalg.{DenseMatrix, DenseVector}
import breeze.plot._
import org.joda.time.DateTime

/**
 * Created by Francois Belletti on 10/28/15.
 */
object PlotTS {

  def showModel(
      modelCoeffs: Array[DenseMatrix[Double]],
      title: Option[String] = None,
      saveToFile: Option[String] = None): Unit ={

    val f = Figure()

    for(i <- modelCoeffs.indices) {

      val p = f.subplot(modelCoeffs.length, 1, i)
      p += image(modelCoeffs(i), GradientPaintScale[Double](-1.0, 1.0))

    }

    if(title.isDefined) {
      f.subplot(0).title = title.get
    }

    if(saveToFile.isDefined){
      f.saveas(saveToFile.get)
    }

  }

  def showCovariance(
      covMatrix: DenseMatrix[Double],
      title: Option[String] = None,
      saveToFile: Option[String] = None): Unit ={

    val f = Figure()

    val p = f.subplot(0)
    p += image(covMatrix.toDenseMatrix)

    if(title.isDefined) {
      f.subplot(0).title = title.get
    }

    if(saveToFile.isDefined){
      f.saveas(saveToFile.get)
    }

  }

  def showProfile(
      profileMatrix: DenseMatrix[Double],
      title: Option[String] = None,
      saveToFile: Option[String] = None): Unit ={

    val f = Figure()

    val p = f.subplot(0)
    p += image(profileMatrix.t)

    p.ylabel = "Space"
    p.xlabel = "Time"

    if(title.isDefined) {
      f.subplot(0).title = title.get
    }

    if(saveToFile.isDefined){
      f.saveas(saveToFile.get)
    }

  }

  def showUnivModel(
      modelCoeffs: Array[DenseVector[Double]],
      title: Option[String] = None,
      saveToFile: Option[String] = None): Unit ={

    val f = Figure()

    for(i <- modelCoeffs.indices) {

      val p = f.subplot(modelCoeffs.length, 1, i)
      p += image(modelCoeffs(i).toDenseMatrix, GradientPaintScale[Double](-1.0, 1.0))

    }

    if(title.isDefined) {
      f.subplot(0).title = title.get
    }

    if(saveToFile.isDefined){
      f.saveas(saveToFile.get)
    }

  }

}


text:
require 'spec_helper'
require 'json'

describe 'cpi.json.erb' do
  let(:jobs_root) { File.join(File.dirname(__FILE__), '../../../../../../../../', 'jobs') }
  let(:cpi_specification_file) { File.absolute_path(File.join(jobs_root, 'azure_cpi/spec')) }
  let(:cpi_json_erb) { File.read(File.absolute_path(File.join(jobs_root, 'azure_cpi/templates/cpi.json.erb'))) }
  let(:manifest) do
    {
      'properties' => {
        'azure' => {
          'environment'            => 'AzureCloud',
          'subscription_id'        => 'fake-subscription-id',
          'tenant_id'              => 'fake-tenant-id',
          'client_id'              => 'fake-client-id',
          'client_secret'          => 'fake-client-secret',
          'resource_group_name'    => 'fake-resource-group-name',
          'storage_account_name'   => 'fake-storage-account-name',
          'ssh_user'               => 'vcap',
          'ssh_public_key'         => 'ssh-rsa ABCDEFGHIJKLMN',
          'default_security_group' => 'fake-default-security-group'
        },
        'registry' => {
          'host' => 'registry-host.example.com',
          'username' => 'admin',
          'password' => 'admin',
          'port' => 25777
        },
        'blobstore' => {
          'address' => 'blobstore-address.example.com',
          'agent' => {
            'user' => 'agent',
            'password' => 'agent-password'
          }
        },
        'nats' => {
          'address' => 'nats-address.example.com',
          'password' => 'nats-password'
        }
      }
    }
  end
  let(:logger) { Logger.new(STDERR) }

  subject(:parsed_json) do
    context_hash = YAML.load_file(cpi_specification_file)
    context = TemplateEvaluationContext.new(context_hash, manifest)
    renderer = ERBRenderer.new(context)
    parsed_json = JSON.parse(renderer.render(cpi_json_erb))
    parsed_json
  end

  it 'is able to render the erb given most basic manifest properties' do
    expect(subject).to eq({
      'cloud'=>{
        'plugin'=>'azure',
        'properties'=> {
          'azure'=>{
            'environment'                 => 'AzureCloud',
            'subscription_id'             => 'fake-subscription-id',
            'tenant_id'                   => 'fake-tenant-id',
            'client_id'                   => 'fake-client-id',
            'client_secret'               => 'fake-client-secret',
            'resource_group_name'         => 'fake-resource-group-name',
            'storage_account_name'        => 'fake-storage-account-name',
            'ssh_user'                    => 'vcap',
            'ssh_public_key'              => 'ssh-rsa ABCDEFGHIJKLMN',
            'default_security_group'      => 'fake-default-security-group',
            'parallel_upload_thread_num'  => 16,
            'debug_mode'                  => false,
            'use_managed_disks'           => false,
            'pip_idle_timeout_in_minutes' => 4
          },
          'registry'=>{
            'address'=>'registry-host.example.com',
            'user'=>'admin',
            'password'=>'admin',
            'http' => {
              'port' => 25777,
              'user' => 'admin',
              'password' => 'admin'
            },
            'endpoint'=>'http://admin:admin@registry-host.example.com:25777'
          },
          'agent'=>{
            'ntp'=>[
              '0.pool.ntp.org',
              '1.pool.ntp.org'
            ],
            'blobstore'=>{
              'provider'=>'dav',
              'options'=>{
                'endpoint'=>'http://blobstore-address.example.com:25250',
                'user'=>'agent',
                'password'=>'agent-password'
              }
            },
            'mbus'=>'nats://nats:nats-password@nats-address.example.com:4222'
          }
        }
      }
    })
  end

  context 'when parsing the azure property' do
    context 'when the managed disks are enabled' do
      before do
        manifest['properties']['azure']['use_managed_disks'] = true
      end

      it 'is able to render use_managed_disks to true' do
        expect(subject['cloud']['properties']['azure']['use_managed_disks']).to be(true)
      end
    end

    context 'when pip_idle_timeout_in_minutes is set to 20' do
      before do
        manifest['properties']['azure']['pip_idle_timeout_in_minutes'] = 20
      end

      it 'is able to render pip_idle_timeout_in_minutes to 20' do
        expect(subject['cloud']['properties']['azure']['pip_idle_timeout_in_minutes']).to be(20)
      end
    end

    context 'when the storage account is not provided' do
      before do
        manifest['properties']['azure']['storage_account_name'] = nil
      end

      context 'when the managed disks are enabled' do
        before do
          manifest['properties']['azure']['use_managed_disks'] = true
        end

        it 'allows storage_account_name to be nil' do
          expect(subject['cloud']['properties']['azure']['storage_account_name']).to be_nil
        end
      end

      context 'when the managed disks are disabled' do
        it 'raises an error of missing storage_account_name' do
          expect { subject }.to raise_error(/storage_account_name cannot be nil if use_managed_disks is false/)
        end
      end
    end

    context 'when the ssh public key is not provided' do
      before do
        manifest['properties']['azure']['ssh_public_key'] = nil
      end

      it 'raises an error of missing ssh_public_key' do
        expect { subject }.to raise_error(/"ssh_public_key" is not set/)
      end
    end

    context 'when the environment is AzureStack' do
      before do
        manifest['properties']['azure']['environment'] = 'AzureStack'
        manifest['properties']['azure']['azure_stack'] = {}
      end

      context 'when all the required properties are provided' do
        before do
          manifest['properties']['azure']['azure_stack']['resource'] = 'fake-token-resource'
        end

        it 'parses the AzureStack properties' do
          expect(subject['cloud']['properties']['azure']['azure_stack']).to eq({
            'domain'                             => 'local.azurestack.external',
            'authentication'                     => 'AzureAD',
            'resource'                           => 'fake-token-resource',
            'endpoint_prefix'                    => 'management',
            "skip_ssl_validation"                => false,
            "use_http_to_access_storage_account" => false,
          })
        end
      end

      context 'when maximal properties are provided' do
        before do
          manifest['properties']['azure']['azure_stack']['domain']                             = 'fake-domain'
          manifest['properties']['azure']['azure_stack']['authentication']                     = 'fake-authentication'
          manifest['properties']['azure']['azure_stack']['resource']                           = 'fake-token-resource'
          manifest['properties']['azure']['azure_stack']['endpoint_prefix']                    = 'fake-endpoint-prefix'
          manifest['properties']['azure']['azure_stack']['skip_ssl_validation']                = true
          manifest['properties']['azure']['azure_stack']['use_http_to_access_storage_account'] = true
        end

        it 'parses the AzureStack properties' do
          expect(subject['cloud']['properties']['azure']['azure_stack']).to eq({
            'domain'                             => 'fake-domain',
            'authentication'                     => 'fake-authentication',
            'resource'                           => 'fake-token-resource',
            'endpoint_prefix'                    => 'fake-endpoint-prefix',
            "skip_ssl_validation"                => true,
            "use_http_to_access_storage_account" => true,
          })
        end
      end

      context 'when azure_stack.resource is invalid' do
        before do
          manifest['properties']['azure']['azure_stack']['domain'] = 'fake-domain'
          manifest['properties']['azure']['azure_stack']['authentication'] = 'fake-authentication'
        end

        context 'when azure_stack.resource is nil' do
          before do
            manifest['properties']['azure']['azure_stack']['resource'] = nil
          end

          it 'raises an error of missing azure_stack.resource' do
            expect { subject }.to raise_error(/"resource" must be set for AzureStack/)
          end
        end

        context 'when azure_stack.resource is empty' do
          before do
            manifest['properties']['azure']['azure_stack']['resource'] = ''
          end

          it 'raises an error of missing azure_stack.resource' do
            expect { subject }.to raise_error(/"resource" must be set for AzureStack/)
          end
        end
      end
    end
  end

  context 'when parsing the registry property' do
    context 'when the registry endpoint is specified' do
      registry_endpoint = 'http://fake-username:fake-password@fake-registry-endpoint:fake-port'
      before do
        manifest['properties']['registry']['endpoint'] = registry_endpoint
      end

      it 'can parse the endpoint' do
        expect(subject['cloud']['properties']['registry']['endpoint']).to eq(registry_endpoint)
      end
    end

    context 'when the registry endpoint is not specified' do
      it 'can parse the endpoint using the host, port, username and password' do
        username = manifest['properties']['registry']['username']
        password = manifest['properties']['registry']['password']
        host = manifest['properties']['registry']['host']
        port = manifest['properties']['registry']['port']
        endpoint = "http://#{username}:#{password}@#{host}:#{port}"
        expect(subject['cloud']['properties']['registry']['endpoint']).to eq(endpoint)
      end
    end

    context 'when the registry password includes special characters' do
      special_chars_password = '=!@#$%^&*/-+?='
      before do
        manifest['properties']['registry']['password'] = special_chars_password
      end

      it 'encodes the password with special characters in the registry URL' do
        registry_uri = URI(subject['cloud']['properties']['registry']['endpoint'])
        expect(URI.decode(registry_uri.password)).to eq(special_chars_password)
      end
    end
  end

  context 'when parsing the agent property' do
    context 'when using an s3 blobstore' do
      let(:rendered_blobstore) { subject['cloud']['properties']['agent']['blobstore'] }

      context 'when provided a minimal configuration' do
        before do
          manifest['properties']['blobstore'].merge!({
            'provider' => 's3',
            'bucket_name' => 'my_bucket',
            'access_key_id' => 'blobstore-access-key-id',
            'secret_access_key' => 'blobstore-secret-access-key',
          })
        end

        it 'renders the s3 provider section with the correct defaults' do
          expect(rendered_blobstore).to eq(
            {
              'provider' => 's3',
              'options' => {
                'bucket_name' => 'my_bucket',
                'access_key_id' => 'blobstore-access-key-id',
                'secret_access_key' => 'blobstore-secret-access-key',
                'use_ssl' => true,
                'port' => 443,
                's3_force_path_style' => false
              }
            }
          )
        end
      end
    end

    context 'when using a local blobstore' do
      let(:rendered_blobstore) { subject['cloud']['properties']['agent']['blobstore'] }

      context 'when provided a minimal configuration' do
        before do
          manifest['properties']['blobstore'].merge!({
            'provider' => 'local',
            'path' => '/fake/path',
          })
        end

        it 'renders the local provider section with the correct defaults' do
          expect(rendered_blobstore).to eq(
            {
              'provider' => 'local',
              'options' => {
                'blobstore_path' => '/fake/path',
              }
            }
          )
        end
      end

      context 'when provided an incomplete configuration' do
        before do
          manifest['properties']['blobstore'].merge!({
            'provider' => 'local',
          })
        end

        it 'raises an error' do
          expect { rendered_blobstore }.to raise_error(/Can't find property 'blobstore.path'/)
        end
      end
    end
  end
end

class TemplateEvaluationContext
  attr_reader :name, :index
  attr_reader :properties, :raw_properties
  attr_reader :spec

  def initialize(spec, manifest)
    @name = spec['job']['name'] if spec['job'].is_a?(Hash)
    @index = spec['index']
    properties = {}
    spec['properties'].each do |name, x|
      default = x['default']
      copy_property(properties, manifest['properties'], name, default)
    end
    @properties = openstruct(properties)
    @raw_properties = properties
    @spec = openstruct(spec)
  end

  def recursive_merge(hash, other)
    hash.merge(other) do |_, old_value, new_value|
      if old_value.class == Hash && new_value.class == Hash
        recursive_merge(old_value, new_value)
      else
        new_value
      end
    end
  end

  def get_binding
    binding.taint
  end

  def p(*args)
    names = Array(args[0])
    names.each do |name|
      result = lookup_property(@raw_properties, name)
      return result unless result.nil?
    end
    return args[1] if args.length == 2
    raise UnknownProperty.new(names)
  end

  def if_p(*names)
    values = names.map do |name|
      value = lookup_property(@raw_properties, name)
      return ActiveElseBlock.new(self) if value.nil?
      value
    end
    yield *values
    InactiveElseBlock.new
  end

  private

  def copy_property(dst, src, name, default = nil)
    keys = name.split('.')
    src_ref = src
    dst_ref = dst
    keys.each do |key|
      src_ref = src_ref[key]
      break if src_ref.nil? # no property with this name is src
    end
    keys[0..-2].each do |key|
      dst_ref[key] ||= {}
      dst_ref = dst_ref[key]
    end
    dst_ref[keys[-1]] ||= {}
    dst_ref[keys[-1]] = src_ref.nil? ? default : src_ref
  end

  def openstruct(object)
    case object
      when Hash
        mapped = object.inject({}) { |h, (k,v)| h[k] = openstruct(v); h }
        OpenStruct.new(mapped)
      when Array
        object.map { |item| openstruct(item) }
      else
        object
    end
  end

  def lookup_property(collection, name)
    keys = name.split('.')
    ref = collection
    keys.each do |key|
      ref = ref[key]
      return nil if ref.nil?
    end
    ref
  end

  class UnknownProperty < StandardError
    def initialize(names)
      @names = names
      super("Can't find property '#{names.join("', or '")}'")
    end
  end

  class ActiveElseBlock
    def initialize(template)
      @context = template
    end
    def else
      yield
    end
    def else_if_p(*names, &block)
      @context.if_p(*names, &block)
    end
  end

  class InactiveElseBlock
    def else; end
    def else_if_p(*_)
      InactiveElseBlock.new
    end
  end
end

class ERBRenderer
  def initialize(context)
    @context = context
  end

  def render(erb_content)
    erb = ERB.new(erb_content)
    erb.result(@context.get_binding)
  end
end


text:
package de.zalando.model
import de.zalando.apifirst.Application._
import de.zalando.apifirst.Domain._
import de.zalando.apifirst.ParameterPlace
import de.zalando.apifirst.naming._
import de.zalando.apifirst.Hypermedia._
import de.zalando.apifirst.Http._
import de.zalando.apifirst.Security
import java.net.URL
import Security._
//noinspection ScalaStyle
object numbers_validation_yaml extends WithModel {

 def types = Map[Reference, Type](
	Reference("⌿paths⌿/⌿get⌿double_optional") →
		Opt(Dbl(TypeMeta(Some("double"), List("max(10.toDouble, true)", "min(0.toDouble, true)", "multipleOf(5.toDouble)"))), TypeMeta(None, List())),
	Reference("⌿paths⌿/⌿get⌿integer_required") →
		Intgr(TypeMeta(Some("int32"), List("max(10.toInt, false)", "min(0.toInt, false)", "multipleOf(5.toInt)"))),
	Reference("⌿paths⌿/⌿get⌿integer_optional") →
		Opt(Intgr(TypeMeta(Some("int32"), List("max(10.toInt, true)", "min(-10.toInt, true)", "multipleOf(5.toInt)"))), TypeMeta(None, List())),
	Reference("⌿paths⌿/⌿get⌿double_required") →
		Dbl(TypeMeta(Some("double"), List("max(10.toDouble, false)", "min(2.toDouble, false)", "multipleOf(5.toDouble)"))),
	Reference("⌿paths⌿/⌿get⌿long_optional") →
		Opt(Lng(TypeMeta(Some("int64"), List("max(10.toLong, true)", "min(10.toLong, true)", "multipleOf(10.toLong)"))), TypeMeta(None, List())),
	Reference("⌿paths⌿/⌿get⌿float_required") →
		Flt(TypeMeta(Some("float"), List("max(10.toFloat, true)", "min(10.toFloat, true)", "multipleOf(5.toFloat)"))),
	Reference("⌿paths⌿/⌿get⌿float_optional") →
		Opt(Flt(TypeMeta(Some("float"), List("max(10.toFloat, false)", "min(1.toFloat, false)", "multipleOf(5.toFloat)"))), TypeMeta(None, List())),
	Reference("⌿paths⌿/⌿get⌿long_required") →
		Lng(TypeMeta(Some("int64"), List("max(10.toLong, true)", "min(0.toLong, true)", "multipleOf(5.toLong)"))),
	Reference("⌿paths⌿/⌿get⌿responses⌿200") →
		Null(TypeMeta(None, List()))
)

 def parameters = Map[ParameterRef, Parameter](
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿float_required")) → Parameter("float_required", Flt(TypeMeta(Some("float"), List("max(10.toFloat, true)", "min(10.toFloat, true)", "multipleOf(5.toFloat)"))), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿double_required")) → Parameter("double_required", Dbl(TypeMeta(Some("double"), List("max(10.toDouble, false)", "min(2.toDouble, false)", "multipleOf(5.toDouble)"))), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿integer_optional")) → Parameter("integer_optional", TypeRef(Reference("⌿paths⌿/⌿get⌿integer_optional")), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿long_required")) → Parameter("long_required", Lng(TypeMeta(Some("int64"), List("max(10.toLong, true)", "min(0.toLong, true)", "multipleOf(5.toLong)"))), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿integer_required")) → Parameter("integer_required", Intgr(TypeMeta(Some("int32"), List("max(10.toInt, false)", "min(0.toInt, false)", "multipleOf(5.toInt)"))), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿float_optional")) → Parameter("float_optional", TypeRef(Reference("⌿paths⌿/⌿get⌿float_optional")), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿double_optional")) → Parameter("double_optional", TypeRef(Reference("⌿paths⌿/⌿get⌿double_optional")), None, None, ".+", encode = true, ParameterPlace.withName("query")),
	ParameterRef(	Reference("⌿paths⌿/⌿get⌿long_optional")) → Parameter("long_optional", TypeRef(Reference("⌿paths⌿/⌿get⌿long_optional")), None, None, ".+", encode = true, ParameterPlace.withName("query"))
)
 def basePath: String =null
 def discriminators: DiscriminatorLookupTable = Map[Reference, Reference](
	)
 def securityDefinitions: SecurityDefinitionsTable = Map[String, Security.Definition](

)
def stateTransitions: StateTransitionsTable = Map[State, Map[State, TransitionProperties]]()
def calls: Seq[ApiCall] = Seq(
	ApiCall(GET, Path(Reference("⌿")),
		HandlerCall(
			"numbers_validation.yaml",
			"Numbers_validationYaml",
			instantiate = false,
			"get",parameters =
			Seq(
				ParameterRef(Reference("⌿paths⌿/⌿get⌿float_required")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿double_required")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿integer_optional")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿long_required")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿integer_required")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿float_optional")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿double_optional")),
				ParameterRef(Reference("⌿paths⌿/⌿get⌿long_optional"))
				)
			),
		Set.empty[MimeType],
		Set(MimeType("application/json"), MimeType("application/yaml")),
		Map.empty[String, Seq[Class[Exception]]],
		TypesResponseInfo(
			Map[Int, ParameterRef](
			200 -> ParameterRef(Reference("⌿paths⌿/⌿get⌿responses⌿200"))
		), None),
		StateResponseInfo(
				Map[Int, State](
					200 -> Self
			), None),
		Set.empty[Security.Constraint]))

def packageName: Option[String] = Some("numbers_validation.yaml")

def model = new StrictModel(calls, types, parameters, discriminators, basePath, packageName, stateTransitions, securityDefinitions)

}


text:
import unittest

from rx.observable import Observable
from rx.testing import TestScheduler, ReactiveTest
from rx.disposables import Disposable, SerialDisposable

on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
created = ReactiveTest.created

class RxException(Exception):
    pass

# Helper function for raising exceptions within lambdas
def _raise(ex):
    raise RxException(ex)

class TestFirst_or_default(unittest.TestCase):
    def test_first_or_default_async_empty(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_completed(250))
        def create():
            return xs.first_or_default(None, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_next(250, 0), on_completed(250))
        xs.subscriptions.assert_equal(subscribe(200, 250))

    def test_first_or_default_async_one(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_completed(250))

        def create():
            return xs.first_or_default(None, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_next(210, 2), on_completed(210))
        xs.subscriptions.assert_equal(subscribe(200, 210))

    def test_first_or_default_async_many(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_next(220, 3), on_completed(250))

        def create():
            return xs.first_or_default(None, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_next(210, 2), on_completed(210))
        xs.subscriptions.assert_equal(subscribe(200, 210))

    def test_first_or_default_async_error(self):
        ex = 'ex'
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_error(210, ex))

        def create():
            return xs.first_or_default(None, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_error(210, ex))
        xs.subscriptions.assert_equal(subscribe(200, 210))

    def test_first_or_default_async_predicate(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_next(220, 3), on_next(230, 4), on_next(240, 5), on_completed(250))

        def create():
            def predicate(x):
                return x % 2 == 1

            return xs.first_or_default(predicate, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_next(220, 3), on_completed(220))
        xs.subscriptions.assert_equal(subscribe(200, 220))

    def test_first_or_default_async_predicate_none(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_next(220, 3), on_next(230, 4), on_next(240, 5), on_completed(250))

        def create():
            def predicate(x):
                return x > 10

            return xs.first_or_default(predicate, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_next(250, 0), on_completed(250))
        xs.subscriptions.assert_equal(subscribe(200, 250))

    def test_first_or_default_async_predicate_throw(self):
        ex = 'ex'
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_error(220, ex))

        def create():
            def predicate(x):
                return x % 2 == 1

            return xs.first_or_default(predicate, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_error(220, ex))
        xs.subscriptions.assert_equal(subscribe(200, 220))

    def test_first_or_default_async_predicate_throws(self):
        ex = 'ex'
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_next(220, 3), on_next(230, 4), on_next(240, 5), on_completed(250))

        def create():
            def predicate(x):
                if x < 4:
                    return False
                else:
                    raise Exception(ex)

            return xs.first_or_default(predicate, 0)

        res = scheduler.start(create=create)

        res.messages.assert_equal(on_error(230, ex))
        xs.subscriptions.assert_equal(subscribe(200, 230))


text:
curdir=`pwd`
cd ../../common
. ./libpkix_init.sh > /dev/null
doPD=1
. ./libpkix_init_nist.sh
cd ${curdir}

numtests=0
passed=0
testunit=PKI
doPki=1

### setup NIST files need to link in
linkPkiNistFiles="InvalidDNnameConstraintsTest3EE.crt
        InvalidonlySomeReasonsTest21EE.crt
        indirectCRLCA3cRLIssuerCRL.crl
        nameConstraintsDN3subCA2Cert.crt
        nameConstraintsDN4CACert.crt
        nameConstraintsDN5CACert.crt
        onlyContainsAttributeCertsCACRL.crl
        onlyContainsCACertsCACRL.crl
        onlyContainsUserCertsCACRL.crl
        onlySomeReasonsCA3compromiseCRL.crl
        requireExplicitPolicy2CACert.crt
        inhibitPolicyMapping5CACert.crt
        inhibitAnyPolicy5CACert.crt
        inhibitAnyPolicy0CACert.crt
        P1Mapping1to234CACert.crt
        UserNoticeQualifierTest15EE.crt
        UserNoticeQualifierTest16EE.crt
        UserNoticeQualifierTest17EE.crt
        UserNoticeQualifierTest18EE.crt
        CPSPointerQualifierTest20EE.crt"

if [ -n "${NIST_FILES_DIR}" ]; then
    if [ ! -d ${HOSTDIR}/rev_data/local ]; then
        mkdir -p ${HOSTDIR}/rev_data/local
    fi

    for i in ${linkPkiNistFiles}; do
        if [ -f ${HOSTDIR}/rev_data/local/$i ]; then
            rm ${HOSTDIR}/rev_data/local/$i
        fi
        cp ${NIST_FILES_DIR}/$i ${HOSTDIR}/rev_data/local/$i
    done
fi

##########
# main
#########

TZ=US/Eastern

ParseArgs $*

RunTests <<EOF
pkixutil test_cert NIST-Test-Files-Used ../../certs ${HOSTDIR}/rev_data/local
pkixutil test_crl NIST-Test-Files-Used ../../certs
pkixutil test_x500name
pkixutil test_generalname
pkixutil test_date NIST-Test-Files-Used
pkixutil test_crlentry ../../certs
pkixutil test_nameconstraints NIST-Test-Files-Used rev_data/local ${HOSTDIR}
pkixutil test_authorityinfoaccess NIST-PDTest ${NIST_PDTEST} certs/BasicLDAPURIPathDiscoveryOU1EE1.crt certs/BasicHTTPURITrustAnchorRootCert.crt
pkixutil test_subjectinfoaccess NIST-PDTest ${NIST_PDTEST} certs/BasicHTTPURITrustAnchorRootCert.crt certs/BasicLDAPURIPathDiscoveryOU1EE1.crt
EOF

totalErrors=$?
html_msg ${totalErrors} 0 "   ${testunit}: passed ${passed} of ${numtests} tests"
exit ${totalErrors}


text:
<Record name="ca_fed_fnd_t" type="delimited">
  <Field name="fin_fed_funded_cd"               type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="obj_id"                          type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="ver_nbr"                         type="numeric"    nullable="true"  trim="false" delimiter="|"  />
  <Field name="dobj_maint_cd_actv_ind"          type="string"     nullable="true"  trim="false" delimiter="|"  />
  <Field name="fin_fed_fnd_nm"                  type="string"     nullable="true"  trim="false" delimiter="|\r\n" />
</Record>