text:
<?php
/**
 * InlineResponse201
 *
 * PHP version 5
 *
 * @category Class
 * @package  SignRequest
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * SignRequest API
 *
 * API for SignRequest.com
 * OpenAPI spec version: v1
 * Contact: tech-support@signrequest.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.11
 */
/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace SignRequest\Model;

use \ArrayAccess;
use \SignRequest\ObjectSerializer;

/**
 * InlineResponse201 Class Doc Comment
 *
 * @category Class
 * @package  SignRequest
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class InlineResponse201 implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'inline_response_201';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'detail' => 'string',
        'cancelled' => 'bool'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'detail' => null,
        'cancelled' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'detail' => 'detail',
        'cancelled' => 'cancelled'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'detail' => 'setDetail',
        'cancelled' => 'setCancelled'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'detail' => 'getDetail',
        'cancelled' => 'getCancelled'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    const DETAIL_OK = 'OK';

    /**
     * Gets allowable values of the enum
     *
     * @return string[]
     */
    public function getDetailAllowableValues()
    {
        return [
            self::DETAIL_OK,
        ];
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['detail'] = isset($data['detail']) ? $data['detail'] : null;
        $this->container['cancelled'] = isset($data['cancelled']) ? $data['cancelled'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        if ($this->container['detail'] === null) {
            $invalidProperties[] = "'detail' can't be null";
        }
        $allowedValues = $this->getDetailAllowableValues();
        if (!is_null($this->container['detail']) && !in_array($this->container['detail'], $allowedValues, true)) {
            $invalidProperties[] = sprintf(
                "invalid value for 'detail', must be one of '%s'",
                implode("', '", $allowedValues)
            );
        }

        if ($this->container['cancelled'] === null) {
            $invalidProperties[] = "'cancelled' can't be null";
        }
        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets detail
     *
     * @return string
     */
    public function getDetail()
    {
        return $this->container['detail'];
    }

    /**
     * Sets detail
     *
     * @param string $detail detail
     *
     * @return $this
     */
    public function setDetail($detail)
    {
        $allowedValues = $this->getDetailAllowableValues();
        if (!in_array($detail, $allowedValues, true)) {
            throw new \InvalidArgumentException(
                sprintf(
                    "Invalid value for 'detail', must be one of '%s'",
                    implode("', '", $allowedValues)
                )
            );
        }
        $this->container['detail'] = $detail;

        return $this;
    }

    /**
     * Gets cancelled
     *
     * @return bool
     */
    public function getCancelled()
    {
        return $this->container['cancelled'];
    }

    /**
     * Sets cancelled
     *
     * @param bool $cancelled cancelled
     *
     * @return $this
     */
    public function setCancelled($cancelled)
    {
        $this->container['cancelled'] = $cancelled;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
erlang_training
===============

Excercises for people who're trying to learn Erlang

Description
===========

Excercises are written as Common Test suites.
Students should fork this repo (or create a branch in it), try running ``$ make test`` on their consoles and write the appropriate code to pass the tests.
Excercise description and some tips are written as part of the test module documentation. To get it in html form, just run ``$ make doc``

Contact Us
===========

For **questions** or **general comments** regarding the use of this library, please use our public
[hipchat room](http://inaka.net/hipchat).

If you find any **bugs** or have a **problem** while using this library, please [open an issue](https://github.com/inaka/erlang_training/issues/new) in this repo (or a pull request :)).

And you can check all of our open-source projects at [inaka.github.io](http://inaka.github.io)

redpajama_set_name: RedPajamaGithub


text:
package com.kodedu.service.extension.math.block;

import com.kodedu.service.ThreadService;
import com.kodedu.service.extension.MathJaxService;
import com.kodedu.service.extension.math.MathProcessor;
import org.asciidoctor.ast.ContentModel;
import org.asciidoctor.extension.Contexts;
import org.asciidoctor.extension.Name;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import static org.asciidoctor.extension.Contexts.*;
import static org.asciidoctor.extension.Contexts.PARAGRAPH;

@Name("stem_")
@Contexts({OPEN, EXAMPLE, SIDEBAR, LITERAL, LISTING, QUOTE, PASS, PARAGRAPH})
@ContentModel(ContentModel.EMPTY)
@Component
@Scope("prototype")
public class StemMathBlockProcessor extends MathBlockProcessor {

    public StemMathBlockProcessor(Environment environment, MathJaxService mathJaxService, ThreadService threadService, MathProcessor mathProcessor) {
        super(environment, mathJaxService, threadService, mathProcessor);
    }

}


text:
class AddCcYourselfToSites < ActiveRecord::Migration
  def self.up
    add_column :sites, :cc_yourself, :boolean
  end

  def self.down
    remove_column :sites, :cc_yourself
  end
end


text:
package org.apache.apex.malhar.lib.utils.serde;

import org.apache.apex.malhar.lib.window.Window;
import org.apache.apex.malhar.lib.window.Window.TimeWindow;

import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

/**
 * @since 3.7.0
 */
public class TimeWindowSerde implements Serde<Window.TimeWindow>
{
  @Override
  public void serialize(TimeWindow timeWindow, Output output)
  {
    output.writeLong(timeWindow.getBeginTimestamp());
    output.writeLong(timeWindow.getDurationMillis());
  }

  @Override
  public TimeWindow deserialize(Input input)
  {
    return new TimeWindow(input.readLong(), input.readLong());
  }

}


text:
<link rel="stylesheet" type="text/css" href="../hotwriting.css">

<link href='http://fonts.googleapis.com/css?family=Merriweather+Sans' rel='stylesheet' type='text/css'>

<audio id="judyMusic" preload="auto" src="Judy.mp3"></audio>

Press a key every time you hear "Doo"

Press any key to begin


text:
\chapter{TMap}

Implements container for ordered associative array with unique keys.
Takes 3 arguments for specialization, first one is type of keys, second one is type of values, third
one is comparator class for keys.
Usage example:

\lstinputlisting[language=Pascal]{mapexample.pp}

Some methods return type TMSet.PNode. Usefull fields are Data.Key, Data.Value, for retrieving
actual Key and Value from node. This node can be also used for navigation between elements by methods of set class.
You can also change value in node (but not key).
(But don't do anything else with it, you can lose data integrity.)

Memory complexity:
Size of stored base + constant overhead for each stored element (3 pointers + one boolean).

Members list:

\begin{longtable}{|m{10cm}|m{5cm}|}
\hline
Method & Complexity guarantees \\ \hline
\multicolumn{2}{|m{15cm}|}{Description} \\ \hline\hline

\verb!Create! & O(1) \\ \hline
\multicolumn{2}{|m{15cm}|}{Constructor. Creates empty map.} \\ \hline\hline

\verb!function Size(): SizeUInt! & O(1) \\ \hline
\multicolumn{2}{|m{15cm}|}{Returns number of elements in map.} \\\hline\hline

\verb!procedure Insert(key: TKey; value: TValue)! &
O(lg N), N is number of elements in map \\ \hline
\multicolumn{2}{|m{15cm}|}{Inserts key value pair into map. If key was already there, it will have
new value assigned.} \\\hline\hline

\verb!procedure Delete(key: TKey)! &
O(lg N) \\ \hline
\multicolumn{2}{|m{15cm}|}{Deletes key (and associated value) from map. If element is not in map, nothing happens.} \\\hline\hline

\verb!function Find(key: T):TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Searches for key in map. If value is not there returns nil. Otherwise
returns pointer to tree node (type TMSet.PNode), which can be used for retrieving data from map.} \\\hline\hline

\verb!function FindLess(key: T):TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Searches for greatest element less than key in map. If such element is not there returns nil. Otherwise
returns pointer to tree node (type TMSet.PNode), which can be used for retrieving data from map.} \\\hline\hline

\verb!function FindLessEqual(key: T):TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Searches for greatest element less or equal than key in map. If such element is not there returns nil. Otherwise
returns pointer to tree node (type TMSet.PNode), which can be used for retrieving data from map.} \\\hline\hline

\verb!function FindGreater(key: T):TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Searches for smallest element greater than key in map. If such element is not there returns nil. Otherwise
returns pointer to tree node (type TMSet.PNode), which can be used for retrieving data from map.} \\\hline\hline

\verb!function FindGreaterEqual(key: T):TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Searches for smallest element greater or equal than key in map. If such element is not there returns nil. Otherwise
returns pointer to tree node (type TMSet.PNode), which can be used for retrieving data from map.} \\\hline\hline

\verb!function Min:TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Returns node containing smallest key of map. If map is empty returns
nil.} \\\hline\hline

\verb!function Max:TMSet.PNode! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Returns node containing largest key of map. If map is empty returns
nil.} \\\hline\hline

\verb!function Next(x:TMSet.PNode):TMSet.PNode! & O(lg N) worst case, but traversal from smallest element to
largest takes O(N) time \\\hline
\multicolumn{2}{|m{15cm}|}{Returns successor of x. If x is largest key of map, returns nil.} \\\hline\hline

\verb!function Prev(x:TMSet.PNode):TMSet.PNode! & O(lg N) worst case, but traversal from largest element to
smallest takes O(N) time \\\hline
\multicolumn{2}{|m{15cm}|}{Returns predecessor of x. If x is smallest key of map, returns nil.} \\\hline\hline

\verb!function IsEmpty(): boolean! & O(1) \\ \hline
\multicolumn{2}{|m{15cm}|}{Returns true when map is empty.} \\\hline

\verb!function GetValue(key:TKey):TValue! & O(lg N) \\\hline
\multicolumn{2}{|m{15cm}|}{Returns value associated with key. Is key isn't in map crashes.} \\\hline

\verb!property item[i: Key]: TValue; default;! & O(ln N) \\\hline
\multicolumn{2}{|m{15cm}|}{Property for accessing key i in map. Can be used just by square
brackets (its default property).} \\\hline\hline

\end{longtable}


text:
from django.db import models
from django.contrib.auth.models import User

class MyFileField(models.FileField):
    pass

class Member(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateTimeField(blank=True, null=True)
    gender = models.CharField(max_length=1, blank=True, choices=[('M','Male'), ('F', 'Female')])

    def __unicode__(self):
        return self.name

class Band(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(Member)

    def __unicode__(self):
        return self.name

class Album(models.Model):
    band = models.ForeignKey(Band)
    name = models.CharField(max_length=100)
    cover_art = models.FileField(upload_to='albums')
    backside_art = MyFileField(upload_to='albums_back', null=True)

    def __unicode__(self):
        return self.name

class HiddenInventoryManager(models.Manager):
    def get_query_set(self):
        return super(HiddenInventoryManager, self).get_query_set().filter(hidden=False)

class Inventory(models.Model):
   barcode = models.PositiveIntegerField(unique=True)
   parent = models.ForeignKey('self', to_field='barcode', blank=True, null=True)
   name = models.CharField(blank=False, max_length=20)
   hidden = models.BooleanField(default=False)

   # see #9258
   default_manager = models.Manager()
   objects = HiddenInventoryManager()

   def __unicode__(self):
      return self.name

class Event(models.Model):
    band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0))
    start_date = models.DateField(blank=True, null=True)
    start_time = models.TimeField(blank=True, null=True)
    description = models.TextField(blank=True)
    link = models.URLField(blank=True)
    min_age = models.IntegerField(blank=True, null=True)

class Car(models.Model):
    owner = models.ForeignKey(User)
    make = models.CharField(max_length=30)
    model = models.CharField(max_length=30)

    def __unicode__(self):
        return u"%s %s" % (self.make, self.model)

class CarTire(models.Model):
    """
    A single car tire. This to test that a user can only select their own cars.
    """
    car = models.ForeignKey(Car)


text:
using UnityEngine;
using System.Collections;
using UnityEditor;
using HedgehogTeam.EasyTouch;
#if UNITY_5_3
using UnityEditor.SceneManagement;
#endif

[CustomEditor(typeof(QuickTouch))]
public class QuickTouchInspector : Editor {

	public override void OnInspectorGUI(){

		QuickTouch t = (QuickTouch)target;

		EditorGUILayout.Space();

		t.quickActionName = EditorGUILayout.TextField("Name",t.quickActionName);

		EditorGUILayout.Space();

		t.is2Finger = EditorGUILayout.Toggle("2 fingers gesture",t.is2Finger);
		t.actionTriggering = (QuickTouch.ActionTriggering)EditorGUILayout.EnumPopup("Action triggering",t.actionTriggering);

		EditorGUILayout.Space();

		if (!t.is2Finger){
			t.isMultiTouch = EditorGUILayout.ToggleLeft("Allow multi-touch",t.isMultiTouch);
		}
		t.enablePickOverUI = EditorGUILayout.ToggleLeft("Allow over UI Element",t.enablePickOverUI);

		serializedObject.Update();
		SerializedProperty touch = serializedObject.FindProperty("onTouch");
		EditorGUILayout.PropertyField(touch, true, null);
		serializedObject.ApplyModifiedProperties();

		if (t.actionTriggering == QuickTouch.ActionTriggering.Up){
			touch = serializedObject.FindProperty("onTouchNotOverMe");
			EditorGUILayout.PropertyField(touch, true, null);
			serializedObject.ApplyModifiedProperties();
		}

		if (GUI.changed){
			EditorUtility.SetDirty(t);
			#if UNITY_5_3
			EditorSceneManager.MarkSceneDirty( EditorSceneManager.GetActiveScene());
			#endif
		}
	}
}


text:
{% extends "eventapp/base.html" %}
{% load i18n %}
{% block title %}{% trans "Page temporarily unavailable" %}{% endblock %}

{% block content %}

{% trans "Page temporarily unavailable" %}

{{ error }}

{% endblock %}


text:
import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  it,
  inject,
  async
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { MdIconRegistry } from '@angular2-material/icon';
import { HeaderComponent } from './header.component';
import { SidenavService } from '../content/sidenav.service';

describe('Component: Header', () => {
  let builder: TestComponentBuilder;

  beforeEachProviders(() => [
    HeaderComponent,
    SidenavService,
    MdIconRegistry
  ]);
  beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
    builder = tcb;
  }));

  it('should inject the component', inject([HeaderComponent],
    (component: HeaderComponent) => {
      expect(component).toBeTruthy();
    }
  ));

  it('should create the component', async(inject([], () => {
    return builder.createAsync(HeaderComponentTestController)
      .then((fixture: ComponentFixture<any>) => {
        let query = fixture.debugElement.query(By.directive(HeaderComponent));
        expect(query).toBeTruthy();
        expect(query.componentInstance).toBeTruthy();
      });
  })));
});

@Component({
  selector: 'test',
  template: `
    <app-header></app-header>
  `,
  directives: [HeaderComponent]
})
class HeaderComponentTestController {
}


text:
package chevalier

import (
	"code.google.com/p/goprotobuf/proto"
)

// NewSourceRequestTag builds a SourceRequest_Tag from a field and a
// value.
func NewSourceRequestTag(field, value string) *SourceRequest_Tag {
	tag := new(SourceRequest_Tag)
	f := field
	v := value
	tag.Field = &f
	tag.Value = &v
	return tag
}

// NewSourceRequest builds a SourceRequest from a slice of tags.
func NewSourceRequest(tags []*SourceRequest_Tag) *SourceRequest {
	req := new(SourceRequest)
	req.Tags = tags
	return req
}

func MarshalSourceRequest(req *SourceRequest) ([]byte, error) {
	marshalled, err := proto.Marshal(req)
	return marshalled, err
}

func UnmarshalSourceRequest(packet []byte) (*SourceRequest, error) {
	source := new(SourceRequest)
	err := proto.Unmarshal(packet, source)
	return source, err
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('login_userid')){
   function login_userid(){
    $CI =& get_instance();
    // We need to use $CI->session instead of $this->session
    $user = $CI->session->userdata('user_id');
    if (!isset($user)) { return NULL; } else { return $user; }
   }
}

if ( ! function_exists('login_username')){
   function login_username(){
    $CI =& get_instance();
    // We need to use $CI->session instead of $this->session
    $user = $CI->session->userdata('user_name');
    if (!isset($user)) { return NULL; } else { return $user; }
   }
}

if( !function_exists('b_url')){
    function b_url() {
        echo base_url();
    }
}


text:
package com.google.aggregate.adtech.worker;

import com.google.aggregate.adtech.worker.testing.InMemoryResultLoggerModule;

/** CLI enum to select a {@code ResultLoggerModule} to use */
public enum ResultLoggerModuleSelector {
  IN_MEMORY(new InMemoryResultLoggerModule()),
  LOCAL_AVRO_TO_S3(new LocalAvroToS3LoggerModule());

  private final ResultLoggerModule resultLoggerModule;

  ResultLoggerModuleSelector(ResultLoggerModule resultLoggerModule) {
    this.resultLoggerModule = resultLoggerModule;
  }

  ResultLoggerModule getResultLoggerModule() {
    return resultLoggerModule;
  }
}


text:
<?php

$languageStrings = Array(
    'LBL_RSS_FEED_SOURCES' => 'Fonti Feed Rss',
    'LBL_ADD_FEED_SOURCE' => 'Aggiungere fonte di alimentazione',
    'LBL_FEEDS_LIST_FROM' => 'Feed List Da',
    'LBL_SET_AS_DEFAULT' => 'Imposta come predefinito',
    'LBL_SENDER' => 'trasmettitore',
    'LBL_FEED_SOURCE' => 'fonte di alimentazione',
    'LBL_ENTER_FEED_SOURCE' => 'Inserisci fonte di alimentazione',
    'SINGLE_Rss' => 'di feed RSS',
);

$jsLanguageStrings = array(
	'JS_RSS_SUCCESSFULLY_SAVED' => 'Rss con successo salvati',
    'JS_INVALID_RSS_URL' => 'Non valido Rss Url',
    'JS_RSS_MADE_AS_DEFAULT' => 'Rss Fatto come predefinito',

);

?>


text:
package org.elasticsearch.ingest.common;

import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.ingest.AbstractProcessor;
import org.elasticsearch.ingest.ConfigurationUtils;
import org.elasticsearch.ingest.IngestDocument;
import org.elasticsearch.ingest.Processor;

import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;

import static org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException;
import static org.elasticsearch.ingest.ConfigurationUtils.readBooleanProperty;

public final class CommunityIdProcessor extends AbstractProcessor {

    public static final String TYPE = "community_id";

    private static final ThreadLocal<MessageDigest> MESSAGE_DIGEST = ThreadLocal.withInitial(() -> {
        try {
            return MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            // should never happen, SHA-1 must be available in all JDKs
            throw new IllegalStateException(e);
        }
    });

    private final String sourceIpField;
    private final String sourcePortField;
    private final String destinationIpField;
    private final String destinationPortField;
    private final String ianaNumberField;
    private final String transportField;
    private final String icmpTypeField;
    private final String icmpCodeField;
    private final String targetField;
    private final byte[] seed;
    private final boolean ignoreMissing;

    CommunityIdProcessor(
        String tag,
        String description,
        String sourceIpField,
        String sourcePortField,
        String destinationIpField,
        String destinationPortField,
        String ianaNumberField,
        String transportField,
        String icmpTypeField,
        String icmpCodeField,
        String targetField,
        byte[] seed,
        boolean ignoreMissing
    ) {
        super(tag, description);
        this.sourceIpField = sourceIpField;
        this.sourcePortField = sourcePortField;
        this.destinationIpField = destinationIpField;
        this.destinationPortField = destinationPortField;
        this.ianaNumberField = ianaNumberField;
        this.transportField = transportField;
        this.icmpTypeField = icmpTypeField;
        this.icmpCodeField = icmpCodeField;
        this.targetField = targetField;
        this.seed = seed;
        this.ignoreMissing = ignoreMissing;
    }

    public String getSourceIpField() {
        return sourceIpField;
    }

    public String getSourcePortField() {
        return sourcePortField;
    }

    public String getDestinationIpField() {
        return destinationIpField;
    }

    public String getDestinationPortField() {
        return destinationPortField;
    }

    public String getIanaNumberField() {
        return ianaNumberField;
    }

    public String getTransportField() {
        return transportField;
    }

    public String getIcmpTypeField() {
        return icmpTypeField;
    }

    public String getIcmpCodeField() {
        return icmpCodeField;
    }

    public String getTargetField() {
        return targetField;
    }

    public byte[] getSeed() {
        return seed;
    }

    public boolean getIgnoreMissing() {
        return ignoreMissing;
    }

    @Override
    public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
        String sourceIp = ingestDocument.getFieldValue(sourceIpField, String.class, ignoreMissing);
        String destinationIp = ingestDocument.getFieldValue(destinationIpField, String.class, ignoreMissing);
        Object ianaNumber = ingestDocument.getFieldValue(ianaNumberField, Object.class, true);
        Supplier<Object> transport = () -> ingestDocument.getFieldValue(transportField, Object.class, ignoreMissing);
        Supplier<Object> sourcePort = () -> ingestDocument.getFieldValue(sourcePortField, Object.class, ignoreMissing);
        Supplier<Object> destinationPort = () -> ingestDocument.getFieldValue(destinationPortField, Object.class, ignoreMissing);
        Object icmpType = ingestDocument.getFieldValue(icmpTypeField, Object.class, true);
        Object icmpCode = ingestDocument.getFieldValue(icmpCodeField, Object.class, true);
        Flow flow = buildFlow(sourceIp, destinationIp, ianaNumber, transport, sourcePort, destinationPort, icmpType, icmpCode);
        if (flow == null) {
            if (ignoreMissing) {
                return ingestDocument;
            } else {
                throw new IllegalArgumentException("unable to construct flow from document");
            }
        }

        ingestDocument.setFieldValue(targetField, flow.toCommunityId(seed));
        return ingestDocument;
    }

    public static String apply(
        String sourceIpAddrString,
        String destIpAddrString,
        Object ianaNumber,
        Object transport,
        Object sourcePort,
        Object destinationPort,
        Object icmpType,
        Object icmpCode,
        int seed
    ) {

        Flow flow = buildFlow(
            sourceIpAddrString,
            destIpAddrString,
            ianaNumber,
            () -> transport,
            () -> sourcePort,
            () -> destinationPort,
            icmpType,
            icmpCode
        );

        if (flow == null) {
            throw new IllegalArgumentException("unable to construct flow from document");
        } else {
            return flow.toCommunityId(toUint16(seed));
        }
    }

    public static String apply(
        String sourceIpAddrString,
        String destIpAddrString,
        Object ianaNumber,
        Object transport,
        Object sourcePort,
        Object destinationPort,
        Object icmpType,
        Object icmpCode
    ) {
        return apply(sourceIpAddrString, destIpAddrString, ianaNumber, transport, sourcePort, destinationPort, icmpType, icmpCode, 0);
    }

    private static Flow buildFlow(
        String sourceIpAddrString,
        String destIpAddrString,
        Object ianaNumber,
        Supplier<Object> transport,
        Supplier<Object> sourcePort,
        Supplier<Object> destinationPort,
        Object icmpType,
        Object icmpCode
    ) {
        if (sourceIpAddrString == null) {
            return null;
        }

        if (destIpAddrString == null) {
            return null;
        }

        Flow flow = new Flow();
        flow.source = InetAddresses.forString(sourceIpAddrString);
        flow.destination = InetAddresses.forString(destIpAddrString);

        Object protocol = ianaNumber;
        if (protocol == null) {
            protocol = transport.get();
            if (protocol == null) {
                return null;
            }
        }
        flow.protocol = Transport.fromObject(protocol);

        switch (flow.protocol) {
            case Tcp:
            case Udp:
            case Sctp:
                flow.sourcePort = parseIntFromObjectOrString(sourcePort.get(), "source port");
                if (flow.sourcePort < 1 || flow.sourcePort > 65535) {
                    throw new IllegalArgumentException("invalid source port [" + sourcePort.get() + "]");
                }

                flow.destinationPort = parseIntFromObjectOrString(destinationPort.get(), "destination port");
                if (flow.destinationPort < 1 || flow.destinationPort > 65535) {
                    throw new IllegalArgumentException("invalid destination port [" + destinationPort.get() + "]");
                }
                break;
            case Icmp:
            case IcmpIpV6:
                // tolerate missing or invalid ICMP types and codes
                flow.icmpType = parseIntFromObjectOrString(icmpType, "icmp type");
                flow.icmpCode = parseIntFromObjectOrString(icmpCode, "icmp code");
                break;
        }

        return flow;
    }

    @Override
    public String getType() {
        return TYPE;
    }

    /**
     * Converts an integer in the range of an unsigned 16-bit integer to a big-endian byte pair
     */
    static byte[] toUint16(int num) {
        if (num < 0 || num > 65535) {
            throw new IllegalStateException("number [" + num + "] must be a value between 0 and 65535");
        }
        return new byte[] { (byte) (num >> 8), (byte) num };
    }

    /**
     * Attempts to coerce an object to an integer
     */
    static int parseIntFromObjectOrString(Object o, String fieldName) {
        if (o == null) {
            return 0;
        } else if (o instanceof Number number) {
            return number.intValue();
        } else if (o instanceof String string) {
            try {
                return Integer.parseInt(string);
            } catch (NumberFormatException e) {
                // fall through to IllegalArgumentException below
            }
        }
        throw new IllegalArgumentException("unable to parse " + fieldName + " [" + o + "]");
    }

    public static final class Factory implements Processor.Factory {

        static final String DEFAULT_SOURCE_IP = "source.ip";
        static final String DEFAULT_SOURCE_PORT = "source.port";
        static final String DEFAULT_DEST_IP = "destination.ip";
        static final String DEFAULT_DEST_PORT = "destination.port";
        static final String DEFAULT_IANA_NUMBER = "network.iana_number";
        static final String DEFAULT_TRANSPORT = "network.transport";
        static final String DEFAULT_ICMP_TYPE = "icmp.type";
        static final String DEFAULT_ICMP_CODE = "icmp.code";
        static final String DEFAULT_TARGET = "network.community_id";

        @Override
        public CommunityIdProcessor create(
            Map<String, Processor.Factory> registry,
            String processorTag,
            String description,
            Map<String, Object> config
        ) throws Exception {
            String sourceIpField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "source_ip", DEFAULT_SOURCE_IP);
            String sourcePortField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "source_port", DEFAULT_SOURCE_PORT);
            String destIpField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "destination_ip", DEFAULT_DEST_IP);
            String destPortField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "destination_port", DEFAULT_DEST_PORT);
            String ianaNumberField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "iana_number", DEFAULT_IANA_NUMBER);
            String transportField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "transport", DEFAULT_TRANSPORT);
            String icmpTypeField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "icmp_type", DEFAULT_ICMP_TYPE);
            String icmpCodeField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "icmp_code", DEFAULT_ICMP_CODE);
            String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field", DEFAULT_TARGET);
            int seedInt = ConfigurationUtils.readIntProperty(TYPE, processorTag, config, "seed", 0);
            if (seedInt < 0 || seedInt > 65535) {
                throw newConfigurationException(TYPE, processorTag, "seed", "must be a value between 0 and 65535");
            }

            boolean ignoreMissing = readBooleanProperty(TYPE, processorTag, config, "ignore_missing", true);
            return new CommunityIdProcessor(
                processorTag,
                description,
                sourceIpField,
                sourcePortField,
                destIpField,
                destPortField,
                ianaNumberField,
                transportField,
                icmpTypeField,
                icmpCodeField,
                targetField,
                toUint16(seedInt),
                ignoreMissing
            );
        }
    }

    /**
     * Represents flow data per https://github.com/corelight/community-id-spec
     */
    public static final class Flow {

        private static final List<Transport> TRANSPORTS_WITH_PORTS = List.of(
            Transport.Tcp,
            Transport.Udp,
            Transport.Sctp,
            Transport.Icmp,
            Transport.IcmpIpV6
        );

        InetAddress source;
        InetAddress destination;
        Transport protocol;
        int sourcePort;
        int destinationPort;
        int icmpType;
        int icmpCode;

        /**
         * @return true iff the source address/port is numerically less than the destination address/port as described
         * at https://github.com/corelight/community-id-spec
         */
        boolean isOrdered() {
            int result = new BigInteger(1, source.getAddress()).compareTo(new BigInteger(1, destination.getAddress()));
            return result < 0 || (result == 0 && sourcePort < destinationPort);
        }

        byte[] toBytes() {
            boolean hasPort = TRANSPORTS_WITH_PORTS.contains(protocol);
            int len = source.getAddress().length + destination.getAddress().length + 2 + (hasPort ? 4 : 0);
            ByteBuffer bb = ByteBuffer.allocate(len);

            boolean isOneWay = false;
            if (protocol == Transport.Icmp || protocol == Transport.IcmpIpV6) {
                // ICMP protocols populate port fields with ICMP data
                Integer equivalent = IcmpType.codeEquivalent(icmpType, protocol == Transport.IcmpIpV6);
                isOneWay = equivalent == null;
                sourcePort = icmpType;
                destinationPort = equivalent == null ? icmpCode : equivalent;
            }

            boolean keepOrder = isOrdered() || ((protocol == Transport.Icmp || protocol == Transport.IcmpIpV6) && isOneWay);
            bb.put(keepOrder ? source.getAddress() : destination.getAddress());
            bb.put(keepOrder ? destination.getAddress() : source.getAddress());
            bb.put(toUint16(protocol.getTransportNumber() << 8));

            if (hasPort) {
                bb.put(keepOrder ? toUint16(sourcePort) : toUint16(destinationPort));
                bb.put(keepOrder ? toUint16(destinationPort) : toUint16(sourcePort));
            }

            return bb.array();
        }

        String toCommunityId(byte[] seed) {
            MessageDigest md = MESSAGE_DIGEST.get();
            md.reset();
            md.update(seed);
            byte[] encodedBytes = Base64.getEncoder().encode(md.digest(toBytes()));
            return "1:" + new String(encodedBytes, StandardCharsets.UTF_8);
        }
    }

    public enum Transport {
        Icmp(1),
        Igmp(2),
        Tcp(6),
        Udp(17),
        Gre(47),
        IcmpIpV6(58),
        Eigrp(88),
        Ospf(89),
        Pim(103),
        Sctp(132);

        private final int transportNumber;

        private static final Map<String, Transport> TRANSPORT_NAMES;

        static {
            TRANSPORT_NAMES = new HashMap<>();
            TRANSPORT_NAMES.put("icmp", Icmp);
            TRANSPORT_NAMES.put("igmp", Igmp);
            TRANSPORT_NAMES.put("tcp", Tcp);
            TRANSPORT_NAMES.put("udp", Udp);
            TRANSPORT_NAMES.put("gre", Gre);
            TRANSPORT_NAMES.put("ipv6-icmp", IcmpIpV6);
            TRANSPORT_NAMES.put("icmpv6", IcmpIpV6);
            TRANSPORT_NAMES.put("eigrp", Eigrp);
            TRANSPORT_NAMES.put("ospf", Ospf);
            TRANSPORT_NAMES.put("pim", Pim);
            TRANSPORT_NAMES.put("sctp", Sctp);
        }

        Transport(int transportNumber) {
            this.transportNumber = transportNumber;
        }

        public int getTransportNumber() {
            return transportNumber;
        }

        public static Transport fromNumber(int transportNumber) {
            switch (transportNumber) {
                case 1:
                    return Icmp;
                case 2:
                    return Igmp;
                case 6:
                    return Tcp;
                case 17:
                    return Udp;
                case 47:
                    return Gre;
                case 58:
                    return IcmpIpV6;
                case 88:
                    return Eigrp;
                case 89:
                    return Ospf;
                case 103:
                    return Pim;
                case 132:
                    return Sctp;
                default:
                    throw new IllegalArgumentException("unknown transport protocol number [" + transportNumber + "]");
            }
        }

        public static Transport fromObject(Object o) {
            if (o instanceof Number number) {
                return fromNumber(number.intValue());
            } else if (o instanceof String protocolStr) {
                // check if matches protocol name
                if (TRANSPORT_NAMES.containsKey(protocolStr.toLowerCase(Locale.ROOT))) {
                    return TRANSPORT_NAMES.get(protocolStr.toLowerCase(Locale.ROOT));
                }

                // check if convertible to protocol number
                try {
                    int protocolNumber = Integer.parseInt(protocolStr);
                    return fromNumber(protocolNumber);
                } catch (NumberFormatException e) {
                    // fall through to IllegalArgumentException
                }

                throw new IllegalArgumentException("could not convert string [" + protocolStr + "] to transport protocol");
            } else {
                throw new IllegalArgumentException(
                    "could not convert value of type [" + o.getClass().getName() + "] to transport protocol"
                );
            }
        }
    }

    public enum IcmpType {
        EchoReply(0),
        EchoRequest(8),
        RouterAdvertisement(9),
        RouterSolicitation(10),
        TimestampRequest(13),
        TimestampReply(14),
        InfoRequest(15),
        InfoReply(16),
        AddressMaskRequest(17),
        AddressMaskReply(18),
        V6EchoRequest(128),
        V6EchoReply(129),
        V6RouterSolicitation(133),
        V6RouterAdvertisement(134),
        V6NeighborSolicitation(135),
        V6NeighborAdvertisement(136),
        V6MLDv1MulticastListenerQueryMessage(130),
        V6MLDv1MulticastListenerReportMessage(131),
        V6WhoAreYouRequest(139),
        V6WhoAreYouReply(140),
        V6HomeAddressDiscoveryRequest(144),
        V6HomeAddressDiscoveryResponse(145);

        private static final Map<Integer, Integer> ICMP_V4_CODE_EQUIVALENTS;
        private static final Map<Integer, Integer> ICMP_V6_CODE_EQUIVALENTS;

        static {
            ICMP_V4_CODE_EQUIVALENTS = new HashMap<>();
            ICMP_V4_CODE_EQUIVALENTS.put(EchoRequest.getType(), EchoReply.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(EchoReply.getType(), EchoRequest.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(TimestampRequest.getType(), TimestampReply.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(TimestampReply.getType(), TimestampRequest.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(InfoRequest.getType(), InfoReply.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(RouterSolicitation.getType(), RouterAdvertisement.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(RouterAdvertisement.getType(), RouterSolicitation.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(AddressMaskRequest.getType(), AddressMaskReply.getType());
            ICMP_V4_CODE_EQUIVALENTS.put(AddressMaskReply.getType(), AddressMaskRequest.getType());

            ICMP_V6_CODE_EQUIVALENTS = new HashMap<>();
            ICMP_V6_CODE_EQUIVALENTS.put(V6EchoRequest.getType(), V6EchoReply.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6EchoReply.getType(), V6EchoRequest.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6RouterSolicitation.getType(), V6RouterAdvertisement.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6RouterAdvertisement.getType(), V6RouterSolicitation.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6NeighborAdvertisement.getType(), V6NeighborSolicitation.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6NeighborSolicitation.getType(), V6NeighborAdvertisement.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6MLDv1MulticastListenerQueryMessage.getType(), V6MLDv1MulticastListenerReportMessage.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6WhoAreYouRequest.getType(), V6WhoAreYouReply.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6WhoAreYouReply.getType(), V6WhoAreYouRequest.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6HomeAddressDiscoveryRequest.getType(), V6HomeAddressDiscoveryResponse.getType());
            ICMP_V6_CODE_EQUIVALENTS.put(V6HomeAddressDiscoveryResponse.getType(), V6HomeAddressDiscoveryRequest.getType());
        }

        private final int type;

        IcmpType(int type) {
            this.type = type;
        }

        public int getType() {
            return type;
        }

        public static IcmpType fromNumber(int type) {
            switch (type) {
                case 0:
                    return EchoReply;
                case 8:
                    return EchoRequest;
                case 9:
                    return RouterAdvertisement;
                case 10:
                    return RouterSolicitation;
                case 13:
                    return TimestampRequest;
                case 14:
                    return TimestampReply;
                case 15:
                    return InfoRequest;
                case 16:
                    return InfoReply;
                case 17:
                    return AddressMaskRequest;
                case 18:
                    return AddressMaskReply;
                case 128:
                    return V6EchoRequest;
                case 129:
                    return V6EchoReply;
                case 133:
                    return V6RouterSolicitation;
                case 134:
                    return V6RouterAdvertisement;
                case 135:
                    return V6NeighborSolicitation;
                case 136:
                    return V6NeighborAdvertisement;
                case 130:
                    return V6MLDv1MulticastListenerQueryMessage;
                case 131:
                    return V6MLDv1MulticastListenerReportMessage;
                case 139:
                    return V6WhoAreYouRequest;
                case 140:
                    return V6WhoAreYouReply;
                case 144:
                    return V6HomeAddressDiscoveryRequest;
                case 145:
                    return V6HomeAddressDiscoveryResponse;
                default:
                    // don't fail if the type is unknown
                    return EchoReply;
            }
        }

        public static Integer codeEquivalent(int icmpType, boolean isIpV6) {
            return isIpV6 ? ICMP_V6_CODE_EQUIVALENTS.get(icmpType) : ICMP_V4_CODE_EQUIVALENTS.get(icmpType);
        }
    }
}


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

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <bean id="poolConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop">
        <property name="maxConnections" value="8"/>
        <property name="connectionFactory" ref="jmsConnectionFactory"/>
    </bean>

    <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
            <bean class="org.apache.camel.test.infra.activemq.services.LegacyEmbeddedBroker" factory-method="createBrokerUrl"/>
        </property>
    </bean>

    <bean id="jmsTransactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
        <property name="connectionFactory" ref="poolConnectionFactory"/>
    </bean>

    <bean id="activemq" class="org.apache.camel.component.jms.JmsComponent">
        <property name="connectionFactory" ref="poolConnectionFactory"/>
        <property name="transacted" value="true"/>
        <property name="transactionManager" ref="jmsTransactionManager"/>
    </bean>

    <bean id="activemq-sender" class="org.apache.camel.component.jms.JmsComponent">
        <property name="connectionFactory" ref="poolConnectionFactory"/>
        <property name="transacted" value="true"/>
        <property name="transactionManager" ref="jmsTransactionManager"/>
    </bean>

    <bean id="myPolicy" class="org.apache.camel.throttling.ThrottlingInflightRoutePolicy">
        <property name="maxInflightExchanges" value="16"/>
        <property name="resumePercentOfMax" value="25"/>
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <jmxAgent id="agent" disabled="true"/>
        <route routePolicyRef="myPolicy">
            <from uri="activemq:queue:JMSTransactionThrottlingRoutePolicyTest?concurrentConsumers=20"/>
            <transacted/>
            <delay><constant>100</constant></delay>
            <to uri="log:foo?groupSize=10"/>
            <to uri="mock:result"/>
        </route>
    </camelContext>

</beans>


text:
Format and validate a URL attribute in Active Record. This is an example gem created for [RailsCasts episode #301](http://railscasts.com/episodes/301-extracting-a-ruby-gem).

## Installation

Add to your Gemfile and run the `bundle` command to install it.

```ruby
gem "url_formatter"
```

**Requires Ruby 1.9.2 or later.**

## Usage

Call `format_url` in an ActiveRecord class and pass the name of the attribute you wish to format into a URL and validate.

```ruby
class Comment < ActiveRecord::Base
  format_url :website
end
```

This will automatically add "http://" to the beginning of the `website` attribute upon saving if no protocol is present. It will also do validation to ensure it looks like a URL.

## Development

Questions or problems? Please post them on the [issue tracker](https://github.com/ryanb/url_formatter/issues). You can contribute changes by forking the project and submitting a pull request. You can ensure the tests passing by running `bundle` and `rake`.

This gem is created by Ryan Bates and is under the MIT License.


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>obter-a-aprovacao-de-local-para-instalacoes-de-mineracao-de-uranio-ou-torio</id>
    <dbId>2690</dbId>
    <nome>Obter a aprovação de local para instalações de mineração de Urânio ou Tório</nome>
    <sigla></sigla>
    <descricao>Consiste em receber dos requerentes a solicitação formal para aprovação de local para instalações de mineração de minério de Urânio e/ou Tório, proceder as necessárias avaliações de segurança e radioproteção, encaminhar os resultado aos níveis hierárquicos superiores da CNEN, para, se aprovado, publicação do ato administrativo no DOU.</descricao>
    <contato></contato>
    <gratuito>false</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="3261">
            <tipo>Empresas públicas ou de economia mista</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="6315">
            <titulo>Solicitar autorização</titulo>
            <descricao>Encaminhar documentação</descricao>
            <documentos>
                <default>
                    <item id="7944">Requerimento específico</item>
                    <item id="7945">GRU</item>
                </default>
            </documentos>
            <custos>
                <default>
                    <custo id="358">
                        <descricao>Taxa de licenciamento, controle e fiscalização de materiais nucleares e radioativos e suas instalações</descricao>
                        <moeda>R$</moeda>
                        <valor>24.000,00</valor>
                        <valorVariavel></valorVariavel>
                        <statusCustoVariavel>0</statusCustoVariavel>
                    </custo>
                </default>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="6376" tipo="postal">
                        <descricao>** Comissão Nacional de Energia Nuclear** - Rua Gal. Severiano, nº 90 - Botafogo - CEP: 22290-901 - Rio de Janeiro - RJ</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/223" dbId="7581">
        <nomeOrgao>Comissão Nacional de Energia Nuclear (CNEN)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="3" idServicoSegmento="6235">Empresas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Indústria</item>
        <item>Mineração</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="11836">radiação</item>
        <item id="11837">material nuclear</item>
        <item id="11838">radioatividade</item>
    </palavras-chave>
</servico>


text:
package org.apache.commons.collections4.bag;

import java.util.Comparator;

import org.apache.commons.collections4.SortedBag;

/**
 * Decorates another SortedBag to provide additional behaviour.
 *

 * Methods are forwarded directly to the decorated bag.
 *
 * @since 3.0
 * @version $Id: AbstractSortedBagDecorator.java 1477752 2013-04-30 18:21:52Z tn $
 */
public abstract class AbstractSortedBagDecorator<E>
        extends AbstractBagDecorator<E> implements SortedBag<E> {

    /** Serialization version */
    private static final long serialVersionUID = -8223473624050467718L;

    /**
     * Constructor only used in deserialization, do not use otherwise.
     * @since 3.1
     */
    protected AbstractSortedBagDecorator() {
        super();
    }

    /**
     * Constructor that wraps (not copies).
     *
     * @param bag  the bag to decorate, must not be null
     * @throws IllegalArgumentException if list is null
     */
    protected AbstractSortedBagDecorator(final SortedBag<E> bag) {
        super(bag);
    }

    /**
     * Gets the bag being decorated.
     *
     * @return the decorated bag
     */
    @Override
    protected SortedBag<E> decorated() {
        return (SortedBag<E>) super.decorated();
    }

    //-----------------------------------------------------------------------

    public E first() {
        return decorated().first();
    }

    public E last() {
        return decorated().last();
    }

    public Comparator<? super E> comparator() {
        return decorated().comparator();
    }

}


text:
package org.asteriskjava.manager.action;

/**
 * The QueueAddAction adds a new member to a queue.

 * It is implemented in apps/app_queue.c

 * The memberName property was added in Asterisk 1.4, the
 * stateInterface property in Asterisk 1.6.
 *
 * @author srt
 * @version $Id$
 */
public class QueueAddAction extends AbstractManagerAction {
    private static final long serialVersionUID = 2L;
    private String queue;
    private String iface;
    private Integer penalty;
    private Boolean paused;
    private String memberName;
    private String stateInterface;

    /**
     * Creates a new empty QueueAddAction.
     */
    public QueueAddAction() {

    }

    /**
     * Creates a new QueueAddAction that adds a new member on the given
     * interface to the given queue.
     *
     * @param queue the name of the queue the new member will be added to
     * @param iface Sets the interface to add. To add a specific channel just
     *              use the channel name, e.g. "SIP/1234".
     * @since 0.2
     */
    public QueueAddAction(String queue, String iface) {
        this.queue = queue;
        this.iface = iface;
    }

    /**
     * Creates a new QueueAddAction that adds a new member on the given
     * interface to the given queue with the given penalty.
     *
     * @param queue   the name of the queue the new member will be added to
     * @param iface   Sets the interface to add. To add a specific channel just
     *                use the channel name, e.g. "SIP/1234".
     * @param penalty the penalty for this member. The penalty must be a
     *                positive integer or 0 for no penalty. When calls are
     *                distributed members with higher penalties are considered last.
     * @since 0.2
     */
    public QueueAddAction(String queue, String iface, Integer penalty) {
        this.queue = queue;
        this.iface = iface;
        this.penalty = penalty;
    }

    /**
     * Returns the name of this action, i.e. "QueueAdd".
     */
    @Override
    public String getAction() {
        return "QueueAdd";
    }

    /**
     * Returns the name of the queue the new member will be added to.
     *
     * @return the name of the queue the new member will be added to.
     */
    public String getQueue() {
        return queue;
    }

    /**
     * Sets the name of the queue the new member will be added to.

     * This property is mandatory.
     *
     * @param queue the name of the queue the new member will be added to.
     */
    public void setQueue(String queue) {
        this.queue = queue;
    }

    /**
     * Returns the name of the channel to dial to reach this member.
     *
     * @return the name of the channel to dial to reach this member.
     */
    public String getInterface() {
        return iface;
    }

    /**
     * Sets the name of the channel (Technology/Location) to dial to reach this member.

     * This property is mandatory.
     *
     * @param iface the name of the channel to dial to reach this member, e.g. "SIP/1234".
     */
    public void setInterface(String iface) {
        this.iface = iface;
    }

    /**
     * Returns the penalty for this member.
     *
     * @return the penalty for this member.
     */
    public Integer getPenalty() {
        return penalty;
    }

    /**
     * Sets the penalty for this member.

     * The penalty must be a positive integer or 0 for no penalty. If it is
     * not set 0 is assumed.

     * When calls are distributed members with higher penalties are considered
     * last.
     *
     * @param penalty the penalty for this member.
     */
    public void setPenalty(Integer penalty) {
        this.penalty = penalty;
    }

    /**
     * Returns if the queue member should be paused when added.
     *
     * @return Boolean.TRUE if the queue member should be paused when added.
     * @since 0.2
     */
    public Boolean getPaused() {
        return paused;
    }

    /**
     * Sets if the queue member should be paused when added.
     *
     * @param paused Boolean.TRUE if the queue member should be paused when
     *               added.
     * @since 0.2
     */
    public void setPaused(Boolean paused) {
        this.paused = paused;
    }

    /**
     * Returns the name of the queue memeber (agent name).

     * Available since Asterisk 1.4
     *
     * @return the name of the queue memeber (agent name).
     * @since 1.0.0
     */
    public String getMemberName() {
        return memberName;
    }

    /**
     * Sets the name of the queue memeber (agent name).

     * Available since Asterisk 1.4
     *
     * @param memberName the name of the queue memeber (agent name).
     * @since 1.0.0
     */
    public void setMemberName(String memberName) {
        this.memberName = memberName;
    }

    /**
     * Returns the name of the channel from which to read devicestate changes.

     * Available since Asterisk 1.6
     *
     * @return the name of the channel from which to read devicestate changes.
     * @since 1.0.0
     */
    public String getStateInterface() {
        return stateInterface;
    }

    /**
     * Sets the name of the channel (Technology/Location) from which to read devicestate changes.

     * Available since Asterisk 1.6
     *
     * @param stateInterface the name of the channel from which to read devicestate changes.
     * @since 1.0.0
     */
    public void setStateInterface(String stateInterface) {
        this.stateInterface = stateInterface;
    }
}


text:
You can find all the utils and common library I use for my python Selenium script, as well as one example of test

## Requirements

The script is ready to use Saucelab of Testingbot tools, as well as define some of the variables with their respective Jenkins plugin.
In order to make it work, you need to install those clients.


text:
echo "PRODUCTION MODE"

rake assets:precompile

./solr_start.sh -p

echo "Starting server."
sudo passenger start -a 0.0.0.0 -p 80 -e production -d
echo "Server daemon started. "


text:
describe Supply do
  describe Supply::Client do
    let(:service_account_file) { File.read(fixture_file("sample-service-account.json")) }
    before do
      stub_request(:post, "https://www.googleapis.com/oauth2/v4/token").
        to_return(status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' })
      stub_request(:post, "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/test-app/edits").
        to_return(status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' })
    end

    it "displays error messages from the API" do
      stub_request(:post, "https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/test-app/edits/1/listings/en-US/icon").
        to_return(status: 403, body: '{"error":{"message":"Ensure project settings are enabled."}}', headers: { 'Content-Type' => 'application/json' })

      expect(UI).to receive(:user_error!).with("Google Api Error: Invalid request - Ensure project settings are enabled.")

      current_edit = double
      allow(current_edit).to receive(:id).and_return(1)

      client = Supply::Client.new(service_account_json: StringIO.new(service_account_file), params: { timeout: 1 })
      allow(client).to receive(:ensure_active_edit!)
      allow(client).to receive(:current_edit).and_return(current_edit)

      client.begin_edit(package_name: 'test-app')
      client.upload_image(image_path: fixture_file("playstore-icon.png"),
                          image_type: "icon",
                            language: "en-US")
    end

    describe "AndroidPublisher" do
      let(:subject) { AndroidPublisher::AndroidPublisherService.new }

      # Verify that the Google API client has all the expected methods we use.
      it "has all the expected Google API methods" do
        expect(subject.class.method_defined?(:insert_edit)).to eq(true)
        expect(subject.class.method_defined?(:delete_edit)).to eq(true)
        expect(subject.class.method_defined?(:validate_edit)).to eq(true)
        expect(subject.class.method_defined?(:commit_edit)).to eq(true)
        expect(subject.class.method_defined?(:list_edit_listings)).to eq(true)
        expect(subject.class.method_defined?(:get_edit_listing)).to eq(true)
        expect(subject.class.method_defined?(:list_edit_apks)).to eq(true)
        expect(subject.class.method_defined?(:list_edit_bundles)).to eq(true)
        expect(subject.class.method_defined?(:update_edit_listing)).to eq(true)
        expect(subject.class.method_defined?(:upload_edit_apk)).to eq(true)
        expect(subject.class.method_defined?(:upload_edit_deobfuscationfile)).to eq(true)
        expect(subject.class.method_defined?(:upload_edit_bundle)).to eq(true)
        expect(subject.class.method_defined?(:list_edit_tracks)).to eq(true)
        expect(subject.class.method_defined?(:update_edit_track)).to eq(true)
        expect(subject.class.method_defined?(:get_edit_track)).to eq(true)
        expect(subject.class.method_defined?(:update_edit_track)).to eq(true)
        expect(subject.class.method_defined?(:update_edit_expansionfile)).to eq(true)
        expect(subject.class.method_defined?(:list_edit_images)).to eq(true)
        expect(subject.class.method_defined?(:upload_edit_image)).to eq(true)
        expect(subject.class.method_defined?(:deleteall_edit_image)).to eq(true)
        expect(subject.class.method_defined?(:upload_edit_expansionfile)).to eq(true)
        expect(subject.class.method_defined?(:uploadapk_internalappsharingartifact)).to eq(true)
        expect(subject.class.method_defined?(:uploadbundle_internalappsharingartifact)).to eq(true)
      end
    end
  end
end


text:
import webbrowser

url = 'http://www.wsb.com/Assignment2/case15.php?videourl=" onerror="alert(document.cookie)'
new = 2
webbrowser.open(url, new=new)


text:
from . import basebot

from .listeners import (messagelistener, noticelistener, joinlistener,
                        partlistener, pinglistener, quitlistener, kicklistener,
                        versionlistener, nicklistener, cannotsendlistener,
                        motdlistener, modelistener)

class ChatBot(basebot.BaseBot):

    def __init__(self, server, port, master):

        super().__init__(server, port, master)

        self.name      = "TestChatBot"
        self.uName     = "tichybot"
        self.rName     = "Chat Tichy Bot"
        self.listeners =[
                        messagelistener.MessageListener(),
                        noticelistener.NoticeListener(),
                        joinlistener.JoinListener(),
                        partlistener.PartListener(),
                        quitlistener.QuitListener(),
                        kicklistener.KickListener(),
                        versionlistener.VersionListener(),
                        nicklistener.NickListener(),
                        motdlistener.MOTDListener(),
                        cannotsendlistener.CannotSendListener(),
                        modelistener.ModeListener(),
                        ]


text:
package org.apache.causeway.viewer.restfulobjects.rendering.domainobjects;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.causeway.core.metamodel.consent.Consent;
import org.apache.causeway.core.metamodel.interactions.managed.ManagedAction;
import org.apache.causeway.core.metamodel.interactions.managed.ManagedCollection;
import org.apache.causeway.core.metamodel.interactions.managed.ManagedProperty;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.core.metamodel.object.ManagedObjects;
import org.apache.causeway.core.metamodel.spec.feature.MixedIn;
import org.apache.causeway.core.metamodel.spec.feature.ObjectAction;
import org.apache.causeway.core.metamodel.spec.feature.ObjectAssociation;
import org.apache.causeway.core.metamodel.spec.feature.ObjectFeature;
import org.apache.causeway.core.metamodel.spec.feature.OneToManyAssociation;
import org.apache.causeway.core.metamodel.spec.feature.OneToOneAssociation;
import org.apache.causeway.core.metamodel.util.Facets;
import org.apache.causeway.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.causeway.viewer.restfulobjects.applib.Rel;
import org.apache.causeway.viewer.restfulobjects.applib.RepresentationType;
import org.apache.causeway.viewer.restfulobjects.applib.RestfulHttpMethod;
import org.apache.causeway.viewer.restfulobjects.rendering.IResourceContext;
import org.apache.causeway.viewer.restfulobjects.rendering.LinkBuilder;
import org.apache.causeway.viewer.restfulobjects.rendering.LinkFollowSpecs;
import org.apache.causeway.viewer.restfulobjects.rendering.ReprRendererAbstract;
import org.apache.causeway.viewer.restfulobjects.rendering.domaintypes.DomainTypeReprRenderer;
import org.apache.causeway.viewer.restfulobjects.rendering.service.valuerender.JsonValueConverter;
import org.apache.causeway.viewer.restfulobjects.rendering.service.valuerender.JsonValueEncoderService;

import lombok.val;

public class DomainObjectReprRenderer
extends ReprRendererAbstract<ManagedObject> {

    private static final String X_RO_DOMAIN_TYPE = "x-ro-domain-type";

    public static LinkBuilder newLinkToBuilder(
            final IResourceContext resourceContext,
            final Rel rel,
            final ManagedObject objectAdapter) {

        final String objectRef = ManagedObjects.stringifyElseFail(objectAdapter, "/");
        final String url = "objects/" + objectRef;
        return LinkBuilder.newBuilder(resourceContext, rel.getName(), RepresentationType.DOMAIN_OBJECT, url).withTitle(objectAdapter.getTitle());
    }

    public static LinkBuilder newLinkToObjectLayoutBuilder(
            final IResourceContext resourceContext,
            final ManagedObject objectAdapter) {

        final Rel rel = Rel.OBJECT_LAYOUT;
        final String objectRef = ManagedObjects.stringifyElseFail(objectAdapter, "/");
        final String url = "objects/" + objectRef + "/object-layout";
        return LinkBuilder.newBuilder(resourceContext, rel.getName(), RepresentationType.OBJECT_LAYOUT, url);
    }

    public static LinkBuilder newLinkToObjectIconBuilder(
            final IResourceContext resourceContext,
            final ManagedObject objectAdapter) {

        final Rel rel = Rel.OBJECT_ICON;
        final String objectRef = ManagedObjects.stringifyElseFail(objectAdapter, "/");
        final String url = "objects/" + objectRef + "/object-icon";
        return LinkBuilder.newBuilder(resourceContext, rel.getName(), RepresentationType.IMAGE, url);
    }

    private static enum Mode {
        REGULAR,
        PERSIST_LINK_ARGUMENTS,
        UPDATE_PROPERTIES_LINK_ARGUMENTS,
        EVENT_SERIALIZATION;

        public boolean isRegular() {
            return this == REGULAR;
        }

        public boolean isPersistLinkArgs() {
            return this == PERSIST_LINK_ARGUMENTS;
        }

        public boolean isUpdatePropertiesLinkArgs() {
            return this == UPDATE_PROPERTIES_LINK_ARGUMENTS;
        }

        public boolean isEventSerialization() {
            return this == EVENT_SERIALIZATION;
        }

        public boolean includeDescribedBy() {
            return isRegular() || isPersistLinkArgs();
        }

        public boolean includeUp() {
            return isRegular();
        }

        public boolean checkVisibility() {
            return isRegular() || isUpdatePropertiesLinkArgs();
        }

        public boolean isArgs() {
            return isPersistLinkArgs() || isUpdatePropertiesLinkArgs();
        }
    }

    private ObjectAdapterLinkTo linkToBuilder;
    private ManagedObject objectAdapter;
    private Mode mode = Mode.REGULAR;

    public DomainObjectReprRenderer(
            final IResourceContext resourceContext,
            final LinkFollowSpecs linkFollower,
            final JsonRepresentation representation) {
        super(resourceContext, linkFollower, RepresentationType.DOMAIN_OBJECT, representation);
        usingLinkToBuilder(new DomainObjectLinkTo());
    }

    /**
     * Override the default {@link ObjectAdapterLinkTo} (that is used for
     * generating links.
     */
    public DomainObjectReprRenderer usingLinkToBuilder(final ObjectAdapterLinkTo objectAdapterLinkToBuilder) {
        this.linkToBuilder = objectAdapterLinkToBuilder.usingUrlBase(resourceContext);
        return this;
    }

    @Override
    public DomainObjectReprRenderer with(final ManagedObject objectAdapter) {
        this.objectAdapter = objectAdapter;
        String domainTypeHref = DomainTypeReprRenderer
                .newLinkToBuilder(
                        getResourceContext(),
                        Rel.DOMAIN_TYPE,
                        objectAdapter.getSpecification())
                .build()
                .getString("href");
        addMediaTypeParams(X_RO_DOMAIN_TYPE, domainTypeHref);
        return this;
    }

    @Override
    public JsonRepresentation render() {

        if(representation == null) {
            return null;
        }

        final boolean isService = objectAdapter.getSpecification().isInjectable();

        if (!(mode.isArgs())) {

            val oidIfAny = objectAdapter.getBookmark();

            // self, extensions.oid
            if (ManagedObjects.isIdentifiable(objectAdapter)) {
                if (includesSelf) {
                    addLinkToSelf();
                }
                oidIfAny.ifPresent(oid->{
                    val oidStr = oid.stringify();
                    getExtensions().mapPutString("oid", oidStr);
                });
            }

            // title
            final String title = objectAdapter.getTitle();
            representation.mapPutString("title", title);

            // serviceId or instance Id
            if (isService) {
                representation.mapPutString("serviceId", objectAdapter.getSpecification().getLogicalTypeName());
            } else {
                oidIfAny.ifPresent(oid->{
                    Optional.ofNullable(oid.getLogicalTypeName())
                    .ifPresent(domainType->
                        representation.mapPutString("domainType", domainType));
                    representation.mapPutString("instanceId", oid.getIdentifier());
                });
            }
        }

        // members
        if(!mode.isUpdatePropertiesLinkArgs()) {
            withMembers(objectAdapter);
        }

        // described by
        if (mode.includeDescribedBy() && !resourceContext.config().isSuppressDescribedByLinks()) {
            addLinkToDescribedBy();
            addLinkToObjectLayout();
            addLinkToObjectIcon();
        }
        if(isService && mode.includeUp()) {
            addLinkToUp();
        }

        if (!mode.isArgs() && !resourceContext.config().isObjectPropertyValuesOnly()) {
            // update/persist
            addPersistLinkIfTransientAndPersistable();
            addUpdatePropertiesLinkIfRequired();

            // extensions
            getExtensions().mapPutBoolean("isService", isService);
            getExtensions().mapPutBoolean("isPersistent", ManagedObjects.isIdentifiable(objectAdapter));
            if(isService) {

                Facets.domainServiceLayoutMenuBar(objectAdapter.getSpecification())
                .ifPresent(menuBar->
                        getExtensions().mapPut("menuBar", menuBar));

            }
        }

        return representation;
    }

    private void addLinkToSelf() {
        final JsonRepresentation link = linkToBuilder.with(objectAdapter).builder(Rel.SELF).build();

        final LinkFollowSpecs linkFollower = getLinkFollowSpecs().follow("links");
        if (linkFollower.matches(link)) {
            val renderer =
                    new DomainObjectReprRenderer(getResourceContext(), linkFollower, JsonRepresentation.newMap())
                    .with(objectAdapter);
            link.mapPutJsonRepresentation("value", renderer.render());
        }

        getLinks().arrayAdd(link);
    }

    private void addLinkToDescribedBy() {
        final JsonRepresentation link = DomainTypeReprRenderer.newLinkToBuilder(getResourceContext(), Rel.DESCRIBEDBY, objectAdapter.getSpecification()).build();

        final LinkFollowSpecs linkFollower = getLinkFollowSpecs().follow("links");
        if (linkFollower.matches(link)) {
            final DomainTypeReprRenderer renderer = new DomainTypeReprRenderer(getResourceContext(), linkFollower, JsonRepresentation.newMap());
            renderer.with(objectAdapter.getSpecification());
            link.mapPutJsonRepresentation("value", renderer.render());
        }
        getLinks().arrayAdd(link);
    }

    private void addLinkToObjectLayout() {
        final LinkBuilder linkBuilder = DomainObjectReprRenderer
                .newLinkToObjectLayoutBuilder(getResourceContext(), objectAdapter);
        final JsonRepresentation link = linkBuilder.build();
        getLinks().arrayAdd(link);
    }

    private void addLinkToObjectIcon() {
        final LinkBuilder linkBuilder = DomainObjectReprRenderer
                .newLinkToObjectIconBuilder(getResourceContext(), objectAdapter);
        final JsonRepresentation link = linkBuilder.build();
        getLinks().arrayAdd(link);
    }

    private void addLinkToUp() {
        final JsonRepresentation link = LinkBuilder.newBuilder(resourceContext, Rel.UP.getName(), RepresentationType.LIST, "services").build();
        getLinks().arrayAdd(link);
    }

    private DomainObjectReprRenderer withMembers(final ManagedObject objectAdapter) {
        final JsonRepresentation appendTo =
                mode.isUpdatePropertiesLinkArgs() ? representation : JsonRepresentation.newMap();
        final List<ObjectAssociation> associations = objectAdapter.getSpecification()
                .streamAssociations(MixedIn.INCLUDED)
                .collect(Collectors.toList());

        addProperties(objectAdapter, appendTo, associations);

        if(!resourceContext.config().isObjectPropertyValuesOnly()) {
            if (!mode.isArgs() ) {
                addCollections(objectAdapter, appendTo, associations);
            }

            if (mode.isRegular()) {
                final Stream<ObjectAction> actions = objectAdapter.getSpecification()
                        .streamAnyActions(MixedIn.INCLUDED);

                addActions(objectAdapter, actions, appendTo);
            }
        }
        if(!mode.isUpdatePropertiesLinkArgs()) {
            representation.mapPutJsonRepresentation("members", appendTo);
        }
        return this;
    }

    private void addProperties(final ManagedObject objectAdapter, final JsonRepresentation members, final List<ObjectAssociation> associations) {
        for (final ObjectAssociation assoc : associations) {

            if (mode.checkVisibility()) {
                final Consent visibility = assoc.isVisible(objectAdapter, getInteractionInitiatedBy(), resourceContext.getWhere());
                if (!visibility.isAllowed()) {
                    continue;
                }
            }
            if (!(assoc instanceof OneToOneAssociation)) {
                continue;
            }

            final OneToOneAssociation property = (OneToOneAssociation) assoc;
            final LinkFollowSpecs linkFollowerForProp = getLinkFollowSpecs().follow("members[" + property.getId() + "]");
            final JsonRepresentation propertyRepresentation = JsonRepresentation.newMap();
            final ObjectPropertyReprRenderer renderer =
                    new ObjectPropertyReprRenderer(getResourceContext(), linkFollowerForProp, property.getId(), propertyRepresentation);
            renderer.with(ManagedProperty.of(objectAdapter, property, resourceContext.getWhere())).usingLinkTo(linkToBuilder);

            if (mode.isArgs()) {
                renderer.asArguments();
            }
            if(mode.isEventSerialization()) {
                renderer.asEventSerialization();
            }

            final JsonRepresentation propertyValueRepresentation = renderer.render();
            final JsonRepresentation propertyRepr = resourceContext.config().isObjectPropertyValuesOnly()
                    ? propertyValueRepresentation.getRepresentation("value")
                            : propertyValueRepresentation;
                    members.mapPutJsonRepresentation(assoc.getId(), propertyRepr);
        }
    }

    private void addCollections(final ManagedObject objectAdapter, final JsonRepresentation members, final List<ObjectAssociation> associations) {
        for (final ObjectAssociation assoc : associations) {

            if (mode.checkVisibility()) {
                final Consent visibility = assoc.isVisible(objectAdapter, getInteractionInitiatedBy(), resourceContext.getWhere());
                if (!visibility.isAllowed()) {
                    continue;
                }
            }

            if (!(assoc instanceof OneToManyAssociation)) {
                continue;
            }

            final OneToManyAssociation collection = (OneToManyAssociation) assoc;

            final LinkFollowSpecs linkFollowerForColl = getLinkFollowSpecs().follow(
                    "members[" + collection.getId() + "]");
            final JsonRepresentation collectionRepresentation = JsonRepresentation.newMap();
            final ObjectCollectionReprRenderer renderer =
                    new ObjectCollectionReprRenderer(getResourceContext(), linkFollowerForColl, collection.getId(), collectionRepresentation);

            val where = resourceContext.getWhere();

            renderer.with(ManagedCollection.of(objectAdapter, collection, where)).usingLinkTo(linkToBuilder);
            if(mode.isEventSerialization()) {
                renderer.asEventSerialization();
            }

            members.mapPutJsonRepresentation(assoc.getId(), renderer.render());
        }
    }

    private void addActions(
            final ManagedObject objectAdapter,
            final Stream<ObjectAction> actions,
            final JsonRepresentation members) {

        actions
        .filter(action->{
            final Consent visibility = action.isVisible(objectAdapter, getInteractionInitiatedBy(), resourceContext.getWhere());
            return visibility.isAllowed();
        })
        .forEach(action->{
            final LinkFollowSpecs linkFollowSpecs = getLinkFollowSpecs().follow("members["+action.getId()+"]");
            final ObjectActionReprRenderer renderer =
                    new ObjectActionReprRenderer(getResourceContext(), linkFollowSpecs, action.getId(),
                            JsonRepresentation.newMap());

            val where = resourceContext.getWhere();

            renderer.with(ManagedAction.of(objectAdapter, action, where)).usingLinkTo(linkToBuilder);
            members.mapPutJsonRepresentation(action.getId(), renderer.render());
        });

    }

    private void addPersistLinkIfTransientAndPersistable() {
        if (ManagedObjects.isIdentifiable(objectAdapter)) {
            return;
        }
        final DomainObjectReprRenderer renderer =
                new DomainObjectReprRenderer(getResourceContext(), null, JsonRepresentation.newMap());
        final JsonRepresentation domainObjectRepr = renderer.with(objectAdapter).asPersistLinkArguments().render();

        final String domainType = objectAdapter.getSpecification().getLogicalTypeName();
        final LinkBuilder persistLinkBuilder = LinkBuilder.newBuilder(getResourceContext(), Rel.PERSIST.getName(), RepresentationType.DOMAIN_OBJECT, "objects/%s", domainType).withHttpMethod(RestfulHttpMethod.POST).withArguments(domainObjectRepr);
        getLinks().arrayAdd(persistLinkBuilder.build());
    }

    private DomainObjectReprRenderer asPersistLinkArguments() {
        this.mode = Mode.PERSIST_LINK_ARGUMENTS;
        return this;
    }

    private DomainObjectReprRenderer asUpdatePropertiesLinkArguments() {
        this.mode = Mode.UPDATE_PROPERTIES_LINK_ARGUMENTS;
        return this;
    }

    // not part of the spec
    public DomainObjectReprRenderer asEventSerialization() {
        this.mode = Mode.EVENT_SERIALIZATION;
        return this;
    }

    private void addUpdatePropertiesLinkIfRequired() {
        if(mode.isEventSerialization()) {
            return;
        }
        if (!ManagedObjects.isIdentifiable(objectAdapter)) {
            return;
        }
        final boolean isService = objectAdapter.getSpecification().isInjectable();
        if(isService) {
            return;
        }

        final DomainObjectReprRenderer renderer =
                new DomainObjectReprRenderer(getResourceContext(), null, JsonRepresentation.newMap());
        final JsonRepresentation domainObjectRepr = renderer.with(objectAdapter).asUpdatePropertiesLinkArguments().render();

        if(!getResourceContext().config().isSuppressUpdateLink()) {
            val objectRef = ManagedObjects.stringifyElseFail(objectAdapter);
            val updateLinkBuilder = LinkBuilder.newBuilder(getResourceContext(), Rel.UPDATE.getName(), RepresentationType.DOMAIN_OBJECT, "objects/%s", objectRef).withHttpMethod(RestfulHttpMethod.PUT).withArguments(domainObjectRepr);
            getLinks().arrayAdd(updateLinkBuilder.build());
        }
    }

    public static Object valueOrRef(
            final IResourceContext context,
            final ObjectFeature objectFeature,
            final JsonValueEncoderService jsonValueEncoder,
            final ManagedObject domainObject) {

        val spec = domainObject.getSpecification();
        if(spec.isValue()) {
            val context2 = JsonValueConverter.Context.of(objectFeature, context.config().isSuppressMemberExtensions());
            return jsonValueEncoder.asObject(domainObject, context2);
        }

        return DomainObjectReprRenderer.newLinkToBuilder(
                context,
                Rel.VALUE,
                domainObject)
                .withTitle(domainObject.getTitle())
                .build();
    }

}


text:
@interface TDFirstViewController : UIViewController<HRColorPickerViewControllerDelegate, TDMatrixDelegate>

@end


text:
'''
Bremerton Weak Lensing Round Trip Module for CosmoSIS
ATTRIBUTION: CFHTLens
because this is a copy of the CFHTLens module with some minor modifications.

'''

import numpy as np
import os,sys
import scipy.interpolate as interpolate

n_z_bin = 1
n_theta = 5
n_z_pair = n_z_bin*(n_z_bin+1)/2
n_tot = n_z_pair*n_theta*2

dirname = os.path.split(__file__)[0]
DEFAULT_COVMAT = os.path.join(dirname,'covariance_matrix_athena.dat')
DEFAULT_DATA = os.path.join(dirname,'xibins_athena.dat')

def load_covariance(filename):

    theta1,theta2,covpp,covmm,covpm = np.loadtxt(filename,skiprows=1,unpack=True,usecols=(0,1,2,3,4))

    #print theta1.shape, covpp.shape
    #sys.exit()
    nbins = int(np.sqrt(len(theta1)))
    covmatPP = covpp.reshape((nbins,nbins))
    covmatMM = covmm.reshape((nbins,nbins))
    covmatPM = covpm.reshape((nbins,nbins))

    covmat = np.bmat([[covmatPP,             covmatPM],
                      [covmatPM.transpose(), covmatMM]])
    #print covmat.shape
    #sys.exit()
    return covmat

def load_data_vector(filename):
    thetas, xip, xim  = np.loadtxt(filename,skiprows=1,unpack=True,usecols=(0,1,2))
    data = np.loadtxt(filename).T

    xi = np.concatenate((xip,xim))

    return thetas, xi.flatten()

def theta_lims_from_bin_mids(theta):
    #Assume theta mids are equally spaced in log space, and that
    #log10(theta_mid) = 0.5 * (log10(theta_lower)+log10(theta_upper))
    #delta_log_theta is difference in log space between bin mids - this
    #will also be the difference between bin limits in log space
    delta_log_theta=np.log10(theta[1])-np.log10(theta[0])
    log10_theta_lims=np.zeros(len(theta)+1)

    for i in range(len(theta)+1):
        log10_theta_lims[i]=np.log10(theta[0])+(i-0.5)*delta_log_theta
    return 10**log10_theta_lims

class BremertonLikelihood(object):
    def __init__(self, covmat_filename, data_filename):
        theta, self.data = load_data_vector(data_filename)
        #Convert thetas from arcminutes to radians?? to match theory thetas
        self.theta = np.radians(theta/60.)
        #print 'theta bin mids',self.theta
        covmat = load_covariance(covmat_filename)
        weight = np.linalg.inv(covmat)
        # n_mu = 1656
        # if self.plus_only:
        #     if self.cut_low_theta: p=84
        #     else: p=105
        # else:
        #     if self.cut_low_theta: p=168
        #     else: p=210

        # alpha = (n_mu - p - 2.0) / (n_mu - 1.0)
        alpha = 1.
        print "Need to check the Anderson Hartlap when cutting matrix - cut first?"
        #print "xi_plus only?",self.plus_only
        #print "Cut low thetas?",self.cut_low_theta
        weight *= alpha
        self.weight = weight

    def interpolate_to_bin(self, theta, xi):
        return np.interp(self.theta, theta, xi)

    """Don't need this now! We have the correct theta values to interpolate at"""
    def integrate_theta_across_bins(self, theta_theory, xi_theory):
        #First get theta_bin_lims from thetas...(or self eventually)
        theta_bin_limits=theta_lims_from_bin_mids(self.theta)
        #Check there's the right number
        assert len(theta_bin_limits)==len(self.theta)+1
        #To get predicted xi for a bin, need to integrate xi * weight function
        #between lower and upper limit of bin (theta_lo,theta_hi)
        #i.e. xi_bin = \int_{theta_lo}^{theta_hi} W(theta) * xi(theta) /  [\int_{theta_lo}^{theta_hi} W(theta)]
        #Geometrically we expect W(theta) = theta^2 (is there some extra effect due to clustering?)
        #First interpolate theory xi - we will use this for all the integrals
        #In fact interpolate xi*theta^2 since this is what we're integrating...use scipy.interplate.splrep (cubic spline)
        integrand_interp = interpolate.splrep(theta_theory, xi_theory*theta_theory**2)
        #Normalization is just \int dtheta theta^2 = (1/3)*(theta_hi^3 - theta_lo^3)
        norms = (theta_bin_limits[1:]**3 - theta_bin_limits[:-1]**3)/3.
        xi_binned=[]
        for i in range(len(self.theta)):
            theta_lo,theta_hi=theta_bin_limits[i],theta_bin_limits[i+1]
            #Use scipy.interpolate.splint to integrate spline integral
            integrand = interpolate.splint(theta_lo,theta_hi,integrand_interp)
            xi_binned.append(integrand/norms[i])
        return np.array(xi_binned)

    def __call__(self, xi_data):

        if True:
            #xi_data is a dictionary containing all the bin pair data vectors
            xi_plus_vector = []
            xi_minus_vector = []
            #loop through the bins loading the theory data
            for i in xrange(1, n_z_bin+1):
                for j in xrange(i, n_z_bin+1):
                    #try both orderings for flexibility
                    try:
                        theta_theory, xi_theory = xi_data[(i,j)]
                    except KeyError:
                        theta_theory, xi_theory = xi_data[(j,i)]
                    theta_theory=theta_theory[:len(theta_theory)/2]
                    xi_plus_theory = xi_theory[:len(theta_theory)]
                    xi_minus_theory = xi_theory[len(theta_theory):]
                    #print xi_plus_theory,xi_minus_theory
                    #interpolate to data values - this is correct if self.theta values are mean for each binp the
                    xi_plus_binned = self.interpolate_to_bin(theta_theory, xi_plus_theory)
                    xi_minus_binned = self.interpolate_to_bin(theta_theory, xi_minus_theory)
                    '''
                    pylab.subplot(121)
                    pylab.loglog(theta_theory,xi_plus_theory)
                    pylab.loglog(self.theta,xi_plus_binned,'o')
                    pylab.subplot(122)
                    pylab.loglog(theta_theory,xi_minus_theory)
                    pylab.loglog(self.theta,xi_minus_binned,'o')
                    pylab.show()
                    '''

                    #build up longer vector of data
                    xi_plus_vector.append(xi_plus_binned)
                    xi_minus_vector.append(xi_minus_binned)

            #flatten to single vector
            xi_plus_vector = np.concatenate(xi_plus_vector)
            xi_minus_vector = np.concatenate(xi_minus_vector)
            #print 'len(xi_plus_vector)', len(xi_plus_vector)
            #concatenate xi_plus_vector and xi_minus_vector to (hopefully) match form of data vector
            xi_vector=np.concatenate((xi_plus_vector,xi_minus_vector))
            #print 'len(xi_vector)', len(xi_vector)
            assert xi_vector.shape == self.data.shape
            #get chi2 and return log like
            delta = xi_vector - self.data

            # arggh, i have to use [0,0] even though the resulting array is 1x1
            # need to make this safer

            #print delta
            #print delta.shape
            #print self.weight.shape

            b = np.dot(delta,self.weight)
            #print b.shape
            chi2 = np.dot(b,delta)
            #print chi2.shape
            chi2 = chi2[0,0]
            #print chi2
            return -chi2/2.0

# ordering is (1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (2,2) (2,3) ... (5,5), (5,6), (6,6)
'''
import pylab
covmat = load_covariance(DEFAULT_COVMAT,False,False)
theta, xi = load_data_vector(DEFAULT_DATA,False,False)
theta = theta[:len(theta)/2]
n_theta_theory=len(theta)
xi_plus,xi_minus = xi[:n_theta_theory],xi[n_theta_theory:]
sigma = covmat.diagonal()**0.5
sigma_plus,sigma_minus = sigma[:n_theta_theory],sigma[n_theta_theory:]
# print theta
# print xi[:4]
pylab.errorbar(theta, xi_plus[0:5], sigma_plus[0:5], fmt='.')
pylab.errorbar(theta, xi_minus[0:5], sigma_minus[0:5], fmt='.')
# pylab.gca().set_yscale('log',nonposy='clip')
# pylab.gca().set_xscale('log')
pylab.show()
'''


text:
var XpenseJS = XpenseJS || {};

(function(){
  'use strict';

  // shortcut for XpenseJS app variable
  var X = XpenseJS;

  // Collections hold all the collections
  X.Collections = {};

  // Collection for storing Categories
  var Categories = Backbone.Collection.extend({

    model: X.Models.Category,
    localStorage: new Backbone.LocalStorage('xpensejs-categories'),
    comparator: function( collection ){
      return( collection.get( 'title' ) );
    },

    // total amount spent monthly as an array of date and amount
    // if no category is specified, it will sum expenses from all categories
    getMonthlyExpenditure: function(start, end, category) {

      var months,
          monthlyExpenditures;

      if(!start || !end || end < start) {
        throw new Error('Invalid date');
      }

      months = start.monthsInBetween(end);
      monthlyExpenditures = _.map(months, function(m){
        var expense = {
          date: m
        };
        expense.amount = X.Collections.Expenses.getTotal(
          m,
          new Date(m.getFullYear(), m.getMonth(), m.daysInMonth()),
          category
        );
        return expense;
      });

      return monthlyExpenditures;

    }

  });

  // Collection for storing Expenses
  var Expenses = Backbone.Collection.extend({

    model: X.Models.Expense,
    localStorage: new Backbone.LocalStorage('xpensejs-expenses'),
    comparator: function( collection ){
      return - ( new Date(collection.get('date')).getTime() );
    },

    // filters expenses by date
    // if arguments are not present, it returns expenses for
    // current month
    filterByDate: function(start, end) {

      var currentDate = new Date;
      if(!start) {
        start = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
      }
      if(!end || end < start) {
        end = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.daysInMonth());
      }

      return this.filter(function(expense){
        var expenseDate = new Date (expense.get('date'));
        if(expenseDate >= start && expenseDate <= end) {
          return true;
        }
      });

    },

    // filters expenses by category
    // same date rule of filterByDate applies here as it users
    // filterByDate internally
    filterByCategory: function(category, start, end) {
      return this.filterByDate(start, end).filter(function(expense){
        return expense.get('category') === category ? true : false;
      });
    },

    // filters expenses by amount greater than amount argument provided
    // same date rule as filterByDate
    amountGt: function(amount, start, end, category) {
      if(!amount) {
        amount = 0;
      }

      if(!category) {
        return this.filterByDate(start, end).filter(function(expense){
          return expense.get('amount') >= amount ? true : false;
        });
      } else {
        return this.filterByCategory(category, start, end).filter(function(expense){
          return expense.get('amount') >= amount ? true : false;
        });
      }

    },

    // filters expenses by amount lesser than amount argument provided
    // same date rule as filterByDate
    amountLt: function(amount, start, end, category) {
      if(!amount) {
        amount = 0;
      }

      if(!category) {
        return this.filterByDate(start, end).filter(function(expense){
          return expense.get('amount') <= amount ? true : false;
        });
      } else {
        return this.filterByCategory(category, start, end).filter(function(expense){
          return expense.get('amount') <= amount ? true : false;
        });
      }

    },

    // returns all satisfied expenses
    // same date rule as filterByDate
    getSatisfied: function(start, end, category) {
      if(!category) {
        return this.filterByDate(start, end).filter(function(expense){
          return expense.get('satisfied');
        });
      } else {
        return this.filterByCategory(category, start, end).filter(function(expense){
          return expense.get('satisfied');
        });
      }
    },

    // returns all dissatisfied expenses
    // same date rule as filterByDate
    getDissatisfied: function(start, end, category) {
      if(!category) {
        return this.filterByDate(start, end).filter(function(expense){
          return !expense.get('satisfied');
        });
      } else {
        return this.filterByCategory(category, start, end).filter(function(expense){
          return !expense.get('satisfied');
        });
      }
    },

    // returns total amount spent in a month
    // same date rule as filterByDate
    getTotal: function(start, end, category) {
      if(!category) {
        return this.filterByDate(start, end).reduce(function(sum, expense){
          return sum + expense.get('amount');
        }, 0);
      } else {
        return this.filterByCategory(category, start, end).reduce(function(sum, expense){
          return sum + expense.get('amount');
        }, 0);
      }
    }

  });

  // Collection for storing Targets
  var Targets = Backbone.Collection.extend({

    model: X.Models.Target,
    localStorage: new Backbone.LocalStorage('xpensejs-targets')

  });

  // create all collections and store it on Collections
  // object in XpenseJS app variable
  X.Collections.Categories = new Categories;
  X.Collections.Expenses = new Expenses;
  X.Collections.Targets = new Targets;

})();