text:
// Copyright [2011] [PagSeguro Internet Ltda.]
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

using System;
using System.Net;
using Uol.PagSeguro.Domain;
using Uol.PagSeguro.Exception;
using Uol.PagSeguro.Resources;
using Uol.PagSeguro.Service;

namespace CancelPreApproval
{
    class Program
    {
        static void Main(string[] args)
        {

            bool isSandbox = false;

            EnvironmentConfiguration.ChangeEnvironment(isSandbox);

            try
            {

                AccountCredentials credentials = PagSeguroConfiguration.Credentials(isSandbox);

                // TODO: Substitute the code below with a valid transaction code for your transaction
                bool cancelResult = PreApprovalService.CancelPreApproval(credentials, "3DFAD3123412340334A96F9136C38804");

                Console.WriteLine(cancelResult);
                Console.ReadKey();
            }
            catch (PagSeguroServiceException exception)
            {
                Console.WriteLine(exception.Message + "\n");

                foreach (ServiceError element in exception.Errors)
                {
                    Console.WriteLine(element + "\n");
                }
                Console.ReadKey();
            }
        }
    }
}


text:
package com.ctrip.xpipe.redis.keeper.monitor;

import com.ctrip.xpipe.redis.core.store.CommandStore;
import com.ctrip.xpipe.redis.core.store.CommandsListener;
import com.ctrip.xpipe.redis.keeper.AbstractRedisKeeperTest;
import com.ctrip.xpipe.redis.keeper.monitor.impl.DefaultCommandStoreDelay;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.concurrent.atomic.AtomicInteger;

import static org.mockito.Mockito.mock;

/**
 * @author wenchao.meng
 *
 *         Nov 24, 2016
 */
@RunWith(MockitoJUnitRunner.class)
public class DefaultCommandDelayTest extends AbstractRedisKeeperTest {

	private int delayLogLimitMicro = 5000;
	private int testCount = 100;
	private AtomicInteger logCount = new AtomicInteger();

	private DefaultCommandStoreDelay commandDelay;

	@Mock
	private CommandStore commandStore;

	@Before
	public void beforeCommandDelayTest() {
		commandDelay = new TestCommandDelay(commandStore, delayLogLimitMicro);
	}

	@Test
	public void testOffsetOverrideNoSend(){

		long offset = 0;
		for (int i = 0; i < DefaultCommandStoreDelay.SUPPORT_SLAVES -1; i++) {

			offset++;
			commandDelay.beginWrite();
			commandDelay.endWrite(offset);
		}

		commandDelay.beginWrite();
		commandDelay.endWrite(offset);

	}

	@Test
	public void testOffsetOverrideSendNoFlush(){

		long offset = 0;
		for (int i = 0; i < DefaultCommandStoreDelay.SUPPORT_SLAVES -1; i++) {

			offset++;
			commandDelay.beginWrite();
			commandDelay.endWrite(offset);
			commandDelay.beginSend(mock(CommandsListener.class), offset);
		}

		commandDelay.beginWrite();
		commandDelay.endWrite(offset);

	}

	@Test
	public void testEndWrite() {

		long offset = 0;

		commandDelay.beginWrite();
		commandDelay.endWrite(offset);

		Assert.assertEquals(0, logCount.get());

		for (int i = 0; i < testCount; i++) {
			offset++;
			commandDelay.beginWrite();
			sleep((delayLogLimitMicro / 1000) + 2);
			commandDelay.endWrite(offset);
			Assert.assertEquals(i + 1, logCount.get());
		}
	}

	@Test
	public void testBeginSend() {

		long offset = 0;
		long expectedLogCount = 0;

		for (int i = 0; i < testCount; i++) {

			offset++;
			commandDelay.beginWrite();
			commandDelay.endWrite(offset);
			sleep((delayLogLimitMicro / 1000) + 2);

			for (int j = 0; j < DefaultCommandStoreDelay.SUPPORT_SLAVES * 2; j++) {

				commandDelay.beginSend(mock(CommandsListener.class), offset);
				if (j < DefaultCommandStoreDelay.SUPPORT_SLAVES) {
					expectedLogCount++;
				}
				Assert.assertEquals(expectedLogCount, logCount.get());
			}
		}
	}

	@Test
	public void testFlush() {

		long offset = 0;

		for (int i = 0; i < testCount; i++) {

			offset++;
			CommandsListener commandsListener = mock(CommandsListener.class);

			commandDelay.beginWrite();
			commandDelay.endWrite(offset);

			commandDelay.beginSend(commandsListener, offset);
			sleep((delayLogLimitMicro / 1000) + 2);

			commandDelay.flushSucceed(commandsListener, offset);
			Assert.assertEquals(i+1, logCount.get());

			commandDelay.flushSucceed(mock(CommandsListener.class), offset);
			Assert.assertEquals(i+1, logCount.get());

		}
	}

	public class TestCommandDelay extends DefaultCommandStoreDelay {

		public TestCommandDelay(CommandStore commandStore, int delayLogLimitMicro) {
			super(commandStore, () -> delayLogLimitMicro);
		}

		@Override
		protected boolean logIfShould(long begin, long end, String message) {

			if (super.logIfShould(begin, end, message)) {
				logCount.incrementAndGet();
				return true;
			}
			return false;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Translation\Catalogue;

/**
 * Diff operation between two catalogues.
 *
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class DiffOperation extends AbstractOperation
{
    /**
     * {@inheritdoc}
     */
    protected function processDomain($domain)
    {
        $this->messages[$domain] = array(
            'all'      => array(),
            'new'      => array(),
            'obsolete' => array(),
        );

        foreach ($this->source->all($domain) as $id => $message) {
            if ($this->target->has($id, $domain)) {
                $this->messages[$domain]['all'][$id] = $message;
                $this->result->add(array($id => $message), $domain);
            } else {
                $this->messages[$domain]['obsolete'][$id] = $message;
            }
        }

        foreach ($this->target->all($domain) as $id => $message) {
            if (!$this->source->has($id, $domain)) {
                $this->messages[$domain]['all'][$id] = $message;
                $this->messages[$domain]['new'][$id] = $message;
                $this->result->add(array($id => $message), $domain);
            }
        }
    }
}


text:
{% extends "post.html" %}

{% block post_title %}
No Cheating Allowed!!!
{% endblock %}

{% block post_subtitle %}
Khan Academy's answer to students cheating on interactive exercies.
{% endblock %}

{% block content %}

    For the past 3 months I have been interning at Khan Academy in Mountain
    View, California. It has been such a great experience and I am very glad
    to have had the opportunity to work with so many wonderful people! Today I
    even got to publish a blog post about one of my projects to the KA
    Engineering blog. You can read it by following
    this link.

{% endblock %}


text:
from fom.session import Fluid
from fom.mapping import Namespace, Tag
from fom.mapping import Object, tag_value, readonly_tag_value
import settings
import time
import calendar
import article
import json

# Fluidinfo parser

session = Fluid()

class fi_article(Object):
	about = readonly_tag_value(u'fluiddb/about')
	doi = tag_value(settings.namespace + '/article/doi')
	doi_url = tag_value(settings.namespace + '/article/doi_url')
	pmid = tag_value(settings.namespace + '/article/pmid')
	journal_id = tag_value(settings.namespace + '/article/journal_id')
	journal_title = tag_value(settings.namespace + '/article/journal_title')
	journal_issn_ppub = tag_value(settings.namespace + '/article/journal_issn_ppub')
	journal_issn_epub = tag_value(settings.namespace + '/article/journal_issn_epub')
	publisher = tag_value(settings.namespace + '/article/publisher')
	article_title = tag_value(settings.namespace + '/article/article_title')
	abstract = tag_value(settings.namespace + '/article/abstract')
	article_type = tag_value(settings.namespace + '/article/article_type')
	article_institution = tag_value(settings.namespace + '/article/article_institution')
	article_country = tag_value(settings.namespace + '/article/article_country')
	subject_area = tag_value(settings.namespace + '/article/subject_area')
	research_organism = tag_value(settings.namespace + '/article/research_organism')
	correspondence = tag_value(settings.namespace + '/article/correspondence')
	author_notes = tag_value(settings.namespace + '/article/author_notes')
	keywords = tag_value(settings.namespace + '/article/keywords')
	pub_date_date = tag_value(settings.namespace + '/article/pub_date_date')
	pub_date_day = tag_value(settings.namespace + '/article/pub_date_day')
	pub_date_month = tag_value(settings.namespace + '/article/pub_date_month')
	pub_date_year = tag_value(settings.namespace + '/article/pub_date_year')
	pub_date_timestamp = tag_value(settings.namespace + '/article/pub_date_timestamp')
	received_date_date = tag_value(settings.namespace + '/article/received_date_date')
	received_date_day = tag_value(settings.namespace + '/article/received_date_day')
	received_date_month = tag_value(settings.namespace + '/article/received_date_month')
	received_date_year = tag_value(settings.namespace + '/article/received_date_year')
	received_date_timestamp = tag_value(settings.namespace + '/article/received_date_timestamp')
	accepted_date_date = tag_value(settings.namespace + '/article/accepted_date_date')
	accepted_date_day = tag_value(settings.namespace + '/article/accepted_date_day')
	accepted_date_month = tag_value(settings.namespace + '/article/accepted_date_month')
	accepted_date_year = tag_value(settings.namespace + '/article/accepted_date_year')
	accepted_date_timestamp = tag_value(settings.namespace + '/article/accepted_date_timestamp')
	award_group_funding_source = tag_value(settings.namespace + '/article/award_group_funding_source')
	award_group_award_id = tag_value(settings.namespace + '/article/award_group_award_id')
	award_group_principle_award_recipient = tag_value(settings.namespace + '/article/award_group_principle_award_recipient')
	funding_statement = tag_value(settings.namespace + '/article/funding_statement')
	copyright_statement = tag_value(settings.namespace + '/article/copyright_statement')
	copyright_year = tag_value(settings.namespace + '/article/copyright_year')
	copyright_holder = tag_value(settings.namespace + '/article/copyright_holder')
	license = tag_value(settings.namespace + '/article/license')
	license_type = tag_value(settings.namespace + '/article/license_type')
	license_url = tag_value(settings.namespace + '/article/license_url')
	ack = tag_value(settings.namespace + '/article/ack')
	conflict = tag_value(settings.namespace + '/article/conflict')
	authors = tag_value(settings.namespace + '/article/authors')
	refs = tag_value(settings.namespace + '/article/refs')
	components = tag_value(settings.namespace + '/article/components')

class fi_ref(Object):
	about = readonly_tag_value(u'fluiddb/about')
	ref = tag_value(settings.namespace + '/ref/ref')
	article_doi = tag_value(settings.namespace + '/ref/article_doi')
	article_title = tag_value(settings.namespace + '/ref/article_title')
	publication_type = tag_value(settings.namespace + '/ref/publication_type')
	doi = tag_value(settings.namespace + '/ref/doi')
	doi_url = tag_value(settings.namespace + '/ref/doi_url')
	pmid = tag_value(settings.namespace + '/ref/pmid')
	authors = tag_value(settings.namespace + '/ref/authors')
	year = tag_value(settings.namespace + '/ref/year')
	source = tag_value(settings.namespace + '/ref/source')
	volume = tag_value(settings.namespace + '/ref/volume')
	fpage = tag_value(settings.namespace + '/ref/fpage')
	lpage = tag_value(settings.namespace + '/ref/lpage')
	collab = tag_value(settings.namespace + '/ref/collab')
	publisher_loc = tag_value(settings.namespace + '/ref/publisher_loc')
	publisher_name = tag_value(settings.namespace + '/ref/publisher_name')
	position = tag_value(settings.namespace + '/ref/position')
	etal = tag_value(settings.namespace + '/ref/etal')

class fi_component(Object):
	about = readonly_tag_value(u'fluiddb/about')
	doi = tag_value(settings.namespace + '/component/doi')
	doi_url = tag_value(settings.namespace + '/component/doi_url')
	type = tag_value(settings.namespace + '/component/type')
	content = tag_value(settings.namespace + '/component/content')
	article_doi = tag_value(settings.namespace + '/component/article_doi')
	position = tag_value(settings.namespace + '/component/position')

class fi_author(Object):
	about = readonly_tag_value(u'fluiddb/about')
	author = tag_value(settings.namespace + '/author/author')
	person_id = tag_value(settings.namespace + '/author/person_id')
	equal_contrib = tag_value(settings.namespace + '/author/equal_contrib')
	article_doi = tag_value(settings.namespace + '/author/article_doi')
	surname = tag_value(settings.namespace + '/author/surname')
	given_names = tag_value(settings.namespace + '/author/given_names')
	department = tag_value(settings.namespace + '/author/department')
	institution = tag_value(settings.namespace + '/author/institution')
	city = tag_value(settings.namespace + '/author/city')
	country = tag_value(settings.namespace + '/author/country')
	corresponding = tag_value(settings.namespace + '/author/corresponding')
	position = tag_value(settings.namespace + '/author/position')
	notes_correspondence = tag_value(settings.namespace + '/author/notes_correspondence')
	notes_footnotes = tag_value(settings.namespace + '/author/notes_footnotes')
	notes_other = tag_value(settings.namespace + '/author/notes_other')

class fi_alm(Object):
	about = readonly_tag_value(u'fluiddb/about')
	doi = tag_value(settings.namespace + '/alm/doi')
	alm_source = tag_value(settings.namespace + '/alm/alm_source')
	type = tag_value(settings.namespace + '/alm/type')
	value = tag_value(settings.namespace + '/alm/value')
	timespan = tag_value(settings.namespace + '/alm/timespan')
	date_date = tag_value(settings.namespace + '/alm/date_date')
	date_day = tag_value(settings.namespace + '/alm/date_day')
	date_month = tag_value(settings.namespace + '/alm/date_month')
	date_year = tag_value(settings.namespace + '/alm/date_year')
	date_timestamp = tag_value(settings.namespace + '/alm/date_timestamp')
	complete = tag_value(settings.namespace + '/alm/complete')

class fi_alm_source(Object):
	about = readonly_tag_value(u'fluiddb/about')
	source = tag_value(settings.namespace + '/alm_source/source')
	url = tag_value(settings.namespace + '/alm_source/url')
	name = tag_value(settings.namespace + '/alm_source/name')
	trusted = tag_value(settings.namespace + '/alm_source/trusted')

def bind_fluidinfo_session():
	session.login(settings.username, settings.password)
	session.bind()

def get_uid_and_initial(key, value):
	"""
	Covert content returned from fom values get query
	to uid and initial values to populate a fom object
	Used by bulk load of values for a single object
	or bulk load of many objects, for example find all references
	of an article in one HTTP get, and build them without doing additional
	HTTP
	"""
	uid = None
	about = None
	initial = {}

	uid = key
	for k, v in value.items():
		if(k == 'fluiddb/about'):
			about = v['value']
		initial[k] = {"value": v['value']}
	return about, uid, initial

def get_uid_from_query(query, obj = None):
	"""
	Refactored method to get the fluidinfo id (uid) and
	existing initial values for an object based on a query
	and optionally constrain the tag list returned based on
	a fom object properties
	"""
	uid = None
	about = None
	initial = {}
	# If a fom Object was supplied, get the tag list from its _path_map
	#  otherwise, use the tag wildcard
	if(obj != None):
		tag_list = []
		for k, v in obj._path_map.items():
			tag_list.append(k)
	else:
		tag_list = ["*"]
	objects = values_get(query, tag_list)
	if(objects.content):
		# Parse content returned, only handling one object at once
		# at the moment
		# Parse content returned with json library to convert null values, etc.
		i = json.loads(objects.content)
		if(type(i) == dict):
			# Only handle one object at a time
			for key, value in i["results"]['id'].items():
				(about, uid, initial) = get_uid_and_initial(key, value)

	return about, uid, initial

def values_get(query, tag_list):
	"""
	Pass-through values get function, to allow external libraries
	to use fom without directly importing
	"""
	if not hasattr(Fluid, 'bound'):
		bind_fluidinfo_session()
	return Fluid.bound.values.get(query, tag_list)

def get_article_initial(doi_url, obj = None):
	"""
	Bulk load initial values from an existing article object
	Return the fluiddb/id (uid) object value, and
	tag values (in initial) to populate a fom Object
	"""
	uid = None
	initial = {}
	query = 'fluiddb/about = "' + doi_url + '"'
	return get_uid_from_query(query, obj)

def get_ref_initial(article_doi, position, obj = None):
	"""
	Bulk load initial values from an existing ref object
	Uniquely keyed by the article_doi and the position of the ref in that article
	Return the fluiddb/id (uid) object value, and
	tag values (in initial) to populate a fom Object
	"""
	uid = None
	initial = {}
	query = 'fluiddb/about = "' + 'ref' + '_' + str(position) + '_' + article_doi + '"'
	return get_uid_from_query(query, obj)

def get_component_initial(article_doi, doi, obj = None):
	"""
	Bulk load initial values from an existing component object
	Uniquely keyed by the article_doi and the doi of the component itself
	Return the fluiddb/id (uid) object value, and
	tag values (in initial) to populate a fom Object
	"""
	uid = None
	initial = {}
	query = 'fluiddb/about = "' + doi + '"'
	return get_uid_from_query(query, obj)

def get_author_initial(article_doi, position, obj = None):
	"""
	Bulk load initial values from an existing author object
	Uniquely keyed by the article_doi and the position of the author in the article
	Return the fluiddb/id (uid) object value, and
	tag values (in initial) to populate a fom Object
	"""
	uid = None
	initial = {}
	query = 'fluiddb/about = "' + 'author' + '_' + str(position) + '_' + article_doi + '"'
	return get_uid_from_query(query, obj)

def main():
	# Basic testing / debug during development
	# moved to load_article.py
	pass

if __name__ == "__main__":
	main()


text:
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var aCallable = require('../internals/a-callable');
var anObject = require('../internals/an-object');
var createAsyncIteratorProxy = require('../internals/async-iterator-create-proxy');
var getAsyncIterator = require('../internals/get-async-iterator');

var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
  var state = this;
  var mapper = state.mapper;
  var innerIterator;

  return new Promise(function (resolve, reject) {
    var outerLoop = function () {
      try {
        Promise.resolve(anObject(state.next.call(state.iterator))).then(function (step) {
          try {
            if (anObject(step).done) {
              state.done = true;
              resolve({ done: true, value: undefined });
            } else {
              Promise.resolve(mapper(step.value)).then(function (mapped) {
                try {
                  state.innerIterator = innerIterator = getAsyncIterator(mapped);
                  state.innerNext = aCallable(innerIterator.next);
                  return innerLoop();
                } catch (error2) { reject(error2); }
              }, reject);
            }
          } catch (error1) { reject(error1); }
        }, reject);
      } catch (error) { reject(error); }
    };

    var innerLoop = function () {
      if (innerIterator = state.innerIterator) {
        try {
          Promise.resolve(anObject(state.innerNext.call(innerIterator))).then(function (result) {
            try {
              if (anObject(result).done) {
                state.innerIterator = state.innerNext = null;
                outerLoop();
              } else resolve({ done: false, value: result.value });
            } catch (error1) { reject(error1); }
          }, reject);
        } catch (error) { reject(error); }
      } else outerLoop();
    };

    innerLoop();
  });
});

$({ target: 'AsyncIterator', proto: true, real: true }, {
  flatMap: function flatMap(mapper) {
    return new AsyncIteratorProxy({
      iterator: anObject(this),
      mapper: aCallable(mapper),
      innerIterator: null,
      innerNext: null
    });
  }
});


text:
classdef QPControllerPlanMatlabImplementation < QPControllerPlan
  properties (SetAccess = protected)
    duration_ = inf;
    start_time_ = 0;
    default_qp_input_ = atlasControllers.QPInputConstantHeight;
    gain_set_ = 'standing';
  end

  methods
    function next_plan = getSuccessor(obj, t, x)
      next_plan = obj;
      next_plan.duration = inf;
    end

    function is_finished = isFinished(obj, t, x)
      if isempty(obj.start_time)
        is_finished = false;
      else
        is_finished = t - obj.start_time >= obj.duration;
      end
    end

    function ret = duration(obj)
      ret = obj.duration_;
    end

    function ret = start_time(obj)
      ret = obj.start_time_;
    end

    function ret = default_qp_input(obj)
      ret = obj.default_qp_input_;
    end

    function ret = gain_set(obj)
      ret = obj.gain_set_;
    end

    function obj = setStartTime(obj, t)
      obj.start_time_ = t;
    end
  end
end


text:
import { Component, OnInit } from '@angular/core';

import { JhiConfigurationService } from './configuration.service';

@Component({
    selector: 'jhi-configuration',
    templateUrl: './configuration.component.html'
})
export class JhiConfigurationComponent implements OnInit {
    allConfiguration: any = null;
    configuration: any = null;
    configKeys: any[];
    filter: string;
    orderProp: string;
    reverse: boolean;

    constructor(
        private configurationService: JhiConfigurationService
    ) {
        this.configKeys = [];
        this.filter = '';
        this.orderProp = 'prefix';
        this.reverse = false;
    }

    keys(dict): Array<string> {
        return (dict === undefined) ? [] : Object.keys(dict);
    }

    ngOnInit() {
        this.configurationService.get().subscribe((configuration) => {
            this.configuration = configuration;

            for (const config of configuration) {
                if (config.properties !== undefined) {
                    this.configKeys.push(Object.keys(config.properties));
                }
            }
        });

        this.configurationService.getEnv().subscribe((configuration) => {
            this.allConfiguration = configuration;
        });
    }
}


text:
package com.ghgande.j2mod.modbus.procimg;

import com.ghgande.j2mod.modbus.util.Observable;

/**
 * Class implementing an observable digital output.
 *
 * @author Dieter Wimberger
 * @author Steve O'Hara (4NG)
 * @version 2.0 (March 2016)
 */
public class ObservableDigitalOut extends Observable implements DigitalOut {

    /**
     * A boolean holding the state of this digital out.
     */
    protected boolean set;

    /**
     * Determine if the digital output is set.
     *
     * @return the boolean value of the digital output.
     */
    @Override
    public boolean isSet() {
        return set;
    }

    /**
     * Set or clear the digital output.  Will notify any registered
     * observers.
     */
    @Override
    public void set(boolean b) {
        set = b;
        notifyObservers("value");
    }
}


text:
namespace System.Spatial
{
  /// <summary>
  /// The exception that is thrown when the dimension of one of the arguments does not match or is invalid.
  /// </summary>
  public class ArgumentDimensionMismatchException : ArgumentException
  {
    public ArgumentDimensionMismatchException(String parameterName, Int32? expectedValue = null)
      : base(FormatMessage(parameterName, expectedValue))
    {
    }

    private static String FormatMessage(String parameterName, Int32? expectedValue)
    {
      return String.Format(expectedValue.HasValue
        ? Exceptions.ArgumentVectorDimensionMismatchExpecting
        : Exceptions.ArgumentVectorDimensionMismatch
        , parameterName
        , expectedValue);
    }
  }
}


text:
"use strict";

var edn  = require('../edn');
var fs   = require('fs');
var exec = require('child_process').exec;

var filename = __dirname + "/transitive.clj";
var data = fs.readFileSync(filename, 'utf8');

var tests;
tests = data.split("\n");
tests = tests.slice(0, tests.length - 1);

function which(command, callback) {
  exec('which ' + command, function (err, stdout) {
    callback(stdout.length ? stdout.trim() : null);
  });
}

exports.transitive = {
  "clojure": function (test) {
    var expected = tests;

    var prog = "(require ['clojure.string :as 'str])" +
      '(println (str/join "\n" ' +
        '(map (fn [l] (pr-str (read-string l))) ' +
        '(str/split-lines (slurp "' + filename + '")))))';

    which('clj', function (path) {
      if (!path) {
        console.warn("Skipping transitive - clojure test");
        test.done();
        return;
      }

      exec(path + ' --eval ' + JSON.stringify(prog), function (error, actual) {
        test.ifError(error);
        actual = actual.split("\n");

        var i;
        for (i = 0; i < expected.length; i++) {
          test.equal(expected[i], actual[i]);
        }

        test.done();
      });
    });
  },

  "js": function (test) {
    var expected = tests;

    var i, obj;
    for (i = 0; i < expected.length; i++) {
      obj = edn.parse(expected[i]);
      test.equal(expected[i], edn.stringify(obj));
    }

    test.done();
  }
};


text:
require 'grape-swagger'

module Caminio
  module Accounts
    module API

      class Root < Grape::API

        desc "caminio-Accounts user and license management"
        prefix '/v1'
        helpers API::Helper

        default_format :json
        format :json

        mount API::Users
        mount API::Auth
        mount API::Initial

        add_swagger_documentation mount_path: '/doc', hide_documentation_path: true

      end

    end
  end
end


text:
    By pressing &shortcut:ChooseRunConfiguration; you can access the Run/Debug dropdown on the main toolbar,
      without the need to use your mouse.


text:
layout: page
title: Mckinney 35th Anniversary
date: 2016-05-24
author: Harry Carrillo
tags: weekly links, java
status: published
summary: Aliquam nec mauris dictum, sagittis libero et, auctor quam. Nunc.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 02/23/2016
  endDate: 02/28/2016
  ctyhocn: RSTMNHX
  groupCode: M3A
published: true
---
Vestibulum ut commodo orci. Aenean semper ligula a aliquam finibus. In id posuere neque, in hendrerit urna. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam arcu velit, pellentesque eget turpis id, semper egestas orci. Vestibulum ullamcorper egestas varius. Sed cursus, neque ac efficitur convallis, ligula mauris blandit leo, in rhoncus nunc sem et elit. Pellentesque at augue eu ligula bibendum tristique.
Fusce congue odio in aliquam rhoncus. Nulla commodo finibus laoreet. Mauris ante risus, condimentum a mi at, suscipit posuere velit. Donec dolor massa, rutrum sed vulputate at, rhoncus quis dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mattis tincidunt elit in blandit. In hac habitasse platea dictumst. Vivamus porta tincidunt turpis, in efficitur orci venenatis et. Nunc euismod molestie porta. Fusce vitae leo laoreet, consectetur orci a, rutrum augue. Aenean hendrerit ex pulvinar porttitor scelerisque.

* Aliquam ut sapien nec orci facilisis auctor
* Sed interdum odio non vulputate egestas
* Pellentesque convallis leo eu lacus elementum, a ullamcorper ipsum imperdiet
* Morbi at eros egestas, consectetur eros ullamcorper, semper libero
* In non risus sed nibh tincidunt euismod ultricies id ipsum
* Cras posuere lorem ac mi congue laoreet.

Curabitur dapibus suscipit consectetur. Sed nec leo quis dui vulputate congue. Quisque quis dolor vitae justo rhoncus hendrerit sed at sem. Proin vel turpis varius, lacinia libero tincidunt, ultrices velit. Ut a imperdiet risus. Donec imperdiet tortor ut tellus imperdiet, eu porta risus semper. Vestibulum lobortis lorem at lacus consequat, malesuada bibendum eros imperdiet.
Suspendisse venenatis quam elit, non posuere sapien ullamcorper vitae. Curabitur ullamcorper orci nec quam consequat bibendum. In posuere pulvinar maximus. Suspendisse malesuada metus ut ligula convallis, a gravida dolor blandit. Aenean pellentesque turpis nibh, vitae rhoncus sem convallis non. Nullam a placerat ipsum, non posuere tortor. Duis quis massa sem. Maecenas in metus porttitor, congue dolor vulputate, fermentum lacus. Aliquam molestie leo vitae dignissim molestie. Suspendisse enim orci, convallis nec enim ac, scelerisque blandit arcu. Donec sollicitudin semper lacus. Suspendisse pretium auctor odio, id viverra arcu.


text:
__author__ = 'Alex Baranov'
from copy import deepcopy
from json import JSONEncoder

class Box(object):
    """Represents the box element"""

    @staticmethod
    def from_json_dict(d):
        """
        Parses the box from the JSON dict
        """
        return Box(d['size'], bottom_left=d['polus'], name=d['name'], kind=d['kind'], weight=d['weight'])

    def __init__(self, size=(), bottom_left=(), name="", kind="solid", weight=None):
        """
        Constructor for box.
              +-------------+
             /             /|
            +-------------+ +
            |             |/
            +-------------+

        Arguments:
            - size: (tuple or list) the element linear sizes.
            - bottom_left:  (list) the coordinates to the button left corner of the element.
            - name: (string) the name of the box.
            - kind: (string) the type of the box.
        """
        super(Box, self).__init__()
        self.size = size
        self.name = name
        self.kind = kind
        self.weight = weight or 0

        if bottom_left == ():
            bottom_left = tuple(0 for _ in xrange(len(size)))

        if len(bottom_left) != len(size):
            raise ValueError("The length of the 'size' argument should be equal to the size of 'bottom_left' argument")
        self.polus = bottom_left

    @property
    def diagonal_polus(self):
        """
        The top left cornet of the rectangle
        """
        return list(self.polus[i] + self.size[i] for i in xrange(len(self.size)))

    @property
    def center(self):
        """
        Get the center position of the box.
        """
        return list(self.polus[i] + self.size[i] / 2.0 for i in xrange(len(self.size)))

    def get_area(self):
        """
        Calculates the area of the rectangle
        """

        return reduce(lambda x, y: x * y, self.size)

    def find_phi_function_value(self, p):
        """
        Gets the Phi-function value that characterise the placement of two box's
        If phi value is greater than 0: objects are NOT intersecting.
        If phi = 0: objects are touching.
        If fi less than 0: object are intersecting.

        Arguments:
            - p : another box.
        """

        n = len(self.size)
        if len(p.size) != n:
            raise ValueError("Unable to compare box's with different dimensions")

        values = []
        for i in xrange(n):
            values.append(p.polus[i] - self.polus[i] - self.size[i])
            values.append(-p.polus[i] + self.polus[i] - p.size[i])

        return max(values)

    def touches(self, other):
        """
        Checks whether current box touches the another one.
        """

        return self.find_phi_function_value(other) == 0

    def intersects(self, other):
        """
        Checks whether two box's are intersecting.
        """
        phi = self.find_phi_function_value(other)
        return phi < 0

    def includes_point(self, p):
        """
        Checks whether the provided point is within the box.

        Arguments:
            p - the list of point coordinates.
        """
        return all((p[i] - x >= 0 for i, x in enumerate(self.polus))) and all(
            (x - p[i] >= 0 for i, x in enumerate(self.diagonal_polus)))

    def includes(self, other):
        """
        Checks whether the current box includes the another one.
        """
        return self.includes_point(other.polus) and self.includes_point(other.diagonal_polus)

    def can_accept(self, other):
        """
        Checks whether the box can accept the another one.

        Arguments:
            - other: the another box

        Returns:
            - True or False.
        """

        return all((value - other.size[index]) >= 0 for index, value in enumerate(self.size))

    def find_free_containers(self, other):
        """
        Gets the list of containers that can be received by placing
        another box into current.

        +-------------------+
        |   a               |
        |                   |
        +-------+           |
        | other |      b    |
        +-------+-----------+

        Arguments:
            - other : the placed box. The polus should be defined.

        Returns:
            - the list of container received.
        """

        assert isinstance(other, Box)
        result = []

        # TODO Rework this to be more pythonic
        n = len(self.size)
        for i in range(n):
            if other.diagonal_polus[i] < self.diagonal_polus[i]:
                # create free container
                polus = []
                size = []
                for j in range(n):
                    if i != j:
                        polus.append(self.polus[j])
                    else:
                        polus.append(other.diagonal_polus[j])

                    size.append(self.diagonal_polus[j] - polus[j])

                result.append(Box(tuple(size), tuple(polus)))
            if other.polus[i] > self.polus[i]:
                polus = self.polus[:]
                size = self.size[:i] + (other.polus[i], ) + self.size[i + 1:]

                result.append(Box(size, polus))

        return result

    def is_blocked(self, other, axes=()):
        """
        Checks whether the current box is blocked the another one.

        By default checks whether the box is blocked by another one by +X axis.

        Arguments:
            other: the other box.
            axes: the tuple of axes to check. For example (1,0,0) checks that block by X axis for 3d case.

        Returns:
            - boolean value.
        """

        if len(other.size) != len(self.size):
            raise ValueError("Boxes sizes should have the same lengths")

        if not axes:
            axes = [0] * len(self.size)
            axes[0] = 1

        checks = []

        c = deepcopy(self)
        for i, a in enumerate(axes):
            # create a copy of the current box.
            c.size = list(c.size)
            c.size[i] += (other.polus[i] + other.size[i]) * a
            checks.append(other.intersects(c))

        return any(checks)

    def is_basis_for(self, other, axes=()):
        """
        Check if current box is basis for another box.
        Be default check is performed by Y axis.

        Example: self is basis for other

           +-------+
           | other |
        +--+-------+--------+
        |                   |
        |       self        |
        |                   |
        |                   |
        +-------------------+
        """
        if len(other.size) != len(self.size):
            raise ValueError("Boxes sizes should have the same lengths")

        if not axes:
            axes = [0] * len(self.size)
            axes[1] = 1

        if not self.touches(other):
            return False

        c = deepcopy(self)
        for i, a in enumerate(axes):
            c.size = list(c.size)
            c.size[i] += (other.polus[i] + other.size[i]) * a

        return c.includes(other)

    def __str__(self):
        """
        String representation of the object.
        """
        return "Box: Name '{}'; Size: '{}'; Polus: '{};".format(self.name, self.size, self.polus)

    def __eq__(self, other):
        """
        Checks whether the current container is equal to other.
        Position is ignored.
        """

        return self.size == other.size and self.name == other.name and \
               self.kind == other.kind

    def __lt__(self, other):
        """
        Compares the areas of boxes
        """
        self.get_area() < other.get_area()

    def __le__(self, other):
        """
        Compares the areas of boxes
        """
        self.get_area() <= other.get_area()

    def __gt__(self, other):
        """
        Compares the areas of boxes
        """
        self.get_area() > other.get_area()

    def __ge__(self, other):
        """
        Compares the areas of boxes
        """
        self.get_area() >= other.get_area()

    def __ne__(self, other):
        """
        Checks that currents box is not equal to another one.
        """
        return not self == other

    def clone(self):
        """
        Returns the deep copy of the box.
        """
        return deepcopy(self)

class BoxJsonEncoder(JSONEncoder):
    """
    Serializes box into json format.
    """

    def default(self, obj):
        if not isinstance(obj, Box):
            return super(BoxJsonEncoder, self).default(obj)

        return dict(obj.__dict__, **{'__type__': 'Box'})


text:
package hu.akarnokd.rxjava;

import java.util.concurrent.TimeUnit;

import rx.*;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;

public class TrackSubscriber1 {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
    RxJavaHooks.setOnObservableStart((observable, onSubscribe) -> {
        if (!onSubscribe.getClass().getName().toLowerCase().contains("map")) {
            return onSubscribe;
        }

        System.out.println("Started");

        return (Observable.OnSubscribe<Object>)observer -> {
            class SignalTracker extends Subscriber<Object> {
                @Override public void onNext(Object o) {
                    // handle onNext before or aftern notifying the downstream
                    observer.onNext(o);
                }
                @Override public void onError(Throwable t) {
                    // handle onError
                    observer.onError(t);
                }
                @Override public void onCompleted() {
                    // handle onComplete
                    System.out.println("Completed");
                    observer.onCompleted();
                }
            }
            SignalTracker t = new SignalTracker();
            onSubscribe.call(t);
        };
      });

      Observable<Integer> observable = Observable.range(1, 5)
          .subscribeOn(Schedulers.io())
          .observeOn(Schedulers.computation())
          .map(integer -> {
            try {
              TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            return integer * 3;
          });

      observable.subscribe(System.out::println);

      Thread.sleep(6000L);
    }
}


text:
.class public final Lmf/org/apache/xerces/stax/events/CharactersImpl;
.super Lmf/org/apache/xerces/stax/events/XMLEventImpl;
.source "CharactersImpl.java"

# interfaces
.implements Lmf/javax/xml/stream/events/Characters;

# instance fields
.field private final fData:Ljava/lang/String;

# direct methods
.method public constructor <init>(Ljava/lang/String;ILmf/javax/xml/stream/Location;)V
    .locals 0

    invoke-direct {p0, p2, p3}, Lmf/org/apache/xerces/stax/events/XMLEventImpl;-><init>(ILmf/javax/xml/stream/Location;)V

    if-nez p1, :cond_0

    const-string/jumbo p1, ""

    :cond_0
    iput-object p1, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    return-void
.end method

# virtual methods
.method public getData()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    return-object v0
.end method

.method public isCData()Z
    .locals 2

    invoke-virtual {p0}, Lmf/org/apache/xerces/stax/events/CharactersImpl;->getEventType()I

    move-result v0

    const/16 v1, 0xc

    if-eq v1, v0, :cond_0

    const/4 v0, 0x0

    return v0

    :cond_0
    const/4 v0, 0x1

    return v0
.end method

.method public isIgnorableWhiteSpace()Z
    .locals 2

    invoke-virtual {p0}, Lmf/org/apache/xerces/stax/events/CharactersImpl;->getEventType()I

    move-result v0

    const/4 v1, 0x6

    if-eq v1, v0, :cond_0

    const/4 v0, 0x0

    return v0

    :cond_0
    const/4 v0, 0x1

    return v0
.end method

.method public isWhiteSpace()Z
    .locals 4

    const/4 v2, 0x0

    iget-object v3, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    if-nez v3, :cond_0

    move v1, v2

    :goto_0
    if-eqz v1, :cond_1

    const/4 v0, 0x0

    :goto_1
    if-ge v0, v1, :cond_3

    iget-object v3, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    invoke-virtual {v3, v0}, Ljava/lang/String;->charAt(I)C

    move-result v3

    invoke-static {v3}, Lmf/org/apache/xerces/util/XMLChar;->isSpace(I)Z

    move-result v3

    if-eqz v3, :cond_2

    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    :cond_0
    iget-object v3, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v1

    goto :goto_0

    :cond_1
    return v2

    :cond_2
    return v2

    :cond_3
    const/4 v2, 0x1

    return v2
.end method

.method public writeAsEncodedUnicode(Ljava/io/Writer;)V
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lmf/javax/xml/stream/XMLStreamException;
        }
    .end annotation

    :try_start_0
    iget-object v1, p0, Lmf/org/apache/xerces/stax/events/CharactersImpl;->fData:Ljava/lang/String;

    invoke-virtual {p1, v1}, Ljava/io/Writer;->write(Ljava/lang/String;)V
    :try_end_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_0

    return-void

    :catch_0
    move-exception v0

    new-instance v1, Lmf/javax/xml/stream/XMLStreamException;

    invoke-direct {v1, v0}, Lmf/javax/xml/stream/XMLStreamException;-><init>(Ljava/lang/Throwable;)V

    throw v1
.end method


text:
#ifndef AudioStream_h
#define AudioStream_h

#include "Arduino.h"

#define AUDIO_BLOCK_SAMPLES  128
#define AUDIO_SAMPLE_RATE    44117.64706
#define AUDIO_SAMPLE_RATE_EXACT 44117.64706 // 48 MHz / 1088, or 96 MHz * 2 / 17 / 256

class AudioStream;
class AudioConnection;

typedef struct audio_block_struct {
	unsigned char ref_count;
	unsigned char memory_pool_index;
	unsigned char reserved1;
	unsigned char reserved2;
	int16_t data[AUDIO_BLOCK_SAMPLES];
} audio_block_t;

class AudioConnection
{
public:
	AudioConnection(AudioStream &source, AudioStream &destination) :
		src(source), dst(destination), src_index(0), dest_index(0),
		next_dest(NULL)
		{ connect(); }
	AudioConnection(AudioStream &source, unsigned char sourceOutput,
		AudioStream &destination, unsigned char destinationInput) :
		src(source), dst(destination),
		src_index(sourceOutput), dest_index(destinationInput),
		next_dest(NULL)
		{ connect(); }
	friend class AudioStream;
protected:
	void connect(void);
	AudioStream &src;
	AudioStream &dst;
	unsigned char src_index;
	unsigned char dest_index;
	AudioConnection *next_dest;
};

#define AudioMemory(num) ({ \
	static DMAMEM audio_block_t data[num]; \
	AudioStream::initialize_memory(data, num); \
})

#define CYCLE_COUNTER_APPROX_PERCENT(n) (((n) + (F_CPU / 32 / AUDIO_SAMPLE_RATE * AUDIO_BLOCK_SAMPLES / 100)) / (F_CPU / 16 / AUDIO_SAMPLE_RATE * AUDIO_BLOCK_SAMPLES / 100))

#define AudioProcessorUsage() (CYCLE_COUNTER_APPROX_PERCENT(AudioStream::cpu_cycles_total))
#define AudioProcessorUsageMax() (CYCLE_COUNTER_APPROX_PERCENT(AudioStream::cpu_cycles_total_max))
#define AudioProcessorUsageMaxReset() (AudioStream::cpu_cycles_total_max = AudioStream::cpu_cycles_total)
#define AudioMemoryUsage() (AudioStream::memory_used)
#define AudioMemoryUsageMax() (AudioStream::memory_used_max)
#define AudioMemoryUsageMaxReset() (AudioStream::memory_used_max = AudioStream::memory_used)

class AudioStream
{
public:
	AudioStream(unsigned char ninput, audio_block_t **iqueue) :
		num_inputs(ninput), inputQueue(iqueue) {
			active = false;
			destination_list = NULL;
			for (int i=0; i < num_inputs; i++) {
				inputQueue[i] = NULL;
			}
			// add to a simple list, for update_all
			// TODO: replace with a proper data flow analysis in update_all
			if (first_update == NULL) {
				first_update = this;
			} else {
				AudioStream *p;
				for (p=first_update; p->next_update; p = p->next_update) ;
				p->next_update = this;
			}
			next_update = NULL;
			cpu_cycles = 0;
			cpu_cycles_max = 0;
		}
	static void initialize_memory(audio_block_t *data, unsigned int num);
	int processorUsage(void) { return CYCLE_COUNTER_APPROX_PERCENT(cpu_cycles); }
	int processorUsageMax(void) { return CYCLE_COUNTER_APPROX_PERCENT(cpu_cycles_max); }
	void processorUsageMaxReset(void) { cpu_cycles_max = cpu_cycles; }
	uint16_t cpu_cycles;
	uint16_t cpu_cycles_max;
	static uint16_t cpu_cycles_total;
	static uint16_t cpu_cycles_total_max;
	static uint8_t memory_used;
	static uint8_t memory_used_max;
protected:
	bool active;
	unsigned char num_inputs;
	static audio_block_t * allocate(void);
	static void release(audio_block_t * block);
	void transmit(audio_block_t *block, unsigned char index = 0);
	audio_block_t * receiveReadOnly(unsigned int index = 0);
	audio_block_t * receiveWritable(unsigned int index = 0);
	static bool update_setup(void);
	static void update_stop(void);
	static void update_all(void) { NVIC_SET_PENDING(IRQ_SOFTWARE); }
	friend void software_isr(void);
	friend class AudioConnection;
private:
	AudioConnection *destination_list;
	audio_block_t **inputQueue;
	static bool update_scheduled;
	virtual void update(void) = 0;
	static AudioStream *first_update; // for update_all
	AudioStream *next_update; // for update_all
	static audio_block_t *memory_pool;
	static uint32_t memory_pool_available_mask[6];
};

#endif


text:
#include "vsx_common.h"

static STREAM_DEVICE_T *g_devtypes;

static STREAM_DEVICE_T *create_device(const char *name, const char *strmatch,
                                      const char *strmatch2,
                                      enum STREAM_METHOD methods[],
                                      enum STREAM_DEVICE_TYPE devtype) {
  STREAM_DEVICE_T *dev;

  if(!(dev = avc_calloc(1, sizeof(STREAM_DEVICE_T)))) {
    return NULL;
  }

  strncpy((char *) dev->name, name, sizeof(dev->name) - 1);
  strncpy((char *) dev->strmatch, strmatch, sizeof(dev->strmatch) - 1);
  if(strmatch2 && strmatch2[0] != '\0') {
    strncpy((char *) dev->strmatch2, strmatch2, sizeof(dev->strmatch2) - 1);
  }
  memcpy(dev->methods, methods, sizeof(enum STREAM_METHOD) * STREAM_DEVICE_METHODS_MAX);
  dev->devtype = devtype;

  return dev;
}

static void devtype_free(STREAM_DEVICE_T *pdev) {
  STREAM_DEVICE_T *pdevnext;

  if(g_devtypes == pdev) {
    g_devtypes = NULL;
  }

  while(pdev) {
    pdevnext = pdev->pnext;
    free(pdev);
    pdev = pdevnext;
  }

}

void devtype_dump(STREAM_DEVICE_T *pdev) {

  while(pdev) {
    fprintf(stderr, "dev:'%s' match:'%s','%s', method:%d,%d,%d,%d, devtype:%d\n", pdev->name, pdev->strmatch, pdev->strmatch2, pdev->methods[0], pdev->methods[1], pdev->methods[2], pdev->methods[3], pdev->devtype);
    pdev = pdev->pnext;
  }
}

const STREAM_DEVICE_T *devtype_finddevice(const char *userAgent, int matchany) {
  const STREAM_DEVICE_T *pdev = NULL;
  const STREAM_DEVICE_T *pmatch = NULL;

  if(!g_devtypes) {
    //devtype_init();
    LOG(X_ERROR("Device database not configured"));
    return NULL;
  }

  pdev = g_devtypes;
  while(pdev) {

    //VSX_DEBUG_LIVE( LOG(X_DEBUGV("devtype_finddevice User-Agent: '%s', matchany: %d, strmatch: '%s', '%s'"),
    //                             userAgent, matchany, pdev->strmatch, pdev->strmatch2); );

    //
    // if matchany is set, any default empty match can be made (last fall-thru device)
    // match & match2 is an 'and' based match
    //
    if(matchany || pdev->strmatch[0] != '\0' || pdev->strmatch[1] != '\0') {

      if(pdev->strmatch[0] == '\0' || (userAgent && strcasestr(userAgent, pdev->strmatch))) {
        if(pdev->strmatch2[0] == '\0' ||
          (userAgent && strcasestr(userAgent, pdev->strmatch2))) {
          pmatch = pdev;
          break;
        }
      }
    }
    pdev = pdev->pnext;
  }

  if(!pmatch && matchany) {
    return pdev;
  } else {
    VSX_DEBUG_LIVE(LOG(X_DEBUG("LIVE - devtype_finddevice returning %s for User-Agent: '%s'"),
                   pmatch->name, userAgent); );
    return pmatch;
  }
}

#define PARSE_FLAG_HAVE_DEVNAME          0x01
#define PARSE_FLAG_HAVE_METHOD           0x02
#define PARSE_FLAG_HAVE_DEVTYPE          0x04
#define PARSE_FLAG_HAVE_MATCH            0x08

#define PARSE_FLAG_HAVE_ALL  (PARSE_FLAG_HAVE_DEVNAME | PARSE_FLAG_HAVE_METHOD | \
                              PARSE_FLAG_HAVE_DEVTYPE | PARSE_FLAG_HAVE_MATCH)

typedef struct PARSE_ENTRY_DATA {
  int                      flags;
  char                     devname[STREAM_DEV_NAME_MAX];
  char                     strmatch[64];
  char                     strmatch2[64];
  unsigned int             numMethods;
  enum STREAM_METHOD       methods[STREAM_DEVICE_METHODS_MAX];
  enum STREAM_DEVICE_TYPE  devtype;
} PARSE_ENTRY_DATA_T;

static enum STREAM_DEVICE_TYPE devtype_typefromstr(const char *str) {

  if(!strcasecmp(str, STREAM_DEVICE_TYPE_MOBILE_STR)) {
    return STREAM_DEVICE_TYPE_MOBILE;
  } else if(!strcasecmp(str, STREAM_DEVICE_TYPE_TABLET_STR)) {
    return STREAM_DEVICE_TYPE_TABLET;
  } else if(!strcasecmp(str, STREAM_DEVICE_TYPE_PC_STR)) {
    return STREAM_DEVICE_TYPE_PC;
  } else if(!strcasecmp(str, STREAM_DEVICE_TYPE_UNSUPPORTED_STR)) {
    return STREAM_DEVICE_TYPE_UNSUPPORTED;
  } else {
    return STREAM_DEVICE_TYPE_UNKNOWN;
  }

}

const char *devtype_methodstr(enum STREAM_METHOD method) {

  switch(method) {
    case STREAM_METHOD_HTTPLIVE:
      return STREAM_METHOD_HTTPLIVE_STR;
    case STREAM_METHOD_DASH:
      return STREAM_METHOD_DASH_STR;
    case STREAM_METHOD_FLVLIVE:
      return STREAM_METHOD_FLVLIVE_STR;
    case STREAM_METHOD_MKVLIVE:
      return STREAM_METHOD_MKVLIVE_STR;
    case STREAM_METHOD_TSLIVE:
      return STREAM_METHOD_TSLIVE_STR;
    case STREAM_METHOD_RTSP:
      return STREAM_METHOD_RTSP_STR;
    case STREAM_METHOD_RTSP_INTERLEAVED:
      return STREAM_METHOD_RTSP_INTERLEAVED_STR;
    case STREAM_METHOD_RTSP_HTTP:
      return STREAM_METHOD_RTSP_HTTP_STR;
    case STREAM_METHOD_RTMPT:
      return STREAM_METHOD_RTMPT_STR;
    case STREAM_METHOD_RTMP:
      return STREAM_METHOD_RTMP_STR;
    case STREAM_METHOD_PROGDOWNLOAD:
      return STREAM_METHOD_PROGDOWNLOAD_STR;
    case STREAM_METHOD_FLASHHTTP:
      return STREAM_METHOD_FLASHHTTP_STR;
    case STREAM_METHOD_UDP_RTP:
      return STREAM_METHOD_UDP_RTP_STR;
    case STREAM_METHOD_UDP:
      return STREAM_METHOD_UDP_STR;
    case STREAM_METHOD_MGR:
      return STREAM_METHOD_MGR_STR;
    case STREAM_METHOD_ANYLIVE:
      return STREAM_METHOD_ANYLIVE_STR;
    case STREAM_METHOD_NONE:
      return STREAM_METHOD_NONE_STR;
    default:
      return "";
  }

}

STREAM_METHOD_T devtype_methodfromstr(const char *str) {

  if(!str) {
    return STREAM_METHOD_UNKNOWN;
  } else if(!strncasecmp(str, STREAM_METHOD_HTTPLIVE_STR,
                  strlen(STREAM_METHOD_HTTPLIVE_STR) + 1)) {
    return STREAM_METHOD_HTTPLIVE;
  } else if(!strncasecmp(str, STREAM_METHOD_DASH_STR,
                  strlen(STREAM_METHOD_DASH_STR) + 1)) {
    return STREAM_METHOD_DASH;
  } else if(!strncasecmp(str, STREAM_METHOD_TSLIVE_STR,
                  strlen(STREAM_METHOD_TSLIVE_STR) + 1)) {
    return STREAM_METHOD_TSLIVE;
  } else if(!strncasecmp(str, STREAM_METHOD_RTSP_STR,
                  strlen(STREAM_METHOD_RTSP_STR) + 1)) {
    return STREAM_METHOD_RTSP;
  } else if(!strncasecmp(str, STREAM_METHOD_RTSP_INTERLEAVED_STR,
                  strlen(STREAM_METHOD_RTSP_INTERLEAVED_STR) + 1)) {
    return STREAM_METHOD_RTSP_INTERLEAVED;
  } else if(!strncasecmp(str, STREAM_METHOD_RTSP_HTTP_STR,
                  strlen(STREAM_METHOD_RTSP_HTTP_STR) + 1)) {
    return STREAM_METHOD_RTSP_HTTP;
  } else if(!strncasecmp(str, STREAM_METHOD_RTMPT_STR,
                  strlen(STREAM_METHOD_RTMPT_STR) + 1)) {
    return STREAM_METHOD_RTMPT;
  } else if(!strncasecmp(str, STREAM_METHOD_RTMP_STR,
                  strlen(STREAM_METHOD_RTMP_STR) + 1)) {
    return STREAM_METHOD_RTMP;
  } else if(!strncasecmp(str, STREAM_METHOD_FLVLIVE_STR,
                  strlen(STREAM_METHOD_FLVLIVE_STR) + 1)) {
    return STREAM_METHOD_FLVLIVE;
  } else if(!strncasecmp(str, STREAM_METHOD_MKVLIVE_STR,
                  strlen(STREAM_METHOD_MKVLIVE_STR) + 1)) {
    return STREAM_METHOD_MKVLIVE;
  } else if(!strncasecmp(str, STREAM_METHOD_PROGDOWNLOAD_STR,
                  strlen(STREAM_METHOD_PROGDOWNLOAD_STR) + 1)) {
    return STREAM_METHOD_PROGDOWNLOAD;
  } else if(!strncasecmp(str, STREAM_METHOD_FLASHHTTP_STR,
                  strlen(STREAM_METHOD_FLASHHTTP_STR) + 1)) {
    return STREAM_METHOD_FLASHHTTP;
  } else if(!strncasecmp(str, STREAM_METHOD_UDP_RTP_STR,
                  strlen(STREAM_METHOD_UDP_RTP_STR) + 1)) {
    return STREAM_METHOD_UDP_RTP;
  } else if(!strncasecmp(str, STREAM_METHOD_UDP_STR,
                  strlen(STREAM_METHOD_UDP_STR) + 1)) {
    return STREAM_METHOD_UDP;
  } else if(!strncasecmp(str, STREAM_METHOD_MGR_STR,
                  strlen(STREAM_METHOD_MGR_STR) + 1)) {
    return STREAM_METHOD_MGR;
  } else if(!strncasecmp(str, STREAM_METHOD_ANYLIVE_STR,
                  strlen(STREAM_METHOD_ANYLIVE_STR) + 1)) {
    return STREAM_METHOD_ANYLIVE;
  } else {
    return STREAM_METHOD_UNKNOWN;
  }

}

char *devtype_dump_methods(int methodBits,  char *buf, unsigned int szbuf) {
  int rc;
  unsigned int idxMethod;
  unsigned int idxbuf = 0;

  if(buf && szbuf > 0) {
    buf[0] = '\0';
  }

  for(idxMethod = 0; idxMethod < STREAM_METHOD_MAX; idxMethod++) {
    if(methodBits & (1 << idxMethod)) {
      if((rc = snprintf(&buf[idxbuf], szbuf - idxbuf, "%s%s",
                        idxbuf > 0 ? "," : "", devtype_methodstr(idxMethod))) > 0) {
        idxbuf += rc;
      }
    }
  }

  return buf;
}

int devtype_method_getbits(STREAM_METHOD_T method) {
  int methodBits = 0;

  methodBits |= (1 << method);

  if(method == STREAM_METHOD_ANYLIVE) {
    methodBits |= (1 << STREAM_METHOD_HTTPLIVE);
    methodBits |= (1 << STREAM_METHOD_DASH);
    methodBits |= (1 << STREAM_METHOD_TSLIVE);
    methodBits |= (1 << STREAM_METHOD_FLVLIVE);
    methodBits |= (1 << STREAM_METHOD_MKVLIVE);
    methodBits |= (1 << STREAM_METHOD_RTSP);
    methodBits |= (1 << STREAM_METHOD_RTSP_INTERLEAVED);
    methodBits |= (1 << STREAM_METHOD_RTSP_HTTP);
    methodBits |= (1 << STREAM_METHOD_RTMP);
    methodBits |= (1 << STREAM_METHOD_RTMPT);
  }

  return methodBits;
}

/*
int devtype_findmethod(const STREAM_DEVICE_T *pdev, STREAM_METHOD_T method) {
  unsigned int idx = 0;
  for(idx = 0; idx < STREAM_DEVICE_METHODS_MAX; idx++) {
    if(pdev->methods[idx] == method) {
      return 1;
    }
  }

  return 0;
}
*/

int cbparse_entry_devtype_method(void *pArg, const char *p) {
  int rc = 0;
  PARSE_ENTRY_DATA_T *pEntryData = (PARSE_ENTRY_DATA_T *) pArg;

  if(pEntryData->numMethods < STREAM_DEVICE_METHODS_MAX) {
    pEntryData->methods[pEntryData->numMethods++] = devtype_methodfromstr(p);
    rc = 1;
  }

  return rc;
}

int cbparse_entry_devtype(void *pArg, const char *p) {
  int rc = 0;
  PARSE_ENTRY_DATA_T *pEntryData = (PARSE_ENTRY_DATA_T *) pArg;

  //fprintf(stderr, "entry '%s'\n", p);

  if(!strncasecmp(p, DEVFILE_KEY_DEVICE, strlen(DEVFILE_KEY_DEVICE))) {

    if((p = strutil_skip_key(p, strlen(DEVFILE_KEY_DEVICE)))) {
      p = avc_dequote(p, NULL, 0);
      strncpy(pEntryData->devname, p, sizeof(pEntryData->devname) - 1);
      pEntryData->flags |= PARSE_FLAG_HAVE_DEVNAME;
    }

  } else if(!strncasecmp(p, DEVFILE_KEY_METHODS, strlen(DEVFILE_KEY_METHODS))) {

    if((p = strutil_skip_key(p, strlen(DEVFILE_KEY_METHODS)))) {
      p = avc_dequote(p, NULL, 0);

      if(strutil_parse_csv(cbparse_entry_devtype_method, pEntryData, p) < 0) {
        LOG(X_WARNING("Failed to parse device type method(s) '%s'"), p);
      }
      //fprintf(stderr, "%s %d %d %d %d\n", pEntryData->devname, pEntryData->methods[0], pEntryData->methods[1], pEntryData->methods[2], pEntryData->methods[3]);

      pEntryData->flags |= PARSE_FLAG_HAVE_METHOD;
    }

  } else if(!strncasecmp(p, DEVFILE_KEY_METHOD, strlen(DEVFILE_KEY_METHOD))) {

    if((p = strutil_skip_key(p, strlen(DEVFILE_KEY_METHOD)))) {
      p = avc_dequote(p, NULL, 0);

      pEntryData->methods[0] = devtype_methodfromstr(p);
      pEntryData->flags |= PARSE_FLAG_HAVE_METHOD;
    }

  } else if(!strncasecmp(p, DEVFILE_KEY_TYPE, strlen(DEVFILE_KEY_TYPE))) {

    if((p = strutil_skip_key(p, strlen(DEVFILE_KEY_TYPE)))) {
      p = avc_dequote(p, NULL, 0);
      pEntryData->devtype = devtype_typefromstr(p);
      pEntryData->flags |= PARSE_FLAG_HAVE_DEVTYPE;
    }

  } else if(!strncasecmp(p, DEVFILE_KEY_MATCH, strlen(DEVFILE_KEY_MATCH))) {

    if((p = strutil_skip_key(p, strlen(DEVFILE_KEY_MATCH)))) {
      p = avc_dequote(p, NULL, 0);
      strncpy(pEntryData->strmatch, p, sizeof(pEntryData->strmatch) - 1);
      pEntryData->flags |= PARSE_FLAG_HAVE_MATCH;
    }

  }

  return rc;
}

int devtype_loadcfg(const char *path) {
  STREAM_DEVICE_T *pdev = NULL;
  STREAM_DEVICE_T *pdevprev = NULL;
  FILE_HANDLE fp;
  char buf[1024];
  const char *p;
  int linenum = 1;
  int count = 0;
  PARSE_ENTRY_DATA_T parseData;

  if(!path) {
    return -1;
  }

  if(g_devtypes) {
    devtype_free(g_devtypes);
    g_devtypes = NULL;
  }

  if((fp = fileops_Open(path, O_RDONLY)) == FILEOPS_INVALID_FP) {
    LOG(X_ERROR("Unable to open metafile for reading: %s"), path);
    return -1;
  }

  while(fileops_fgets(buf, sizeof(buf) - 1, fp)) {

    p = buf;
    while(*p == ' ' || *p == '\t') {
      p++;
    }

    if(*p == '#') {
      continue;
    }

    memset(&parseData, 0, sizeof(parseData));
    if(strutil_parse_csv(cbparse_entry_devtype, &parseData, p) < 0) {
      LOG(X_ERROR("Failed to parse line %d in file %s"), linenum, path);
      devtype_free(g_devtypes);
      break;
    } else if((parseData.flags & PARSE_FLAG_HAVE_ALL)) {
      if(!(pdev = create_device(parseData.devname, parseData.strmatch,
                           parseData.strmatch2, parseData.methods,
                           parseData.devtype))) {
        LOG(X_ERROR("Failed to create device config from line %d"), linenum);
        devtype_free(g_devtypes);
        break;
      } else if(pdevprev) {
        pdevprev->pnext = pdev;
      } else {
        g_devtypes = pdev;
      }
      pdevprev = pdev;
      count++;

    } else if(strlen(p) > 1) {
      LOG(X_WARNING("Incomplete line %d in file %s"), linenum, path);
    }

    linenum++;
  }

  fileops_Close(fp);

  LOG(X_DEBUG("Read %d device profiles from %s"), count, path);

  //devtype_dump(g_devtypes);

  return count;
}

int devtype_defaultcfg() {
  STREAM_DEVICE_T *pdev = NULL;
  unsigned int idx;
  enum STREAM_METHOD methods[STREAM_DEVICE_METHODS_MAX];

  if(g_devtypes) {
    devtype_free(g_devtypes);
    g_devtypes = NULL;
  }

  for(idx = 0; idx < STREAM_DEVICE_METHODS_MAX; idx++) {
    methods[idx] = STREAM_METHOD_UNKNOWN;
  }

  if(!(pdev = create_device("unknown", "", "", methods,
                             STREAM_DEVICE_TYPE_UNKNOWN))) {
    return -1;
  }

  g_devtypes = pdev;

  return 1;
}


text:
<?php

require_once 'swift_required.php';
require_once __DIR__.'/Mime/SimpleMessageAcceptanceTest.php';

class Swift_MessageAcceptanceTest extends Swift_Mime_SimpleMessageAcceptanceTest
{
    public function testAddPartWrapper()
    {
        $message = $this->createMessage();
        $message->setSubject('just a test subject');
        $message->setFrom([
            'chris.corbyn@swiftmailer.org' => 'Chris Corbyn', ]);

        $id = $message->getId();
        $date = $message->getDate();
        $boundary = $message->getBoundary();

        $message->addPart('foo', 'text/plain', 'iso-8859-1');
        $message->addPart('test foo', 'text/html', 'iso-8859-1');

        $this->assertEquals(
            'Message-ID: <'.$id.'>'."\r\n".
            'Date: '.$date->format('r')."\r\n".
            'Subject: just a test subject'."\r\n".
            'From: Chris Corbyn <chris.corbyn@swiftmailer.org>'."\r\n".
            'MIME-Version: 1.0'."\r\n".
            'Content-Type: multipart/alternative;'."\r\n".
            ' boundary="'.$boundary.'"'."\r\n".
            "\r\n\r\n".
            '--'.$boundary."\r\n".
            'Content-Type: text/plain; charset=iso-8859-1'."\r\n".
            'Content-Transfer-Encoding: quoted-printable'."\r\n".
            "\r\n".
            'foo'.
            "\r\n\r\n".
            '--'.$boundary."\r\n".
            'Content-Type: text/html; charset=iso-8859-1'."\r\n".
            'Content-Transfer-Encoding: quoted-printable'."\r\n".
            "\r\n".
            'test foo'.
            "\r\n\r\n".
            '--'.$boundary.'--'."\r\n",
            $message->toString()
            );
    }

    protected function createMessage()
    {
        Swift_DependencyContainer::getInstance()
            ->register('properties.charset')->asValue(null);

        return new Swift_Message();
    }
}


text:
<?php

/**
 * This file is part of the Open Performance Monitor Client package
 *
 * The Open Performance Monitor collects data to measure the performance of websites
 *
 * @package OPMCLient
 */
namespace Whm\Opm\Client\Command;

use Whm\Opm\Client\Server\MessurementResult;

use Buzz\Browser;
use Whm\Opm\Client\Messure\MessurementContainer;
use phmLabs\Components\Annovent\Event\Event;
use Whm\Opm\Client\Server\Server;
use Whm\Opm\Client\Config\Config;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Whm\Opm\Client\Console\Command;

/**
 * ProcessUrl
 *
 * Process an url and send the result (har file) to an opm server
 *
 * @category Command
 * @package OPMClient
 * @license https://raw.github.com/thewebhatesme/opm_server/master/LICENSE
 * @example $./bin/client messure
 * @version GIT: $Id$
 * @since Date: 2014-03-12
 * @author Nils Langner <nils.langner@phmlabs.com>
 */
class Messure extends Command
{

    /**
     *
     * @var string Path to config file
     */
    private $configFile;

    /**
     *
     * @var \Whm\Opm\Client\Config\Config Configuration object
     */
    private $config;

    /**
     *
     * @var \Whm\Opm\Client\Messure\MessurementContainer Object to hold data of messurement
     */
    private $messurementContainer;

    /**
     *
     * @var \Whm\Opm\Client\Server\Server
     */
    private $server;

    private $dryrun;

    /**
     * {@inheritDoc}
     */
    protected function configure ()
    {
        $this->setName('messure')
            ->setDescription('Run a specified messurement.')
            ->addArgument('identifier', InputArgument::REQUIRED, 'The task identifier.')
            ->addArgument('messureType', InputArgument::REQUIRED, 'The messurement type.')
            ->addArgument('parameters', InputArgument::REQUIRED, 'The parameters.');
    }

    /**
     * Initializes the configuration
     *
     * @param string $configFile Path to config file
     * @uses \Whm\Opm\Client\Config\Config::createFromFilet to read configuration
     * @uses \phmLabs\Components\Annovent\Event\Event to fire an event
     */
    private function initConfig ($configFile)
    {
        $this->configFile = $configFile;
        $this->config = Config::createFromFile($configFile);
        $this->getEventDispatcher()->notify(new Event('config.create', array("config" => $this->config,"configFileName" => $configFile)));
    }

    /**
     * Initialize container to hold the data of the messurement
     *
     * @uses \Whm\Opm\Client\Messure\MessurementContainer
     * @uses \phmLabs\Components\Annovent\Event\Event to fire an event
     */
    private function initMessurementContainer ()
    {
        $this->messurementContainer = new MessurementContainer();
        $this->getEventDispatcher()->notify(new Event('messure.messurementcontainer.create', array('container' => $this->messurementContainer)));
    }

    /**
     * initialize server and create an event
     *
     * @uses \Whm\Opm\Client\Server\Server
     * @uses \phmLabs\Components\Annovent\Event\Event to fire an event
     */
    private function initServer ()
    {
        $browser = new Browser();
        $this->server = new Server($this->config, $browser);
        $this->getEventDispatcher()->notify(new Event('server.create', array('server' => $this->server)));
    }

    /**
     * Execute messurement task
     *
     * @example $./bin/client messure
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     */
    protected function execute (InputInterface $input, OutputInterface $output)
    {
        $this->dryrun = $input->getOption('dryrun');

        $this->initConfig($input->getOption('config'));
        $this->initMessurementContainer();
        $this->initServer();

        $identifier = $input->getArgument('identifier');
        $messureType = $input->getArgument("messureType");
        $parameters = unserialize($input->getArgument('parameters'));

        $messureObject = $this->messurementContainer->getMessurement($messureType);
        $metrics = $this->messurementContainer->getMetrics($messureType);

        $messurementResult = new MessurementResult();
        $rawData = $messureObject->run($identifier, $parameters);
        $messurementResult->setMessurementRawData($rawData);

        foreach( $metrics as $metric ) {
            $metricValue = $metric->calculateMetric($rawData);
            $messurementResult->addMetric($metric->getName(), $metricValue);
        }

        if ($this->dryrun) {
            $output->writeln("Identifier: " . $identifier);
            $output->writeln("Result: " . $rawData);
        } else {
            $this->server->addTaskMessurement($identifier, $rawData);
        }
    }
}


text:
import sys
from django.contrib.auth import get_user_model
from django.core.management import load_command_class
from django.core.management.base import NoArgsCommand
from djangojames.db.utils import reset_schema
from optparse import make_option, NO_DEFAULT

from randomworld.defaults import UserFactory, DUMMY_PASSWORD
from randomworld.names import name_factory

class LoadRandomData(NoArgsCommand):
    ignore_reset_default = False
    dummy_factories = [(UserFactory, 30)]

    option_list = NoArgsCommand.option_list + (
        make_option('-i', '--ignore_reset', action='store_true', dest='ignore_reset',
                    help='Do not extecute the reset command (equivalent to syncdb)'),
    )
    help = "Drops and recreates database and loads dummydata."

    def log(self, message):
        sys.stdout.write("%s\n" % message)

    def create_objects(self):
        for klass, count in self.dummy_factories:
            #self.log("create %s %s ..." % (count, klass.FACTORY_FOR.__name__))
            for i in range(count):
                klass().save()

    def handle_noargs(self, **options):
        from django.conf import settings
        from django.db import models
        from django.core.management.sql import emit_post_sync_signal
        from django.db.utils import DEFAULT_DB_ALIAS
        from django.core.management import call_command

        ignore_reset = options.get('ignore_reset')
        if ignore_reset is None:
            ignore_reset = self.ignore_reset_default

        db = options.get('database', DEFAULT_DB_ALIAS)
        database_config = settings.DATABASES[db]

        if not ignore_reset:
            reset_schema(database_config)

            # hack to avoid using south
            klass = load_command_class('django.core', 'syncdb')
            args = {}
            defaults = {}
            options['interactive'] = False
            for opt in klass.option_list:
                if opt.default is NO_DEFAULT:
                    defaults[opt.dest] = None
                else:
                    defaults[opt.dest] = opt.default
            defaults.update(options)
            klass.execute(*args, **defaults)

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            emit_post_sync_signal(models.get_models(), 0, 0, db)

            call_command('migrate', fake=True)

        self.log("load Random Dummy data ...")

        try:
            user = get_user_model().objects.create_superuser('admin', 'admin@admin.dummy', DUMMY_PASSWORD)
            user.first_name, user.last_name = name_factory.get_full_name()
            user.save()
            self.log("superuser: admin")
        except Exception, e:
            self.log("WARNING: could not create superuser: %s" % str(e))

        self.create_objects()

        self.log("dummy passwords: %s" % DUMMY_PASSWORD)


text:
using System;

namespace Xb.Db
{
    //Inner-Class of Xb.Db.Model
    public partial class Model
    {
        /// <summary>
        /// Error Infomation Class
        /// エラー情報クラス
        /// </summary>
        /// <remarks></remarks>
        public class Error
        {
            /// <summary>
            /// Error type
            /// エラー区分
            /// </summary>
            public enum ErrorType
            {
                /// <summary>
                /// Validation OK
                /// エラー無し
                /// </summary>
                NoError,

                /// <summary>
                /// Charactor length overflow
                /// 文字長超過
                /// </summary>
                LengthOver,

                /// <summary>
                /// Value is not number
                /// 数値でない値
                /// </summary>
                NotNumber,

                /// <summary>
                /// Number of digits of integer part exceeded
                /// 整数部分の桁数超過
                /// </summary>
                IntegerOver,

                /// <summary>
                /// Number of digits of decimal part exceeded
                /// 小数部分の桁数超過
                /// </summary>
                DecimalOver,

                /// <summary>
                /// Null Not Permitted
                /// Nullが許可されていないカラムでNullを検出
                /// </summary>
                NotPermittedNull,

                /// <summary>
                /// Value is not datetime
                /// 日付型でない値
                /// </summary>
                NotDateTime,

                /// <summary>
                /// Unknown error
                /// 未定義のエラー
                /// </summary>
                NotDefinedError
            }

            /// <summary>
            /// Name
            /// エラー名
            /// </summary>
            public string Name { get; }

            /// <summary>
            /// Value
            /// 値
            /// </summary>
            public string Value { get; }

            /// <summary>
            /// Error type
            /// エラー型
            /// </summary>
            public ErrorType Type { get; }

            /// <summary>
            /// Customize error message
            /// カスタマイズエラーメッセージ
            /// </summary>
            private readonly string _customMessage;

            /// <summary>
            /// Message
            /// メッセージ
            /// </summary>
            public string Message
            {
                get
                {
                    if (this._customMessage != null)
                        return this._customMessage;

                    switch (this.Type)
                    {
                        case ErrorType.LengthOver:
                            return "Charactor Length Overflow";
                        case ErrorType.IntegerOver:
                            return "Number of digits of Integer part Exceeded";
                        case ErrorType.DecimalOver:
                            return "Number of digits of Decimal part Exceeded";
                        case ErrorType.NotNumber:
                            return "Not Number";
                        case ErrorType.NotPermittedNull:
                            return "Null Not Permitted";
                        case ErrorType.NotDateTime:
                            return "Not DateTime";
                        default:
                            return "Unknown Error";
                    }
                }
            }

            /// <summary>
            /// Constructor
            /// コンストラクタ
            /// </summary>
            /// <param name="columnName"></param>
            /// <param name="value"></param>
            /// <param name="type"></param>
            /// <param name="customMessage"></param>
            /// <remarks></remarks>
            public Error(string columnName
                       , string value
                       , ErrorType type
                       , string customMessage = null)
            {
                this.Name = columnName;
                this.Value = value;
                this.Type = type;
                this._customMessage = customMessage;

            }

            /// <summary>
            /// Constructor
            /// コンストラクタ
            /// </summary>
            /// <param name="customMessage"></param>
            /// <remarks></remarks>
            public Error(string customMessage)
            {
                this.Name = "-";
                this.Value = "-";
                this.Type = ErrorType.NotDefinedError;
                this._customMessage = customMessage;
            }

            /// <summary>
            /// Constructor
            /// コンストラクタ
            /// </summary>
            /// <param name="columnName"></param>
            /// <param name="customMessage"></param>
            /// <remarks></remarks>
            public Error(string columnName
                       , string customMessage)
            {
                this.Name = columnName;
                this.Value = "-";
                this.Type = ErrorType.NotDefinedError;
                this._customMessage = customMessage;
            }
        }
    }
}


text:
from django.http import HttpResponse, HttpResponseBadRequest, \
    HttpResponseRedirect , Http404
from django.views.decorators.http import require_POST
from django.contrib import messages
from django.utils.translation import ugettext as _

from seahub.auth.decorators import login_required
from seahub.options.models import UserOptions
from seahub.settings import SITE_ROOT

@login_required
@require_POST
def save_options(request):
    """
    """
    username = request.user.username
    repo_enc = request.POST.get('repo-enc', '')
    server_crypto = True if repo_enc.startswith('server') else False

    if server_crypto:
        UserOptions.objects.enable_server_crypto(username)
    else:
        UserOptions.objects.disable_server_crypto(username)

    next = request.META.get('HTTP_REFERER', None)
    if next is None:
        next = SITE_ROOT

    return HttpResponseRedirect(next)

@login_required
@require_POST
def sub_lib_enable_set(request):
    """
    """
    username = request.user.username
    enable_sub_lib = request.POST.get('enable-sub-lib', '')

    if enable_sub_lib:
        UserOptions.objects.enable_sub_lib(username)
    else:
        UserOptions.objects.disable_sub_lib(username)

    next = request.META.get('HTTP_REFERER', None)
    if next is None:
        next = SITE_ROOT

    return HttpResponseRedirect(next)


text:
Not found

Sorry the page you were looking for was not found.


text:
require './canhelplib'

module CanhelpPlugin
  include Canhelp

  def self.get_page_views_per_course(
    subdomain = prompt(:subdomain),
    account_id = prompt(:account_id),
    start_time = prompt(:start_time),
    end_time = prompt(:end_time)
  )

    token = get_token

    subaccount_ids = get_sub_accounts(subdomain,account_id)

    subaccount_ids << account_id

    puts "\t"
    puts "Grabbing enrollments from courses in the following accounts:"

    with_page_views = []
    without_page_views = []
    student_page_views = []

    subaccount_ids.each do |subaccount_id|
      puts "- #{subaccount_id}"
    end

    subaccount_ids.each do |subaccount|
      courses = get_courses(subdomain, subaccount)

      courses.each do |course|
        course_ids = course['id']

        enrollments = get_all_pages(
          token,
          "https://#{subdomain}.instructure.com/api/v1/courses/#{course_ids}/enrollments?state[]=active&state[]=completed&type[]=StudentEnrollment"
        )

        puts
        print "Total Number of StudentEnrollment: "
        puts enrollments.count
        puts

        enrollments.each do |enrollment|
          student_id =enrollment['user_id']
          student_name = enrollment['user']['name']

          print "Fetching Pageviews for #{student_name} #{student_id}: "
          page_views = get_json(
            token,
            "https://#{subdomain}.instructure.com/api/v1/users/#{student_id}/page_views?start_time=#{start_time}&end_time=#{end_time}"
          )

            if page_views.empty?
              puts "False"
              without_page_views += page_views
            else
              puts "True"
              with_page_views += page_views
            end

        end

      end

    end

    unique_users_with_page_views = with_page_views.map { |user_page_view| user_page_view['links']['user']
    }.uniq

    puts
    puts "- Total count of users with Pageviews: #{unique_users_with_page_views.count}"
    puts "-- #{unique_users_with_page_views}"
    puts "- Total count of users without Pageviews: #{without_page_views.count}"

  end
end


text:
message(STATUS "Running @_compiler@ @_in@ @_out@")
execute_process(COMMAND "@_compiler@" "@_in@" "@_out@"
  OUTPUT_VARIABLE _compile_out
  ERROR_VARIABLE _compile_err
  RESULT_VARIABLE _compile_ret)

if(NOT ${_compile_ret} EQUAL 0)
  message(FATAL_ERROR "Compilation failed. (retcode: ${_compile_ret})
out: ${_compile_out}
err: ${_compile_err}
")
endif()


text:
[![Build Status](https://travis-ci.org/minifast/voot.png)](https://travis-ci.org/minifast/voot) [![Code Climate](https://codeclimate.com/github/minifast/voot.png)](https://codeclimate.com/github/minifast/voot)

Voot lets you read and write WebVTT files with great ease.

## Usage

    > vtt = Voot.load("~/Movies/My Indian Films/manty-poothon.vtt")
    => #<Voot::Vtt>
    > vtt.cues.length
    => 1
    > vtt.cues.first.payload
    => "You are those knights and whatever, let me marry Srivani or we will dance"

## Installation

Add this line to your application's Gemfile:

    gem 'voot'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install voot

## Contributing

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


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="#aa000000">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textItem"
            android:height="82dp"
            android:textColor="#FFFFFFFF"/>
</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace SampleApp {

   public partial class FormSnapToContent : Form {

      private Control mControl;

      public void setControl(Control control) {
         if (mControl == control) {
            return;
         }
         if (null != mControl) {
            Controls.Remove(mControl);
            FormSub sub = mControl as FormSub;
            if (null != sub) {
               sub.onRemoved();
            }
         }
         mControl = control;
         if (null != mControl) {
            Controls.Add(mControl);
            FormSub sub = mControl as FormSub;
            if (null != sub) {
               sub.onAdded();
            }
            snapToControl();
         }
      }

      private void snapToControl() {
         if (null != mControl) {
            SetClientSizeCore(mControl.Width, mControl.Height);
         }
      }

      private void FormSnapToContent_Load(object sender, EventArgs e) {

      }

   }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="@dimen/subtitle">

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/category_bar"
        android:layout_weight="1"
        android:background="@android:color/transparent" />

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/category_shop"
        android:layout_weight="1"
        android:background="@android:color/transparent" />

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/category_hospitale"
        android:layout_weight="1"
        android:background="@android:color/transparent" />

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/category_restaurant"
        android:layout_weight="1"
        android:background="@android:color/transparent" />

    <ImageButton
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/category_hotel"
        android:layout_weight="1"
        android:background="@android:color/transparent" />
</LinearLayout>


text:
using namespace agora::rtm;
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Generic;

namespace AgoraClrLibrary {
	public ref class AgoraClrRTMChannel
	{
	public:
		AgoraClrRTMChannel(IRtmService* service, String^ id);
		~AgoraClrRTMChannel();

		int Join();
		int Leave();
		int SendMessage(ClrMessage^ msg);
		int SendMessage(ClrMessage^ msg,ClrSendMessageOptions^ options );
		void Release();
		property String^ Id { String^ get() { return id; }}
		int getMembers();

		AT<>::Type^ onJoinSuccess;
		AT<EnumJoinChannelErrCode>::Type^ onJoinFailure;
		AT<EnumLeaveChannelErrCode>::Type^ onLeave;
		AT<String^, ClrMessage^>::Type^ onMessageReceived;
		AT<long long, EnumChannelMessageErrCode>::Type^ onSendMessageResult;
		AT<ClrChannelMember^>::Type^ onMemberJoined;
		AT<ClrChannelMember^>::Type^ onMemberLeft;
		AT<List<ClrChannelMember^>^, EnumGetMembersErrCode>::Type^ onGetMembers;
		AT<List<ClrRtmChannelAttribute^>^>::Type^ onAttributesUpdated;
		AT<int>::Type^ onMemberCountUpdated;

		AT<String^,ClrFileMessage^>::Type^ onFileMessageReceived;
		AT<String^,ClrImageMessage^>::Type^ onImageMessageReceived;

	private:
		String^ id;
		IRtmService* service;
		IChannel* channel;
		AgoraClrRTMChannelEventHandler* events;
		List<GCHandle>^ gchs;

		void NativeOnJoinSuccess();
		void NativeOnJoinFailure(JOIN_CHANNEL_ERR code);
		void NativeOnLeave(LEAVE_CHANNEL_ERR code);
		void NativeOnMessageReceived(const char* userId, const IMessage* msg);
		void NativeOnSendMessageResult(long long id, CHANNEL_MESSAGE_ERR_CODE code);
		void NativeOnMemberJoined(IChannelMember* member);
		void NativeOnMemberLeft(IChannelMember* member);
		void NativeOnGetMembers(IChannelMember** members, int count, GET_MEMBERS_ERR code);
		void NativeOnAttributesUpdated(const IRtmChannelAttribute* attrs[], int count);
		void NativeOnMemberCountUpdated(int count);

		//1.3°æ±¾ÐÂÔö Îļþ+ͼƬÏûÏ¢ £¨×î´ó30M£¬·þÎñÆ÷×î¶à·ÅÆßÌ죩
		void NativeOnFileMessageReceived(const char * userId, const IFileMessage*  message);
		void NativeOnImageMessageReceived(const char * userId, const IImageMessage*  message);

	private:
		template<typename E, typename D>
		inline void regEvent(E& e, D^ d)
		{
			gchs->Add(GCHandle::Alloc(d));
			e = reinterpret_cast<E>(Marshal::GetFunctionPointerForDelegate(d).ToPointer());
		}

		void bindEvents();
	};

}


text:
namespace pipe { namespace algorithm {

template <typename Generator, typename Predicate>
auto all(Generator gen, Predicate pred)
{
	for (auto&& item : gen)
		if (!pred(item))
			return false;

	return true;
}

template <typename Generator, typename Predicate>
auto some(Generator gen, Predicate pred)
{
	for (auto&& item : gen)
		if (pred(item))
			return true;

	return false;
}

template <typename Predicate>
auto all(Predicate pred)
{
	return details::algorithm([=](auto gen) { return all(std::move(gen), pred); });
}

template <typename Predicate>
auto none(Predicate pred)
{
    return all(pipe::functional::negate(pred));
}

template <typename Predicate>
auto some(Predicate pred)
{
	return details::algorithm([=](auto gen) { return some(std::move(gen), pred); });
}

}} // namespace pipe::algorithm


text:
 "use strict";

readConfig(apiObj);

function readConfig(arr) {   // Read the config.js file
  var len = arr.length;
  var array;

  if(len) {
    // for loop reads array of config objects defining each command in the REST API
    for(var i=0;i<len;i++) {
      var comp = createComponent(arr[i]);
      if(comp)
        var ex = document.getElementById('explorer');
        ex.appendChild(comp);
    }
  }
}

function createContainer(id, cName, text) {
  var el = document.createElement("div");
  if(id) el.setAttribute('id', id );
  if(cName) el.setAttribute('class', cName );
  if(text)   el.innerText = text;
  return el;
}

function displayResponseView(result, dataId) {
  var responseView = document.getElementById(dataId + "-resp");

  while(responseView.firstChild){
    responseView.removeChild(responseView.firstChild);
  }
  var titlebar = createContainer(null, 'titlebar', "Response");
  responseView.appendChild(titlebar);
  var rText = createContainer(null, 'content', "");
  rText.innerText = JSON.stringify(result);
  responseView.appendChild(rText);
}

function sendRequest(url, method, dataId, headerStr) { // need to add form to this?
  var headers = headerStr.split('|');
  var headerObj = {};  // create object from headerStr; split to array, obj transform

  for(var i=0;i<headers.length;i++) {
    var headerItem = headers[i];
    var itemArr = headerItem.split(':');
    headerObj[itemArr[0]] = itemArr[1];
  }

  jQuery.ajax({
    method: method,
    url: url,
    data: $('#' + dataId + "-test").serialize(),
    headers: JSON.stringify(headerObj)
  })
    .done((result, sText, rObj) => {
      displayResponseView(result, dataId);
      console.log(result); // send text to response-view
  })
    .fail((jqXHR, textStatus, error) => {
      console.log(textStatus);  // failed message in console
  });
}

function createForm(item) {
  var f = document.createElement("form");
  f.setAttribute('method', item.method);
  f.setAttribute('action', item.url);
  f.setAttribute('id', item.title + item.method + "-test");
  f.setAttribute('name', item.title);
  return f;                   // append all input elements to this form element
}

function setTitleDisplay(comp, item) {
  var titlebar = createContainer(null, 'titlebar', item.title);
  comp.appendChild(titlebar);  // add title to componenet header

  var displayM = createContainer(null, 'displayM', item.method);  // Method display
  comp.appendChild(displayM);

  var displayUrl = createContainer(null, 'url', item.url);  // URL display
  comp.appendChild(displayUrl);

  var headerStr = createHeaderStr('', item.headers);
  var displayHeaders = createContainer('headers', 'url', headerStr);  // Header display
  comp.appendChild(displayHeaders);
}

function createComponent(item) {
  var di = document.createElement("div");  // component container created
  di.setAttribute('id', item.title);
  //di.setAttribute('id', item.title + item.method)
  di.setAttribute('class', 'component');

  setTitleDisplay(di, item);
  var frm = createForm(item);   // return a form, append body fields if any

  if(item.body && item.body.length) {
    var blen = item.body.length;
    for(var j=0;j<blen;j++) {
      createInput(item.body[j], frm);
    }
  }

  addButtons(frm, item);
  addResponsViewer(frm, item.title + item.method + "-resp");
  di.appendChild(frm);  // add the new form to the componenet container
  return di;
}

/* create an input from each item listed in the body[] array */
function createInput(inpObj, frmEl) {
  var br = document.createElement("br");
  var inp = document.createElement("input"); //input element, Submit button
  inp.setAttribute('class', 'input');  // special class to id these fields

  for(var i in inpObj) {
    if (inpObj.hasOwnProperty(i)) {
       inp.setAttribute(i, inpObj[i]);
    }
  }
  frmEl.appendChild(inp);
  frmEl.appendChild(br);
}

function createHeaderStr(headerStr, header) {
  for(var i in header) {
    if (header.hasOwnProperty(i)) {
      if(headerStr === '') {
        headerStr += i + ':' + header[i];
      }
      else {
        headerStr += '|' + i + ':' + header[i];
      }
    }
  }
  return headerStr;
}

/* Add buttons to each API component: Submit, Test, Clear */
function addButtons(el, item) {
  var buttons = document.createElement("div"); // buttons container
  buttons.setAttribute('class',"buttons");

  var sub = document.createElement("input"); //input element, Submit button
  sub.setAttribute('type',"button");
  sub.setAttribute('value',"Send Request");
  sub.setAttribute('class', "button");

  if(item) {   // needs an id item.title + item.method
    var url = item.url;
    var method = item.method;
    var str = '';
    var header = item.headers;
    var headerStr = createHeaderStr(str, header);
    var dataId = item.title + item.method;

    sub.setAttribute('onclick', "return sendRequest('" + url + "','" + method + "','" + dataId + "','" + headerStr + "');");
  }

  var test = null;
  if(item.body && item.body.length) {

    var testid = dataId + "-test";
    test = document.createElement("input"); //input element, Test button
    test.setAttribute('type',"button");
    test.setAttribute('value',"Test Data");
    test.setAttribute('onclick',"fillTestData('" + testid + "')");
    test.setAttribute('class', "button");

    var clear = document.createElement("input"); //input element, Clear button
    clear.setAttribute('type',"reset");
    clear.setAttribute('value',"Clear Form");
    clear.setAttribute('class', "button");
  }

  buttons.appendChild(sub);

  if(item.body && item.body.length) {
    buttons.appendChild(test);
    buttons.appendChild(clear);
  }
  el.appendChild(buttons);
}

function addResponsViewer(el, id) {
  var resp = createContainer(id, 'response-view', ''); // id = item.title + item.method + "-resp"
  el.appendChild(resp);
}

function fillTestData(testid) {
  var frm = document.getElementById(testid);
  var len = frm.length - 3;

  for(var i=0; i<len; i++) {
    var inputs = frm.getElementsByClassName("input");
    var attlen = inputs[i].attributes.length;
    var testdata = '';
    if(attlen) {
        testdata = inputs[i].attributes[attlen - 1].textContent;
    }
    if(testdata !== '') inputs[i].value = testdata;
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>slyfox.za.net Package Repository</title>

	<link rel="import" href="components.html">
	<link rel="stylesheet" href="app.css">

	<template id="t" is="auto-binding">
		<flatiron-director route="{{route}}" autohash></flatiron-director>
		<core-scaffold>
			<core-header-panel navigation flex mode="seamed">
				<core-toolbar></core-toolbar>
				<core-menu selected="{{route}}" valueattr="hash">
					<template repeat="{{pages}}">
						<paper-item hash="{{hash}}" noink>{{name}}</paper-item>
					</template>
				</core-menu>
			</core-header-panel>

slyfox.za.net Package Repository

			<core-animated-pages fit selected="{{route}}" valueattr="hash">

Overview

This site stores packages built by me. View the available
					packages for each operating system or Linux distribution using the links in the navigation menu.

				<template repeat="{{page in pages|repos}}">

					<repo-page page="{{page}}"></repo-page>

</template>
			</core-animated-pages>
		</core-scaffold>
	</template>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>war</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <parent>
        <groupId>ghostd.boot.sourcemaps</groupId>
        <artifactId>spring-boot-source-maps-example</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>ghostd.boot.sourcemaps</groupId>
            <artifactId>static</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.google.javascript</groupId>
            <artifactId>closure-compiler</artifactId>
            <version>v20151015</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.0.31-beta</version>
        </dependency>
    </dependencies>
</project>