text:
package com.opengamma.engine.calcnode;

import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.LongSet;
import it.unimi.dsi.fastutil.objects.Object2LongMap;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import com.opengamma.engine.cache.IdentifierEncodedValueSpecifications;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.util.ArgumentChecker;

/**
 * Contains details about the result of a calculation job. The result can be correlated to the original
 * {@link CalculationJob} through the {@link CalculationJobSpecification}.
 */
public class CalculationJobResult implements IdentifierEncodedValueSpecifications {

  private static final Logger s_logger = LoggerFactory.getLogger(CalculationJobResult.class);

  private final CalculationJobSpecification _specification;

  /**
   * The set of result items in the same order as the items from the original job request.
   */
  private final List<CalculationJobResultItem> _resultItems;

  private final long _durationNanos;
  private final String _nodeId;

  /**
   * Constructs an instance.
   *
   * @param specification  the original calculation job specification, not null
   * @param durationNanos  the duration of the job in nanoseconds
   * @param resultItems  the results in the same order as the items in the original request, not null
   * @param nodeId  the identifier of the calculation node used to perform the job
   */
  public CalculationJobResult(CalculationJobSpecification specification, long durationNanos,
      List<CalculationJobResultItem> resultItems, String nodeId) {
    ArgumentChecker.notNull(specification, "specification");
    ArgumentChecker.notNull(resultItems, "resultItems");
    if (durationNanos < 0) {
      // Avoid failing for this, as nanoTime() may not work correctly
      s_logger.warn("Duration must be non-negative: " + durationNanos);
      durationNanos = 0;
    }
    ArgumentChecker.notNull(nodeId, "Node ID the job was executed on");

    _specification = specification;
    _durationNanos = durationNanos;
    _resultItems = resultItems;
    _nodeId = nodeId;
  }

  //-------------------------------------------------------------------------
  /**
   * Gets the original calculation job specification.
   *
   * @return the original calculation job specification, not null
   */
  public CalculationJobSpecification getSpecification() {
    return _specification;
  }

  /**
   * Gets the results in the same order as the items in the original request.
   *
   * @return the result items, not null
   */
  public List<CalculationJobResultItem> getResultItems() {
    return Collections.unmodifiableList(_resultItems);
  }

  /**
   * Gets the duration of the job in nanoseconds.
   *
   * @return the duration of the job in nanoseconds
   */
  public long getDuration() {
    return _durationNanos;
  }

  /**
   * Gets the identifier of the compute node used to perform the job.
   *
   * @return the identifier of the compute node used to perform the job
   */
  public String getComputeNodeId() {
    return _nodeId;
  }

  //-------------------------------------------------------------------------
  @Override
  public void convertIdentifiers(final Long2ObjectMap<ValueSpecification> identifiers) {
    for (CalculationJobResultItem item : _resultItems) {
      item.convertIdentifiers(identifiers);
    }
  }

  @Override
  public void collectIdentifiers(final LongSet identifiers) {
    for (CalculationJobResultItem item : _resultItems) {
      item.collectIdentifiers(identifiers);
    }
  }

  @Override
  public void convertValueSpecifications(final Object2LongMap<ValueSpecification> valueSpecifications) {
    for (CalculationJobResultItem item : _resultItems) {
      item.convertValueSpecifications(valueSpecifications);
    }
  }

  @Override
  public void collectValueSpecifications(final Set<ValueSpecification> valueSpecifications) {
    for (CalculationJobResultItem item : _resultItems) {
      item.collectValueSpecifications(valueSpecifications);
    }
  }

  @Override
  public String toString() {
    return "CalculationJobResult with " + _specification.toString();
  }

  @Override
  public int hashCode() {
    int hc = 1;
    hc += (hc << 4) + _specification.hashCode();
    hc += (hc << 4) + _resultItems.hashCode();
    hc += (hc << 4) + ((int) (_durationNanos >>> 32) ^ (int) _durationNanos);
    hc += (hc << 4) + ObjectUtils.nullSafeHashCode(_nodeId);
    return hc;
  }

  @Override
  public boolean equals(final Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof CalculationJobResult)) {
      return false;
    }
    final CalculationJobResult other = (CalculationJobResult) o;
    return _specification.equals(other._specification)
        && _resultItems.equals(other._resultItems)
        && (_durationNanos == other._durationNanos)
        && ObjectUtils.nullSafeEquals(_nodeId, other._nodeId);
  }

}


text:
/*
 * Author: Mauro Mandracchia - info@ideabile.com
 * All Right Reserved - 2014
 * Table content example
 */
define([ "jquery", "backbone", "underscore", "./TableView", "./TableCollection" ],
    function ($, Backbone, _, TableView, TableCollection) {
        "use strict";

        var Table, ractive, TheadRows, Rows;

        Table = {};

        // Initial start of the Single Page Application
        Table.init = function (elem, opts, data) {
            var thead_rows, rows;

            // Add data to the Rows collection
            rows = new TableCollection(data);

            ractive = new TableView({
                el: elem,
                data: {
                    rows: rows,
                    log: function(model){
                        console.log("model:\n\n",model);
                    }
                },
                adapt: [ 'Backbone' ]
            });

            ractive.on({

                typeChange: function (elem, attr, value) {

                    var model = filters.get(elem);
                    if (typeof model != "undefined") {
                        model.set(attr, value);
                    }

                },

                removeFilter: function (elem, id) {

                    var model = filters.get(id);
                    filters.remove(model);

                }
            });

            $(".e-add").on("click", function () {
                filters.add({});
            });

        };

        return Table;
    });

redpajama_set_name: RedPajamaGithub


text:
CREATE PROC [etljob].[prc_GetStoppedAgentJobs] @JobCat SYSNAME
AS
DECLARE @startdate DATETIME
	,@endtime DATETIME
DECLARE @OutputTemp AS TABLE (StopId INT)

SET @endtime = getdate()

UPDATE etljob.stop
SET RecoveryEnd = @endtime
OUTPUT inserted.[StopID]
INTO @OutputTemp
WHERE etljob.stop.RecoveryEnd IS NULL

SELECT @startdate = min([StopStart])
FROM [etljob].[vw_Stop] s
INNER JOIN @OutputTemp o
	ON s.StopID = o.StopId

EXEC etljob.[prc_GetMissedJobID] @startdate
	,@endtime
	,@JobCat


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Component\Server\GrantType;

use Assert\Assertion;
use Jose\JWTLoaderInterface;
use Jose\Object\JWKSetInterface;
use Jose\Object\JWSInterface;
use OAuth2Framework\Component\Server\Endpoint\Token\GrantTypeData;
use OAuth2Framework\Component\Server\Model\Client\ClientId;
use OAuth2Framework\Component\Server\Model\Client\ClientRepositoryInterface;
use OAuth2Framework\Component\Server\Model\ResourceOwner\ResourceOwnerId;
use OAuth2Framework\Component\Server\Model\TrustedIssuer\TrustedIssuerInterface;
use OAuth2Framework\Component\Server\Model\UserAccount\UserAccountId;
use OAuth2Framework\Component\Server\Model\UserAccount\UserAccountRepositoryInterface;
use OAuth2Framework\Component\Server\Response\OAuth2Exception;
use OAuth2Framework\Component\Server\Response\OAuth2ResponseFactoryManager;
use Psr\Http\Message\ServerRequestInterface;

final class JWTBearerGrantType implements GrantTypeInterface
{
    /**
     * @var JWTLoaderInterface
     */
    private $jwtLoader;

    /**
     * @var ClientRepositoryInterface
     */
    private $clientRepository;

    /**
     * @var UserAccountRepositoryInterface
     */
    private $userAccountRepository;

    /**
     * @var bool
     */
    private $encryptionRequired = false;

    /**
     * @var JWKSetInterface|null
     */
    private $keyEncryptionKeySet = null;

    /**
     * @var TrustedIssuerInterface[]
     */
    private $trustedIssuers = [];

    /**
     * JWTBearerGrantType constructor.
     *
     * @param JWTLoaderInterface             $jwsLoader
     * @param ClientRepositoryInterface      $clientRepository
     * @param UserAccountRepositoryInterface $userAccountRepository
     */
    public function __construct(JWTLoaderInterface $jwsLoader, ClientRepositoryInterface $clientRepository, UserAccountRepositoryInterface $userAccountRepository)
    {
        $this->jwtLoader = $jwsLoader;
        $this->clientRepository = $clientRepository;
        $this->userAccountRepository = $userAccountRepository;
    }

    /**
     * @param TrustedIssuerInterface $trustedIssuer
     *
     * @return JWTBearerGrantType
     */
    public function addTrustedIssuer(TrustedIssuerInterface $trustedIssuer): JWTBearerGrantType
    {
        $name = $trustedIssuer->name();
        $this->trustedIssuers[$name] = $trustedIssuer;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getAssociatedResponseTypes(): array
    {
        return [];
    }

    /**
     * @param bool            $encryptionRequired
     * @param JWKSetInterface $keyEncryptionKeySet
     */
    public function enableEncryptedAssertions(bool $encryptionRequired, JWKSetInterface $keyEncryptionKeySet)
    {
        Assertion::boolean($encryptionRequired);

        $this->encryptionRequired = $encryptionRequired;
        $this->keyEncryptionKeySet = $keyEncryptionKeySet;
    }

    /**
     * {@inheritdoc}
     */
    public function getGrantType(): string
    {
        return 'urn:ietf:params:oauth:grant-type:jwt-bearer';
    }

    public function checkTokenRequest(ServerRequestInterface $request)
    {
        $parameters = $request->getParsedBody() ?? [];
        $requiredParameters = ['assertion'];

        foreach ($requiredParameters as $requiredParameter) {
            if (!array_key_exists($requiredParameter, $parameters)) {
                throw new OAuth2Exception(400, ['error' => OAuth2ResponseFactoryManager::ERROR_INVALID_REQUEST, 'error_description' => sprintf('The parameter \'%s\' is missing.', $requiredParameter)]);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function prepareTokenResponse(ServerRequestInterface $request, GrantTypeData $grantTypeResponse): GrantTypeData
    {
        $parameters = $request->getParsedBody() ?? [];
        $assertion = $parameters['assertion'];
        try {
            $jws = $this->jwtLoader->load($assertion, $this->keyEncryptionKeySet, $this->encryptionRequired);
            Assertion::isInstanceOf($jws, JWSInterface::class, 'Assertion does not contain signed claims.');
            Assertion::eq(1, $jws->countSignatures(), 'Assertion must have only one signature.');
            Assertion::true($jws->hasClaim('iss'), 'Assertion does not contain \'iss\' claims.');
            Assertion::true($jws->hasClaim('sub'), 'Assertion does not contain \'sub\' claims.');
            $grantTypeResponse = $this->checkJWTSignature($grantTypeResponse, $jws);
        } catch (OAuth2Exception $e) {
            throw $e;
        } catch (\Exception $e) {
            throw new OAuth2Exception(400, ['error' => OAuth2ResponseFactoryManager::ERROR_INVALID_REQUEST, 'error_description' => $e->getMessage()]);
        }
        $grantTypeResponse = $grantTypeResponse->withoutRefreshToken();

        return $grantTypeResponse;
    }

    /**
     * {@inheritdoc}
     */
    public function grant(ServerRequestInterface $request, GrantTypeData $grantTypeResponse): GrantTypeData
    {
        //Nothing to do
        return $grantTypeResponse;
    }

    /**
     * @param GrantTypeData $grantTypeResponse
     * @param JWSInterface  $jws
     *
     * @throws OAuth2Exception
     *
     * @return GrantTypeData
     */
    private function checkJWTSignature(GrantTypeData $grantTypeResponse, JWSInterface $jws): GrantTypeData
    {
        $iss = $jws->getClaim('iss');
        $sub = $jws->getClaim('sub');
        if (array_key_exists($iss, $this->trustedIssuers)) {
            $issuer = $this->trustedIssuers[$iss];
            $allowedSignatureAlgorithms = $issuer->getAllowedSignatureAlgorithms();
            $signatureKeys = $issuer->getSignatureKeys();
            $resourceOwnerId = $this->findResourceOwner($sub);
            $grantTypeResponse = $grantTypeResponse->withResourceOwnerId($resourceOwnerId);
        } else {
            $client = $this->clientRepository->find(ClientId::create($iss));
            if (null === $client || true === $client->isDeleted()) {
                throw new  OAuth2Exception(400, ['error' => OAuth2ResponseFactoryManager::ERROR_INVALID_GRANT, 'error_description' => 'Unable to find the assertion issuer.']);
            }
            if (null === $grantTypeResponse->getClient()) {
                $grantTypeResponse = $grantTypeResponse->withClient($client);
            } elseif ($grantTypeResponse->getClient()->getPublicId()->getValue() !== $client->getPublicId()->getValue()) {
                throw new  OAuth2Exception(401, ['error' => OAuth2ResponseFactoryManager::ERROR_INVALID_CLIENT, 'error_description' => 'Client authentication failed.']);
            }
            Assertion::eq($sub, $iss, 'When the client is the assertion issuer then the subject must be the client.');
            $grantTypeResponse = $grantTypeResponse->withResourceOwnerId($client->getPublicId());
            $allowedSignatureAlgorithms = $this->jwtLoader->getSupportedSignatureAlgorithms();
            $signatureKeys = $client->getPublicKeySet();
        }

        Assertion::true($jws->getSignature(0)->hasProtectedHeader('alg'), 'Invalid assertion');
        $alg = $jws->getSignature(0)->getProtectedHeader('alg');
        Assertion::inArray($alg, $allowedSignatureAlgorithms, sprintf('The signature algorithm \'%s\' is not allowed.', $alg));
        $this->jwtLoader->verify($jws, $signatureKeys);
        $grantTypeResponse = $grantTypeResponse->withMetadata('jwt', $jws);

        return $grantTypeResponse;
    }

    /**
     * @param string $subject
     *
     * @return ResourceOwnerId|null
     */
    private function findResourceOwner(string $subject): ? ResourceOwnerId
    {
        $userAccount = $this->userAccountRepository->findUserAccount(UserAccountId::create($subject));
        if (null !== $userAccount) {
            return $userAccount->getPublicId();
        }
        $client = $this->clientRepository->find(ClientId::create($subject));
        if (null !== $client) {
            return $client->getPublicId();
        }

        return null;
    }
}


text:
package at.arz.latte.rodeo.pipeline;

import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class CommandLineStepConfiguration
		extends StepConfiguration {

	@Size(max = Template.MAX_LENGTH)
	private String mainScript;

	@Size(max = Template.MAX_LENGTH)
	private String successScript;

	@Size(max = Template.MAX_LENGTH)
	private String failureScript;

	public String getMainScript() {
		return mainScript;
	}

	public void setMainScript(String mainScript) {
		this.mainScript = mainScript;
	}

	public String getSuccessScript() {
		return successScript;
	}

	public void setSuccessScript(String successScript) {
		this.successScript = successScript;
	}

	public String getFailureScript() {
		return failureScript;
	}

	public void setFailureScript(String failureScript) {
		this.failureScript = failureScript;
	}

	public void setOptional(boolean optional) {
		this.optional = optional;
	}

}


text:
id: 366
title: 'What's technically new for SG 4D?'
date: 2010-04-02T13:24:26+00:00
author: Junda Ong
layout: post
guid: http://blog.just2us.com/2010/04/whats-technically-new-for-sg-4d/
permalink: /2010/04/whats-technically-new-for-sg-4d/
dsq_thread_id:
  - 81749235
arkayne-cache-post:
  - |
    |

arkayne-time-post:
  - 1400154121
categories:
  - Applications
  - Development
  - iPhone
tags:
  - SG 4D
---
In the previous post, I have highlighted what's new for SG 4D. In this post, I will be highlighting what's new, from a technical point of view.

I am excited to write what is technically new in the app, as there are aplenty, and we have used many awesome technology from iPhone 3.0 SDK, including CoreData, In-app purchase, Facebook Connect library, etc..

### 1. Google's AppEngine

I lied. Not only did we use awesome technology from iPhone, we used awesome technology from Google!

The server side is now completely powered by Google's AppEngine. This brings about several benefits: cheap/free server hosting, scalable architecture, stable+distributed+fast servers.

The process of retrieving 4D results is also technically more sound, using REST with JSON, and a proper cron job for web crawling. This makes me happier and sleeps better.

### 2. Core Data

Not only the server application is improved, the client application too, with another awesome technology!

In short, Core Data is the iPhone 3.0 SDK framework for managing data (or commonly databases). The list of features and benefits can be found here.

What Core Data meant for SG 4D is that **all the results**, _I meant all 24 years of results_, are easily stored and queried using the framework.

No longer is your analysis of a 4D number done on the server side. When you asked to analysis a 4D number, your iPhone will query the large set of data using Core Data, and give you the analysis instantly!

This also means more advance analysis is possible in the future!

### 3. In-App Purchase

In-App Purchase is the ability to purchase items right from the app. This is a breakthrough for iPhone 3.0.

In SG 4D, you can now purchase/unlock the Premium Features immediately. Hence, it is not needed to download a lite version, and subsequently upgrading to a paid version.

We have also simplified the purchasing of the Premium Features by just having a $3.99 purchase to get all the features, including future features such as push notification!

### 4. Copy-and-paste

In iPhone 3.0, the _most awesome_ feature should be none other than copy-and-paste (pun intended).

In SG 4D, you could now copy and the 4D results, and paste it anywhere – SMS, Email, twitter, etc..

To make things easier, we also added functions to Email and SMS to your friends.

### 5. Wallpaper Selection

You are now able to select your favorite wallpaper that goes along with the 4D results!

You might have noticed that the minimum OS requirement is now 3.1 (instead of 3.0). This is due to one of the SDK API we used for selecting, resizing and cropping your photo.

_Anyway, the photo above is my 3 hour old nephew, born on March 31, 2010 (Wed). And my dad strike 3rd prize, even before using him for wallpaper (:_

### 6. Sharing on Facebook

Facebook Connect for iPhone is a library for integrating apps with Facebook.

For SG 4D, you could now set your status to help to share SG 4D app with your friends. Right now, we know this is nothing much.

In the future, we are thinking you could post status, such as "I strike 1st prize!", "Bought 1234 for this wed, sat and sun", etc.. If you have any idea on better use for Facebook with SG 4D, we are happy to hear.

### 7. Reviewing on AppStore

We would like you to review the app, no matter good or bad.

To help you to help us review, we have added a function under More to bring you right to App Store to write a review.

In addition, 14 days after you installed the app, SG 4D will prompt you to rate and review us.

### Conclusion

SG 4D version 2 is a big overhaul, technically more sound, and has promising future.


text:
{% block content %}

VoiceX

Welcome to VoiceX! Below are the numbers for posting messages on this server:

VoiceX (US): 6503089145 (Text #help to get started. Regular SMS charges apply.)

Mungano (US): 6503084147 (Text #help to get started. Regular SMS charges apply.)

VoiceX (Kenya): 2122 (Text #help to get started. It's a toll free number. No charges for either sending or receiving text.)

Mungano (Kenya): --

{% endblock %}


text:
# Log into a Nexpose console. Returns a connection object.
#
# @param consoleIP [String] the IP address of the Nexpose console.
# @return [Connection] the connection object.
def NexposeLogin(consoleIP)
    require "io/console"

    print "Username: "
    username = $stdin.gets.chomp
    print "Password: "
    password = STDIN.noecho(&:gets).chomp
    puts ""

    # Blank the proxy variables so they won't be used to connect to the Console.
    ENV['http_proxy'] = nil
    ENV['https_proxy'] = nil

    # Create connection and login.
    nsc = Nexpose::Connection.new(consoleIP, username, password)
    nsc.login
    return nsc
end

class Nexpose::Connection
    # Check if an input is a valid engine id.
    #
    # @param engID [Fixnum] an id to check against the list of valid engine ids.
    # @return [Boolean] true if engID is valid.
    def validate_engineid(engID)
        # Create array of engine ids for validation
        engine_ids = []
        for eng in self.list_engines do
            engine_ids << eng.id
        end

        return engine_ids.include?(engID.to_i)
    end

    # Get the ID for a site name.
    #
    # @param sitename [String] the site name to look up.
    # @return [Fixnum] the id for the site name.
    def sitename_to_id(sitename)
        self.list_sites.each { |site|
            if site.name == sitename
                return site.id
            end
        }
    end

    # Get the name for a site ID.
    #
    # @param siteid [Fixnum] a site id to look up.
    # @return [String] the name of the site.
    def siteid_to_name(siteid)
        self.list_sites.each { |site|
            if site.id == siteid
                return site.name
            end
        }
    end

    # Get a Hash object containing pairs of site ids/names where the Hash key is the site id.
    #
    # @return [Hash] object with site ids as the keys and site names as the values.
    def getSitesInfobyId()
        sitesinfo = {}
        self.list_sites.each { |site|
            sitesinfo[site.id] = site.name
        }
        return sitesinfo
    end

    # Get a Hash object containing pairs of site names/ids where the Hash key is the site name.
    #
    # @return [Hash] object with site names as the keys and site ids as the values.
    def getSitesInfobyName()
        sitesinfo = {}
        self.list_sites.each { |site|
            sitesinfo[site.name] = site.id
        }
        return sitesinfo
    end

    # Get a Hash object containing pairs of scan template names/ids where the Hash key is the scan template id.
    #
    # @return [Hash] object with scan template ids as the keys and scan template names as the values.
    def getScanTemplatesbyId()
        templateinfo = {}
        self.list_scan_templates.each { |template|
            templateinfo[template.id] = template.name
        }
        return templateinfo
    end

    # Get a Hash object containing pairs of scan template names/ids where the Hash key is the scan template name.
    #
    # @return [Hash] object with scan template names as the keys and scan template ids as the values.
    def getScanTemplatesbyName()
        templateinfo = {}
        self.list_scan_templates.each { |template|
            templateinfo[template.name] = template.id
        }
        return templateinfo
    end

    # Get an Asset object for the specified host IP.
    #
    # @param host [String] the hostname to get an Asset object for.
    # @return [Asset] the Asset object for the host.
    def getAsset(host)
        return self.filter(Nexpose::Search::Field::ASSET, Nexpose::Search::Operator::IS, host)
    end

    # Get an array of Asset objects for hosts that have not been scanned in 'X' days.
    #
    # @param days [Fixnum] the number of days back to check for unscanned hosts.
    # @return [Array[Asset]] array of Asset objects for the hosts.
    def notScannedSince(days)
        return self.filter(Nexpose::Search::Field::SCAN_DATE, Nexpose::Search::Operator::EARLIER_THAN, days.to_i)
    end
end

class Nexpose::Site

    # Load asset hostnames from a CSV file.
    #
    # @param nsc [Connection] an active connection to a Nexpose console.
    # @param csvfile [String] path to a CSV file to load hostnames from. (The first column will be used.)
    def load_csv_hostnames(nsc, csvfile)
        puts "Loading site..."
        @site = Site.load(@nsc, self.id)

        puts "Building hostname/asset list..."
        @hostnames = []
        CSV.foreach(@csvfile) do |line|
            @hostnames << HostName.new(line[0])
        end

        puts "Saving site assets..."
        @site.included_addresses = @hostnames
        @site.save(@nsc)
        puts "Done."
        puts "Site #{self.id} now has #{@hostnames.length} assets."
    end

end


text:
import numpy as np
import pyrtools
from PIL import Image

import sys

img = Image.open('../examples/einsteinCorrect.pgm')
img = np.asarray(img)
sfpyr = pyrtools.SFpyr(img, int(sys.argv[1]), int(sys.argv[2]))
sfpyr.showPyr()
recon = sfpyr.reconPyr()
pyrtools.showIm(recon)


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.
 */
package spear.providence.MapeoDB;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
/**
 *
 * @author Daniel
 */
public class EliminarUsuario  {
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
   /**
	 * Asigna el SessionFactory para conectarse a la base de datos.
	 * @param s El SessionFactory.
	 */
	public void setSessionFactory (SessionFactory s) {
		sessionFactory = s;
	}
    public void eliminar(String nombre) {
    hibernateTemplate.delete("from Persona where Nombre=:" +nombre);
    }

}


text:
require 'spec_helper'

module Ec2::Blackout

  describe Ec2Instance do

    describe ".running_instances" do
      it "returns a list of instances that are in the running state" do
        expect_instance_filter('running', 'ap-southeast-2')
        Ec2Instance.running_instances("ap-southeast-2", Options.new)
      end
    end

    describe ".stopped_instances" do
      it "returns a list of instances that are in the stopped state" do
        expect_instance_filter('stopped', 'ap-southeast-2')
        Ec2Instance.stopped_instances("ap-southeast-2", Options.new)
      end
    end

    describe "#stop" do
      let!(:aws_instance) { double("ec2 instance") }
      let!(:instance) { stubbed_stoppable_instance(aws_instance) }

      it "stops the instance" do
        aws_instance.should_receive(:stop)
        instance.stop
      end

      it "tags the instance with a timestamp indicating when it was stopped" do
        aws_instance.should_receive(:add_tag).with do |tag_name, tag_attributes|
          expect(tag_name).to eq Ec2Instance::TIMESTAMP_TAG_NAME
          expect(Time.now - tag_attributes[:value]).to be < 1
        end

        instance.stop
      end

      context 'when the instance has an Elastic IP' do
        let(:eip) { double(:eip) }

        before do
          aws_instance.stub(:has_elastic_ip?).and_return(true)
          aws_instance.stub(:elastic_ip).and_return(eip)
        end

        context 'and it is running in a VPC' do

          before do
            eip.stub(:vpc?).and_return(true)
          end

          it "saves the associated elastic IP as a tag" do
            eip.should_receive(:allocation_id).and_return("eipalloc-eab23c0d")
            aws_instance.should_receive(:add_tag).with(Ec2Instance::EIP_TAG_NAME, :value => "eipalloc-eab23c0d")
            instance.stop
          end
        end

        context 'and it is running in EC2 classic' do
          before do
            eip.stub(:vpc?).and_return(false)
          end

          it "saves the elastic public IP as a tag" do
            eip.should_receive(:public_ip).and_return("public-ip")
            aws_instance.should_receive(:add_tag).with(Ec2Instance::EIP_TAG_NAME, :value => "public-ip")
            instance.stop
          end
        end
      end

    end

    describe "#start" do
      let!(:aws_instance) { double("ec2 instance") }
      let!(:instance) { stubbed_startable_instance(aws_instance) }

      it "starts the instance" do
        aws_instance.should_receive(:start)
        instance.start
      end

      it "remove ec2 blackout tags from the instance" do
        tags = ec2_tags(Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-12 02:35:52 UTC', Ec2Instance::EIP_TAG_NAME => 'eipalloc-eab23c0d')
        aws_instance.stub(:tags).and_return(tags)
        tags.should_receive(:delete).with(Ec2Instance::TIMESTAMP_TAG_NAME)
        tags.should_receive(:delete).with(Ec2Instance::EIP_TAG_NAME)
        instance.start
      end

      it "reattaches the previous elastic IP" do
        tags = ec2_tags(Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-12 02:35:52 UTC', Ec2Instance::EIP_TAG_NAME => 'eipalloc-eab23c0d')
        aws_instance.stub(:tags).and_return(tags)
        aws_instance.should_receive(:associate_elastic_ip).with("eipalloc-eab23c0d")
        instance.start
      end

      it "should retry attaching the elastic IP if it fails" do
        tags = ec2_tags(Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-12 02:35:52 UTC', Ec2Instance::EIP_TAG_NAME => 'eipalloc-eab23c0d')
        aws_instance.stub(:tags).and_return(tags)
        aws_instance.should_receive(:associate_elastic_ip).and_raise(:error)
        aws_instance.should_receive(:associate_elastic_ip)
        instance.eip_retry_delay_seconds = 0
        instance.start
      end
    end

    describe "#stoppable?" do
      let!(:aws_instance) { double("ec2 instance") }
      let!(:instance) { stubbed_stoppable_instance(aws_instance) }

      it "returns true if the instance meets all conditions for being stoppable" do
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_true
      end

      it "returns false if the instance is not running" do
        aws_instance.stub(:status).and_return(:stopped)
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_false
      end

      it "returns false if the instance belongs to an autoscaling group" do
        aws_instance.stub(:tags).and_return(ec2_tags('aws:autoscaling:groupName' => 'foobar'))
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_false
      end

      it "returns false if the instance matches the exclude tags specified in the options" do
        options = Ec2::Blackout::Options.new(:exclude_by_tag =>  ["foo=bar"])
        instance = stubbed_stoppable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags("foo" => "bar"))
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_false
      end

      it "returns false if the instance does not match the include tags specified in the options" do
        options = Ec2::Blackout::Options.new(:include_by_tag =>  ["foo=bar"])
        instance = stubbed_stoppable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags("foo" => "baz"))
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_false
      end

      it "returns false if the instance volume type is not EBS" do
        aws_instance.stub(:root_device_type).and_return('not_ebs')
        stoppable, reason = instance.stoppable?
        expect(stoppable).to be_false
      end
    end

    describe "#startable?" do
      let!(:aws_instance) { double("ec2 instance") }
      let!(:instance) { stubbed_startable_instance(aws_instance) }

      it "returns true if the instance meets all conditions for being startable" do
        startable, reason = instance.startable?
        expect(startable).to be_true
      end

      it "returns false if the instance does not have the ec2 blackout timestamp tag" do
        aws_instance.stub(:tags).and_return(ec2_tags({}))
        startable, reason = instance.startable?
        expect(startable).to be_false
      end

      it "returns true if the force tag was specified even if the instance does not have the ec2 blackout timestamp tag" do
        options = Ec2::Blackout::Options.new(:force => true)
        instance = stubbed_startable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags({}))
        startable, reason = instance.startable?
        expect(startable).to be_true
      end

      it "returns false if the instance matches the exclude tags specified in the options" do
        options = Ec2::Blackout::Options.new(:exclude_by_tag =>  ["foo=bar"])
        instance = stubbed_startable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags("foo" => "bar", Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-13 02:35:52 UTC'))
        startable, reason = instance.startable?
        expect(startable).to be_false
      end

      it "returns true if the instance matches the include tags specified in the options" do
        options = Ec2::Blackout::Options.new(:include_by_tag =>  ["foo=bar"])
        instance = stubbed_startable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags("foo" => "bar", Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-13 02:35:52 UTC'))
        startable, reason = instance.startable?
        expect(startable).to be_true
      end

      it "returns false if the instance does not match the include tags specified in the options" do
        options = Ec2::Blackout::Options.new(:include_by_tag =>  ["foo=bar"])
        instance = stubbed_startable_instance(aws_instance, options)
        aws_instance.stub(:tags).and_return(ec2_tags("bar" => "baz", Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-13 02:35:52 UTC'))
        startable, reason = instance.startable?
        expect(startable).to be_false
      end

    end

    def stubbed_stoppable_instance(underlying_aws_stub, options = Options.new)
      underlying_aws_stub.stub(:status).and_return(:running)
      underlying_aws_stub.stub(:has_elastic_ip?).and_return(false)
      underlying_aws_stub.stub(:tags).and_return(ec2_tags({}))
      underlying_aws_stub.stub(:add_tag)
      underlying_aws_stub.stub(:stop)
      underlying_aws_stub.stub(:root_device_type).and_return(:ebs)
      Ec2Instance.new(underlying_aws_stub, options)
    end

    def stubbed_startable_instance(underlying_aws_stub, options = Options.new)
      underlying_aws_stub.stub(:status).and_return(:stopped)
      underlying_aws_stub.stub(:has_elastic_ip?).and_return(false)
      underlying_aws_stub.stub(:tags).and_return(ec2_tags(Ec2Instance::TIMESTAMP_TAG_NAME => '2014-02-13 02:35:52 UTC'))
      underlying_aws_stub.stub(:associate_elastic_ip)
      underlying_aws_stub.stub(:start)
      Ec2Instance.new(underlying_aws_stub, options)
    end

    def expect_instance_filter(state, region)
      instances_stub = double("instances")
      ec2_stub = double("ec2 instance", :instances => instances_stub)
      AWS::EC2.should_receive(:new).with(:region => region).and_return(ec2_stub)
      instances_stub.should_receive(:filter).with('instance-state-name', state).and_return([double, double])
    end

    def ec2_tags(tags_hash)
      # Hack to add a "to_h" method to hash instance (ruby 1.9 doesn't have it, but 2.0 does).
      # This lets us use a simple hash instead of an instance of AWS::EC2::ResourceTagCollection to
      # represent the instance tags.
      if !tags_hash.respond_to?(:to_h)
        def tags_hash.to_h
          self
        end
      end
      tags_hash
    end

  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.gradle.api.artifacts.result (Gradle API 1.12)</title>
<META NAME="keywords" CONTENT="org.gradle.api.artifacts.result package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">

      Overview
    Package
      Class

      Deprecated
      Index
      Help

    Groovy Documentation

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Package org.gradle.api.artifacts.result

 Classes that compose the resolution result

    Interface Summary

        ComponentSelectionReason
        Answers the question why a component was selected during the dependency resolution.

        DependencyResult
        An edge in the dependency graph.

        ResolutionResult
        Contains the information about the result of dependency resolution.

        ResolvedComponentResult
        Represents a component instance in the resolved dependency graph.

        ResolvedDependencyResult
        A dependency that was resolved successfully.

        UnresolvedDependencyResult
        A dependency that could not be resolved.

Gradle API 1.12


text:
module Scripts::Injections
  extend ActiveSupport::Concern

  ODBC_CONNECTION_REGEX = /ODBC.connect\(?\s*['"](\w+)['"]\s*\)?/
  AR_CONNECTION_REGEX   = /@@ar_connection\[['"](\w+)['"]\]/
  DB_PROPERTY_REGEX     = /@@databases\[['"](\w+)['"]\]\[['"](\w+)['"]\]/

  def text_with_injections
    lines = text.each_line.map do |line|
      if (match = line.match(ODBC_CONNECTION_REGEX)) && line[','].blank?
        connection_name = match.captures.first

        inject_db_properties line, connection_name
      elsif (match = line.match(AR_CONNECTION_REGEX))
        connection_name = match.captures.first

        inject_ar_connection line, connection_name
      elsif (match = line.match(DB_PROPERTY_REGEX))
        connection_name = match.captures.first
        property_key    = match.captures.last

        replace_db_property line, connection_name, property_key
      else
        line
      end
    end

    lines.join
  end

  private

    def inject_db_properties line, connection_name
      db = Database.current.find_by name: connection_name

      if db && db.driver.downcase =~ /freetds/ && db.user && db.password
        arguments = "'#{connection_name}', '#{db.user}', '#{db.password}'"
        new_line  = line.sub ODBC_CONNECTION_REGEX, "ODBC.connect(#{arguments})"

        "#{new_line}\r\n"
      else
        line
      end
    end

    def inject_ar_connection line, connection_name
      @db = Database.current.find_by name: connection_name

      if @db
        line.sub AR_CONNECTION_REGEX, "_ar_connection(#{@db.ar_config}, '#{@db.cipher_key}', '#{@db.cipher_iv}')"
      else
        line
      end
    end

    def replace_db_property line, connection_name, property_key
      db = Database.current.find_by name: connection_name

      if db && db.property(property_key)
        value = db.property property_key

        line.sub DB_PROPERTY_REGEX, "'#{value}'"
      else
        line
      end
    end
end


text:
package org.springframework.security.web.bind.support;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.util.ReflectionUtils;

/**
 * @author Rob Winch
 *
 */
@SuppressWarnings("deprecation")
public class AuthenticationPrincipalArgumentResolverTests {
	private Object expectedPrincipal;
	private AuthenticationPrincipalArgumentResolver resolver;

	@Before
	public void setup() {
		resolver = new AuthenticationPrincipalArgumentResolver();
	}

	@After
	public void cleanup() {
		SecurityContextHolder.clearContext();
	}

	@Test
	public void supportsParameterNoAnnotation() throws Exception {
		assertThat(resolver.supportsParameter(showUserNoAnnotation())).isFalse();
	}

	@Test
	public void supportsParameterAnnotation() throws Exception {
		assertThat(resolver.supportsParameter(showUserAnnotationObject())).isTrue();
	}

	@Test
	public void supportsParameterCustomAnnotation() throws Exception {
		assertThat(resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
	}

	@Test
	public void resolveArgumentNullAuthentication() throws Exception {
		assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
				.isNull();
	}

	@Test
	public void resolveArgumentNullPrincipal() throws Exception {
		setAuthenticationPrincipal(null);
		assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
				.isNull();
	}

	@Test
	public void resolveArgumentString() throws Exception {
		setAuthenticationPrincipal("john");
		assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
				.isEqualTo(expectedPrincipal);
	}

	@Test
	public void resolveArgumentPrincipalStringOnObject() throws Exception {
		setAuthenticationPrincipal("john");
		assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
				.isEqualTo(expectedPrincipal);
	}

	@Test
	public void resolveArgumentUserDetails() throws Exception {
		setAuthenticationPrincipal(new User("user", "password",
				AuthorityUtils.createAuthorityList("ROLE_USER")));
		assertThat(
				resolver.resolveArgument(showUserAnnotationUserDetails(), null, null,
						null)).isEqualTo(expectedPrincipal);
	}

	@Test
	public void resolveArgumentCustomUserPrincipal() throws Exception {
		setAuthenticationPrincipal(new CustomUserPrincipal());
		assertThat(
				resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null,
						null, null)).isEqualTo(expectedPrincipal);
	}

	@Test
	public void resolveArgumentCustomAnnotation() throws Exception {
		setAuthenticationPrincipal(new CustomUserPrincipal());
		assertThat(resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
				.isEqualTo(expectedPrincipal);
	}

	@Test
	public void resolveArgumentNullOnInvalidType() throws Exception {
		setAuthenticationPrincipal(new CustomUserPrincipal());
		assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
				.isNull();
	}

	@Test(expected = ClassCastException.class)
	public void resolveArgumentErrorOnInvalidType() throws Exception {
		setAuthenticationPrincipal(new CustomUserPrincipal());
		resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null);
	}

	@Test(expected = ClassCastException.class)
	public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
		setAuthenticationPrincipal(new CustomUserPrincipal());
		resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null,
				null, null);
	}

	@Test
	public void resolveArgumentObject() throws Exception {
		setAuthenticationPrincipal(new Object());
		assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
				.isEqualTo(expectedPrincipal);
	}

	private MethodParameter showUserNoAnnotation() {
		return getMethodParameter("showUserNoAnnotation", String.class);
	}

	private MethodParameter showUserAnnotationString() {
		return getMethodParameter("showUserAnnotation", String.class);
	}

	private MethodParameter showUserAnnotationErrorOnInvalidType() {
		return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class);
	}

	private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() {
		return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType",
				String.class);
	}

	private MethodParameter showUserAnnotationUserDetails() {
		return getMethodParameter("showUserAnnotation", UserDetails.class);
	}

	private MethodParameter showUserAnnotationCustomUserPrincipal() {
		return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class);
	}

	private MethodParameter showUserCustomAnnotation() {
		return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class);
	}

	private MethodParameter showUserAnnotationObject() {
		return getMethodParameter("showUserAnnotation", Object.class);
	}

	private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
		Method method = ReflectionUtils.findMethod(TestController.class, methodName,
				paramTypes);
		return new MethodParameter(method, 0);
	}

	@Target({ ElementType.PARAMETER })
	@Retention(RetentionPolicy.RUNTIME)
	@AuthenticationPrincipal
	static @interface CurrentUser {
	}

	@Target({ ElementType.PARAMETER })
	@Retention(RetentionPolicy.RUNTIME)
	@AuthenticationPrincipal(errorOnInvalidType = true)
	static @interface CurrentUserErrorOnInvalidType {
	}

	public static class TestController {
		public void showUserNoAnnotation(String user) {
		}

		public void showUserAnnotation(@AuthenticationPrincipal String user) {
		}

		public void showUserAnnotationErrorOnInvalidType(
				@AuthenticationPrincipal(errorOnInvalidType = true) String user) {
		}

		public void showUserAnnotationCurrentUserErrorOnInvalidType(
				@CurrentUserErrorOnInvalidType String user) {
		}

		public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) {
		}

		public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) {
		}

		public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) {
		}

		public void showUserAnnotation(@AuthenticationPrincipal Object user) {
		}
	}

	private static class CustomUserPrincipal {
	}

	private void setAuthenticationPrincipal(Object principal) {
		this.expectedPrincipal = principal;
		SecurityContextHolder.getContext()
				.setAuthentication(
						new TestingAuthenticationToken(expectedPrincipal, "password",
								"ROLE_USER"));
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.References
{
    [ExportLanguageService(typeof(IFindUsagesService), StringConstants.CSharpLspLanguageName), Shared]
    internal class CSharpLspFindUsagesService : RoslynFindUsagesService
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public CSharpLspFindUsagesService(CSharpLspClientServiceFactory csharpLspClientServiceFactory, RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace)
            : base(csharpLspClientServiceFactory, remoteLanguageServiceWorkspace)
        {
        }
    }

    [ExportLanguageService(typeof(IFindUsagesService), StringConstants.VBLspLanguageName), Shared]
    internal class VBLspFindUsagesService : RoslynFindUsagesService
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public VBLspFindUsagesService(VisualBasicLspClientServiceFactory vbLspClientServiceFactory, RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace)
            : base(vbLspClientServiceFactory, remoteLanguageServiceWorkspace)
        {
        }
    }
}


text:
/*
  Inject code into the target process to load our DLL.	The target thread
  should be suspended on entry; it remains suspended on exit.

  Initially I used the "stack" method of injection.  However, this fails
  when DEP is active, since that doesn't allow code to execute in the stack.
  To overcome this I used the "CreateRemoteThread" method.  However, this
  would fail with Wselect, a program to assist batch files.  Wselect runs,
  but it has no output.  As it turns out, removing the suspended flag would
  make Wselect work, but it caused problems with everything else.  So now I
  allocate a section of memory and change the context to run from there.  At
  first I had an event to signal when the library was loaded, then the memory
  was released.  However, that wouldn't work with -p and CMD.EXE (4NT v8
  worked fine).  Since it's possible the DLL might start a process suspended,
  I've decided to simply keep the memory.
*/

#include "ansicon.h"

#ifdef _WIN64
#ifndef WOW64_CONTEXT_ALL
#include "wow64.h"

TWow64GetThreadContext Wow64GetThreadContext;
TWow64SetThreadContext Wow64SetThreadContext;
#define IMPORT_WOW64
#endif

#define CONTEXT 	 WOW64_CONTEXT
#undef	CONTEXT_CONTROL
#define CONTEXT_CONTROL  WOW64_CONTEXT_CONTROL
#define GetThreadContext Wow64GetThreadContext
#define SetThreadContext Wow64SetThreadContext

#define MakeVA( cast, offset ) (cast)((DWORD_PTR)base + (DWORD)(offset))

extern DWORD LLW32;
LPVOID base;

int export_cmp( const void* a, const void* b )
{
  return strcmp( (LPCSTR)a, MakeVA( LPCSTR, *(const PDWORD)b ) );
}

/*
  Get the address of the 32-bit LoadLibraryW function from 64-bit code.  This
  was originally done via executing a helper program (ANSI-LLW.exe), but for
  some reason, virus scanners really didn't like it (even when I rewrote it in
  assembly so it was 1024 bytes and literally two instructions, virustotal
  still had three scanners complaining).  Now I do it the "hard" way - load the
  32-bit kernel32.dll directly and search the exports.	Even worse, it seems
  Wow64 loads kernel32.dll at a different base address each boot (at least, I
  hope it only changes each boot).  Fortunately, loading the DLL as an image in
  64-bit code seems to use the 32-bit address.
*/
BOOL get_LLW32( void )
{
  HMODULE kernel32;
  TCHAR   buf[MAX_PATH];
  UINT	  len;
  PIMAGE_DOS_HEADER	  pDosHeader;
  PIMAGE_NT_HEADERS32	  pNTHeader;
  PIMAGE_EXPORT_DIRECTORY pExportDir;
  PDWORD  fun_table, name_table;
  PWORD   ord_table;
  PDWORD  pLLW;

  len = GetSystemWow64Directory( buf, MAX_PATH );
  wcscpy( buf + len, L"\\kernel32.dll" );
  // MinGW-w64 has a typo, calling it LINRARY.
  kernel32 = LoadLibraryEx( buf, NULL, 0x20/*LOAD_LIBRARY_AS_IMAGE_RESOURCE*/ );
  if (kernel32 == NULL)
  {
    DEBUGSTR( 1, L"Unable to load 32-bit kernel32.dll!" );
    return FALSE;
  }
  // The handle uses low bits as flags, so strip 'em off.
  base = (LPVOID)((DWORD_PTR)kernel32 & 0xFFFF0000);

  // Tests to make sure we're looking at a module image (the 'MZ' header)
  pDosHeader = (PIMAGE_DOS_HEADER)base;
  if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
  {
    DEBUGSTR( 1, L"Image has no DOS header!" );
    return FALSE;
  }

  // The MZ header has a pointer to the PE header
  pNTHeader = MakeVA( PIMAGE_NT_HEADERS32, pDosHeader->e_lfanew );

  // One more test to make sure we're looking at a "PE" image
  if (pNTHeader->Signature != IMAGE_NT_SIGNATURE)
  {
    DEBUGSTR( 1, L"Image has no NT header!" );
    return FALSE;
  }

  // We now have a valid pointer to the module's PE header.
  // Get a pointer to its exports section.
  pExportDir = MakeVA( PIMAGE_EXPORT_DIRECTORY,
			pNTHeader->OptionalHeader.
			 DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].
			  VirtualAddress );

  fun_table  = MakeVA( PDWORD, pExportDir->AddressOfFunctions );
  name_table = MakeVA( PDWORD, pExportDir->AddressOfNames );
  ord_table  = MakeVA( PWORD,  pExportDir->AddressOfNameOrdinals );

  pLLW = bsearch( "LoadLibraryW", name_table, pExportDir->NumberOfNames,
		  sizeof(DWORD), export_cmp );
  if (pLLW == NULL)
  {
    DEBUGSTR( 1, L"Could not find LoadLibraryW!" );
    return FALSE;
  }
  LLW32 = MakeVA( DWORD, fun_table[ord_table[pLLW - name_table]] );

  FreeLibrary( kernel32 );
  return TRUE;
}
#else
DWORD LLW32;
#endif

void InjectDLL32( LPPROCESS_INFORMATION ppi, LPCTSTR dll )
{
  CONTEXT context;
  DWORD   len;
  LPVOID  mem;
  DWORD   mem32;
  #define CODESIZE 20
  BYTE	  code[CODESIZE+TSIZE(MAX_PATH)];
  union
  {
    PBYTE  pB;
    PDWORD pL;
  } ip;

  len = TSIZE(lstrlen( dll ) + 1);
  if (len > TSIZE(MAX_PATH))
    return;

  if (LLW32 == 0)
  {
#ifdef _WIN64
    if (!get_LLW32())
      return;
#else
    LLW32 = (DWORD)GetProcAddress( GetModuleHandleA( "kernel32.dll" ),
						     "LoadLibraryW" );
#endif
  }
#ifdef IMPORT_WOW64
  if (Wow64GetThreadContext == 0)
  {
    #define GETPROC( proc ) proc = (T##proc)GetProcAddress( hKernel, #proc )
    HMODULE hKernel = GetModuleHandleA( "kernel32.dll" );
    GETPROC( Wow64GetThreadContext );
    GETPROC( Wow64SetThreadContext );
    // Assume if one is defined, so is the other.
    if (Wow64GetThreadContext == 0)
    {
      DEBUGSTR( 1, L"Failed to get pointer to Wow64GetThreadContext.\n" );
      return;
    }
  }
#endif

  CopyMemory( code + CODESIZE, dll, len );
  len += CODESIZE;

  context.ContextFlags = CONTEXT_CONTROL;
  GetThreadContext( ppi->hThread, &context );
  mem = VirtualAllocEx( ppi->hProcess, NULL, len, MEM_COMMIT,
			PAGE_EXECUTE_READWRITE );
  mem32 = (DWORD)(DWORD_PTR)mem;

  ip.pB = code;

  *ip.pB++ = 0x68;			// push  eip
  *ip.pL++ = context.Eip;
  *ip.pB++ = 0x9c;			// pushf
  *ip.pB++ = 0x60;			// pusha
  *ip.pB++ = 0x68;			// push  L"path\to\ANSI32.dll"
  *ip.pL++ = mem32 + CODESIZE;
  *ip.pB++ = 0xe8;			// call  LoadLibraryW
  *ip.pL++ = LLW32 - (mem32 + (DWORD)(ip.pB+4 - code));
  *ip.pB++ = 0x61;			// popa
  *ip.pB++ = 0x9d;			// popf
  *ip.pB++ = 0xc3;			// ret

  WriteProcessMemory( ppi->hProcess, mem, code, len, NULL );
  FlushInstructionCache( ppi->hProcess, mem, len );
  context.Eip = mem32;
  SetThreadContext( ppi->hThread, &context );
}


text:
require 'diameter/avp_parser'
require 'diameter/u24'

# The Diameter module
module Diameter
  # A Diameter message.
  #
  # @!attribute [r] version
  #   The Diameter protocol version (currently always 1)
  # @!attribute [r] command_code
  #   The Diameter Command-Code of this messsage.
  # @!attribute [r] app_id
  #   The Diameter application ID of this message, or 0 for base
  #   protocol messages.
  # @!attribute [r] hbh
  #   The hop-by-hop identifier of this message.
  # @!attribute [r] ete
  #   The end-to-end identifier of this message.
  # @!attribute [r] request
  #   Whether this message is a request.
  # @!attribute [r] answer
  #   Whether this message is an answer.
  class Message
    attr_reader :version, :command_code, :app_id, :hbh, :ete, :request, :answer
    include Internals

    # Creates a new Diameter message.
    #
    # @param [Hash] options The options
    # @option options [Fixnum] command_code
    #   The Diameter Command-Code of this messsage.
    # @option options [Fixnum] app_id
    #   The Diameter application ID of this message, or 0 for base
    #   protocol messages.
    # @option options [Fixnum] hbh
    #   The hop-by-hop identifier of this message.
    # @option options [Fixnum] ete
    #   The end-to-end identifier of this message.
    # @option options [true, false] request
    #   Whether this message is a request. Defaults to true.
    # @option options [true, false] proxyable
    #   Whether this message can be forwarded on. Defaults to true.
    # @option options [true, false] error
    #   Whether this message is a Diameter protocol error. Defaults to false.
    # @option options [Array<AVP>] avps
    #   The list of AVPs to include on this message.
    def initialize(options = {})
      @version = 1
      @command_code = options[:command_code]
      @app_id = options[:app_id]
      @hbh = options[:hbh] || Message.next_hbh
      @ete = options[:ete] || Message.next_ete

      @request = options.fetch(:request, true)
      @answer = !@request
      @proxyable = options.fetch(:proxyable, false)
      @retransmitted = false
      @error = false

      @avps = options[:avps] || []
    end

    # Represents this message (and all its AVPs) in human-readable
    # string form.
    #
    # @see AVP::to_s for how the AVPs are represented.
    # @return [String]
    def to_s
      "#{@command_code}: #{@avps.collect(&:to_s)}"
    end

    # Serializes a Diameter message (header plus AVPs) into the series
    # of bytes representing it on the wire.
    #
    # @return [String] The byte-encoded form.
    def to_wire
      content = ''
      @avps.each { |a| content += a.to_wire }
      length_8, length_16 = Internals::UInt24.to_u8_and_u16(content.length + 20)
      code_8, code_16 = Internals::UInt24.to_u8_and_u16(@command_code)
      request_flag = @request ? '1' : '0'
      proxy_flag = @proxyable ? '1' : '0'
      flags_str = "#{request_flag}#{proxy_flag}000000"

      header = [@version, length_8, length_16, flags_str, code_8, code_16, @app_id, @hbh, @ete].pack('CCnB8CnNNN')
      header + content
    end

    # @!group AVP retrieval

    # Returns the first AVP with the given name. Only covers "top-level"
    # AVPs - it won't look inside Grouped AVPs.
    #
    # Also available as [], e.g. message['Result-Code']
    #
    # @param name [String] The AVP name, either one predefined in
    #   {Constants::AVAILABLE_AVPS} or user-defined with {AVP.define}
    #
    # @return [AVP] if there is an AVP with that name
    # @return [nil] if there is not an AVP with that name
    def avp_by_name(name)
      code, _type, vendor = Internals::AVPNames.get(name)
      avp_by_code(code, vendor)
    end

    # Returns all AVPs with the given name. Only covers "top-level"
    # AVPs - it won't look inside Grouped AVPs.
    #
    # @param name [String] The AVP name, either one predefined in
    #   {Constants::AVAILABLE_AVPS} or user-defined with {AVP.define}
    #
    # @return [Array<AVP>]
    def all_avps_by_name(name)
      code, _type, vendor = Internals::AVPNames.get(name)
      all_avps_by_code(code, vendor)
    end

    alias_method :avp, :avp_by_name
    alias_method :[], :avp_by_name
    alias_method :avps, :all_avps_by_name

    # @private
    # Prefer AVP.define and the by-name versions to this
    #
    # Returns the first AVP with the given code and vendor. Only covers "top-level"
    # AVPs - it won't look inside Grouped AVPs.
    #
    # @param code [Fixnum] The AVP Code
    # @param vendor [Fixnum] Optional vendor ID for a vendor-specific
    #   AVP.
    # @return [AVP] if there is an AVP with that code/vendor
    # @return [nil] if there is not an AVP with that code/vendor
    def avp_by_code(code, vendor = 0)
      avps = all_avps_by_code(code, vendor)
      if avps.empty?
        nil
      else
        avps[0]
      end
    end

    # @private
    # Prefer AVP.define and the by-name versions to this
    #
    # Returns all AVPs with the given code and vendor. Only covers "top-level"
    # AVPs - it won't look inside Grouped AVPs.
    #
    # @param code [Fixnum] The AVP Code
    # @param vendor [Fixnum] Optional vendor ID for a vendor-specific
    #   AVP.
    # @return [Array<AVP>]
    def all_avps_by_code(code, vendor = 0)
      @avps.select do |a|
        vendor_match =
          if a.vendor_specific?
            a.vendor_id == vendor
          else
            vendor == 0
          end
        (a.code == code) && vendor_match
      end
    end

    # Does this message contain a (top-level) AVP with this name?
    # @param name [String] The AVP name, either one predefined in
    #   {Constants::AVAILABLE_AVPS} or user-defined with {AVP.define}
    #
    # @return [true, false]
    def has_avp?(name)
      !!avp(name)
    end

    # @private
    #
    # Not recommended for normal use - all AVPs should be given to the
    # constructor. Used to allow the stack to add appropriate
    # Origin-Host/Origin-Realm AVPs to outbound messages.
    #
    # @param host [String] The Diameter Identity for the stack.
    # @param realm [String] The Diameter realm for the stack.
    def add_origin_host_and_realm(host, realm)
      @avps << AVP.create("Origin-Host", host) unless has_avp? 'Origin-Host'
      @avps << AVP.create("Origin-Realm", realm) unless has_avp? 'Origin-Realm'
    end

    # @!endgroup

    # @!group Parsing

    # Parses the first four bytes of the Diameter header to learn the
    # length. Callers should use this to work out how many more bytes
    # they need to read off a TCP connection to pass to self.from_bytes.
    #
    # @param header [String] A four-byte Diameter header
    # @return [Fixnum] The message length field from the header
    def self.length_from_header(header)
      _version, length_8, length_16 = header.unpack('CCn')
      Internals::UInt24.from_u8_and_u16(length_8, length_16)
    end

    # Parses a byte representation (a 20-byte header plus AVPs) into a
    # DiameterMessage object.
    #
    # @param bytes [String] The on-the-wire byte representation of a
    #   Diameter message.
    # @return [DiameterMessage] The parsed object form.
    def self.from_bytes(bytes)
      header = bytes[0..20]
      version, _length_8, _length_16, flags_str, code_8, code_16, app_id, hbh, ete = header.unpack('CCnB8CnNNN')
      command_code = Internals::UInt24.from_u8_and_u16(code_8, code_16)

      request = (flags_str[0] == '1')
      proxyable = (flags_str[1] == '1')

      avps = Internals::AVPParser.parse_avps_int(bytes[20..-1])
      Message.new(version: version, command_code: command_code, app_id: app_id, hbh: hbh, ete: ete, request: request, proxyable: proxyable, retransmitted: false, error: false, avps: avps)
    end

    # @!endgroup

    # Generates an answer to this request, filling in a Result-Code or
    # Experimental-Result AVP.
    #
    # @param result_code [Fixnum] The value for the Result-Code AVP
    # @option opts [Fixnum] experimental_result_vendor
    #   If given, creates an Experimental-Result AVP with this vendor
    #   instead of the Result-Code AVP.
    # @option opts [Array<String>] copying_avps
    #   A list of AVP names to copy from the request to the answer.
    # @option opts [Array<Diameter::AVP>] avps
    #   A list of AVP objects to add on the answer.
    # @return [Diameter::Message] The response created.
    def create_answer(result_code, opts={})
      fail "Cannot answer an answer" if answer

      avps = []
      avps << avp_by_name("Session-Id") unless avp_by_name("Session-Id").nil?
      avps += opts.fetch(:avps, [])
      avps << if opts[:experimental_result_vendor]
                AVP.create("Experimental-Result",
                           [AVP.create("Experimental-Result-Code", result_code),
                            AVP.create("Vendor-Id", opts[:experimental_result_vendor])])
              else
                AVP.create("Result-Code", result_code)
              end

      avps += opts.fetch(:copying_avps, []).collect do |name|
        src_avp = avp_by_name(name)

        fail if src_avp.nil?

        src_avp.dup
      end

      Message.new(version: version, command_code: command_code, app_id: app_id, hbh: hbh, ete: ete, request: false, proxyable: @proxyable, retransmitted: false, error: false, avps: avps)
    end

    private
    def self.next_hbh
      @hbh ||= rand(10000)
      @hbh += 1
      @hbh
    end

    def self.next_ete
      @ete ||= (Time.now.to_i & 0x00000fff) + (rand(2**32) & 0xfffff000)
      @ete += 1
    end

  end
end


text:
{-# LANGUAGE OverloadedStrings #-}

-- | 'fetch-hackage pkg' fetches and unpacks the sources of the given package
--   and prints some information about it

import Scoutess.Service.Source.Core
import Scoutess.Service.Source.Hackage (fetchHackage)

import Data.Text                       (Text, pack, unpack)
import Distribution.Package
import Distribution.PackageDescription
import System.Environment              (getArgs)

main = do
  [pkg] <- getArgs
  let dir = "./"
  result <- fetchHackage (SourceConfig dir) (pack pkg) Nothing
  case result of
    Left except      -> putStrLn (show except)
    Right sourceInfo -> printPackageInfo sourceInfo

  where printPackageInfo si = do
          let pkgDescr      = srcPackageDescription si
          let pkgIdentifier = package pkgDescr
          putStrLn $ "Fetched package " ++ unpack (srcVersion si)
          putStrLn $ " maintained by " ++ maintainer pkgDescr
          putStrLn $ " licensed under " ++ show (license pkgDescr)
          putStrLn $ " with sources living in " ++ srcPath si


text:
namespace WASM
{
	extern bool check_limits;
}
namespace Serialization
{
	// An exception that is thrown for various errors during serialization.
	// Any code using serialization should handle it!
	struct FatalSerializationException
	{
		std::string message;
		FatalSerializationException(std::string&& inMessage)
		: message(std::move(inMessage)) {}
	};

	// An abstract output stream.
	struct OutputStream
	{
		enum { isInput = false };

		OutputStream(): next(nullptr), end(nullptr) {}

		Uptr capacity() const { return SIZE_MAX; }

		// Advances the stream cursor by numBytes, and returns a pointer to the previous stream cursor.
		inline U8* advance(Uptr numBytes)
		{
			if(next + numBytes > end) { extendBuffer(numBytes); }
			WAVM_ASSERT_THROW(next + numBytes <= end);

			U8* data = next;
			next += numBytes;
			return data;
		}

	protected:

		U8* next;
		U8* end;

		// Called when there isn't enough space in the buffer to hold a write to the stream.
		// Should update next and end to point to a new buffer, and ensure that the new
		// buffer has at least numBytes. May throw FatalSerializationException.
		virtual void extendBuffer(Uptr numBytes) = 0;
	};

	// An output stream that writes to an array of bytes.
	struct ArrayOutputStream : public OutputStream
	{
		// Moves the output array from the stream to the caller.
		std::vector<U8>&& getBytes()
		{
			bytes.resize(next - bytes.data());
			next = nullptr;
			end = nullptr;
			return std::move(bytes);
		}

	private:

		std::vector<U8> bytes;

		virtual void extendBuffer(Uptr numBytes)
		{
			const Uptr nextIndex = next - bytes.data();

			// Grow the array by larger and larger increments, so the time spent growing
			// the buffer is O(1).
			bytes.resize(std::max((Uptr)nextIndex+numBytes,(Uptr)bytes.size() * 7 / 5 + 32));

			next = bytes.data() + nextIndex;
			end = bytes.data() + bytes.size();
		}
		virtual bool canExtendBuffer(Uptr numBytes) const { return true; }
	};

	// An abstract input stream.
	struct InputStream
	{
		enum { isInput = true };

		InputStream(const U8* inNext,const U8* inEnd): next(inNext), end(inEnd) {}

		virtual Uptr capacity() const = 0;

		// Advances the stream cursor by numBytes, and returns a pointer to the previous stream cursor.
		inline const U8* advance(Uptr numBytes)
		{
			if(next + numBytes > end) { getMoreData(numBytes); }
			const U8* data = next;
			next += numBytes;
			return data;
		}

		// Returns a pointer to the current stream cursor, ensuring that there are at least numBytes following it.
		inline const U8* peek(Uptr numBytes)
		{
			if(next + numBytes > end) { getMoreData(numBytes); }
			return next;
		}

	protected:

		const U8* next;
		const U8* end;

		// Called when there isn't enough space in the buffer to satisfy a read from the stream.
		// Should update next and end to point to a new buffer, and ensure that the new
		// buffer has at least numBytes. May throw FatalSerializationException.
		virtual void getMoreData(Uptr numBytes) = 0;
	};

	// An input stream that reads from a contiguous range of memory.
	struct MemoryInputStream : InputStream
	{
		MemoryInputStream(const U8* begin,Uptr numBytes): InputStream(begin,begin+numBytes) {}
		virtual Uptr capacity() const { return end - next; }
	private:
		virtual void getMoreData(Uptr numBytes) { throw FatalSerializationException("expected data but found end of stream"); }
	};

	// Serialize raw byte sequences.
	FORCEINLINE void serializeBytes(OutputStream& stream,const U8* bytes,Uptr numBytes)
	{ memcpy(stream.advance(numBytes),bytes,numBytes); }
	FORCEINLINE void serializeBytes(InputStream& stream,U8* bytes,Uptr numBytes)
	{
      if ( numBytes < eosio::chain::wasm_constraints::wasm_page_size )
         memcpy(bytes,stream.advance(numBytes),numBytes);
      else
         throw FatalSerializationException(std::string("Trying to deserialize bytes of size : " + std::to_string((uint64_t)numBytes)));
   }

	// Serialize basic C++ types.
	template<typename Stream,typename Value>
	FORCEINLINE void serializeNativeValue(Stream& stream,Value& value) { serializeBytes(stream,(U8*)&value,sizeof(Value)); }

	template<typename Stream> void serialize(Stream& stream,U8& i) { serializeNativeValue(stream,i); }
	template<typename Stream> void serialize(Stream& stream,U32& i) { serializeNativeValue(stream,i); }
	template<typename Stream> void serialize(Stream& stream,U64& i) { serializeNativeValue(stream,i);  }
	template<typename Stream> void serialize(Stream& stream,I8& i) { serializeNativeValue(stream,i); }
	template<typename Stream> void serialize(Stream& stream,I32& i) { serializeNativeValue(stream,i); }
	template<typename Stream> void serialize(Stream& stream,I64& i) { serializeNativeValue(stream,i); }
	template<typename Stream> void serialize(Stream& stream,F32& f) { serializeNativeValue(stream,f); }
	template<typename Stream> void serialize(Stream& stream,F64& f) { serializeNativeValue(stream,f); }

	// LEB128 variable-length integer serialization.
	template<typename Value,Uptr maxBits>
	FORCEINLINE void serializeVarInt(OutputStream& stream,Value& inValue,Value minValue,Value maxValue)
	{
		Value value = inValue;

		if(value < minValue || value > maxValue)
		{
			throw FatalSerializationException(std::string("out-of-range value: ") + std::to_string(minValue) + "<=" + std::to_string(value) + "<=" + std::to_string(maxValue));
		}

		bool more = true;
		while(more)
		{
			U8 outputByte = (U8)(value&127);
			value >>= 7;
			more = std::is_signed<Value>::value
				? (value != 0 && value != Value(-1)) || (value >= 0 && (outputByte & 0x40)) || (value < 0 && !(outputByte & 0x40))
				: (value != 0);
			if(more) { outputByte |= 0x80; }
			*stream.advance(1) = outputByte;
		};
	}

	template<typename Value,Uptr maxBits>
	FORCEINLINE void serializeVarInt(InputStream& stream,Value& value,Value minValue,Value maxValue)
	{
		// First, read the variable number of input bytes into a fixed size buffer.
		enum { maxBytes = (maxBits + 6) / 7 };
		U8 bytes[maxBytes] = {0};
		Uptr numBytes = 0;
		I8 signExtendShift = (I8)sizeof(Value) * 8;
		while(numBytes < maxBytes)
		{
			U8 byte = *stream.advance(1);
			bytes[numBytes] = byte;
			++numBytes;
			signExtendShift -= 7;
			if(!(byte & 0x80)) { break; }
		};

		// Ensure that the input does not encode more than maxBits of data.
		enum { numUsedBitsInLastByte = maxBits - (maxBytes-1) * 7 };
		enum { numUnusedBitsInLast = 8 - numUsedBitsInLastByte };
		enum { lastBitUsedMask = U8(1<<(numUsedBitsInLastByte-1)) };
		enum { lastByteUsedMask = U8(1<<numUsedBitsInLastByte)-U8(1) };
		enum { lastByteSignedMask = U8(~U8(lastByteUsedMask) & ~U8(0x80)) };
		const U8 lastByte = bytes[maxBytes-1];
		if(!std::is_signed<Value>::value)
		{
			if((lastByte & ~lastByteUsedMask) != 0)
			{
				throw FatalSerializationException("Invalid unsigned LEB encoding: unused bits in final byte must be 0");
			}
		}
		else
		{
			const I8 signBit = I8((lastByte & lastBitUsedMask) << numUnusedBitsInLast);
			const I8 signExtendedLastBit = signBit >> numUnusedBitsInLast;
			if((lastByte & ~lastByteUsedMask) != (signExtendedLastBit & lastByteSignedMask))
			{
				throw FatalSerializationException(
					"Invalid signed LEB encoding: unused bits in final byte must match the most-significant used bit");
			}
		}

		// Decode the buffer's bytes into the output integer.
		value = 0;
		for(Uptr byteIndex = 0;byteIndex < maxBytes;++byteIndex)
		{ value |= Value(bytes[byteIndex] & ~0x80) << (byteIndex * 7); }

		// Sign extend the output integer to the full size of Value.
		if(std::is_signed<Value>::value && signExtendShift > 0)
		{ value = Value(value << signExtendShift) >> signExtendShift; }

		// Check that the output integer is in the expected range.
		if(value < minValue || value > maxValue)
		{ throw FatalSerializationException(std::string("out-of-range value: ") + std::to_string(minValue) + "<=" + std::to_string(value) + "<=" + std::to_string(maxValue)); }
	}

	// Helpers for various common LEB128 parameters.
	template<typename Stream,typename Value> void serializeVarUInt1(Stream& stream,Value& value) { serializeVarInt<Value,1>(stream,value,0,1); }
	template<typename Stream,typename Value> void serializeVarUInt7(Stream& stream,Value& value) { serializeVarInt<Value,7>(stream,value,0,127); }
	template<typename Stream,typename Value> void serializeVarUInt32(Stream& stream,Value& value) { serializeVarInt<Value,32>(stream,value,0,UINT32_MAX); }
	template<typename Stream,typename Value> void serializeVarUInt64(Stream& stream,Value& value) { serializeVarInt<Value,64>(stream,value,0,UINT64_MAX); }
	template<typename Stream,typename Value> void serializeVarInt7(Stream& stream,Value& value) { serializeVarInt<Value,7>(stream,value,-64,63); }
	template<typename Stream,typename Value> void serializeVarInt32(Stream& stream,Value& value) { serializeVarInt<Value,32>(stream,value,INT32_MIN,INT32_MAX); }
	template<typename Stream,typename Value> void serializeVarInt64(Stream& stream,Value& value) { serializeVarInt<Value,64>(stream,value,INT64_MIN,INT64_MAX); }

	// Serializes a constant. If deserializing, throws a FatalSerializationException if the deserialized value doesn't match the constant.
	template<typename Constant>
	void serializeConstant(InputStream& stream,const char* constantMismatchMessage,Constant constant)
	{
		Constant savedConstant;
		serialize(stream,savedConstant);
		if(savedConstant != constant)
		{
			throw FatalSerializationException(std::string(constantMismatchMessage) + ": loaded " + std::to_string(savedConstant) + " but was expecting " + std::to_string(constant));
		}
	}
	template<typename Constant>
	void serializeConstant(OutputStream& stream,const char* constantMismatchMessage,Constant constant)
	{
		serialize(stream,constant);
	}

	// Serialize containers.
	template<typename Stream>
	void serialize(Stream& stream,std::string& string)
	{
      constexpr size_t max_size = eosio::chain::wasm_constraints::maximum_func_local_bytes;
		Uptr size = string.size();
		serializeVarUInt32(stream,size);
		if(Stream::isInput)
		{
			// Advance the stream before resizing the string:
			// try to get a serialization exception before making a huge allocation for malformed input.
			const U8* inputBytes = stream.advance(size);
         if (size >= max_size && WASM::check_limits)
            throw FatalSerializationException(std::string("Trying to deserialize string of size : " + std::to_string((uint64_t)size) + ", which is over by "+std::to_string(size - max_size )+" bytes"));
			string.resize(size);
			memcpy(const_cast<char*>(string.data()),inputBytes,size);
			string.shrink_to_fit();
		}
		else { serializeBytes(stream,(U8*)string.c_str(),size); }
	}

	template<typename Stream,typename Element,typename Allocator,typename SerializeElement>
	void serializeArray(Stream& stream,std::vector<Element,Allocator>& vector,SerializeElement serializeElement)
	{
      constexpr size_t max_size = eosio::chain::wasm_constraints::maximum_func_local_bytes;
		Uptr size = vector.size();
		serializeVarUInt32(stream,size);
		if(Stream::isInput)
		{
			// Grow the vector one element at a time:
			// try to get a serialization exception before making a huge allocation for malformed input.
			vector.clear();
         if (size >= max_size && WASM::check_limits)
            throw FatalSerializationException(std::string("Trying to deserialize array of size : " + std::to_string((uint64_t)size) + ", which is over by "+std::to_string(size - max_size )+" bytes"));
			for(Uptr index = 0;index < size;++index)
			{
				vector.push_back(Element());
				serializeElement(stream,vector.back());
			}
         vector.shrink_to_fit();
		}
		else
		{
			for(Uptr index = 0;index < vector.size();++index) { serializeElement(stream,vector[index]); }
		}
	}

	template<typename Stream,typename Element,typename Allocator>
	void serialize(Stream& stream,std::vector<Element,Allocator>& vector)
	{
		serializeArray(stream,vector,[](Stream& stream,Element& element){serialize(stream,element);});
	}
}


text:
package agents.firm.utilities;

import agents.firm.Department;
import model.utilities.filters.ExponentialFilter;

/**
 *
Description

 *
 Simple price averager using ExponentialFilter
 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author carrknight
 * @version 2014-06-14
 * @see
 */
public class ExponentialPriceAverager implements PriceAverager {

    private final ExponentialFilter<Integer> averagedPrice;

    /**
     * when we fail to trade, if this flag is true we feed a "0" price for that day, if this flag is false we ignore it.
     */
    private final NoTradingDayPolicy noTradingDayPolicy;

    public ExponentialPriceAverager(float weight, NoTradingDayPolicy policy) {
        this.averagedPrice = new ExponentialFilter<>(weight);
        this.noTradingDayPolicy = policy;
    }

    /**
     * call this at the end/beginning of the day to collect data to build your average
     *
     * @param department the department being averaged
     */
    @Override
    public void endOfTheDay(Department department) {

        int lastClosingPrice = department.getLastClosingPrice();
        if(lastClosingPrice < 0)
            return;
        else if(department.getTodayTrades() > 0)
        {
            averagedPrice.addObservation(department.getLastClosingPrice());
        }

        switch (noTradingDayPolicy)
        {
            case COUNT_AS_0:
                averagedPrice.addObservation(0);
                break;
            case COUNT_AS_LAST_CLOSING_PRICE:
                averagedPrice.addObservation(department.getLastClosingPrice());
                break;
            default:
            case IGNORE:
                break;
        }

    }

    @Override
    public float getAveragedPrice(Department department) {
       return averagedPrice.getSmoothedObservation();
    }
}


text:
<?php
namespace TYPO3\Flow\Tests\Unit\Persistence;

require_once('Fixture/Repository/NonstandardEntityRepository.php');

/**
 * Testcase for the base Repository
 *
 */
class RepositoryTest extends \TYPO3\Flow\Tests\UnitTestCase
{
    /**
     * @test
     */
    public function abstractRepositoryImplementsRepositoryInterface()
    {
        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class);
        $this->assertTrue($repository instanceof \TYPO3\Flow\Persistence\RepositoryInterface);
    }

    /**
     * dataProvider for constructSetsObjectTypeFromClassName
     */
    public function modelAndRepositoryClassNames()
    {
        $idSuffix = uniqid();
        return array(
            array('TYPO3\Blog\Domain\Repository', 'C' . $idSuffix . 'BlogRepository', 'TYPO3\Blog\Domain\Model\\C' . $idSuffix . 'Blog'),
            array('Domain\Repository\Content', 'C' . $idSuffix . 'PageRepository', 'Domain\Model\\Content\\C' . $idSuffix . 'Page'),
            array('Domain\Repository', 'C' . $idSuffix . 'RepositoryRepository', 'Domain\Model\\C' . $idSuffix . 'Repository')
        );
    }

    /**
     * @test
     * @dataProvider modelAndRepositoryClassNames
     */
    public function constructSetsObjectTypeFromClassName($repositoryNamespace, $repositoryClassName, $modelClassName)
    {
        $mockClassName = $repositoryNamespace . '\\' . $repositoryClassName;
        eval('namespace ' . $repositoryNamespace . '; class ' . $repositoryClassName . ' extends \TYPO3\Flow\Persistence\Repository {}');

        $repository = new $mockClassName();
        $this->assertEquals($modelClassName, $repository->getEntityClassName());
    }

    /**
     * @test
     */
    public function constructSetsObjectTypeFromClassConstant()
    {
        $repositoryNamespace = 'TYPO3\Flow\Tests\Persistence\Fixture\Repository';
        $repositoryClassName = 'NonstandardEntityRepository';
        $modelClassName = 'TYPO3\Flow\Tests\Persistence\Fixture\Model\Entity';
        $fullRepositorClassName = $repositoryNamespace . '\\' . $repositoryClassName;

        $repository = new $fullRepositorClassName();
        $this->assertEquals($modelClassName, $repository->getEntityClassName());
    }

    /**
     * @test
     */
    public function createQueryCallsPersistenceManagerWithExpectedClassName()
    {
        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\Generic\PersistenceManager::class);
        $mockPersistenceManager->expects($this->once())->method('createQueryForType')->with('ExpectedType');

        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $repository->_set('entityClassName', 'ExpectedType');
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);

        $repository->createQuery();
    }

    /**
     * @test
     */
    public function createQuerySetsDefaultOrderingIfDefined()
    {
        $orderings = array('foo' => \TYPO3\Flow\Persistence\QueryInterface::ORDER_ASCENDING);
        $mockQuery = $this->getMock(\TYPO3\Flow\Persistence\QueryInterface::class);
        $mockQuery->expects($this->once())->method('setOrderings')->with($orderings);
        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\Generic\PersistenceManager::class);
        $mockPersistenceManager->expects($this->exactly(2))->method('createQueryForType')->with('ExpectedType')->will($this->returnValue($mockQuery));

        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $repository->_set('entityClassName', 'ExpectedType');
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);
        $repository->setDefaultOrderings($orderings);
        $repository->createQuery();

        $repository->setDefaultOrderings(array());
        $repository->createQuery();
    }

    /**
     * @test
     */
    public function findAllCreatesQueryAndReturnsResultOfExecuteCall()
    {
        $expectedResult = $this->getMock(\TYPO3\Flow\Persistence\QueryResultInterface::class);

        $mockQuery = $this->getMock(\TYPO3\Flow\Persistence\QueryInterface::class);
        $mockQuery->expects($this->once())->method('execute')->with()->will($this->returnValue($expectedResult));

        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $repository->expects($this->once())->method('createQuery')->will($this->returnValue($mockQuery));

        $this->assertSame($expectedResult, $repository->findAll());
    }

    /**
     * @test
     */
    public function findByidentifierReturnsResultOfGetObjectByIdentifierCall()
    {
        $identifier = '123-456';
        $object = new \stdClass();

        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\PersistenceManagerInterface::class);
        $mockPersistenceManager->expects($this->once())->method('getObjectByIdentifier')->with($identifier, 'stdClass')->will($this->returnValue($object));

        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);
        $repository->_set('entityClassName', 'stdClass');

        $this->assertSame($object, $repository->findByIdentifier($identifier));
    }

    /**
     * @test
     */
    public function addDelegatesToPersistenceManager()
    {
        $object = new \stdClass();
        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\PersistenceManagerInterface::class);
        $mockPersistenceManager->expects($this->once())->method('add')->with($object);
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);
        $repository->_set('entityClassName', get_class($object));
        $repository->add($object);
    }

    /**
     * @test
     */
    public function removeDelegatesToPersistenceManager()
    {
        $object = new \stdClass();
        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\PersistenceManagerInterface::class);
        $mockPersistenceManager->expects($this->once())->method('remove')->with($object);
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);
        $repository->_set('entityClassName', get_class($object));
        $repository->remove($object);
    }

    /**
     * @test
     */
    public function updateDelegatesToPersistenceManager()
    {
        $object = new \stdClass();
        $mockPersistenceManager = $this->getMock(\TYPO3\Flow\Persistence\PersistenceManagerInterface::class);
        $mockPersistenceManager->expects($this->once())->method('update')->with($object);
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $this->inject($repository, 'persistenceManager', $mockPersistenceManager);
        $repository->_set('entityClassName', get_class($object));
        $repository->update($object);
    }

    /**
     * @test
     */
    public function magicCallMethodAcceptsFindBySomethingCallsAndExecutesAQueryWithThatCriteria()
    {
        $mockQueryResult = $this->getMock(\TYPO3\Flow\Persistence\QueryResultInterface::class);
        $mockQuery = $this->getMock(\TYPO3\Flow\Persistence\QueryInterface::class);
        $mockQuery->expects($this->once())->method('equals')->with('foo', 'bar')->will($this->returnValue('matchCriteria'));
        $mockQuery->expects($this->once())->method('matching')->with('matchCriteria')->will($this->returnValue($mockQuery));
        $mockQuery->expects($this->once())->method('execute')->with()->will($this->returnValue($mockQueryResult));

        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $repository->expects($this->once())->method('createQuery')->will($this->returnValue($mockQuery));

        $this->assertSame($mockQueryResult, $repository->findByFoo('bar'));
    }

    /**
     * @test
     */
    public function magicCallMethodAcceptsFindOneBySomethingCallsAndExecutesAQueryWithThatCriteria()
    {
        $object = new \stdClass();
        $mockQueryResult = $this->getMock(\TYPO3\Flow\Persistence\QueryResultInterface::class);
        $mockQueryResult->expects($this->once())->method('getFirst')->will($this->returnValue($object));
        $mockQuery = $this->getMock(\TYPO3\Flow\Persistence\QueryInterface::class);
        $mockQuery->expects($this->once())->method('equals')->with('foo', 'bar')->will($this->returnValue('matchCriteria'));
        $mockQuery->expects($this->once())->method('matching')->with('matchCriteria')->will($this->returnValue($mockQuery));
        $mockQuery->expects($this->once())->method('execute')->will($this->returnValue($mockQueryResult));

        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $repository->expects($this->once())->method('createQuery')->will($this->returnValue($mockQuery));

        $this->assertSame($object, $repository->findOneByFoo('bar'));
    }

    /**
     * @test
     */
    public function magicCallMethodAcceptsCountBySomethingCallsAndExecutesAQueryWithThatCriteria()
    {
        $mockQuery = $this->getMock(\TYPO3\Flow\Persistence\QueryInterface::class);
        $mockQuery->expects($this->once())->method('equals')->with('foo', 'bar')->will($this->returnValue('matchCriteria'));
        $mockQuery->expects($this->once())->method('matching')->with('matchCriteria')->will($this->returnValue($mockQuery));
        $mockQuery->expects($this->once())->method('count')->will($this->returnValue(2));

        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $repository->expects($this->once())->method('createQuery')->will($this->returnValue($mockQuery));

        $this->assertSame(2, $repository->countByFoo('bar'));
    }

    /**
     * @test
     * @expectedException \PHPUnit_Framework_Error
     */
    public function magicCallMethodTriggersAnErrorIfUnknownMethodsAreCalled()
    {
        $repository = $this->getMock(\TYPO3\Flow\Persistence\Repository::class, array('createQuery'));
        $repository->__call('foo', array());
    }

    /**
     * @test
     * @expectedException \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
     */
    public function addChecksObjectType()
    {
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $repository->_set('entityClassName', 'ExpectedObjectType');

        $repository->add(new \stdClass());
    }

    /**
     * @test
     * @expectedException \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
     */
    public function removeChecksObjectType()
    {
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $repository->_set('entityClassName', 'ExpectedObjectType');

        $repository->remove(new \stdClass());
    }
    /**
     * @test
     * @expectedException \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
     */
    public function updateChecksObjectType()
    {
        $repository = $this->getAccessibleMock(\TYPO3\Flow\Persistence\Repository::class, array('dummy'));
        $repository->_set('entityClassName', 'ExpectedObjectType');

        $repository->update(new \stdClass());
    }
}


text:
classdef KSumLaplaceFC < KernelFeatureFC
    %KSUMLAPLACEFC A function classs defining sum of Laplace kernels on features
    %extracted using the specified feature extractor.
    %   .

    properties(SetAccess = protected)
    end

    methods
        % width w enters to kernel with 1/w in the exp.
        function this = KSumLaplaceFC(varargin)
            v = varargin;
            this@KernelFeatureFC(v{:});

        end

        % implementing abstract method
        function Kmat = kernelEval(this, F1, F2)
            if isempty(F1) || isempty(F2)
                Kmat = [];
                return;
            end
            lwidths = this.kerParams;
            F1sc = diag(1./lwidths)*F1;
            F2sc = diag(1./lwidths)*F2;
            assert(size(F1sc, 1) == size(F2sc, 1));
            d = size(F1sc, 1);
            Kmat = zeros(size(F1sc, 2), size(F2sc, 2));
            for i=1:d
                f1i = F1sc(i, :);
                f2i = F2sc(i, :);

                D = abs(bsxfun(@minus, f1i', f2i));
                Kmat = Kmat + exp(-D);
            end
        end

        function obj = finalize(this)
            % construct a dummy obj. Modify later.
            %obj = KSumLaplaceFC(this.kerParams, this.featureExtractor, ...
            %    this.centerInstances.instances(1), this.inputInstances.instances(1));
            obj = KSumLaplaceFC();
            obj.options = this.options;
            obj.featureExtractor = this.featureExtractor;
            obj.inputFeatures = [];
            obj.centerFeatures = this.centerFeatures(:, this.markedInd);
            obj.markedInd = 1:size(obj.centerFeatures, 2);
            obj.weightMat = this.weightMat;
            obj.kerParams = this.kerParams;
        end
    end % end methods
end


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

.log-message {
    font-family: monospace;
}

.log-checkpoint {
    font-family: monospace;
    font-weight: bold;
}

.log-delta {
    font-family: monospace;
    text-align: right;
}

.log-delta-header {
    text-align: right;
}

.log-message-header {
    text-align: left;
}


text:
/**
 * MUI Angular DropdownItem Component
 * @module angular/dropdown-item
 */

import angular from 'angular';

const moduleName = 'mui.dropdown-item';

angular.module(moduleName, [])
  .directive('muiDropdownItem', function() {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        link: '@'
      },
      transclude: true,
      template: '

'
    };
  });

/** Define module API */
export default moduleName;


text:
<?php

namespace Mailgun\Model\Tag;

use Mailgun\Model\ApiResponse;

/**
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
final class UpdateResponse implements ApiResponse
{
    /**
     * @var string
     */
    private $message;

    /**
     * @param string $message
     */
    private function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * @param array $data
     *
     * @return UpdateResponse
     */
    public static function create(array $data)
    {
        return new self($data['message']);
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }
}