text:
describe Halogen::Embeds::Definition do
  describe '#validate' do
    it 'returns true with procedure' do
      result = Halogen::Embeds::Definition.new(:name, {}, proc {}).validate

      expect(result).to eq(true)
    end

    it 'raises exception without procedure' do
      expect {
        Halogen::Embeds::Definition.new(:name, {}, nil).validate
      }.to raise_error do |exception|
        expect(exception).to be_an_instance_of(Halogen::InvalidDefinition)
        expect(exception.message).to(
          eq('Embed name must be defined with a proc'))
      end
    end
  end

  describe '#enabled?' do
    let :definition do
      Halogen::Embeds::Definition.new(:name, {}, proc {})
    end

    it 'is true if instance rules return true' do
      repr = double(:repr, embed?: true)

      expect(definition.enabled?(repr)).to eq(true)
    end

    it 'is false if instance rules return false' do
      repr = double(:repr, embed?: false)

      expect(definition.enabled?(repr)).to eq(false)
    end
  end

  describe '#embed_via_options?' do
    let :klass do
      Class.new { include Halogen }
    end

    it 'is true for expected values' do
      [1, 2, true, '1', '2', 'true', 'yes'].each do |value|
        repr = klass.new(embed: { foo: value })

        definition = Halogen::Embeds::Definition.new(:foo, {}, proc {})

        expect(definition.send(:embed_via_options?, repr)).to eq(true)
      end
    end

    it 'is false for expected values' do
      [0, false, '0', 'false'].each do |value|
        repr = klass.new(embed: { foo: value })

        definition = Halogen::Embeds::Definition.new(:foo, {}, proc {})

        expect(definition.send(:embed_via_options?, repr)).to eq(false)
      end
    end
  end
end


text:
<?php

class WP_JSON_Taxonomies {
	/**
	 * Register the taxonomy-related routes
	 *
	 * @param array $routes Existing routes
	 * @return array Modified routes
	 */
	public function register_routes( $routes ) {
		$tax_routes = array(
			'/posts/types/(?P<type>\w+)/taxonomies' => array(
				array( array( $this, 'get_taxonomies_for_type' ), WP_JSON_Server::READABLE | WP_JSON_Server::HIDDEN_ENDPOINT ),
			),
			'/posts/types/(?P<type>\w+)/taxonomies/(?P<taxonomy>\w+)' => array(
				array( array( $this, 'get_taxonomy' ),   WP_JSON_Server::READABLE | WP_JSON_Server::HIDDEN_ENDPOINT ),
			),
			'/posts/types/(?P<type>\w+)/taxonomies/(?P<taxonomy>\w+)/terms' => array(
				array( array( $this, 'get_terms' ),      WP_JSON_Server::READABLE | WP_JSON_Server::HIDDEN_ENDPOINT ),
			),
			'/posts/types/(?P<type>\w+)/taxonomies/(?P<taxonomy>\w+)/terms/(?P<term>\w+)' => array(
				array( array( $this, 'get_term' ),       WP_JSON_Server::READABLE | WP_JSON_Server::HIDDEN_ENDPOINT ),
			),
			'/taxonomies' => array(
				array( array( $this, 'get_taxonomies' ), WP_JSON_Server::READABLE ),
			),
			'/taxonomies/(?P<taxonomy>\w+)' => array(
				array( array( $this, 'get_taxonomy_object' ), WP_JSON_Server::READABLE ),
			),
			'/taxonomies/(?P<taxonomy>\w+)/terms' => array(
				array( array( $this, 'get_taxonomy_terms' ), WP_JSON_Server::READABLE ),
			),
			'/taxonomies/(?P<taxonomy>\w+)/terms/(?P<term>\w+)' => array(
				array( array( $this, 'get_taxonomy_term' ), WP_JSON_Server::READABLE ),
			),
		);

		return array_merge( $routes, $tax_routes );
	}

	/**
	 * Get taxonomies for a post type
	 * @param string $type Post type
	 * @param string $context Context (view|embed)
	 * @return array Taxonomy data
	 */
	public function get_taxonomies_for_type( $type, $context = 'view' ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::get_taxonomies( $type )' );

		return $this->get_taxonomies( $type, $context );
	}

	/**
	 * Get taxonomies
	 *
	 * @param string|null $type A specific post type for which to retrieve taxonomies (optional)
	 * @return array Taxonomy data
	 */
	public function get_taxonomies( $type = null, $context = 'view' ) {
		if ( null === $type ) {
			$taxonomies = get_taxonomies( '', 'objects' );
		} else {
			$taxonomies = get_object_taxonomies( $type, 'objects' );
		}

		$data = array();

		foreach ( $taxonomies as $tax_type => $value ) {
			$tax = $this->prepare_taxonomy_object( $value, $context );
			if ( is_wp_error( $tax ) ) {
				continue;
			}

			$data[] = $tax;
		}

		return $data;
	}

	/**
	 * Get taxonomies (legacy route with support for passing $type)
	 *
	 * @deprecated
	 * @see get_taxonomy_object
	 *
	 * @param string $type Post type to get taxonomies for (deprecated)
	 * @param string $taxonomy Taxonomy slug
	 * @return array Taxonomy data
	 */
	public function get_taxonomy( $type, $taxonomy ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::get_taxonomy_object' );

		return $this->get_taxonomy_object( $taxonomy );
	}

	/**
	 * Get taxonomies
	 *
	 * @param string $taxonomy Taxonomy slug
	 * @return array Taxonomy data
	 */
	public function get_taxonomy_object( $taxonomy ) {
		$tax = get_taxonomy( $taxonomy );

		if ( empty( $tax ) ) {
			return new WP_Error( 'json_taxonomy_invalid_id', __( 'Invalid taxonomy ID.' ), array( 'status' => 404 ) );
		}

		return $this->prepare_taxonomy_object( $tax );
	}

	/**
	 * Prepare a taxonomy for serialization
	 *
	 * @deprecated
	 * @see prepare_taxonomy_object
	 *
	 * @param stdClass $taxonomy Taxonomy data
	 * @param string|null $type Post type to get taxonomies for (deprecated)
	 * @param string $context Context (view|embed). True/false are allowed for backwards compatibility, and map to embed/view respectively.
	 * @return array Taxonomy data
	 */
	protected function prepare_taxonomy( $taxonomy, $type = null, $context = 'view' ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::prepare_taxonomy_object' );

		return $this->prepare_taxonomy_object( $taxonomy, $context );
	}

	/**
	 * Prepare a taxonomy object for serialization
	 *
	 * @param stdClass $taxonomy Taxonomy data
	 * @param string $context Context (view|embed). True/false are allowed for backwards compatibility, and map to embed/view respectively.
	 * @return array Taxonomy data
	 */
	protected function prepare_taxonomy_object( $taxonomy, $context = 'view' ) {
		if ( $taxonomy->public === false ) {
			return new WP_Error( 'json_cannot_read_taxonomy', __( 'Cannot view taxonomy' ), array( 'status' => 403 ) );
		}

		// Backwards compatibility with _in_collection parameter
		if ( $context === true ) {
			$context = 'embed';
			_deprecated_argument( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', '$context should be set to "embed" rather than true' );
		}
		elseif ( $context === false ) {
			$context = 'view';
			_deprecated_argument( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', '$context should be set to "view" rather than false' );
		}

		$base_url = '/taxonomies/' . $taxonomy->name;

		$data = array(
			'name'         => $taxonomy->label,
			'slug'         => $taxonomy->name,
			'labels'       => $taxonomy->labels,
			'types'        => $taxonomy->object_type,
			'show_cloud'   => $taxonomy->show_tagcloud,
			'hierarchical' => $taxonomy->hierarchical,
			'meta'         => array(
				'links' => array(
					'archives' => json_url( $base_url . '/terms' ),
					'collection' => json_url( '/taxonomies' ),
					'self' => json_url( $base_url )
				)
			),
		);

		return apply_filters( 'json_prepare_taxonomy', $data, $taxonomy, $context );
	}

	/**
	 * Add taxonomy data to post type data
	 *
	 * @param array $data Type data
	 * @param array $post Internal type data
	 * @param boolean $_in_taxonomy The record being filtered is a taxonomy object (internal use)
	 * @return array Filtered data
	 */
	public function add_taxonomy_data( $data, $type, $context = 'view' ) {
		if ( $context !== 'embed' ) {
			$data['taxonomies'] = $this->get_taxonomies( $type->name, 'embed' );
		}

		return $data;
	}

	/**
	 * Get terms for a post type (legacy route with support for passing $type)
	 *
	 * @deprecated
	 * @see get_taxonomy_terms
	 *
	 * @param string $type Post type for which to fetch taxonomies (deprecated)
	 * @param string $taxonomy Taxonomy slug
	 * @return array Term collection
	 */
	public function get_terms( $type, $taxonomy ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::get_taxonomy_terms' );

		return $this->get_taxonomy_terms( $taxonomy );
	}

	/**
	 * Get all terms for a post type
	 *
	 * @param string $taxonomy Taxonomy slug
	 * @return array Term collection
	 */
	public function get_taxonomy_terms( $taxonomy ) {
		if ( ! taxonomy_exists( $taxonomy ) ) {
			return new WP_Error( 'json_taxonomy_invalid_id', __( 'Invalid taxonomy ID.' ), array( 'status' => 404 ) );
		}

		$args = array(
			'hide_empty' => false,
		);

		$terms = get_terms( $taxonomy, $args );

		if ( is_wp_error( $terms ) ) {
			return $terms;
		}

		$data = array();
		foreach ( $terms as $term ) {
			$data[] = $this->prepare_taxonomy_term( $term );
		}

		return $data;
	}

	/**
	 * Get term for a post type
	 *
	 * @deprecated
	 * @see get_taxonomy_term
	 *
	 * @param string $type Post type (deprecated)
	 * @param string $taxonomy Taxonomy slug
	 * @param string $term Term slug
	 * @param string $context Context (view/view-parent)
	 * @return array Term entity
	 */
	public function get_term( $type, $taxonomy, $term, $context = 'view' ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::get_taxonomy_term( $taxonomy, $term )' );

		return $this->get_taxonomy_term( $taxonomy, $term, $context );
	}

	/**
	 * Get term for a post type
	 *
	 * @param string $taxonomy Taxonomy slug
	 * @param string $term Term slug
	 * @param string $context Context (view/view-parent)
	 * @return array Term entity
	 */
	public function get_taxonomy_term( $taxonomy, $term, $context = 'view' ) {
		if ( ! taxonomy_exists( $taxonomy ) ) {
			return new WP_Error( 'json_taxonomy_invalid_id', __( 'Invalid taxonomy ID.' ), array( 'status' => 404 ) );
		}

		$data = get_term( $term, $taxonomy );

		if ( empty( $data ) ) {
			return new WP_Error( 'json_taxonomy_invalid_term', __( 'Invalid term ID.' ), array( 'status' => 404 ) );
		}

		return $this->prepare_taxonomy_term( $data, $context );
	}

	/**
	 * Add term data to post data
	 *
	 * @param array $data Post data
	 * @param array $post Internal post data
	 * @param string $context Post context
	 * @return array Filtered data
	 */
	public function add_term_data( $data, $post, $context ) {
		$post_type_taxonomies = get_object_taxonomies( $post['post_type'] );
		$terms = wp_get_object_terms( $post['ID'], $post_type_taxonomies );
		$data['terms'] = array();

		foreach ( $terms as $term ) {
			$data['terms'][ $term->taxonomy ][] = $this->prepare_taxonomy_term( $term );
		}

		return $data;
	}

	/**
	 * Prepare term data for serialization
	 *
	 * @deprecated
	 * @see prepare_taxonomy_term
	 *
	 * @param array|object $term The unprepared term data
	 * @param string|null $type Post type to get taxonomies for (deprecated)
	 * @return array The prepared term data
	 */
	protected function prepare_term( $term, $type = null, $context = 'view' ) {
		_deprecated_function( __CLASS__ . '::' . __FUNCTION__, 'WPAPI-1.1', __CLASS__ . '::prepare_taxonomy_term( $term )' );

		return $this->prepare_taxonomy_term( $term, $context );
	}

	/**
	 * Prepare term data for serialization
	 *
	 * @param array|object $term The unprepared term data
	 * @return array The prepared term data
	 */
	protected function prepare_taxonomy_term( $term, $context = 'view' ) {
		$base_url = '/taxonomies/' . $term->taxonomy . '/terms';

		$data = array(
			'ID'          => (int) $term->term_taxonomy_id,
			'name'        => $term->name,
			'slug'        => $term->slug,
			'description' => $term->description,
			'parent'      => (int) $term->parent,
			'count'       => (int) $term->count,
			'link'        => get_term_link( $term, $term->taxonomy ),
			'meta'        => array(
				'links' => array(
					'collection' => json_url( $base_url ),
					'self'       => json_url( $base_url . '/' . $term->term_id ),
				),
			),
		);

		if ( ! empty( $data['parent'] ) && $context === 'view' ) {
			$data['parent'] = $this->get_taxonomy_term( $term->taxonomy, $data['parent'], 'view-parent' );
		} elseif ( empty( $data['parent'] ) ) {
			$data['parent'] = null;
		}

		return apply_filters( 'json_prepare_term', $data, $term );
	}
}

redpajama_set_name: RedPajamaGithub


text:
const VOID_ELEMENTS = [
	'area',
	'base',
	'br',
	'col',
	'embed',
	'hr',
	'img',
	'input',
	'keygen',
	'link',
	'menuitem',
	'meta',
	'param',
	'source',
	'track',
	'wbr',
]

const NO_WHITESPACE = [
	'table',
	'tbody',
	'tfoot',
	'thead',
	'tr',
]

export default VOID_ELEMENTS

export function canHaveChildren(tagName: string): boolean {
	return VOID_ELEMENTS.indexOf(tagName.toLowerCase()) === -1
}
export function canHaveWhitespace(tagName: string): boolean {
	return NO_WHITESPACE.indexOf(tagName.toLowerCase()) !== -1
}


text:
<?php

namespace WeinBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HerkunftslandType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('wein')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'WeinBundle\Entity\Herkunftsland'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'weinbundle_herkunftsland';
    }
}


text:
<?php

final class ManiphestTaskSubtaskController
  extends ManiphestController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $this->getViewer();
    $id = $request->getURIData('id');

    $task = id(new ManiphestTaskQuery())
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->executeOne();
    if (!$task) {
      return new Aphront404Response();
    }

    $cancel_uri = $task->getURI();

    $edit_engine = id(new ManiphestEditEngine())
      ->setViewer($viewer)
      ->setTargetObject($task);

    $subtype_map = $task->newEditEngineSubtypeMap();

    $subtype_options = $subtype_map->getCreateFormsForSubtype(
      $edit_engine,
      $task);

    if (!$subtype_options) {
      return $this->newDialog()
        ->setTitle(pht('No Forms'))
        ->appendParagraph(
          pht(
            'You do not have access to any forms which can be used to '.
            'create a subtask.'))
        ->addCancelButton($cancel_uri, pht('Close'));
    }

    $menu = id(new PHUIObjectItemListView())
      ->setUser($viewer)
      ->setBig(true)
      ->setFlush(true);

    foreach ($subtype_options as $form_key => $subtype_form) {
      $subtype_key = $subtype_form->getSubtype();
      $subtype = $subtype_map->getSubtype($subtype_key);

      $subtask_uri = id(new PhutilURI("/task/edit/form/{$form_key}/"))
        ->replaceQueryParam('parent', $id)
        ->replaceQueryParam('template', $id)
        ->replaceQueryParam('status', ManiphestTaskStatus::getDefaultStatus());
      $subtask_uri = $this->getApplicationURI($subtask_uri);

      $item = id(new PHUIObjectItemView())
        ->setHeader($subtype_form->getDisplayName())
        ->setHref($subtask_uri)
        ->setClickable(true)
        ->setImageIcon($subtype->newIconView())
        ->addAttribute($subtype->getName());

      $menu->addItem($item);
    }

    return $this->newDialog()
      ->setTitle(pht('Choose Subtype'))
      ->appendChild($menu)
      ->addCancelButton($cancel_uri);
  }

}


text:
typedef struct Node {
  int val;
  struct Node* prev;
  struct Node* next;
} Node;

//represents a dll
typedef struct DLL {
  struct Node* head;
  struct Node* tail;
} DLL;

DLL* create(int n);
Node* create_node(int n);
void push(DLL* list, int n);
void append(DLL* list, int n);
int size(DLL* list);
int pop(DLL* list);
int shift(DLL* list);
void delete(DLL* list, int n);


text:
#pragma once

#ifdef _WIN32
#include <GL/glut.h>
#include <Windows.h>
#elif __linux__
#include <GL/glut.h>
#else
#include <GLUT/glut.h>
#endif
/**
  * Base Engine for the framework. Handles windowing and freeglut/OpenGL contexts.
  * Engine is static.
  */
class Engine
{
public:
	/**
	* Constructor takes in command line arguments, a title and initial window dimensions.
	*/
	Engine(int argc, char** argv, const char *title, const int& windowWidth, const int& windowHeight);
	virtual ~Engine(){};
	/**
	 * Initial startup method. Sets up GL context and windowing functions to handle drawing, timing and input.
	 */
	virtual void Run();
	/**
	 * Returns self.
	 */
	static Engine* GetCurrentInstance();
	/** Returns window title */
	static const char* GetWindowTitle();
	/** Returns window id */
	static int GetWindowID();
	/** Returns window width */
	static int GetWindowWidth();
	/** Returns window height */
	static int GetWindowHeight();

protected:
	/** pointer to current window context */
	static Engine *current;

	static const char* windowTitle;
	static int windowID;
	static int windowWidth;
	static int windowHeight;
	static int time;

	/** Sets up default initial functionality for window */
	static void InitFunc();
	/** Calls {@link Draw} and handles double buffering */
	static void DrawFunc();
	/** Checks runtime between successive calls and runs {@link Update} before pushing redisplay */
	static void IdleFunc();
	/** Handles window resize */
	static void ResizeFunc(int _width, int _height);
	/** Handles key press */
	static void KeyDownFunc(unsigned char key, int x, int y);
	/** Handles key release */
	static void KeyUpFunc(unsigned char key, int x, int y);
	/** Handles special key press */
	static void SpecialKeyDownFunc(int key, int x, int y);
	/** Handles special key release */
	static void SpecialKeyUpFunc(int key, int x, int y);
	/** Handles mouse button click */
	static void MouseFunc(int button, int state, int x, int y);
	/** Handles mouse click and drag (active motion) */
	static void MouseMotionFunc(int x, int y);
	/** Handles mouse movement (passive motion) */
	static void PassiveMouseMotionFunc(int x, int y);

	// Pure virtual functions handled overloaded by Scene
	virtual void Initialise() = 0;
	virtual void Draw() = 0;
	virtual void Reshape(int w, int h) = 0;
	virtual void Update(const double&) = 0;
	virtual void HandleKey(unsigned char key, int state, int x, int y) = 0;
	virtual void HandleSpecialKey(int key, int state, int x, int y) = 0;
	virtual void HandleMouse(int button, int state, int x, int y) = 0;
	virtual void HandleMouseDrag(int x, int y) = 0;
	virtual void HandleMouseMove(int x, int y) = 0;

	/**
	 * Iterates through OpenGL error list and dumps error information to console.
	 * <p>
	 * Call this method in a draw loop.
	 */
	static int CheckGLError();
};


text:
package edu.utah.further.core.util.spring;

/**
 * Example of a spring service interface.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, AVP Health Sciences IT Office, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne <oren.livne@utah.edu>
 * @version Feb 13, 2009
 */
public interface HelloService
{
	/**
	 * Return a reply to a message.
	 *
	 * @param message
	 *            input message
	 * @return reply message
	 */
	String sayHi(String message);
}


text:
package com.pi4j.io.gpio.trigger.test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.test.MockGpioFactory;
import com.pi4j.io.gpio.test.MockGpioProvider;
import com.pi4j.io.gpio.test.MockPin;
import com.pi4j.io.gpio.trigger.GpioPulseStateTrigger;

public class GpioPulseStateTriggerTests {

    private static MockGpioProvider provider;
    private static GpioController gpio;
    private static GpioPinDigitalInput inputPin;
    private static GpioPinDigitalOutput outputPin;
    private static GpioPulseStateTrigger trigger;

    @BeforeClass
    public static void setup() {
        // create a mock gpio provider and controller
        provider = MockGpioFactory.getMockProvider();
        gpio = MockGpioFactory.getInstance();

        // provision pins for testing
        inputPin = gpio.provisionDigitalInputPin(MockPin.DIGITAL_INPUT_PIN,  "digitalInputPin");
        outputPin = gpio.provisionDigitalOutputPin(MockPin.DIGITAL_OUTPUT_PIN,  "digitalOutputPin");

        // create trigger
        trigger = new GpioPulseStateTrigger(outputPin, 200);

        // add trigger to input pin
        inputPin.addTrigger(trigger);
    }

    @AfterClass
    public static void teardown() {
        // remove trigger
        inputPin.removeTrigger(trigger);
    }

    @Test
    public void testHasTrigger() {
        // verify that the input pin does have a trigger assigned
        assertFalse(inputPin.getTriggers().isEmpty());
    }

    @Test
    public void testTrigger() throws InterruptedException {
        provider.setMockState(MockPin.DIGITAL_INPUT_PIN, PinState.LOW);
        provider.setMockState(MockPin.DIGITAL_INPUT_PIN, PinState.HIGH);

        // wait before continuing test
        Thread.sleep(50);

        // verify that the output pin states is now high
        assertEquals(PinState.HIGH, outputPin.getState());

        // wait before continuing test
        Thread.sleep(200);

        // verify that the output pin states is now low
        assertEquals(PinState.LOW, outputPin.getState());
    }
}


text:
{% extends "zerver/emails/compiled/email_base_default.html" %}

{% block illustration %}

{% endblock %}

{% block content %}

{% trans %}Dear former administrators of {{ realm_name }},{% endtrans %}

{% trans %}One of your administrators requested reactivation of the previously deactivated Zulip organization hosted at {{ realm_uri }}.{% endtrans %}

    {{ _('Click the button below to reactivate your organization.') }}
    {{ _('Reactivate organization') }}

{% trans %}If the request was in error, you can take no action and this link will expire in 24 hours.{% endtrans %}

{% trans %}Contact us any time at {{ support_email }} if you run into trouble, have any feedback, or just want to chat!{% endtrans %}

{% endblock %}


text:
![demo](http://blog.dfilimonov.com/assets/images/cat-demo.gif)

Check out [this blog post](http://blog.dfilimonov.com/2013/09/12/devtools-terminal.html) for more info


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

#include "third_party/blink/renderer/modules/webcodecs/audio_encoder.h"

#include <cinttypes>
#include <limits>

#include "base/metrics/histogram_functions.h"
#include "base/numerics/safe_conversions.h"
#include "base/trace_event/common/trace_event_common.h"
#include "base/trace_event/trace_event.h"
#include "media/audio/audio_opus_encoder.h"
#include "media/base/audio_parameters.h"
#include "media/base/limits.h"
#include "media/base/mime_util.h"
#include "media/base/offloading_audio_encoder.h"
#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_traits.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_typedefs.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_data_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_decoder_config.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_encoder_config.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_encoder_support.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_encoded_audio_chunk_metadata.h"
#include "third_party/blink/renderer/modules/webaudio/audio_buffer.h"
#include "third_party/blink/renderer/modules/webcodecs/allow_shared_buffer_source_util.h"
#include "third_party/blink/renderer/modules/webcodecs/encoded_audio_chunk.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"

namespace blink {

namespace {

constexpr const char kCategory[] = "media";

AudioEncoderTraits::ParsedConfig* ParseConfigStatic(
    const AudioEncoderConfig* config,
    ExceptionState& exception_state) {
  if (!config) {
    exception_state.ThrowTypeError("No config provided");
    return nullptr;
  }
  auto* result = MakeGarbageCollected<AudioEncoderTraits::ParsedConfig>();

  result->codec = media::AudioCodec::kUnknown;
  bool is_codec_ambiguous = true;
  bool parse_succeeded = ParseAudioCodecString(
      "", config->codec().Utf8(), &is_codec_ambiguous, &result->codec);

  if (!parse_succeeded || is_codec_ambiguous) {
    exception_state.ThrowTypeError("Unknown codec.");
    return nullptr;
  }

  result->options.channels = config->numberOfChannels();
  if (result->options.channels < 1 ||
      result->options.channels > media::limits::kMaxChannels) {
    exception_state.ThrowTypeError(String::Format(
        "Invalid channel number; expected range from %d to %d, received %d.", 1,
        media::limits::kMaxChannels, result->options.channels));
    return nullptr;
  }

  result->options.sample_rate = config->sampleRate();
  if (result->options.sample_rate < media::limits::kMinSampleRate ||
      result->options.sample_rate > media::limits::kMaxSampleRate) {
    exception_state.ThrowTypeError(String::Format(
        "Invalid sample rate; expected range from %d to %d, received %d.",
        media::limits::kMinSampleRate, media::limits::kMaxSampleRate,
        result->options.sample_rate));
    return nullptr;
  }

  result->codec_string = config->codec();
  if (config->hasBitrate()) {
    if (config->bitrate() > std::numeric_limits<int>::max()) {
      exception_state.ThrowTypeError(String::Format(
          "Bitrate is too large; expected at most %d, received %" PRIu64,
          std::numeric_limits<int>::max(), config->bitrate()));
      return nullptr;
    }
    result->options.bitrate = static_cast<int>(config->bitrate());
  }

  return result;
}

bool VerifyCodecSupportStatic(AudioEncoderTraits::ParsedConfig* config,
                              ExceptionState* exception_state) {
  switch (config->codec) {
    case media::AudioCodec::kOpus: {
      if (config->options.channels > 2) {
        // Our Opus implementation only supports up to 2 channels
        if (exception_state) {
          exception_state->ThrowDOMException(
              DOMExceptionCode::kNotSupportedError,
              String::Format("Too many channels for Opus encoder; "
                             "expected at most 2, received %d.",
                             config->options.channels));
        }
        return false;
      }
      if (config->options.bitrate.has_value() &&
          config->options.bitrate.value() <
              media::AudioOpusEncoder::kMinBitrate) {
        if (exception_state) {
          exception_state->ThrowDOMException(
              DOMExceptionCode::kNotSupportedError,
              String::Format(
                  "Opus bitrate is too low; expected at least %d, received %d.",
                  media::AudioOpusEncoder::kMinBitrate,
                  config->options.bitrate.value()));
        }
        return false;
      }
      return true;
    }
    default:
      if (exception_state) {
        exception_state->ThrowDOMException(DOMExceptionCode::kNotSupportedError,
                                           "Unsupported codec type.");
      }
      return false;
  }
}

AudioEncoderConfig* CopyConfig(const AudioEncoderConfig& config) {
  auto* result = AudioEncoderConfig::Create();
  result->setCodec(config.codec());
  result->setSampleRate(config.sampleRate());
  result->setNumberOfChannels(config.numberOfChannels());
  if (config.hasBitrate())
    result->setBitrate(config.bitrate());
  return result;
}

}  // namespace

// static
const char* AudioEncoderTraits::GetNameForDevTools() {
  return "AudioEncoder(WebCodecs)";
}

// static
const char* AudioEncoderTraits::GetName() {
  return "AudioEncoder";
}

AudioEncoder* AudioEncoder::Create(ScriptState* script_state,
                                   const AudioEncoderInit* init,
                                   ExceptionState& exception_state) {
  auto* result =
      MakeGarbageCollected<AudioEncoder>(script_state, init, exception_state);
  return exception_state.HadException() ? nullptr : result;
}

AudioEncoder::AudioEncoder(ScriptState* script_state,
                           const AudioEncoderInit* init,
                           ExceptionState& exception_state)
    : Base(script_state, init, exception_state) {
  UseCounter::Count(ExecutionContext::From(script_state),
                    WebFeature::kWebCodecs);
}

AudioEncoder::~AudioEncoder() = default;

void AudioEncoder::ProcessConfigure(Request* request) {
  DCHECK_NE(state_.AsEnum(), V8CodecState::Enum::kClosed);
  DCHECK_EQ(request->type, Request::Type::kConfigure);
  DCHECK(active_config_);
  DCHECK_EQ(active_config_->codec, media::AudioCodec::kOpus);
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  request->StartTracing();

  auto software_encoder = std::make_unique<media::AudioOpusEncoder>();
  media_encoder_ = std::make_unique<media::OffloadingAudioEncoder>(
      std::move(software_encoder));

  auto output_cb = ConvertToBaseRepeatingCallback(CrossThreadBindRepeating(
      &AudioEncoder::CallOutputCallback, WrapCrossThreadWeakPersistent(this),
      // We can't use |active_config_| from |this| because it can change by
      // the time the callback is executed.
      WrapCrossThreadPersistent(active_config_.Get()), reset_count_));

  auto done_callback = [](AudioEncoder* self, media::AudioCodec codec,
                          Request* req, media::Status status) {
    if (!self || self->reset_count_ != req->reset_count) {
      req->EndTracing(/*aborted=*/true);
      return;
    }
    DCHECK_CALLED_ON_VALID_SEQUENCE(self->sequence_checker_);
    if (!status.is_ok()) {
      self->HandleError(
          self->logger_->MakeException("Encoding error.", status));
    } else {
      base::UmaHistogramEnumeration("Blink.WebCodecs.AudioEncoder.Codec",
                                    codec);
    }

    req->EndTracing();
    self->blocking_request_in_progress_ = false;
    self->ProcessRequests();
  };

  blocking_request_in_progress_ = true;
  first_output_after_configure_ = true;
  media_encoder_->Initialize(
      active_config_->options, std::move(output_cb),
      ConvertToBaseOnceCallback(CrossThreadBindOnce(
          done_callback, WrapCrossThreadWeakPersistent(this),
          active_config_->codec, WrapCrossThreadPersistent(request))));
}

void AudioEncoder::ProcessEncode(Request* request) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(state_, V8CodecState::Enum::kConfigured);
  DCHECK(media_encoder_);
  DCHECK_EQ(request->type, Request::Type::kEncode);
  DCHECK_GT(requested_encodes_, 0);

  request->StartTracing();

  auto* audio_data = request->input.Release();

  auto data = audio_data->data();

  // The data shouldn't be closed at this point.
  DCHECK(data);

  auto done_callback = [](AudioEncoder* self, Request* req,
                          media::Status status) {
    if (!self || self->reset_count_ != req->reset_count) {
      req->EndTracing(/*aborted=*/true);
      return;
    }
    DCHECK_CALLED_ON_VALID_SEQUENCE(self->sequence_checker_);
    if (!status.is_ok()) {
      self->HandleError(
          self->logger_->MakeException("Encoding error.", status));
    }

    req->EndTracing();
    self->ProcessRequests();
  };

  if (data->channel_count() != active_config_->options.channels ||
      data->sample_rate() != active_config_->options.sample_rate) {
    media::Status error(media::StatusCode::kEncoderFailedEncode);
    error.WithData("channels", data->channel_count());
    error.WithData("sampleRate", data->sample_rate());

    HandleError(logger_->MakeException(
        "Input audio buffer is incompatible with codec parameters", error));

    request->EndTracing();

    audio_data->close();
    return;
  }

  // If |data|'s memory layout allows it, |audio_bus| will be a simple wrapper
  // around it. Otherwise, |audio_bus| will contain a converted copy of |data|.
  auto audio_bus = media::AudioBuffer::WrapOrCopyToAudioBus(data);

  base::TimeTicks timestamp = base::TimeTicks() + data->timestamp();

  --requested_encodes_;
  media_encoder_->Encode(std::move(audio_bus), timestamp,
                         ConvertToBaseOnceCallback(CrossThreadBindOnce(
                             done_callback, WrapCrossThreadWeakPersistent(this),
                             WrapCrossThreadPersistent(request))));

  audio_data->close();
}

void AudioEncoder::ProcessReconfigure(Request* request) {
  // Audio decoders don't currently support any meaningful reconfiguring
}

AudioEncoder::ParsedConfig* AudioEncoder::ParseConfig(
    const AudioEncoderConfig* opts,
    ExceptionState& exception_state) {
  return ParseConfigStatic(opts, exception_state);
}

bool AudioEncoder::CanReconfigure(ParsedConfig& original_config,
                                  ParsedConfig& new_config) {
  return original_config.codec == new_config.codec &&
         original_config.options.channels == new_config.options.channels &&
         original_config.options.bitrate == new_config.options.bitrate &&
         original_config.options.sample_rate == new_config.options.sample_rate;
}

bool AudioEncoder::VerifyCodecSupport(ParsedConfig* config,
                                      ExceptionState& exception_state) {
  return VerifyCodecSupportStatic(config, &exception_state);
}

void AudioEncoder::CallOutputCallback(
    ParsedConfig* active_config,
    uint32_t reset_count,
    media::EncodedAudioBuffer encoded_buffer,
    absl::optional<media::AudioEncoder::CodecDescription> codec_desc) {
  DCHECK(active_config);
  if (!script_state_->ContextIsValid() || !output_callback_ ||
      state_.AsEnum() != V8CodecState::Enum::kConfigured ||
      reset_count != reset_count_) {
    return;
  }

  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  MarkCodecActive();

  auto buffer = media::DecoderBuffer::FromArray(
      std::move(encoded_buffer.encoded_data), encoded_buffer.encoded_data_size);
  buffer->set_timestamp(encoded_buffer.timestamp - base::TimeTicks());
  buffer->set_is_key_frame(true);
  buffer->set_duration(encoded_buffer.duration);
  auto* chunk = MakeGarbageCollected<EncodedAudioChunk>(std::move(buffer));

  auto* metadata = MakeGarbageCollected<EncodedAudioChunkMetadata>();
  if (first_output_after_configure_ || codec_desc.has_value()) {
    first_output_after_configure_ = false;
    auto* decoder_config = MakeGarbageCollected<AudioDecoderConfig>();
    decoder_config->setCodec(active_config->codec_string);
    decoder_config->setSampleRate(encoded_buffer.params.sample_rate());
    decoder_config->setNumberOfChannels(active_config->options.channels);
    if (codec_desc.has_value()) {
      auto* desc_array_buf = DOMArrayBuffer::Create(codec_desc.value().data(),
                                                    codec_desc.value().size());
      decoder_config->setDescription(
          MakeGarbageCollected<AllowSharedBufferSource>(desc_array_buf));
    }
    metadata->setDecoderConfig(decoder_config);
  }

  TRACE_EVENT_BEGIN1(kCategory, GetTraceNames()->output.c_str(), "timestamp",
                     chunk->timestamp());

  ScriptState::Scope scope(script_state_);
  output_callback_->InvokeAndReportException(nullptr, chunk, metadata);

  TRACE_EVENT_END0(kCategory, GetTraceNames()->output.c_str());
}

// static
ScriptPromise AudioEncoder::isConfigSupported(ScriptState* script_state,
                                              const AudioEncoderConfig* config,
                                              ExceptionState& exception_state) {
  auto* parsed_config = ParseConfigStatic(config, exception_state);
  if (!parsed_config) {
    DCHECK(exception_state.HadException());
    return ScriptPromise();
  }

  auto* support = AudioEncoderSupport::Create();
  support->setSupported(VerifyCodecSupportStatic(parsed_config, nullptr));
  support->setConfig(CopyConfig(*config));

  return ScriptPromise::Cast(
      script_state, ToV8Traits<AudioEncoderSupport>::ToV8(script_state, support)
                        .ToLocalChecked());
}

}  // namespace blink


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: FrameEncoder.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: FrameEncoder.js

'use strict'

var jsBin = require('js-binary'),
	Type = jsBin.Type,
	types = jsBin.types,
	Data = jsBin.Data,
	ReadState = jsBin.ReadState

/**
 * Help encode/decode protocol frames
 * @class
 * @param {Peer} peer
 * @param {Connection} connection
 * @private
 */
function FrameEncoder(peer, connection) {
	/**
	 * @member {Peer}
	 * @private
	 */
	this._peer = peer

	/**
	 * @member {Connection}
	 * @private
	 */
	this._connection = connection
}

module.exports = FrameEncoder

var Peer = require('./Peer')

/**
 * @property {Type}
 * @private
 */
FrameEncoder._handshakeType = new Type({
	version: 'uint', // 1
	auth: {
		user: 'string',
		password: 'string'
	},
	calls: [{ // local calls
		id: 'uint',
		hash: 'Buffer'
	}],
	messages: [{ // local messages
		id: 'uint',
		hash: 'Buffer'
	}]
})

/**
 * @property {Type}
 * @private
 */
FrameEncoder._handshakeAnswerType = new Type({
	'error?': 'string'
})

/**
 * @property {Type}
 * @private
 */
FrameEncoder._errorType = new Type({
	reason: 'string',
	code: 'uint'
})

/**
 * Generate the handshake frame and send it.
 * This MUST be the very first frame in the connection
 * @param {string} user
 * @param {string} password
 * @param {Array<Call>} calls
 * @param {Array<Message>} messages
 */
FrameEncoder.prototype.doHandshake = function (user, password, calls, messages) {
	this._connection.sendFrame(FrameEncoder._handshakeType.encode({
		version: 1,
		auth: {
			user: user,
			password: password
		},
		calls: calls.map(function (call) {
			return {
				id: call.id,
				hash: call.hash
			}
		}),
		messages: messages.map(function (message) {
			return {
				id: message.id,
				hash: message.hash
			}
		})
	}))
}

/**
 * Generate the handshake answer frame and send it.
 * This MUST be the second frame in the connection
 * @param {?Error|string} error - null if the connection is good to go, an Error instance otherwise
 */
FrameEncoder.prototype.doAnswerHandshake = function (error) {
	this._connection.sendFrame(FrameEncoder._handshakeAnswerType.encode({
		error: error ? String(error) : undefined
	}))
}

/**
 * Generate the call frame and send it
 * @param {number} sid
 * @param {number} id
 * @param {?*} data
 * @param {?Type} type
 * @throws if badly formatted data
 */
FrameEncoder.prototype.doCall = function (sid, id, data, type) {
	// 0x00 <sid:uint> <id:uint> <data>
	var frame = new Data
	frame.writeUInt8(0)
	types.uint.write(sid, frame)
	types.uint.write(id, frame)
	if (type !== null) {
		type.write(data, frame, '')
	}
	this._connection.sendFrame(frame.toBuffer())
}

/**
 * Generate the message frame and send it
 * @param {number} id
 * @param {?*} data
 * @param {?Type} type
 * @throws if badly formatted data
 */
FrameEncoder.prototype.doSend = function (id, data, type) {
	// 0x01 <id:uint> <data>
	var frame = new Data
	frame.writeUInt8(1)
	types.uint.write(id, frame)
	if (type !== null) {
		type.write(data, frame, '')
	}
	this._connection.sendFrame(frame.toBuffer())
}

/**
 * Generate the answer frame and send it.
 *
 * This function was designed to be binded like
 * `doAnswer.bind(frameEncoder, sid, type)`
 * to act like an async callback `function(err,response)`
 * @param {number} sid
 * @param {Call} call
 * @param {?Error} err
 * @param {*} data
 */
FrameEncoder.prototype.doAnswer = function (sid, call, err, data) {
	var reason, code
	if (err) {
		reason = String(err.message || err)
		code = typeof err.code === 'number' && err.code > 0 ? err.code : 0
		return this.doAnswerError(sid, reason, code)
	}
	this.doAnswerSuccess(sid, data, call)
}

/**
 * Generate the answer frame and send it
 *
 * If any enconding errors occur:
 * * the call will be answer with error instead and
 * * 'error' event will be fired on Peer
 * @param {number} sid
 * @param {*} data
 * @param {Call} call
 */
FrameEncoder.prototype.doAnswerSuccess = function (sid, data, call) {
	// 0x02 <sid:uint> <data>
	var frame = new Data
	frame.writeUInt8(2)
	types.uint.write(sid, frame)
	if (call.output !== null) {
		try {
			call.output.write(data, frame, '')
		} catch (e) {
			// Answer with error and fire 'error' event
			this.doAnswerError(sid, 'Internal error', Peer.ERROR.INTERNAL)
			this._peer.emit('error', new Error('Encoding error in ' + call.name + ': ' + e.message))
			return
		}
	}
	this._connection.sendFrame(frame.toBuffer())
}

/**
 * Generate the answer frame and send it
 * @param {number} sid
 * @param {string} reason
 * @param {number} [code=0]
 */
FrameEncoder.prototype.doAnswerError = function (sid, reason, code) {
	// 0x03 <sid:uint> <data>
	var frame = new Data
	frame.writeUInt8(3)
	types.uint.write(sid, frame)
	FrameEncoder._errorType.write({
		reason: reason,
		code: code || 0
	}, frame, '')
	this._connection.sendFrame(frame.toBuffer())
}

/**
 * Read a frame as a handshake
 * @param {Buffer} frame
 * @return {Object}
 */
FrameEncoder.prototype.readHandshake = function (frame) {
	return FrameEncoder._handshakeType.decode(frame)
}

/**
 * Read a frame as a handshake answer
 * @param {Buffer} frame
 * @return {Object}
 */
FrameEncoder.prototype.readHandshakeAnswer = function (frame) {
	return FrameEncoder._handshakeAnswerType.decode(frame)
}

/**
 * Read and route an incoming frame
 * @param {Buffer} frame
 */
FrameEncoder.prototype.processFrame = function (frame) {
	var state = new ReadState(frame),
		frameKind, sid, id, error

	frameKind = state.readUInt8()
	if (frameKind === 0) {
		// Call
		sid = types.uint.read(state)
		id = types.uint.read(state)
		this._peer._processCall(sid, id, state)
	} else if (frameKind === 1) {
		// Message
		id = types.uint.read(state)
		this._peer._processMessage(id, state)
	} else if (frameKind === 2) {
		// Success response
		sid = types.uint.read(state)
		this._peer._processResponse(sid, state)
	} else if (frameKind === 3) {
		// Error response
		sid = types.uint.read(state)
		error = FrameEncoder._errorType.read(state)
		this._peer._processError(sid, error.reason, error.code)
	} else {
		throw new Error('Protocol error, invalid frame kind: ' + frameKind)
	}
}

Home

Classes

Call

Connection

Context

Message

Peer

Events

close

connect

error

frame

close

connect

error

Global

checkHash

    Documentation generated by JSDoc 3.5.5 on Mon Nov 27 2017 16:15:03 GMT-0200 (Horário brasileiro de verão)


text:
<?php
namespace Concrete\Core\Marketplace;

use Loader;
use Config;
use Log;
use \Concrete\Core\Legacy\ItemList;
use \Concrete\Core\Package\Package;

class RemoteItemList extends ItemList
{
    protected $includeInstalledItems = true;
    protected $params = array();
    protected $type = 'themes';
    protected $itemsPerPage = 20;

    public static function getItemSets($type)
    {
        $cache = \Core::make('cache/expensive');
        $r = $cache->getItem('concrete.marketplace.remote_item_sets.' . $type);
        if ($r->isMiss()) {
            $r->lock();
            $url = Config::get('concrete.urls.concrete5') . Config::get('concrete.urls.paths.marketplace.remote_item_list');
            $url .= $type . '/-/get_remote_item_sets';
            if (Config::get('concrete.marketplace.log_requests')) {
                Log::info($url);
            }
            $contents = Loader::helper("file")->getContents($url);
            $sets = array();
            if ($contents != '') {
                $objects = @Loader::helper('json')->decode($contents);
                if (is_array($objects)) {
                    foreach ($objects as $obj) {
                        $mr = new RemoteItemSet();
                        $mr->id = $obj->marketplaceItemSetID;
                        $mr->name = $obj->marketplaceItemSetName;
                        $sets[] = $mr;
                    }
                }
            }
            $r->set($sets);
        }
        return $r->get();
    }

    public function setIncludeInstalledItems($pp)
    {
        $this->includeInstalledItems = $pp;
    }

    public function setType($type)
    {
        $this->type = $type;
    }

    public function filterByKeywords($keywords)
    {
        $this->params['keywords'] = $keywords;
    }

    public function filterByMarketplaceItemID($mpID)
    {
        $this->params['mpID'] = $mpID;
    }

    public function sortBy($sortBy)
    {
        $this->params['sort'] = $sortBy;
    }

    public function filterBySet($set)
    {
        $this->params['set'] = $set;
    }

    public function filterByIsFeaturedRemotely($r)
    {
        $this->params['is_featured_remotely'] = $r;
    }

    public function filterByCompatibility($r)
    {
        $this->params['is_compatible'] = $r;
    }

    public function execute()
    {
        $this->loadQueryStringPagingVariable();
        $params = $this->params;
        $params['version'] = APP_VERSION;
        $params['itemsPerPage'] = $this->itemsPerPage;
        $mi = Marketplace::getInstance();
        $params['csToken'] = $mi->getSiteToken();

        if ($this->includeInstalledItems) {
            $params['includeInstalledItems'] = 1;
        } else {
            $params['includeInstalledItems'] = 0;
            $list = Package::getInstalledList();
            foreach ($list as $pkg) {
                $params['installedPackages'][] = $pkg->getPackageHandle();
            }
        }

        if (isset($_REQUEST[$this->queryStringPagingVariable])) {
            $params[$this->queryStringPagingVariable] = $_REQUEST[$this->queryStringPagingVariable];
        }

        $uh = Loader::helper('url');

        $url = Config::get('concrete.urls.concrete5') . Config::get('concrete.urls.paths.marketplace.remote_item_list');
        $url = $uh->buildQuery($url . $this->type . '/-/get_remote_list', $params);
        if (Config::get('concrete.marketplace.log_requests')) {
            Log::info($url);
        }
        $r = Loader::helper('file')->getContents($url);
        $r2 = @Loader::helper('json')->decode($r);

        $total = 0;
        $items = array();

        if (is_object($r2)) {
            $items = $r2->items;
            $total = $r2->total;
        }

        $this->total = $total;
        $this->setItems($items);
    }

    public function get($itemsToGet = 0, $offset = 0)
    {
        $this->start = $offset;
        $items = $this->items;
        $marketplaceItems = array();
        foreach ($items as $stdObj) {
            $mi = new RemoteItem();
            $mi->setPropertiesFromJSONObject($stdObj);
            $marketplaceItems[] = $mi;
        }

        return $marketplaceItems;
    }

}


text:
namespace cc {

class PixelTestOutputSurface : public OutputSurface {
 public:
  explicit PixelTestOutputSurface(
      scoped_refptr<ContextProvider> context_provider,
      bool flipped_output_surface);
  explicit PixelTestOutputSurface(
      std::unique_ptr<SoftwareOutputDevice> software_device);
  ~PixelTestOutputSurface() override;

  // OutputSurface implementation.
  void BindToClient(OutputSurfaceClient* client) override;
  void EnsureBackbuffer() override;
  void DiscardBackbuffer() override;
  void BindFramebuffer() override;
  void Reshape(const gfx::Size& size,
               float device_scale_factor,
               const gfx::ColorSpace& color_space,
               bool has_alpha,
               bool use_stencil) override;
  bool HasExternalStencilTest() const override;
  void ApplyExternalStencil() override;
  void SwapBuffers(OutputSurfaceFrame frame) override;
  OverlayCandidateValidator* GetOverlayCandidateValidator() const override;
  bool IsDisplayedAsOverlayPlane() const override;
  unsigned GetOverlayTextureId() const override;
  bool SurfaceIsSuspendForRecycle() const override;
  uint32_t GetFramebufferCopyTextureFormat() override;

  void set_has_external_stencil_test(bool has_test) {
    external_stencil_test_ = has_test;
  }

 private:
  void SwapBuffersCallback();

  bool external_stencil_test_ = false;
  OutputSurfaceClient* client_ = nullptr;
  base::WeakPtrFactory<PixelTestOutputSurface> weak_ptr_factory_;
};

}  // namespace cc

#endif  // CC_TEST_PIXEL_TEST_OUTPUT_SURFACE_H_


text:
module Concurrent

  # Raised when errors occur during configuration.
  ConfigurationError = Class.new(StandardError)

  # Raised when a lifecycle method (such as `stop`) is called in an improper
  # sequence or when the object is in an inappropriate state.
  LifecycleError = Class.new(StandardError)

  # Raised when an object's methods are called when it has not been
  # properly initialized.
  InitializationError = Class.new(StandardError)

  # Raised when an object with a start/stop lifecycle has been started an
  # excessive number of times. Often used in conjunction with a restart
  # policy or strategy.
  MaxRestartFrequencyError = Class.new(StandardError)

  # Raised when an attempt is made to modify an immutable object
  # (such as an `IVar`) after its final state has been set.
  MultipleAssignmentError = Class.new(StandardError)

  # Raised by an `Executor` when it is unable to process a given task,
  # possibly because of a reject policy or other internal error.
  RejectedExecutionError = Class.new(StandardError)

  # Raised when an operation times out.
  TimeoutError = Class.new(StandardError)

end


text:
"""
"""

# Created on 2016.08.31
#
# Author: Giovanni Cannata
#
# Copyright 2013, 2014, 2015, 2016, 2017 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.

from sys import stdin, getdefaultencoding

from .. import ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, NO_ATTRIBUTES, SEQUENCE_TYPES
from ..core.exceptions import LDAPConfigurationParameterError

# checks
_CLASSES_EXCLUDED_FROM_CHECK = ['subschema']
_ATTRIBUTES_EXCLUDED_FROM_CHECK = [ALL_ATTRIBUTES,
                                   ALL_OPERATIONAL_ATTRIBUTES,
                                   NO_ATTRIBUTES,
                                   'ldapSyntaxes',
                                   'matchingRules',
                                   'matchingRuleUse',
                                   'dITContentRules',
                                   'dITStructureRules',
                                   'nameForms',
                                   'altServer',
                                   'namingContexts',
                                   'supportedControl',
                                   'supportedExtension',
                                   'supportedFeatures',
                                   'supportedCapabilities',
                                   'supportedLdapVersion',
                                   'supportedSASLMechanisms',
                                   'vendorName',
                                   'vendorVersion',
                                   'subschemaSubentry',
                                   'ACL']
_UTF8_ENCODED_SYNTAXES = ['1.2.840.113556.1.4.904',  # DN String [MICROSOFT]
                          '1.2.840.113556.1.4.1362',  # String (Case) [MICROSOFT]
                          '1.3.6.1.4.1.1466.115.121.1.12',  # DN String [RFC4517]
                          '1.3.6.1.4.1.1466.115.121.1.15',  # Directory String [RFC4517]
                          '1.3.6.1.4.1.1466.115.121.1.41',  # Postal Address) [RFC4517]
                          '1.3.6.1.4.1.1466.115.121.1.58',  # Substring Assertion [RFC4517]
                          '2.16.840.1.113719.1.1.5.1.6',  # Case Ignore List [NOVELL]
                          '2.16.840.1.113719.1.1.5.1.14',  # Tagged String [NOVELL]
                          '2.16.840.1.113719.1.1.5.1.15',  # Tagged Name and String [NOVELL]
                          '2.16.840.1.113719.1.1.5.1.23',  # Tagged Name [NOVELL]
                          '2.16.840.1.113719.1.1.5.1.25']  # Typed Name [NOVELL]

_UTF8_ENCODED_TYPES = []

_CASE_INSENSITIVE_ATTRIBUTE_NAMES = True
_CASE_INSENSITIVE_SCHEMA_NAMES = True

# abstraction layer
_ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX = 'OA_'

# communication
_POOLING_LOOP_TIMEOUT = 10  # number of seconds to wait before restarting a cycle to find an active server in the pool

_RESPONSE_SLEEPTIME = 0.05  # seconds to wait while waiting for a response in asynchronous strategies
_RESPONSE_WAITING_TIMEOUT = 20  # waiting timeout for receiving a response in asynchronous strategies
_SOCKET_SIZE = 4096  # socket byte size
_CHECK_AVAILABILITY_TIMEOUT = 2.5  # default timeout for socket connect when checking availability
_RESET_AVAILABILITY_TIMEOUT = 5  # default timeout for resetting the availability status when checking candidate addresses
_RESTARTABLE_SLEEPTIME = 2  # time to wait in a restartable strategy before retrying the request
_RESTARTABLE_TRIES = 30  # number of times to retry in a restartable strategy before giving up. Set to True for unlimited retries
_REUSABLE_THREADED_POOL_SIZE = 10
_REUSABLE_THREADED_LIFETIME = 3600  # 1 hour
_DEFAULT_THREADED_POOL_NAME = 'REUSABLE_DEFAULT_POOL'
_ADDRESS_INFO_REFRESH_TIME = 300  # seconds to wait before refreshing address info from dns
_RESPONSE_DN_ENCODING = ["utf-8"]  # some broken LDAP implementation may havedifferent encoding against RFC

if stdin and stdin.encoding:
    _DEFAULT_ENCODING = stdin.encoding
elif getdefaultencoding():
    _DEFAULT_ENCODING = getdefaultencoding()
else:
    _DEFAULT_ENCODING = 'utf-8'

def get_config_parameter(parameter):
    if parameter == 'CASE_INSENSITIVE_ATTRIBUTE_NAMES':
        return _CASE_INSENSITIVE_ATTRIBUTE_NAMES
    elif parameter == 'CASE_INSENSITIVE_SCHEMA_NAMES':
        return _CASE_INSENSITIVE_SCHEMA_NAMES
    elif parameter == 'ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX':
        return _ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX
    elif parameter == 'POOLING_LOOP_TIMEOUT':
        return _POOLING_LOOP_TIMEOUT
    elif parameter == 'RESPONSE_SLEEPTIME':
        return _RESPONSE_SLEEPTIME
    elif parameter == 'RESPONSE_WAITING_TIMEOUT':
        return _RESPONSE_WAITING_TIMEOUT
    elif parameter == 'SOCKET_SIZE':
        return _SOCKET_SIZE
    elif parameter == 'CHECK_AVAILABILITY_TIMEOUT':
        return _CHECK_AVAILABILITY_TIMEOUT
    elif parameter == 'RESTARTABLE_SLEEPTIME':
        return _RESTARTABLE_SLEEPTIME
    elif parameter == 'RESTARTABLE_TRIES':
        return _RESTARTABLE_TRIES
    elif parameter == 'REUSABLE_THREADED_POOL_SIZE':
        return _REUSABLE_THREADED_POOL_SIZE
    elif parameter == 'REUSABLE_THREADED_LIFETIME':
        return _REUSABLE_THREADED_LIFETIME
    elif parameter == 'DEFAULT_THREADED_POOL_NAME':
        return _DEFAULT_THREADED_POOL_NAME
    elif parameter == 'ADDRESS_INFO_REFRESH_TIME':
        return _ADDRESS_INFO_REFRESH_TIME
    elif parameter == 'RESET_AVAILABILITY_TIMEOUT':
        return _RESET_AVAILABILITY_TIMEOUT
    elif parameter == 'DEFAULT_ENCODING':
        return _DEFAULT_ENCODING
    elif parameter == 'CLASSES_EXCLUDED_FROM_CHECK':
        return _CLASSES_EXCLUDED_FROM_CHECK
    elif parameter == 'ATTRIBUTES_EXCLUDED_FROM_CHECK':
        return _ATTRIBUTES_EXCLUDED_FROM_CHECK
    elif parameter == 'UTF8_ENCODED_SYNTAXES':
        return _UTF8_ENCODED_SYNTAXES
    elif parameter == 'UTF8_ENCODED_TYPES':
        return _UTF8_ENCODED_TYPES
    elif parameter == 'RESPONSE_DN_ENCODING':
        return _RESPONSE_DN_ENCODING
    raise LDAPConfigurationParameterError('configuration parameter %s not valid' % parameter)

def set_config_parameter(parameter, value):
    if parameter == 'CASE_INSENSITIVE_ATTRIBUTE_NAMES':
        global _CASE_INSENSITIVE_ATTRIBUTE_NAMES
        _CASE_INSENSITIVE_ATTRIBUTE_NAMES = value
    elif parameter == 'CASE_INSENSITIVE_SCHEMA_NAMES':
        global _CASE_INSENSITIVE_SCHEMA_NAMES
        _CASE_INSENSITIVE_SCHEMA_NAMES = value
    elif parameter == 'ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX':
        global _ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX
        _ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX = value
    elif parameter == 'POOLING_LOOP_TIMEOUT':
        global _POOLING_LOOP_TIMEOUT
        _POOLING_LOOP_TIMEOUT = value
    elif parameter == 'RESPONSE_SLEEPTIME':
        global _RESPONSE_SLEEPTIME
        _RESPONSE_SLEEPTIME = value
    elif parameter == 'RESPONSE_WAITING_TIMEOUT':
        global _RESPONSE_WAITING_TIMEOUT
        _RESPONSE_WAITING_TIMEOUT = value
    elif parameter == 'SOCKET_SIZE':
        global _SOCKET_SIZE
        _SOCKET_SIZE = value
    elif parameter == 'CHECK_AVAILABILITY_TIMEOUT':
        global _CHECK_AVAILABILITY_TIMEOUT
        _CHECK_AVAILABILITY_TIMEOUT = value
    elif parameter == 'RESTARTABLE_SLEEPTIME':
        global _RESTARTABLE_SLEEPTIME
        _RESTARTABLE_SLEEPTIME = value
    elif parameter == 'RESTARTABLE_TRIES':
        global _RESTARTABLE_TRIES
        _RESTARTABLE_TRIES = value
    elif parameter == 'REUSABLE_THREADED_POOL_SIZE':
        global _REUSABLE_THREADED_POOL_SIZE
        _REUSABLE_THREADED_POOL_SIZE = value
    elif parameter == 'REUSABLE_THREADED_LIFETIME':
        global _REUSABLE_THREADED_LIFETIME
        _REUSABLE_THREADED_LIFETIME = value
    elif parameter == 'DEFAULT_THREADED_POOL_NAME':
        global _DEFAULT_THREADED_POOL_NAME
        _DEFAULT_THREADED_POOL_NAME = value
    elif parameter == 'ADDRESS_INFO_REFRESH_TIME':
        global _ADDRESS_INFO_REFRESH_TIME
        _ADDRESS_INFO_REFRESH_TIME = value
    elif parameter == 'RESET_AVAILABILITY_TIMEOUT':
        global _RESET_AVAILABILITY_TIMEOUT
        _RESET_AVAILABILITY_TIMEOUT = value
    elif parameter == 'DEFAULT_ENCODING':
        global _DEFAULT_ENCODING
        _DEFAULT_ENCODING = value
    elif parameter == 'CLASSES_EXCLUDED_FROM_CHECK':
        global _CLASSES_EXCLUDED_FROM_CHECK
        _CLASSES_EXCLUDED_FROM_CHECK = value
    elif parameter == 'ATTRIBUTES_EXCLUDED_FROM_CHECK':
        global _ATTRIBUTES_EXCLUDED_FROM_CHECK
        _ATTRIBUTES_EXCLUDED_FROM_CHECK = value
    elif parameter == 'UTF8_ENCODED_SYNTAXES':
        global _UTF8_ENCODED_SYNTAXES
        _UTF8_ENCODED_SYNTAXES = value
    elif parameter == 'UTF8_ENCODED_TYPES':
        global _UTF8_ENCODED_TYPES
        _UTF8_ENCODED_TYPES = value
    elif parameter == 'RESPONSE_DN_ENCODING':
        global _RESPONSE_DN_ENCODING
        _RESPONSE_DN_ENCODING = value if isinstance(value, SEQUENCE_TYPES) else [value]
    else:
        raise LDAPConfigurationParameterError('unable to set configuration parameter %s' % parameter)


text:
#ifndef FINDER_PATTERN_H
#define FINDER_PATTERN_H

#include <zxing/oned/OneDResultPoint.h>

#include <vector>

namespace zxing {

namespace oned {

namespace rss {

/**
 * Encapsulates an RSS barcode finder pattern, including its start/end position and row.
 */
class FinderPattern
{

public:
    FinderPattern(int value, std::vector<int> startEnd, int start, int end, int rowNumber);

    FinderPattern(const FinderPattern* other = nullptr);

    int getValue() const;

    std::vector<int> &getStartEnd();

    QSharedPointer<std::vector<QSharedPointer<ResultPoint>> > &getResultPoints();

    bool equals(const FinderPattern& other) const;

    int hashCode() const;

    bool isValid() const;

private:
    int m_value;
    std::vector<int> m_startEnd;
    QSharedPointer<std::vector<QSharedPointer<ResultPoint>> > m_resultPoints;

};

}
}
}

#endif


text:
chmod -R 777 uploads
chmod -R 777 smarty/templates_c
rm smarty/templates_c/*


text:
require 'chefspec'

describe 'chocolatey_package::upgrade' do
  let(:chef_run) do
    ChefSpec::ServerRunner.new(platform: 'windows', version: '2012R2')
                          .converge(described_recipe)
  end

  it 'upgrades a package' do
    expect(chef_run).to upgrade_chocolatey_package('7zip')
  end

  it 'upgrades a specific version of a package with options' do
    expect(chef_run).to upgrade_chocolatey_package('git').with(
      version: %w(2.7.1)
    )
  end
end


text:
(function() {
    'use strict';

    angular
        .module('artemisApp')
        .controller('ResultController', ResultController);

    ResultController.$inject = ['Result'];

    function ResultController(Result) {

        var vm = this;

        vm.results = [];

        loadAll();

        function loadAll() {
            Result.query(function(result) {
                vm.results = result;
                vm.searchQuery = null;
            });
        }
    }
})();


text:
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Xunit;

namespace BracketPipe.Tests
{
  public class GenerateNodesTest
  {
    [Fact]
    public void HtmlFromNodes()
    {
      Assert.Equal("<!DOCTYPE html>

Paragraph text

", GetHtml().ToHtml());
    }

    [Fact]
    public void ReadToEnd()
    {
      var origString = default(string);
      using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BracketPipe.Tests.LongSample.html"))
      using (var reader = new StreamReader(stream))
      {
        origString = reader.ReadToEnd();
      }

      using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BracketPipe.Tests.LongSample.html"))
      {
        var source = new TextSource(stream);
        var newString = source.ReadToEnd();
        Assert.Equal(origString, newString);
      }
    }

    private IEnumerable<HtmlNode> GetHtml()
    {
      yield return new HtmlDoctype();
      yield return new HtmlStartTag("body");
      yield return new HtmlStartTag("div")
      {
        { "id", "first" },
        { "class", "start" }
      };
      yield return new HtmlStartTag("p").Add("style", "color:red;");
      yield return new HtmlText("Paragraph text");
      yield return new HtmlEndTag("p");
      yield return new HtmlEndTag("div");
      yield return new HtmlEndTag("body");
    }
  }
}


text:
    <input type="checkbox" name="port-<%= id %>" id="port-<%= id %>" value="<%= id %>" class="port-checkbox" <% if (selected) { print('checked="checked"') } %> />
    <label for="port-<%= id %>"><%= name %> (<%= streamName %>)


text:
@interface ProjectDeleteAlertControllerVisualStyle : SDCAlertControllerDefaultVisualStyle

@end


text:
package org.whitesource.agent.api.model;

import java.io.Serializable;
import java.util.Objects;

public class ProjectTag implements Serializable {
    private static final long serialVersionUID = 1835100904098326933L;

    /* --- Members --- */

    private String tagKey;

    private String tagValue;

    /* --- Constructors --- */

    /**
     * Default constructor
     */
    public ProjectTag() {

    }

    /**
     * Constructor
     *
     * @param tagKey
     * @param tagValue
     */
    public ProjectTag(String tagKey, String tagValue) {
        this.tagKey = tagKey;
        this.tagValue = tagValue;
    }

    /* --- Overridden methods --- */

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append("ProjectTag@").append(Integer.toHexString(hashCode()))
                .append("[")
                .append("tagKey= ").append(tagKey).append(",")
                .append("tagValue= ").append(tagValue)
                .append(" ]");

        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ProjectTag)) return false;
        ProjectTag that = (ProjectTag) o;
        return Objects.equals(tagKey, that.tagKey) &&
                Objects.equals(tagValue, that.tagValue);
    }

    @Override
    public int hashCode() {
        return Objects.hash(tagKey, tagValue);
    }

    public String getTagKey() {
        return tagKey;
    }

    public void setTagKey(String tagKey) {
        this.tagKey = tagKey;
    }

    public String getTagValue() {
        return tagValue;
    }

    public void setTagValue(String tagValue) {
        this.tagValue = tagValue;
    }
}


text:
#ifndef SANDESHA2_PERMANENT_CREATE_SEQ_MGR_H
#define SANDESHA2_PERMANENT_CREATE_SEQ_MGR_H

/**
 * @file sandesha2_permanent_create_seq_mgr.h
 * @brief Sandesha Permanat Create Sequence Manager Interface
 */

#include <axutil_allocator.h>
#include <axutil_env.h>
#include <axutil_error.h>
#include <axutil_string.h>
#include <axutil_utils.h>

#ifdef __cplusplus
extern "C"
{
#endif

/** @defgroup sandesha2_permanent_create_seq_mgr Permanat Create Sequence Manager
  * @ingroup sandesha2
  * @{
  */

AXIS2_EXTERN struct sandesha2_create_seq_mgr * AXIS2_CALL
sandesha2_permanent_create_seq_mgr_create(
    const axutil_env_t *env,
    axis2_char_t *dbname);

/** @} */
#ifdef __cplusplus
}
#endif
#endif /* SANDESHA2_PERMANENT_CREATE_SEQ_MGR_H */


text:
package com.ubb.app.adapters;

import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shirwa.simplistic_rss.RssItem;
import com.ubb.app.R;
import com.ubb.app.interfaces.NewsClickListener;
import com.ubb.app.viewholders.NewsViewHolder;

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

/**
 * Created by Browsing on 10/4/2015.
 */
public class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {

    private NewsClickListener onNewsClickListener;

    public void setOnNewsClickListener(NewsClickListener onNewsClickListener) {
        this.onNewsClickListener = onNewsClickListener;
    }

    private List<RssItem> items = new ArrayList<>();

    public void setItems(List<RssItem> items) {
        this.items = items;
    }

    public List<RssItem> getItems() {
        return items;
    }

    @Override
    public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, null);
        return new NewsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(NewsViewHolder holder, int position) {
        final RssItem item = items.get(position);

        holder.title.setText(item.getTitle());
        if (item.getDescription() == null)
            holder.content.setText(null);
        else
            holder.content.setText(Html.fromHtml(item.getDescription()));
        holder.content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onNewsClickListener != null) {
                    onNewsClickListener.onNewsClick(item);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        if (items == null) {
            return 0;
        }
        return items.size();
    }
}


text:
<?php

namespace app\modules\admfarmacia;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Insumos;

/**
 * InsumosSearch represents the model behind the search form about `app\models\Insumos`.
 */
class InsumosSearch extends Insumos
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idInsumo', 'NroSerie', 'idProveedor', 'Stock'], 'integer'],
            [['FechaVencimiento', 'Descripcion'], 'safe'],
            [['Precio'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Insumos::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'idInsumo' => $this->idInsumo,
            'NroSerie' => $this->NroSerie,
            'idProveedor' => $this->idProveedor,
            'FechaVencimiento' => $this->FechaVencimiento,
            'Precio' => $this->Precio,
            'Stock' => $this->Stock,
        ]);

        $query->andFilterWhere(['like', 'Descripcion', $this->Descripcion]);

        return $dataProvider;
    }
}


text:
module FlexAttributes
  class FloatConverter

    def self.convert(val=nil)
      val.to_f
    end

  end
end


text:
* { font-family: verdana, sans-serif; }
code { font-family: monaco, sans-serif; }
dl,dt,dd { display:block; border: 1px solid black; padding:3px; }
.protected { color: gray; }
.documentation { font-style: italic; }
.error { color: red; }


text:
@class Camera;
@class Lens;

@interface CameraBag : NSObject <NSCoding>
{
	NSMutableArray* cameras;
	NSMutableArray* lenses;

	NSString* archivePath;
}

+ (id)initSharedCameraBagFromArchive:(NSString*)archiveFile;
+ (CameraBag*)sharedCameraBag;

- (NSInteger)cameraCount;
- (void)deleteCamera:(Camera*)camera;
- (Camera*)findCameraForIndex:(NSInteger)index;
- (Camera*)findSelectedCamera;
- (void)moveCameraFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex;

- (void)deleteLens:(Lens*)lens;
- (Lens*)findSelectedLens;
- (Lens*)findLensForIndex:(NSInteger)index;
- (void)moveLensFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex;
- (NSInteger)lensCount;

- (void)addCamera:(Camera*)camera;
- (void)addLens:(Lens*)lens;

- (void)save;

@end


text:
const ObjectId = require('mongoose').Types.ObjectId;

class DbId {
  constructor(id_string) {
    this.id_string = id_string;
    try {
      this._objectId = new ObjectId(this.id_string);
    } catch (error) {
      this._objectId = null;
    }
  }

  isValid() {
    return this._objectId instanceof ObjectId;
  }

  get asObjectId() {
    return this._objectId;
  }
}

exports.DbId = DbId;


text:
/*
 * COPYRIGHT AND PERMISSION NOTICE
 *
 * Copyright (C) 1991-2007 Unicode, Inc. All rights reserved.
 * Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of the Unicode data files and any associated documentation (the "Data
 * Files") or Unicode software and any associated documentation (the
 * "Software") to deal in the Data Files or Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, and/or sell copies of the Data Files or Software, and
 * to permit persons to whom the Data Files or Software are furnished to do
 * so, provided that (a) the above copyright notice(s) and this permission
 * notice appear with all copies of the Data Files or Software, (b) both the
 * above copyright notice(s) and this permission notice appear in associated
 * documentation, and (c) there is clear notice in each modified Data File or
 * in the Software as well as in the documentation associated with the Data
 * File(s) or Software that the data or software has been modified.
 *
 * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
 * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
 * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
 * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THE DATA FILES OR SOFTWARE.
 *
 * Except as contained in this notice, the name of a copyright holder shall not
 * be used in advertising or otherwise to promote the sale, use or other
 * dealings in these Data Files or Software without prior written
 * authorization of the copyright holder.
 */

package sun.text.resources.ga;

import sun.util.resources.ParallelListResourceBundle;

public class FormatData_ga extends ParallelListResourceBundle {
    protected final Object[][] getContents() {
        return new Object[][] {
            { "MonthNames",
                new String[] {
                    "Ean\u00e1ir",
                    "Feabhra",
                    "M\u00e1rta",
                    "Aibre\u00e1n",
                    "Bealtaine",
                    "Meitheamh",
                    "I\u00fail",
                    "L\u00fanasa",
                    "Me\u00e1n F\u00f3mhair",
                    "Deireadh F\u00f3mhair",
                    "Samhain",
                    "Nollaig",
                    "",
                }
            },
            { "MonthAbbreviations",
                new String[] {
                    "Ean",
                    "Feabh",
                    "M\u00e1rta",
                    "Aib",
                    "Beal",
                    "Meith",
                    "I\u00fail",
                    "L\u00fan",
                    "MF\u00f3mh",
                    "DF\u00f3mh",
                    "Samh",
                    "Noll",
                    "",
                }
            },
            { "MonthNarrows",
                new String[] {
                    "E",
                    "F",
                    "M",
                    "A",
                    "B",
                    "M",
                    "I",
                    "L",
                    "M",
                    "D",
                    "S",
                    "N",
                    "",
                }
            },
            { "DayNames",
                new String[] {
                    "D\u00e9 Domhnaigh",
                    "D\u00e9 Luain",
                    "D\u00e9 M\u00e1irt",
                    "D\u00e9 C\u00e9adaoin",
                    "D\u00e9ardaoin",
                    "D\u00e9 hAoine",
                    "D\u00e9 Sathairn",
                }
            },
            { "DayAbbreviations",
                new String[] {
                    "Domh",
                    "Luan",
                    "M\u00e1irt",
                    "C\u00e9ad",
                    "D\u00e9ar",
                    "Aoine",
                    "Sath",
                }
            },
            { "AmPmMarkers",
                new String[] {
                    "a.m.",
                    "p.m.",
                }
            },
            { "Eras",
                new String[] {
                    "RC",
                    "AD",
                }
            },
            { "short.Eras",
                new String[] {
                    "RC",
                    "AD",
                }
            },
            { "NumberPatterns",
                new String[] {
                    "#,##0.###",
                    "\u00a4 #,##0.00",
                    "#,##0%",
                }
            },
            { "NumberElements",
                new String[] {
                    ".",
                    ",",
                    ";",
                    "%",
                    "0",
                    "#",
                    "-",
                    "E",
                    "\u2030",
                    "\u221e",
                    "NaN",
                }
            },
            { "TimePatterns",
                new String[] {
                    "HH:mm:ss z",
                    "HH:mm:ss z",
                    "HH:mm:ss",
                    "HH:mm",
                }
            },
            { "DatePatterns",
                new String[] {
                    "EEEE, yyyy MMMM dd",
                    "yyyy MMMM d",
                    "yyyy MMM d",
                    "yy/MM/dd",
                }
            },
            { "DateTimePatterns",
                new String[] {
                    "{1} {0}",
                }
            },
            { "DateTimePatternChars", "RbMLkUnsSElFtTauKcZ" },
        };
    }
}


text:
jquery-grid
===========

Evens out row heights in grid layouts


text:
* [ServiceLocator](ServiceLocator) [:notebook:](http://en.wikipedia.org/wiki/Service_locator_pattern)
* [Repository](Repository)
* [EAV](EAV) [:notebook:](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model)


text:
require 'stattleship/models/game'
require 'stattleship/models/injury'
require 'stattleship/models/league'
require 'stattleship/models/official'
require 'stattleship/models/penalty'
require 'stattleship/models/player'
require 'stattleship/models/playing_position'
require 'stattleship/models/scoreboard'
require 'stattleship/models/scoring_player'
require 'stattleship/models/scoring_play'
require 'stattleship/models/season'
require 'stattleship/models/team'
require 'stattleship/models/team_outcome_streak'
require 'stattleship/models/venue'
require 'stattleship/models/ranking'

require 'stattleship/models/at_bat'
require 'stattleship/models/line_up'
require 'stattleship/models/pitch'

module Stattleship
  module Models
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="@color/transparent"
        android:src="@drawable/cog"
        android:scaleType="center" />

</android.support.design.widget.CoordinatorLayout>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;

namespace LinqToDB.Common.Internal.Cache
{
	/// <summary>
	/// Represents a local in-memory cache whose values are not serialized.
	/// </summary>
	public interface IMemoryCache<TKey> : IDisposable
		where TKey: notnull
	{
		/// <summary>
		/// Gets the item associated with this key if present.
		/// </summary>
		/// <param name="key">An object identifying the requested entry.</param>
		/// <param name="value">The located value or null.</param>
		/// <returns>True if the key was found.</returns>
		bool TryGetValue(TKey key, out object? value);

		/// <summary>
		/// Create or overwrite an entry in the cache.
		/// </summary>
		/// <param name="key">An object identifying the entry.</param>
		/// <returns>The newly created <see cref="ICacheEntry{TKey}"/> instance.</returns>
		ICacheEntry<TKey> CreateEntry(TKey key);

		/// <summary>
		/// Removes the object associated with the given key.
		/// </summary>
		/// <param name="key">An object identifying the entry.</param>
		void Remove(TKey key);
	}
}


text:
package com.github.walterfan.kanban.domain;

/**
 *
 *    public final static int CATEGORY_TYPE_TASK = 1;
 *
 *    public final static int CATEGORY_TYPE_LORE = 2;
 *
 *    public final static int CATEGORY_TYPE_BOOK = 3;
 *
 *    public final static int CATEGORY_TYPE_FRIEND = 4;
 *
 *    public final static int CATEGORY_TYPE_SITE = 5;
 *
 * @author Walter Fan
 *
 */
public enum CategoryType {
	TASK(1),
	LORE(2),
	BOOK(3),
	FIRIENT(4),
	SITE(5);

	private int value;

	CategoryType(int val) {
		this.value = val;
	}

	public int getValue() {
		return this.value;
	}
}


text:
echo "This will only work one time, then you have to restart!"

echo "Creating pet..."
curl -X POST http://localhost:8080/pets -d @pet.json --header "Content-Type: application/json"

echo "Getting created pet with id 1"
curl -X GET "http://localhost:8080/pets/1"

echo "Listing pets..."
curl -X GET "http://localhost:8080/pets?pageSize=10&offset=0"

echo "Deleting pet..."
curl -X DELETE "http://localhost:8080/pets/1"


text:
package org.ovirt.engine.core.common.utils.exceptions;

/**
 * Exception marking failure in initialization flow
 *
 */
public class InitializationException extends Exception {

    public InitializationException() {
    }

    public InitializationException(String message) {
        super(message);
    }

    public InitializationException(Throwable cause) {
        super(cause);
    }

    public InitializationException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
set( GTS_FOUND OFF )

set(GTS_CONFIG_EXECUTABLE /bin/gts-config)
#set(GTS_CONFIG_EXECUTABLE ${PROJECT_SOURCE_DIR}/gts/bin/gts-config)

if( GTS_CONFIG_EXECUTABLE )
  set( GTS_FOUND ON )

  # run the gsl-config program to get cxxflags
  execute_process(
    COMMAND sh "${GTS_CONFIG_EXECUTABLE}" --cflags
    OUTPUT_VARIABLE GTS_CFLAGS
    RESULT_VARIABLE RET
    ERROR_QUIET
    )

  if( RET EQUAL 0 )
    string( STRIP "${GTS_CFLAGS}" GTS_CFLAGS )
    separate_arguments( GTS_CFLAGS )

    # parse definitions from cflags; drop -D* from CFLAGS
    string( REGEX MATCHALL "-D[^;]+"
      GTS_DEFINITIONS  "${GTS_CFLAGS}" )
    string( REGEX REPLACE "-D[^;]+;" ""
      GTS_CFLAGS "${GTS_CFLAGS}" )

    # parse include dirs from cflags; drop -I prefix
    string( REGEX MATCHALL "-I[^;]+"
      GTS_INCLUDE_DIRS "${GTS_CFLAGS}" )
    string( REPLACE "-I" ""
      GTS_INCLUDE_DIRS "${GTS_INCLUDE_DIRS}")
    string( REGEX REPLACE "-I[^;]+;" ""
      GTS_CFLAGS "${GTS_CFLAGS}")

    message("GTS_DEFINITIONS=${GTS_DEFINITIONS}")
    message("GTS_INCLUDE_DIRS=${GTS_INCLUDE_DIRS}")
    message("GTS_CFLAGS=${GTS_CFLAGS}")
  else( RET EQUAL 0 )
    set( GTS_FOUND FALSE )
  endif( RET EQUAL 0 )

  # run the gsl-config program to get the libs
  execute_process(
    COMMAND sh "${GTS_CONFIG_EXECUTABLE}" --libs
    OUTPUT_VARIABLE GTS_LIBRARIES
    RESULT_VARIABLE RET
    ERROR_QUIET
    )
  if( RET EQUAL 0 )
    string(STRIP "${GTS_LIBRARIES}" GTS_LIBRARIES )
    separate_arguments( GTS_LIBRARIES )

    # extract linkdirs (-L) for rpath (i.e., LINK_DIRECTORIES)
    string( REGEX MATCHALL "-L[^;]+"
      GTS_LIBRARY_DIRS "${GTS_LIBRARIES}" )
    string( REPLACE "-L" ""
      GTS_LIBRARY_DIRS "${GTS_LIBRARY_DIRS}" )
  else( RET EQUAL 0 )
    set( GTS_FOUND FALSE )
  endif( RET EQUAL 0 )

  MARK_AS_ADVANCED(
    GTS_CFLAGS
  )

else( GTS_CONFIG_EXECUTABLE )
    message( STATUS "FindGTS: gts-config not found.")
endif( GTS_CONFIG_EXECUTABLE )

if( GTS_FOUND )
  if( NOT GTS_FIND_QUIETLY )
    message( STATUS "FindGTS: Found both GTS headers and library" )
  endif( NOT GTS_FIND_QUIETLY )
else( GTS_FOUND )
  if( GTS_FIND_REQUIRED )
    message( FATAL_ERROR "FindGTS: Could not find GTS headers or library" )
  endif( GTS_FIND_REQUIRED )
endif( GTS_FOUND )


text:
package net.mtu.eggplant.dbc.test;

import java.awt.geom.Dimension2D;

/**
 * Adds a Double implementation of Dimension2D just like the one in
 * {@link java.awt.geom.Point2D}.
 *
 * @version $Revision: 1.2 $
 */
public final class XDimension2D {

  private XDimension2D() {
    //no instances
  }

  /**
   * A Dimension2D with double precision.
   */
  public static class Double extends Dimension2D {
    public Double() {
      this(0, 0);
    }

    public Double(final double width,
                 final double height) {
      _width = width;
      _height = height;
    }

    private double _height;
    public double getHeight() {
      return _height;
    }

    private double _width;
    public double getWidth() {
      return _width;
    }

    public void setSize(final double width,
                        final double height) {
      _width = width;
      _height = height;
    }
  }
}


text:
package com.blogspot.sontx.bottle.view.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.blogspot.sontx.bottle.R;
import com.blogspot.sontx.bottle.model.bean.MessageBase;
import com.blogspot.sontx.bottle.model.bean.PublicProfile;
import com.blogspot.sontx.bottle.system.Resource;
import com.blogspot.sontx.bottle.view.custom.AutoSizeImageView;
import com.blogspot.sontx.bottle.view.custom.RichVideoView;
import com.blogspot.sontx.bottle.view.fragment.OnMessageInteractionListener;
import com.squareup.picasso.Picasso;

import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import it.slyce.messaging.utils.DateTimeUtils;

public final class MessageAdapterHelper {
    public static void bindMessageToVideoViewHolder(VideoViewHolder holder, MessageBase message, Resource resource) {
        String url = resource.absoluteUrl(message.getMediaUrl());
        holder.richVideoView.setVideoUrl(url);
    }

    public static void bindMessageToPhotoViewHolder(PhotoViewHolder holder, MessageBase message, Resource resource) {
        String url = resource.absoluteUrl(message.getMediaUrl());
        holder.autoSizeImageView.setImageUrl(url);
    }

    public static void bindMessageToTextViewHolder(MessageBase message, final TextViewHolder textViewHolder, Resource resource, final String currentUserId, final OnMessageInteractionListener listener) {
        PublicProfile owner = message.getOwner();

        textViewHolder.item = message;
        textViewHolder.displayNameView.setText(owner.getDisplayName());
        String url = resource.absoluteUrl(owner.getAvatarUrl());
        Picasso.with(textViewHolder.root.getContext()).load(url).into(textViewHolder.avatarView);
        textViewHolder.timestampView.setText(DateTimeUtils.getTimestamp(textViewHolder.root.getContext(), message.getTimestamp()));
        textViewHolder.textContentView.setText(message.getText());

        showCurrentUserMessageBar(message, textViewHolder, currentUserId);

        textViewHolder.directMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnDirectMessageClick(listener, textViewHolder);
            }
        });
        textViewHolder.voteMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnVoteMessageClick(listener, textViewHolder);
            }
        });
        textViewHolder.moreOptionView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnEditMessageClick(textViewHolder, currentUserId, listener);
            }
        });
        textViewHolder.deleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnDeleteMessageClick(textViewHolder, listener);
            }
        });
    }

    public static void unbindMessageToTextViewHolder(TextViewHolder textViewHolder) {
        textViewHolder.directMessageView.setOnClickListener(null);
        textViewHolder.voteMessageView.setOnClickListener(null);
        textViewHolder.moreOptionView.setOnClickListener(null);
        textViewHolder.deleteView.setOnClickListener(null);
    }

    public static void fireOnDeleteMessageClick(final TextViewHolder textViewHolder, final OnMessageInteractionListener listener) {
        if (textViewHolder.item.getId() < 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(textViewHolder.itemView.getContext());
            builder.setMessage("Your message is posting to server, wait a few minutes and try again.");
            builder.show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(textViewHolder.itemView.getContext());
        builder.setMessage("Delete this message, are you sure?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (listener != null)
                    listener.onDeleteMessageClick(textViewHolder.item);
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    public static void fireOnEditMessageClick(final TextViewHolder textViewHolder, final String currentUserId, final OnMessageInteractionListener listener) {
        showEditMode(textViewHolder, currentUserId, true);

        textViewHolder.ignoreEditView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnIgnoreChangeClick(textViewHolder, currentUserId);
            }
        });
        textViewHolder.applyEditView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fireOnApplyChangeClick(textViewHolder, currentUserId, listener);
            }
        });
    }

    public static void fireOnApplyChangeClick(TextViewHolder textViewHolder, String currentUserId, OnMessageInteractionListener listener) {
        String text = textViewHolder.editTextContentView.getText().toString();
        text = text.trim();

        if (text.length() == 0) {
            Toast.makeText(textViewHolder.itemView.getContext(), "Your message is empty!", Toast.LENGTH_SHORT).show();
        } else {
            fireOnIgnoreChangeClick(textViewHolder, currentUserId);
            textViewHolder.textContentView.setText(text);
            MessageBase messageBase = textViewHolder.item;
            messageBase.setText(text);
            listener.onUpdateMessageClick(messageBase);
        }
    }

    public static void fireOnIgnoreChangeClick(TextViewHolder textViewHolder, String currentUserId) {
        showEditMode(textViewHolder, currentUserId, false);
    }

    public static void fireOnVoteMessageClick(OnMessageInteractionListener listener, TextViewHolder textViewHolder) {
        if (null != listener)
            listener.onVoteMessageClick(textViewHolder.item);
    }

    public static void fireOnDirectMessageClick(OnMessageInteractionListener listener, TextViewHolder textViewHolder) {
        if (null != listener)
            listener.onDirectMessageClick(textViewHolder.item);
    }

    private static void showCurrentUserMessageBar(MessageBase message, TextViewHolder textViewHolder, String currentUserId) {
        if (message.getOwner().getId().equals(currentUserId)) {
            textViewHolder.voteMessageView.setVisibility(View.GONE);
            textViewHolder.directMessageView.setVisibility(View.GONE);
            textViewHolder.moreOptionView.setVisibility(View.VISIBLE);
            textViewHolder.deleteView.setVisibility(View.VISIBLE);
        } else {
            textViewHolder.voteMessageView.setVisibility(View.VISIBLE);
            textViewHolder.directMessageView.setVisibility(View.VISIBLE);
            textViewHolder.moreOptionView.setVisibility(View.GONE);
            textViewHolder.deleteView.setVisibility(View.GONE);
        }
    }

    private static void showEditMode(TextViewHolder textViewHolder, String currentUserId, boolean isEditMode) {
        if (isEditMode) {
            textViewHolder.voteMessageView.setVisibility(View.GONE);
            textViewHolder.directMessageView.setVisibility(View.GONE);
            textViewHolder.moreOptionView.setVisibility(View.GONE);
            textViewHolder.deleteView.setVisibility(View.GONE);
            textViewHolder.ignoreEditView.setVisibility(View.VISIBLE);
            textViewHolder.applyEditView.setVisibility(View.VISIBLE);

            textViewHolder.editTextContentView.setVisibility(View.VISIBLE);
            textViewHolder.textContentView.setVisibility(View.GONE);
            textViewHolder.editTextContentView.setText(textViewHolder.textContentView.getText());

            if (textViewHolder instanceof PhotoViewHolder) {
                PhotoViewHolder photoViewHolder = (PhotoViewHolder) textViewHolder;
                photoViewHolder.autoSizeImageView.setVisibility(View.GONE);
            }
        } else {
            textViewHolder.ignoreEditView.setVisibility(View.GONE);
            textViewHolder.applyEditView.setVisibility(View.GONE);

            textViewHolder.editTextContentView.setVisibility(View.GONE);
            textViewHolder.textContentView.setVisibility(View.VISIBLE);

            if (textViewHolder instanceof PhotoViewHolder) {
                PhotoViewHolder photoViewHolder = (PhotoViewHolder) textViewHolder;
                photoViewHolder.autoSizeImageView.setVisibility(View.VISIBLE);
            }

            InputMethodManager inputMethodManager = (InputMethodManager) textViewHolder.itemView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(textViewHolder.editTextContentView.getWindowToken(), 0);

            showCurrentUserMessageBar(textViewHolder.item, textViewHolder, currentUserId);
        }
    }

    public static class TextViewHolder extends RecyclerView.ViewHolder {
        final View root;
        final CircleImageView avatarView;
        final TextView displayNameView;
        final TextView timestampView;
        final TextView textContentView;
        public final View directMessageView;
        public final View voteMessageView;
        public final View interactionView;
        public final View moreOptionView;
        public final View deleteView;
        final TextView editTextContentView;
        public final View ignoreEditView;
        public final View applyEditView;

        public MessageBase item;

        public TextViewHolder(View view) {
            super(view);
            root = view;
            displayNameView = ButterKnife.findById(view, R.id.display_name_view);
            timestampView = ButterKnife.findById(view, R.id.timestamp_view);
            avatarView = ButterKnife.findById(view, R.id.avatar_view);
            textContentView = ButterKnife.findById(view, R.id.text_content_view);
            directMessageView = ButterKnife.findById(view, R.id.direct_message_view);
            voteMessageView = ButterKnife.findById(view, R.id.vote_message_view);
            interactionView = ButterKnife.findById(view, R.id.interaction_layout);
            moreOptionView = ButterKnife.findById(view, R.id.more_option_message_view);
            editTextContentView = ButterKnife.findById(view, R.id.edit_text_content_view);
            deleteView = ButterKnife.findById(view, R.id.delete_message_view);
            ignoreEditView = ButterKnife.findById(view, R.id.ignore_change_view);
            applyEditView = ButterKnife.findById(view, R.id.apply_change_view);
        }
    }

    public static class PhotoViewHolder extends TextViewHolder {
        final AutoSizeImageView autoSizeImageView;

        public PhotoViewHolder(View view) {
            super(view);
            autoSizeImageView = ButterKnife.findById(view, R.id.image_view);
        }
    }

    public static class VideoViewHolder extends TextViewHolder {
        final RichVideoView richVideoView;

        VideoViewHolder(View view) {
            super(view);
            richVideoView = ButterKnife.findById(view, R.id.video_view);
        }
    }
}


text:
Groups <button type="button" data-toggle="modal" data-target="#manage-permissions-modal" class="btn btn-link btn-manage-permissions">Manage Permissions</button><button type="button" class="btn btn-primary btn-create-group pull-right">Create Group</button>

<?php if($groups != array()): ?>

      Name
      Abbreviation
      Members
      Action

      <?php foreach($groups as $pos => $group): ?>
      <tr class="<?php echo ($pos % 2 == 0) ? 'odd' : 'even'; ?>">
        <?php echo $group->getName(); ?>
        <?php echo $group->getAbbreviation(); ?>
        <?php echo $group->getMemberCount(); ?>
        <a href="/admin/group/detail/id/<?php echo $group->getId(); ?>">view

      <?php endforeach; ?>

<?php else: ?>
  There are no groups to display
<?php endif; ?>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Manage Permissions

          <button type="button" class="close message-close" aria-hidden="true">×</button>

        <form class="form-inline" role="form">

            Name
            <input type="text" class="form-control" id="permission-name" name="permission-name" placeholder="Name">

            Description
            <input type="text" class="form-control" id="permission-description" name="permission-description" placeholder="Description">

          <button type="submit" class="btn btn-primary btn-create-permission">Create Permission</button>
        </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>