text:
require "testup/testcase"
require_relative "utils/frozen"

# class Geom::Transformation2d
class TC_Geom_Transformation2d < TestUp::TestCase

  include TestUp::SketchUpTests::Frozen

  def setup
    # ...
  end

  def teardown
    # ...
  end

  # Copied from mathutils.cpp
  DivideByZeroTol = 1.0e-10

  def assert_matrix_equal(matrix1, matrix2)
    matrix1.each_with_index { |expected, index|
      assert_in_delta(expected, matrix2[index], DivideByZeroTol)
    }
  end

  def test_Operator_Multiply
    point1 = Geom::Point2d.new(1, 2)
    point2 = Geom::Point2d.new(4, 5)
    transform1 = Geom::Transformation2d.translation(point1)

    output = transform1 * point2
    expected = Geom::Point2d.new(5, 7)
    assert_equal(expected, output)
    assert_kind_of(Geom::Point2d, output)

    output = transform1 * [4, 5]
    assert_equal(expected, output)
    assert_kind_of(Array, output)

    output = transform1 * Geom::Vector2d.new(4, 5)
    assert_equal(Geom::Vector2d.new(4, 5), output)
    assert_kind_of(Geom::Vector2d, output)

    transform2 = Geom::Transformation2d.translation(point2)
    expected2 = [1.0, 0.0,
                 0.0, 1.0,
                 5.0, 7.0]
    output = transform1 * transform2
    assert_equal(expected2, output.to_a)
    assert_kind_of(Geom::Transformation2d, output)
  end

  def test_Operator_Multiply_order_of_operation
    tr1 = Geom::Transformation2d.translation([2, 5])
    tr2 = Geom::Transformation2d.rotation(ORIGIN_2D, 30.degrees)
    result = tr1 * tr2
    expected = [0.8660253882408142, -0.5,
                0.5, 0.8660253882408142,
                2.0,  5.0]
    assert_matrix_equal(expected, result.to_a)
  end

  def test_Operator_Multiply_invalid_arguments
    point1 = Geom::Point2d.new(1, 2)
    transform1 = Geom::Transformation2d.translation(point1)

    assert_raises(TypeError, 'Argument with nil') do
      transform1 * nil
    end

    assert_raises(TypeError, 'Argument with string') do
      transform1 * 'sketchup'
    end

    assert_raises(TypeError, 'Argument with numbers') do
      transform1 * 1234
    end

    assert_raises(TypeError, 'Argument with array of length 3') do
      transform1 * [1, 2, 3]
    end

    assert_raises(TypeError, 'Argument with array of length 7') do
      transform1 * [1, 2, 3, 4, 6, 7]
    end
  end

  def test_clone
    transformation = Geom::Transformation2d.new
    cloned = transformation.clone
    assert(cloned.to_a == transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
    refute_equal(transformation.object_id, cloned.object_id)
  end

  def test_clone_too_many_arguments
    transformation = Geom::Transformation2d.new
    assert_raises(ArgumentError, 'Argument with nil') do
      transformation.clone(nil)
    end

    assert_raises(ArgumentError, 'Argument with transformation') do
      transformation.clone(transformation)
    end
  end

  def test_identity_Query
    transformation = Geom::Transformation2d.new
    assert(transformation.identity?, "Geom::Transformation2d.new")

    transformation.set!(IDENTITY_2D)
    assert(transformation.identity?, "IDENTITY_2D")

    transformation.set!([1, 0, 0, 1, 0, 1])
    refute(transformation.identity?)
  end

  def test_identity_Query_too_many_arguments
    assert_raises(ArgumentError, 'Argument with nil') do
      IDENTITY_2D.identity?(nil)
    end

    assert_raises(ArgumentError, 'Argument with identity matrix') do
      IDENTITY_2D.identity?(IDENTITY_2D)
    end
  end

  def test_initialize_transformation
    transformation = Geom::Transformation2d.new
    assert_equal(IDENTITY_2D.to_a, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_initialize_array
    matrix1 = [1, 0, 0, 1, 0, 0]
    transformation = Geom::Transformation2d.new(matrix1)
    assert_equal(matrix1, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)

    matrix1 = [2.0, 0.5, 0.5, 2.0, 1.0, 1.0]
    transformation = Geom::Transformation2d.new(matrix1)
    assert_equal(matrix1, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_initialize_scale
    transformation = Geom::Transformation2d.scaling(5)
    matrix3 = [5, 0, 0, 5, 0, 0]
    assert_equal(matrix3, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)

    transformation = Geom::Transformation2d.scaling(2.5)
    matrix3 = [2.5, 0, 0, 2.5, 0, 0]
    assert_equal(matrix3, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_initialize_invalid_arguments
    assert_raises(TypeError, 'Argument with number') do
      Geom::Transformation2d.new(1234)
    end

    assert_raises(TypeError, 'Argument with string') do
      Geom::Transformation2d.new('sketchup')
    end
  end

  class CustomTransformation < Geom::Transformation2d; end
  def test_initialize_subclassed
    # Making sure we created the objects correctly so it can be sub-classed.
    transform = CustomTransformation::new
    assert_kind_of(CustomTransformation, transform)
    assert_kind_of(Geom::Transformation2d, transform)
  end

  def test_inverse
    point1 = Geom::Point2d.new(11, 22)
    transformation1 = Geom::Transformation2d.translation(point1)
    expected = Geom::Transformation2d.translation(Geom::Point2d.new(-11, -22))
    output = transformation1.inverse
    assert_equal(expected.to_a, output.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1.inverse)
    refute_equal(transformation1.to_a, output.to_a)

    transformation2 = Geom::Transformation2d.rotation(ORIGIN_2D, 30.degrees)
    matrix = [0.8660253882408142, 0.5,
              -0.5, 0.8660253882408142,
              0.0, 0.0]
    output = transformation2.inverse
    assert_matrix_equal(matrix, output.to_a)
    assert_kind_of(Geom::Transformation2d, transformation2)
    refute_equal(transformation2.to_a, output.to_a)
  end

  def test_inverse_too_many_arguments
    point1 = Geom::Point2d.new(11, 22)
    transformation1 = Geom::Transformation2d.translation(point1)
    assert_raises(ArgumentError, 'Argument with nil') do
      transformation1.inverse(nil)
    end

    assert_raises(ArgumentError, 'Argument with transformation') do
      transformation1.inverse(transformation1)
    end
  end

  def test_invert_Bang
    point1 = Geom::Point2d.new(11, 22)
    transformation1 = Geom::Transformation2d.translation(point1)
    expected = Geom::Transformation2d.translation(Geom::Point2d.new(-11, -22))
    assert_equal(expected.to_a, transformation1.invert!.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1.invert!)
  end

  def test_invert_Bang_frozen
    assert_raises(FROZEN_ERROR, 'set frozen Geom::Transformation2d') do
      IDENTITY_2D.invert!
    end
  end

  def test_invert_Bang_invalid_arguments
    point1 = Geom::Point2d.new(11, 22)
    transformation1 = Geom::Transformation2d.translation(point1)
    assert_raises(ArgumentError, 'Argument with nil') do
      transformation1.invert!(nil)
    end

    assert_raises(ArgumentError, 'Argument with transformation') do
      transformation1.invert!(transformation1)
    end
  end

  def test_rotation
    point1 = Geom::Point2d.new(11, 22)
    angle = 45.degrees
    transformation1 = Geom::Transformation2d.rotation(point1, angle)
    expected = [0.7071067690849304, -0.7071067690849304,
                0.7071067690849304, 0.7071067690849304,
                18.778175354003906, -1.3345222473144531]
    assert_matrix_equal(expected, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)
  end

  def test_rotation_invalid_arguments
    point1 = Geom::Point2d.new(11, 22)
    vector1 = Geom::Vector2d.new(1, 1)
    angle = 45.degrees
    assert_raises(ArgumentError, 'Argument with nil') do
      Geom::Transformation2d.rotation(nil)
    end

    assert_raises(TypeError, 'Argument with nils') do
      Geom::Transformation2d.rotation(nil, nil)
    end

    assert_raises(TypeError, 'Argument with first valid and second invalid') do
      Geom::Transformation2d.rotation(point1, 'sketchup')
    end

    assert_raises(TypeError, 'Argument with second valid and first invalid') do
      Geom::Transformation2d.rotation('sketchup', angle)
    end

    assert_raises(ArgumentError, 'Arugment with one extra argument') do
      Geom::Transformation2d.rotation(point1, angle, 'food please')
    end

    assert_raises(TypeError, 'Argument with vector3s') do
      Geom::Transformation2d.rotation(vector1, angle)
    end

    assert_raises(ArgumentError, 'empty argument') do
      Geom::Transformation2d.rotation
    end
  end

  def test_scaling_point_and_uniform_scale
    point = Geom::Point2d.new(1, 2)
    transformation = Geom::Transformation2d.scaling(point, 10)
    expected = [10.0,   0.0,
                 0.0,  10.0,
                -9.0, -18.0]
    assert_equal(expected, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_scaling_uniform_scale
    transformation = Geom::Transformation2d.scaling(10)
    expected = [10.0,  0.0,
                 0.0, 10.0,
                 0.0,  0.0]
    assert_equal(expected, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_scaling_non_uniform_scale
    transformation = Geom::Transformation2d.scaling(10, 20)
    expected = [10.0,  0.0,
                 0.0, 20.0,
                 0.0,  0.0]
    assert_equal(expected, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_scaling_point_and_non_uniform_scale
    point = Geom::Point2d.new(1, 2)
    transformation = Geom::Transformation2d.scaling(point, 10, 20)
    expected = [10.0,   0.0,
                 0.0,  20.0,
                -9.0, -38.0]
    assert_equal(expected, transformation.to_a)
    assert_kind_of(Geom::Transformation2d, transformation)
  end

  def test_scaling_invalid_arguments
    point1 = Geom::Point2d.new(1, 2)
    assert_raises(TypeError, 'Argument with nil') do
      Geom::Transformation2d.scaling(nil)
    end

    assert_raises(TypeError, 'Argument with nils') do
      Geom::Transformation2d.scaling(nil, nil)
    end

    assert_raises(TypeError, 'Argument with vector2d') do
      vec1 = Geom::Vector2d.new(1, 2)
      Geom::Transformation2d.scaling(vec1, 4, 5)
    end

    assert_raises(TypeError, 'Argumet with 1 valid and 2 invalid') do
      Geom::Transformation2d.scaling(point1, 'sketchup', 'ketchup')
    end

    assert_raises(TypeError, 'Argument with 2 valid and 1 invalid') do
      Geom::Transformation2d.scaling(point1, 10, '30')
    end

    assert_raises(ArgumentError, 'too many arguments') do
      Geom::Transformation2d.scaling(point1, 10, 20, 30)
    end

    assert_raises(ArgumentError, 'empty argument') do
      Geom::Transformation2d.scaling
    end
  end

  def test_set_Bang_transformation
    transformation1 = Geom::Transformation2d.translation(Geom::Point2d.new(1, 2))
    transformation2 = Geom::Transformation2d.new
    refute_equal(transformation2.to_a, transformation1.to_a)
    transformation2.set!(transformation1)
    assert_equal(transformation1.to_a, transformation2.to_a)
    assert_kind_of(Geom::Transformation2d, transformation2)
  end

  def test_set_Bang_array
    transformation1 = Geom::Transformation2d.new
    matrix = [1.0, 2.0,
              3.0, 4.0,
              5.0, 6.0]
    refute_equal(transformation1.to_a, matrix)
    transformation1.set!(matrix)
    assert_equal(matrix, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)
  end

  def test_set_Bang_scale
    transformation1 = Geom::Transformation2d.new
    scale_transformation = Geom::Transformation2d.scaling(11)
    refute_equal(scale_transformation.to_a, transformation1.to_a)
    transformation1.set!(scale_transformation)
    assert_equal(scale_transformation.to_a, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)
  end

  def test_set_Bang_frozen
    assert_raises(FROZEN_ERROR, 'set frozen Geom::Transformation2d') do
      IDENTITY_2D.set!([0, 1, 1, 0, 1, 1])
    end
  end

  def test_set_Bang_invalid_arguments
    transformation1 = Geom::Transformation2d.new

    assert_raises(TypeError, 'Argument with nil') do
      transformation1.set!(nil)
    end

    assert_raises(TypeError, 'Argument with array size of 1') do
      transformation1.set!([1])
    end

    assert_raises(TypeError, 'Argument with array size of 5') do
      transformation1.set!([1, 2, 3, 4, 5])
    end

    assert_raises(ArgumentError, 'too many arguments') do
      transformation1.set!(Geom::Vector2d.new(1, 2), ORIGIN_2D)
    end

    assert_raises(ArgumentError, 'empty argument') do
      transformation1.set!
    end
  end

  def test_to_a
    transformation1 = Geom::Transformation2d.new
    assert_equal(IDENTITY_2D.to_a, transformation1.to_a)
    assert_kind_of(Array, transformation1.to_a)
  end

  def test_to_a_too_many_arguments
    transformation1 = Geom::Transformation2d.new

    assert_raises(ArgumentError, 'Argument with nil') do
      transformation1.to_a(nil)
    end

    assert_raises(ArgumentError, 'Argument with transformation') do
      transformation1.to_a(IDENTITY_2D)
    end
  end

  def test_translation
    point1 = Geom::Point2d.new(1, 2)
    vector1 = Geom::Vector2d.new(4, 5)

    transformation1 = Geom::Transformation2d.translation(point1)
    expected = [1.0, 0.0,
                0.0, 1.0,
                1.0, 2.0,]
    assert_equal(expected, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)

    transformation1 = Geom::Transformation2d.translation(vector1)
    expected = [1.0, 0.0,
                0.0, 1.0,
                4.0, 5.0]
    assert_equal(expected, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)

    transformation1 = Geom::Transformation2d.translation([2, 3])
    expected = [1.0, 0.0,
                0.0, 1.0,
                2.0, 3.0]
    assert_equal(expected, transformation1.to_a)
    assert_kind_of(Geom::Transformation2d, transformation1)
  end

  def test_translation_invalid_arguments
    assert_raises(TypeError, 'Argument with nil') do
      Geom::Transformation2d.translation(nil)
    end

    assert_raises(TypeError, 'Argument with number') do
      Geom::Transformation2d.translation(1234)
    end

    assert_raises(ArgumentError, 'too many arguments') do
      Geom::Transformation2d.translation(ORIGIN_2D, ORIGIN_2D)
    end

    assert_raises(ArgumentError, 'empty argument') do
      Geom::Transformation2d.translation
    end

    assert_raises(ArgumentError, 'Argument with array with length 1') do
      Geom::Transformation2d.translation([1])
    end

    matrix = [1, 2, 3, 4, 5, 6, 7]
    assert_raises(ArgumentError, 'Argument with array with legth 7') do
      Geom::Transformation2d.translation(matrix)
    end
  end
end


text:
/**
 * @description
 *
 * A humpback-view created at Sat Aug 29 2015 16:08:20 GMT-0400 (EDT).
 */

angular.module( 'humpback.views.AdminDataView.states', [

])
.config(function config( $stateProvider, $urlRouterProvider) {
	$stateProvider
		.state( 'admin.data.data', {
			url: '/:id?skip?sort?limit?criteria?page',
			reloadOnSearch: false,
			ncyBreadcrumb: {
          		label: '{{ thismodel.name }}'
        	},
			views: {
				"admin@admin": {
					controller: 'AdminDataViewCtrl',
					templateUrl: 'app/views/admin/data/view/index.html'
				},
				"widgets@admin.data.data": {
					templateUrl: 'app/views/admin/data/view/widgets.html'
				}
			}
		})
		;
});

redpajama_set_name: RedPajamaGithub


text:
// Run this with ts-node (https://github.com/TypeStrong/ts-node)

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();

app.get('/', (req, res) => res.send("Hello World"))

// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);

const server = http.Server(app);
server.listen(3000);

const io = socketIo(server);
console.log("listening on 3000");

// Tell Socket.io to start accepting connections
// 1 - Keep a dictionary of all the players as key/value
var players = {};
var bullet_array = [];
var WORLD_SIZE_SPAWN_x = 1000;
var WORLD_SIZE_SPAWN_y = 1000;
io.on('connection', function (socket) {
  console.log("New client has connected with id:", socket.id);
  socket.on('new-player', function (state_data) { // Listen for new-player event on this client
    console.log("New player has state:", state_data);
    // 2 - Add the new player to the dict
    players[socket.id] = state_data;
    // Send an update event
    io.emit('update-players', players);
  })
  socket.on('disconnect', function () {
    // 3- Delete from dict on disconnect
    delete players[socket.id];
    // Send an update event
  })

  // Listen for move events and tell all other clients that something has moved
  socket.on('move-player', function (position_data) {
    if (players[socket.id] == undefined) return; // Happens if the server restarts and a client is still connected
    players[socket.id].x = position_data.x;
    players[socket.id].y = position_data.y;
    players[socket.id].angle = position_data.angle;
    io.emit('update-players', players);
  })

  // Listen for shoot-bullet events and add it to our bullet array
  socket.on('shoot-bullet', function (data) {
    if (players[socket.id] == undefined) return;
    var new_bullet = data;
    data.owner_id = socket.id; // Attach id of the player to the bullet
    if (Math.abs(data.speed_x) > 20 || Math.abs(data.speed_y) > 20) {
      console.log("Player", socket.id, "is cheating!");
    }

    bullet_array.push(new_bullet);
    /*setTimeout(function () {
      bullet_array.shift();
    }, 1500);*/
  });
})

// Healthpack
setInterval(function () {
  var x = Math.random() * WORLD_SIZE_SPAWN_x / 2 + WORLD_SIZE_SPAWN_x / 2;
  var y = Math.random() * WORLD_SIZE_SPAWN_y / 2 + WORLD_SIZE_SPAWN_y / 2;
  io.emit('new-healthpack', x, y);
}, 10000);

// Invpack
setInterval(function () {
  var x = Math.random() * WORLD_SIZE_SPAWN_x  / 2 + WORLD_SIZE_SPAWN_x  / 2;
  var y = Math.random() * WORLD_SIZE_SPAWN_y / 2 + WORLD_SIZE_SPAWN_y / 2;
  io.emit('new-invpack', x, y);
}, 25000);

// Stealthpack
setInterval(function () {
  var x = Math.random() * WORLD_SIZE_SPAWN_x  / 2 + WORLD_SIZE_SPAWN_x  / 2;
  var y = Math.random() * WORLD_SIZE_SPAWN_y / 2 + WORLD_SIZE_SPAWN_y / 2;
  io.emit('new-stealthpack', x, y);
}, 18000);

// Update the bullets 60 times per frame and send updates
function ServerGameLoop() {

  for (var i = 0; i < bullet_array.length; i++) {
    var bullet = bullet_array[i];
    bullet.x += bullet.speed_x;
    bullet.y += bullet.speed_y;

    // Check if this bullet is close enough to hit any player
    for (var id in players) {
      if (bullet.owner_id != id) {
        // And your own bullet shouldn't kill you
        var dx = players[id].x - bullet.x;
        var dy = players[id].y - bullet.y;
        var dist = Math.sqrt(dx * dx + dy * dy);
        if (dist < 70 && dist > 60) {
          io.emit('player-hit', id); // Tell everyone this player got hit
        }
      }
    }

    // Remove if it goes too far off screen
    if (bullet.x < -10 || bullet.x > 1500 || bullet.y < -10 || bullet.y > 1500) {
      bullet_array.splice(i, 1);
      i--;
    }

  }

  // Tell everyone where all the bullets are by sending the whole array
  io.emit("bullets-update", bullet_array);

}

setInterval(ServerGameLoop, 12);


text:
set -eu

WORDS="activiat.*\|appropiate\|availible\|availilbe\|availble\|cusomize\|debain\|defintion\|deleteing\|dependan.*\|destory\|equalogic\|extactly\|futher\|heath\|inteval\|maintainance\|maintainence\|maintanence\|maintenence\|managment\|mulitple\|neccessary\|numberic\|occured\|organis.*\|performace\|pervious\|prefered\|proirity\|reciev.*\|reciv.*\|remeber\|repositary\|seach\|seperat.*\|.*[^r]sever[^aei].*\|shrotcut\|sotre\|stroage\|strorage\|suceed.*\|sucess\|succesful\|updateing\|whilst\|wish\|licence[s]\?"

FOUND_TYPO=$(grep -iow $WORDS $1)
if [ "${FOUND_TYPO}" != "" ]
then
  echo "$1 contains $FOUND_TYPO"
fi

for w in "operation system" "goto " "TODO[: ]*[rR]emove
"
do
  grep -qi "$w" "$1" && echo "$1 contains $w"
done


text:
package com.activiti.pojo.schedule;

import java.io.Serializable;
import java.util.Date;

/**
 * 互评时间表
 * Created by 12490 on 2017/8/6.
 */
public class ScheduleDto implements Serializable {
    private static final long serialVersionUID = 2120869894112984147L;

    private String courseName;  //课程名称
    private String courseCode;  //课程代码
    private Date startTime;      //提交作业开始时间
    private Date commitEndTime;  //提交作业结束时间
    private Date judgeStartTime; //互评开始时间
    private Date judgeEndTime;   //互评结束时间
    private Date auditStartTime;  //学生审查开始时间
    private Date auditEndTime;   //学生审查结束时间
    private Date publishTime;    //发布成绩时间
    private int judgeTimes;    //每个学生需要互评的次数(后期算出)

    public ScheduleDto() {
    }

    public int getJudgeTimes() {
        return judgeTimes;
    }

    public void setJudgeTimes(int judgeTimes) {
        this.judgeTimes = judgeTimes;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseCode() {
        return courseCode;
    }

    public void setCourseCode(String courseCode) {
        this.courseCode = courseCode;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getCommitEndTime() {
        return commitEndTime;
    }

    public void setCommitEndTime(Date commitEndTime) {
        this.commitEndTime = commitEndTime;
    }

    public Date getJudgeStartTime() {
        return judgeStartTime;
    }

    public void setJudgeStartTime(Date judgeStartTime) {
        this.judgeStartTime = judgeStartTime;
    }

    public Date getJudgeEndTime() {
        return judgeEndTime;
    }

    public void setJudgeEndTime(Date judgeEndTime) {
        this.judgeEndTime = judgeEndTime;
    }

    public Date getAuditStartTime() {
        return auditStartTime;
    }

    public void setAuditStartTime(Date auditStartTime) {
        this.auditStartTime = auditStartTime;
    }

    public Date getAuditEndTime() {
        return auditEndTime;
    }

    public void setAuditEndTime(Date auditEndTime) {
        this.auditEndTime = auditEndTime;
    }

    public Date getPublishTime() {
        return publishTime;
    }

    public void setPublishTime(Date publishTime) {
        this.publishTime = publishTime;
    }

    @Override
    public String toString() {
        return "ScheduleDto{" +
                "courseName='" + courseName + '\'' +
                ", courseCode='" + courseCode + '\'' +
                ", startTime=" + startTime +
                ", commitEndTime=" + commitEndTime +
                ", judgeStartTime=" + judgeStartTime +
                ", judgeEndTime=" + judgeEndTime +
                ", auditStartTime=" + auditStartTime +
                ", auditEndTime=" + auditEndTime +
                ", publishTime=" + publishTime +
                ", judgeTimes=" + judgeTimes +
                '}';
    }
}


text:
<?php

/* MatrixBundle:EstudianteGrupo:asignarnoras.html.twig */
class __TwigTemplate_8eb619bf3251b1eabdaa69453a2b1df6f51512eaf2417320e14c0f15869c2d59 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("::base.html.twig", "MatrixBundle:EstudianteGrupo:asignarnoras.html.twig", 1);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
Administrar Grupo

    ";
        // line 7
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")));
        foreach ($context['_seq'] as $context["_key"] => $context["e"]) {
            // line 8
            echo "

              ";
            // line 10
            echo twig_escape_filter($this->env, (($this->getAttribute($this->getAttribute($context["e"], "usuario", array()), "nombrecompleto", array()) . " - Nota Actual: ") . $this->getAttribute($context["e"], "nota", array())), "html", null, true);
            echo "

            env, $this->env->getExtension('routing')->getPath("estudiantegrupo_edit", array("id" => $this->getAttribute($context["e"], "id", array()))), "html", null, true);
            echo "\" class=\"opciones\">
              <button class=\"list-group-item btn btn-custom\">
                Asignar Nota
              </button>

    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['e'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 19
        echo "

";
    }

    public function getTemplateName()
    {
        return "MatrixBundle:EstudianteGrupo:asignarnoras.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  62 => 19,  49 => 12,  44 => 10,  40 => 8,  36 => 7,  31 => 4,  28 => 3,  11 => 1,);
    }
}


text:
package com.alsash.reciper.ui.adapter.observer;

import android.support.v7.widget.RecyclerView;

import java.util.Set;

/**
 * Simple adapter data observer that update positions of views on data changes
 */
public class AdapterPositionSetObserver extends RecyclerView.AdapterDataObserver {

    private final Set<Integer>[] positionSets;

    @SafeVarargs
    public AdapterPositionSetObserver(Set<Integer>... positionSets) {
        this.positionSets = positionSets;
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        if (itemCount <= 0) return;
        for (int i = itemCount + positionStart - 1; i >= positionStart; i--) {
            for (Set<Integer> set : positionSets) {
                if (set.remove(i)) set.add(i + 1);
            }
        }
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        if (itemCount <= 0) return;
        for (int i = positionStart; i <= itemCount + positionStart; i++) {
            for (Set<Integer> set : positionSets) {
                if (set.remove(i + 1)) set.add(i);
            }
        }
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        if (fromPosition == toPosition) return;
        if (itemCount != 1) return; // Google says: Moving more than 1 item is not supported yet :)
        for (Set<Integer> set : positionSets) {
            boolean fromExist = set.contains(fromPosition);
            boolean toExist = set.contains(toPosition);
            if (fromExist != toExist) {
                if (fromExist) {
                    set.remove(fromPosition);
                    set.add(toPosition);
                }
                if (toExist) {
                    set.remove(toPosition);
                    set.add(fromPosition);
                }
            }
        }
    }
}


text:
<?php

namespace Yajra\Oci8\Connectors;

use Illuminate\Database\Connectors\Connector;
use Illuminate\Database\Connectors\ConnectorInterface;
use Illuminate\Support\Arr;
use PDO;
use Yajra\Pdo\Oci8;

class OracleConnector extends Connector implements ConnectorInterface
{
    /**
     * The default PDO connection options.
     *
     * @var array
     */
    protected $options = [
        PDO::ATTR_CASE               => PDO::CASE_LOWER,
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_ORACLE_NULLS       => PDO::NULL_NATURAL,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
    ];

    /**
     * Establish a database connection.
     *
     * @param  array  $config
     * @return PDO
     */
    public function connect(array $config)
    {
        $tns = ! empty($config['tns']) ? $config['tns'] : $this->getDsn($config);

        $options = $this->getOptions($config);

        if (defined('OCI_CRED_EXT') && Arr::get($options, 'session_mode') === OCI_CRED_EXT) {
            // External connections can only be used with user / and an empty password
            $config['username'] = '/';
            $config['password'] = null;
        }

        $connection = $this->createConnection($tns, $config, $options);

        return $connection;
    }

    /**
     * Create a DSN string from a configuration.
     *
     * @param  array  $config
     * @return string
     */
    protected function getDsn(array $config)
    {
        if (! empty($config['tns'])) {
            return $config['tns'];
        }

        // parse configuration
        $config = $this->parseConfig($config);

        // check multiple connections/host, comma delimiter
        $config = $this->checkMultipleHostDsn($config);

        // return generated tns
        return $config['tns'];
    }

    /**
     * Parse configurations.
     *
     * @param  array  $config
     * @return array
     */
    protected function parseConfig(array $config)
    {
        $config = $this->setHost($config);
        $config = $this->setPort($config);
        $config = $this->setProtocol($config);
        $config = $this->setServiceId($config);
        $config = $this->setTNS($config);
        $config = $this->setCharset($config);

        return $config;
    }

    /**
     * Set host from config.
     *
     * @param  array  $config
     * @return array
     */
    protected function setHost(array $config)
    {
        $config['host'] = isset($config['host']) ? $config['host'] : $config['hostname'];

        return $config;
    }

    /**
     * Set port from config.
     *
     * @param  array  $config
     * @return array
     */
    private function setPort(array $config)
    {
        $config['port'] = isset($config['port']) ? $config['port'] : '1521';

        return $config;
    }

    /**
     * Set protocol from config.
     *
     * @param  array  $config
     * @return array
     */
    private function setProtocol(array $config)
    {
        $config['protocol'] = isset($config['protocol']) ? $config['protocol'] : 'TCP';

        return $config;
    }

    /**
     * Set service id from config.
     *
     * @param  array  $config
     * @return array
     */
    protected function setServiceId(array $config)
    {
        $config['service'] = empty($config['service_name'])
            ? $service_param = 'SID = '.$config['database']
            : $service_param = 'SERVICE_NAME = '.$config['service_name'];

        return $config;
    }

    /**
     * Set tns from config.
     *
     * @param  array  $config
     * @return array
     */
    protected function setTNS(array $config)
    {
        $config['tns'] = "(DESCRIPTION = (ADDRESS = (PROTOCOL = {$config['protocol']})(HOST = {$config['host']})(PORT = {$config['port']})) (CONNECT_DATA =({$config['service']})))";

        return $config;
    }

    /**
     * Set charset from config.
     *
     * @param  array  $config
     * @return array
     */
    protected function setCharset(array $config)
    {
        if (! isset($config['charset'])) {
            $config['charset'] = 'AL32UTF8';
        }

        return $config;
    }

    /**
     * Set DSN host from config.
     *
     * @param  array  $config
     * @return array
     */
    protected function checkMultipleHostDsn(array $config)
    {
        $host = is_array($config['host']) ? $config['host'] : explode(',', $config['host']);

        $count = count($host);
        if ($count > 1) {
            $address = '';
            for ($i = 0; $i < $count; $i++) {
                $address .= '(ADDRESS = (PROTOCOL = '.$config['protocol'].')(HOST = '.trim($host[$i]).')(PORT = '.$config['port'].'))';
            }

            // backwards compatibility for users dont have this field in their php config
            $loadBalance = $config['load_balance'] ?? 'yes';

            // create a tns with multiple address connection
            $config['tns'] = "(DESCRIPTION = {$address} (LOAD_BALANCE = {$loadBalance}) (FAILOVER = on) (CONNECT_DATA = (SERVER = DEDICATED) ({$config['service']})))";
        }

        return $config;
    }

    /**
     * Create a new PDO connection.
     *
     * @param  string  $tns
     * @param  array  $config
     * @param  array  $options
     * @return PDO
     */
    public function createConnection($tns, array $config, array $options)
    {
        // add fallback in case driver is not set, will use pdo instead
        if (! in_array($config['driver'], ['oci8', 'pdo-via-oci8', 'oracle'])) {
            return parent::createConnection($tns, $config, $options);
        }

        $config = $this->setCharset($config);
        $options['charset'] = $config['charset'];

        return new Oci8($tns, $config['username'], $config['password'], $options);
    }
}


text:
import jwt from 'jsonwebtoken';
import request from 'supertest';
import mongoose from 'mongoose';
import { expect } from 'chai';
import {
  BAD_REQUEST, UNAUTHORIZED, CONFLICT, CREATED,
  NOT_FOUND, OK
} from 'http-status';
import {
  forEach, omit, get, merge, clone, keys, pick
} from 'lodash';

import User from '../src/database/models/user.model';
import Client from '../src/database/models/client.model';
import Project from '../src/database/models/project.model';
import exporters from '../src/exporter';
import { api } from '../src/config';
import {
  userTest, userCreate, HOST, createUsers,
  createFullProject, createClient
} from './seed';

describe('# Export Tests', () => {
  let tokenUser;
  let tokenAdmin;
  let adminUser;
  let normalUser;
  let tokenClient;
  let tokenClientFail;
  let tokenClientNotExists;
  let project;
  const locale = 'fr_FR';

  before(() =>
    createUsers()
    .then(([admin, normal]) => {
      adminUser = get(admin, 'user', {});
      tokenAdmin = get(admin, 'token', '');
      normalUser = get(normal, 'user', {});
      tokenUser = get(normal, 'token', '');
      return true;
    })
    .then(() =>
      createFullProject(adminUser))
    .then((prjct) => {
      project = prjct;
      return createClient(adminUser, { projects: [get(project, '_id', '')] })
      .then(() => createClient(adminUser, { name: 'Client fail', projects: [] }, false));
    })
    .then(() =>
      Client.findOne({ projects: { $ne: [] } }).exec())
    .then((client) => {
      tokenClient = jwt.sign(merge(pick(client, ['_id']), { role: 'client' }),
        get(api, 'secret', ''));
      return Client.findOne({ $or: [{ projects: { $size: 0 } }, { projects: null }] })
        .exec();
    })
    .then((client) => {
      tokenClientFail = jwt.sign(merge(pick(client, ['_id']), { role: 'client' }),
        get(api, 'secret', ''));
      tokenClientNotExists = jwt.sign({
        _id: new mongoose.Types.ObjectId(),
        role: 'client'
      }, get(api, 'secret', ''));
      return true;
    }));

  after(() =>
    User.remove({}).exec()
    .then(() => Client.remove({}).exec())
    .then(() => Project.remove({}).exec()));

  describe('## Export Translation : GET /api/export/project/{id}/locale/{locale}/type/{type}', () => {
    forEach(keys(exporters), type => {
      describe(`## Error cases for ${type} type`, () => {
        it(`should fail without a token for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/${locale}/type/${type}`)
          .expect(UNAUTHORIZED));

        it(`should return a 404 for an unauthorized user for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenUser}`)
          .expect(NOT_FOUND));

        it(`should return a 400 for an authorized user for a wrong type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/${locale}/type/${type}fail`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(BAD_REQUEST));

        it(`should return a 400 for an wrong locale for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/toto/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(BAD_REQUEST));

        it(`should return a 404 for an locale not in project for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/nso_ZA/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(NOT_FOUND));

        it(`should return a 400 for an authorized user for a wrong project id a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/toto/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(BAD_REQUEST));

        it(`should return a 404 for an authorized user for a not existing project for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${new mongoose.Types.ObjectId()}/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(NOT_FOUND));
      });

      describe(`## Success cases for ${type} type`, () => {
        it(`should return a 200 for an authorized user for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/project/${get(project, '_id', '')}/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(OK));
      });
    });
  });

  describe('## Export Translation Projects: POST /api/export/projects/locale/{locale}/type/{type}', () => {
    forEach(keys(exporters), type => {
      describe(`## Error cases for ${type} type`, () => {
        it(`should fail without a token for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .send({ projects: [get(project, '_id', '')] })
          .expect(UNAUTHORIZED));

        it(`should return a 404 for an unauthorized user for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .send({ projects: [get(project, '_id', '')] })
          .set('Authorization', `Bearer ${tokenUser}`)
          .expect(NOT_FOUND));

        it(`should return a 400 for an authorized user for a wrong type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}fail`)
          .send({ projects: [get(project, '_id', '')] })
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(BAD_REQUEST));

        it(`should return a 400 for an unexisting locale for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/toto/type/${type}`)
          .send({ projects: [get(project, '_id', '')] })
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .expect(BAD_REQUEST));

        it(`should return a 404 for an locale not in project for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/nso_ZA/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: [get(project, '_id', '')] })
          .expect(NOT_FOUND));

        it(`should return a 400 for an authorized user for a wrong project id a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: ['toto'] })
          .expect(BAD_REQUEST));

        it(`should return a 404 for an authorized user for all not existing project id a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: [new mongoose.Types.ObjectId()] })
          .expect(NOT_FOUND));

        it(`should return a 404 for an authorized user for a not existing project id a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: [get(project, '_id', ''), new mongoose.Types.ObjectId()] })
          .expect(NOT_FOUND));

        it(`should return a 400 for an authorized user with no projects for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ })
          .expect(BAD_REQUEST));

        it(`should return a 400 for an authorized user with empty projects for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: [] })
          .expect(BAD_REQUEST));
      });

      describe(`## Success cases for ${type} type`, () => {
        it(`should return a 200 for an authorized user for a ${type} type`, () =>
          request(HOST)
          .post(`/api/export/projects/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenAdmin}`)
          .send({ projects: [get(project, '_id', '')] })
          .expect(OK));
      });
    });
  });

  describe('## Export Translation client: GET /api/export/locale/{locale}/type/{type}', () => {
    forEach(keys(exporters), type => {
      describe(`## Error cases for ${type} type`, () => {
        it(`should fail without a token for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}`)
          .expect(UNAUTHORIZED));

        it(`should return a 403 for an unauthorized user for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenUser}`)
          .expect(UNAUTHORIZED));

        it(`should return a 400 for an authorized client for a wrong type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}fail`)
          .set('Authorization', `Bearer ${tokenClient}`)
          .expect(BAD_REQUEST));

        it(`should return a 400 for an wrong locale for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/toto/type/${type}`)
          .set('Authorization', `Bearer ${tokenClient}`)
          .expect(BAD_REQUEST));

        it(`should return a 404 for an locale not in project for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/nso_ZA/type/${type}`)
          .set('Authorization', `Bearer ${tokenClient}`)
          .expect(NOT_FOUND));

        it(`should return a 401 for an not existing client for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenClientNotExists}`)
          .expect(UNAUTHORIZED));

        it(`should return a 404 for an authorized client with no project for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenClientFail}`)
          .expect(NOT_FOUND));
      });

      describe(`## Success cases for ${type} type`, () => {
        it(`should return a 200 for an authorized client for a ${type} type`, () =>
          request(HOST)
          .get(`/api/export/locale/${locale}/type/${type}`)
          .set('Authorization', `Bearer ${tokenClient}`)
          .expect(OK));
      });
    });
  });
});


text:
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

#if !SILVERLIGHT && !PORTABLE
using System;
using System.Threading;
using BenchmarkSuite.Framework.Internal;

namespace BenchmarkSuite.Framework
{
    /// <summary>
    /// Marks a test that must run in the STA, causing it
    /// to run in a separate thread if necessary.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=true)]
    public class RequiresSTAAttribute : PropertyAttribute
    {
        /// <summary>
        /// Construct a RequiresSTAAttribute
        /// </summary>
        public RequiresSTAAttribute()
        {
            this.Properties.Add(PropertyNames.ApartmentState, ApartmentState.STA);
        }
    }
}
#endif


text:
"""
This module implements helper functions for vim.Task
"""
__author__ = "VMware, Inc."

import time

import pyVim.connect as connect
from pyVmomi import vim
from pyVmomi import vmodl

def build_task_filter(task):
    """A helper that builds a filter for a particular task object.

    This method builds a property filter for use with a task object and

    :rtype vim.PropertyFilter: property filter for this object
    """

    pc = connect.GetSi().content.propertyCollector

    obj_spec = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)]
    prop_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                           pathSet=[],
                                                           all=True)

    filter_spec = vmodl.query.PropertyCollector.FilterSpec()
    filter_spec.objectSet = obj_spec
    filter_spec.propSet = [prop_spec]
    filter = pc.CreateFilter(filter_spec, True)
    return filter

def wait_for_task(task, *args, **kwargs):
    """A helper method for blocking 'wait' based on the task class.

    This dynamic helper allows you to call .wait() on any task to keep the
    python process from advancing until the task is completed on the vCenter
    or ESX host on which the task is actually running.

    Usage Examples
    ==============

    This method can be used in a number of ways. It is intended to be
    dynamically injected into the vim.Task object and these samples indicate
    that. The method may, however, be used free-standing if you prefer.

    Given an initial call similar to this...

    code::
        rename_task = datastore.Rename('new_name')

    simple use case
    ===============

    code::
        rename_task.wait()

    The main python process will block until the task completes on vSphere.

    use with callbacks
    ==================

    Simple callback use...

    code::
        def output(task, *args):
            print task.info.state

        rename_task.wait(queued=output,
                         running=output,
                         success=output,
                         error=output)

    Only on observed task status transition will the callback fire. That is
    if the task is observed leaving queued and entering running, then the
    callback for 'running' is fired.

    :type task: vim.Task
    :param task: any subclass of the vim.Task object

    :rtype None: returns or raises exception

    :raises vim.RuntimeFault:
    """

    def no_op(task, *args):
        pass

    queued_callback = kwargs.get('queued', no_op)
    running_callback = kwargs.get('running', no_op)
    success_callback = kwargs.get('success', no_op)
    error_callback = kwargs.get('error', no_op)

    si = connect.GetSi()
    pc = si.content.propertyCollector
    filter = build_task_filter(task)

    try:
        version, state = None, None

        # Loop looking for updates till the state moves to a completed state.
        waiting = True
        while waiting:
            update = pc.WaitForUpdates(version)
            version = update.version
            for filterSet in update.filterSet:
                for objSet in filterSet.objectSet:
                    task = objSet.obj
                    for change in objSet.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue

                        if state == vim.TaskInfo.State.success:
                            success_callback(task, *args)
                            waiting = False

                        elif state == vim.TaskInfo.State.queued:
                            queued_callback(task, *args)

                        elif state == vim.TaskInfo.State.running:
                            running_callback(task, *args)

                        elif state == vim.TaskInfo.State.error:
                            error_callback(task, *args)
                            raise task.info.error

    finally:
        if filter:
            filter.Destroy()

def poll_task(task, *args, **kwargs):
    """A helper method for polling state changes on the task class.

    Similar to wait_for_task this helper introduces a sleep_seconds optional
    kwarg and a 'periodic' call back that can be used to check vCenter status
    or interact with vCenter periodically while we wait for a task to complete.
    The prime use-case for this utility is the power_on case described below.

    This dynamic helper allows you to call .wait() on any task to keep the
    python process from advancing until the task is completed on the vCenter
    or ESX host on which the task is actually running.

    NOTE: sleep_seconds of 0 indicates check as fast as possible. This
    mode will generate a great deal of network traffic.

    Usage Examples
    ==============

    This method can be used in a number of ways. It is intended to be
    dynamically injected into the vim.Task object and these samples indicate
    that. The method may, however, be used free-standing if you prefer.

    Given an initial call similar to this...

    code::
        rename_task = datastore.Rename('new_name')

    simple use case
    ===============

    code::
        rename_task.wait()

    The main python process will block until the task completes on vSphere
    the datastore object will be updated automatically with the new name.

    use with sleep_seconds
    ======================
    code::
        rename_task.wait(sleep_seconds=0)

    The default sleep_seconds is 1, meaning the vCenter server is polled at
    most 1 time every 1 second. If you set sleep_seconds to 0, the vCenter
    server will be polled as fast as possible. This has the tendency to create
    a great deal of network traffic.

    code::
        rename_task.wait(sleep_seconds=3)

    The process will wait 3 seconds between polling vCenter for task status.
    The default is to wait 1 second between polling vCenter for task updates.

    use with callbacks
    ==================

    Simple callback use...

    code::
        def output(task, state, *args):
            print state

        rename_task.wait(queued=output,
                         running=output,
                         success=output,
                         error=output)

    Only on observed task status transition will the callback fire. That is
    if the task is observed leaving queued and entering running, then the
    callback for 'running' is fired.

    NOTE: *kwargs

    Callbacks with sleep_seconds
    ============================
    code::
        def output(task):
            print task.info.state

        rename_task.wait(sleep_seconds=3,
                         queued=output,
                         running=output,
                         success=output,
                         error=output)

    The wait method will sleep 3 seconds before re-examining the task status
    again.

    The periodic callback
    =====================
    code::
        def check_for_question(task, virtual_machine):
            if virtual_machine.runtime.question:
                handle_vm_question(virtual_machine)

        power_on_task.wait(virtual_machine, periodic=check_for_question)

    You may have a situation where you need to periodically poll the state of
    another object which might block your task's completion. An example of
    this is the PowerOn_Task operation which can be blocked by a question
    appearing on the VM's runtime. Use a periodic task to poll for such a
    change in state and handle things.

    :type task: vim.Task
    :param task: any subclass of the vim.Task object

    :rtype None: returns or raises exception

    :raises vim.RuntimeFault:
    """

    def no_op(task, *args):
        pass

    sleep_seconds = kwargs.get('sleep_seconds', 1)

    queued_callback = kwargs.get('queued', no_op)
    running_callback = kwargs.get('running', no_op)
    success_callback = kwargs.get('success', no_op)
    error_callback = kwargs.get('error', no_op)

    periodic_callback = kwargs.get('periodic', no_op)

    last_state = None
    while True:
        periodic_callback(task, *args)

        if last_state != task.info.state:
            last_state = task.info.state

            if last_state == vim.TaskInfo.State.success:
                success_callback(task, *args)
                return

            elif last_state == vim.TaskInfo.State.queued:
                queued_callback(task, *args)

            elif last_state == vim.TaskInfo.State.running:
                running_callback(task, *args)

            elif last_state == vim.TaskInfo.State.error:
                error_callback(task, *args)
                raise task.info.error

        if sleep_seconds is not None:
            time.sleep(sleep_seconds)

# NOTE: This kind of injection usually goes at the *bottom* of a file.
vim.Task.poll = poll_task
vim.Task.wait = wait_for_task
vim.Task.is_alive = property(lambda t: t.info.state not in [
    vim.TaskInfo.State.success, vim.TaskInfo.State.error])
vim.Task.filter = property(build_task_filter)


text:
package de.danoeh.antennapod.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ListView;

import org.apache.commons.lang3.Validate;

import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.adapter.NavListAdapter;
import de.danoeh.antennapod.feed.EventDistributor;
import de.danoeh.antennapod.feed.Feed;
import de.danoeh.antennapod.fragment.*;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.storage.DBReader;
import de.danoeh.antennapod.util.StorageUtils;
import de.danoeh.antennapod.util.menuhandler.NavDrawerActivity;

import java.util.List;

/**
 * The activity that is shown when the user launches the app.
 */
public class MainActivity extends ActionBarActivity implements NavDrawerActivity{
    private static final String TAG = "MainActivity";
    private static final int EVENTS = EventDistributor.DOWNLOAD_HANDLED
            | EventDistributor.DOWNLOAD_QUEUED
            | EventDistributor.FEED_LIST_UPDATE
            | EventDistributor.UNREAD_ITEMS_UPDATE
            | EventDistributor.QUEUE_UPDATE;

    public static final String PREF_NAME = "MainActivityPrefs";
    public static final String PREF_IS_FIRST_LAUNCH = "prefMainActivityIsFirstLaunch";

    public static final String EXTRA_NAV_INDEX = "nav_index";
    public static final String EXTRA_NAV_TYPE = "nav_type";
    public static final String EXTRA_FRAGMENT_ARGS = "fragment_args";

    public static final int POS_NEW = 0,
            POS_QUEUE = 1,
            POS_DOWNLOADS = 2,
            POS_HISTORY = 3,
            POS_ADD = 4;

    private ExternalPlayerFragment externalPlayerFragment;
    private DrawerLayout drawerLayout;

    private ListView navList;
    private NavListAdapter navAdapter;

    private ActionBarDrawerToggle drawerToggle;

    private CharSequence drawerTitle;
    private CharSequence currentTitle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme(UserPreferences.getTheme());
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        StorageUtils.checkStorageAvailability(this);
        setContentView(R.layout.main);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        drawerTitle = currentTitle = getTitle();

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navList = (ListView) findViewById(R.id.nav_list);

        TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.nav_drawer_toggle});
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, typedArray.getResourceId(0, 0), R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                currentTitle = getSupportActionBar().getTitle();
                getSupportActionBar().setTitle(drawerTitle);
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getSupportActionBar().setTitle(currentTitle);
                supportInvalidateOptionsMenu();

            }
        };
        typedArray.recycle();

        drawerLayout.setDrawerListener(drawerToggle);
        FragmentManager fm = getSupportFragmentManager();

        FragmentTransaction transaction = fm.beginTransaction();

        Fragment mainFragment = fm.findFragmentByTag("main");
        if (mainFragment != null) {
            transaction.replace(R.id.main_view, mainFragment);
        } else {
            loadFragment(NavListAdapter.VIEW_TYPE_NAV, POS_NEW, null);
        }

        externalPlayerFragment = new ExternalPlayerFragment();
        transaction.replace(R.id.playerFragment, externalPlayerFragment);
        transaction.commit();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        navAdapter = new NavListAdapter(itemAccess, this);
        navList.setAdapter(navAdapter);
        navList.setOnItemClickListener(navListClickListener);

        checkFirstLaunch();
    }

    private void checkFirstLaunch() {
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        if (prefs.getBoolean(PREF_IS_FIRST_LAUNCH, true)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    drawerLayout.openDrawer(navList);
                }
            }, 1500);

            SharedPreferences.Editor edit = prefs.edit();
            edit.putBoolean(PREF_IS_FIRST_LAUNCH, false);
            edit.commit();
        }
    }

    public ActionBar getMainActivtyActionBar() {
        return getSupportActionBar();
    }

    public boolean isDrawerOpen() {
        return drawerLayout != null && navList != null && drawerLayout.isDrawerOpen(navList);
    }

    public List<Feed> getFeeds() {
        return (navDrawerData != null) ? navDrawerData.feeds : null;
    }

    private void loadFragment(int viewType, int relPos, Bundle args) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        // clear back stack
        for (int i = 0; i < fragmentManager.getBackStackEntryCount(); i++) {
            fragmentManager.popBackStack();
        }

        FragmentTransaction fT = fragmentManager.beginTransaction();
        Fragment fragment = null;
        if (viewType == NavListAdapter.VIEW_TYPE_NAV) {
            switch (relPos) {
                case POS_NEW:
                    fragment = new NewEpisodesFragment();
                    break;
                case POS_QUEUE:
                    fragment = new QueueFragment();
                    break;
                case POS_DOWNLOADS:
                    fragment = new DownloadsFragment();
                    break;
                case POS_HISTORY:
                    fragment = new PlaybackHistoryFragment();
                    break;
                case POS_ADD:
                    fragment = new AddFeedFragment();
                    break;

            }
            currentTitle = getString(NavListAdapter.NAV_TITLES[relPos]);
            selectedNavListIndex = relPos;

        } else if (viewType == NavListAdapter.VIEW_TYPE_SUBSCRIPTION) {
            Feed feed = itemAccess.getItem(relPos);
            currentTitle = "";
            fragment = ItemlistFragment.newInstance(feed.getId());
            selectedNavListIndex = NavListAdapter.SUBSCRIPTION_OFFSET + relPos;

        }
        if (fragment != null) {
            if (args != null) {
                fragment.setArguments(args);
            }
            fT.replace(R.id.main_view, fragment, "main");
            fragmentManager.popBackStack();
        }
        fT.commit();
        getSupportActionBar().setTitle(currentTitle);
        if (navAdapter != null) {
            navAdapter.notifyDataSetChanged();
        }
    }

    public void loadNavFragment(int position, Bundle args) {
        loadFragment(NavListAdapter.VIEW_TYPE_NAV, position, args);
    }

    public void loadFeedFragment(long feedID) {
        if (navDrawerData != null) {
            for (int i = 0; i < navDrawerData.feeds.size(); i++) {
                if (navDrawerData.feeds.get(i).getId() == feedID) {
                    loadFragment(NavListAdapter.VIEW_TYPE_SUBSCRIPTION, i, null);
                    break;
                }
            }
        }
    }

    public void loadChildFragment(Fragment fragment) {
        Validate.notNull(fragment);
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .replace(R.id.main_view, fragment, "main")
                .addToBackStack(null)
                .commit();
    }

    private AdapterView.OnItemClickListener navListClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int viewType = parent.getAdapter().getItemViewType(position);
            if (viewType != NavListAdapter.VIEW_TYPE_SECTION_DIVIDER && position != selectedNavListIndex) {
                int relPos = (viewType == NavListAdapter.VIEW_TYPE_NAV) ? position : position - NavListAdapter.SUBSCRIPTION_OFFSET;
                loadFragment(viewType, relPos, null);
                selectedNavListIndex = position;
                navAdapter.notifyDataSetChanged();
            }
            drawerLayout.closeDrawer(navList);
        }
    };

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
        if (savedInstanceState != null) {
            currentTitle = savedInstanceState.getString("title");
            if (!drawerLayout.isDrawerOpen(navList)) {
                getSupportActionBar().setTitle(currentTitle);
            }
            selectedNavListIndex = savedInstanceState.getInt("selectedNavIndex");
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("title", getSupportActionBar().getTitle().toString());
        outState.putInt("selectedNavIndex", selectedNavListIndex);

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        StorageUtils.checkStorageAvailability(this);
        EventDistributor.getInstance().register(contentUpdate);

        Intent intent = getIntent();
        if (navDrawerData != null && intent.hasExtra(EXTRA_NAV_INDEX) && intent.hasExtra(EXTRA_NAV_TYPE)) {
            handleNavIntent();
        }

        loadData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        cancelLoadTask();
        EventDistributor.getInstance().unregister(contentUpdate);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.show_preferences:
                startActivity(new Intent(this, PreferenceActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    private DBReader.NavDrawerData navDrawerData;
    private AsyncTask<Void, Void, DBReader.NavDrawerData> loadTask;
    private int selectedNavListIndex = 0;

    private NavListAdapter.ItemAccess itemAccess = new NavListAdapter.ItemAccess() {
        @Override
        public int getCount() {
            if (navDrawerData != null) {
                return navDrawerData.feeds.size();
            } else {
                return 0;
            }
        }

        @Override
        public Feed getItem(int position) {
            if (navDrawerData != null && position < navDrawerData.feeds.size()) {
                return navDrawerData.feeds.get(position);
            } else {
                return null;
            }
        }

        @Override
        public int getSelectedItemIndex() {
            return selectedNavListIndex;
        }

        @Override
        public int getQueueSize() {
            return (navDrawerData != null) ? navDrawerData.queueSize : 0;
        }

        @Override
        public int getNumberOfUnreadItems() {
            return (navDrawerData != null) ? navDrawerData.numUnreadItems : 0;
        }

    };

    private void loadData() {
        cancelLoadTask();
        loadTask = new AsyncTask<Void, Void, DBReader.NavDrawerData>() {
            @Override
            protected DBReader.NavDrawerData doInBackground(Void... params) {
                return DBReader.getNavDrawerData(MainActivity.this);
            }

            @Override
            protected void onPostExecute(DBReader.NavDrawerData result) {
                super.onPostExecute(navDrawerData);
                boolean handleIntent = (navDrawerData == null);

                navDrawerData = result;
                navAdapter.notifyDataSetChanged();

                if (handleIntent) {
                    handleNavIntent();
                }
            }
        };
        loadTask.execute();
    }

    private void cancelLoadTask() {
        if (loadTask != null) {
            loadTask.cancel(true);
        }
    }

    private EventDistributor.EventListener contentUpdate = new EventDistributor.EventListener() {

        @Override
        public void update(EventDistributor eventDistributor, Integer arg) {
            if ((EVENTS & arg) != 0) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Received contentUpdate Intent.");
                loadData();
            }
        }
    };

    private void handleNavIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(EXTRA_NAV_INDEX) && intent.hasExtra(EXTRA_NAV_TYPE)) {
            int index = intent.getIntExtra(EXTRA_NAV_INDEX, 0);
            int type = intent.getIntExtra(EXTRA_NAV_TYPE, NavListAdapter.VIEW_TYPE_NAV);
            Bundle args = intent.getBundleExtra(EXTRA_FRAGMENT_ARGS);
            loadFragment(type, index, args);
        }
        setIntent(new Intent(MainActivity.this, MainActivity.class)); // to avoid handling the intent twice when the configuration changes
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
}


text:
"""Treadmill container initialization.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import logging
import os
import pprint

import click

from treadmill import subproc
from treadmill.fs import linux as fs_linux

_LOGGER = logging.getLogger(__name__)

def init():
    """Top level command handler."""
    @click.command(name='start-container')
    @click.option('--container-root', type=click.Path(exists=True),
                  required=True)
    def start_container(container_root):
        """Treadmill container boot process.
        """
        _LOGGER.info('Initializing container: %s', container_root)

        # We only preserve anything mounted on the container root.
        fs_linux.cleanup_mounts([container_root + '*'], ignore_exc=True)
        # Mount a proc in the new namespaces
        fs_linux.mount_procfs(container_root)
        # remount current proc to /proc
        # new process entering container namespace can see the correct /proc
        fs_linux.mount_procfs('/')

        # Chroot into the container
        os.chroot(container_root)
        os.chdir('/')

        # XXX: Debug info
        _LOGGER.debug('Current mounts: %s',
                      pprint.pformat(fs_linux.list_mounts()))

        # Clean the environ
        # TODO: Remove me once clean environment management is merged in.
        del os.environ['PYTHONPATH']
        del os.environ['LC_ALL']
        del os.environ['LANG']

        subproc.safe_exec(
            [
                's6_svscan',
                '-s',
                '/services'
            ]
        )

    return start_container


text:
package me.kuehle.carreport.data.calculation;

import android.content.Context;

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

import me.kuehle.carreport.Preferences;
import me.kuehle.carreport.R;

public class DistanceToVolumeCalculation extends AbstractVolumeDistanceCalculation {
    public DistanceToVolumeCalculation(Context context) {
        super(context);
    }

    @Override
    public String getName() {
        return mContext.getString(R.string.calc_option_distance_to_volume,
                getInputUnit(), getOutputUnit());
    }

    @Override
    public String getInputUnit() {
        Preferences prefs = new Preferences(mContext);
        return prefs.getUnitDistance();
    }

    @Override
    public String getOutputUnit() {
        Preferences prefs = new Preferences(mContext);
        return prefs.getUnitVolume();
    }

    @Override
    protected CalculationItem[] onCalculate(double input) {
        List<CalculationItem> items = new ArrayList<>();

        for (int i = 0; i < mNames.size(); i++) {
            String name = mNames.get(i);
            double avgConsumption = mAvgConsumptions.get(i);

            items.add(new CalculationItem(name, input * avgConsumption));
        }

        return items.toArray(new CalculationItem[items.size()]);
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace Tests.Serialization.RuntimeModels
{
	using System;
	using SafetySharp.Modeling;
	using Shouldly;
	using Utilities;

	internal class DelegatesInArray : TestModel
	{
		private static bool _hasConstructorRun;

		protected override void Check()
		{
			var c = new C();
			var m = InitializeModel(c);

			_hasConstructorRun = false;
			Create(m);

			ExecutableStateFormulas.ShouldBeEmpty();
			RootComponents.Length.ShouldBe(1);

			var root = RootComponents[0];
			root.ShouldBeOfType<C>();
			c = (C)root;

			c.Funcs.Length.ShouldBe(2);
			c.Funcs[0]().ShouldBe(true);
			c.Funcs[1]().ShouldBe(false);

			_hasConstructorRun.ShouldBe(false);
		}

		private class C : Component
		{
			public readonly Func<bool>[] Funcs = new Func<bool>[2];

			public C()
			{
				_hasConstructorRun = true;

				Funcs[0] = M;
				Funcs[1] = () => false;
			}

			private bool M()
			{
				return true;
			}
		}
	}
}


text:
@implementation ProfileHeaderView
@synthesize user, padding;

+ (CGFloat)defaultHeight {
    CGFloat height = 65.0;

    if ([UIView instancesRespondToSelector:@selector(tintColor)]) {
        height += 12.0;
    }

    return height;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        titleLabel = [[UILabel alloc] init];
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        [titleLabel setTextColor:[UIColor blackColor]];
        [titleLabel setBackgroundColor:[UIColor clearColor]];
        [titleLabel setFont:[UIFont boldSystemFontOfSize:19.0f]];
        [self addSubview:titleLabel];

        subtitleLabel = [[UILabel alloc] init];
        [subtitleLabel setTextAlignment:NSTextAlignmentLeft];
        [subtitleLabel setTextColor:[UIColor darkGrayColor]];
        [subtitleLabel setBackgroundColor:[UIColor clearColor]];
        [subtitleLabel setFont:[UIFont systemFontOfSize:14.0f]];
        [self addSubview:subtitleLabel];

        if (![UIView instancesRespondToSelector:@selector(tintColor)]) {
            [titleLabel setShadowColor:[UIColor whiteColor]];
            [titleLabel setShadowOffset:CGSizeMake(0.0f, 1.0f)];

            [subtitleLabel setShadowColor:[UIColor whiteColor]];
            [subtitleLabel setShadowOffset:CGSizeMake(0.0f, 1.0f)];
        }
    }

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat width = [self bounds].size.width;
    [titleLabel setFrame:CGRectMake(padding, 20.0f, width - (padding * 2), 20.0f)];
    [subtitleLabel setFrame:CGRectMake(padding, 42.0f, width - (padding * 2), 20.0f)];
}

- (void)setPadding:(CGFloat)padding_ {
    padding = padding_;

    [self setNeedsLayout];
}

- (NSString *)title {
    return [titleLabel text];
}

- (void)setTitle:(NSString *)title {
    [titleLabel setText:title];
}

- (NSString *)subtitle {
    return [subtitleLabel text];
}

- (void)setSubtitle:(NSString *)subtitle {
    [subtitleLabel setText:subtitle];
}

- (void)dealloc {
    [user release];
    [subtitleLabel release];
    [titleLabel release];

    [super dealloc];
}

@end


text:
import * as b from "bobril";
import * as styles from "./styles";
import * as c from "./styleConsts";

export interface IBadgeData {
  children?: b.IBobrilChildren;
  badgeContent: b.IBobrilChildren;
  primary?: boolean;
  secondary?: boolean;
}

interface IBadgeCtx extends b.IBobrilCtx {
  data: IBadgeData;
}

const radius = 12;
const radius2x = Math.floor(2 * radius);

const rootStyle = b.styleDef([c.positionRelative, {
  display: 'inline-block',
  padding: [radius2x + 'px', radius2x + 'px', radius + 'px', radius + 'px'].join(' '),
}]);

const badgeStyle = b.styleDef([c.positionAbsolute, c.circle, {
  display: 'flex',
  flexDirection: 'row',
  flexWrap: 'wrap',
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  top: 0,
  right: 0,
  fontWeight: "medium",
  fontSize: radius,
  width: radius2x,
  height: radius2x,
  backgroundColor: styles.alternateTextColor,
  color: styles.textColor,
}]);

const primaryStyle = b.styleDefEx(badgeStyle, {
  backgroundColor: styles.accent1Color,
  color: styles.alternateTextColor
});

const secondaryStyle = b.styleDefEx(badgeStyle, {
  backgroundColor: styles.primary1Color,
  color: styles.alternateTextColor
});

export const Badge = b.createComponent<IBadgeData>({
  render(ctx: IBadgeCtx, me: b.IBobrilNode) {
    const d = ctx.data;
    b.style(me, rootStyle);
    me.children = [
      d.children,
      b.styledDiv(d.badgeContent, badgeStyle, d.primary && primaryStyle, d.secondary && secondaryStyle)
    ];
  }
});


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/android/media_player_listener.h"

#include "base/android/jni_android.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "jni/MediaPlayerListener_jni.h"
#include "media/base/android/media_player_android.h"

using base::android::AttachCurrentThread;
using base::android::CheckException;
using base::android::ScopedJavaLocalRef;

namespace media {

MediaPlayerListener::MediaPlayerListener(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    base::WeakPtr<MediaPlayerAndroid> media_player)
    : task_runner_(task_runner),
      media_player_(media_player) {
  DCHECK(task_runner_.get());
  DCHECK(media_player_);
}

MediaPlayerListener::~MediaPlayerListener() {}

void MediaPlayerListener::CreateMediaPlayerListener(
    jobject context, jobject media_player) {
  JNIEnv* env = AttachCurrentThread();
  CHECK(env);
  if (j_media_player_listener_.is_null()) {
    j_media_player_listener_.Reset(Java_MediaPlayerListener_create(
        env, reinterpret_cast<intptr_t>(this), context, media_player));
  }
}

void MediaPlayerListener::ReleaseMediaPlayerListenerResources() {
  JNIEnv* env = AttachCurrentThread();
  CHECK(env);
  if (!j_media_player_listener_.is_null()) {
    Java_MediaPlayerListener_releaseResources(
        env, j_media_player_listener_.obj());
  }
  j_media_player_listener_.Reset();
}

void MediaPlayerListener::OnMediaError(
    JNIEnv* /* env */, jobject /* obj */, jint error_type) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnMediaError, media_player_, error_type));
}

void MediaPlayerListener::OnVideoSizeChanged(
    JNIEnv* /* env */, jobject /* obj */, jint width, jint height) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnVideoSizeChanged, media_player_,
      width, height));
}

void MediaPlayerListener::OnBufferingUpdate(
    JNIEnv* /* env */, jobject /* obj */, jint percent) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnBufferingUpdate, media_player_, percent));
}

void MediaPlayerListener::OnPlaybackComplete(
    JNIEnv* /* env */, jobject /* obj */) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnPlaybackComplete, media_player_));
}

void MediaPlayerListener::OnSeekComplete(
    JNIEnv* /* env */, jobject /* obj */) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnSeekComplete, media_player_));
}

void MediaPlayerListener::OnMediaPrepared(
    JNIEnv* /* env */, jobject /* obj */) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnMediaPrepared, media_player_));
}

void MediaPlayerListener::OnMediaInterrupted(
    JNIEnv* /* env */, jobject /* obj */) {
  task_runner_->PostTask(FROM_HERE, base::Bind(
      &MediaPlayerAndroid::OnMediaInterrupted, media_player_));
}

bool MediaPlayerListener::RegisterMediaPlayerListener(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace media


text:
This is a Roll20 character sheet for use with the Gamma World 7th edition system
(the one based on D&D 4E).


text:
require 'rails_helper'

RSpec.describe ImagesController, type: :controller do
  before(:each) do
    @user1= User.create!(username: Faker::Internet.user_name, password: "passwords", first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, description: Faker::StarWars.quote, email: Faker::Internet.email, genres: Faker::Book.genre)
    @studio1= Studio.create!(name: "Studio1", owner: @user1, full_address: "351 W Hubbard St, Chicago, IL 60654", description: "I hate this test", price: 500, website:"http://wikijamz.herokuapp.com")
    @availability1= Availability.create!(start_time: "2016-04-26 01:00:00", end_time: "2016-04-26 20:00:00", studio: @studio1)
    @image = Image.create(media: File.open("app/assets/images/studio_photos/2.jpg"))
  end

  context '#new' do
    before { allow(controller).to receive(:current_user) {@user1}}

    it 'finds the right studio based on id' do
      get :new, studio_id: @studio1.id
      expect(assigns(:studio)).to eq @studio1
    end

    it 'creates a new image object' do
      get :new, studio_id: @studio1.id
      expect(assigns(:image)).to be_a Image
    end
  end

  context '#show' do
    before { allow(controller).to receive(:current_user) {@user1}}

    it 'finds the right studio' do
      get :show, studio_id: @studio1.id, id: @image.id
      expect(assigns(:studio)).to eq @studio1
    end

    it 'finds the right image' do
      get :show, studio_id: @studio1.id, id: @image.id
      expect(assigns(:image)).to eq @image
    end
  end

end


text:
"""
Update the README.md file with the authors from the git log
"""

import re
import subprocess

AUTHORS = "README.md"
IGNORE = [ "nick@raig-wood.com" ]

def load():
    """
    returns a set of emails already in authors
    """
    with open(AUTHORS) as fd:
        authors = fd.read()
    emails = set(re.findall(r"<(?!!--)(.*?)>", authors))
    emails.update(IGNORE)
    return emails

def add_email(name, email):
    """
    adds the email passed in to the end of authors
    """
    print("Adding %s <%s>" % (name, email))
    with open(AUTHORS, "a+") as fd:
        print("- %s <%s>" % (name, email), file=fd)
    subprocess.check_call(["git", "commit", "-m", "Add %s to contributors" % name, AUTHORS])

def main():
    out = subprocess.check_output(["git", "log", '--reverse', '--format=%an|%ae', "master"])

    previous = load()
    for line in out.split(b"\n"):
        line = line.decode("utf-8")
        line = line.strip()
        if line == "":
            continue
        name, email = line.split("|")
        if email in previous:
            continue
        previous.add(email)
        add_email(name, email)

if __name__ == "__main__":
    main()


text:
'use strict';

//const fizzBuzz = require('./fizz-buzz');
require('should');

xdescribe('FizzBuzz', function () {
  it('should do something', function () {
    'the answer'.should.equal('42');
  });
});


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/Assertions.h"
#include "nsAlgorithm.h"
#include "nsDebug.h"

namespace mozilla {

struct StackBlock;
struct StackMark;
class AutoStackArena;

/**
 * Private helper class for AutoStackArena.
 */
class StackArena {
private:
  friend class AutoStackArena;
  StackArena();
  ~StackArena();

  nsresult Init() { return mBlocks ? NS_OK : NS_ERROR_OUT_OF_MEMORY; }

  // Memory management functions
  void* Allocate(size_t aSize);
  void Push();
  void Pop();

  size_t SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) const;

  // our current position in memory
  size_t mPos;

  // a list of memory block. Usually there is only one
  // but if we overrun our stack size we can get more memory.
  StackBlock* mBlocks;

  // the current block of memory we are passing our chucks of
  StackBlock* mCurBlock;

  // our stack of mark where push has been called
  StackMark* mMarks;

  // the current top of the mark list
  PRUint32 mStackTop;

  // the size of the mark array
  PRUint32 mMarkLength;
};

/**
 * Class for stack scoped arena memory allocations.
 *
 * Callers who wish to allocate memory whose lifetime corresponds to
 * the lifetime of a stack-allocated object can use this class.
 * First, declare an AutoStackArena object on the stack.
 * Then all subsequent calls to Allocate will allocate memory from an
 * arena pool that will be freed when that variable goes out of scope.
 * Nesting is allowed.
 *
 * The allocations cannot be for more than 4044 bytes.
 */
class NS_STACK_CLASS AutoStackArena {
public:
  AutoStackArena() : mOwnsStackArena(false) {
    if (!gStackArena) {
      gStackArena = new StackArena();
      mOwnsStackArena = true;
      gStackArena->Init();
    }
    gStackArena->Push();
  }

  ~AutoStackArena() {
    gStackArena->Pop();
    if (mOwnsStackArena) {
      delete gStackArena;
      gStackArena = nsnull;
    }
  }

  static void* Allocate(size_t aSize) {
    MOZ_ASSERT(aSize <= 4044);
    return gStackArena->Allocate(aSize);
  }

private:
  static StackArena* gStackArena;
  bool mOwnsStackArena;
};

} // namespace mozilla


text:
package iseeapp.co.iseeapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.Uri;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Toast;

import com.facebook.AppEventsLogger;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.Facebook;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GameActivity extends ActionBarActivity {

    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 0;
    private TakePhotoFragment photoFragment;
    private LoginFagment loginFagment;
    private guess guessFagment;
    private ResultList listFragment;
    private MenuFragment menuFragmaent;
    private Register registerFragment;

    private FragmentTransaction transaction;
    private int fragID = 0;
    private Context con;
    private boolean isUserLogedIn = false;
    private Uri file;
    private Session session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        printkey();

        photoFragment = new TakePhotoFragment();
        loginFagment = new LoginFagment();
        registerFragment = new Register();
        guessFagment = new guess();

        listFragment = new ResultList();
        menuFragmaent = new MenuFragment();

        con = this.getApplicationContext();

        checklogin();
    }

    public void setFile(Uri f){
        file = f;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if((fragID==1)||(fragID==1)){
                return false;
            }else {
                gotToMenu();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();  // Always call the superclass method first

        AppEventsLogger.activateApp(this);
        //Toast.makeText(this,"reusumed: ====>   "+fragID,Toast.LENGTH_SHORT).show();
        // Get the Camera in
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    public void gotologin(){
        fragID = 1;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) loginFagment)
                .commit();

    }

    public void gotoTakePhoto(){

        fragID = 2;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) photoFragment)
                .commit();

    }

    public void gotToMenu(){

        fragID = 0;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) menuFragmaent)
                .commit();

    }

    public void gotoGuessPhoto(){

        fragID = 3;
        guessFagment.setArguments(file);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) guessFagment)
                .commit();

    }

    public void gotoResultsPhoto(){
        fragID = 4;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) listFragment)
                .commit();

    }

    public void gotoRegister() {
        fragID = 5;
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, (android.support.v4.app.Fragment) registerFragment)
                .commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_game, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        session = Session.getActiveSession();
        Log.d("test",""+requestCode);
        if(requestCode==64206){
        if(session !=null) {
            session.onActivityResult(this, requestCode, resultCode,
                    data);
            if (session.isOpened()) {
                loginResult(true);
            } else {
                loginResult(false);
            }
        }
        }else {

            photoFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void checklogin(){
        Session session = Session.getActiveSession();

        if(session==null){
            // try to restore from cache
            session = Session.openActiveSessionFromCache(this);
        }

        if(session!=null && session.isOpened()){
            gotToMenu();
        }
        else{
            gotologin();
        }
    }

    public void login() {
        isUserLogedIn = true;
    }

    public void setpoint(Point point) {
           guessFagment.setPoint(point);
    }

    public void setName(String name) {
        guessFagment.setName(name);
    }

    private void printkey(){
        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo("iseeapp.co.iseeapp",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }

    // Facebook Login Result
    public void loginResult(boolean result) {
        // TODO Auto-generated method stub
        if (result) {
            Log.e("Facebook Login ", "Successful");
            gotToMenu();
        } else {
            Log.e("Facebook Logout", "Un Successful");
        }
    }

    public void fblogin() {
        session = Session.getActiveSession();

        if (session == null
                || session.getState() == SessionState.CLOSED_LOGIN_FAILED
                || session.getState() == SessionState.CLOSED) {
            session = new Session(this);
        }
        if (!session.isOpened()) {
            session.openForRead(new Session.OpenRequest(this));
        }
        Session.setActiveSession(session);

    }
}


text:
package com.spotify.helios.servicescommon;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.readytalk.metrics.StatsDReporter;
import io.dropwizard.lifecycle.Managed;
import java.util.List;

public class ManagedStatsdReporter implements Managed {

  private static final int POLL_INTERVAL_SECONDS = 15;

  private final StatsDReporter statsdReporter;

  public ManagedStatsdReporter(final String endpoint, final MetricRegistry registry) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(endpoint));

    final List<String> parts = Splitter.on(":").splitToList(endpoint);
    checkArgument(parts.size() == 2, "Specification of statsd host port has wrong number of "
                                     + "parts. Should be host:port");
    final String host = parts.get(0);
    final int port = Integer.valueOf(parts.get(1));
    statsdReporter = StatsDReporter.forRegistry(registry).build(host, port);
  }

  @Override
  public void start() throws Exception {
    statsdReporter.start(POLL_INTERVAL_SECONDS, SECONDS);
  }

  @Override
  public void stop() throws Exception {
    statsdReporter.close();
  }
}


text:
package bytecodeAnalysis.data;

import bytecodeAnalysis.ExpectContract;

// A class to test the clash of the same class in different source paths
// See also ../../conflict/TestConflict.java
public class TestConflict {
  static int throwInDataNativeInConflict() {
    throw new RuntimeException();
  }

  static native int nativeInDataThrowInConflict();

  @ExpectContract(value = "->fail", pure = true)
  static int throwBoth() {
    throw new RuntimeException();
  }

  void pureInDataSideEffectInConflict() { }

  void sideEffectInDataPureInConflict() {
    System.out.println();
  }

  @ExpectContract(pure = true)
  void pureBoth() { }

  void sideEffectBoth() {
    System.out.println();
  }
}