text:
"""This file contains cache-related utility functions used by GRR."""

import functools
import threading

from grr_response_core.lib import rdfvalue

WITH_LIMITED_CALL_FREQUENCY_PASS_THROUGH = False

def WithLimitedCallFrequency(min_time_between_calls: rdfvalue.Duration):
  """Function call rate-limiting decorator.

  This decorator ensures that the wrapped function will be called at most
  once in min_time_between_calls time for the same set of arguments. For all
  excessive calls a previous cached return value will be returned.

  Suppose we use the decorator like this:
  @cache.WithLimitedCallFrequency(rdfvalue.Duration.From(30, rdfvalue.SECONDS))
  def Foo(id):
    ...

  If Foo(42) is called and then Foo(42) is called again within 30 seconds, then
  the second call will simply return the cached return value of the first.

  If Foo(42) is called and then Foo(43) is called within 30 seconds, the
  wrapped function will be properly called in both cases, since these Foo calls
  have different arguments sets.

  If Foo(42) is called and takes a long time to finish, and another
  Foo(42) call is done in another thread, then the latter call will wait for
  the first one to finish and then return the cached result value. I.e. the
  wrapped function will be called just once, thus keeping the guarantee of
  at most 1 run in min_time_between_calls.

  NOTE 1: this function becomes a trivial pass-through and does no caching if
  module-level WITH_LIMITED_CALL_FREQUENCY_PASS_THROUGH variable is set to
  True. This is used in testing.

  NOTE 2: all decorated functions' arguments have to be hashable.

  Args:
    min_time_between_calls: An rdfvalue.Duration specifying the minimal
    time to pass between 2 consecutive function calls with same arguments.

  Returns:
    A Python function decorator.
  """

  def Decorated(f):
    """Actual decorator implementation."""

    lock = threading.RLock()
    prev_times = {}
    prev_results = {}
    result_locks = {}

    @functools.wraps(f)
    def Fn(*args, **kwargs):
      """Wrapper around the decorated function."""

      if WITH_LIMITED_CALL_FREQUENCY_PASS_THROUGH:
        # This effectively turns off the caching.
        min_time = rdfvalue.Duration(0)
      else:
        min_time = min_time_between_calls

      key = (args, tuple(sorted(kwargs.items())))
      now = rdfvalue.RDFDatetime.Now()

      with lock:
        for k, prev_time in list(prev_times.items()):
          if now - prev_time >= min_time:
            prev_times.pop(k)
            prev_results.pop(k, None)
            result_locks.pop(k, None)

        try:
          # We eliminated all the old entries, so if the key is present
          # in the cache, it means that the data is fresh enough to be used.
          return prev_results[key]
        except KeyError:
          prev_time = None

        try:
          result_lock = result_locks[key]
        except KeyError:
          result_lock = threading.RLock()
          result_locks[key] = result_lock

      with result_lock:
        t = prev_times.get(key)

        if t == prev_time:
          result = f(*args, **kwargs)
          with lock:
            prev_times[key] = rdfvalue.RDFDatetime.Now()
            prev_results[key] = result

          return result
        else:
          return prev_results[key]

    return Fn

  return Decorated


text:
            Produto

Cliente

    <input id="in1" type="text" size="30" pInputText [(ngModel)]="selecionado.cliente">

Pedido

 <button pButton type="button" label="Inserir" icon="fa-folder-open" (click)="inserirProduto()"></button>

redpajama_set_name: RedPajamaGithub


text:
module RackAttackReset
  class << self
    def gem_push_backoff(remote_ip, user_display_id)
      Rack::Attack::EXP_BACKOFF_LEVELS.each do |level|
        keys(level, remote_ip, user_display_id).each { |key| Rack::Attack.cache.store.delete(key) }
      end
    end

    private

    def keys(level, remote_ip, user_display_id)
      period            = Rack::Attack::EXP_BASE_LIMIT_PERIOD**level
      time_counter      = (Time.now.to_i / period).to_i
      # counter may have incremented by 1 since the key was set, best to reset prev counter as well.
      # pre time counter/window key is applicable for +1 second after the counter has changed
      # see: https://github.com/kickstarter/rack-attack/pull/85
      prev_time_counter = time_counter - 1
      prefix            = Rack::Attack.cache.prefix

      ["#{prefix}:#{time_counter}:#{Rack::Attack::PUSH_EXP_THROTTLE_KEY}/#{level}:#{remote_ip}",
       "#{prefix}:#{prev_time_counter}:#{Rack::Attack::PUSH_EXP_THROTTLE_KEY}/#{level}:#{remote_ip}",
       "#{prefix}:#{time_counter}:#{Rack::Attack::PUSH_THROTTLE_PER_USER_KEY}/#{level}:#{user_display_id}",
       "#{prefix}:#{prev_time_counter}:#{Rack::Attack::PUSH_THROTTLE_PER_USER_KEY}/#{level}:#{user_display_id}"]
    end
  end
end


text:
/*!
 *************************************************************************************
 * \file erc_api.c
 *
 * \brief
 *    External (still inside video decoder) interface for error concealment module
 *
 *  \author
 *     - Ari Hourunranta                <ari.hourunranta@nokia.com>
 *     - Viktor Varsa                     <viktor.varsa@nokia.com>
 *     - Ye-Kui Wang                   <wyk@ieee.org>
 *
 *************************************************************************************
 */

#include <stdlib.h>

#include "global.h"
#include "memalloc.h"
#include "erc_api.h"

objectBuffer_t *erc_object_list = NULL;
ercVariables_t *erc_errorVar = NULL;
frame erc_recfr;
int erc_mvperMB;

/*!
 ************************************************************************
 * \brief
 *    Initinize the error concealment module
 ************************************************************************
 */
void ercInit(int pic_sizex, int pic_sizey, int flag)
{
  ercClose(erc_errorVar);
  erc_object_list = (objectBuffer_t *) calloc((pic_sizex * pic_sizey) >> 6, sizeof(objectBuffer_t));
  if (erc_object_list == NULL) no_mem_exit("ercInit: erc_object_list");

  /* the error concelament instance is allocated */
  erc_errorVar = ercOpen();

  /* set error concealment ON */
  ercSetErrorConcealment(erc_errorVar, flag);
}

/*!
 ************************************************************************
 * \brief
 *      Allocates data structures used in error concealment.
 *\return
 *      The allocated ercVariables_t is returned.
 ************************************************************************
 */
ercVariables_t *ercOpen( void )
{
  ercVariables_t *errorVar = NULL;

  errorVar = (ercVariables_t *)malloc( sizeof(ercVariables_t));
  if ( errorVar == NULL ) no_mem_exit("ercOpen: errorVar");

  errorVar->nOfMBs = 0;
  errorVar->segments = NULL;
  errorVar->currSegment = 0;
  errorVar->yCondition = NULL;
  errorVar->uCondition = NULL;
  errorVar->vCondition = NULL;
  errorVar->prevFrameYCondition = NULL;

  errorVar->concealment = 1;

  return errorVar;
}

/*!
 ************************************************************************
 * \brief
 *      Resets the variables used in error detection.
 *      Should be called always when starting to decode a new frame.
 * \param errorVar
 *      Variables for error concealment
 * \param nOfMBs
 *      Number of macroblocks in a frame
 * \param numOfSegments
 *    Estimated number of segments (memory reserved)
 * \param picSizeX
 *      Width of the frame in pixels.
 ************************************************************************
 */
void ercReset( ercVariables_t *errorVar, int nOfMBs, int numOfSegments, int32 picSizeX )
{
  int *tmp = NULL;
  int i = 0;

  if ( errorVar && errorVar->concealment )
  {
    /* If frame size has been changed */
    if ( nOfMBs != errorVar->nOfMBs && errorVar->yCondition != NULL )
    {
      free( errorVar->yCondition );
      errorVar->yCondition = NULL;
      free( errorVar->prevFrameYCondition );
      errorVar->prevFrameYCondition = NULL;
      free( errorVar->uCondition );
      errorVar->uCondition = NULL;
      free( errorVar->vCondition );
      errorVar->vCondition = NULL;
      free( errorVar->segments );
      errorVar->segments = NULL;
    }

    /* If the structures are uninitialized (first frame, or frame size is chaned) */
    if ( errorVar->yCondition == NULL )
    {
      errorVar->segments = (ercSegment_t *)malloc( numOfSegments*sizeof(ercSegment_t) );
      if ( errorVar->segments == NULL ) no_mem_exit("ercReset: errorVar->segments");
      memset( errorVar->segments, 0, numOfSegments*sizeof(ercSegment_t));
      errorVar->nOfSegments = numOfSegments;

      errorVar->yCondition = (int *)malloc( 4*nOfMBs*sizeof(int) );
      if ( errorVar->yCondition == NULL ) no_mem_exit("ercReset: errorVar->yCondition");
      errorVar->prevFrameYCondition = (int *)malloc( 4*nOfMBs*sizeof(int) );
      if ( errorVar->prevFrameYCondition == NULL ) no_mem_exit("ercReset: errorVar->prevFrameYCondition");
      errorVar->uCondition = (int *)malloc( nOfMBs*sizeof(int) );
      if ( errorVar->uCondition == NULL ) no_mem_exit("ercReset: errorVar->uCondition");
      errorVar->vCondition = (int *)malloc( nOfMBs*sizeof(int) );
      if ( errorVar->vCondition == NULL ) no_mem_exit("ercReset: errorVar->vCondition");
      errorVar->nOfMBs = nOfMBs;
    }
    else
    {
      /* Store the yCondition struct of the previous frame */
      tmp = errorVar->prevFrameYCondition;
      errorVar->prevFrameYCondition = errorVar->yCondition;
      errorVar->yCondition = tmp;
    }

    /* Reset tables and parameters */
    memset( errorVar->yCondition, 0, 4*nOfMBs*sizeof(*errorVar->yCondition));
    memset( errorVar->uCondition, 0,   nOfMBs*sizeof(*errorVar->uCondition));
    memset( errorVar->vCondition, 0,   nOfMBs*sizeof(*errorVar->vCondition));

    if (errorVar->nOfSegments != numOfSegments)
    {
      free( errorVar->segments );
      errorVar->segments = NULL;
      errorVar->segments = (ercSegment_t *)malloc( numOfSegments*sizeof(ercSegment_t) );
      if ( errorVar->segments == NULL ) no_mem_exit("ercReset: errorVar->segments");
      errorVar->nOfSegments = numOfSegments;
    }

    memset( errorVar->segments, 0, errorVar->nOfSegments*sizeof(ercSegment_t));

    for ( i = 0; i < errorVar->nOfSegments; i++ )
    {
      errorVar->segments[i].fCorrupted = 1; //! mark segments as corrupted
      errorVar->segments[i].startMBPos = 0;
      errorVar->segments[i].endMBPos = nOfMBs - 1;
    }

    errorVar->currSegment = 0;
    errorVar->nOfCorruptedSegments = 0;
  }
}

/*!
 ************************************************************************
 * \brief
 *      Resets the variables used in error detection.
 *      Should be called always when starting to decode a new frame.
 * \param errorVar
 *      Variables for error concealment
 ************************************************************************
 */
void ercClose( ercVariables_t *errorVar )
{
  if ( errorVar != NULL )
  {
    if (errorVar->yCondition != NULL)
    {
      free( errorVar->segments );
      free( errorVar->yCondition );
      free( errorVar->uCondition );
      free( errorVar->vCondition );
      free( errorVar->prevFrameYCondition );
    }
    free( errorVar );
    errorVar = NULL;
  }

  if (erc_object_list)
  {
    free(erc_object_list);
    erc_object_list=NULL;
  }
}

/*!
 ************************************************************************
 * \brief
 *      Sets error concealment ON/OFF. Can be invoked only between frames, not during a frame
 * \param errorVar
 *      Variables for error concealment
 * \param value
 *      New value
 ************************************************************************
 */
void ercSetErrorConcealment( ercVariables_t *errorVar, int value )
{
  if ( errorVar != NULL )
    errorVar->concealment = value;
}

/*!
 ************************************************************************
 * \brief
 *      Creates a new segment in the segment-list, and marks the start MB and bit position.
 *      If the end of the previous segment was not explicitly marked by "ercStopSegment",
 *      also marks the end of the previous segment.
 *      If needed, it reallocates the segment-list for a larger storage place.
 * \param currMBNum
 *      The MB number where the new slice/segment starts
 * \param segment
 *      Segment/Slice No. counted by the caller
 * \param bitPos
 *      Bitstream pointer: number of bits read from the buffer.
 * \param errorVar
 *      Variables for error detector
 ************************************************************************
 */
void ercStartSegment( int currMBNum, int segment, u_int32 bitPos, ercVariables_t *errorVar )
{
  if ( errorVar && errorVar->concealment )
  {
    errorVar->currSegmentCorrupted = 0;

    errorVar->segments[ segment ].fCorrupted = 0;
    errorVar->segments[ segment ].startMBPos = currMBNum;

  }
}

/*!
 ************************************************************************
 * \brief
 *      Marks the end position of a segment.
 * \param currMBNum
 *      The last MB number of the previous segment
 * \param segment
 *      Segment/Slice No. counted by the caller
 *      If (segment<0) the internal segment counter is used.
 * \param bitPos
 *      Bitstream pointer: number of bits read from the buffer.
 * \param errorVar
 *      Variables for error detector
 ************************************************************************
 */
void ercStopSegment( int currMBNum, int segment, u_int32 bitPos, ercVariables_t *errorVar )
{
  if ( errorVar && errorVar->concealment )
  {
    errorVar->segments[ segment ].endMBPos = currMBNum; //! Changed TO 12.11.2001
    errorVar->currSegment++;
  }
}

/*!
 ************************************************************************
 * \brief
 *      Marks the current segment (the one which has the "currMBNum" MB in it)
 *      as lost: all the blocks of the MBs in the segment as corrupted.
 * \param picSizeX
 *      Width of the frame in pixels.
 * \param errorVar
 *      Variables for error detector
 ************************************************************************
 */
void ercMarkCurrSegmentLost(int32 picSizeX, ercVariables_t *errorVar )
{
  int j = 0;
  int current_segment;

  current_segment = errorVar->currSegment-1;
  if ( errorVar && errorVar->concealment )
  {
    if (errorVar->currSegmentCorrupted == 0)
    {
      errorVar->nOfCorruptedSegments++;
      errorVar->currSegmentCorrupted = 1;
    }

    for ( j = errorVar->segments[current_segment].startMBPos; j <= errorVar->segments[current_segment].endMBPos; j++ )
    {
      errorVar->yCondition[MBNum2YBlock (j, 0, picSizeX)] = ERC_BLOCK_CORRUPTED;
      errorVar->yCondition[MBNum2YBlock (j, 1, picSizeX)] = ERC_BLOCK_CORRUPTED;
      errorVar->yCondition[MBNum2YBlock (j, 2, picSizeX)] = ERC_BLOCK_CORRUPTED;
      errorVar->yCondition[MBNum2YBlock (j, 3, picSizeX)] = ERC_BLOCK_CORRUPTED;
      errorVar->uCondition[j] = ERC_BLOCK_CORRUPTED;
      errorVar->vCondition[j] = ERC_BLOCK_CORRUPTED;
    }
    errorVar->segments[current_segment].fCorrupted = 1;
  }
}

/*!
 ************************************************************************
 * \brief
 *      Marks the current segment (the one which has the "currMBNum" MB in it)
 *      as OK: all the blocks of the MBs in the segment as OK.
 * \param picSizeX
 *      Width of the frame in pixels.
 * \param errorVar
 *      Variables for error detector
 ************************************************************************
 */
void ercMarkCurrSegmentOK(int32 picSizeX, ercVariables_t *errorVar )
{
  int j = 0;
  int current_segment;

  current_segment = errorVar->currSegment-1;
  if ( errorVar && errorVar->concealment )
  {
    // mark all the Blocks belonging to the segment as OK */
    for ( j = errorVar->segments[current_segment].startMBPos; j <= errorVar->segments[current_segment].endMBPos; j++ )
    {
      errorVar->yCondition[MBNum2YBlock (j, 0, picSizeX)] = ERC_BLOCK_OK;
      errorVar->yCondition[MBNum2YBlock (j, 1, picSizeX)] = ERC_BLOCK_OK;
      errorVar->yCondition[MBNum2YBlock (j, 2, picSizeX)] = ERC_BLOCK_OK;
      errorVar->yCondition[MBNum2YBlock (j, 3, picSizeX)] = ERC_BLOCK_OK;
      errorVar->uCondition[j] = ERC_BLOCK_OK;
      errorVar->vCondition[j] = ERC_BLOCK_OK;
    }
    errorVar->segments[current_segment].fCorrupted = 0;
  }
}

/*!
 ************************************************************************
 * \brief
 *      Marks the Blocks of the given component (YUV) of the current MB as concealed.
 * \param currMBNum
 *      Selects the segment where this MB number is in.
 * \param comp
 *      Component to mark (0:Y, 1:U, 2:V, <0:All)
 * \param picSizeX
 *      Width of the frame in pixels.
 * \param errorVar
 *      Variables for error detector
 ************************************************************************
 */
void ercMarkCurrMBConcealed( int currMBNum, int comp, int32 picSizeX, ercVariables_t *errorVar )
{
  int setAll = 0;

  if ( errorVar && errorVar->concealment )
  {
    if (comp < 0)
    {
      setAll = 1;
      comp = 0;
    }

    switch (comp)
    {
    case 0:
      errorVar->yCondition[MBNum2YBlock (currMBNum, 0, picSizeX)] = ERC_BLOCK_CONCEALED;
      errorVar->yCondition[MBNum2YBlock (currMBNum, 1, picSizeX)] = ERC_BLOCK_CONCEALED;
      errorVar->yCondition[MBNum2YBlock (currMBNum, 2, picSizeX)] = ERC_BLOCK_CONCEALED;
      errorVar->yCondition[MBNum2YBlock (currMBNum, 3, picSizeX)] = ERC_BLOCK_CONCEALED;
      if (!setAll)
        break;
    case 1:
      errorVar->uCondition[currMBNum] = ERC_BLOCK_CONCEALED;
      if (!setAll)
        break;
    case 2:
      errorVar->vCondition[currMBNum] = ERC_BLOCK_CONCEALED;
    }
  }
}


text:
//
// COMP 371 Assignment Framework
//
// Created by Nicolas Bergeron on 8/7/14.
// Updated by Gary Chang on 14/1/15
//
// Copyright (c) 2014-2015 Concordia University. All rights reserved.
//

#include "Animation.h"
#include "Renderer.h"
#include "World.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>

// Include GLEW - OpenGL Extension Wrangler
#include <GL/glew.h>

using namespace glm;
using namespace std;

AnimationKey::AnimationKey() : Model()
{
}

AnimationKey::~AnimationKey()
{
}

void AnimationKey::Update(float dt)
{
	Model::Update(dt);
}

void AnimationKey::Draw()
{
	Model::Draw();
}

bool AnimationKey::ParseLine(const std::vector<ci_string> &token)
{
	if (token.empty())
	{
		return true;
	}
	else
	{
		return Model::ParseLine(token);
	}
}

Animation::Animation()
	: mName(""), mCurrentTime(0.0f), mDuration(0.0f), mVertexBufferID(0), mVertexArrayID(0)
{
}

Animation::~Animation()
{
}

void Animation::CreateVertexBuffer()
{
    // This is just to display lines between the animation keys
    for (int i=0; i<mKey.size(); ++i)
    {
//        cout << "mKey SIZE: " << mKey[i].GetName().c_str() << endl;

        Vertex v;
        v.position = mKey[i].mPosition;
        mVertexBuffer.push_back(v);
    }

	// Create a vertex array
	glGenVertexArrays(1, &mVertexArrayID);

	// Upload Vertex Buffer to the GPU, keep a reference to it (mVertexBufferID)
	glGenBuffers(1, &mVertexBufferID);
	glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*mVertexBuffer.size(), &(mVertexBuffer[0]), GL_STATIC_DRAW);
}

void Animation::Update(float dt)
{
	mCurrentTime += dt;

    while(mCurrentTime > mDuration)
    {
        mCurrentTime -= mDuration;
    }
}

void Animation::Draw()
{
	// Draw lines between waypoints
	//
	// Steps:
	// - Draw the Vertex Buffer
	// - The Shader used to draw the Animation is AnimationLines, only requires to send the positions of the waypoints
	// - You need to bind the vertex buffer created in CreateVertexBuffer() as the input of the vertex shader
	// - Also set the WorldTransform uniform variable in the vertex shader
	// - You Should use GL_LINE_LOOP as a primitive to draw lines (not triangles)
	// - You can look at CubeModel::Draw() for a good example!

	// The Model View Projection transforms are computed in the Vertex Shader
	glBindVertexArray(mVertexArrayID);
	GLuint WorldMatrixLocation = glGetUniformLocation(Renderer::GetShaderProgramID(), "WorldTransform");
    glUniformMatrix4fv(WorldMatrixLocation, 1, GL_FALSE, &mat4(1.0f)[0][0]);

	// 1st attribute buffer : vertex Positions
    glEnableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferID);
	glVertexAttribPointer(0,
		3,				// size
		GL_FLOAT,		// type
		GL_FALSE,		// normalized?
		sizeof(Vertex), // stride
		(void*)0        // array buffer offset
		);

	// Draw the triangles !
	glDrawArrays(GL_LINE_LOOP, 0, mVertexBuffer.size());

	glDisableVertexAttribArray(0);
}

void Animation::Load(ci_istringstream& iss)
{
	ci_string line;

	// Parse model line by line
	while(std::getline(iss, line))
	{
		// Splitting line into tokens
		ci_istringstream strstr(line);
		istream_iterator<ci_string, char, ci_char_traits> it(strstr);
		istream_iterator<ci_string, char, ci_char_traits> end;
		vector<ci_string> token(it, end);

		if (ParseLine(token) == false)
		{
			fprintf(stderr, "Error loading scene file... token:  %s!", token[0].c_str());
			getchar();
			exit(-1);
		}
	}
}

bool Animation::ParseLine(const std::vector<ci_string> &token)
{
    if (token.empty())
    {
        return true;
    }
	else if (token[0] == "name")
	{
		assert(token.size() > 2);
		assert(token[1] == "=");

		mName = token[2];
		return true;
	}
	else if (token[0] == "key")
	{
		assert(token.size() > 5);
        assert(token[1] == "=");
        assert(token[3] == "time");
        assert(token[4] == "=");

		ci_string name = token[2];
		AnimationKey *key = World::GetInstance()->FindAnimationKey(name);

		assert(key != nullptr);
		AddKey(key, atof(token[5].c_str()));
		return true;
	}
	return false;
}

void Animation::AddKey(AnimationKey* key, float time)
{
    assert(time >= mDuration);
	mKey.push_back(*key);
    mKeyTime.push_back(time);
    mDuration = time;
}

ci_string Animation::GetName() const
{
	return mName;
}

/**
 *	return: World Matrix
 */
glm::mat4 Animation::GetAnimationWorldMatrix() const
{
    // @TODO 3 - Find the 2 keys to interpolate the transformation
    //           Interpolate the position, scaling and rotation separately
    //           Finally concatenate the interpolated transforms into a single
    //           world transform and return it.

	int key1 = 0;
	int key2 = 0;
	float normalizedTime = 0.0f;

	for(int i = 0; i < this->mKey.size(); ++i) {
		if(this->mCurrentTime < this->mKeyTime[i]){
			key1 = i - 1;
			key2 = i;
			normalizedTime = (this->mCurrentTime - this->mKeyTime[key1])/(this->mKeyTime[key2] - this->mKeyTime[key1]);
			break;
		}
	}

	//Interpolate Between 2 Keys
	vec3 position = mix(this->mKey[key1].mPosition, this->mKey[key2].mPosition, normalizedTime);
	vec3 scaling = mix(this->mKey[key1].mScaling, this->mKey[key2].mScaling, normalizedTime);

	//2 Rotation States
	quat rotation1(angleAxis(this->mKey[key1].mRotationAngleInDegrees, this->mKey[key1].mRotationAxis));
	quat rotation2(angleAxis(this->mKey[key2].mRotationAngleInDegrees, this->mKey[key2].mRotationAxis));

	//Slerp
	quat rotation = slerp(rotation1, rotation2, normalizedTime);

	//Concatenate Interpolated Components to a Single World Transform
	mat4 worldMatrix(1.0f);
	mat4 translationMatrix = translate(worldMatrix, position);
	mat4 rotationMatrix = mat4_cast(rotation);
	mat4 scaleMatrix = scale(worldMatrix, scaling);
	return translationMatrix * rotationMatrix * scaleMatrix;
}


text:
class AddRebateToOrders < ActiveRecord::Migration
  def self.up
    add_column :orders, :rebate, :float, :default => 0
    add_column :orders, :rebate_type, :string
  end

  def self.down
    remove_column :orders, :rebate_type
    remove_column :orders, :rebate
  end
end


text:
'use strict';

describe('Controller: DeveloperCtrl', function () {

  // load the controller's module
  beforeEach(module('myApp'));

  var DeveloperCtrl,
    scope,
    $httpBackend;

  // Initialize the controller and a mock scope
  beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('api/developers')
      .respond([
            {ci: 1, name: 'Roberto', language: 'Java'},
            {ci: 2, name: 'Juan', language: 'PHP'}
        ]);
    scope = $rootScope.$new();
    DeveloperCtrl = $controller('DeveloperController', {
      $scope: scope
    });
  }));

  it('should attach a list of developers to the scope', function () {
    expect(scope.developers).toBeUndefined();
    $httpBackend.flush();
    expect(scope.developers.length).toBe(2);
  });
});


text:
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(WM_PUBLIC_EXPORT, wm::TooltipClient*)
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(WM_PUBLIC_EXPORT, void**)

namespace wm {

DEFINE_UI_CLASS_PROPERTY_KEY(TooltipClient*, kRootWindowTooltipClientKey, NULL)
DEFINE_UI_CLASS_PROPERTY_KEY(std::u16string*, kTooltipTextKey, NULL)
DEFINE_UI_CLASS_PROPERTY_KEY(void*, kTooltipIdKey, NULL)

void SetTooltipClient(aura::Window* root_window, TooltipClient* client) {
  DCHECK_EQ(root_window->GetRootWindow(), root_window);
  root_window->SetProperty(kRootWindowTooltipClientKey, client);
}

TooltipClient* GetTooltipClient(aura::Window* root_window) {
  if (root_window)
    DCHECK_EQ(root_window->GetRootWindow(), root_window);
  return root_window ?
      root_window->GetProperty(kRootWindowTooltipClientKey) : NULL;
}

void SetTooltipText(aura::Window* window, std::u16string* tooltip_text) {
  window->SetProperty(kTooltipTextKey, tooltip_text);
}

void SetTooltipId(aura::Window* window, void* id) {
  if (id != GetTooltipId(window))
    window->SetProperty(kTooltipIdKey, id);
}

const std::u16string GetTooltipText(aura::Window* window) {
  std::u16string* string_ptr = window->GetProperty(kTooltipTextKey);
  return string_ptr ? *string_ptr : std::u16string();
}

const void* GetTooltipId(aura::Window* window) {
  return window->GetProperty(kTooltipIdKey);
}

}  // namespace wm


text:
package restlib.data;

import java.nio.CharBuffer;

import org.junit.Test;

import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;

public final class ConnectionOptionTest {
    @Test
    public void testEquals() {
        new EqualsTester()
            .addEqualityGroup(
                    ConnectionOption.CLOSE,
                    ConnectionOption.create("CLOSE"),
                    ConnectionOption.PARSER.parse(CharBuffer.wrap("CLOSE")).get())
            .addEqualityGroup(
                    ConnectionOption.KEEP_ALIVE,
                    ConnectionOption.create("keep-alive"))
            .addEqualityGroup(ConnectionOption.create("abc"), ConnectionOption.create("abc"))
            .testEquals();
    }
    @Test
    public void testNulls() {
        new NullPointerTester()
            .testAllPublicStaticMethods(ConnectionOption.class);
        new NullPointerTester()
            .testAllPublicInstanceMethods(ConnectionOption.CLOSE);
    }
}


text:
// This technique works AS IS for month end data points
//   In fact, this works for any series where each value is evenly spaced,
//   and every series starts at the same value and is 1 to 1
//     In other words, values at the same index, need to have the same x value
//     for all series
//
// TODO: now that tooltips don't use jquery, could likely get rid of the charts
//       collection by simply adding some optional functionality to the model
nv.charts.cumulativeLineChartDaily = function() {
  var selector = null,
      data = [],
      duration = 500,
      tooltip = function(key, x, y, e, graph) {
        return '
' + key + '
' +
               '
' +  y + ' at ' + x + '
'
      };

  var graph = nv.models.cumulativeLine()
                .x(function(d,i) { return i })
                .color(d3.scale.category10().range()),
      showTooltip = function(e) {
        var offsetElement = document.getElementById(selector.substr(1)),
            left = e.pos[0] + offsetElement.offsetLeft,
            top = e.pos[1] + offsetElement.offsetTop,
            formatX = graph.xAxis.tickFormat(),
            formatY = graph.yAxis.tickFormat(),
            x = formatX(graph.x()(e, e.pointIndex)),
            //x = formatX(graph.x()(e.point)),
            y = formatY(graph.y()(e.point)),
            content = tooltip(e.series.key, x, y, e, graph);

        nv.tooltip.show([left, top], content);
      };

  //setting component defaults
  //graph.xAxis.tickFormat(d3.format(',r'));
  graph.xAxis.tickFormat(function(d) {
    //return d3.time.format('%x')(new Date(d))
    return d3.time.format('%x')(new Date(data[0].values[d].x))
  });

  //graph.yAxis.tickFormat(d3.format(',.2f'));
  graph.yAxis.tickFormat(d3.format(',.2%'));

  //TODO: consider a method more similar to how the docs are built
  function chart() {
    if (!selector || !data.length) return chart; //do nothing if you have nothing to work with

    d3.select(selector).select('svg')
        .datum(data)
      .transition().duration(duration).call(graph); //consider using transition chaining like in the docs

    return chart;
  }

  // This should always only be called once, then update should be used after,
  //     in which case should consider the 'd3 way' and merge this with update,
  //     but simply do this on enter... will try another example the d3 way
  chart.build = function() {
    if (!selector || !data.length) return chart; //do nothing if you have nothing to work with

    nv.addGraph({
      generate: function() {
        var container = d3.select(selector),
            width = function() { return parseInt(container.style('width')) },
            height = function() { return parseInt(container.style('height')) },
            svg = container.append('svg');

        graph
            .width(width)
            .height(height);

        svg
            .attr('width', width())
            .attr('height', height())
            .datum(data)
          .transition().duration(duration).call(graph);

        return graph;
      },
      callback: function(graph) {
        graph.dispatch.on('tooltipShow', showTooltip);
        graph.dispatch.on('tooltipHide', nv.tooltip.cleanup);

        //TODO: fix issue of multiple graphs failing on resize
        //TODO: create resize queue and have nv core handle resize instead of binding all to window resize
        window.onresize =
        function() {
          // now that width and height are functions, should be automatic..of course you can always override them
          d3.select(selector + ' svg')
              .attr('width', graph.width()()) //need to set SVG dimensions, chart is not aware of the SVG component
              .attr('height', graph.height()())
              .call(graph);
        };
      }
    });

    return chart;
  };

  /*
  //  moved to chart()
  chart.update = function() {
    if (!selector || !data.length) return chart; //do nothing if you have nothing to work with

    d3.select(selector).select('svg')
        .datum(data)
      .transition().duration(duration).call(graph);

    return chart;
  };
  */

  chart.data = function(_) {
    if (!arguments.length) return data;
    data = _;
    return chart;
  };

  chart.selector = function(_) {
    if (!arguments.length) return selector;
    selector = _;
    return chart;
  };

  chart.duration = function(_) {
    if (!arguments.length) return duration;
    duration = _;
    return chart;
  };

  chart.tooltip = function(_) {
    if (!arguments.length) return tooltip;
    tooltip = _;
    return chart;
  };

  chart.xTickFormat = function(_) {
    if (!arguments.length) return graph.xAxis.tickFormat();
    graph.xAxis.tickFormat(typeof _ === 'function' ? _ : d3.format(_));
    return chart;
  };

  chart.yTickFormat = function(_) {
    if (!arguments.length) return graph.yAxis.tickFormat();
    graph.yAxis.tickFormat(typeof _ === 'function' ? _ : d3.format(_));
    return chart;
  };

  chart.xAxisLabel = function(_) {
    if (!arguments.length) return graph.xAxis.axisLabel();
    graph.xAxis.axisLabel(_);
    return chart;
  };

  chart.yAxisLabel = function(_) {
    if (!arguments.length) return graph.yAxis.axisLabel();
    graph.yAxis.axisLabel(_);
    return chart;
  };

  d3.rebind(chart, graph, 'x', 'y');

  chart.graph = graph; // Give direct access for getter/setters, and dispatchers

  return chart;
};


text:
#ifndef WKCredentialTypes_h
#define WKCredentialTypes_h

#ifdef __cplusplus
extern "C" {
#endif

enum {
    kWKCredentialPersistenceNone,
    kWKCredentialPersistenceForSession,
    kWKCredentialPersistencePermanent
};
typedef uint32_t WKCredentialPersistence;

#ifdef __cplusplus
}
#endif

#endif /* WKCredentialTypes_h */


text:
<?php

class Home
{
    public static function create($data) {
    }

    public static function update($id, $data) {
    }

    public static function read($id) {
    }

    public static function delete($id) {
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>503 Service Unavailable</title>

Service Unavailable

The server is temporarily unable to service your
    request due to maintenance downtime or capacity
    problems. Please try again later.


text:
<?php
/**
 * wallee SDK
 *
 * This library allows to interact with the wallee payment service.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Wallee\Sdk\Model;
use \Wallee\Sdk\ObjectSerializer;

/**
 * ShopifySubscriptionWeekday model
 *
 * @category    Class
 * @description
 * @package     Wallee\Sdk
 * @author      customweb GmbH
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache License v2
 */
class ShopifySubscriptionWeekday
{
    /**
     * Possible values of this enum
     */
    const MONDAY = 'MONDAY';
    const TUESDAY = 'TUESDAY';
    const WEDNESDAY = 'WEDNESDAY';
    const THURSDAY = 'THURSDAY';
    const FRIDAY = 'FRIDAY';
    const SATURDAY = 'SATURDAY';
    const SUNDAY = 'SUNDAY';

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public static function getAllowableEnumValues()
    {
        return [
            self::MONDAY,
            self::TUESDAY,
            self::WEDNESDAY,
            self::THURSDAY,
            self::FRIDAY,
            self::SATURDAY,
            self::SUNDAY,
        ];
    }
}


text:
// Derived from Inferno utils/6l/obj.c and utils/6l/span.c
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
//
//	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
//	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
//	Portions Copyright © 1997-1999 Vita Nuova Limited
//	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
//	Portions Copyright © 2004,2006 Bruce Ellis
//	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
//	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
//	Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package ld

import (
	"cmd/internal/objabi"
	"cmd/internal/sys"
	"cmd/oldlink/internal/sym"
	"log"
)

func linknew(arch *sys.Arch) *Link {
	ctxt := &Link{
		Syms:         sym.NewSymbols(),
		Out:          &OutBuf{arch: arch},
		Arch:         arch,
		LibraryByPkg: make(map[string]*sym.Library),
	}

	if objabi.GOARCH != arch.Name {
		log.Fatalf("invalid objabi.GOARCH %s (want %s)", objabi.GOARCH, arch.Name)
	}

	AtExit(func() {
		if nerrors > 0 && ctxt.Out.f != nil {
			ctxt.Out.f.Close()
			mayberemoveoutfile()
		}
	})

	return ctxt
}

// computeTLSOffset records the thread-local storage offset.
// Not used for Android where the TLS offset is determined at runtime.
func (ctxt *Link) computeTLSOffset() {
	switch ctxt.HeadType {
	default:
		log.Fatalf("unknown thread-local storage offset for %v", ctxt.HeadType)

	case objabi.Hplan9, objabi.Hwindows, objabi.Hjs, objabi.Haix:
		break

	case objabi.Hlinux,
		objabi.Hfreebsd,
		objabi.Hnetbsd,
		objabi.Hopenbsd,
		objabi.Hdragonfly,
		objabi.Hsolaris:
		/*
		 * ELF uses TLS offset negative from FS.
		 * Translate 0(FS) and 8(FS) into -16(FS) and -8(FS).
		 * Known to low-level assembly in package runtime and runtime/cgo.
		 */
		ctxt.Tlsoffset = -1 * ctxt.Arch.PtrSize

	case objabi.Hdarwin:
		/*
		 * OS X system constants - offset from 0(GS) to our TLS.
		 */
		switch ctxt.Arch.Family {
		default:
			log.Fatalf("unknown thread-local storage offset for darwin/%s", ctxt.Arch.Name)

			/*
			 * For x86, Apple has reserved a slot in the TLS for Go. See issue 23617.
			 * That slot is at offset 0x30 on amd64.
			 * The slot will hold the G pointer.
			 * These constants should match those in runtime/sys_darwin_{386,amd64}.s
			 * and runtime/cgo/gcc_darwin_{386,amd64}.c.
			 */
		case sys.AMD64:
			ctxt.Tlsoffset = 0x30

		case sys.ARM64:
			ctxt.Tlsoffset = 0 // dummy value, not needed
		}
	}

}


text:
<?php

defined('_JEXEC') or die;

/**
 * Send Test Mail Controller from global configuration
 *
 * @since  3.5
 */
class ConfigControllerApplicationSendtestmail extends JControllerBase
{
	/**
	 * Method to send the test mail.
	 *
	 * @return  string
	 *
	 * @since   3.5
	 */
	public function execute()
	{
		if (!JSession::checkToken('get'))
		{
			$this->app->enqueueMessage(JText::_('JINVALID_TOKEN'));
			$this->app->redirect('index.php');
		}

		if (!JFactory::getUser()->authorise('core.admin'))
		{
			$this->app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'));
			$this->app->redirect('index.php');
		}

		$model = new ConfigModelApplication;
		echo new JResponseJson($model->sendTestMail());
		JFactory::getApplication()->close();
	}
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Tests\CommandHandler;

use Prophecy\Prophecy\ObjectProphecy;
use Sylius\Bundle\ApiBundle\Command\Account\SendResetPasswordEmail;
use Sylius\Bundle\ApiBundle\CommandHandler\Account\SendResetPasswordEmailHandler;
use Sylius\Component\Channel\Repository\ChannelRepositoryInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\User\Model\UserInterface;
use Sylius\Component\User\Repository\UserRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Bundle\FrameworkBundle\Test\MailerAssertionsTrait;
use Symfony\Contracts\Translation\TranslatorInterface;

final class SendResetPasswordEmailHandlerTest extends KernelTestCase
{
    use MailerAssertionsTrait;

    /** @test */
    public function it_sends_password_reset_token_email(): void
    {
        if ($this->isItSwiftmailerTestEnv()) {
            $this->markTestSkipped('Test is relevant only for the environment without swiftmailer');
        }

        $container = self::getContainer();

        /** @var TranslatorInterface $translator */
        $translator = $container->get('translator');

        $emailSender = $container->get('sylius.email_sender');

        /** @var ChannelRepositoryInterface|ObjectProphecy $channelRepository */
        $channelRepository = $this->prophesize(ChannelRepositoryInterface::class);
        /** @var UserRepositoryInterface|ObjectProphecy $userRepository */
        $userRepository = $this->prophesize(UserRepositoryInterface::class);
        /** @var ChannelInterface|ObjectProphecy $channel */
        $channel = $this->prophesize(ChannelInterface::class);
        /** @var UserInterface|ObjectProphecy $user */
        $user = $this->prophesize(UserInterface::class);

        $user->getUsername()->willReturn('username');
        $user->getPasswordResetToken()->willReturn('token');

        $channelRepository->findOneByCode('CHANNEL_CODE')->willReturn($channel->reveal());
        $userRepository->findOneByEmail('user@example.com')->willReturn($user->reveal());

        $resetPasswordEmailHandler = new SendResetPasswordEmailHandler(
            $emailSender,
            $channelRepository->reveal(),
            $userRepository->reveal(),
        );

        $resetPasswordEmailHandler(new SendResetPasswordEmail(
            'user@example.com',
            'CHANNEL_CODE',
            'en_US',
        ));

        self::assertEmailCount(1);
        $email = self::getMailerMessage();
        self::assertEmailAddressContains($email, 'To', 'user@example.com');
        self::assertEmailHtmlBodyContains(
            $email,
            $translator->trans('sylius.email.password_reset.to_reset_your_password_token', [], null, 'en_US'),
        );
    }

    private function isItSwiftmailerTestEnv(): bool
    {
        $env = self::getContainer()->getParameter('kernel.environment');

        return $env === 'test_with_swiftmailer';
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Text.RegularExpressions;
using Xunit;

namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests
{
    public abstract class ObjectFormatterTestBase
    {
        protected static PrintOptions SingleLineOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SingleLine };
        protected static PrintOptions SeparateLinesOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SeparateLines, MaximumOutputLength = int.MaxValue };
        protected static PrintOptions HiddenOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.Hidden };

        public void AssertMembers(string str, params string[] expected)
        {
            int i = 0;
            foreach (var line in str.Split(new[] { "\r\n  " }, StringSplitOptions.None))
            {
                if (i == 0)
                {
                    Assert.Equal(expected[i] + " {", line);
                }
                else if (i == expected.Length - 1)
                {
                    Assert.Equal(expected[i] + "\r\n}\r\n", line);
                }
                else
                {
                    Assert.Equal(expected[i] + ",", line);
                }

                i++;
            }

            Assert.Equal(expected.Length, i);
        }

        public string FilterDisplayString(string str)
        {
            str = Regex.Replace(str, @"Id = \d+", "Id = *");
            str = Regex.Replace(str, @"Id=\d+", "Id=*");
            str = Regex.Replace(str, @"Id: \d+", "Id: *");

            return str;
        }
    }
}


text:
require 'hydra/datastream/non_indexed_rights_metadata'
require 'hydra/model_mixins/hybrid_delegator'
require 'role_controls'
require 'avalon/controlled_vocabulary'

class Admin::Collection < ActiveFedora::Base
  include Hydra::ModelMixins::CommonMetadata
  include ActiveFedora::Associations
  include Hydra::ModelMixins::RightsMetadata
  include Hydra::ModelMixins::HybridDelegator

  has_many :media_objects, property: :is_member_of_collection
  has_metadata name: 'descMetadata', type: ActiveFedora::SimpleDatastream do |sds|
    sds.field :name, :string
    sds.field :unit, :string
    sds.field :description, :string
  end
  has_metadata name: 'inheritedRights', type: Hydra::Datastream::InheritableRightsMetadata
  has_metadata name: 'defaultRights', type: Hydra::Datastream::NonIndexedRightsMetadata, autocreate: true

  validates :name, :uniqueness => { :solr_name => 'name_tesim'}, presence: true
  validates :unit, presence: true, inclusion: { in: Proc.new{ Admin::Collection.units } }
  validates :managers, length: {minimum: 1, message: 'Collection requires at least 1 manager'}

  delegate :name, to: :descMetadata, unique: true
  delegate :unit, to: :descMetadata, unique: true
  delegate :description, to: :descMetadata, unique: true
  delegate :read_groups, :read_users, :access, :access=, :hidden?, :hidden=, :group_exceptions,
           :group_exceptions=, :user_exceptions, :user_exceptions=, to: :defaultRights, prefix: :default

  def self.units
    Avalon::ControlledVocabulary.find_by_name(:units)
  end

  def created_at
    @created_at ||= DateTime.parse(create_date)
  end

  def to_solr(solr_doc = Hash.new, opts = {})
    map = Solrizer::default_field_mapper
    solr_doc[ map.solr_name(:name, :stored_searchable, type: :string).to_sym ] = self.name
    super(solr_doc)
  end

  def managers
    edit_users & (RoleControls.users("manager") || [])
  end

  def managers= users
    old_managers = managers
    users.each {|u| add_manager u}
    (old_managers - users).each {|u| remove_manager u}
  end

  def add_manager user
    return unless RoleControls.users("manager").include?(user)
    self.edit_users += [user]
    self.inherited_edit_users += [user]
  end

  def remove_manager user
    return unless managers.include? user
    #raise "OneManagerLeft" if self.managers.size == 1 # Requires at least 1 manager

    self.edit_users -= [user]
    self.inherited_edit_users -= [user]
  end

  def editors
    edit_users - RoleControls.users("manager")
  end

  def editors= users
    old_editors = editors
    users.each {|u| add_editor u}
    (old_editors - users).each {|u| remove_editor u}
  end

  def add_editor user
    self.edit_users += [user]
    logger.debug "EDIT USERS #{self.edit_users}"
    self.inherited_edit_users += [user]
  end

  def remove_editor user
    return unless editors.include? user
    self.edit_users -= [user]
    self.inherited_edit_users -= [user]
  end

  def depositors
    read_users
  end

  def depositors= users
    old_depositors = depositors
    users.each {|u| add_depositor u}
    (old_depositors - users).each {|u| remove_depositor u}
  end

  def add_depositor user
    # Do not add an edit_user to read_users or he will be removed from edit_users
    unless self.edit_users.include? user
      self.read_users += [user]
      self.inherited_edit_users += [user]
    else
      raise "UserIsEditor"
    end
  end

  def remove_depositor user
    return unless depositors.include? user
    self.read_users -= [user]
    self.inherited_edit_users -= [user]
  end

  def inherited_edit_users
    inheritedRights.edit_access.machine.person
  end

  def inherited_edit_users= users
    p = {}
    (inherited_edit_users - users).each {|u| p[u] = 'none'}
    users.each {|u| p[u] = 'edit'}
    inheritedRights.update_permissions('person'=>p)
  end

  def self.reassign_media_objects( media_objects, source_collection, target_collection)
    media_objects.dup.each do |media_object|

      source_collection.remove_relationship(:is_member_of_collection, "info:fedora/#{media_object.pid}")
      source_collection.media_objects.delete media_object

      target_collection.add_relationship(:is_member_of_collection, "info:fedora/#{media_object.pid}")
      target_collection.media_objects << media_object

      media_object.collection = target_collection
      media_object.save!
    end
    source_collection.save!
    target_collection.save!
  end

end


text:
class Finances::GetUnsortedIncome
  include Finances::GroupByAccount

  def initialize(gateway)
    @gateway = gateway
  end

  def run
    group_by_account unsorted_transactions
  end

  def unsorted_transactions
    sorted_transaction_ids = @gateway.credits.map(&:transaction_id)
    @gateway.transactions.select(&:credit?).reject do |t|
      sorted_transaction_ids.include? t.id
    end
  end
end


text:
module Transactionable
  class ViewsGenerator < Rails::Generators::Base
    source_root File.expand_path('../../../../app/views/transactionable/', __FILE__)
    desc "Copies shared transactionable views to your application."

    def copy_shared_partials
      directory "shared/", "app/views/transactionable/shared/"
    end
  end
end


text:
package uk.org.ngo.squeezer.util;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import uk.org.ngo.squeezer.R;
import uk.org.ngo.squeezer.Squeezer;
import uk.org.ngo.squeezer.model.PlayerState;
import uk.org.ngo.squeezer.model.Song;

public class Scrobble {

    public static boolean haveScrobbleDroid() {
        return Intents.isBroadcastReceiverAvailable(
                Squeezer.getContext(),
                "net.jjc1138.android.scrobbler.action.MUSIC_STATUS");
    }

    public static boolean haveSls() {
        return Intents.isBroadcastReceiverAvailable(
                Squeezer.getContext(),
                "com.adam.aslfms.notify.playstatechanged");
    }

    public static boolean canScrobble() {
        return haveScrobbleDroid() || haveSls();
    }

    /**
     * Conditionally broadcasts a scrobbling intent populated from a player state.
     *
     * @param context the context to use to fetch resources.
     * @param playerState the player state to scrobble from.
     */
    public static void scrobbleFromPlayerState(@NonNull Context context, @Nullable PlayerState playerState) {
        if (playerState == null || !Scrobble.canScrobble())
            return;

        @PlayerState.PlayState String playStatus = playerState.getPlayStatus();
        Song currentSong = playerState.getCurrentSong();

        if (playStatus == null || currentSong == null)
            return;

        Log.d("Scrobble", "Scrobbling, playing is: " + (PlayerState.PLAY_STATE_PLAY.equals(playStatus)));
        Intent i = new Intent();

        if (Scrobble.haveScrobbleDroid()) {
            // http://code.google.com/p/scrobbledroid/wiki/DeveloperAPI
            i.setAction("net.jjc1138.android.scrobbler.action.MUSIC_STATUS");
            i.putExtra("playing", PlayerState.PLAY_STATE_PLAY.equals(playStatus));
            i.putExtra("track", currentSong.getName());
            i.putExtra("album", currentSong.getAlbum());
            i.putExtra("artist", currentSong.getArtist());
            i.putExtra("secs", currentSong.getDuration());
            i.putExtra("source", "P");
        } else if (Scrobble.haveSls()) {
            // http://code.google.com/p/a-simple-lastfm-scrobbler/wiki/Developers
            i.setAction("com.adam.aslfms.notify.playstatechanged");
            i.putExtra("state", PlayerState.PLAY_STATE_PLAY.equals(playStatus) ? 0 : 2);
            i.putExtra("app-name", context.getText(R.string.app_name));
            i.putExtra("app-package", "uk.org.ngo.squeezer");
            i.putExtra("track", currentSong.getName());
            i.putExtra("album", currentSong.getAlbum());
            i.putExtra("artist", currentSong.getArtist());
            i.putExtra("duration", currentSong.getDuration());
            i.putExtra("source", "P");
        }
        context.sendBroadcast(i);
    }
}


text:
/*
 (c) DHTMLX Ltd, 2011
 Licensing: You allowed to use this component for free under GPL or you need to obtain Commercial/Enterprise license to use it in non-GPL project
 Contact: sales@dhtmlx.com
 */
 dhtmlxSpreadSheet.prototype.addContext = function() {
	var menu;
	if (this.context) {
		menu = this.context;
	} else {
		menu = new dhtmlXMenuObject();
		menu.setImagePath(this.settings.image_path);
		menu.setIconPath(this.settings.icons_path);
		menu.renderAsContextMenu();
		menu.addNewChild(null, 1, "lock", "Lock", false, "lock.png");
		menu.addNewChild(null, 2, "validator", "Validate", false, "validate.png");
		menu.addRadioButton("child", "validator", 1, "none", "None", "validators", true, false);
		menu.addRadioButton("child", "validator", 2, "number", "Number", "validators", false, false);
		menu.addRadioButton("child", "validator", 3, "email", "Email", "validators", false, false);
		menu.addRadioButton("child", "validator", 4, "positive", "Positive", "validators", false, false);
		menu.addRadioButton("child", "validator", 5, "not_empty", "Not empty", "validators", false, false);
		var self = this;
		this.grid.attachEvent("onBeforeContextMenu", function(row, col){
			self._ctxCells = [{ row: row, col: col }];
			return self.onBeforeContextMenu(row, col);
        });
		menu.attachEvent("onBeforeContextMenu", function(){
			var block = self.grid.getSelectedBlock();
			if (block === null) return false;
			var cells = [];
			for (var i = block.LeftTopRow; i <= block.RightBottomRow; i++) {
				for (var j = block.LeftTopCol; j <= block.RightBottomCol; j++) {
					cells.push({ row: i, col: j });
				}
			}
			self._ctxCells = cells;
			return self.onBeforeContextMenu(cells[0].row, cells[0].col);
        });
		menu.attachEvent("onRadioClick", function(menuitemId, type) {
			self._validatorIsSetted(menuitemId,type);
			return true;
		});
		menu.attachEvent("onClick", function(id) {
			switch (id) {
				case 'lock':
					var range = self._old_ctx();
					var value = self.isLocked(range.minrow, range.mincol);
					for (var i = 0; i < self._ctxCells.length; i++)
						self.lockCell(self._ctxCells[i].row, self._ctxCells[i].col, !value);
					break;
				default:
					break;
			}
		});
		this.context = menu;
	}

	return menu;
};

dhtmlxSpreadSheet.prototype._old_ctx = function() {
	if (!this._ctxCells) return;
	var minrow = 100000;
	var mincol = 100000;
	var maxrow = -1;
	var maxcol = -1;
	for (var i = 0; i < this._ctxCells.length; i++) {
		minrow = Math.min(minrow, this._ctxCells[i].row);
		mincol = Math.min(mincol, this._ctxCells[i].col);
		maxrow = Math.max(maxrow, this._ctxCells[i].row);
		maxcol = Math.max(maxcol, this._ctxCells[i].col);
	}
	this._old("cells", [minrow, mincol, maxrow, maxcol]);
	return {
		minrow: minrow,
		mincol: mincol,
		maxrow: maxrow,
		maxcol: maxcol
	};
};

dhtmlxSpreadSheet.prototype.onBeforeContextMenu = function(row, col){
	if (col == 0) return false;
	if (this.settings.read_only) return false;
	var style = this.getCellStyle(row, col);
	var json = style.get_json();
	this.context.setRadioChecked("validators", json.validator);
	this.context.setItemText("lock", json.lock == "true" ? "Unlock" : "Lock");
	return true;
}

dhtmlxSpreadSheet.prototype._validatorIsSetted = function(menuitemid, type) {
	if (!this._ctxCells) return;
	var self = this;
	window.setTimeout(function() {
		var value = self.context.getRadioChecked("validators");
		self.context.hideContextMenu();
		self._old_ctx();
		for (var i = 0; i < self._ctxCells.length; i++) {
			var row = self._ctxCells[i].row;
			var col = self._ctxCells[i].col;
			if (self.isLocked(row, col)) continue;
			var style = self.getCellStyle(row, col);
			style.set('validator', value);
			self.to_stack(row, col);
			self.validateCell(row, col);
		}
		self._ctxCells = null;
	}, 1);
};

dhtmlxSpreadSheet.prototype.lockCell = function(row, col, value) {
	this.context.hideContextMenu();
	var style = this.getCellStyle(row, col);
	var lock = style.get('lock');
	var inverse_value = lock == 'false' ? 'true' : 'false';
	if (typeof(value) != 'undefined')
		value = (value == true) ? 'true' : 'false';
	else
		value = inverse_value;
	style.set('lock', value);
	this.to_stack(row, col);
	this.renderCell(row, col);
};

dhtmlxSpreadSheet.prototype.isLocked = function(row, col) {
	var style = this.getCellStyle(row, col);
	var lock = style.get('lock');
	return lock == 'false' ? false : true;
};

dhtmlxSpreadSheet.prototype.validate = function() {
	for (var i = 0; i < this.settings.rows; i++) {
		var row = i + 1;
		for (var j = 1; j <= this.settings.cols; j++) {
			this.validateCell(row, j);
		}
	}
}

dhtmlxSpreadSheet.prototype.validateCell = function(row, col) {
	var cell = this.grid.cells(row, col);
	var style = this.getCellStyle(row, col);
	var json = style.get_json();
	var validator = this.validators[json.validator]

	var value = cell.getValue();
	if (validator && this[validator] && this[validator](value) == false) {
		cell.cell.className += ' invalid';
	} else {
		cell.cell.className = cell.cell.className.replace(/ invalid/g, '');
	}
};

dhtmlxSpreadSheet.prototype.render = function() {
	for (var i = 0; i < this.settings.rows; i++) {
		var row = i + 1;
		for (var j = 1; j <= this.settings.cols; j++) {
			this.renderCell(row, j);
		}
	}
};

dhtmlxSpreadSheet.prototype.renderCell = function(row, col) {
	var cell = this.grid.cells(row, col);
	var style = this.getCellStyle(row, col);
	var json = style.get_json();
	this.validateCell(row, col);

	if (json.lock == 'true') {
		cell.cell.className += ' locked';
	} else {
		cell.cell.className = cell.cell.className.replace(/ locked/g, '');
	}
};

dhtmlxSpreadSheet.prototype._is_number = function(value) {
	var reg = /^\-?\d+(\.\d+)?$/;
	value = value.toString().trim();
	if (reg.test(value)) return true;
	return false;
}

dhtmlxSpreadSheet.prototype._is_email = function(value) {
	var reg = /^.+@.+\..{2,4}$/;
	value = value.toString().trim();
	if (reg.test(value)) return true;
	return false;
}

dhtmlxSpreadSheet.prototype._is_positive = function(value) {
	var reg = /^\d+(\.\d+)?$/;
	value = value.toString().trim();
	if (reg.test(value)) return true;
	return false;
}

dhtmlxSpreadSheet.prototype._is_not_empty = function(value) {
	value = value.toString().trim();
	if (value) return true;
	return false;
}

dhtmlxSpreadSheet.prototype.validators = {
	"none": null,
	"number": "_is_number",
	"email": "_is_email",
	"positive": "_is_positive",
	"not_empty": "_is_not_empty"
};

/*! additional event which occurs when block-selection container is shown.
 *  is used to make double click on selected cell a little better.
 **/
dhtmlXGridObject.prototype._ShowSelection = function()
{
	if (this._selectionObj) {
		this.callEvent("onBlockSelectionShown", []);
	    this._selectionObj.style.display = '';
	}
}