text:
"use strict";

var expect = require('chai').expect,
    mb = require('../lib/musicbrainz'),

	Release = mb.Release,
	ReleaseGroup = mb.ReleaseGroup,
	Recording = mb.Recording,
	Artist = mb.Artist,
	Label = mb.Label,
	Work = mb.Work,
	Disc = mb.Disc;

var testReleaseMbid = '1d9f2d0e-f81d-4ee9-90b4-d2fa8c1f13f0',
	testReleaseGroupMbid = 'eda96b07-480c-3c97-9223-1ead72289dd2',
	testRecordingMbid = '066c13ca-e62b-4b49-ba4e-290e23723e0e',
	testArtistMbid = '11ae9fbb-f3d7-4a47-936f-4c0a04d3b3b5',
	testLabelMbid = '46f0f4cd-8aab-4b33-b698-f459faf64190',
	testWorkMbid = '15d89e06-c8b4-3170-8258-570f0b811273',
	testDiscId = '5RCTaO1Vd7Lv4pwVqo6kk7UVGzs-';

var testBadReleaseMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadReleaseGroupMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadRecordingMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadArtistMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadLabelMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadWorkMbid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
	testBadDiscId = 'discIddiscIddiscId';

var testReleaseQuery = 'Elephant',
    testReleaseSpecialCharsQuery = 'I\'m Not a Fan...But the Kids Like It!',
	testReleaseGroupQuery = '',
	testRecordingQuery = 'Fell In Love With A Girl',
	testArtistQuery = 'The White Stripes',
	testLabelQuery = 'Warp',
	testWorkQuery = 'XX';

var testBadReleaseQuery = 'Uyguyg uiygu ygui',
	testBadReleaseGroupQuery = 'Ugb uhbu yvgg uyv',
	testBadRecordingQuery = '0976087078',
	testBadArtistQuery = 'OIouiyhi ughiug',
	testBadLabelQuery = 'OIjhkopk p;ko',
	testBadWorkQuery = 'OIjhiouhguhuh uh u';

describe('mb', function() {

	describe('#configure', function () {
		it('shouldn\'t crash', function (done) {
			mb.configure({
				baseURI: 'http://musicbrainz.org/ws/2/',
				rateLimit: {
					requests: 2,
					interval: 2000
				}
			});

			done();
		});
	});

	describe('#lookupRelease()', function(){
		it('should find an release by MBID', function (done) {
			mb.lookupRelease(testReleaseMbid, null, function (err, release) {
				if (err) { throw err; }

				expect(release).to.be.an.instanceof(Release);
				expect(release).to.have.property('id').that.equals(testReleaseMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupRelease(testBadReleaseMbid, null, function (err, release) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when MBID is not present', function (done) {
			mb.lookupRelease( '', [], function(err, release){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});
	});

	describe('#lookupReleaseGroup()', function(){
		it('should find an release group by MBID', function (done) {
			mb.lookupReleaseGroup(testReleaseGroupMbid, null, function (err, releaseGroup) {
				if (err) { throw err; }

				expect(releaseGroup).to.be.an.instanceof(ReleaseGroup);
				expect(releaseGroup).to.have.property('id').that.equals(testReleaseGroupMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupReleaseGroup(testBadReleaseMbid, null, function (err, releaseGroup) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when MBID is not present', function (done) {
			mb.lookupReleaseGroup( '', [], function(err, releaseGroup){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#lookupRecording()', function(){
		it('should find an recording by MBID', function (done) {
			mb.lookupRecording(testRecordingMbid, null, function (err, recording) {
				if (err) { throw err; }

				expect(recording).to.be.an.instanceof(Recording);
				expect(recording).to.have.property('id').that.equals(testRecordingMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupRecording(testBadReleaseMbid, null, function (err, recording) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when MBID is not present', function (done) {
			mb.lookupRecording( '', [], function(err, recording){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#lookupArtist()', function(){
		it('should find an artist by MBID', function (done) {
			mb.lookupArtist(testArtistMbid, null, function (err, artist) {
				if (err) { throw err; }

				expect(artist).to.be.an.instanceof(Artist);
				expect(artist).to.have.property('id').that.equals(testArtistMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupArtist(testBadArtistMbid, null, function (err, artist) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when MBID is not present', function (done) {
			mb.lookupArtist( '', [], function(err, artist){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it ('should include aliases when requested and present', function(done) {
			mb.lookupArtist('1bc41dff-5397-4c53-bb50-469d2c277197', ['aliases'], function(err, artist) {
				if (err) { throw err; }

				expect(artist.aliases).to.have.length.above(0);
				done();
			});
		});
	});

	describe('#lookupLabel()', function(){

		it('should find a label by MBID', function (done) {
			mb.lookupLabel(testLabelMbid, null, function (err, label) {
				if (err) { throw err; }

				expect(label).to.be.an.instanceof(Label);
				expect(label).to.have.property('id').that.equals(testLabelMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupLabel(testBadLabelMbid, null, function (err, label) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when MBID is not present', function (done) {
			mb.lookupLabel( '', [], function(err, label){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#lookupWork()', function(){

		it('should find a work by MBID', function (done) {
			mb.lookupWork(testWorkMbid, null, function (err, work) {
				if (err) { throw err; }

				expect(work).to.be.an.instanceof(Work);
				expect(work).to.have.property('id').that.equals(testWorkMbid);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupWork(testBadWorkMbid, null, function (err, work) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when mbid is not present', function (done) {
			mb.lookupWork( '', [], function(err, work){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#lookupDiscId()', function(){
		it('should find a disc its DiscId', function (done) {
			mb.lookupDiscId(testDiscId, null, function (err, disc) {
				if (err) { throw err; }

				expect(disc).to.be.an.instanceof(Disc);
				expect(disc).to.have.property('id').that.equals(testDiscId);
				done();
			});
		});

		it('should return an error with a bad MBID', function (done) {
			mb.lookupDiscId(testBadDiscId, null, function (err, disc) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an error when mbid is not present', function (done) {
			mb.lookupDiscId( '', [], function(err, disc){
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#searchReleases()', function(){
		it('should return an array of releases from a valid query', function (done) {
			mb.searchReleases( testReleaseQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				if (result.length) {
					expect(result[0]).to.be.instanceof(Release);
				}
				done();
			});
		});

		it('should return an empty array from a bad query', function (done) {
			mb.searchReleases( testBadReleaseQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result).to.be.empty;
				done();
			});
		});

		it('should return an error when query is empty', function (done) {
			mb.searchReleases( '', {}, function (err, result) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return an array of a single release from a valid query with 1 result', function(done) {
			mb.searchReleases( "\"From Parts Unknown\"", {
				reid: "7b396f47-71e4-4624-b1e4-92f125b720a1",
			}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				expect(result.length).to.be.eql(1);
				expect(result[0]).to.be.instanceof(Release);
				done();
			});
		});

        it('should return a release even with special characters in the name', function(done) {
            mb.searchReleases( testReleaseSpecialCharsQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result[0]).to.be.instanceof(Release);

                done();
            });
        });

	});

	describe('#searchReleaseGroups()', function(){
		it('should return an array of release groups from a valid query', function (done) {
			mb.searchReleaseGroups( '"I Shall Exterminate Everything Around Me That Restricts Me From Being the Master"', {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				if (result.length) {
					expect(result[0]).to.be.instanceof(ReleaseGroup);
				}
				done();
			});
		});

		it('should return an empty array from a bad query', function (done) {
			mb.searchReleaseGroups( testBadReleaseQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result).to.be.empty;
				done();
			});
		});

		it('should return an error when query is empty', function (done) {
			mb.searchReleaseGroups( '', {}, function (err, result) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it('should return a release even with special characters in the name', function(done) {
			mb.searchReleaseGroups( '"Ænima"', {}, function (err, result) {
			if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result[0]).to.be.instanceof(ReleaseGroup);
				done();
      });
    });

	});

	describe('#searchRecordings()', function(){
		it('should return an array of recordings from a valid query', function (done) {
			mb.searchRecordings( testRecordingQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				if (result.length) {
					expect(result[0]).to.be.instanceof(Recording);
				}
				done();
			});
		});

		it('should return an empty array from a bad query', function (done) {
			mb.searchRecordings( testBadRecordingQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result).to.be.empty;
				done();
			});
		});

		it('should return an array of a single recording from a valid query with 1 result', function(done) {
			mb.searchRecordings( "\"Heart On\"", {
				reid: "0bfb1ff1-a34f-4224-8e90-674aaaa8ad6a",
			}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				expect(result.length).to.be.eql(1);
				expect(result[0]).to.be.instanceof(Recording);
				done();
			});
		});

		it('should return an error when query is empty', function (done) {
			mb.searchRecordings( '', {}, function (err, result) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

	});

	describe('#searchArtists()', function(){
		it('should return an array of artists from a valid query', function (done) {
			mb.searchArtists( testArtistQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				if (result.length) {
					expect(result[0]).to.be.instanceof(Artist);
				}
				done();
			});
		});

		it('should return an array of a single artist from a valid query with 1 result', function(done) {
			mb.searchArtists( "\"Eagles of Death Metal\"", {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);

				expect(result.length).to.be.eql(1);
				expect(result[0]).to.be.instanceof(Artist);
				done();
			});
		});

		it('should return an empty array from a bad query', function (done) {
			mb.searchArtists( testBadArtistQuery, {}, function (err, result) {
				if (err) { throw err; }
				expect(result).to.be.instanceof(Array);
				expect(result).to.be.empty;
				done();
			});
		});

		it('should return an error when query is empty', function (done) {
			mb.searchArtists( '', {}, function (err, result) {
				expect(err).to.be.an.instanceof(Error);
				done();
			});
		});

		it ('should include aliases in results', function(done) {
			mb.searchArtists('"The Dillinger Escape Plan"', {}, function(err, result) {
				if (err) { throw err; }

				expect(result[0].aliases).to.have.length.above(0);
				done();
			});
		});

	});

});

//describe('Release', function(){ });
//describe('ReleaseGroup', function(){ });
//describe('Recording', function(){ });
//describe('Artist', function(){ });
//describe('Label', function(){ });
//describe('Work', function(){ });
//describe('Disc', function(){ });


text:
'use strict';

import * as UrlConstants from './constants/url-constants.js'
import * as UserConstants from './constants/user-constants.js'

module.exports = {
  github: UrlConstants.GITHUB,
  linkedin: UrlConstants.LINKEDIN,
  instagram: UrlConstants.INSTAGRAM,
  email: UserConstants.EMAIL,
  resume: UrlConstants.RESUME
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.aws.ec2.springboot;

import org.apache.camel.CamelContext;
import org.apache.camel.component.aws.ec2.EC2Component;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
public class EC2ComponentAutoConfiguration {

    @Bean(name = "aws-ec2-component")
    @ConditionalOnClass(CamelContext.class)
    @ConditionalOnMissingBean(EC2Component.class)
    public EC2Component configureEC2Component(CamelContext camelContext)
            throws Exception {
        EC2Component component = new EC2Component();
        component.setCamelContext(camelContext);
        return component;
    }
}


text:
package grpclogging

import (
	"github.com/gogo/protobuf/proto"
	"github.com/golang/protobuf/jsonpb"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type protoMarshaler struct {
	jsonpb.Marshaler
	message proto.Message
}

func (m *protoMarshaler) MarshalJSON() ([]byte, error) {
	out, err := m.Marshaler.MarshalToString(m.message)
	if err != nil {
		return nil, err
	}
	return []byte(out), nil
}

func ProtoMessage(key string, val interface{}) zapcore.Field {
	if pm, ok := val.(proto.Message); ok {
		return zap.Reflect(key, &protoMarshaler{message: pm})
	}
	return zap.Any(key, val)
}

func Error(err error) zapcore.Field {
	if err == nil {
		return zap.Skip()
	}

	// Wrap the error so it no longer implements fmt.Formatter. This will prevent
	// zap from adding the "verboseError" field to the log record that includes a
	// full stack trace.
	return zap.Error(struct{ error }{err})
}


text:
require 'spec_helper'

describe Optimizer::Algebra::Summarization, '#summarizers' do
  subject { object.summarizers }

  let(:base)          { Relation.new([[:id, Integer]], [[1]])                            }
  let(:attribute)     { Attribute::Object.new(:test)                                     }
  let(:summarize_per) { TABLE_DEE                                                        }
  let(:relation)      { base.summarize(summarize_per) { |r| r.add(attribute, function) } }
  let(:object)        { described_class.new(relation)                                    }

  before do
    expect(object.operation).to be_kind_of(Algebra::Summarization)
  end

  context 'when summarizers are optimized' do
    let(:function) { base[:id].sum }

    it { should eql(relation.summarizers) }
  end

  context 'when summarizers are not optimized' do
    let(:function) { Aggregate::Sum.new(Function::Numeric::Absolute.new(1)) }

    it { should_not be(relation.summarizers) }

    it { should eql(attribute => Aggregate::Sum.new(1)) }
  end
end


text:
package com.github.ubiquill.calagator.views;

import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.commonsware.cwac.anddown.AndDown;
import com.github.ubiquill.calagator.R;
import com.github.ubiquill.calagator.domain.model.Event;
import com.github.ubiquill.calagator.utils.DateHelper;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Briar Rose Schreiber <ubiquill@riseup.net> on 7/25/15.
 */
public class EventDetailsView {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.eventTitle)
    TextView eventTitle;
    @Bind(R.id.eventDate)
    TextView eventDate;
    @Bind(R.id.eventTime)
    TextView eventTime;
    @Bind(R.id.venueSection)
    LinearLayout venueSection;
    @Bind(R.id.venueName)
    TextView venueName;
    @Bind(R.id.venueAddress)
    TextView venueAddress;
    @Bind(R.id.map)
    ImageView map;
    @Bind(R.id.venueAccessSection)
    LinearLayout venueAccessSection;
    @Bind(R.id.venueAccessInfo)
    TextView venueAccessInfo;
    @Bind(R.id.eventDetails)
    TextView eventDetails;
    @Bind(R.id.bottom_area)
    LinearLayout bottomArea;
    private View view;

    public EventDetailsView(View view) {
        this.view = view;
        ButterKnife.bind(this, view);

        toolbar.setTitle(view.getContext().getResources().getString(R.string.app_name));
    }

    public void bindEvent(Event event) {
        eventTitle.setText(event.getTitle());
        eventDate.setText(event.getStartDate().toString("E, MMM dd"));
        eventTime.setText(DateHelper.getEventTimeString(event));
        bottomArea.setVisibility(View.VISIBLE);
        if (event.getVenue() != null) {
            venueSection.setVisibility(View.VISIBLE);
            venueName.setText(event.getVenue().getTitle());
            venueAddress.setText(event.getVenue().getStreetAddress());

            if (event.getVenue().getStaticMapURL() != null) {
                Glide.with(view.getContext()).load(event.getVenue().getStaticMapURL()).into(map);
            } else {
                map.setVisibility(View.GONE);
            }

            if (event.getVenue().getAccessNotes() != null
                    && event.getVenue().getAccessNotes().length() > 0) {
                venueAccessSection.setVisibility(View.VISIBLE);
                venueAccessInfo.setText(event.getVenue().getAccessNotes());
            } else {
                venueAccessSection.setVisibility(View.GONE);
            }
        } else {
            venueSection.setVisibility(View.GONE);
        }
        AndDown result = new AndDown();
        String html = result.markdownToHtml(event.getDescription());
        eventDetails.setText(Html.fromHtml(html));
    }

}


text:
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Control/Concurrent/Chan/Lifted.hs" #-}

{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts #-}

{-# LANGUAGE Safe #-}

{- |
Module      :  Control.Concurrent.Chan.Lifted
Copyright   :  Liyang HU, Bas van Dijk
License     :  BSD-style

Maintainer  :  Bas van Dijk <v.dijk.bas@gmail.com>
Stability   :  experimental

This is a wrapped version of "Control.Concurrent.Chan" with types
generalised from 'IO' to all monads in 'MonadBase'.

'Chan.unGetChan' and 'Chan.isEmptyChan' are deprecated in @base@, therefore
they are not included here. Use 'Control.Concurrent.STM.TVar' instead.
-}

module Control.Concurrent.Chan.Lifted
    ( Chan
    , newChan
    , writeChan
    , readChan
    , dupChan
    , getChanContents
    , writeList2Chan
    ) where

--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------

-- from base:
import Control.Concurrent.Chan ( Chan )
import qualified Control.Concurrent.Chan as Chan
import System.IO ( IO )
import Prelude ( (.) )

-- from transformers-base:
import Control.Monad.Base ( MonadBase, liftBase )

--------------------------------------------------------------------------------
-- * Chans
--------------------------------------------------------------------------------

-- | Generalized version of 'Chan.newChan'.
newChan :: MonadBase IO m => m (Chan a)
newChan = liftBase Chan.newChan
{-# INLINABLE newChan #-}

-- | Generalized version of 'Chan.writeChan'.
writeChan :: MonadBase IO m => Chan a -> a -> m ()
writeChan chan = liftBase . Chan.writeChan chan
{-# INLINABLE writeChan #-}

-- | Generalized version of 'Chan.readChan'.
readChan :: MonadBase IO m => Chan a -> m a
readChan = liftBase . Chan.readChan
{-# INLINABLE readChan #-}

-- | Generalized version of 'Chan.dupChan'.
dupChan :: MonadBase IO m => Chan a -> m (Chan a)
dupChan = liftBase . Chan.dupChan
{-# INLINABLE dupChan #-}

-- | Generalized version of 'Chan.getChanContents'.
getChanContents :: MonadBase IO m => Chan a -> m [a]
getChanContents = liftBase . Chan.getChanContents
{-# INLINABLE getChanContents #-}

-- | Generalized version of 'Chan.writeList2Chan'.
writeList2Chan :: MonadBase IO m => Chan a -> [a] -> m ()
writeList2Chan chan = liftBase . Chan.writeList2Chan chan
{-# INLINABLE writeList2Chan #-}


text:
package com.edgar.designpattern.more;
public class DDDemo
{
   public static void main(String[] args)
   {
      Asteroid theAsteroid = new Asteroid();
      SpaceShip theSpaceShip = new SpaceShip();
      ApolloSpacecraft theApolloSpacecraft = new ApolloSpacecraft();
      theAsteroid.collideWith(theSpaceShip);
      theAsteroid.collideWith(theApolloSpacecraft);
      System.out.println();

      ExplodingAsteroid theExplodingAsteroid = new ExplodingAsteroid();
      theExplodingAsteroid.collideWith(theSpaceShip);
      theExplodingAsteroid.collideWith(theApolloSpacecraft);
      System.out.println();

      Asteroid theAsteroidReference = theExplodingAsteroid;
      theAsteroidReference.collideWith(theSpaceShip);
      theAsteroidReference.collideWith(theApolloSpacecraft);
      System.out.println();

      SpaceShip theSpaceShipReference = theApolloSpacecraft;
      theAsteroid.collideWith(theSpaceShipReference);
      theAsteroidReference.collideWith(theSpaceShipReference);
      System.out.println();

      theSpaceShipReference = theApolloSpacecraft;
      theAsteroidReference = theExplodingAsteroid;
      theSpaceShipReference.collideWith(theAsteroid);
      theSpaceShipReference.collideWith(theAsteroidReference);
   }
}

class SpaceShip
{
   void collideWith(Asteroid inAsteroid)
   {
      inAsteroid.collideWith(this);
   }
}

class ApolloSpacecraft extends SpaceShip
{
   void collideWith(Asteroid inAsteroid)
   {
      inAsteroid.collideWith(this);
   }
}

class Asteroid
{
   void collideWith(SpaceShip s)
   {
      System.out.println("Asteroid hit a SpaceShip");
   }

   void collideWith(ApolloSpacecraft as)
   {
      System.out.println("Asteroid hit an ApolloSpacecraft");
   }
}

class ExplodingAsteroid extends Asteroid
{
   void collideWith(SpaceShip s)
   {
      System.out.println("ExplodingAsteroid hit a SpaceShip");
   }

   void collideWith(ApolloSpacecraft as)
   {
      System.out.println("ExplodingAsteroid hit an ApolloSpacecraft");
   }
}


text:
<?php

namespace phpSweetPDO\SQLHelpers;

/**
 * Class with basic helpers to build some SQL operators easily
 */

class Basic
{
    /**
     * INSERT INTO helper routine. Example of use:
     *
     *
     * <?php
     * $connection->execute(
     *  BasicHelpers::insert("mytable", array("name" => "John Smith"))
     * );
     *
     *
     * It will execute "INSERT INTO mytable (name) VALUES("John Smith")"
     *
     * @static
     * @param string $tablename Name of the table to which to insert the data
     * @param array $data Associative array of fieldName => fieldValue to insert into table
     * @return array Generated SQL statement and data for it
     *
     */
    public static function insert($tablename, array $data)
    {
        return self::makeValuesSQL('INSERT INTO ', $tablename, $data);
    }

    /**
     * REPLACE INTO helper routine. Example of use:
     *
     *
     * <?php
     * $connection->execute(
     *  BasicHelpers::replace("mytable", array("name" => "John Smith"))
     * );
     *
     *
     * It will execute "REPLACE INTO mytable (name) VALUES("John Smith")"
     *
     * @static
     * @param string $tablename Name of the table to which to insert the data
     * @param array $data Associative array of fieldName => fieldValue to insert into table
     * @return array Generated SQL statement and data for it
     *
     */
    public static function replace($tablename, array $data)
    {
        return self::makeValuesSQL('REPLACE INTO ', $tablename, $data);
    }

    /**
     * Forms an SQL operator in form $operator $tablename (fields...) VALUES (data...)
     *
     * Used in INSERT and REPLACE statements construction
     *
     * @static
     * @param string $operator
     * @param string $tablename
     * @param array $data
     * @return array Generated SQL statement and data for it
     */
    protected static function makeValuesSQL($operator, $tablename, array $data)
    {
        //Forming initial SQL skeleton INSERT INTO table(field1, field2,...) VAlUES(
        $sql = $operator . ' `' . $tablename . '` (' . implode(', ', array_keys($data)) . ') VALUES (';

        //Now making a parameter for each field (field1 => :field1...)
        $sqlFieldParams = array();
        foreach ($data as $fieldName => $fieldValue) {
            $sqlFieldParams [] = ':' . $fieldName;
        }

        //Listing params
        $sql .= implode(', ', $sqlFieldParams) . ')';

        return array(
            $sql,
            $data
        );
    }

    /**
     * Update helper rountine. Example of use:
     *
     *
     * <?php
     * $connection->execute(BasicHelpers::update("mytable", array("name" => "John Smith"), "userid=1"));
     *
     *
     * @param string $tablename Name of the table to which to insert the data
     * @param array $data Associative array of fieldName => fieldValue to update on table
     * @param bool|string $criteria WHERE part of the query (without 'WHERE' keyword itself)
     * @return string Generated SQL statement
     *
     */
    public static function update($tablename, array $data, $criteria = false)
    {
        $sql = 'UPDATE `' . $tablename . '` SET ';
        $sqlFieldParams = array();
        foreach ($data as $fieldName => $fieldValue) {
            $sqlFieldParams [] = $fieldName . '=:' . $fieldName;
        }
        $sql .= implode(', ', $sqlFieldParams) . ($criteria ? ' WHERE ' . $criteria : "");

        return array(
            $sql,
            $data
        );
    }

    /**
     * Insert helper routine. Example of use:
     *
     *
     * <?php
     * $connection->execute(BasicHelpers::insert("mytable", array("name" => "John Smith")));
     *
     *
     * @param string $tablename Name of the table to which to insert the data
     * @param array $data Associative array of fieldName => fieldValue to insert into table
     * @return string Generated SQL statement
     *
     */
    public static function insertOnDuplicateKeyUpdate($tablename, array $data)
    {

        //Forming initial SQL skeleton INSERT INTO table(field1, field2,...) VAlUES(
        $sql = 'INSERT INTO `' . $tablename . '` (' . implode(', ', array_keys($data)) . ') VALUES (';

        //Now making a parameter for each field (field1 => :field1...)
        $sqlFieldParams = array();
        foreach ($data as $fieldName => $fieldValue) {
            $sqlFieldParams [] = ':' . $fieldName;
        }

        //Listing params
        $sql .= implode(', ', $sqlFieldParams);
        $sql .= ')';

        //ON DUPLICATE KEY UPDATE
        $sql .= ' ON DUPLICATE KEY UPDATE ';

        $sqlFieldParams = array();
        foreach ($data as $fieldName => $fieldValue) {
            $sqlFieldParams [] = "{$fieldName} = :{$fieldName}";
        }

        $sql .= implode(', ', $sqlFieldParams);

        return array(
            $sql,
            $data
        );
    }
}


text:
var Handlebars = require('handlebars');

module.exports = function (context, pattern, options) {
  var match = new RegExp(pattern).test(context);
  if(match) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
};

Handlebars.registerHelper('test', function (context, pattern, options) {
  var match = new RegExp(pattern).test(context);
  if(match) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:id="@id/download" android:oneshot="false"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:duration="@integer/play_download_download_frame_ms" android:drawable="@drawable/play_ic_dl_l_download_00000" />
    <item android:duration="@integer/play_download_download_frame_ms" android:drawable="@drawable/play_ic_dl_l_download_00001" />
    <item android:duration="@integer/play_download_download_frame_ms" android:drawable="@drawable/play_ic_dl_l_download_00002" />
    <item android:duration="@integer/play_download_download_frame_ms" android:drawable="@drawable/play_ic_dl_l_download_00003" />
    <item android:duration="@integer/play_download_download_frame_ms" android:drawable="@drawable/play_ic_dl_l_download_00004" />
</animation-list>


text:
/*  ConfigurableMapViewerCMV
 *  version 2.0.0-beta.1
 *  Project: http://cmv.io/
 */

define({noLegend:"Sem legenda",moveUp:"Mover para cima",moveDown:"Mover para baixo",zoomTo:"Aproximar à Camada",transparency:"Transparência",metadata:"Metadados",layerSwipe:"Deslizar camada",layerSwipeVertical:"Vertical",layerSwipeHorizontal:"Horizontal",layerSwipeScope:"Janela",dynamicSublayersOn:"Activar todas as subcamadas",dynamicSublayersOff:"Desligar todas as subcamadas"});
//# sourceMappingURL=resource.js.map


text:
<!DOCTYPE html>

	<title>Overview Example</title>
	<meta charset="utf8"/>

cEngine.js

		Welcome! cEngine.js is a small canvas-engine for javascript. This page features examples for the core engine, as well as the plugins included.

1. Simple canvas drawing

		In this example, we create a new instance of cEngine.js and run one step to draw a square.

	Go to the simple canvas drawing example >

var engine = cEngine.create({
  step: function (context) {
    context.fillStyle = 'red'
    context.fillRect(10, 10, 10, 10)
  }
}).step()

2. Plugin activityTracker

		This example features the activityTracker, which stops the engine when the user loses focus of the window. This plugin will restart the engine when the user focuses on the window.

	Go to the activityTracker example >

var engine = cEngine.create({
  plugins: {
    activityTracker: cEngine.activityTracker.create({
      stopOnUserLeave: true
    })
  },
  autoClear: true,
  step: function(context, width, height, dt){
    context.fillStyle = 'red'
    context.fillRect(Math.random()*20, Math.random()*20, 10, 10)
  }
}).start()

3. Plugin fill

	Go to fill example >

var engine = cEngine.create({
  autoClear: true,
  height: 512,
  plugins: {
    fill: cEngine.fill.create({
      mode: 'stretch',
      aspectRetion: true
    })
  },
  step: function(context, width, height){
    context.fillStyle = context.fillStyle === 'red' ? 'blue': 'red'
    context.fillRect(width * Math.random(), height * Math.random(), 10, 10)
  }
})

engine.start()

Plugin filter

	Go to filter example >

Code see example page

Filter-App

	Go to Filter-App >

Plugin frameRate

	Go to frameRate example >

Code see example page

Plugin input

	Go to input example >

Code see example page

Plugin stats

	Go to stats example >

var obj = { x: 50, y: 50 };

var engine = cEngine.create({
  autoClear: true,
  plugins: {
    stats: cEngine.stats.create(),
    filter: cEngine.filter.create({
      filters: [{
        Shader: cEngine.filter.Shader.greyscale
      }]
    })
  },
  step: function(context){
    obj.x += (Math.random() - 0.5) * 10
    obj.y += (Math.random() - 0.5) * 10
    context.fillStyle = 'red'
    context.fillRect(obj.x, obj.y, 10, 10)
  }
}).start()

		Coded with love by Rene Müller, see more at https://renmuell.github.io/.


text:
@interface PodsDummy_Kommander_tvOS : NSObject
@end
@implementation PodsDummy_Kommander_tvOS
@end


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Portfolio\Display\Component;

use Chamilo\Core\Repository\Form\ContentObjectForm;
use Chamilo\Core\Repository\Integration\Chamilo\Core\Tracking\Storage\DataClass\Activity;
use Chamilo\Core\Repository\Storage\DataClass\ComplexContentObjectItem;
use Chamilo\Core\Repository\Workspace\PersonalWorkspace;
use Chamilo\Core\Tracking\Storage\DataClass\Event;
use Chamilo\Libraries\Architecture\Exceptions\NotAllowedException;
use Chamilo\Libraries\Format\Structure\Breadcrumb;
use Chamilo\Libraries\Format\Structure\BreadcrumbTrail;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;
use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable;
use Chamilo\Libraries\Utilities\Utilities;

/**
 * Component that allows the user to update the content of a portfolio item or folder
 *
 * @package repository\content_object\portfolio\display
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 */
class UpdaterComponent extends ItemComponent
{

    /**
     * Executes this component
     */
    public function build()
    {
        if ($this->canEditComplexContentObjectPathNode($this->get_current_node()))
        {
            $selected_complex_content_object_item = $this->get_current_complex_content_object_item();
            $content_object = $this->get_current_content_object();

            $form = ContentObjectForm::factory(
                ContentObjectForm::TYPE_EDIT,
                new PersonalWorkspace($this->get_user()),
                $content_object,
                'edit',
                'post',
                $this->get_url(
                    array(
                        self::PARAM_ACTION => self::ACTION_UPDATE_COMPLEX_CONTENT_OBJECT_ITEM,
                        self::PARAM_STEP => $this->get_current_step())));

            if ($form->validate())
            {
                $succes = $form->update_content_object();

                if ($succes)
                {
                    Event::trigger(
                        'Activity',
                        \Chamilo\Core\Repository\Manager::context(),
                        array(
                            Activity::PROPERTY_TYPE => Activity::ACTIVITY_UPDATED,
                            Activity::PROPERTY_USER_ID => $this->get_user_id(),
                            Activity::PROPERTY_DATE => time(),
                            Activity::PROPERTY_CONTENT_OBJECT_ID => $content_object->get_id(),
                            Activity::PROPERTY_CONTENT => $content_object->get_title()));
                }

                if ($succes && $form->is_version())
                {
                    $old_id = $selected_complex_content_object_item->get_ref();
                    $new_id = $content_object->get_latest_version()->get_id();
                    $selected_complex_content_object_item->set_ref($new_id);
                    $selected_complex_content_object_item->update();

                    $condition = new EqualityCondition(
                        new PropertyConditionVariable(
                            ComplexContentObjectItem::class_name(),
                            ComplexContentObjectItem::PROPERTY_PARENT),
                        new StaticConditionVariable($old_id),
                        ComplexContentObjectItem::get_table_name());
                    $parameters = new DataClassRetrievesParameters($condition);
                    $children = \Chamilo\Core\Repository\Storage\DataManager::retrieve_complex_content_object_items(
                        ComplexContentObjectItem::class_name(),
                        $parameters);

                    $failures = 0;

                    while ($child = $children->next_result())
                    {
                        $child->set_parent($new_id);

                        if (! $child->update())
                        {
                            $failures ++;
                        }
                    }

                    $succes = ($succes) && ($failures == 0);
                }

                $message = htmlentities(
                    Translation::get(
                        ($succes ? 'ObjectUpdated' : 'ObjectNotUpdated'),
                        array('OBJECT' => Translation::get('ContentObject')),
                        Utilities::COMMON_LIBRARIES));

                $params = array();
                $params[self::PARAM_COMPLEX_CONTENT_OBJECT_ITEM_ID] = $this->get_complex_content_object_item_id();
                $params[self::PARAM_ACTION] = self::ACTION_VIEW_COMPLEX_CONTENT_OBJECT;

                $this->redirect($message, (! $succes), $params);
            }
            else
            {
                if ($this->get_current_node()->is_root())
                {
                    $title = Translation::get('ChangeIntroduction');
                }
                else
                {
                    $title = Translation::get('EditContentObject');
                }

                $trail = BreadcrumbTrail::getInstance();
                $trail->add(
                    new Breadcrumb($this->get_url(array(self::PARAM_STEP => $this->get_current_step())), $title));

                $html = array();

                $html[] = $this->render_header();
                $html[] = $form->toHtml();
                $html[] = $this->render_footer();

                return implode(PHP_EOL, $html);
            }
        }
        else
        {
            throw new NotAllowedException();
        }
    }

    /**
     *
     * @see \libraries\SubManager::get_additional_parameters()
     */
    public function get_additional_parameters()
    {
        return array(self::PARAM_STEP);
    }
}


text:
import {expect} from 'chai'
import {setupComponentTest} from 'ember-mocha'
import {
  helpers,
  settings as propTypesSettings
} from 'ember-prop-types/mixins/prop-types'
import {afterEach, beforeEach, describe, it} from 'mocha'
const {validatePropTypes} = helpers

describe('Unit / Component / frost-file-picker /', function () {
  setupComponentTest('frost-file-picker', {unit: true})

  let component
  beforeEach(function () {
    component = this.subject({accept: '*'})
  })

  describe('`proptypes` validation', function () {
    let throwErrors

    beforeEach(function () {
      // save our real settings so that we can force validation,
      // in case our environment.js ever decides that such validation should be optional.
      throwErrors = propTypesSettings.throwErrors
      propTypesSettings.throwErrors = true
    })

    afterEach(function () {
      propTypesSettings.throwErrors = throwErrors
    })

    it('should have valid `proptypes` declaration', function () {
      expect(function () {
        validatePropTypes(component)
      }).to.not.throw()
    })
  })
})


text:
import json
import inspect

try:
    from itertools import imap as map  # PY2
except ImportError:
    pass

import tornado.web
from jsonschema import validate, ValidationError

from tornado_json.utils import is_method
from tornado_json.constants import HTTP_METHODS
from tornado_json.requesthandlers import APIHandler

def _validate_example(rh, method, example_type):
    """Validates example against schema

    :returns: Formatted example if example exists and validates, otherwise None
    :raises ValidationError: If example does not validate against the schema
    """
    example = getattr(method, example_type + "_example")
    schema = getattr(method, example_type + "_schema")

    if example is None:
        return None

    try:
        validate(example, schema)
    except ValidationError as e:
        raise ValidationError(
            "{}_example for {}.{} could not be validated.\n{}".format(
                example_type, rh.__name__, method.__name__, str(e)
            )
        )

    return json.dumps(example, indent=4, sort_keys=True)

def _get_rh_methods(rh):
    """Yield all HTTP methods in ``rh`` that are decorated
    with schema.validate"""
    for k, v in vars(rh).items():
        if all([
            k in HTTP_METHODS,
            is_method(v),
            hasattr(v, "input_schema")
        ]):
            yield (k, v)

def _get_tuple_from_route(route):
    """Return (pattern, handler_class) tuple from ``route``

    :type route: tuple|tornado.web.URLSpec
    :rtype: tuple
    :raises TypeError: If ``route`` is not a tuple or URLSpec
    """
    if isinstance(route, tuple):
        assert len(route) >= 2
        pattern, handler_class = route[:2]
    elif isinstance(route, tornado.web.URLSpec):
        pattern, handler_class = route.regex.pattern, route.handler_class
    else:
        raise TypeError("Unknown route type '{}'"
                        .format(type(route).__name__))
    return pattern, handler_class

def _escape_markdown_literals(string):
    """Escape any markdown literals in ``string`` by prepending with \\

    :type string: str
    :rtype: str
    """
    literals = list("\\`*_{}[]()<>#+-.!:|")
    escape = lambda c: '\\' + c if c in literals else c
    return "".join(map(escape, string))

def _cleandoc(doc):
    """Remove uniform indents from ``doc`` lines that are not empty

    :returns: Cleaned ``doc``
    """
    indent_length = lambda s: len(s) - len(s.lstrip(" "))
    not_empty = lambda s: s != ""

    lines = doc.split("\n")
    indent = min(map(indent_length, filter(not_empty, lines)))

    return "\n".join(s[indent:] for s in lines)

def _add_indent(string, indent):
    """Add indent of ``indent`` spaces to ``string.split("\n")[1:]``

    Useful for formatting in strings to already indented blocks
    """
    lines = string.split("\n")
    first, lines = lines[0], lines[1:]
    lines = ["{indent}{s}".format(indent=" " * indent, s=s)
             for s in lines]
    lines = [first] + lines
    return "\n".join(lines)

def _get_example_doc(rh, method, type):
    assert type in ("input", "output")

    example = _validate_example(rh, method, type)
    if not example:
        return ""
    res = """
    **{type} Example**
    ```json
    {example}
    ```
    """.format(
        type=type.capitalize(),
        example=_add_indent(example, 4)
    )
    return _cleandoc(res)

def _get_input_example(rh, method):
    return _get_example_doc(rh, method, "input")

def _get_output_example(rh, method):
    return _get_example_doc(rh, method, "output")

def _get_schema_doc(schema, type):
    res = """
    **{type} Schema**
    ```json
    {schema}
    ```
    """.format(
        schema=_add_indent(json.dumps(schema, indent=4, sort_keys=True), 4),
        type=type.capitalize()
    )
    return _cleandoc(res)

def _get_input_schema_doc(method):
    return _get_schema_doc(method.input_schema, "input")

def _get_output_schema_doc(method):
    return _get_schema_doc(method.output_schema, "output")

def _get_notes(method):
    res = """
    **Notes**

    {}
    """.format(
        _add_indent(inspect.getdoc(method), 4)
    )
    return _cleandoc(res)

def _get_method_doc(rh, method_name, method):
    res = """## {method_name}

    {input_schema}
    {input_example}
    {output_schema}
    {output_example}
    {notes}
    """.format(
        method_name=method_name.upper(),
        input_schema=_get_input_schema_doc(method),
        output_schema=_get_output_schema_doc(method),
        notes=_get_notes(method),
        input_example=_get_input_example(rh, method),
        output_example=_get_output_example(rh, method),
    )
    return _cleandoc("\n".join([l.rstrip() for l in res.splitlines()]))

def _get_rh_doc(rh):
    res = "\n\n".join([_get_method_doc(rh, method_name, method)
                       for method_name, method in _get_rh_methods(rh)])
    return res

def _get_content_type(rh):
    # XXX: Content-type is hard-coded but ideally should be retrieved;
    #  the hard part is, we don't know what it is without initializing
    #  an instance, so just leave as-is for now
    return "Content-Type: application/json"

def _get_route_doc(url, rh):
    route_doc = """
    # {route_pattern}

        {content_type}

    {rh_doc}
    """.format(
        route_pattern=_escape_markdown_literals(url),
        content_type=_get_content_type(rh),
        rh_doc=_add_indent(_get_rh_doc(rh), 4)
    )
    return _cleandoc(route_doc)

def _write_docs_to_file(documentation):
    # Documentation is written to the root folder
    with open("API_Documentation.md", "w+") as f:
        f.write(documentation)

def get_api_docs(routes):
    """
    Generates GitHub Markdown formatted API documentation using
    provided schemas in RequestHandler methods and their docstrings.

    :type  routes: [(url, RequestHandler), ...]
    :param routes: List of routes (this is ideally all possible routes of the
        app)
    :rtype: str
    :returns: generated GFM-formatted documentation
    """
    routes = map(_get_tuple_from_route, routes)

    documentation = []
    for url, rh in sorted(routes, key=lambda a: a[0]):
        if issubclass(rh, APIHandler):
            documentation.append(_get_route_doc(url, rh))

    documentation = (
        "**This documentation is automatically generated.**\n\n" +
        "**Output schemas only represent `data` and not the full output; " +
        "see output examples and the JSend specification.**\n" +
        "\n
\n
\n".join(documentation)
    )
    return documentation

def api_doc_gen(routes):
    """Get and write API documentation for ``routes`` to file"""
    documentation = get_api_docs(routes)
    _write_docs_to_file(documentation)


text:
define(function(require, exports, module) {

  'use strict';

  var React = require('react');
  var Q = require('q');

  var events = require('events');
  var mixins = require('mixins');
  var Path = require('path');
  var NodeCount = require('node-count');
  var FastaPreview = require('fasta-preview');

  var d = React.DOM;
  var syncro = 0;

  // TODO: move to own file.
  var labelCols = 'col-sm-4';
  var controlCols = 'col-sm-8';

  module.exports = React.createClass({
    displayName: 'FastaOptions',

    mixins: [mixins.ComputableState],

    getInitialState: function () {
      return {exportableNodes: []};
    },

    queryIsNew: function (query) {
      var thisQuery = query.toXML();
      var isDifferent = thisQuery !== this.state.currentQuery;
      this.setState({currentQuery: thisQuery});
      return isDifferent;
    },

    computeState: function (props) {
      if (!this.queryIsNew(props.query)) return;

      var columns = props.query.getViewNodes().map(function (p, i) {
          return {path: p, index: i, selected: i === 0};
      });
      this.setState({
        exportableNodes: columns.filter(function (c) { // Diff here.
          return c.path.isa('SequenceFeature') || c.path.isa('Protein');
        })
      });
    },

    renderExportableNode: function (node) {
      var that = this;
      return d.button(
          {
            key: node.path.toString(),
            onClick: function () {
              var state = that.state; // Diff here.
              state.exportableNodes.forEach(function (n) {
                n.selected = false;
              });
              node.selected = !node.selected;
              that.setState(state);
            },
            className: 'btn btn-default' + (node.selected ? ' active' : '')
          },
          Path(node));
    },

    render: function () {
      var exportableNodes = this.state.exportableNodes;
      var preview = this.renderPreview();
      return d.form(
          {className: 'form-horizontal', onSubmit: events.preventDefault},
          d.div({className: 'row'},
            d.div({className: 'col-sm-6'},
              d.div(
                {className: 'form-group'},
                d.label({className: labelCols + ' control-label'},
                  'Exported Items'),
                d.div(
                  {className: 'btn-group ' + controlCols},
                  exportableNodes.map(this.renderExportableNode)))),
            NodeCount({
              mine: this.props.mine,
              query: this.props.query,
              nodes: exportableNodes.filter(to('selected')).map(to('path')),
              what: 'Sequence' // Diff here
            })),
          preview);
    },

    renderPreview: function () {
      return FastaPreview({ // Diff here.
        mine: this.props.mine,
        query: this.props.query,
        nodes: this.state.exportableNodes.filter(to('selected')).map(to('path'))
      });
    }
  });

  function to (y) {
    return function (x) {
      return x && x[y];
    }
  }

});


text:
<?php

namespace ApiBundle\Api\Resource\OrderInfo;

use ApiBundle\Api\ApiRequest;
use ApiBundle\Api\Exception\ErrorCode;
use ApiBundle\Api\Resource\AbstractResource;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class OrderInfo extends AbstractResource
{
    public function add(ApiRequest $request)
    {
        $params = $request->request->all();

        if (empty($params['targetId']) || empty($params['targetType'])) {
            throw new BadRequestHttpException('缺少参数', null, ErrorCode::INVALID_ARGUMENT);
        }

        $this->addVipParams($params);

        list($checkInfo, $orderInfo) = $this->service('Order:OrderFacadeService')->getOrderInfo($params['targetType'], $params['targetId'], $params);

        if (isset($checkInfo['error'])) {
            throw new BadRequestHttpException($checkInfo['error'], null, ErrorCode::INVALID_ARGUMENT);
        }

        $this->addOrderAssocInfo($orderInfo);

        return $orderInfo;
    }

    private function addVipParams(&$params)
    {
        if ($params['targetType'] == 'vip') {
            $vipSetting = $this->service('System:SettingService')->get('vip');
            $defaultUnitType = 'month';
            $defaultDuration = 3;
            if ($vipSetting && !empty($vipSetting['buyType'])) {
                if ($vipSetting['buyType'] == '10') {
                    $defaultDuration = $vipSetting['default_buy_months10'];
                    //按年
                } elseif ($vipSetting['buyType'] == '20') {
                    $defaultUnitType = 'year';
                    $defaultDuration = $vipSetting['default_buy_years'];
                    //按月
                } else {
                    $defaultDuration = $vipSetting['default_buy_months'];
                }
            }

            $params['unit'] = $defaultUnitType;
            $params['duration'] = $defaultDuration;
        }
    }

    private function addOrderAssocInfo(&$orderInfo)
    {
        $orderInfo['availableCoupons'] = $this->service('Card:CardService')->findCurrentUserAvailableCouponForTargetTypeAndTargetId(
            $orderInfo['targetType'], $orderInfo['targetId']
        );

        $coinSetting = $this->service('System:SettingService')->get('coin');

        if (!empty($coinSetting['coin_name'])) {
            $orderInfo['coinName'] = $coinSetting['coin_name'];
        } else {
            $orderInfo['coinName'] = '虚拟币';
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0009_alter_order_rfidcard'),
    ]

    operations = [
        migrations.AlterField(
            model_name='order',
            name='amount',
            field=models.DecimalField(default=0, verbose_name='amount', max_digits=15, decimal_places=2),
            preserve_default=False,
        ),
    ]


text:
package pl.edu.ug.introductiontojee.jpa.jpql.datessearch.domain;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
import java.util.List;

@Stateless
public class MessageStorageService {
    @PersistenceContext
    EntityManager em;

    public Message get(Long id) {
        return em.find(Message.class, id);
    }

    public void add(Message message) {
        message.setId(null);
        message.setCreatedAt(new Date());

        em.persist(message);
    }

    public void update(Long id, String title, String message) {
        Message msg = em.find(Message.class, id);
        msg.setTitle(title);
        msg.setMessage(message);

        em.merge(msg);
    }

    public void delete(Long id) {
        Message message = em.find(Message.class, id);
        em.remove(message);
    }

    public List<Message> getAllMessages(){
        //noinspection unchecked
        return em.createNamedQuery("message.all").getResultList();
    }

    public List<Message> getMessages(int offset, int limit){
        //noinspection unchecked
        return em.createNamedQuery("message.all").
                setFirstResult(offset).
                setMaxResults(limit).
                getResultList();
    }

    public Long getCount() {
        return (Long) em.createQuery("select count(m) from Message m").getSingleResult();
    }

    public List<Message> getBetweenDates(Date from, Date to) {
        //noinspection unchecked
        return em.createQuery("select m from Message m where m.createdAt BETWEEN :from AND :to")
                .setParameter("from", from)
                .setParameter("to", to)
                .getResultList();
    }

    public List<Message> getAfterDate(Date date) {
        //noinspection unchecked
        return em.createQuery("select m from Message m where m.createdAt > :date")
                .setParameter("date", date)
                .getResultList();
    }

    public List<Message> getBeforeDate(Date date) {
        //noinspection unchecked
        return em.createQuery("select m from Message m where m.createdAt < :date")
                .setParameter("date", date)
                .getResultList();
    }
}


text:
package android

import (
	"fmt"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/beevik/etree"
	"github.com/bitrise-io/bitrise-init/models"
	"github.com/bitrise-io/bitrise-init/utility"
	"github.com/bitrise-io/go-utils/log"
	"github.com/bitrise-io/go-utils/sliceutil"
)

type icon struct {
	prefix       string
	fileNameBase string
}

func lookupIconName(manifestPth string) ([]icon, error) {
	doc := etree.NewDocument()
	if err := doc.ReadFromFile(manifestPth); err != nil {
		return nil, err
	}

	log.Debugf("Looking for app icons. Manifest path: %s", manifestPth)
	parsedIcons, err := parseIconName(doc)
	if err != nil {
		return nil, err
	}

	return parsedIcons, nil
}

// parseIconName fetches icon name from AndroidManifest.xml.
func parseIconName(doc *etree.Document) ([]icon, error) {
	man := doc.SelectElement("manifest")
	if man == nil {
		log.Debugf("Key manifest not found in manifest file")
		return nil, nil
	}
	app := man.SelectElement("application")
	if app == nil {
		log.Debugf("Key application not found in manifest file")
		return nil, nil
	}
	ic := app.SelectAttr("android:icon")
	if ic == nil {
		log.Debugf("Attribute not found in manifest file")
		return nil, nil
	}

	iconPathParts := strings.Split(strings.TrimPrefix(ic.Value, "@"), "/")
	if len(iconPathParts) != 2 {
		return nil, fmt.Errorf("unsupported icon key (%s)", ic.Value)
	}
	return []icon{{
		prefix:       iconPathParts[0],
		fileNameBase: iconPathParts[1],
	}}, nil
}

func lookupIconPaths(resPth string, icon icon) ([]string, error) {
	var resourceSuffixes = [...]string{"xxxhdpi", "xxhdpi", "xhdpi", "hdpi", "mdpi", "ldpi"}
	resourceDirs := make([]string, len(resourceSuffixes))
	for _, mipmapSuffix := range resourceSuffixes {
		resourceDirs = append(resourceDirs, icon.prefix+"-"+mipmapSuffix)
	}

	for _, dir := range resourceDirs {
		iconPaths, err := filepath.Glob(filepath.Join(regexp.QuoteMeta(resPth), dir, icon.fileNameBase+".png"))
		if err != nil {
			return nil, err
		}
		if len(iconPaths) != 0 {
			return iconPaths, nil
		}
	}
	return nil, nil
}

func lookupIcons(projectDir string, basepath string) ([]string, error) {
	variantPaths := filepath.Join(regexp.QuoteMeta(projectDir), "*", "src", "*")
	manifestPaths, err := filepath.Glob(filepath.Join(variantPaths, "AndroidManifest.xml"))
	if err != nil {
		return nil, err
	}
	resourcesPaths, err := filepath.Glob(filepath.Join(variantPaths, "res"))
	if err != nil {
		return nil, err
	}

	// falling back to standard icon name, if not found in manifest
	iconNames := []icon{
		{
			prefix:       "mipmap",
			fileNameBase: "ic_launcher",
		},
		{
			prefix:       "mipmap",
			fileNameBase: "ic_launcher_round",
		},
	}
	for _, manifestPath := range manifestPaths {
		icons, err := lookupIconName(manifestPath)
		if err != nil {
			return nil, err
		}
		iconNames = append(iconNames, icons...)
	}

	var iconPaths []string
	for _, resourcesPath := range resourcesPaths {
		for _, icon := range iconNames {
			foundIconPaths, err := lookupIconPaths(resourcesPath, icon)
			if err != nil {
				return nil, err
			}
			iconPaths = append(iconPaths, foundIconPaths...)
		}
	}
	return sliceutil.UniqueStringSlice(iconPaths), nil
}

// LookupIcons returns the largest resolution for all potential android icons.
func LookupIcons(projectDir string, basepath string) (models.Icons, error) {
	iconPaths, err := lookupIcons(projectDir, basepath)
	if err != nil {
		return nil, err
	}
	return utility.CreateIconDescriptors(iconPaths, basepath)
}


text:
import { join } from 'path';

import { SeedConfig } from './seed.config';
// import { ExtendPackages } from './seed.config.interfaces';

/**
 * This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
 * below.
 */
export class ProjectConfig extends SeedConfig {

  PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');

  ENABLE_SCSS = true;

  constructor() {
    super();
        this.APP_TITLE = 'League of Data';
    // this.GOOGLE_ANALYTICS_ID = 'Your site's ID';

    /* Enable typeless compiler runs (faster) between typed compiler runs. */
    // this.TYPED_COMPILE_INTERVAL = 5;

    // Add `NPM` third-party libraries to be injected/bundled.
    this.NPM_DEPENDENCIES = [
        ...this.NPM_DEPENDENCIES,
        {src: 'jquery/dist/jquery.min.js', inject: 'libs'},
        //{src: 'semantic-ui/dist/semantic.min.css', inject: true},
        //{src: 'semantic-ui/dist/semantic.min.js', inject: 'libs'},
        {src: 'chart.js/dist/Chart.min.js', inject: 'libs'},
        {src: 'd3/build/d3.min.js', inject: 'libs'}
      // {src: 'lodash/lodash.min.js', inject: 'libs'},
    ];

    // Add `local` third-party libraries to be injected/bundled.
    this.APP_ASSETS = [
        {src: `${this.APP_SRC}/semantic/semantic.min.js`, inject: 'libs', vendor: false},
        {src: `${this.APP_SRC}/semantic/semantic.min.css`, inject: true, vendor: false},
        //{src: '${this.APP_SRC}/semantic/semantic.min.js', inject: 'libs', vendor: false}
        // {src: `${this.CSS_SRC}/path-to-lib/test-lib.css`, inject: true, vendor: false},
    ];

    // Add packages (e.g. ng2-translate)
    // let additionalPackages: ExtendPackages[] = [{
    //   name: 'ng2-translate',
    //   // Path to the package's bundle
    //   path: 'node_modules/ng2-translate/bundles/ng2-translate.umd.js'
    // }];
    //
    // this.addPackagesBundles(additionalPackages);

    /* Add proxy middlewar */
    // this.PROXY_MIDDLEWARE = [
    //   require('http-proxy-middleware')({ ws: false, target: 'http://localhost:3003' })
    // ];

    /* Add to or override NPM module configurations: */
    // this.PLUGIN_CONFIGS['browser-sync'] = { ghostMode: false };
  }

}


text:
require 'test/unit'
require 'test/helper'

class TC_Time_Isdst_InstanceMethod < Test::Unit::TestCase
   include Test::Helper

   def setup
      @time = Time.local(2000, 1, 1)
   end

   def test_isdst_basic
      assert_respond_to(@time, :isdst)
      assert_nothing_raised{ @time.isdst }
      assert_kind_of(Boolean, @time.isdst)
   end

   def test_dst_basic
      assert_respond_to(@time, :dst?)
      assert_nothing_raised{ @time.dst? }
      assert_kind_of(Boolean, @time.dst?)
   end

   def test_isdst
      #assert_equal(true, Time.local(2000, 7, 1).isdst)
      #assert_equal(false, Time.local(2000, 1, 1).isdst)
   end

   def test_dst?
      #assert_equal(true, Time.local(2000, 7, 1).dst?)
      #assert_equal(false, Time.local(2000, 1, 1).dst?)
   end

   def test_isdst_expected_errors
      assert_raise(ArgumentError){ @time.isdst(1) }
      assert_raise(ArgumentError){ @time.dst?(1) }
      assert_raise(NoMethodError){ @time.isdst = 1 }
   end

   def teardown
      @time = nil
   end
end


text:
import React from 'react';

import PostList from './partials/PostList';

const Posts = (props) => {
  return (
    <PostList {...props} />
  );
};

export default Posts;


text:
package org.apache.cassandra.db.compaction;

import java.io.RandomAccessFile;
import java.util.*;

import com.google.common.collect.Iterators;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

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

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.locator.SimpleStrategy;
import org.apache.cassandra.utils.ByteBufferUtil;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class BlacklistingCompactionsTest
{
    private static final String KEYSPACE1 = "BlacklistingCompactionsTest";
    private static final String CF_STANDARD1 = "Standard1";

    @After
    public void leakDetect() throws InterruptedException
    {
        System.gc();
        System.gc();
        System.gc();
        Thread.sleep(10);
    }

    @BeforeClass
    public static void defineSchema() throws ConfigurationException
    {
        SchemaLoader.prepareServer();
        SchemaLoader.createKeyspace(KEYSPACE1,
                                    SimpleStrategy.class,
                                    KSMetaData.optsWithRF(1),
                                    SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD1));
        closeStdErr();
    }

    public static void closeStdErr()
    {
        // These tests generate an error message per CorruptSSTableException since it goes through
        // DebuggableThreadPoolExecutor, which will log it in afterExecute.  We could stop that by
        // creating custom CompactionStrategy and CompactionTask classes, but that's kind of a
        // ridiculous amount of effort, especially since those aren't really intended to be wrapped
        // like that.
        System.err.close();
    }

    @Test
    public void testBlacklistingWithSizeTieredCompactionStrategy() throws Exception
    {
        testBlacklisting(SizeTieredCompactionStrategy.class.getCanonicalName());
    }

    @Test
    public void testBlacklistingWithLeveledCompactionStrategy() throws Exception
    {
        testBlacklisting(LeveledCompactionStrategy.class.getCanonicalName());
    }

    public void testBlacklisting(String compactionStrategy) throws Exception
    {
        // this test does enough rows to force multiple block indexes to be used
        Keyspace keyspace = Keyspace.open(KEYSPACE1);
        final ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Standard1");

        final int ROWS_PER_SSTABLE = 10;
        final int SSTABLES = cfs.metadata.getMinIndexInterval() * 2 / ROWS_PER_SSTABLE;

        cfs.setCompactionStrategyClass(compactionStrategy);

        // disable compaction while flushing
        cfs.disableAutoCompaction();
        //test index corruption
        //now create a few new SSTables
        long maxTimestampExpected = Long.MIN_VALUE;
        Set<DecoratedKey> inserted = new HashSet<>();

        for (int j = 0; j < SSTABLES; j++)
        {
            for (int i = 0; i < ROWS_PER_SSTABLE; i++)
            {
                DecoratedKey key = Util.dk(String.valueOf(i));
                long timestamp = j * ROWS_PER_SSTABLE + i;
                new RowUpdateBuilder(cfs.metadata, timestamp, key.getKey())
                        .clustering("cols" + "i")
                        .add("val", "val" + i)
                        .build()
                        .applyUnsafe();
                maxTimestampExpected = Math.max(timestamp, maxTimestampExpected);
                inserted.add(key);
            }
            cfs.forceBlockingFlush();
            CompactionsTest.assertMaxTimestamp(cfs, maxTimestampExpected);
            assertEquals(inserted.toString(), inserted.size(), Util.getAll(Util.cmd(cfs).build()).size());
        }

        Collection<SSTableReader> sstables = cfs.getSSTables();
        int currentSSTable = 0;
        int sstablesToCorrupt = 8;

        // corrupt first 'sstablesToCorrupt' SSTables
        for (SSTableReader sstable : sstables)
        {
            if (currentSSTable + 1 > sstablesToCorrupt)
                break;

            RandomAccessFile raf = null;

            try
            {
                int corruptionSize = 50;
                raf = new RandomAccessFile(sstable.getFilename(), "rw");
                assertNotNull(raf);
                assertTrue(raf.length() > corruptionSize);
                raf.seek(new Random().nextInt((int)(raf.length() - corruptionSize)));
                // We want to write something large enough that the corruption cannot get undetected
                // (even without compression)
                byte[] corruption = new byte[corruptionSize];
                Arrays.fill(corruption, (byte)0xFF);
                raf.write(corruption);

            }
            finally
            {
                FileUtils.closeQuietly(raf);
            }

            currentSSTable++;
        }

        int failures = 0;

        // in case something will go wrong we don't want to loop forever using for (;;)
        for (int i = 0; i < sstables.size(); i++)
        {
            try
            {
                cfs.forceMajorCompaction();
            }
            catch (Exception e)
            {
                // kind of a hack since we're not specifying just CorruptSSTableExceptions, or (what we actually expect)
                // an ExecutionException wrapping a CSSTE.  This is probably Good Enough though, since if there are
                // other errors in compaction presumably the other tests would bring that to light.
                failures++;
                continue;
            }
            break;
        }

        cfs.truncateBlocking();
        assertEquals(sstablesToCorrupt, failures);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diaporthe kellermaniana G. Winter

### Remarks
null


text:
module PDUTools
  class MessagePart
    attr_reader :address, :body, :body_encoding, :timestamp, :validity_period, :user_data_header
    attr_writer :body
    attr_accessor :metadata

    def initialize address, body, body_encoding, timestamp, validity_period, user_data_header
      @address = address
      @body = body
      @body_encodig = body_encoding
      @timestamp = timestamp
      @validity_period = validity_period
      @user_data_header = user_data_header
    end

    def complete?
      return true unless @user_data_header
      return true unless @user_data_header[:multipart]
      if @user_data_header[:multipart][:parts] > 1
        false
      else
        true
      end
    end
  end
end


text:
package net.sourceforge.squirrel_sql.client.preferences;

import net.sourceforge.squirrel_sql.client.IApplication;
import net.sourceforge.squirrel_sql.client.util.IOptionPanel;

public interface INewSessionPropertiesPanel extends IOptionPanel
{
	void initialize(IApplication app);
}


text:
namespace base {

namespace {

void ExpectSetFlagDeath(AtomicFlag* flag) {
  ASSERT_TRUE(flag);
  EXPECT_DCHECK_DEATH(flag->Set());
}

// Busy waits (to explicitly avoid using synchronization constructs that would
// defeat the purpose of testing atomics) until |tested_flag| is set and then
// verifies that non-atomic |*expected_after_flag| is true and sets |*done_flag|
// before returning if it's non-null.
void BusyWaitUntilFlagIsSet(AtomicFlag* tested_flag, bool* expected_after_flag,
                            AtomicFlag* done_flag) {
  while (!tested_flag->IsSet())
    PlatformThread::YieldCurrentThread();

  EXPECT_TRUE(*expected_after_flag);
  if (done_flag)
    done_flag->Set();
}

}  // namespace

TEST(AtomicFlagTest, SimpleSingleThreadedTest) {
  AtomicFlag flag;
  ASSERT_FALSE(flag.IsSet());
  flag.Set();
  ASSERT_TRUE(flag.IsSet());
}

TEST(AtomicFlagTest, DoubleSetTest) {
  AtomicFlag flag;
  ASSERT_FALSE(flag.IsSet());
  flag.Set();
  ASSERT_TRUE(flag.IsSet());
  flag.Set();
  ASSERT_TRUE(flag.IsSet());
}

TEST(AtomicFlagTest, ReadFromDifferentThread) {
  // |tested_flag| is the one being tested below.
  AtomicFlag tested_flag;
  // |expected_after_flag| is used to confirm that sequential consistency is
  // obtained around |tested_flag|.
  bool expected_after_flag = false;
  // |reset_flag| is used to confirm the test flows as intended without using
  // synchronization constructs which would defeat the purpose of exercising
  // atomics.
  AtomicFlag reset_flag;

  Thread thread("AtomicFlagTest.ReadFromDifferentThread");
  ASSERT_TRUE(thread.Start());
  thread.task_runner()->PostTask(FROM_HERE,
                                 BindOnce(&BusyWaitUntilFlagIsSet, &tested_flag,
                                          &expected_after_flag, &reset_flag));

  // To verify that IsSet() fetches the flag's value from memory every time it
  // is called (not just the first time that it is called on a thread), sleep
  // before setting the flag.
  PlatformThread::Sleep(TimeDelta::FromMilliseconds(20));

  // |expected_after_flag| is used to verify that all memory operations
  // performed before |tested_flag| is Set() are visible to threads that can see
  // IsSet().
  expected_after_flag = true;
  tested_flag.Set();

  // Sleep again to give the busy loop time to observe the flag and verify
  // expectations.
  PlatformThread::Sleep(TimeDelta::FromMilliseconds(20));

  // Use |reset_flag| to confirm that the above completed (which the rest of
  // this test assumes).
  while (!reset_flag.IsSet())
    PlatformThread::YieldCurrentThread();

  tested_flag.UnsafeResetForTesting();
  EXPECT_FALSE(tested_flag.IsSet());
  expected_after_flag = false;

  // Perform the same test again after the controlled UnsafeResetForTesting(),
  // |thread| is guaranteed to be synchronized past the
  // |UnsafeResetForTesting()| call when the task runs per the implicit
  // synchronization in the post task mechanism.
  thread.task_runner()->PostTask(FROM_HERE,
                                 BindOnce(&BusyWaitUntilFlagIsSet, &tested_flag,
                                          &expected_after_flag, nullptr));

  PlatformThread::Sleep(TimeDelta::FromMilliseconds(20));

  expected_after_flag = true;
  tested_flag.Set();

  // The |thread|'s destructor will block until the posted task completes, so
  // the test will time out if it fails to see the flag be set.
}

TEST(AtomicFlagTest, SetOnDifferentSequenceDeathTest) {
  // Checks that Set() can't be called from another sequence after being called
  // on this one. AtomicFlag should die on a DCHECK if Set() is called again
  // from another sequence.

  // Note: flag must be declared before the Thread so that its destructor runs
  // later. Otherwise there's a race between destructing flag and running
  // ExpectSetFlagDeath.
  AtomicFlag flag;

  ::testing::FLAGS_gtest_death_test_style = "threadsafe";
  Thread t("AtomicFlagTest.SetOnDifferentThreadDeathTest");
  ASSERT_TRUE(t.Start());
  EXPECT_TRUE(t.WaitUntilThreadStarted());

  flag.Set();
  t.task_runner()->PostTask(FROM_HERE, BindOnce(&ExpectSetFlagDeath, &flag));
}

}  // namespace base


text:
``` purescript
data ST :: * -> !
```

The `ST` effect represents _local mutation_, i.e. mutation which does not "escape" into the surrounding computation.

An `ST` computation is parameterized by a phantom type which is used to restrict the set of reference cells it is allowed to access.

The `runST` function can be used to handle the `ST` effect.

#### `STRef`

``` purescript
data STRef :: * -> * -> *
```

The type `STRef s a` represents a mutable reference holding a value of type `a`, which can be used with the `ST s` effect.

#### `newSTRef`

``` purescript
newSTRef :: forall a h r. a -> Eff (st :: ST h | r) (STRef h a)
```

Create a new mutable reference.

#### `readSTRef`

``` purescript
readSTRef :: forall a h r. STRef h a -> Eff (st :: ST h | r) a
```

Read the current value of a mutable reference.

#### `modifySTRef`

``` purescript
modifySTRef :: forall a h r. STRef h a -> (a -> a) -> Eff (st :: ST h | r) a
```

Modify the value of a mutable reference by applying a function to the current value.

#### `writeSTRef`

``` purescript
writeSTRef :: forall a h r. STRef h a -> a -> Eff (st :: ST h | r) a
```

Set the value of a mutable reference.

#### `runST`

``` purescript
runST :: forall a r. (forall h. Eff (st :: ST h | r) a) -> Eff r a
```

Run an `ST` computation.

Note: the type of `runST` uses a rank-2 type to constrain the phantom type `s`, such that the computation must not leak any mutable references
to the surrounding computation.

It may cause problems to apply this function using the `$` operator. The recommended approach is to use parentheses instead.

#### `pureST`

``` purescript
pureST :: forall a. (forall h r. Eff (st :: ST h | r) a) -> a
```

A convenience function which combines `runST` with `runPure`, which can be used when the only required effect is `ST`.

Note: since this function has a rank-2 type, it may cause problems to apply this function using the `$` operator. The recommended approach
is to use parentheses instead.


text:
@implementation NSString (Common)
- (CGFloat)getHeightWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    return [self getSizeWithFont:font constrainedToSize:size].height;
}

- (CGFloat)getWidthWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    return [self getSizeWithFont:font constrainedToSize:size].width;
}

- (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    CGSize resultSize = CGSizeZero;
    if (self.length <= 0) {
        return resultSize;
    }
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        resultSize = [self boundingRectWithSize:size
                                        options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{NSFontAttributeName: font}
                                        context:nil].size;
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        resultSize = [self sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
        //        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font}];
        //
        //        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        //        [paragraphStyle setLineSpacing:2.0];
        //
        //        [attributedStr addAttribute:NSParagraphStyleAttributeName
        //                              value:paragraphStyle
        //                              range:NSMakeRange(0, [self length])];
        //        resultSize = [attributedStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;

#endif
    }
    resultSize = CGSizeMake(MIN(size.width, ceilf(resultSize.width)), MIN(size.height, ceilf(resultSize.height)));
    //    if ([self containsEmoji]) {
    //        resultSize.height += 10;
    //    }
    return resultSize;
}

- (NSString *)md5Str
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)trimWhitespace
{
    NSMutableString *str = [self mutableCopy];
    CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
    return str;
}

- (BOOL)isEmpty
{
    return [[self trimWhitespace] isEqualToString:@""];
}

@end


text:
from ..apibits import *

class UsersEndpoint(ApiEndpoint):

    def all(self, params={}, headers={}):
        from ..resources import User
        method = ApiMethod("get", "/users", params, headers, self.parent)
        json = self.client.execute(method)
        return ApiList(User, json, method, client=self.client)

    def retrieve(self, user_id, params={}, headers={}):
        from ..resources import User
        params = ParamsBuilder.merge({
            "user_id" : user_id,
        }, params)
        method = ApiMethod("get", "/users/:user_id", params, headers, self.parent)
        json = self.client.execute(method)
        return User(json, method, client=self.client)

    def update(self, user_id, params={}, headers={}):
        from ..resources import User
        params = ParamsBuilder.merge({
            "user_id" : user_id,
        }, params)
        method = ApiMethod("put", "/users/:user_id", params, headers, self.parent)
        json = self.client.execute(method)
        return User(json, method, client=self.client)

    def create(self, params={}, headers={}):
        from ..resources import User
        method = ApiMethod("post", "/users", params, headers, self.parent)
        json = self.client.execute(method)
        return User(json, method, client=self.client)

    def reset_password(self, email, params={}, headers={}):
        params = ParamsBuilder.merge({
            "email" : email,
        }, params)
        method = ApiMethod("post", "/users/reset_password", params, headers, self.parent)
        json = self.client.execute(method)
        return json


text:
require 'pact_broker/api/resources/latest_provider_pacts'

module PactBroker
  module Api
    module Resources
      describe LatestProviderPacts do
        before do
          allow(PactBroker::Pacts::Service).to receive(:find_latest_pact_versions_for_provider).and_return(pacts)
          allow(PactBroker::Api::Decorators::ProviderPactsDecorator).to receive(:new).and_return(decorator)
          allow_any_instance_of(LatestProviderPacts).to receive(:resource_exists?).and_return(provider)
        end

        let(:provider) { double('provider') }
        let(:pacts) { double('pacts') }
        let(:path) { '/pacts/provider/Bar/latest' }
        let(:decorator) { instance_double('PactBroker::Api::Decorators::ProviderPactsDecorator') }

        subject { get path; last_response }

        context "with no tag" do
          it "finds the pacts" do
            expect(PactBroker::Pacts::Service).to receive(:find_latest_pact_versions_for_provider).with("Bar", tag: nil)
            subject
          end

          it "sets the correct resource title" do
            expect(decorator).to receive(:to_json) do | options |
              expect(options[:user_options][:title]).to eq "Latest pact versions for the provider Bar"
            end
            subject
          end
        end

        context "with a tag" do
          let(:path) { '/pacts/provider/Bar/latest/prod' }

          it "finds the pacts with a tag" do
            expect(PactBroker::Pacts::Service).to receive(:find_latest_pact_versions_for_provider).with("Bar", tag: "prod")
            subject
          end

          it "sets the correct resource title" do
            expect(decorator).to receive(:to_json) do | options |
              expect(options[:user_options][:title]).to eq "Latest pact versions for the provider Bar with consumer version tag 'prod'"
            end
            subject
          end
        end
      end
    end
  end
end


text:
class DomainMailer < ApplicationMailer
  def request_authcode domain, authcode
    @domain = domain
    @authcode = authcode

    mail to: domain.registrant.email, bcc: ["registrar@dot.ph"], subject: "Authorization Code for #{domain.name}"
  end

  def status_pending_transfer_update_notice domain
    @domain = domain

    mail to: domain.partner.email, bcc: ["registrar@dot.ph"], subject: "Pending Domain Transfer Out - #{domain.name}"
  end

  def send_info_csv partner
    begin
      csv_title = "Domains List #{partner.name}"
      csv = Domain.to_csv(partner)

      attachments["#{csv_title}.csv"] = {mime_type: 'text/csv', content: csv}

      mail to: partner.email, bcc: ["registrar@dot.ph"], subject: "Domains List for #{partner.name}"
    rescue Exception => e
      raise "Domain info CSV mail failed for #{partner.name} - #{e}"
    end
  end
end