text:
@interface DateFormatter : NSObject

+ (NSDate *)dateFromString:(NSString *)stringDate withOffSet:(NSNumber *)offset;
+ (NSString*)weekDayFromDate:(NSDate *)date;

@end

redpajama_set_name: RedPajamaGithub


text:
title: WAI-ARIA Support
page_title: WAI-ARIA Support - RadDatePicker
description: Check our Web Forms article about RadDatePicker WAI-ARIA Support.
slug: datepicker/accessibility-and-internationalization/wai-aria-support
tags: wai-aria,support
published: True
position: 6
---

# WAI-ARIA Support

The **RadDatePicker** control offers **WAI-ARIA** support which can be easily enabled by setting the **EnableAriaSupport** server property to **true**, e.g.

````ASP.NET
        <telerik:RadDatePicker RenderMode="Lightweight" Width="100%" ID="RadDatePicker1" runat="server" EnableAriaSupport="true" EnableKeyboardNavigation="true">
            <Calendar ID="Calendar1" runat="server" EnableAriaSupport="true"></Calendar>
            <DateInput ToolTip="Date input" runat="server" Label="Delivery date"></DateInput>
        </telerik:RadDatePicker>
````

All ARIA attributes are **lower case**. They are shown in the table below.

>caption

|  Control  |  Attributes  |
| ------ | ------ |
| **RadDatePicker** | Role:button |

>note
An issue with the use of WAI-ARIA in HTML documents is that they do not pass validation. When you run a HTML document containing ARIA attributes through the W3C Validator it shows errors in the results for any ARIA attributes. The DOCTYPE declarations do not include any information about the WAI ARIA attributes and you cannot have a valid document that includes elements, attributes, and attribute values, not detailed in its DTDs.
>

# See Also

 * [This functionality online](https://demos.telerik.com/aspnet-ajax/calendar/examples/functionality/waiariasupport/defaultcs.aspx)

 * [WAI-ARIA basic information](https://www.w3.org/WAI/intro/aria)


text:
require('./extensions');

var Handlebars = require('handlebars');

var internal =
{
    loadTemplates: function ()
    {
        var fs = require('fs');

        var templatesFolder = __dirname + '\\templates';

        var templateFilenames = fs.readdirSync(templatesFolder);

        var templates = {};

        for (var i = 0; i < templateFilenames.length; i++)
        {
            var templateFilename = templateFilenames[i];

            var contents = fs.readFileSync(templatesFolder + '\\' + templateFilename, 'utf8');

            templates[templateFilename] = Handlebars.compile(contents);
        }

        return templates;
    }
};

module.exports =
{
    templates: internal.loadTemplates()
};


text:
from django.contrib import admin

# Register your models here.
from user_app.models import CoworkUser, Hub
from django.contrib.auth.models import Permission

class CoworkUserAdmin(admin.ModelAdmin):
    filter_horizontal = ('hubs',)
    list_display = ('username',)

    def username(self, obj):
        return obj.user.username

    def has_change_permission(self, request, obj=None):
        """Returns true if the user has view permission"""
        if request.user.has_perm("user_app.view_coworkuser") or \
                request.user.has_perm("user_app.view_coworkuser"):
            return True
        else:
            return False

class HubAdmin(admin.ModelAdmin):
    list_display = ('name', 'location',)
    list_filter = ('location',)
    search_fields = ['name', 'location']

admin.site.register(CoworkUser, CoworkUserAdmin)
admin.site.register(Hub, HubAdmin)
admin.site.register(Permission)


text:
#ifndef __RTT_STATFS_H__
#define __RTT_STATFS_H__

#include <rtthread.h>

struct statfs
{
	rt_size_t f_bsize; 	 /* block size */
	rt_size_t f_blocks;  /* total data blocks in file system */
	rt_size_t f_bfree;	 /* free blocks in file system */
};

#endif


text:
PDFKit.configure do |config|
  config.wkhtmltopdf = ''
  ENV['PATH'].split(File::PATH_SEPARATOR).any? do |directory|
    config.wkhtmltopdf = File.join(directory, program.to_s) if File.executable?(File.join(directory, program.to_s))
  end
end


text:
using UnityEngine;
using UnityEngine.UI;

public class ClimberControls : MonoBehaviour
{
	Vector3 acceleration;
	Vector3 velocity;
	public Transform climber;
    public float downAcceleration;
    public float bungeeDistanceMultiplier;
    public float bungeeSnapDistance;
    public float bungeeSnapMultiplier;
    public float drag;
    public float invulnTime;
	public GameManager gm;
    private float invulnRemaining;

    float maxStrength = 1;
    float currentStrength = 1;
    public float strengthRegenRate;
    public float strengthConsumptionRate;
    public Text strengthText;
    public RectTransform strMeter;
    private float strMeterFullWidth;

    public GameObject[] ropes;

    private void Start()
    {
        transform.position = new Vector3(0, 0.0001f, 1);
        strMeterFullWidth = strMeter.rect.width;
    }

    // Update is called once per frame
    private void Update()
    {
        if(invulnRemaining > 0)
        {
            invulnRemaining -= Time.deltaTime;
            if(invulnRemaining <= 0)
            {
                gameObject.GetComponent<SpriteRenderer>().color = new Color(1, 1, 1, 1);
            }
        }

        acceleration = Vector3.zero;

        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S) || Input.touchCount > 0)
        {
            acceleration.y -= downAcceleration * currentStrength;

            //  We are pulling down, sap strength
            currentStrength -= strengthConsumptionRate * Time.deltaTime;

            //  Strength cant drop below 0
            if (currentStrength < 0)
            {
                currentStrength = 0;
            }
        }
        else
        {
            currentStrength += strengthRegenRate * Time.deltaTime;
            //  Cap strength at max (currently 1)
            if (currentStrength > maxStrength)
            {
                currentStrength = maxStrength;
            }
        }

        strengthText.text = "Str: " + currentStrength;
        strMeter.sizeDelta = new Vector2(currentStrength * strMeterFullWidth, strMeter.rect.height);
        strMeter.anchoredPosition = new Vector2((1-currentStrength) * strMeterFullWidth / -2, 0);

        //  Basic rope correction force
        acceleration.y += -climber.position.y * bungeeDistanceMultiplier;

        //  Rope is getting taugth correction force
        if (climber.position.y > bungeeSnapDistance)
        {
            acceleration.y += -climber.position.y*bungeeSnapMultiplier;

        }
        else if (climber.position.y < -bungeeSnapDistance)
        {
            acceleration.y += -climber.position.y* bungeeSnapMultiplier;
        }

        velocity += acceleration * Time.deltaTime;
        velocity *= drag;
        climber.position += velocity * Time.deltaTime;

        //rope.LookAt(transform, new Vector3(0, 1, 0));
        for (int i = 0; i < ropes.Length; i++)
        {
            Vector3 deltaPos = (transform.position + new Vector3(0, 0.5f, 1)) - ropes[i].transform.position;
            ropes[i].transform.forward = deltaPos;
            ropes[i].transform.localScale = new Vector3(0.25f, 0.25f, deltaPos.magnitude*2);
        }
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if (gm != null && invulnRemaining <= 0)
		{
			gm.changeScore (-50);
            gm.changeLives(-1);
            invulnRemaining = invulnTime;
            gameObject.GetComponent<SpriteRenderer>().color = new Color(1, 0, 0, 190.0f / 255.0f);
		    other.gameObject.GetComponent<SpriteRenderer> ().color = Color.red;
		}
	}
}


text:
cask 'workflowy' do
  version '1.1.8'
  sha256 '1f00f936bc918e6265e12a084ee3a8d3bac381ba6afae6f1fcf3ae6314668429'

  # github.com/workflowy/desktop was verified as official when first introduced to the cask
  url "https://github.com/workflowy/desktop/releases/download/v#{version}/WorkFlowy.dmg"
  appcast 'https://github.com/workflowy/desktop/releases.atom'
  name 'WorkFlowy'
  homepage 'https://workflowy.com/downloads/mac/'

  app 'WorkFlowy.app'
end


text:
#pragma once
#include <aws/ds/DirectoryService_EXPORTS.h>
#include <aws/ds/DirectoryServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace DirectoryService
{
namespace Model
{

  /**
   *
Registers a new event topic.

See Also:
   AWS
   * API Reference

   */
  class AWS_DIRECTORYSERVICE_API RegisterEventTopicRequest : public DirectoryServiceRequest
  {
  public:
    RegisterEventTopicRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline const Aws::String& GetDirectoryId() const{ return m_directoryId; }

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline void SetDirectoryId(const Aws::String& value) { m_directoryIdHasBeenSet = true; m_directoryId = value; }

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline void SetDirectoryId(Aws::String&& value) { m_directoryIdHasBeenSet = true; m_directoryId = std::move(value); }

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline void SetDirectoryId(const char* value) { m_directoryIdHasBeenSet = true; m_directoryId.assign(value); }

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline RegisterEventTopicRequest& WithDirectoryId(const Aws::String& value) { SetDirectoryId(value); return *this;}

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline RegisterEventTopicRequest& WithDirectoryId(Aws::String&& value) { SetDirectoryId(std::move(value)); return *this;}

    /**
     *
The Directory ID that will publish status messages to the SNS topic.

     */
    inline RegisterEventTopicRequest& WithDirectoryId(const char* value) { SetDirectoryId(value); return *this;}

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline const Aws::String& GetTopicName() const{ return m_topicName; }

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline void SetTopicName(const Aws::String& value) { m_topicNameHasBeenSet = true; m_topicName = value; }

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline void SetTopicName(Aws::String&& value) { m_topicNameHasBeenSet = true; m_topicName = std::move(value); }

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline void SetTopicName(const char* value) { m_topicNameHasBeenSet = true; m_topicName.assign(value); }

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline RegisterEventTopicRequest& WithTopicName(const Aws::String& value) { SetTopicName(value); return *this;}

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline RegisterEventTopicRequest& WithTopicName(Aws::String&& value) { SetTopicName(std::move(value)); return *this;}

    /**
     *
The SNS topic name to which the directory will publish status messages. This
     * SNS topic must be in the same region as the specified Directory ID.

     */
    inline RegisterEventTopicRequest& WithTopicName(const char* value) { SetTopicName(value); return *this;}

  private:
    Aws::String m_directoryId;
    bool m_directoryIdHasBeenSet;
    Aws::String m_topicName;
    bool m_topicNameHasBeenSet;
  };

} // namespace Model
} // namespace DirectoryService
} // namespace Aws


text:
package com.geeksforgeeks.Matrix;

/**
 * Created by Vaidehi Murarka on 12/20/2016.
 *
 * http://www.programcreek.com/2013/01/leetcode-search-a-2d-matrix-java/
 *
 * Complexity: O(log(mn))
 *
 */
public class SearchMatrix {
    public boolean findElement(int[][] input, int element){
        if(input == null || input.length == 0){
            return false;
        }

        int rows = input.length;
        int columns = input[0].length;
        int start = 0;
        int end = rows*columns - 1;

        while(start <= end){
            int middle = (start + end)/2;
            int middleX = middle / columns;
            int middleY = middle % columns;
            if(input[middleX][middleY] == element){
                return true;
            } else{
                if(input[middleX][middleY] > element){
                    end = middle - 1;
                } else {
                    start = middle + 1;
                }
            }
        }
        return false;
    }

    public static void main(String[] args){
        SearchMatrix searchMatrix = new SearchMatrix();
        boolean result = searchMatrix.findElement(new int[][]{
                {1,   3,  5,  7},
                {10, 11, 16, 20},
                {23, 30, 34, 50}}, 3);
        System.out.println(result);
    }
}


text:
#include "playlistwidget.h"
#include <QAbstractItemModel>
#include <QStringList>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidgetItem>
#include <QDebug>
#include <QtGui>
#include <QDragEnterEvent>
#include "controler.h"
#include "playlistmanager.h"
PlaylistWidget::PlaylistWidget(QWidget *parent) :
    QListWidget(parent)
{
    this->setGeometry(30,30, 270, 120);
  //  this->setFixedHeight(300);
  //  this->setFixedWidth(270);
    this->setVisible(true);

 //   list = new QListWidget(this);
 //   list->setGeometry(10,10, 250, 280);
 //   list->setVisible(true);

 //   QWidgetItem* button_play=  new QWidget();
 //   button_play->setGeometry(30, 30, 50, 30);
   // connect(button_play, SIGNAL (released()), this, SLOT (play()));
   // button_play.setVisible(true);

    for(int i=0; i<(Controler::getControl()).size(); i++)
    this->insertItem(i,(Controler::getControl()).getAudioFileName(i).c_str());

    connect(this, SIGNAL ( itemDoubleClicked(QListWidgetItem*)), this, SLOT (doubleClicked()));
    connect(this, SIGNAL ( itemClicked(QListWidgetItem*)), this, SLOT (clicked()));

	timer= new QTimer(this);
    connect(&(((PlayListManager*)this->parentWidget())->list), SIGNAL( itemClicked(QListWidgetItem*)) , this, SLOT (selected()));
    timer->start(1000);

		setAcceptDrops(true);
        setDragEnabled(true);

        setSelectionMode(QAbstractItemView::SingleSelection);
        setDropIndicatorShown(true);
        setDragDropMode(QAbstractItemView::InternalMove);

        setAlternatingRowColors(true);

};

void PlaylistWidget::doubleClicked(){
	std::lock_guard<std::recursive_mutex> lock(mutex);

    qDebug()<<this->currentIndex()<<this->currentItem();
 	Controler::getControl().setCurrentFileIndex(this->currentRow());
}

void PlaylistWidget::clicked(){
	std::lock_guard<std::recursive_mutex> lock(mutex);
	((PlayListManager*)this->parentWidget())->selected_song=this->currentRow();
}

void PlaylistWidget::loadPlaylist(unsigned int idx){
	std::lock_guard<std::recursive_mutex> lock(mutex);

	this->clear();
	if(Controler::getControl().getPlayListSize(idx)>0)
		for(int i=0; i<Controler::getControl().getPlayListSize(idx); i++){
			this->insertItem(i,(Controler::getControl()).getAudioFileName(idx, i).c_str());
		}
	if(this->count()>0){
		this->setCurrentRow(Controler::getControl().getCurrentFileIndex());
	}
}

void PlaylistWidget::selected(){
	std::lock_guard<std::recursive_mutex> lock(mutex);
	if(((PlayListManager*)this->parentWidget())->selected_playlist!=old_playlist_index){
		old_playlist_index=((PlayListManager*)this->parentWidget())->selected_playlist;
		loadPlaylist(((PlayListManager*)this->parentWidget())->selected_playlist);
	}
	if(old_playlist_index==Controler::getControl().getCurrentPlayListIndex() && Controler::getControl().getPlayListSize()>0){
		this->item(Controler::getControl().getCurrentFileIndex())->setBackgroundColor(Qt::red);

	}
	/*while(this->count()>0)
		this->takeItem(0);
		for(int i=0; i<Controler::getControl().size(); i++){
			this->insertItem(i,(Controler::getControl()).getAudioFileName(i).c_str());
		}
	if(this->count()>0){
		this->setCurrentRow(Controler::getControl().getCurrentFileIndex());
	}*/
}

    void PlaylistWidget::dragEnterEvent(QDragEnterEvent *event)
    {
			std::lock_guard<std::recursive_mutex> lock(mutex);

		if (event->mimeData()->hasUrls())
        {
            event->acceptProposedAction();
        } else {
            QListWidget::dragEnterEvent(event);
        }
    }

    void PlaylistWidget::dragMoveEvent(QDragMoveEvent *event)
    {

        if (event->mimeData()->hasUrls())
        {
            event->acceptProposedAction();
        } else {
            QListWidget::dragMoveEvent(event);
        }
    }

    void PlaylistWidget::dropEvent(QDropEvent *event)
    {

        if (event->mimeData()->hasUrls())
        {
            QList<QUrl> urls = event->mimeData()->urls();
            if (!urls.isEmpty())
            {
                QUrl url;
                foreach (url,urls)
                {
					std::string file_path=url.toString().toStdString();
					std::string path =file_path.substr(7, file_path.length()-6);
					try{
						std::lock_guard<std::recursive_mutex> lock(mutex);

	                	Controler::getControl().addFile(((PlayListManager*)this->parentWidget())->selected_playlist, path);

	//						new QListWidgetItem(Controler::getControl().getAudioFileName(Controler::getControl().size()-1).c_str(),this);

        		    }catch(std::string e)
            		{
            			std::cerr << e << std::endl;
            		}

                }
		loadPlaylist(old_playlist_index);
            }
            event->acceptProposedAction();
        }
        QListWidget::dropEvent(event);
    }


text:
<!DOCTYPE html>

<link href='../fullcalendar.css' rel='stylesheet' />
<link href='../fullcalendar.print.css' rel='stylesheet' media='print' />


text:
package test

import (
	"github.com/tidepool-org/platform/auth"
	dataSourceStoreStructured "github.com/tidepool-org/platform/data/source/store/structured"
)

type Provider struct {
	AuthClientInvocations                int
	AuthClientStub                       func() auth.Client
	AuthClientOutputs                    []auth.Client
	AuthClientOutput                     *auth.Client
	DataSourceStructuredStoreInvocations int
	DataSourceStructuredStoreStub        func() dataSourceStoreStructured.Store
	DataSourceStructuredStoreOutputs     []dataSourceStoreStructured.Store
	DataSourceStructuredStoreOutput      *dataSourceStoreStructured.Store
}

func NewProvider() *Provider {
	return &Provider{}
}

func (p *Provider) AuthClient() auth.Client {
	p.AuthClientInvocations++
	if p.AuthClientStub != nil {
		return p.AuthClientStub()
	}
	if len(p.AuthClientOutputs) > 0 {
		output := p.AuthClientOutputs[0]
		p.AuthClientOutputs = p.AuthClientOutputs[1:]
		return output
	}
	if p.AuthClientOutput != nil {
		return *p.AuthClientOutput
	}
	panic("AuthClient has no output")
}

func (p *Provider) DataSourceStructuredStore() dataSourceStoreStructured.Store {
	p.DataSourceStructuredStoreInvocations++
	if p.DataSourceStructuredStoreStub != nil {
		return p.DataSourceStructuredStoreStub()
	}
	if len(p.DataSourceStructuredStoreOutputs) > 0 {
		output := p.DataSourceStructuredStoreOutputs[0]
		p.DataSourceStructuredStoreOutputs = p.DataSourceStructuredStoreOutputs[1:]
		return output
	}
	if p.DataSourceStructuredStoreOutput != nil {
		return *p.DataSourceStructuredStoreOutput
	}
	panic("DataSourceStructuredStore has no output")
}

func (p *Provider) AssertOutputsEmpty() {
	if len(p.AuthClientOutputs) > 0 {
		panic("AuthClientOutputs is not empty")
	}
	if len(p.DataSourceStructuredStoreOutputs) > 0 {
		panic("DataSourceStructuredStoreOutputs is not empty")
	}
}


text:
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { restartableTask } from 'ember-concurrency';
import { filter } from 'rsvp';

export default class SelectableTermsList extends Component {
  @tracked terms = [];

  get topLevelTermsRelationshipPromise() {
    return this.args.vocabulary ? this.args.vocabulary.getTopLevelTerms() : null;
  }

  loadFilteredTerms = restartableTask(async () => {
    let terms = [];
    if (this.topLevelTermsRelationshipPromise) {
      terms = (await this.topLevelTermsRelationshipPromise).slice();
    } else if (this.args.terms) {
      terms = this.args.terms.slice();
    }

    if (this.args.termFilter) {
      const exp = new RegExp(this.args.termFilter, 'gi');
      this.terms = await filter(terms, async (term) => {
        const searchString = await term.getTitleWithDescendantTitles();
        return searchString.match(exp);
      });
    } else {
      this.terms = terms;
    }
  });
}


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

	<title>Ambush</title>

	<link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />

Ambush

Teams: USMC vs. OpFor

Place: Makkah Coast, Saudi Arabia

Terrain: Desert town with streets, fences, and sewer pipes

Type of Combat: Medium range combat

Overview

Map set around a convoy of broken-down vehicles and hosts a wide variety of elevated spots, enabling you to hold your breath and take aim. Both spawn points provide ample sniping locations which overlook the middle of the map, along with the opposing sniper positions. The sewer tunnels are an area of the map which are most largely overlooked. This is a small area, but one that has saved lives on more than one occasion, especially by protecting players from the bombs of airstrikes. This map is also known for spam grenading (throwing a random grenade anywhere and getting a kill). All types of classes are effective here. Desert camouflage or Digital camouflage  work best. By jumping onto certain points and objects, players are allowed to get into destroyed buildings that are otherwise inaccessible.

Stealth classes work particularly well here, as the map offers a lot of cover, dark corners and high grass. In addition, many of the buildings encourage camping. Getting up behind people is a good way to get headshots. Be warned though: On team deathmatch, the spawn locations swap sides frequently, meaning the player may end up in the middle of their own spawn point. Additionally, claymores and C4 are frequently used, so Bomb Squad is particularly useful, especially if the aforementioned stealth class is used.

Tactics

The tunnels under the center of the map can be used to flank enemies taking point B in Domination, and players in the middle in general.

The turret near USMC spawn can be used when on defense but enemies will usually return once they know the player's position.

Snipers often lurk on the first story roof tops of the buildings on either side of the road.

From the second story building on the east side of the map, one can get a good sniper view of their east pathway.

A good team can establish excellent fire lanes, but it requires coordination, and team members must cover the rear area to prevent flanking.

All weapons, although one must take extra precautions when using a shotgun, can be effective on this map if the user flanks and stays out of the open. It is recommended using Extreme Conditioning to get through open areas fast. Use the tunnels in the center of the map to avoid being caught out in the open. If the player stays around the outer areas of the map, they can easily spawn kill. Snipers must take particular care to keep moving, as most players often scan the 4 main elevated buildings.

Some buildings on the OpFor spawn side of the map can be hopped into.

If one of the sewer pipes is frequently being used by the enemy the other one can be used as an effective gunning post as there are two smaller barred pipes connecting the sewers and they can be shot through, but plant Claymores at both ends of the tunnel because it is very likely the player will be surrounded.

On Domination, one can easily defend flags A or C using the nearby mounted M249s

If the player spawns as a member the USMC on this map they are more likely to be spawn trapped at their beginning spawn point.


text:
pwny package
============

The ``pwny`` package provides a convence metapackage that imports the entire
public API of `pwnypack` into a single namespace::

    >>> from pwny import *
    >>> enhex(asm('mov rax, 0xced', target=Target(arch=Architecture.x86_64)))
    u'b8ed0c0000'

For details about what exactly is made available, please consult the
documentation of the individual :doc:`pwnypack modules <pwnypack>`.


text:
package com.productfoundry.akka.cqrs

import org.scalacheck.Arbitrary._
import org.scalacheck.{Arbitrary, Gen}

trait Fixtures {

  implicit def ArbitraryDummyId: Arbitrary[DummyId] = Arbitrary {
    Gen.delay(DummyId.generate())
  }

  implicit def ArbitraryRevision[R <: Revision[R]](implicit companion: RevisionCompanion[R]): Arbitrary[R] = Arbitrary {
    Gen.choose(0, 100).map(value => companion.apply(value.toLong))
  }

  implicit def ArbitraryCommit: Arbitrary[Commit] = Arbitrary {
    for {
      id <- arbitrary[DummyId]
      revision <- arbitrary[AggregateRevision]
      values <- arbitrary[Seq[Int]]
    } yield Changes(values.map(value => DummyEvent(id, value)): _*).createCommit(AggregateTag("", id.toString, revision))
  }

  implicit def ArbitraryConfirmable: Arbitrary[DummyConfirmable] = Arbitrary {
    arbitrary[Long].map(value => DummyConfirmable(value))
  }

  implicit def ArbitraryAggregateTag: Arbitrary[AggregateTag] = Arbitrary {
    for {
      name <- arbitrary[String]
      id <- arbitrary[DummyId]
      revision <- arbitrary[AggregateRevision]
    } yield AggregateTag(name, id.toString, revision)
  }
}


text:
import {Component, OnInit, Input} from '@angular/core';
import {Messages} from "../../messages";
import {AbstractRegisteredService} from "../../../domain/registered-service";
import {Data} from "../data";

@Component({
  selector: 'app-logo',
  templateUrl: './logo.component.html'
})
export class LogoComponent implements OnInit {

  constructor(public messages: Messages,
              public data: Data) {
  }

  ngOnInit() {
  }

}


text:
FROM debian:jessie

MAINTAINER Yuvi Panda <yuvipanda@riseup.net>
RUN echo shit
RUN apt-get update
RUN apt-get install --yes --no-install-recommends \
    python3.4 \
    python3-pip \
    python3.4-dev

COPY . /srv/nbserve/

RUN pip3 install ipython tornado nbconvert pytz

WORKDIR /srv/nbserve
RUN python3 /srv/nbserve/setup.py install

EXPOSE 8000

CMD python3 -m nbserver.app


text:
int main(int argc, char * argv[]) {
    return bandit::run(argc,argv);
}


text:
<?php
namespace Disque\Connection\Response;

class IntResponse extends BaseResponse
{
    /**
     * Parse response
     *
     * @return string Response
     */
    public function parse()
    {
        return (int) $this->data;
    }
}


text:
/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Copyright (c) 2008-2012 Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package tck.java.time;

import static org.testng.Assert.assertEquals;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;

import org.testng.annotations.Test;

/**
 * Test Clock.
 */
@Test
public class TCKClock {

    static class MockInstantClock extends Clock {
        final long millis;
        final ZoneId zone;
        MockInstantClock(long millis, ZoneId zone) {
            this.millis = millis;
            this.zone = zone;
        }
        @Override
        public long millis() {
            return millis;
        }
        @Override
        public Instant instant() {
            return Instant.ofEpochMilli(millis());
        }
        @Override
        public ZoneId getZone() {
            return zone;
        }
        @Override
        public Clock withZone(ZoneId timeZone) {
            return new MockInstantClock(millis, timeZone);
        }
        @Override
        public boolean equals(Object obj) {
            return false;
        }
        @Override
        public int hashCode() {
            return 0;
        }
        @Override
        public String toString() {
            return "Mock";
        }
    }

    private static final Instant INSTANT = Instant.ofEpochSecond(1873687, 357000000);
    private static final ZoneId ZONE = ZoneId.of("Europe/Paris");
    private static final Clock MOCK_INSTANT = new MockInstantClock(INSTANT.toEpochMilli(), ZONE);

    //-----------------------------------------------------------------------
    @Test
    public void test_mockInstantClock_get() {
        assertEquals(MOCK_INSTANT.instant(), INSTANT);
        assertEquals(MOCK_INSTANT.millis(), INSTANT.toEpochMilli());
        assertEquals(MOCK_INSTANT.getZone(), ZONE);
    }

    @Test
    public void test_mockInstantClock_withZone() {
        ZoneId london = ZoneId.of("Europe/London");
        Clock changed = MOCK_INSTANT.withZone(london);
        assertEquals(MOCK_INSTANT.instant(), INSTANT);
        assertEquals(MOCK_INSTANT.millis(), INSTANT.toEpochMilli());
        assertEquals(changed.getZone(), london);
    }

}


text:
angular.module('metrics').factory('metricsHubService', function ($localStorage, rxnPortalConfiguration, rx) {

    var log = new rx.Subject();
    var onLoad = new rx.Subject();
    var onUpdate = new rx.Subject();

    const hub = new signalR.HubConnectionBuilder()
        .withUrl("/systemMetricsHub")
        //.rootPath(rxnPortalConfiguration.baseWebServicesUrl)
        //  .configureLogging(signalR.LogLevel.Debug)

        //    .withAutomaticReconnect([0, 0, 10000])
        //'bearer_token': ''//$localStorage.authorizationData.token
        .build();

    hub.start().then(function () {
        console.log("RxnMetrics now streaming")
    }).catch(function (err) {
        return console.error("RxnMetrics connected failed: " + err.toString());
    });

    hub.on("HistoricalData", function (allMetrics) {
        onLoad.onNext(allMetrics);
    });

    hub.on("OnUpdate", function (metric) {
        onUpdate.onNext(metric);
    });

    var metricsHubService = {
        onLoad: onLoad,
        onUpdate: onUpdate
    };

    return metricsHubService;
});


text:
@interface GradeCell () {
    Grade *grade;
}
@end

@implementation GradeCell

@synthesize iconView;
@synthesize titleLabel;
@synthesize amountLabel;

@dynamic grade;

- (Grade *)grade
{
    return grade;
}

- (void)setGrade:(Grade *)newGrade
{
    grade = newGrade;

    iconView.image = grade.icon;
    titleLabel.text = grade.title;
    amountLabel.text = [NSString stringWithFormat:@"%d", grade.amount];

    iconView.alpha = (grade.amount > 0) ? 1 : 0.4;
}

+ (GradeCell *)newInstance
{
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"GradeCell" owner:self options:nil];
    if (nibContents.count > 0) {
        GradeCell *cell = [nibContents objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

+ (NSString *)reuseIdentifier
{
    return @"GradeCell";
}

@end


text:
module.exports.operateOnIndex = function(keys, index, values) {
  values.sort();
  var range_keys = index.rangeSync(values[0], values[values.length - 1]);
  var ret = range_keys.filter(function(rec) {
    for (var i = 0; i < values.length; i++) {
      if (values[i] == rec.r) {
        return true;
      }
    }
  });
  return ret;
};


text:
#ifndef __ASM_PREFETCH_H
#define __ASM_PREFETCH_H
#define Pref_Load 0
#define Pref_Store 1
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define Pref_LoadStreamed 4
#define Pref_StoreStreamed 5
#define Pref_LoadRetained 6
#define Pref_StoreRetained 7
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define Pref_WriteBackInvalidate 25
#define Pref_PrepareForStore 30
#ifdef __ASSEMBLY__
#endif
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#endif


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

<TITLE>
atg.payment.tax (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

atg.payment.tax

Interfaces

ShippingDestination

TaxableItem

TaxProcessor

TaxRequestInfo

TaxStatus

Classes

ShippingDestinationImpl

TaxableItemImpl

TaxRequestInfoImpl


text:
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spiritsc/dynamic_accessors/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
[![Build status](https://secure.travis-ci.org/spiritsc/dynamic_accessors.png)][travis]
[![Coverage Status](https://coveralls.io/repos/spiritsc/dynamic_accessors/badge.png)](https://coveralls.io/r/spiritsc/dynamic_accessors)

[travis]: http://travis-ci.org/spiritsc/dynamic_accessors

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'dynamic_accessors'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dynamic_accessors

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
//
//  DPSpheroSettingViewController.h
//  dConnectDeviceSphero
//
//  Copyright (c) 2014 NTT DOCOMO, INC.
//  Released under the MIT license
//  http://opensource.org/licenses/mit-license.php
//

#import <UIKit/UIKit.h>
/*!
 @brief 設定画面の大元のViewController。
 */
@interface DPSpheroSettingViewController : UIPageViewController

@end


text:
	<title>Design of XSOM</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

Design of XSOM

By Kohsuke Kawaguchi

	This document describes the details you need to know to extend/maintain XSOM.

Design Goals

	The primary design goals of XSOM are:

Expose all the information defined in the schema spec

Provide additional methods that helps simplifying client applications.

	Providing mutation methods was a non-goal for this project, primarily because of the added complexity.

Building workspace

	The workspace uses Ant as the build tool. The followings are the major targets:

clean

remove the intermediate and output files.

compile

generate a parser by RelaxNGCC and compile all the source files into the bin directory.

jar

make a jar file

release

build a distribution zip file that contains everything from the source code to a binary file

src-zip

Build a zip file that contains the source code.

Architecture

	XSOM consists of roughly three parts.

	The first part is the public interface, which is defined in the com.sun.xml.xsom package. The entire functionality of XSOM is exposed via this interface. This interface is derived from a draft document submitted to W3C by some WG members.

	The second part is the implementation of these interfaces, the com.sun.xml.xsom.impl package. These code are all hand-written.

	The third part is a parser that reads XML representation of XML Schema and builds XSOM nodes accordingly. The package is com.sun.xml.xsom.parser. This part of the code is mostly generated by RelaxNGCC.

Implementation Details

	Most of the implementation classes are fairly simple. Probably the only one interesting piece of code is the Ref class, which is a reference to other schema components.

	The Ref class itself is just a place hodler and this class defined a series of inner interfaces that are specialized to hold a reference to different kinds of schema components.

	The sole purpose of this indirection layer is to support forward references during a parsing of the XML representation.

	A typical reference interface would look like this:

public static interface Term {
    /** Obtains a reference as a term. */
    XSTerm getTerm();
}

	In case this indirection is unnecessary, all implementation classes of XSTerm implements this Ref.Term interface. This applies to all the other types of the Ref interface. Therefore, whereever a reference is necessary, you can stimply pass a real object. In other words, a direct reference (XS***Impl) can be always treated as an indirect reference (Ref.***).

	Implementations for forward references are placed in the com.sun.xml.xsom.impl.parser.DelayedRef class. The detail will be discussed later.

Parser

	The following collaboration diagram shows various objects that participate in a parsing process.

	XSOMParser is the only publicly visible component in this picture. This class also keeps references to vairous other objects that are necessary to parse schemas. This includes an error handler, the root SchemaSet object, an entity resolver, etc.

	Whenever the parse method is called, it will create a new NGCCRuntimeEx and configure XMLReader so that a schema file is parsed into this NGCCRuntimeEx instance.

	NGCCRuntimeEx derives from NGCCRuntime, which is a class generated by RelaxNGCC. This object will use other RelaxNGCC-generated classes and parse a document and constructs a XSOM object graph appropriately.

	When a new XML document is referenced by an import or include statement, a new set of NGCCRuntimeEx is set up to parse that document. One NGCCRuntimeEx can only parse one XML document.

Forward references and back-patching

	Since we use SAX to parse schemas, the referenced schema component is often unavailable when we hit a reference. Because of this, when we see a reference, we create a "delayed" reference that keeps the name of the referenced component.

	Note that because of the way XML Schema <redefine> works, all the references by name must be lazily bound even if the component is already defined.

	All these "delayed" references are remembered and tracked by XSOMParser. When the client calls the XSOMParser.getResult method, XSOMParser will make sure that they resolve to a schema component correctly.
	"Delayed" references are available in the DelayedRef class.

RelaxNGCC

	The actual parser is generated by RelaxNGCC from xsom/src/*.rng files. xmlschema.rng is the entry point and all the other files are referenced from this file. For more information about RelaxNGCC, goto here. Or just contact me (as I'm one of the developers of RelaxNGCC.)


text:
set -euo pipefail

## Adapted from https://github.com/nk412/optparse

options_usage=""
options_contractions=""
options_defaults=""
options_process=""
options_arguments_string=""

invalid_options() {
  echo "OPTPARSE: ERROR: ${1}" && exit 1
}

define_option() {
  if [ $# -lt 3 ]; then invalid_options "define_option <short> <long> <variable> [<desc>] [<default>] [<value>]"; fi

  for arg in $(seq 1 $#) ; do
    local option="$(eval "echo \$${arg}")"
    local key="$(echo ${option} | awk -F "=" '{print $1}')";
    local value="$(echo ${option} | awk -F "=" '{print $2}')";

    #essentials: shortname, longname, description
    if [ "$key" = "desc" ]; then local desc="$value"
    elif [ "$key" = "default" ]; then local default="$value"
    elif [ "$key" = "variable" ]; then local variable="$value"
    elif [ "$key" = "value" ]; then local val="$value"
    elif [ "$key" = "short" ]; then
      local shortname="$value"
      local short="-${shortname}"
      if [ ${#shortname} -ne 1 ]; then invalid_options "short name expected to be one character long"; fi
    elif [ "$key" = "long" ]; then
      local longname="$value"
      local long="--${longname}"
      if [ ${#longname} -lt 2 ]; then invalid_options "long name expected to be atleast one character long"; fi
    fi
  done

  local default="${default:-}"
  local val="${val:-}"

  if [ -z "${variable}" ]; then invalid_options "You must give a variable for option: ($short/$long)"; fi
  if [ -z "${val}" ]; then local val="\$OPTARG"; fi

  # build OPTIONS and help
  options_usage="${options_usage}#NL ${short},$(printf "%-25s %s" "${long}" "${desc}")"
  if [ -n "${default}" ]; then options_usage="${options_usage} [default:$default]"; fi

  options_contractions="${options_contractions}#NL#TB#TB${long})#NL#TB#TB#TBparams=\"\$params ${short}\";;"
  if [ -n "${default}" ]; then options_defaults="${options_defaults}#NL${variable}=${default}"; fi

  options_arguments_string="${options_arguments_string}${shortname}"
  if [ "${val}" = "\$OPTARG" ]; then options_arguments_string="${options_arguments_string}:"; fi

  options_process="${options_process}#NL  ${shortname}) ${variable}=\"$val\";;"
}

build_options() {
  local build_file="$(mktemp -u)"

  # Building getopts header here

  # Function usage
  cat << EOF > $build_file
  function usage(){
    cat << XXX
usage: \$0 [OPTIONS]

OPTIONS:
$options_usage

-? --help                    Display this message
XXX
  }

  # Contract long options into short options
  params=""
  while [ \$# -ne 0 ]; do
    param="\$1"
    shift

    case "\$param" in
      $options_contractions
      "-?"|--help)
      usage
      exit 0;;
    *)
      if [[ "\$param" == --* ]]; then
        echo -e "Unrecognized long option: \$param"
        usage
        exit 1
      fi
      params="\$params \"\$param\"";;
  esac
done

eval set -- "\$params"

# Set default variable values
$options_defaults

# Process using getopts
while getopts "$options_arguments_string" option; do
  case \$option in
    $options_process
    :) echo "Option - \$OPTARG requires an argument"; exit 1;;
    *) usage; exit 1;;
  esac
done

# Clean up after self
rm $build_file

EOF

  if osx; then
    sed -i "" 's/#NL/\'$'\n/g' $build_file
    sed -i "" 's/#TB/\'$'\t/g' $build_file
  else
    local -A o=( ['#NL']='\n' ['#TB']='\t' )
    for i in "${!o[@]}"; do sed -i "s/${i}/${o[$i]}/g" $build_file; done
  fi

  # Unset global variables
  unset options_usage
  unset options_process
  unset options_arguments_string
  unset options_defaults
  unset options_contractions

  # Return file name to parent
  echo "${build_file}"
}


text:
'use strict';

var _jsx2 = require('babel-runtime/helpers/jsx');

var _jsx3 = _interopRequireDefault(_jsx2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _enzyme = require('enzyme');

var _manager = require('./manager');

var _manager2 = _interopRequireDefault(_manager);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _mockContext = function _mockContext(slide, routeParams) {
  return {
    styles: {
      global: {
        body: []
      },
      controls: {},
      progress: {
        pacman: []
      }
    },
    store: {
      getState: function getState() {
        return {
          route: {
            params: routeParams,
            slide: slide
          },
          style: {
            globalStyleSet: []
          }
        };
      },
      dispatch: function dispatch() {},
      subscribe: function subscribe() {}
    }
  };
};

var _ref = (0, _jsx3.default)('div', {}, void 0, 'Slide Content');

var MockSlide = function (_Component) {
  (0, _inherits3.default)(MockSlide, _Component);

  function MockSlide() {
    (0, _classCallCheck3.default)(this, MockSlide);
    return (0, _possibleConstructorReturn3.default)(this, _Component.apply(this, arguments));
  }

  MockSlide.prototype.render = function render() {
    return _ref;
  };

  return MockSlide;
}(_react.Component);

var MockSlideSet = function (_Component2) {
  (0, _inherits3.default)(MockSlideSet, _Component2);

  function MockSlideSet() {
    (0, _classCallCheck3.default)(this, MockSlideSet);
    return (0, _possibleConstructorReturn3.default)(this, _Component2.apply(this, arguments));
  }

  MockSlideSet.prototype.render = function render() {
    return (0, _jsx3.default)('div', {}, void 0, this.props.children);
  };

  return MockSlideSet;
}(_react.Component);

MockSlideSet.defaultProps = {
  hasSlideChildren: true
};

var _mockChildContext = function _mockChildContext() {
  return { styles: function styles() {} };
};

var _ref2 = (0, _jsx3.default)(MockSlide, {});

var _ref3 = (0, _jsx3.default)(MockSlide, {});

var _ref4 = (0, _jsx3.default)(_manager2.default, {}, void 0, (0, _jsx3.default)(MockSlide, {}), (0, _jsx3.default)(MockSlide, {}));

var _ref5 = (0, _jsx3.default)(_manager2.default, {}, void 0, (0, _jsx3.default)(MockSlide, {}), (0, _jsx3.default)(MockSlide, {}));

var _ref6 = (0, _jsx3.default)(_manager2.default, {}, void 0, (0, _jsx3.default)(MockSlide, {}), (0, _jsx3.default)(MockSlideSet, {}, void 0, (0, _jsx3.default)(MockSlide, {}), (0, _jsx3.default)(MockSlide, {})));

describe('<Manager />', function () {
  test('should render correctly.', function () {
    var wrapper = (0, _enzyme.mount)((0, _jsx3.default)(_manager2.default, {
      transition: ['zoom', 'slide'],
      transitionDuration: 500
    }, void 0, _ref2, _ref3), { context: _mockContext(0, []), childContextTypes: _mockChildContext() });
    expect(wrapper).toMatchSnapshot();
  });

  test('should render the export configuration when specified.', function () {
    var wrapper = (0, _enzyme.mount)(_ref4, {
      context: _mockContext(0, ['export']),
      childContextTypes: _mockChildContext()
    });
    expect(wrapper).toMatchSnapshot();
  });

  test('should render the overview configuration when specified.', function () {
    var wrapper = (0, _enzyme.mount)(_ref5, {
      context: _mockContext(0, ['overview']),
      childContextTypes: _mockChildContext()
    });
    expect(wrapper).toMatchSnapshot();
  });

  test('should render with slideset slides', function () {
    var wrapper = (0, _enzyme.mount)(_ref6, { context: _mockContext(1, []), childContextTypes: _mockChildContext() });
    expect(wrapper).toMatchSnapshot();
  });
});


text:
import { GridPanel } from "../../gridPanel/gridPanel";
import { RowNode } from "../../entities/rowNode";
import { BeanStub } from "../../context/beanStub";
export declare class AutoHeightCalculator extends BeanStub {
    private beans;
    private $scope;
    private columnController;
    private rowCssClassCalculator;
    $compile: any;
    private gridPanel;
    registerGridComp(gridPanel: GridPanel): void;
    getPreferredHeightForRow(rowNode: RowNode): number;
    private addInRowCssClasses;
}


text:
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
 <title>Thermal Expansion</title>
 <meta name="description" content="">
 <meta name="viewport" content="width=device-width">
 <link href="Beta10.css" type="text/css" rel="stylesheet">

Standalone thermal expansion calculator.

    <form id="calcForm" class="form-horizontal">

Recipe

Mouseover text for input cell boxes

            Volume

              <input type="text" class="input-mini" id="Volume" name="Volume" value="7.5" required>Gal

            Current Temperature

              <input type="text" class="input-mini" id="Temp" name="Temp" value="120" required> F

            Final Temperature

              <input type="text" class="input-mini" id="FinalTemp" name="FinalTemp" value="155" required> F

General Results

            Room temp volume

              7.49  gal

            Volume at boil

              7.82  gal

            Volume at Final Temp

              7.65  gal

    </form>

Created by Pricelessbrewing

	  Mash Calculator

Credits

   Formulas based on thermal expansion for water at varying temperature with dataset restricted to 70F to 212F for greatest accuracy for brewers.


text:
package konto

import org.junit.Assert._
import org.junit.Test

/**JUnit4-Testtreiber für die zu erstellende Konto-Klassenhierarchie sowie das Konto-Begleitobjekt.
 * @author Christoph Knabe 2014-10-28*/
//Für Eclipse müssen Sie in der Datei .classpath hinter dem Scala- und Java-Container folgenden ergänzen:
//   <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
class KontoTest {

  @Test def buchungen(){
    //Expliziter Aufruf der Fabrikmethode apply aus dem Begleitobjekt Konto:
    val knabeKonto = Konto.apply(new Person("Knabe"))
    val schmidtKonto = Konto.apply(new Person("Schmidt"))
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(0, schmidtKonto.saldoCt)

    knabeKonto.einzahlen(10000)
    assertEquals(10000, knabeKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, 3333)
    assertEquals(6667, knabeKonto.saldoCt)
    assertEquals(3333, schmidtKonto.saldoCt)

    //Einzahlungen müssen positiv sein!
    def verboteneEinzahlungenPruefen(konto: Konto, betraege: Long*){
      for(betrag<-betraege) _exceptionExpected(konto.einzahlen(betrag))
    }
    verboteneEinzahlungenPruefen(knabeKonto, 0, -1, -999)
    verboteneEinzahlungenPruefen(schmidtKonto, 0, -1, -999)

    //Nur positive Beträge dürfen überwiesen werden!
    def verboteneUeberweisungenPruefen(betraege: Long*){
      for(betrag<-betraege) _exceptionExpected(knabeKonto.ueberweisen(schmidtKonto, betrag))
    }
    verboteneUeberweisungenPruefen(0, -1, -999)
    verboteneUeberweisungenPruefen(0, -1, -999)
  }

  @Test def sparKontoBuchungen(){
    //Impliziter Aufruf ohne Methodenbezeichner der Fabrikmethoden apply aus dem Begleitobjekt Konto:
    val knabeKonto = Konto(new Person("Knabe"), 0.02f) //SparKonto mit Guthabenzinssatz
    val schmidtKonto = Konto(new Person("Schmidt")) //Einfaches Konto ohne Zinssatz und Kreditrahmen
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(0, schmidtKonto.saldoCt)

    knabeKonto.einzahlen(10000)
    assertEquals(10000, knabeKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, 3333)
    assertEquals(6667, knabeKonto.saldoCt)
    assertEquals(3333, schmidtKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, 6667)
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(10000, schmidtKonto.saldoCt)

    //Das knabeKonto ist jetzt leer. Da es ein SparKonto ist, darf nicht weiter darüber verfügt werden!
    try{
      knabeKonto.ueberweisen(schmidtKonto, 1)
      fail("expected: IllegalArgumentException")
    }catch{
      case expected: IllegalArgumentException =>
    }
    //Dieser Überweisungsversuch darf nichts an den Salden geändert haben:
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(10000, schmidtKonto.saldoCt)
  }

  @Test def giroKontoBuchungen(){
    val kreditrahmen = 50000
    val knabeKonto = Konto(new Person("Knabe"), kreditrahmen) //GiroKonto mit Kreditrahmen
    val schmidtKonto = Konto(new Person("Schmidt"), 0.02f) //SparKonto mit Guthabenzinssatz
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(0, schmidtKonto.saldoCt)

    knabeKonto.einzahlen(10000)
    assertEquals(10000, knabeKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, 3333)
    assertEquals(6667, knabeKonto.saldoCt)
    assertEquals(3333, schmidtKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, 6667)
    assertEquals(0, knabeKonto.saldoCt)
    assertEquals(10000, schmidtKonto.saldoCt)

    knabeKonto.ueberweisen(schmidtKonto, kreditrahmen)
    assertEquals(-kreditrahmen, knabeKonto.saldoCt)
    assertEquals(60000, schmidtKonto.saldoCt)

    //Das knabeKonto hat jetzt den Kreditrahmen erschöpft. Es darf nicht weiter darüber verfügt werden!
    try{
      knabeKonto.ueberweisen(schmidtKonto, 1)
      fail("expected: IllegalArgumentException")
    }catch{
      case expected: IllegalArgumentException =>
    }
    //Dieser Überweisungsversuch darf nichts an den Salden geändert haben:
    assertEquals(-50000, knabeKonto.saldoCt)
    assertEquals(60000, schmidtKonto.saldoCt)
  }

  @Test def sparzinsen(){
    val sparKonto = Konto(new Person("Knabe"), 0.03f) //SparKonto mit Guthabenzinssatz
    sparKonto.einzahlen(100000)
    assertEquals(100000, sparKonto.saldoCt)

    {
      val result = sparKonto.verzinsen(360)
	  assertEquals(3000, result)
      assertEquals(103000, sparKonto.saldoCt)
    }
    {
	  val result = sparKonto.verzinsen(10) //Kaufmännisch gelten 360 Tage als ein Jahr
      assertEquals(86, result)
      assertEquals(103086, sparKonto.saldoCt)
    }
  }

  @Test def kreditzinsen(){
    val giroKonto = Konto(new Person("Knabe"), 10000) //GiroKonto mit Kreditrahmen
    giroKonto.einzahlen(100000)
    assertEquals(100000, giroKonto.saldoCt)

    {
      //Guthaben werden auf einem Girokonto nicht verzinst:
      val result = giroKonto.verzinsen(360) //Kaufmännisch gelten 360 Tage als ein Jahr
	    assertEquals(0, result)
      assertEquals(100000, giroKonto.saldoCt)
    }

    val zielKonto = Konto(new Person("Knabe"))
    giroKonto.ueberweisen(zielKonto, 110000)
    assertEquals(-10000, giroKonto.saldoCt)
    Konto.kreditzinssatzPA = 0.10 // 10% per annum

    {
      val result = giroKonto.verzinsen(360) //Kaufmännisch gelten 360 Tage als ein Jahr
      assertEquals(-1000, result)
      assertEquals(-11000, giroKonto.saldoCt)
    }
    {
      val result = giroKonto.verzinsen(10) //Kaufmännisch gelten 360 Tage als ein Jahr
      assertEquals(-31, result)
      assertEquals(-11031, giroKonto.saldoCt)
    }
  }

  /**Wirft einen AssertionError, wenn bei der Ausführung von action
   *  keine IllegalArgumentException geworfen wird.*/
  private def _exceptionExpected(action: => Unit){
    try{
	  action
	  fail("expected: IllegalArgumentException")
	}catch{
	  case expected: IllegalArgumentException =>
	}
  }

}


text:
This project creates a working snap of youtube-dl.

To get this done, we need to do the following:
 - Build from current git

## Current state

Working features:
 - Video downloading

Known issues:
  - The home plug needs to be connected manually after snap install with
    "sudo snap connect youtube-dl:home ubuntu-core:home"
  - ffprobe is not found when using `-x --audioformat mp3` option.
    Fix proposed in pull request


text:
<?php
/**
 * @package Guzzle PHP <http://www.guzzlephp.org>
 * @license See the LICENSE file that was distributed with this source code.
 */

namespace Guzzle\Aws\S3\Command\Object;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Aws\S3\Command\AbstractS3BucketCommand;

/**
 * Delete an object from a bucket
 *
 * @guzzle key doc="Key of the object to delete" required="true"
 * @guzzle bucket doc="Bucket that contains the object" required="true"
 * @guzzle mfa doc="MFA token for deletion"
 * @guzzle version_id doc="Version ID of the object to delete"
 *
 * @author Michael Dowling <michael@guzzlephp.org>
 */
class DeleteObject extends AbstractS3BucketCommand
{
    /**
     * {@inheritdoc}
     */
    protected function build()
    {
        $this->request = $this->client->getS3Request(RequestInterface::DELETE, $this->get('bucket'), $this->get('key'));

        if ($this->get('version_id')) {
            $this->request->getQuery()->set('versionId', $this->get('version_id'));
        }

        if ($this->get('mfa')) {
            $this->request->setHeader('x-amz-mfa', $this->get('mfa'));
        }
    }

    /**
     * Set the key of the object
     *
     * @param string $key The key or name of the object
     *
     * @return DeleteObject
     */
    public function setKey($key)
    {
        return $this->set('key', $key);
    }

    /**
     * Set a MFA token to authenticate deleting the object.  Only set this
     * parameter if MFA delete is enabled on the bucket.
     *
     * The passed $mfa value is the concatenation of your authentication
     * device's serial number, a space, and the authentication code displayed
     * on it.
     *
     * @param string $mfa
     *
     * @return DeleteObject
     */
    public function setMfa($mfa)
    {
        return $this->set('mfa', $mfa);
    }

    /**
     * Set the version ID of the object to delete.  Only set this parameter
     * is bucket versioning is enabled on the bucket
     *
     * @param string $versionId
     *
     * @return DeleteObject
     */
    public function setVersionId($versionId)
    {
        return $this->set('version_id', $versionId);
    }
}


text:
package com.amazonaws.services.devicefarm.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.devicefarm.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RunMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RunMarshaller {

    private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("arn").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("type").build();
    private static final MarshallingInfo<String> PLATFORM_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("platform").build();
    private static final MarshallingInfo<java.util.Date> CREATED_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("created").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();
    private static final MarshallingInfo<String> RESULT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("result").build();
    private static final MarshallingInfo<java.util.Date> STARTED_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("started").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<java.util.Date> STOPPED_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("stopped").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<StructuredPojo> COUNTERS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("counters").build();
    private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("message").build();
    private static final MarshallingInfo<Integer> TOTALJOBS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("totalJobs").build();
    private static final MarshallingInfo<Integer> COMPLETEDJOBS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("completedJobs").build();
    private static final MarshallingInfo<String> BILLINGMETHOD_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("billingMethod").build();
    private static final MarshallingInfo<StructuredPojo> DEVICEMINUTES_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deviceMinutes").build();
    private static final MarshallingInfo<StructuredPojo> NETWORKPROFILE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("networkProfile").build();
    private static final MarshallingInfo<String> PARSINGRESULTURL_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("parsingResultUrl").build();
    private static final MarshallingInfo<String> RESULTCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("resultCode").build();
    private static final MarshallingInfo<Integer> SEED_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("seed").build();
    private static final MarshallingInfo<String> APPUPLOAD_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("appUpload").build();
    private static final MarshallingInfo<Integer> EVENTCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("eventCount").build();
    private static final MarshallingInfo<Integer> JOBTIMEOUTMINUTES_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("jobTimeoutMinutes").build();
    private static final MarshallingInfo<String> DEVICEPOOLARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("devicePoolArn").build();
    private static final MarshallingInfo<String> LOCALE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("locale").build();
    private static final MarshallingInfo<StructuredPojo> RADIOS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("radios").build();
    private static final MarshallingInfo<StructuredPojo> LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("location").build();
    private static final MarshallingInfo<StructuredPojo> CUSTOMERARTIFACTPATHS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("customerArtifactPaths").build();
    private static final MarshallingInfo<String> WEBURL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("webUrl").build();
    private static final MarshallingInfo<Boolean> SKIPAPPRESIGN_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("skipAppResign").build();
    private static final MarshallingInfo<String> TESTSPECARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("testSpecArn").build();
    private static final MarshallingInfo<StructuredPojo> DEVICESELECTIONRESULT_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deviceSelectionResult").build();
    private static final MarshallingInfo<StructuredPojo> VPCCONFIG_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("vpcConfig").build();

    private static final RunMarshaller instance = new RunMarshaller();

    public static RunMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Run run, ProtocolMarshaller protocolMarshaller) {

        if (run == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(run.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(run.getName(), NAME_BINDING);
            protocolMarshaller.marshall(run.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(run.getPlatform(), PLATFORM_BINDING);
            protocolMarshaller.marshall(run.getCreated(), CREATED_BINDING);
            protocolMarshaller.marshall(run.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(run.getResult(), RESULT_BINDING);
            protocolMarshaller.marshall(run.getStarted(), STARTED_BINDING);
            protocolMarshaller.marshall(run.getStopped(), STOPPED_BINDING);
            protocolMarshaller.marshall(run.getCounters(), COUNTERS_BINDING);
            protocolMarshaller.marshall(run.getMessage(), MESSAGE_BINDING);
            protocolMarshaller.marshall(run.getTotalJobs(), TOTALJOBS_BINDING);
            protocolMarshaller.marshall(run.getCompletedJobs(), COMPLETEDJOBS_BINDING);
            protocolMarshaller.marshall(run.getBillingMethod(), BILLINGMETHOD_BINDING);
            protocolMarshaller.marshall(run.getDeviceMinutes(), DEVICEMINUTES_BINDING);
            protocolMarshaller.marshall(run.getNetworkProfile(), NETWORKPROFILE_BINDING);
            protocolMarshaller.marshall(run.getParsingResultUrl(), PARSINGRESULTURL_BINDING);
            protocolMarshaller.marshall(run.getResultCode(), RESULTCODE_BINDING);
            protocolMarshaller.marshall(run.getSeed(), SEED_BINDING);
            protocolMarshaller.marshall(run.getAppUpload(), APPUPLOAD_BINDING);
            protocolMarshaller.marshall(run.getEventCount(), EVENTCOUNT_BINDING);
            protocolMarshaller.marshall(run.getJobTimeoutMinutes(), JOBTIMEOUTMINUTES_BINDING);
            protocolMarshaller.marshall(run.getDevicePoolArn(), DEVICEPOOLARN_BINDING);
            protocolMarshaller.marshall(run.getLocale(), LOCALE_BINDING);
            protocolMarshaller.marshall(run.getRadios(), RADIOS_BINDING);
            protocolMarshaller.marshall(run.getLocation(), LOCATION_BINDING);
            protocolMarshaller.marshall(run.getCustomerArtifactPaths(), CUSTOMERARTIFACTPATHS_BINDING);
            protocolMarshaller.marshall(run.getWebUrl(), WEBURL_BINDING);
            protocolMarshaller.marshall(run.getSkipAppResign(), SKIPAPPRESIGN_BINDING);
            protocolMarshaller.marshall(run.getTestSpecArn(), TESTSPECARN_BINDING);
            protocolMarshaller.marshall(run.getDeviceSelectionResult(), DEVICESELECTIONRESULT_BINDING);
            protocolMarshaller.marshall(run.getVpcConfig(), VPCCONFIG_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
namespace v8 {
namespace internal {

// Memory barriers on ARM are funky, but the kernel is here to help:
//
// * ARMv5 didn't support SMP, there is no memory barrier instruction at
//   all on this architecture, or when targeting its machine code.
//
// * Some ARMv6 CPUs support SMP. A full memory barrier can be produced by
//   writing a random value to a very specific coprocessor register.
//
// * On ARMv7, the "dmb" instruction is used to perform a full memory
//   barrier (though writing to the co-processor will still work).
//   However, on single core devices (e.g. Nexus One, or Nexus S),
//   this instruction will take up to 200 ns, which is huge, even though
//   it's completely un-needed on these devices.
//
// * There is no easy way to determine at runtime if the device is
//   single or multi-core. However, the kernel provides a useful helper
//   function at a fixed memory address (0xffff0fa0), which will always
//   perform a memory barrier in the most efficient way. I.e. on single
//   core devices, this is an empty function that exits immediately.
//   On multi-core devices, it implements a full memory barrier.
//
// * This source could be compiled to ARMv5 machine code that runs on a
//   multi-core ARMv6 or ARMv7 device. In this case, memory barriers
//   are needed for correct execution. Always call the kernel helper, even
//   when targeting ARMv5TE.
//

inline void MemoryBarrier() {
#if defined(__linux__) || defined(__ANDROID__)
  // Note: This is a function call, which is also an implicit compiler barrier.
  typedef void (*KernelMemoryBarrierFunc)();
  ((KernelMemoryBarrierFunc)0xffff0fa0)();
#elif defined(__QNXNTO__)
  __cpu_membarrier();
#else
#error MemoryBarrier() is not implemented on this platform.
#endif
}

// An ARM toolchain would only define one of these depending on which
// variant of the target architecture is being used. This tests against
// any known ARMv6 or ARMv7 variant, where it is possible to directly
// use ldrex/strex instructions to implement fast atomic operations.
#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \
    defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || \
    defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \
    defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \
    defined(__ARM_ARCH_6KZ__) || defined(__ARM_ARCH_6T2__)

inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
                                         Atomic32 old_value,
                                         Atomic32 new_value) {
  Atomic32 prev_value;
  int reloop;
  do {
    // The following is equivalent to:
    //
    //   prev_value = LDREX(ptr)
    //   reloop = 0
    //   if (prev_value != old_value)
    //      reloop = STREX(ptr, new_value)
    __asm__ __volatile__("    ldrex %0, [%3]\n"
                         "    mov %1, #0\n"
                         "    cmp %0, %4\n"
#ifdef __thumb2__
                         "    it eq\n"
#endif
                         "    strexeq %1, %5, [%3]\n"
                         : "=&r"(prev_value), "=&r"(reloop), "+m"(*ptr)
                         : "r"(ptr), "r"(old_value), "r"(new_value)
                         : "cc", "memory");
  } while (reloop != 0);
  return prev_value;
}

inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
                                       Atomic32 old_value,
                                       Atomic32 new_value) {
  Atomic32 result = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
  MemoryBarrier();
  return result;
}

inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
                                       Atomic32 old_value,
                                       Atomic32 new_value) {
  MemoryBarrier();
  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
}

inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
                                          Atomic32 increment) {
  Atomic32 value;
  int reloop;
  do {
    // Equivalent to:
    //
    //  value = LDREX(ptr)
    //  value += increment
    //  reloop = STREX(ptr, value)
    //
    __asm__ __volatile__("    ldrex %0, [%3]\n"
                         "    add %0, %0, %4\n"
                         "    strex %1, %0, [%3]\n"
                         : "=&r"(value), "=&r"(reloop), "+m"(*ptr)
                         : "r"(ptr), "r"(increment)
                         : "cc", "memory");
  } while (reloop);
  return value;
}

inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
                                        Atomic32 increment) {
  // TODO(digit): Investigate if it's possible to implement this with
  // a single MemoryBarrier() operation between the LDREX and STREX.
  // See http://crbug.com/246514
  MemoryBarrier();
  Atomic32 result = NoBarrier_AtomicIncrement(ptr, increment);
  MemoryBarrier();
  return result;
}

inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
                                         Atomic32 new_value) {
  Atomic32 old_value;
  int reloop;
  do {
    // old_value = LDREX(ptr)
    // reloop = STREX(ptr, new_value)
    __asm__ __volatile__("   ldrex %0, [%3]\n"
                         "   strex %1, %4, [%3]\n"
                         : "=&r"(old_value), "=&r"(reloop), "+m"(*ptr)
                         : "r"(ptr), "r"(new_value)
                         : "cc", "memory");
  } while (reloop != 0);
  return old_value;
}

// This tests against any known ARMv5 variant.
#elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \
      defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__)

// The kernel also provides a helper function to perform an atomic
// compare-and-swap operation at the hard-wired address 0xffff0fc0.
// On ARMv5, this is implemented by a special code path that the kernel
// detects and treats specially when thread pre-emption happens.
// On ARMv6 and higher, it uses LDREX/STREX instructions instead.
//
// Note that this always perform a full memory barrier, there is no
// need to add calls MemoryBarrier() before or after it. It also
// returns 0 on success, and 1 on exit.
//
// Available and reliable since Linux 2.6.24. Both Android and ChromeOS
// use newer kernel revisions, so this should not be a concern.
namespace {

inline int LinuxKernelCmpxchg(Atomic32 old_value,
                              Atomic32 new_value,
                              volatile Atomic32* ptr) {
  typedef int (*KernelCmpxchgFunc)(Atomic32, Atomic32, volatile Atomic32*);
  return ((KernelCmpxchgFunc)0xffff0fc0)(old_value, new_value, ptr);
}

}  // namespace

inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
                                         Atomic32 old_value,
                                         Atomic32 new_value) {
  Atomic32 prev_value;
  for (;;) {
    prev_value = *ptr;
    if (prev_value != old_value)
      return prev_value;
    if (!LinuxKernelCmpxchg(old_value, new_value, ptr))
      return old_value;
  }
}

inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
                                         Atomic32 new_value) {
  Atomic32 old_value;
  do {
    old_value = *ptr;
  } while (LinuxKernelCmpxchg(old_value, new_value, ptr));
  return old_value;
}

inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
                                          Atomic32 increment) {
  return Barrier_AtomicIncrement(ptr, increment);
}

inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
                                        Atomic32 increment) {
  for (;;) {
    // Atomic exchange the old value with an incremented one.
    Atomic32 old_value = *ptr;
    Atomic32 new_value = old_value + increment;
    if (!LinuxKernelCmpxchg(old_value, new_value, ptr)) {
      // The exchange took place as expected.
      return new_value;
    }
    // Otherwise, *ptr changed mid-loop and we need to retry.
  }
}

inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
                                       Atomic32 old_value,
                                       Atomic32 new_value) {
  Atomic32 prev_value;
  for (;;) {
    prev_value = *ptr;
    if (prev_value != old_value) {
      // Always ensure acquire semantics.
      MemoryBarrier();
      return prev_value;
    }
    if (!LinuxKernelCmpxchg(old_value, new_value, ptr))
      return old_value;
  }
}

inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
                                       Atomic32 old_value,
                                       Atomic32 new_value) {
  // This could be implemented as:
  //    MemoryBarrier();
  //    return NoBarrier_CompareAndSwap();
  //
  // But would use 3 barriers per succesful CAS. To save performance,
  // use Acquire_CompareAndSwap(). Its implementation guarantees that:
  // - A succesful swap uses only 2 barriers (in the kernel helper).
  // - An early return due to (prev_value != old_value) performs
  //   a memory barrier with no store, which is equivalent to the
  //   generic implementation above.
  return Acquire_CompareAndSwap(ptr, old_value, new_value);
}

#else
#  error "Your CPU's ARM architecture is not supported yet"
#endif

// NOTE: Atomicity of the following load and store operations is only
// guaranteed in case of 32-bit alignement of |ptr| values.

inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
  *ptr = value;
}

inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
  *ptr = value;
  MemoryBarrier();
}

inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
  MemoryBarrier();
  *ptr = value;
}

inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; }

inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
  Atomic32 value = *ptr;
  MemoryBarrier();
  return value;
}

inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
  MemoryBarrier();
  return *ptr;
}

} }  // namespace v8::internal

#endif  // V8_ATOMICOPS_INTERNALS_ARM_GCC_H_


text:
package com.scarabsoft.jrest;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

final class DefaultHttpClientFactory implements HttpClientFactory {
    @Override
    public HttpClient get() {
        return HttpClientBuilder.create().build();
    }
}


text:
"""quick and dirty test"""

import unittest
import subprocess
import os

class MyTest(unittest.TestCase):
    """RNA Alignment test"""
    def test_rna_align_find_seq_in_alignment(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_align_find_seq_in_alignment.py -a test_data/RF00167.stockholm.sto -f test_data/xx.fa"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

    def test_rna_align_find_core(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_align_find_core.py test_data/RF00167.stockholm.sto"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

    def test_rna_align_seq_to_alignment(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_align_seq_to_alignment.py -f test_data/4lvv_cmalign.txt -a test_data/RF01831.stockholm.sto"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

    def test_rna_align_seq_to_alignment_2(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_align_seq_to_alignment.py -s test_data/4lvv.seq -a test_data/RF01831.stockholm.sto -m test_data/RF01831.cm"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

    def test_rna_align_get_ss_from_alignment(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_align_get_ss_from_alignment.py test_data/ade.fa"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

    def test_rna_alignment(self):
        print('----------------------------------------------------------------------')
        cmd = "./rna_alignment.py"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)
    def test_random_assignment_of_nucleotides(self):
        print('----------------------------------------------------------------------')
        cmd = "python random_assignment_of_nucleotides.py --alignfn test_data/aln1.fasta"
        print(cmd)
        code = os.system(cmd)
        self.assertEqual(code, 0)

if __name__ == '__main__':
    unittest.main()


text:
package models;

/**
 * @author Steve Chaloner (steve@objectify.be)
 */
public class Foo
{
    public String x;

    public Boolean y;

    public Integer z;
}


text:
'use strict';

/**
 * Module dependencies.
 */

var config = require('../config');
var models = require('../models');
var Total = models.Total;

var TOTAL_MODULE_SQL = 'SELECT count(distinct(name)) AS count FROM module;';
var TOTAL_VERSION_SQL = 'SELECT count(name) AS count FROM module;';
var TOTAL_USER_SQL = 'SELECT count(name) AS count FROM user;';
if (config.database.dialect === 'postgres') {
  // pg not allow table name as 'user'
  TOTAL_USER_SQL = 'SELECT count(name) AS count FROM public.user;';
}

exports.get = function* () {
  // var DB_SIZE_SQL = 'SELECT TABLE_NAME AS name, data_length, index_length \
  //   FROM information_schema.tables WHERE TABLE_SCHEMA = ? \
  //   GROUP BY TABLE_NAME \
  //   ORDER BY data_length DESC \
  //   LIMIT 0, 200';
  var rs = yield [
    // models.query(DB_SIZE_SQL, [config.db]),
    models.queryOne(TOTAL_MODULE_SQL),
    models.queryOne(TOTAL_VERSION_SQL),
    models.queryOne(TOTAL_USER_SQL),
    exports.getTotalInfo(),
  ];

  // var sizes = rs[0];
  var mc = rs[0];
  var vc = rs[1];
  var uc = rs[2];
  var info = rs[3] || {};

  if (typeof info.module_delete === 'string') {
    info.module_delete = Number(info.module_delete);
  }

  var total = {
    data_tables: {},
    disk_size: 0,
    data_size: 0,
    index_size: 0,
    disk_format_version: 0,
    committed_update_seq: 0,
    update_seq: 0,
    purge_seq: 0,
    compact_running: false,
    doc_count: mc.count,
    doc_del_count: info.module_delete || 0,
    doc_version_count: vc.count,
    user_count: uc.count,
    store_engine: config.database.dialect,
    sync_status: info.sync_status,
    need_sync_num: info.need_sync_num || 0,
    success_sync_num: info.success_sync_num || 0,
    fail_sync_num: info.fail_sync_num || 0,
    left_sync_num: info.left_sync_num || 0,
    last_sync_time: info.last_sync_time || 0,
    last_exist_sync_time: info.last_exist_sync_time || 0,
    last_sync_module: info.last_sync_module || '',
  };

  // for (var i = 0; i < sizes.length; i++) {
  //   var row = sizes[i];
  //   total.data_tables[row.name] = {
  //     data_size: row.data_length,
  //     index_size: row.index_length,
  //   };
  //   total.data_size += row.data_length;
  //   total.index_size += row.index_length;
  // }

  total.disk_size = total.data_size + total.index_size;

  return total;
};

exports.getTotalInfo = function* () {
  var row = yield Total.find({
    where: {
      name: 'total'
    }
  });
  if (row && typeof row.module_delete === 'string') {
    row.module_delete = Number(row.module_delete);
  }
  return row;
};

exports.plusDeleteModule = function* () {
  var sql = 'UPDATE total SET module_delete=module_delete+1 WHERE name=\'total\'';
  return yield* models.query(sql);
};

exports.setLastSyncTime = function* (time) {
  var sql = 'UPDATE total SET last_sync_time=? WHERE name=\'total\'';
  return yield* models.query(sql, [Number(time)]);
};

exports.setLastExistSyncTime = function* (time) {
  var sql = 'UPDATE total SET last_exist_sync_time=? WHERE name=\'total\'';
  return yield* models.query(sql, [Number(time)]);
};

exports.updateSyncStatus = function* (status) {
  var sql = 'UPDATE total SET sync_status=? WHERE name=\'total\'';
  return yield* models.query(sql, [status]);
};

exports.updateSyncNum = function* (params) {
  var args = [
    params.syncStatus,
    params.need || 0,
    params.success || 0,
    params.fail || 0,
    params.left || 0,
    params.lastSyncModule
  ];
  var sql = 'UPDATE total SET \
    sync_status=?, need_sync_num=?, success_sync_num=?, \
    fail_sync_num=?, left_sync_num=?, last_sync_module=? \
    WHERE name=\'total\'';
  return yield* models.query(sql, args);
};


text:
<?php

class EmpresaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	 public function filters() {
        return array(
            'rights', // perform access control for CRUD operations
        );
    }

    /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Empresa;
		$model->nombre =$_POST['nombreEmpresa'];
		$model->ruc =$_POST['ruc'];
		$model->descripcion =$_POST['descripcionEmpresa'];
		$model->save();
                $this->redirect(array('default/index'));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
		$modelEmpresa = new Empresa;
                $model = $modelEmpresa->findByPk($_POST['idEmpresa']);
		$model->nombre =$_POST['nombreEmpresaEditar'];
		$model->ruc =$_POST['rucEditar'];
		$model->descripcion =$_POST['descripcionEmpresaEditar'];
		$model->save();
                $this->redirect(array('default/index'));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	 public function actionDelete() {
        $id = $_POST['idEmpresaEliminar'];
        $this->loadModel($id)->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        $this->redirect(array('default/index'));
    }

    /**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Empresa');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Empresa('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Empresa']))
			$model->attributes=$_GET['Empresa'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Empresa the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Empresa::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Empresa $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='empresa-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
namespace M.Executables
{
    /// <summary>
    /// A marker interface signifying whether and inteceptor should discard all other interceptors and be the only one executed.
    /// </summary>
    public interface IDiscardOtherInterceptors
    {
    }
}


text:
from distutils.core import setup
import py2exe, sys
from glob import glob
sys.path.append("C:\\Temp\\Microsoft.VC90.CRT")
data_files = [("Microsoft.VC90.CRT", glob(r'C:\Temp\Microsoft.VC90.CRT\*.*'))]
setup(
    data_files=data_files,
    console=['ride.py'])


text:
from django.db import models

class GlobalSetting(models.Model):
    """
    A global setting is a key-value setting which can be set for a
    pretix instance. It will be inherited by all events and organizers.
    It is filled via the register_global_settings signal.
    """
    key = models.CharField(max_length=255, primary_key=True)
    value = models.TextField()

    def __init__(self, *args, object=None, **kwargs):
        super().__init__(*args, **kwargs)

class OrganizerSetting(models.Model):
    """
    An organizer setting is a key-value setting which can be set for an
    organizer. It will be inherited by the events of this organizer
    """
    object = models.ForeignKey('Organizer', related_name='setting_objects', on_delete=models.CASCADE)
    key = models.CharField(max_length=255)
    value = models.TextField()

class EventSetting(models.Model):
    """
    An event setting is a key-value setting which can be set for a
    specific event
    """
    object = models.ForeignKey('Event', related_name='setting_objects', on_delete=models.CASCADE)
    key = models.CharField(max_length=255)
    value = models.TextField()


text:
using UnityEngine;
using System.Collections;

public static class Rotation2D {

	private static Quaternion rotation = new Quaternion();

	/// <summary>
	/// Smoothly looks at target in 2D. Return Quaternion to be applied to transform.rotation
	/// </summary>
	/// <returns>
	/// The <see cref="Quaternion"/>.
	/// </returns>
	/// <param name='transform'>
	/// Transform of the rotating object
	/// </param>
	/// <param name='target'>
	/// Target being looked at
	/// </param>
	/// <param name='axis'>
	/// Global axis of rotation, must be single axis
	/// </param>
	/// <param name='damping'>
	/// Rotation speed.
	/// </param>
	public static Quaternion SmoothLookAt(Transform transform, Vector3 target, Vector3 axis, float speed){
		if(axis == Vector3.up || axis == -Vector3.up){
			target.y = transform.position.y;
			if(target.y >= transform.position.y) {
				rotation = Quaternion.LookRotation(target - transform.position, Vector3.up);
			}
			else {
				rotation = Quaternion.LookRotation(target - transform.position, -Vector3.up);
			}
		}else if(axis == Vector3.right || axis == -Vector3.right){
			target.x = transform.position.x;
			if(target.x >= transform.position.x)
				rotation = Quaternion.LookRotation(target - transform.position, Vector3.right);
			else
				rotation = Quaternion.LookRotation(target - transform.position, -Vector3.right);
		}else if(axis == Vector3.forward || axis == -Vector3.forward){
			target.z = transform.position.z;
			if(target.z >= transform.position.z)
				rotation = Quaternion.LookRotation(target - transform.position, Vector3.forward);
			else
				rotation = Quaternion.LookRotation(target - transform.position, -Vector3.forward);
		}
		return Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
	}

	/// <summary>
	/// Looks at target in 2D
	/// </summary>
	/// <param name='transform'>
	/// Transform of the rotating object
	/// </param>
	/// <param name='target'>
	/// Target being looked at
	/// </param>
	/// <param name='axis'>
	/// Global axis of rotation, a single axis
	/// </param>
	public static void LookAt(Transform transform, Vector3 target, Vector3 axis){
		if(axis == Vector3.up || axis == -Vector3.up){
			target.y = transform.position.y;
		}else if(axis == Vector3.right || axis == -Vector3.right){
			target.x = transform.position.x;
		}else if(axis == Vector3.forward || axis == -Vector3.forward){
			target.z = transform.position.z;
		}
		transform.LookAt(target, axis);
	}
}


text:
using System.Collections.Generic;
using System.Linq;

namespace XCommon.Patterns.Specification.Query
{
    public interface ISpecificationQuery<TEntity, TFilter>
	{
		IQueryable<TEntity> Build(IEnumerable<TEntity> source, TFilter filter);

		IQueryable<TEntity> Build(IQueryable<TEntity> source, TFilter filter);
	}
}


text:
'use strict';
/* global browser, expect */

// #############################################################################
// INTEGRATION TEST HELPER LIBRARY
var CMS = {};

CMS.Protractor = {
    mainElementsWaitTime: 12000,
    iframeWaitTime: 15000,

    // utility to generate a number of random digits
    randomDigits: function (digitsNumber) {
        return Math.floor(Math.random() * (Math.pow(10, digitsNumber) + 1));
    },

    // utility to wait for element to appear on the page
    waitFor: function (element) {
        return browser.wait(function () {
            return browser.isElementPresent(element);
        }, this.mainElementsWaitTime);
    },

    // utility to wait for element to be displayed on the page
    waitForDisplayed: function (element) {
        return browser.wait(function () {
            return element.isDisplayed();
        }, this.mainElementsWaitTime);
    },

    // utility to test the expectation that the element is missing
    expectToBeAbsent: function (element) {
        return element.isPresent().then(function (present) {
            return expect(present).toBeFalsy();
        });
    },

    // utility to select the option
    selectOption: function (select, optionText, option) {
        var that = this;

        // wait for select to appear
        that.waitFor(select);

        // click on select
        return select.click().then(function () {
            // send option text to select
            select.sendKeys(optionText);
            // click on option
            return option.click();
        }).then(function () {
            // click on select
            return select.click();
        });
    },

    // utility to log in to the site
    login: function (data) {
        var that = this;

        // object can contain username and password, if not set it will
        // fallback to 'admin'
        var credentials = data.credentials ||
            {
                site: 'http://127.0.0.1:8000/',
                username: 'admin',
                password: 'admin'
            };
        var elements = data.elements;

        // go to the main page
        browser.get(credentials.site);

        // wait for username input to appear
        that.waitFor(elements.usernameInput);

        elements.usernameInput.clear();

        // fill in email field
        elements.usernameInput.sendKeys(
            credentials.username).then(function () {
            elements.passwordInput.clear();

            // fill in password field
            return elements.passwordInput.sendKeys(
                credentials.password);
        }).then(function () {
            elements.loginButton.click();

            // wait for user menu to appear
            that.waitFor(elements.userMenu);
        });
    }

};

module.exports = CMS.Protractor;


text:
/*
 * UML Domain Functions (Synchronous Services)
 */
${function_declarations}


text:
<?php
/**
 * Check upload progress
 *
 * @author   Anton Shevchuk
 * @created  29.07.13 11:48
 */

/**
 * @namespace
 */
namespace Application;

return
/**
 * @return \closure
 */
function ($file) use ($view) {
    /**
     * @var Bootstrap $this
     * @var \Bluz\View\View $view
     */
    // used native session settings without rewrite save path
    // because PHP_SESSION_UPLOAD_PROGRESS mechanism is epic
    if (session_id() == '') {
        session_start();
    }

    $key = ini_get("session.upload_progress.prefix") . $file;

    if (!isset($_SESSION[$key])) {
        throw new Exception("Invalid file identity");
    }

    $this->useLayout(false);
    return function () use ($key) {
        return json_encode($_SESSION[$key]);
    };
};


text:
require 'spec_helper'

describe "Authentication" do

  subject { page }

  describe "signin page" do
    before { visit signin_path }

#    it { should have_content('Sign in') }
#    it { should have_title('Sign in') }

    describe "with invalid information" do
      before { click_button "Sign in" }

      it { should have_title('Sign in') }
      it { should have_selector('div.alert.alert-error') }
    end
    describe "with valid information" do
      let(:user) { FactoryGirl.create(:user) }
      before do
        fill_in "Email",    with: user.email.upcase
        fill_in "Password", with: user.password
        click_button "Sign in"
      end

      it { should have_title(user.name) }
#      it { should have_link('Profile',     href: user_path(user)) }
      it { should have_link('Sign out',    href: signout_path) }
      it { should_not have_link('Sign in', href: signin_path) }
    end
  end
end