text:
import logging

import requests
import wrapt

from opencensus.trace import (
    attributes_helper,
    exceptions_status,
    execution_context,
    integrations,
)
from opencensus.trace import span as span_module
from opencensus.trace import utils

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

log = logging.getLogger(__name__)

MODULE_NAME = 'requests'

HTTP_HOST = attributes_helper.COMMON_ATTRIBUTES['HTTP_HOST']
HTTP_METHOD = attributes_helper.COMMON_ATTRIBUTES['HTTP_METHOD']
HTTP_PATH = attributes_helper.COMMON_ATTRIBUTES['HTTP_PATH']
HTTP_ROUTE = attributes_helper.COMMON_ATTRIBUTES['HTTP_ROUTE']
HTTP_STATUS_CODE = attributes_helper.COMMON_ATTRIBUTES['HTTP_STATUS_CODE']
HTTP_URL = attributes_helper.COMMON_ATTRIBUTES['HTTP_URL']

def trace_integration(tracer=None):
    """Wrap the requests library to trace it."""
    log.info('Integrated module: {}'.format(MODULE_NAME))

    if tracer is not None:
        # The execution_context tracer should never be None - if it has not
        # been set it returns a no-op tracer. Most code in this library does
        # not handle None being used in the execution context.
        execution_context.set_opencensus_tracer(tracer)

    # Wrap Session class
    # Since
    # https://github.com/psf/requests/commit/d72d1162142d1bf8b1b5711c664fbbd674f349d1
    # (v0.7.0, Oct 23, 2011), get, post, etc are implemented via request which
    # again, is implemented via Session.request (`Session` was named `session`
    # before v1.0.0, Dec 17, 2012, see
    # https://github.com/psf/requests/commit/4e5c4a6ab7bb0195dececdd19bb8505b872fe120)
    wrapt.wrap_function_wrapper(
        MODULE_NAME, 'Session.request', wrap_session_request)
    # pylint: disable=protected-access
    integrations.add_integration(integrations._Integrations.REQUESTS)

def wrap_session_request(wrapped, instance, args, kwargs):
    """Wrap the session function to trace it."""
    # Check if request was sent from an exporter. If so, do not wrap.
    if execution_context.is_exporter():
        return wrapped(*args, **kwargs)

    method = kwargs.get('method') or args[0]
    url = kwargs.get('url') or args[1]

    excludelist_hostnames = execution_context.get_opencensus_attr(
        'excludelist_hostnames')
    parsed_url = urlparse(url)
    if parsed_url.port is None:
        dest_url = parsed_url.hostname
    else:
        dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
    if utils.disable_tracing_hostname(dest_url, excludelist_hostnames):
        return wrapped(*args, **kwargs)

    path = parsed_url.path if parsed_url.path else '/'

    _tracer = execution_context.get_opencensus_tracer()
    _span = _tracer.start_span()

    _span.name = '{}'.format(path)
    _span.span_kind = span_module.SpanKind.CLIENT

    try:
        tracer_headers = _tracer.propagator.to_headers(
            _tracer.span_context)
        kwargs.setdefault('headers', {}).update(
            tracer_headers)
    except Exception:  # pragma: NO COVER
        pass

    # Add the component type to attributes
    _tracer.add_attribute_to_current_span(
        "component", "HTTP")

    # Add the requests host to attributes
    _tracer.add_attribute_to_current_span(
        HTTP_HOST, dest_url)

    # Add the requests method to attributes
    _tracer.add_attribute_to_current_span(
        HTTP_METHOD, method.upper())

    # Add the requests path to attributes
    _tracer.add_attribute_to_current_span(
        HTTP_PATH, path)

    # Add the requests url to attributes
    _tracer.add_attribute_to_current_span(HTTP_URL, url)

    try:
        result = wrapped(*args, **kwargs)
    except requests.Timeout:
        _span.set_status(exceptions_status.TIMEOUT)
        raise
    except requests.URLRequired:
        _span.set_status(exceptions_status.INVALID_URL)
        raise
    except Exception as e:
        _span.set_status(exceptions_status.unknown(e))
        raise
    else:
        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, result.status_code
        )
        _span.set_status(
            utils.status_from_http_code(result.status_code)
        )
        return result
    finally:
        _tracer.end_span()


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
    <title>granite-file-reader demo</title>

    <link rel="icon" href="./favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon"/>

    <link   rel="import" href="../../polymer/polymer.html">

    <link rel="import" href="../../paper-styles/color.html">
    <link rel="import" href="../../iron-demo-helpers/demo-snippet.html">
    <link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html">
    <link rel="import" href="../../iron-icons/iron-icons.html">

    <link rel="import" href="../../granite-file-reader/granite-file-reader.html">

granite-file-reader

      <demo-snippet class="centered-demo">
        <template>
          <granite-file-reader  read-as="dataURL" accept=".txt,.html,.css,.sh">

Click here to load a file

          </granite-file-reader>
        </template>
      </demo-snippet>

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {

	var magnificOptions = {
		type: 'image',
		closeOnContentClick: true,
		closeBtnInside: true,
		image: {
			titleSrc: function(item) {
				return item.el.find('img').attr('alt');
			}
		},
		callbacks: {
			open: function() {
				// for firefox, which launches Magnific after a sort
				if($(".InputfieldFileJustSorted").size() > 0) this.close();
			}
		}
	};

	$("a.InputfieldFileLink").magnificPopup(magnificOptions);

	$(document).on('reloaded', '.InputfieldImage', function() {
		var $t = $(this);
		$t.find("a.InputfieldFileLink").magnificPopup(magnificOptions);
		if($t.is(".InputfieldImageGrid")) {
			unsetGridMode($t);
			setGridMode($t);
		}
	});

	$(document).on('click', '.InputfieldImage .InputfieldFileMove', function() {

		var $li = $(this).parent('p').parent('li');
		var $ul = $li.parent();

		if($(this).is('.InputfieldFileMoveTop')) $ul.prepend($li);
			else $ul.append($li);

		$ul.children('li').each(function(n) {
			$(this).find('.InputfieldFileSort').val(n);
		});

		return false;
	});

	function setGridModeItem($a) {
		var $img = $a.children("img");
		var gridSize = $img.attr('data-gridsize');
		$a.css('background', '#000 url(' + $img.attr('src') + ') center center no-repeat');
		$a.css('width', gridSize + 'px').css('height', gridSize + 'px');
		$img.css('height', gridSize + 'px');
		if($img.width() > (gridSize-1) && $img.height() > (gridSize-1)) $a.css('background-size', 'cover');
	}

	function setGridMode($parent) {
		$parent.find("i.fa-th").replaceWith($(""));
		$parent.find(".InputfieldFileLink").each(function() {
			setGridModeItem($(this));
		});
		$parent.addClass('InputfieldImageGrid');
	}

	function unsetGridModeItem($a) {
		$a.css({
			background: 'none',
			width: '',
			height: ''
		}).find('img').css('height', '');
	}

	function unsetGridMode($parent) {
		$parent.removeClass('InputfieldImageGrid');
		$parent.find(".InputfieldFileLink").each(function() {
			unsetGridModeItem($(this));
		});
		$parent.find("i.fa-list").replaceWith($(""));
	}

	var $listToggle = $("")
		.append("");
	$(".InputfieldImage .InputfieldHeader").append($listToggle);
	$(document).on('click', '.InputfieldImageListToggle', function() {
		var $parent = $(this).parents(".InputfieldImage");
		if($parent.hasClass('InputfieldImageGrid')) unsetGridMode($parent);
			else setGridMode($parent);
		return false;
	});

	$(".InputfieldImage").find(".InputfieldImageDefaultGrid").each(function() {
		setGridMode($(this).parents(".InputfieldImage"));
	});

	$(document).on('AjaxUploadDone', '.InputfieldImage .InputfieldFileList', function() {
		$("a.InputfieldFileLink", $(this)).magnificPopup(magnificOptions);
		var $parent = $(this).parents('.InputfieldImage');
		if($parent.is(".InputfieldImageGrid")) {
			unsetGridMode($parent);
			setGridMode($parent);
		}
	});

});


text:
require 'rails_helper'
require 'pry'

describe TeamsController do
  # Airbrake-1807465099223895248
  describe '#delete', type: :controller do
    before(:each) do
      user = build(:instructor)
      stub_current_user(user, user.role.name, user.role)
      # to deal with redirect_to :back
      request.env['HTTP_REFERER'] = 'www.google.com'
    end

    it 'will redirect to previous page if the team cannot be found by id' do
      allow(Team).to receive(:find).with(any_args).and_return(nil)
      allow(Team).to receive(:find_by).with(any_args).and_return(nil)
      post :delete, id: 1
      expect(response).to redirect_to 'www.google.com'
    end

    it 'will delete the team if current team did not involve in any other reviews' do
      team = double('Team', id: 1, name: 'test team', parent_id: 1)
      signed_up_teams = [double('SignedUpTeam', topic_id: 1, is_waitlisted: true)]
      controller.session[:team_type] = 'Assignment'
      controller.session[:user] = double('User', id: 1)

      allow(Team).to receive(:find).with(any_args).and_return(team)
      allow(Team).to receive(:find_by).with(any_args).and_return(team)
      allow(Assignment).to receive(:find).with(any_args).and_return(double('Course'))
      allow(SignedUpTeam).to receive(:where).with(any_args).and_return(signed_up_teams)
      allow(SignedUpTeam).to receive_message_chain(:where, :first).with(any_args).and_return(signed_up_teams.first)
      allow(TeamsUser).to receive(:where).with(any_args).and_return(nil)
      allow(signed_up_teams).to receive(:destroy_all).and_return(true)
      allow(team).to receive(:destroy).and_return(true)

      post :delete, id: 1
      expect(response).to redirect_to 'www.google.com'
    end
  end
end

describe ImportFileController do
  # Airbrake-1774360945974838307
  describe '#importFile', type: :controller do
    it 'will catch the error info if the tempfile cannot be obtained from params[:file]' do
      controller.params = {
        id: 1,
        options: {"has_column_names" => "true", "handle_dups" => "ignore"},
        model: 'AssignmentTeam',
        file: nil
      }
      session = {
        assignment_id: 1
      }
      expect { controller.send(:importFile, session, controller.params) }.not_to raise_error
      expect(controller.send(:importFile, session, controller.params).inspect).to eq("[#<NoMethodError: undefined method `each_line' for nil:NilClass>]")
    end
  end
end

describe MenuItemsController do
  # Airbrake-1766139777878852159
  describe '#link', type: :controller do
    it "can handle the situation (redirect_to '/') when the session[:menu] is nil" do
      controller.params[:name] = "manage/courses"
      controller.session[:menu] = nil
      get :link
      expect(response).to redirect_to('/')
    end

    it 'redirect to node.url when the session[:menu] is not nil' do
      controller.params[:name] = "manage/courses"
      allow(controller.session[:menu]).to receive(:try).with(any_args).and_return(double('node', url: '/tree_display/goto_courses'))
      get :link
      expect(response).to redirect_to('/tree_display/goto_courses')
    end
  end
end

describe GradesController do
  # Airbrake-1784274870078015831
  describe '#redirect_when_disallowed', type: :controller do
    before(:each) do
      controller.instance_variable_set(:@participant, double('Participant',
                                                             team: build(:assignment_team),
                                                             assignment: double('Assignment', id: 1, max_team_size: 1)))
      # allow(@participant).to receive(:assignment).with(no_args).and_return(build(:assignment, id: 1, max_team_size: 2))
      # allow(@participant).to receive(:team).with(no_args).and_return(build(:assignment_team))
      controller.session[:user] = double('User', id: 1)
    end

    it 'will return true when reviewer is nil' do
      allow(AssignmentParticipant).to receive_message_chain(:where, :first).with(any_args).and_return(nil)
      expect(controller.send(:redirect_when_disallowed)).to eq(true)
    end

    it 'will return false when reviewer is current_user' do
      allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(double('User', id: 1))
      allow(AssignmentParticipant).to receive_message_chain(:where, :first).with(any_args).and_return(double('User', user_id: 1))
      expect(controller.send(:redirect_when_disallowed)).to eq(false)
    end
  end
end

describe ReviewMappingController do
  before(:each) do
    user = build(:instructor)
    stub_current_user(user, user.role.name, user.role)
    # to deal with redirect_to :back
    request.env['HTTP_REFERER'] = 'www.google.com'
  end
  # Airbrake-1800902813969550245
  describe '#delete_reviewer' do
    it 'will stay in current page if review_response_map_id is nil' do
      allow(ReviewResponseMap).to receive(:find).with(any_args).and_return(nil)
      allow(ReviewResponseMap).to receive(:find_by).with(any_args).and_return(nil)
      post :delete_reviewer, id: 1
      expect(flash[:error]).to eq('This review has already been done. It cannot been deleted.')
      expect(response).to redirect_to 'www.google.com'
    end

    it 'will delete reviewer if current reviewer did not do any reviews' do
      review_response_map = double('ReviewResponseMap',
                                  id: 1,
                                  reviewee: double('Participant', name: 'stu1'),
                                  reviewer: double('Participant', name: 'stu2'))
      allow(ReviewResponseMap).to receive(:find).with(any_args).and_return(review_response_map)
      allow(ReviewResponseMap).to receive(:find_by).with(any_args).and_return(review_response_map)
      allow(Response).to receive(:exists?).with(any_args).and_return(false)
      allow(review_response_map).to receive(:destroy).and_return(true)
      post :delete_reviewer, id: 1
      expect(flash[:success]).to eq("The review mapping for \"stu1\" and \"stu2\" has been deleted.")
      expect(response).to redirect_to 'www.google.com'
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/all_getcode"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/common_fragment_base_color">

    <include layout="@layout/include_titlebar"/>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="@dimen/common_padding_top">

        <LinearLayout
            android:id="@+id/c1_apponitment"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_marginTop="@dimen/common_padding_top"
            android:background="@color/common_white"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="手机"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:singleLine="true"
                android:layout_weight="4"
                android:textColor="@color/color_middle_text"
                android:textSize="@dimen/common_text_middle" />

            <EditText
                android:id="@+id/etPhoneNum"
                style="?android:attr/textViewStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:background="@null"
                android:inputType="phone|number"
                android:hint="请输入手机号"
                android:textColor="@color/color_middle_text"
                android:textSize="@dimen/common_text_middle" />
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.1dp"
            android:background="@color/common_line_color" />

        <LinearLayout
            android:id="@+id/c1_password"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="@color/common_white"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="密码"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:singleLine="true"
                android:layout_weight="4"
                android:textColor="@color/color_middle_text"
                android:textSize="@dimen/common_text_middle" />

            <EditText
                android:id="@+id/et_password"
                style="?android:attr/textViewStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:background="@null"
                android:hint="请输入密码"
                android:inputType="textPassword"
                android:textColor="@color/color_middle_text"
                android:textSize="@dimen/common_text_middle" />
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.1dp"
            android:background="@color/common_line_color" />

        <LinearLayout
            android:id="@+id/c1_coupons"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:background="@color/common_white"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:hint="验证码"
                android:layout_weight="1"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:singleLine="true"
                android:textColor="@color/color_middle_text"
                android:textSize="@dimen/common_text_middle" />

            <EditText
                android:id="@+id/etCode"
                style="?android:attr/textViewStyle"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@null"
                android:inputType="number"
                android:singleLine="true"
                android:hint="请输入验证码"
                android:textColor="@color/color_middle_text" />

            <Button
                android:id="@+id/btnGetCode"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@null"
                android:layout_weight="1"
                android:text="获取验证码"
                android:textColor="@color/color_deep_text"
                android:textAppearance="?android:attr/textAppearanceMedium" />

        </LinearLayout>

    </LinearLayout>

    <Button
        style="@style/CommButton"
        android:text="下 一 步"
        android:id="@+id/btn_sure" />

</LinearLayout>


text:
goog.provide('ol.test.control.Control');

describe('ol.control.Control', function() {
  var map, control;

  beforeEach(function() {
    map = new ol.Map({
      target: document.createElement('div')
    });
    var element = document.createElement('DIV');
    control = new ol.control.Control({element: element});
    control.setMap(map);
  });

  afterEach(function() {
    goog.dispose(map);
  });

  describe('dispose', function() {
    it('removes the control element from its parent', function() {
      goog.dispose(control);
      expect(control.element.parentNode).to.be(null);
    });
  });
});

describe('ol.control.Control\'s target', function() {
  describe('target as string or element', function() {
    it('transforms target from string to element', function() {
      var target = document.createElement('div');
      target.id = 'mycontrol';
      document.body.appendChild(target);
      var ctrl = new ol.control.Control({target: 'mycontrol'});
      expect(ctrl.target_.id).to.equal('mycontrol');
      goog.dispose(ctrl);
    });
    it('accepts element for target', function() {
      var target = document.createElement('div');
      target.id = 'mycontrol';
      document.body.appendChild(target);
      var ctrl = new ol.control.Control({target: target});
      expect(ctrl.target_.id).to.equal('mycontrol');
      goog.dispose(ctrl);
    });
    it('ignores non-existing target id', function() {
      var ctrl = new ol.control.Control({target: 'doesnotexist'});
      expect(ctrl.target_).to.equal(null);
      goog.dispose(ctrl);
    });
  });
});

goog.require('goog.dispose');
goog.require('ol.Map');
goog.require('ol.control.Control');


text:
package org.bubblecloud.zigbee.api.cluster.impl.api.general.commissioning;

/**
 * @author Manlio Bacco
 * @version $LastChangedRevision$ ($LastChangedDate$)
 * @since 0.8.0
 */
public interface ResetStartupOptions {

    byte getResetCurrent();

    byte getResetAll();

    byte getEraseIndex();
}


text:
package cz.znj.kvr.sw.exp.java.guavaexp.test;

import com.google.common.math.LongMath;
import com.google.common.primitives.UnsignedLong;
import org.junit.Assert;
import org.junit.Test;

import java.math.BigInteger;

/**
 * Created by rat on 2015-09-20.
 */
public class LongMathTest
{
	@Test
	public void			testModulo()
	{
		Assert.assertEquals(-1, -4L%3L);
		Assert.assertEquals(2, LongMath.mod(-4L, 3L));
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Parameters xml_version="1" xmlns="http://cypress.com/xsd/cydatawounding_v1">
  <Param name="PartNumber" value="CYW43438KUBG" />
  <Param name="PartAvailability" value="Active" />
  <Param name="DeviceDie" value="4343A1" />
  <Param name="Silicon_Revision" value="PRODUCTION" />
  <Param name="Package" value="63-WLBGA" />
  <Param name="DeviceSeries" value="43438" />
  <Param name="Speed_MHz" value="50" />
  <Param name="Flash_KB" value="0" />
  <Param name="ROM_KB" value="640" />
  <Param name="SRAM_KB" value="512" />
  <Param name="Bluetooth" value="" />
  <Param name="Vddmin_volts" value="2.4" />
  <Param name="Vddmax_volts" value="4.8" />
  <Param name="TempMin_Celsius" value="-30" />
  <Param name="TempMax_Celsius" value="70" />
  <Param name="SiliconID" value="0x00000000" />
  <Param name="Module" value="" />
  <Param name="REQUIRED_KITS" value="None" />
  <Param name="Next_Best_Alt_Part" value="None" />
  <Param name="DATASHEET" value="http://www.cypress.com/documentation/datasheets/cyw43438-single-chip-ieee-80211ac-bgn-macbasebandradio-integrated-bluetooth" />
</Parameters>


text:
@class CollectionTableView, CollectionTableViewCell;

@protocol CollectionTableViewDelegate <UITableViewDelegate>

- (void)collectionTableView:(CollectionTableView *)tableView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;

- (CGSize)collectionTableView:(CollectionTableView *)tableView sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionTableView:(CollectionTableView *)tableView insetForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionTableView:(CollectionTableView *)tableView heightBetweenItemAtIndex:(NSInteger)section;

@end

@protocol CollectionTableViewDataSource <UITableViewDataSource>

- (NSInteger)collectionTableView:(CollectionTableView *)tableView numberOfItemsInSection:(NSInteger)section;

- (CollectionTableViewCell *)collectionTableView:(CollectionTableView *)tableView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

- (UIView *)collectionTableView:(CollectionTableView *)tableView leftViewAtIndexPath:(NSIndexPath *)indexPath;

@end

@interface CollectionTableView : UITableView

@property (nonatomic, assign) id<CollectionTableViewDelegate> collectionDelegate;
@property (nonatomic, assign) id<CollectionTableViewDataSource> collectionDataSource;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

@end


text:
@interface VXWalkthroughPagePickerViewController : VXWalkthroughPageViewController

	@property (nonatomic,weak) IBOutlet UIButton *previousButton;
	@property (nonatomic,weak) IBOutlet UIButton *nextButton;

	@property (nonatomic,weak) IBOutlet UIButton *actionButton;

- (IBAction)actionClicked:(id)sender;

	- (IBAction)nextClicked:(id)sender;
	- (IBAction)previousClicked:(id)sender;

@end


text:
A simple blog using laravel

This is a small, light-weight, no outside dependency (other than what laravel requires) blog app that I built to use as a template for all of my sites.

## Installation

1. Clone the repository.
2. Run `composer install` in the root directory.
3. Run `php artisan key:generate` to generate an application key.
3. Set database credentials.
4. Run `php artisan migrate`.
5. Start the server with `php artisan serve`.
6. Register a single user who can post as admin via the url localhost/register.
7. Close off the register GET and POST routes that `Route::auth()` uses by uncommenting the /register routes found in app/Http/routes.php.
8. Do some exploring.

## Posting

1. You must login to post blog posts. You can login at the url localhost/login.
2. HTML can be used to format the body of your post.
3. If adding images to a blog post, create an images folder (for example, in the public directory) and dump your images there. Use an html img tag and relevant src in the body of the post to link in your images.

## To Do

1. Add a commenting system.
2. Add pagination.
3. Add an easier way to upload images for a post and generate the relative links.


text:
layout:     post
author:		Najko Jahn
title:      MDC Berlin joins OpenAPC!
date:       2015-05-15 11:21:29
summary:
categories: general
comments: true
---

The [Max Delbrück Center for Molecular Medicine (MDC)](https://www.mdc-berlin.de/en) has joined [openapc.github.io](https://openapc.github.io) and is sharing its expenditures for publications in both Open Access and toll-access journals.

Contact person is [Dr.Dorothea Busjahn](https://www.mdc-berlin.de/1161898/de/about_the_mdc/structure/administration/library/teammember).

### Cost data

#### Open Access

The data set covers publication fees for 23 Open Access journal articles paid in 2014. Total expenditure was 41 464€ and the average fee paid 1 220€.

#### Hybrid

In many toll-access journals some of the articles are open access after a fee has been paid. This model is often called "hybrid open access". The dataset covers 11 hybrid open access articles. Total expenditure amounts to 20 054€. Average fee is 1 823.1€ and the median 1 382€.

### Fees paid per publisher

![plot of chunk tree_MDC](/figure/tree_MDC-1.png)

###  Average costs per year

![plot of chunk box_MDC_year](/figure/box_MDC_year-1.png)

###  Average costs per publisher

![plot of chunk box_MDC_publisher](/figure/box_MDC_publisher-1.png)


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Traçar Jusante

Esta ferramenta determina o traçado ou caminho de fluxo, em uma direção da jusante a partir de pontos na sua camada de análise.

Por exemplo, suponha que você tenha feições de ponto representando fontes de contaminação e você deseja determinar onde a contaminação fluirá na sua área de estudo. Você pode utilizar a ferramenta Traçar Jusante para identificar o caminho que tomará a contaminação. Este traçado também pode ser dividido em segmentos de linha individuais especificando um valor de distância e unidades. A linha sendo retornada pode ser o comprimento total do caminho do fluxo, um comprimento máximo do traçado especificado ou recortado para feições de área como sua área de estudo. Em muitos casos, se o comprimento total do caminho do traçado for retornado, ele será da origem de todo o caminho até o oceano.

O resultado é uma linha representando o traçado da jusante. Se uma distância for especificada para  Dividir o traçado em segmentos de linha, a linha do traçado será dividida em múltiplas linhas onde cada linha é do comprimento especificado. Por exemplo, se o seu ponto de entrada representar um derramamento de contaminação e o rio que ele flui mover em um intervalo de 0.6 milhas por hora ou 15 milhas por dia, você poderá desejar dividir o rio em 15 segmentos de milha. A divisão do traçado em 15 intervalos de milha mostrará aproximadamente onde o derramamento percorrerá cada dia. A linha será simbolizada utilizando cores graduadas baseadas na distância e será rotulada com a distância desde o começo do traçado.

O traçado resultante terá todos os atributos dos seus pontos de entrada, como também, atributos adicionais.

 PointID—Contém o valor de ID do ponto de entrada.

 LengthKm—Contém o comprimento em quilômetros do traçado total da jusante.

 Description e DataResolution—Contêm informações pertencendo aos dados hidrológicos utilizados para calcular o traçado.

 FromDistance e ToDistance—Contêm a distância de e para de cada segmento de linha. Estes atributos são gravados se Dividir o traçado em segmentos de linha for utilizada.

Se  Utilizar extensão de mapa atual estiver selecionada, somente as feições de ponto na camada de análise visíveis dentro da extensão de mapa atual serão analisadas. Se não selecionada, todas as feições na camada de entrada serão utilizadas, mesmo que estiverem fora da extensão de mapa atual.

Dividir o traçado em segmentos de linha

A linha do traçado será dividida em múltiplas linhas onde cada linha é do comprimento especificado. Por exemplo, se o seu ponto de entrada representar um derramamento de contaminação e o rio que ele flui mover em um intervalo de 0.6 milhas por hora ou 15 milhas por dia, você poderá desejar dividir o rio em 15 segmentos de milha. A divisão do traçado em 15 intervalos de milha mostrará aproximadamente onde o derramamento percorrerá cada dia. A linha será simbolizada utilizando cores graduadas baseadas na distância e será rotulada com a distância desde o começo do traçado. O traçado resultante terá múltiplos segmentos de linha, cada um com campos  FromDistance e ToDistance.

Distância máxima do traçado

Determina o comprimento total da linha que será retornada. Se você fornecer feições de área para recortar o traçado, o resultado será recortado na feição de área, não importando a distância que você inserir aqui.

Recortar saída para

Desenhe ou forneça uma camada de área onde você deseja que o traçado seja recortado. Por exemplo, se você desejar somente que o resultado esteja dentro da sua área de estudo, como seu município, utilize sua feição de município como entrada, então o traçado irá parar no limite do município.

Nome da camada resultante

O nome da camada que será criada em  Meu Conteúdo e adicionada no mapa. O nome padrão é baseado no nome da camada de análise. Se a camada já existir, você será avisado para confirmar se deseja substituí-la.

Ao utilizar a caixa suspensa  Salvar resultado em, é possível especificar o nome de uma pasta em Meu Conteúdo onde o resultado será salvo.


text:
#ifndef __USER_CONFIG_H__
#define __USER_CONFIG_H__

/*support one platform at the same project*/
#define ESP_PLATFORM            1
#define LEWEI_PLATFORM          0

/*support one server at the same project*/
#define HTTPD_SERVER            1
#define WEB_SERVICE             0

/*support one device at the same project*/
#define PLUG_DEVICE             1
#define LIGHT_DEVICE            0
#define SENSOR_DEVICE           0 //TBD

#if LIGHT_DEVICE
#define USE_US_TIMER
#endif

#define RESTORE_KEEP_TIMER 0

#if ESP_PLATFORM

#if PLUG_DEVICE || LIGHT_DEVICE
#define BEACON_TIMEOUT  150000000
#define BEACON_TIME     50000
#endif

#if SENSOR_DEVICE
#define HUMITURE_SUB_DEVICE         1
#define FLAMMABLE_GAS_SUB_DEVICE    0
#endif

#if SENSOR_DEVICE
#define SENSOR_DEEP_SLEEP

#if HUMITURE_SUB_DEVICE
#define SENSOR_DEEP_SLEEP_TIME    30000000
#elif FLAMMABLE_GAS_SUB_DEVICE
#define SENSOR_DEEP_SLEEP_TIME    60000000
#endif
#endif

#define AP_CACHE
#ifdef AP_CACHE
#define AP_CACHE_NUMBER    5
#endif

//#define SOFTAP_ENCRYPT
#ifdef SOFTAP_ENCRYPT
#define PASSWORD    "v*%W>L<@i&Nxe!"
#endif

#define USE_DNS
#define ESP_DOMAIN      "iot.espressif.cn"

/*SSL not Ready*/
//#define SERVER_SSL_ENABLE
//#define CLIENT_SSL_ENABLE
//#define UPGRADE_SSL_ENABLE

#elif LEWEI_PLATFORM

#endif

#endif


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.pratap.cardviews1.MainActivity" >

    <item
        android:id="@+id/action_delete"
        android:icon="@drawable/ic_action_delete"
        android:orderInCategory="100"
        android:title="@string/action_search"
        android:visible="false"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="ifRoom"/>

</menu>


text:
package io.alef.yap.core;

import io.alef.yap.expression.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ReferenceProcessor implements Evaluator {

    private final Map<String, DefaultSymbol> symbols;

    public ReferenceProcessor(Map<String, DefaultSymbol> symbols) {
        this.symbols = symbols;
    }

    @Override
    public Expression apply(ForwardReference forwardReference) {
        return Expressions.reference(symbols.get(forwardReference.getValue()));
    }

    @Override
    public Expression apply(Reference reference) {
        return reference;
    }

    @Override
    public Expression apply(Pattern pattern) {
        return pattern;
    }

    @Override
    public Expression apply(Sequence sequence) {
        final List<Expression> elements = sequence.getElements();
        final List<Expression> normalisedElements = new ArrayList<>();
        for (Expression element : elements) {
            normalisedElements.add(element.apply(this));
        }
        return Expressions.sequence(normalisedElements);
    }
}


text: Ansible playbook to deploy cats.


text:
extern crate cql_ffi;

use std::slice;

use cql_ffi::*;

unsafe fn print_error(future: &mut CassFuture) {
    let message = future.error_message();
    let message = slice::from_raw_parts(&message.data, message.length as usize);
    println!("Error: {:?}", message);
}

unsafe fn create_cluster() -> *mut CassCluster {
    let cluster = CassCluster::new();
    cluster.set_contact_points(str2ref("127.0.0.1,127.0.0.2,127.0.0.3"));
    cluster
}

unsafe fn connect_session(session: &mut CassSession, cluster: &mut CassCluster) -> CassError {
    let future: CassFuture = &mut session.connect(cluster);
    future.wait();
    future
}

//~ fn on_log(message:&CassLogMessage, data:data) {

    //~ println!("{}",
        //~ message.time_ms / 1000,
        //~ message->time_ms % 1000,
        //~ cass_log_level_string(message.severity),
        //~ message.file, message.line, message.function,
        //~ message.message);
//~ }

fn main() {
    //~ CassCluster* cluster = NULL;
    //~ CassSession* session = NULL;
    //~ CassFuture* close_future = NULL;
    //~ FILE* log_file = fopen("driver.log", "w+");
    //~ if (log_file == NULL) {
        //~ fprintf(stderr, "Unable to open log file\n");
    //~ }
/* Log configuration *MUST* be done before any other driver call */
    cass_log_set_level(CASS_LOG_INFO);
    cass_log_set_callback(on_log, log_file);
    cluster = create_cluster();
    session = cass_session_new();
    if (connect_session(session, cluster) != CASS_OK) {
        cass_cluster_free(cluster);
        cass_session_free(session);
        return -1;
    }
    close_future = cass_session_close(session);
    cass_future_wait(close_future);
    cass_future_free(close_future);
    cass_cluster_free(cluster);
    cass_session_free(session);
/* This *MUST* be the last driver call */
    cass_log_cleanup();
    fclose(log_file);
    return 0;
}


text:
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace WInterop.Devices;

public static partial class ControlCodes
{
    /// <summary>
    ///  Codes for controlling the mount point manager. (\\.\MountPointManager or \Device\MountPointManager)
    /// </summary>
    public enum MountManager : uint
    {
        // Maybe I Should Drive - Drive Letter Assignment & The Mount Manager
        // http://www.osronline.com/article.cfm?id=107

        /// <summary>
        ///  Create a mount point. Uses MOUNTMGR_CREATE_POINT_INPUT. [IOCTL_MOUNTMGR_CREATE_POINT]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560457.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 0, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        CreatePoint = 0x006dc000,

        /// <summary>
        ///  Works like QueryPoints, but deletes symbolic links and database entries for matches.
        ///  [IOCTL_MOUNTMGR_DELETE_POINTS]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560461.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 1, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        DeletePoints = 0x006dc004,

        /// <summary>
        ///  Returns mount points that match MOUNTMGR_MOUNT_POINT. Returns matches in MOUNTMGR_MOUNT_POINTS.
        ///  [IOCTL_MOUNTMGR_QUERY_POINTS]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560474.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)
        /// </remarks>
        QueryPoints = 0x006d0008,

        /// <summary>
        ///  Same as DeletePoints, but does not remove symbolic links.
        ///  [IOCTL_MOUNTMGR_DELETE_POINTS_DBONLY]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560464.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 3, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        DeletePointsDatabaseOnly = 0x006dc00c,

        /// <summary>
        ///  Gets the existing drive letter or assigns the next available letter if applicable. Uses
        ///  MOUNTMGR_DRIVE_LETTER_TARGET for input and MOUNTMGR_DRIVE_LETTER_INFORMATION for output.
        ///  [IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560473.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 4, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        NextDriveLetter = 0x006dc010,

        /// <summary>
        ///  Tell the mount manager to auto assign drive letters when they are introduced to the system.
        ///  [IOCTL_MOUNTMGR_AUTO_DL_ASSIGNMENTS]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560448.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 5, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        AutoDriveLetterAssignments = 0x006dc014,

        /// <summary>
        ///  Alert the mount manager that a volume mount point has been created. Allows the mount point
        ///  to persist if volumes are moved from one system to another. SetVolumeMountPoint() calls
        ///  this. Uses MOUNTMGR_VOLUME_MOUNT_POINT. [IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560485.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 6, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        VolumeMountPointCreated = 0x006dc018,

        /// <summary>
        ///  Alert the mount manager that a volume mount point has been deleted. DeleteVolumeMountPoint()
        ///  calls this. Uses MOUNTMGR_VOLUME_MOUNT_POINT.
        ///  [IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560491.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 7, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        VolumeMountPointDeleted = 0x006dc01c,

        /// <summary>
        ///  Used to track the state of the mount manager. Returns the Epic number that reflects the current
        ///  change state. Uses MOUNTMGR_CHANGE_NOTIFY_INFO. [IOCTL_MOUNTMGR_CHANGE_NOTIFY]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560451.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 8, METHOD_BUFFERED, FILE_READ_ACCESS)
        /// </remarks>
        ChangeNotify = 0x006d4020,

        /// <summary>
        ///  Tells the mount manager to reserve the symbolic link reserved if the volume
        ///  goes offline. Uses MOUNTMGR_TARGET_NAME. [IOCTL_MOUNTMGR_KEEP_LINKS_WHEN_OFFLINE]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560468.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 9, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        KeepLinksWhenOffline = 0x006dc024,

        /// <summary>
        ///  Tells the mount manager to scan it's dead mounted device list to see if it can
        ///  resolve unique ids. Used primarily for cluster support.
        ///  [IOCTL_MOUNTMGR_CHECK_UNPROCESSED_VOLUMES]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560454.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 10, METHOD_BUFFERED, FILE_READ_ACCESS)
        /// </remarks>
        CheckUnprocessedVolumes = 0x006d4028,

        /// <summary>
        ///  Allows manually notifying the mount manager that a volume is available.
        ///  Uses MOUNTMGR_TARGET_NAME. [IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION]
        /// </summary>
        /// <remarks>
        ///  https://msdn.microsoft.com/en-us/library/windows/hardware/ff560477.aspx
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 11, METHOD_BUFFERED, FILE_READ_ACCESS)
        /// </remarks>
        VolumeArrivalNotification = 0x006d402c,

        /// <summary>
        ///  Gets the DOS drive letter for the given volume if it has one.
        ///  Takes MOUNTMGR_TARGET_NAME as input and returns MOUNTMGR_VOLUE_PATHS.
        ///  [IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH]
        /// </summary>
        /// <remarks>
        ///  Added in Windows XP. IoVolumeDeviceToDosName() uses this as does GetFinalPathNameByHandle().
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
        /// </remarks>
        QueryDosVolumePath = 0x006d0030,

        /// <summary>
        ///  Gets all volume path names for the given volume.
        ///  Takes MOUNTMGR_TARGET_NAME as input and returns MOUNTMGR_VOLUE_PATHS.
        ///  [IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATHS]
        /// </summary>
        /// <remarks>
        ///  Added in Windows XP. GetVolumePathNamesForVolumeNameW() uses this.
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 13, METHOD_BUFFERED, FILE_ANY_ACCESS)
        /// </remarks>
        QueryDosVolumePaths = 0x006d0034,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_SCRUB_REGISTRY]
        /// </summary>
        /// <remarks>
        ///  Added in Windows Server 2003.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 14, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        ScrubRegistry = 0x006dc038,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_QUERY_AUTO_MOUNT]
        /// </summary>
        /// <remarks>
        ///  Added in Windows Server 2003.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)
        /// </remarks>
        QueryAutoMount = 0x006d003c,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_SET_AUTO_MOUNT]
        /// </summary>
        /// <remarks>
        ///  Added in Windows Server 2003.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 16, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        SetAutoMount = 0x006dc040,

        /// <summary>
        ///  Assigns the drive letter for the boot volume. Similar to NextDriveLetter, but with a
        ///  special treatment of WinPE boot volumes (which are 'X' by default). Takes no input or output.
        ///  [IOCTL_MOUNTMGR_BOOT_DL_ASSIGNMENT]
        /// </summary>
        /// <remarks>
        ///  Added in Windows 7.
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 17, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        BootDriveLetterAssignment = 0x006dc044,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_TRACELOG_CACHE]
        /// </summary>
        /// <remarks>
        ///  Added in Windows 7.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 18, METHOD_BUFFERED, FILE_READ_ACCESS)
        /// </remarks>
        TracelogCache = 0x006d4048,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_PREPARE_VOLUME_DELETE]
        /// </summary>
        /// <remarks>
        ///  Added in Windows 8.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 19, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        PrepareVolumeDelete = 0x006dc04c,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_CANCEL_VOLUME_DELETE]
        /// </summary>
        /// <remarks>
        ///  Added in Windows 8.
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 20, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        CancelVolumeDelete = 0x006dc050,

        /// <summary>
        ///  [IOCTL_MOUNTMGR_SILO_ARRIVAL]
        /// </summary>
        /// <remarks>
        ///  Added in Windows 10 Anniversary Update (RS1).
        ///
        ///  CTL_CODE(MOUNTMGRCONTROLTYPE, 21, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
        /// </remarks>
        SiloArrival = 0x006dc054
    }
}


text:
status="$(playerctl -p spotify status 2>&1)"
if [ "$status" != "No players found" ]
then
  artist="$(playerctl -p spotify metadata artist)"
  if [ "$artist" != "" ]
  then
    echo " $(playerctl -p spotify metadata artist) - $(playerctl -p spotify metadata title)"
  else
    # Clear any string that was previously displayed
    echo ""
  fi
else
  # Clear any string that was previously displayed
  echo ""
fi


text:
import queue
import threading

import numpy as np

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

TIMEOUT = 1

class StageTest(test.TestCase):

  @test_util.run_deprecated_v1
  def testSimple(self):
    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.float32)
        v = 2. * (array_ops.zeros([128, 128]) + x)
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea([dtypes.float32])
        stage = stager.put([v])
        y = stager.get()
        y = math_ops.reduce_max(math_ops.matmul(y, y))

    G.finalize()

    with self.session(graph=G) as sess:
      sess.run(stage, feed_dict={x: -1})
      for i in range(10):
        _, yval = sess.run([stage, y], feed_dict={x: i})
        self.assertAllClose(4 * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)

  @test_util.run_deprecated_v1
  def testMultiple(self):
    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.float32)
        v = 2. * (array_ops.zeros([128, 128]) + x)
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea([dtypes.float32, dtypes.float32])
        stage = stager.put([x, v])
        z, y = stager.get()
        y = math_ops.reduce_max(z * math_ops.matmul(y, y))

    G.finalize()

    with self.session(graph=G) as sess:
      sess.run(stage, feed_dict={x: -1})
      for i in range(10):
        _, yval = sess.run([stage, y], feed_dict={x: i})
        self.assertAllClose(
            4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)

  @test_util.run_deprecated_v1
  def testDictionary(self):
    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.float32)
        v = 2. * (array_ops.zeros([128, 128]) + x)
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea(
            [dtypes.float32, dtypes.float32],
            shapes=[[], [128, 128]],
            names=['x', 'v'])
        stage = stager.put({'x': x, 'v': v})
        ret = stager.get()
        z = ret['x']
        y = ret['v']
        y = math_ops.reduce_max(z * math_ops.matmul(y, y))

    G.finalize()

    with self.session(graph=G) as sess:
      sess.run(stage, feed_dict={x: -1})
      for i in range(10):
        _, yval = sess.run([stage, y], feed_dict={x: i})
        self.assertAllClose(
            4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4)

  def testColocation(self):
    gpu_dev = test.gpu_device_name()

    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.float32)
        v = 2. * (array_ops.zeros([128, 128]) + x)
      with ops.device(gpu_dev):
        stager = data_flow_ops.StagingArea([dtypes.float32])
        y = stager.put([v])
        expected_name = gpu_dev if 'gpu' not in gpu_dev else '/device:GPU:0'
        self.assertEqual(y.device, expected_name)
      with ops.device('/cpu:0'):
        x = stager.get()[0]
        self.assertEqual(x.device, '/device:CPU:0')

    G.finalize()

  @test_util.run_deprecated_v1
  def testPeek(self):
    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.int32, name='x')
        p = array_ops.placeholder(dtypes.int32, name='p')
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea(
            [
                dtypes.int32,
            ], shapes=[[]])
        stage = stager.put([x])
        peek = stager.peek(p)
        ret = stager.get()

    G.finalize()

    with self.session(graph=G) as sess:
      for i in range(10):
        sess.run(stage, feed_dict={x: i})

      for i in range(10):
        self.assertTrue(sess.run(peek, feed_dict={p: i}) == [i])

  def testPeekBadIndex(self):
    stager = data_flow_ops.StagingArea([
        dtypes.int32,
    ], shapes=[[10]])
    stager.put([array_ops.zeros([10], dtype=dtypes.int32)])

    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                'must be scalar'):
      self.evaluate(stager.peek([]))

  @test_util.run_deprecated_v1
  def testSizeAndClear(self):
    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.float32, name='x')
        v = 2. * (array_ops.zeros([128, 128]) + x)
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea(
            [dtypes.float32, dtypes.float32],
            shapes=[[], [128, 128]],
            names=['x', 'v'])
        stage = stager.put({'x': x, 'v': v})
        ret = stager.get()
        size = stager.size()
        clear = stager.clear()

    G.finalize()

    with self.session(graph=G) as sess:
      sess.run(stage, feed_dict={x: -1})
      self.assertEqual(sess.run(size), 1)
      sess.run(stage, feed_dict={x: -1})
      self.assertEqual(sess.run(size), 2)
      sess.run(clear)
      self.assertEqual(sess.run(size), 0)

  @test_util.run_deprecated_v1
  def testCapacity(self):
    self.skipTest('b/123423516 this test is flaky on gpu.')
    capacity = 3

    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.int32, name='x')
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea(
            [
                dtypes.int32,
            ], capacity=capacity, shapes=[[]])
        stage = stager.put([x])
        ret = stager.get()
        size = stager.size()

    G.finalize()

    value_queue = queue.Queue()
    n = 8

    with self.session(graph=G) as sess:
      # Stage data in a separate thread which will block when it hits the
      # staging area's capacity and thus not fill the value_queue with n tokens
      def thread_run():
        for i in range(n):
          sess.run(stage, feed_dict={x: i})
          value_queue.put(0)

      t = threading.Thread(target=thread_run)
      t.daemon = True
      t.start()

      # Get tokens from the value_queue until a timeout occurs
      try:
        for i in range(n):
          value_queue.get(timeout=TIMEOUT)
      except queue.Empty:
        pass

      # Should've timed out on the iteration 'capacity'
      if not i == capacity:
        self.fail("Expected to timeout on iteration '{}' "
                  "but instead timed out on iteration '{}' "
                  "Staging Area size is '{}' and configured "
                  "capacity is '{}'.".format(capacity, i, sess.run(size),
                                             capacity))

      # Should have capacity elements in the staging area
      self.assertTrue(sess.run(size) == capacity)

      # Clear the staging area completely
      for i in range(n):
        self.assertTrue(sess.run(ret) == [i])

      # It should now be empty
      self.assertTrue(sess.run(size) == 0)

  @test_util.run_deprecated_v1
  def testMemoryLimit(self):
    memory_limit = 512 * 1024  # 512K
    chunk = 200 * 1024  # 256K
    capacity = memory_limit // chunk

    with ops.Graph().as_default() as G:
      with ops.device('/cpu:0'):
        x = array_ops.placeholder(dtypes.uint8, name='x')
      with ops.device(test.gpu_device_name()):
        stager = data_flow_ops.StagingArea(
            [
                dtypes.uint8,
            ], memory_limit=memory_limit, shapes=[[]])
        stage = stager.put([x])
        ret = stager.get()
        size = stager.size()

    G.finalize()

    value_queue = queue.Queue()
    n = 8

    with self.session(graph=G) as sess:
      # Stage data in a separate thread which will block when it hits the
      # staging area's capacity and thus not fill the value_queue with n tokens
      def thread_run():
        for i in range(n):
          sess.run(stage, feed_dict={x: np.full(chunk, i, dtype=np.uint8)})
          value_queue.put(0)

      t = threading.Thread(target=thread_run)
      t.daemon = True
      t.start()

      # Get tokens from the value_queue until a timeout occurs
      try:
        for i in range(n):
          value_queue.get(timeout=TIMEOUT)
      except queue.Empty:
        pass

      # Should've timed out on the iteration 'capacity'
      if not i == capacity:
        self.fail("Expected to timeout on iteration '{}' "
                  "but instead timed out on iteration '{}' "
                  "Staging Area size is '{}' and configured "
                  "capacity is '{}'.".format(capacity, i, sess.run(size),
                                             capacity))

      # Should have capacity elements in the staging area
      self.assertTrue(sess.run(size) == capacity)

      # Clear the staging area completely
      for i in range(n):
        self.assertTrue(np.all(sess.run(ret)[0] == i))

      self.assertTrue(sess.run(size) == 0)

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


text:
module Feature.Query.ErrorSpec where

import Network.Wai (Application)

import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON

import Protolude hiding (get)

spec :: SpecWith ((), Application)
spec = do
  describe "Non existent api schema" $ do
    it "succeeds when requesting root path" $
      get "/" `shouldRespondWith` 200

    it "gives 404 when requesting a nonexistent table in this nonexistent schema" $
      get "/nonexistent_table" `shouldRespondWith` 404

  describe "Non existent URL" $ do
    it "gives 404 on a single nested route" $
      get "/projects/nested" `shouldRespondWith` 404

    it "gives 404 on a double nested route" $
      get "/projects/nested/double" `shouldRespondWith` 404

  describe "Unsupported HTTP methods" $ do
    it "should return 405 for CONNECT method" $
      request methodConnect "/"
          []
          ""
        `shouldRespondWith`
          [json|
            {"hint": null,
             "details": null,
             "code": "PGRST117",
             "message":"Unsupported HTTP method: CONNECT"}|]
          { matchStatus = 405 }

    it "should return 405 for TRACE method" $
      request methodTrace "/"
          []
          ""
        `shouldRespondWith`
          [json|
            {"hint": null,
             "details": null,
             "code": "PGRST117",
             "message":"Unsupported HTTP method: TRACE"}|]
          { matchStatus = 405 }

    it "should return 405 for OTHER method" $
      request "OTHER" "/"
          []
          ""
        `shouldRespondWith`
          [json|
            {"hint": null,
             "details": null,
             "code": "PGRST117",
             "message":"Unsupported HTTP method: OTHER"}|]
          { matchStatus = 405 }


text:
module Volt
  module TemplateHelpders
    module ClassMethods
      def template(name, template, bindings)
        @templates[name] = { 'html' => template, 'bindings' => bindings }
      end
    end

    def self.included(base)
      # Setup blank templates class variable
      base.class_attribute :__templates
      base.__templates = {}

      base.send :extend, ClassMethods
    end
  end

end


text:
<?php

namespace app\controllers\backend;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\Event;
use app\models\Email;
use app\models\Peserta;
use app\models\AbsensiForm;

class EmailController extends Controller
{
	public function behaviors(){
		return [
			'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
		];
	}

	public function actionBroadcast(){
        $peserta = Peserta::find()->all();
		foreach($peserta as $key){
            $temp = $key->email;
            echo $temp;
        }
	}

	public function actionSend2(){
		 //broadcast semua
        $email = new Email();
       if ($email->load(Yii::$app->request->post()) && $email->validate()) {
        $peserta = Peserta::find()->all();
        foreach($peserta as $key){
            $temp = $key->email;
			echo $temp;
            $content_template = $email->content;
            //mengambil subjek dari email yang akan dikirimkan
            $subject_template = $email->subject;

            $subject = str_replace("{nama}", $key->nama, $subject_template);

            $content = str_replace("{nama}", $key->nama, $content_template);

            echo "
";
            Yii::$app->mailer
                     ->compose()
                     ->setFrom(Yii::$app->params['adminEmail'])
                     ->setHtmlBody($content)
                     ->setSubject($subject)
                     ->setTo($temp)
                     ->send();
            }
        }

	}

	public function actionSend()
	{

   //      //broadcast semua
   //      $email = new Email();
   //     if ($email->load(Yii::$app->request->post()) && $email->validate()) {
   //      $peserta = Peserta::find()->all();
   //      foreach($peserta as $key){
   //          $temp = $key->email;
			// echo $temp;
   //          $content_template = $email->content;
   //          //mengambil subjek dari email yang akan dikirimkan
   //          $subject_template = $email->subject;

   //          $subject = str_replace("{nama}", $key->nama, $subject_template);

   //          $content = str_replace("{nama}", $key->nama, $content_template);

   //          echo "
";
   //          Yii::$app->mailer
   //                   ->compose()
   //                   ->setFrom(Yii::$app->params['adminEmail'])
   //                   ->setHtmlBody($content)
   //                   ->setSubject($subject)
   //                   ->setTo($temp)
   //                   ->send();
   //          }
   //      }

        //send per event
        $email = new Email();
        if ($email->load(Yii::$app->request->post()) && $email->validate()) {
            //mengambil event yang dipilih
            $event=Event::findOne($email->id_event);
            //mengambil content dari email yang akan dikirimkan
            $content_template = $email->content;
            //mengambil subjek dari email yang akan dikirimkan
            $subject_template = $email->subject;

            foreach($event->absensis as $absensi){
                $temp =$absensi->idPeserta->email;
                echo $temp;

                // echo $absensi->idPeserta->email;
                echo "
";
                $subject = str_replace("{nama}", $absensi->idPeserta->nama, $subject_template);
                $subject = str_replace("{nama_seminar}", $event->nama, $subject);
                $subject = str_replace("{jadwal}", $event->jadwal, $subject);

                $content = str_replace("{nama}", $absensi->idPeserta->nama, $content_template);
                $content = str_replace("{nama_seminar}", $event->nama, $content);
                $content = str_replace("{jadwal}", $event->jadwal, $content);

                Yii::$app->mailer
                        ->compose()
						->setFrom(Yii::$app->params['adminEmail'])
                        ->setHtmlBody($content)
                        ->setSubject($subject)
                        ->setTo($temp)
                        ->send();
            }

        }
	}

	public function actionMail()
    {
        $email = new Email();
        $data = Event::find()->all();
        return $this->render('notif', ['data'=>$data,
                                      'email' => $email,
        ]);

    }

}


text:
package org.demis27.rest.api.raml.reader;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.demis27.rest.api.raml.RestAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class RamlReader {

    private static final Logger LOGGER = LoggerFactory.getLogger(RamlReader.class);

    public RestAPI read(String fileName) throws IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        RestAPI api = mapper.readValue(new File(fileName), RestAPI.class);

        return api;
    }
}


text:
package Moose2012.CommandBased.subsystems;

import Moose2012.CommandBased.RobotMap;
import Moose2012.CommandBased.commands.BallFeederOff;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;

public class BallFeeder extends Subsystem {
    // Put methods for controlling this subsystem
    // here. Call these from Commands.

    Victor loadingMotor;
    //DigitalInput topLim;
    //DigitalInput midLim;
    //DigitalInput botLim;

    public BallFeeder ()
    {
        loadingMotor = new Victor(RobotMap.loadingMotor);
        //topLim= new DigitalInput(RobotMap.ballSensorTop);
        //midLim= new DigitalInput(RobotMap.ballSensorMiddle);
        //botLim= new DigitalInput(RobotMap.ballSensorBottom);

    }

    public void initDefaultCommand() {
        // Set the default command for a subsystem here.
        setDefaultCommand(new BallFeederOff());
    }

    public void feedOff() { // don't pick up balls
            loadingMotor.set(0);
    }

    public void feedIn() { // pick up balls
            loadingMotor.set(-RobotMap.loaderSpeed);
    }

    public void feedOut() {  // release balls
        loadingMotor.set(RobotMap.loaderSpeed);
    }
}


text:
namespace alraune {

    export class FilePicker implements KindaControl, FrontToBackContributor {
        /// @augment e9006604-9ac4-488c-acda-64b57ad6aafe
        readonly placeholder = new ControlPlaceholder()
        readonly hiddenFileInputID = nextUID()
        readonly buttonID = nextUID()
        value: AlFileFormValue
        file: File
        static savedState: {value: AlFileFormValue, file: File}
        static the: FilePicker

        constructor(private backPile: AlBackToFrontCommandPile) {
            FilePicker.the = this
            this.value = this.backPile.fileValue
        }

        getPlaceholder(): ControlPlaceholder {
            return this.placeholder
        }

        saveState() {
            FilePicker.savedState = {value: this.value, file: this.file}
        }

        restoreState() {
            this.value = FilePicker.savedState.value
            this.file = FilePicker.savedState.file
            this.updateGivenPlaceholderIsInDOM()
        }

        contributeToFrontToBackCommand(p: Params_contributeToFrontToBackCommand): void {
            if (p.preflight) {
                const lightValue: AlFileFormValue = {...this.value}
                lightValue.base64 = ""
                ;(p.ftb as any)[this.backPile.ftbProp] = lightValue
            } else {
                ;(p.ftb as any)[this.backPile.ftbProp] = this.value
            }
        }

        updateGivenPlaceholderIsInDOM() {
            const self = this
            this.placeholder.setHTML(buildString(s => {
                s.ln(`<div>`)
                s.ln(`<input id="${this.hiddenFileInputID}" type="file" style="display: none;">`)

                function renderButton(title: string) {
                    return `<button id="${self.buttonID}" class="btn btn-default" style=""><i class="fa fa-cloud-upload"></i> ${title}</button>`
                }

                if (this.value.specified) {
                    s.ln(`<span style="margin-right: 4px;">${escapeHTML(self.value.name)} (${formatFileSizeApprox(self.value.size)})</span>`)
                    s.ln(renderButton(t("", "Изменить...")))
                }
                else {
                    s.ln(renderButton(t("", "Выбрать...")))
                }
                s.ln(`</div>`)
            }))

            const jHiddenFileInput = byIDSingle(this.hiddenFileInputID)
            jHiddenFileInput.on("change", () => {
                const files: FileList = (jHiddenFileInput as any)[0].files
                this.file = files[0]
                st.clog("File selected", this.file)
                const reader = new FileReader()
                reader.onload = () => {
                    const dataURL: string = reader.result
                    const base64 = dataURL.substring(dataURL.indexOf(",") + 1)
                    this.value = {specified: true, name: this.file.name, base64, size: this.file.size, changed: true}
                    this.updateGivenPlaceholderIsInDOM()
                    AlFrontPile.state.filePicked.resumeTestFromSut()
                }
                reader.readAsDataURL(this.file)
            })

            byIDSingle(this.buttonID).on("click", () => {
                jHiddenFileInput.click()
            })
        }

        async debug_selectFile(name: string): Promise<void> {
            AlFrontPile.state.filePicked.reset()

            const ibr = AlFrontPile.state.initialBackResponse
            // byIDSingle(this.buttonID).click()
            const ftb = {} as AlFrontToBackCommandPile
            ftb.opcode = "Debug_RobotClickAndTypeIntoOpenFileDialog"
            ftb.mouseX = 250
            ftb.mouseY = 300
            ftb.fileNameToTypeByRobot = ibr.debugTestContentRoot + ibr.debugPlatformSeparator + name
            sendCommandToBack({url: ibr.debugPostURL, ftb})

            await AlFrontPile.state.filePicked.pauseTestFromTest()
        }
    }
}


text:
<?php
namespace Dashboard\Model;

class ProductCategory
{
    private $product_category_id;
    private $product_category;

    public function exchangeArray($data)
    {
        $this->product_category_id = (!empty($data['product_category_id']))?$data['product_category_id']:null;
        $this->product_category = (!empty($data['product_category']))?$data['product_category']:null;
    }

    public function getProductCategoryId()
    {
        return $this->product_category_id;
    }

    public function setProductCategoryId($product_category_id)
    {
        $this->product_category_id = $product_category_id;
    }

    public function getProductCategory()
    {
        return $this->product_category;
    }

    public function setProductCategory($product_category)
    {
        $this->product_category = $product_category;
    }
}


text:
namespace UnitTest {

class TestReporter;
class TestResults;
class Timer;

int RunAllTests();
int RunAllTests(TestReporter& reporter);
int RunAllTests(TestReporter& reporter, TestList const& list, char const* suiteName, int maxTestTimeInMs = 0);

class TestRunner
{
public:

	template <class Predicate>
	int RunAllTestsIf(const Predicate& predicate) const
	{
		TestContext context;
		return RunAllTestsIf(context, Test::GetTestList(), 0, predicate);
	}

	template <class Predicate>
	int RunAllTestsIf(TestReporter& reporter, const Predicate& predicate) const
	{
		TestContext context(&reporter);
		return RunAllTestsIf(context, Test::GetTestList(), 0, predicate);
	}

	template <class Predicate>
	int RunAllTestsIf(TestReporter& reporter, TestList const& list, char const* suiteName, const Predicate& predicate, int maxTestTimeInMs = 0) const
	{
		TestContext context(&reporter);
		return RunAllTestsIf(context, list, suiteName, predicate, maxTestTimeInMs);
	}

private:

	// To remove dependencies on TestReporter, TestResults and Timer
	class TestContext
	{
	public:
		TestContext();
		TestContext(TestReporter* reporter_);
		~TestContext();

		TestReporter* GetReporter() const;
		TestResults* GetResult() const;
		Timer* GetTimer() const;

	private:
		TestReporter* reporter;
		TestResults* result;
		Timer*       timer;

		bool ownReporter;
	};

	template <class Predicate>
	int RunAllTestsIf(TestContext& context, TestList const& list, char const* suiteName, const Predicate& predicate, int maxTestTimeInMs = 0) const
	{
		TestResults* result = context.GetResult();

	    Test* curTest = list.GetHead();
	    while (curTest != 0)
	    {
		    if ( IsTestInSuite(curTest,suiteName) && predicate(curTest) )
		    {
	        	    RunTest(result, curTest, maxTestTimeInMs);
			 }

	     	 curTest = curTest->next;
	    }

	    return Finish(context);
	}

	// To remove dependencies
	int  Finish(TestContext& context) const;
	bool IsTestInSuite(Test* const curTest, char const* suiteName) const;
	void RunTest(TestResults* const result, Test* const curTest, int const maxTestTimeInMs) const;
};

// Predicate version of RunAllTests(TestReporter& reporter, TestList const& list, char const* suiteName, int maxTestTimeInMs = 0)
template <class Predicate>
int RunAllTestsIf(TestReporter& reporter, TestList const& list, char const* suiteName, const Predicate& predicate, int maxTestTimeInMs = 0)
{
	TestRunner runner;
	return runner.RunAllTestsIf(reporter, list, suiteName, predicate, maxTestTimeInMs);
}

// Predicate version of RunAllTests(TestReporter& reporter)
template <class Predicate>
int RunAllTestsIf(TestReporter& reporter, const Predicate& predicate)
{
	TestRunner runner;
	return runner.RunAllTestsIf(reporter, predicate);
}

// Predicate version of RunAllTests()
template <class Predicate>
int RunAllTestsIf(const Predicate& predicate)
{
	TestRunner runner;
	return runner.RunAllTestsIf(predicate);
}

}

#endif


text:
package doubler;

public interface Doubler {
    int doubleIt(int toDouble);
}


text:
package com.navercorp.pinpoint.test.fork;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PinpointConfig {
    String value();
}


text:
<?php

namespace BookStack\Entities\Tools;

use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Bookshelf;

class ShelfContext
{
    protected $KEY_SHELF_CONTEXT_ID = 'context_bookshelf_id';

    /**
     * Get the current bookshelf context for the given book.
     */
    public function getContextualShelfForBook(Book $book): ?Bookshelf
    {
        $contextBookshelfId = session()->get($this->KEY_SHELF_CONTEXT_ID, null);

        if (!is_int($contextBookshelfId)) {
            return null;
        }

        /** @var Bookshelf $shelf */
        $shelf = Bookshelf::visible()->find($contextBookshelfId);
        $shelfContainsBook = $shelf && $shelf->contains($book);

        return $shelfContainsBook ? $shelf : null;
    }

    /**
     * Store the current contextual shelf ID.
     */
    public function setShelfContext(int $shelfId)
    {
        session()->put($this->KEY_SHELF_CONTEXT_ID, $shelfId);
    }

    /**
     * Clear the session stored shelf context id.
     */
    public function clearShelfContext()
    {
        session()->forget($this->KEY_SHELF_CONTEXT_ID);
    }
}


text:
package cherry.foundation.sql;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.io.IOException;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.security.util.InMemoryResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * {@link SqlLoaderImpl} のテスト。
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/applicationContext-test.xml")
public class SqlLoaderImplTest {

	@Autowired
	private SqlLoader sqlLoader;

	@Test
	public void DDLをファイルから読込む() throws IOException {
		Map<String, String> sqlmap = sqlLoader.load(getClass());
		assertEquals("SELECT 1 FROM dual", sqlmap.get("TEST01"));
		assertEquals("SELECT 2 FROM dual", sqlmap.get("TEST02"));
		assertEquals("SELECT 3 FROM dual", sqlmap.get("TEST03"));
		assertEquals("SELECT 4 FROM dual", sqlmap.get("TEST04"));
		assertEquals("SELECT 5 FROM dual", sqlmap.get("TEST05"));
		assertNull(sqlmap.get("TEST06"));
	}

	@Test
	public void DDLをリソースから読込む() throws IOException {
		Resource resource = new InMemoryResource("-- NAME: TEST00\nSELECT 0 FROM dual;");
		Map<String, String> sqlmap = sqlLoader.load(resource);
		assertEquals("SELECT 0 FROM dual", sqlmap.get("TEST00"));
	}

}


text:
//
// Created by raver119 on 10.11.2017.
//

#ifndef LIBND4J_BITWISEUTILS_H
#define LIBND4J_BITWISEUTILS_H
#include <array/ByteOrder.h>
#include <system/op_boilerplate.h>

#include <climits>
#include <vector>

namespace sd {
class SD_LIB_EXPORT BitwiseUtils {
 public:
  /**
   * This method returns first non-zero bit index
   * @param holder
   * @return
   */
  static int valueBit(int holder);

  /**
   *  This method returns vector representation of bits.
   *
   *  PLEASE NOTE: Result is ALWAYS left-to-right
   */
  static std::vector<int> valueBits(int holder);

  /**
   *  This method returns TRUE if it's called on Big-Endian system, and false otherwise
   */
  static bool isBE();

  /**
   * This method returns enum
   * @return
   */
  static sd::ByteOrder asByteOrder();

  /**
   * This method swaps bytes: LE vs BE
   * @tparam T
   * @param v
   * @return
   */
  template <typename T>
  static SD_INLINE T swap_bytes(T v) {
    static_assert(CHAR_BIT == 8, "CHAR_BIT != 8");

    union S {
      T v;
      unsigned char u8[sizeof(T)];
      S(T val) { v = val; }
    };

    S source(v);
    S dest(v);

    for (size_t k = 0; k < sizeof(T); k++) dest.u8[k] = source.u8[sizeof(T) - k - 1];

    return dest.v;
  }

  /**
   * This method flips bits in given value
   *
   * @tparam T
   * @param v
   * @return
   */
  static int SD_INLINE flip_bits(int v) { return ~v; }

  static int8_t SD_INLINE flip_bits(int8_t v) { return ~v; }

  static int16_t SD_INLINE flip_bits(int16_t v) { return ~v; }

  static uint8_t SD_INLINE flip_bits(uint8_t v) { return ~v; }

  static uint16_t SD_INLINE flip_bits(uint16_t v) { return ~v; }

  static uint32_t SD_INLINE flip_bits(uint32_t v) { return ~v; }

  static uint64_t SD_INLINE flip_bits(uint64_t v) { return ~v; }

  static sd::LongType SD_INLINE flip_bits(sd::LongType v) { return ~v; }
};
}  // namespace sd

#endif  // LIBND4J_BITWISEUTILS_H


text:
#include <aws/codecommit/model/DeleteCommentContentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CodeCommit::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteCommentContentRequest::DeleteCommentContentRequest() :
    m_commentIdHasBeenSet(false)
{
}

Aws::String DeleteCommentContentRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_commentIdHasBeenSet)
  {
   payload.WithString("commentId", m_commentId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteCommentContentRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodeCommit_20150413.DeleteCommentContent"));
  return headers;

}


text:
{% extends "shop/base.html" %}
{% load i18n %}

{% block navbar %}

{% trans "Contact Us" %}

{% endblock %}

{% block content %}

{% trans "Contact Information" %}

{% if form.errors %}

    {% blocktrans count form.errors|length as count %}
        Please correct the following error:
        {% plural %}
        Please correct the following errors:
    {% endblocktrans %}

{% endif %}

{% blocktrans %}
We would be honored to answer any questions you may have about our company, product, or people.
Feel free to contact us for any reason whatsoever. Please fill out the form below and we'll
get back to you as soon as we can with an answer.
{% endblocktrans %}

    <form method="post" action=".">{% csrf_token %}
        {{ form.as_p }}

	<input type="submit" value="{% trans "Send Email" %}"/>

    </form>

{% endblock %}


text:
using Xunit;

namespace System.Numerics.Tests
{
    public class remainderTest
    {
        private static int s_samples = 10;
        private static Random s_temp = new Random(-210220377);
        private static Random s_random = new Random(100);

        [Fact]
        public static void RunRemainderPositive()
        {
            byte[] tempByteArray1 = new byte[0];
            byte[] tempByteArray2 = new byte[0];

            // Remainder Method - Two Large BigIntegers
            for (int i = 0; i < s_samples; i++)
            {
                tempByteArray1 = GetRandomByteArray(s_random);
                tempByteArray2 = GetRandomByteArray(s_random);
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");
            }

            // Remainder Method - Two Small BigIntegers
            for (int i = 0; i < s_samples; i++)
            {
                tempByteArray1 = GetRandomByteArray(s_random, 2);
                tempByteArray2 = GetRandomByteArray(s_random, 2);
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");
            }

            // Remainder Method - One large and one small BigIntegers
            for (int i = 0; i < s_samples; i++)
            {
                tempByteArray1 = GetRandomByteArray(s_random);
                tempByteArray2 = GetRandomByteArray(s_random, 2);
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");

                tempByteArray1 = GetRandomByteArray(s_random, 2);
                tempByteArray2 = GetRandomByteArray(s_random);
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");
            }
        }

        [Fact]
        public static void RunRemainderNegative()
        {
            byte[] tempByteArray1 = new byte[0];
            byte[] tempByteArray2 = new byte[0];

            // Remainder Method - One large BigIntegers and zero
            for (int i = 0; i < s_samples; i++)
            {
                tempByteArray1 = GetRandomByteArray(s_random);
                tempByteArray2 = new byte[] { 0 };
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");

                Assert.Throws<DivideByZeroException>(() =>
                {
                    VerifyRemainderString(Print(tempByteArray2) + Print(tempByteArray1) + "bRemainder");
                });
            }

            // Remainder Method - One small BigIntegers and zero
            for (int i = 0; i < s_samples; i++)
            {
                tempByteArray1 = GetRandomByteArray(s_random, 2);
                tempByteArray2 = new byte[] { 0 };
                VerifyRemainderString(Print(tempByteArray1) + Print(tempByteArray2) + "bRemainder");

                Assert.Throws<DivideByZeroException>(() =>
                {
                    VerifyRemainderString(Print(tempByteArray2) + Print(tempByteArray1) + "bRemainder");
                });
            }
        }

        [Fact]
        public static void RunRemainderBoundary()
        {
            byte[] tempByteArray1 = new byte[0];
            byte[] tempByteArray2 = new byte[0];

            // Check interesting cases for boundary conditions
            // You'll either be shifting a 0 or 1 across the boundary
            // 32 bit boundary  n2=0
            VerifyRemainderString(Math.Pow(2, 32) + " 2 bRemainder");

            // 32 bit boundary  n1=0 n2=1
            VerifyRemainderString(Math.Pow(2, 33) + " 2 bRemainder");
        }

        [Fact]
        public static void RunRemainderAxioms()
        {
            byte[] tempByteArray1 = new byte[0];
            byte[] tempByteArray2 = new byte[0];

            // Axiom: X%1 = 0
            VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bRemainder", BigInteger.Zero.ToString());
            VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bRemainder", BigInteger.Zero.ToString());

            for (int i = 0; i < s_samples; i++)
            {
                String randBigInt = Print(GetRandomByteArray(s_random));
                VerifyIdentityString(BigInteger.One + " " + randBigInt + "bRemainder", BigInteger.Zero.ToString());
            }

            // Axiom: 0%X = 0
            VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bRemainder", BigInteger.Zero.ToString());
            VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " bRemainder", BigInteger.Zero.ToString());

            for (int i = 0; i < s_samples; i++)
            {
                String randBigInt = Print(GetRandomByteArray(s_random));
                VerifyIdentityString(randBigInt + BigInteger.Zero + " bRemainder", BigInteger.Zero.ToString());
            }

            // Axiom: X%X = 0
            VerifyIdentityString(Int32.MaxValue + " " + Int32.MaxValue + " bRemainder", BigInteger.Zero.ToString());
            VerifyIdentityString(Int64.MaxValue + " " + Int64.MaxValue + " bRemainder", BigInteger.Zero.ToString());

            for (int i = 0; i < s_samples; i++)
            {
                String randBigInt = Print(GetRandomByteArray(s_random));
                VerifyIdentityString(randBigInt + randBigInt + "bRemainder", BigInteger.Zero.ToString());
            }

            // Axiom: X%(X + Y) = X where Y is 1 if x>=0 and -1 if x<0
            VerifyIdentityString((new BigInteger(Int32.MaxValue) + 1) + " " + Int32.MaxValue + " bRemainder", Int32.MaxValue.ToString());
            VerifyIdentityString((new BigInteger(Int64.MaxValue) + 1) + " " + Int64.MaxValue + " bRemainder", Int64.MaxValue.ToString());

            for (int i = 0; i < s_samples; i++)
            {
                byte[] test = GetRandomByteArray(s_random);
                String randBigInt = Print(test);
                BigInteger modify = new BigInteger(1);
                if ((test[test.Length - 1] & 0x80) != 0)
                {
                    modify = BigInteger.Negate(modify);
                }
                VerifyIdentityString(randBigInt + modify.ToString() + " bAdd " + randBigInt + "bRemainder", randBigInt.Substring(0, randBigInt.Length - 1));
            }
        }

        private static void VerifyRemainderString(string opstring)
        {
            StackCalc sc = new StackCalc(opstring);
            while (sc.DoNextOperation())
            {
                Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
            }
        }

        private static void VerifyIdentityString(string opstring1, string opstring2)
        {
            StackCalc sc1 = new StackCalc(opstring1);
            while (sc1.DoNextOperation())
            {
                //Run the full calculation
                sc1.DoNextOperation();
            }

            StackCalc sc2 = new StackCalc(opstring2);
            while (sc2.DoNextOperation())
            {
                //Run the full calculation
                sc2.DoNextOperation();
            }

            Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
        }

        private static byte[] GetRandomByteArray(Random random)
        {
            return GetRandomByteArray(random, random.Next(1, 100));
        }

        private static byte[] GetRandomByteArray(Random random, int size)
        {
            return MyBigIntImp.GetNonZeroRandomByteArray(random, size);
        }

        private static String Print(byte[] bytes)
        {
            return MyBigIntImp.Print(bytes);
        }
    }
}


text:
package deb

import (
	"archive/tar"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"errors"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"os"
	"sort"
	"strings"

	"github.com/pnelson/archive/ar"
)

var (
	ErrControl = errors.New("archive/deb: empty control file")
	ErrData    = errors.New("archive/deb: empty data file")
	ErrFormat  = errors.New("archive/deb: data format not implemented")
	ErrField   = errors.New("archive/deb: invalid control field")
)

// NewPackage creates a new Package from the file specified by path.
func NewPackage(path string) (*Package, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}

	pkg := &Package{
		Path:   path,
		Name:   fi.Name(),
		Size:   fi.Size(),
		Fields: make(map[string]string),
	}

	ar := ar.NewReader(f)
	for {
		hdr, err := ar.Next()
		if err != nil {
			if err != io.EOF {
				return nil, err
			}
			break
		}

		switch hdr.Name {
		case "control.tar.gz":
			err = pkg.readControl(ar)
		case "data.tar":
			r := tar.NewReader(ar)
			err = pkg.readData(r)
		case "data.tar.bz2":
			r := NewTarBz2Reader(ar)
			err = pkg.readData(r)
		case "data.tar.gz":
			r, err := NewTarGzReader(ar)
			if err != nil {
				if err != io.EOF {
					return nil, err
				}
				return nil, ErrData
			}

			err = pkg.readData(r)
		case "data.tar.lzma":
			err = ErrFormat
		case "data.tar.xz":
			err = ErrFormat
		}

		if err != nil {
			return nil, err
		}
	}

	err = pkg.parseFields()
	if err != nil {
		return nil, err
	}

	err = pkg.generateChecksums()
	if err != nil {
		return nil, err
	}

	sort.Strings(pkg.Files)

	return pkg, nil
}

// Reads raw control data from the package.
func (p *Package) readControl(ar *ar.Reader) error {
	r, err := NewTarGzReader(ar)
	if err != nil {
		if err != io.EOF {
			return err
		}
		return ErrControl
	}

	for {
		hdr, err := r.Next()
		if err != nil {
			if err != io.EOF {
				return err
			}
			break
		}

		buf, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		switch hdr.Name {
		case "./control":
			p.ControlData = string(buf)
		case "./preinst":
			p.PreInstData = string(buf)
		case "./prerm":
			p.PreRmData = string(buf)
		case "./postinst":
			p.PostInstData = string(buf)
		case "./postrm":
			p.PostRmData = string(buf)
		}
	}

	return nil
}

// Reads the data file for a listing of files the package installs.
func (p *Package) readData(r *tar.Reader) error {
	for {
		hdr, err := r.Next()
		if err != nil {
			if err != io.EOF {
				return err
			}
			break
		}

		fi := hdr.FileInfo()
		if !fi.IsDir() {
			p.Files = append(p.Files, hdr.Name)
		}
	}

	return nil
}

// Parses the raw ControlData into individual fields.
func (p *Package) parseFields() error {
	prev := ""
	lines := strings.Split(p.ControlData, "\n")
	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}

		if line[0] == ' ' || line[0] == '\t' {
			p.Fields[prev] += fmt.Sprintf("\n%s", line[1:])
			continue
		}

		parts := strings.SplitN(trimmed, ": ", 2)
		if len(parts) != 2 {
			return ErrField
		}

		key := parts[0]
		value := parts[1]
		p.Fields[key] = value
		prev = key
	}

	return nil
}

// Generates MD5, SHA1, and SHA256 checksums of the package.
func (p *Package) generateChecksums() error {
	buf, err := ioutil.ReadFile(p.Path)
	if err != nil {
		return err
	}

	p.Fields["MD5sum"] = generateChecksum(md5.New(), &buf)
	p.Fields["SHA1"] = generateChecksum(sha1.New(), &buf)
	p.Fields["SHA256"] = generateChecksum(sha256.New(), &buf)

	return nil
}

func generateChecksum(h hash.Hash, b *[]byte) string {
	_, err := h.Write(*b)
	if err != nil {
		return ""
	}
	return fmt.Sprintf("%x", h.Sum(nil))
}


text:
package org.drools.xml.jaxb.util;

import java.util.Arrays;
import java.util.List;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class JaxbListAdapter extends XmlAdapter<JaxbListWrapper, List> {

    @Override
    public JaxbListWrapper marshal(List v) throws Exception {
        if ( v == null ) {
            return new JaxbListWrapper( new Object[0] );
        }
        return new JaxbListWrapper( v.toArray( new Object[v.size()]) );
    }

    @Override
    public List unmarshal(JaxbListWrapper v) throws Exception {
        return Arrays.asList( v.getElements() );
    }

}


text:
#ifndef GLOBAL_ENGINE_CONFIG_HPP
#define GLOBAL_ENGINE_CONFIG_HPP

#include "engine/engine_config.hpp"

namespace osrm
{
using engine::EngineConfig;
}

#endif


text:
layout: page
title: Guardian Tough Trade Award Ceremony
date: 2016-05-24
author: Eugene Haas
tags: weekly links, java
status: published
summary: Sed in ornare purus. Donec libero dolor, maximus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 12/22/2019
  endDate: 12/23/2019
  ctyhocn: PFNBEHX
  groupCode: GTTAC
published: true
---
Cras vitae leo id turpis vehicula bibendum sed quis lectus. Suspendisse id magna ac velit aliquet cursus. Vestibulum nec efficitur est. Duis congue, ipsum sit amet interdum molestie, justo lorem consectetur tellus, vitae aliquam leo metus sit amet libero. Donec gravida accumsan velit vitae porttitor. Nam interdum ante sit amet scelerisque venenatis. Aliquam finibus ac sem faucibus hendrerit. Aenean odio erat, semper in malesuada a, finibus a magna. Suspendisse vel porta ipsum. Nulla vel diam eget sapien varius suscipit quis sed nibh.

* Vivamus eu lacus eu velit volutpat lacinia
* Cras nec metus at nisl auctor iaculis
* Duis viverra orci consequat ante malesuada volutpat
* Nulla scelerisque libero sit amet ex consectetur maximus.

Sed in nibh vel enim molestie laoreet ullamcorper vitae ligula. Suspendisse placerat magna ut augue pretium, at commodo dui lacinia. Nam fermentum blandit odio, a tristique felis rutrum quis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus luctus egestas fringilla. Curabitur vel est a magna aliquam molestie vitae et ex. Cras vitae neque in ante euismod rhoncus. Sed fringilla metus sed facilisis imperdiet. Sed lacinia orci risus, ac hendrerit velit gravida eget.


text:
const DrawCard = require('../../drawcard.js');

class FishmongersSquare extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Draw card and gain gold',
            phase: 'marshal',
            cost: ability.costs.kneelSelf(),
            condition: context => this.opponentDiscardPileHas10() && (context.player.canDraw() || context.player.canGainGold()),
            handler: context => {
                let messageSegments = [];
                if(context.player.canDraw()) {
                    context.player.drawCardsToHand(1);
                    messageSegments.push('draw 1 card');
                }
                if(context.player.canGainGold()) {
                    this.game.addGold(context.player, 1);
                    messageSegments.push('gain 1 gold');
                }
                const message = '{0} kneels {1} to ' + messageSegments.join(' and');
                this.game.addMessage(message, context.player, this);
            }
        });
    }

    opponentDiscardPileHas10() {
        let opponents = this.game.getOpponents(this.controller);
        return opponents.some(opponent => opponent.discardPile.length >= 10);
    }
}

FishmongersSquare.code = '13112';

module.exports = FishmongersSquare;


text:
var assert = require("assert"),
	path = require("path"),
	bundle = require("../lib/graph/make_graph_with_bundles"),
	findbundle = require("../lib/loader/find_bundle"),
	logging = require("../lib/logger"),
	comparify = require("comparify");

describe("find bundle", function () {
	var fakeLoader = {
		baseURL: path.join(__dirname, "bundle")
	};

	it("with given names", function () {
		fakeLoader["bundle"] = ["app_a", "app_b"];
		var bundles = findbundle(fakeLoader);
		assert.deepEqual(["app_a", "app_b"], bundles);
	});

	it("with a glob string", function () {
		fakeLoader["bundle"] = "app_*";
		var bundles = findbundle(fakeLoader);
		assert.deepEqual([
			'app_a',
			'app_b',
			'app_c',
			'app_d'
		], bundles);
	});

	it("wildcard with extension", function() {
		fakeLoader["bundle"] = ["pages/*.component"];
		var bundles = findbundle(fakeLoader);
		assert.deepEqual([
			'pages/cart.component',
		], bundles);
	});

	it("the steal convention trailing slash", function() {
		fakeLoader["bundle"] = ["pages/**/"];
		var bundles = findbundle(fakeLoader);
		assert.deepEqual([
			'pages/home/home',
			'pages/restaurant/list/list'
		], bundles);
	});

	it("trailing slash and wildcard extension", function() {
		fakeLoader["bundle"] = ["pages/**/", "pages/**/*.component"];
		var bundles = findbundle(fakeLoader);
		assert.deepEqual([
			'pages/home/home',
			'pages/restaurant/list/list',
			'pages/cart.component',
			'pages/order/history.component'
		], bundles);
	});
});

describe("bundle", function () {
	beforeEach(function () {
		logging.setup({quiet: true});
	});

	it("should work", function (done) {

		bundle({
			config: __dirname + "/bundle/stealconfig.js",
			main: "bundle",
			logLevel: 3
		}).then(function (data) {
			var graphCompare = require('./bundle/bundle_graph');
			comparify(data.graph, graphCompare, true);
			done();

		}).catch(function (e) {
			done(e)
		});
	});

	it("works with globs", function (done) {
		bundle({
			config: __dirname + "/bundle/stealconfig.js",
			main: "bundle",
			logLevel: 3,
			bundle: "app_*"
		}).then(function (data) {
			var graphCompare = require('./bundle/bundle_graph');
			comparify(data.graph, graphCompare, true);
			done();

		}).catch(function (e) {
			done(e)
		});
	});

	it("localSteal run in 'build' platform", function (done) {
		var system = {
			config: __dirname + "/live_reload/package.json!npm"
		};
		var options = {
			quiet: true
		};
		bundle(system, options).then(function (data) {
			assert.equal('build', data.loader.getPlatform());
			done();
		}).catch(function (e) {
			done(e)
		});
	});

	describe("npm", function () {
		it("with bundle array", function (done) {

			bundle({
				config: __dirname + "/npm-bundle/package.json!npm",
				bundle: [
					"npm-bundle/components/component-1/",
					"npm-bundle/components/component-2/"
				]
			}).then(function (data) {
				var modules = Object.keys(data.graph);
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#components/component-1/component-1"));
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#components/component-2/component-2"));
				done();

			}).catch(function (e) {
				done(e)
			});
		});

		it("with globs in bundle array", function (done) {
			bundle({
				config: __dirname + "/npm-bundle/package.json!npm",
				bundle: [
					"npm-bundle/sites/**/*"
				]
			}).then(function (data) {
				var modules = Object.keys(data.graph);
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#sites/site-1"));
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#sites/site-2"));
				done();

			}).catch(function (e) {
				done(e)
			});
		});

		it("with negative glob patterns", function (done) {
			bundle({
				config: __dirname + "/npm-bundle/package.json!npm",
				bundle: [
					"npm-bundle/components/**/*",
					"!npm-bundle/components/**/*-test.js"
				]
			}).then(function (data) {
				var modules = Object.keys(data.graph);
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#components/component-1/component-1"));
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#components/component-2/component-2"));
				assert.ok(~modules.indexOf("npm-bundle@0.0.1#components/component-3/component-3"));
				assert.ok(!~modules.indexOf("npm-bundle@0.0.1#components/component-3/component-3-test"));
				done();

			}).catch(function (e) {
				done(e)
			});
		})
	});

});