text:
package dk.muj.mujlib.util;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.*;

public class MCollectionsTest
{
	private static final Integer[] arr = {1, 2, 3, 43, 2456, 2645};

	@Test
	public void testSet() throws Exception
	{
		Set<Integer> set = MCollections.set(arr);

		// Size
		assertEquals(arr.length, set.size());

		// Contains
		for (Integer e : arr)
		{
			assertTrue(set.contains(e));
		}
		assertTrue(set.containsAll(MCollections.list(arr)));

		// Equals
		assertTrue(set.equals(MCollections.set(arr)));

		// Empty
		assertTrue(MCollections.set().isEmpty());

		// Ensure no UnsupportedOperations is thrown.
		assertTrue(set.add(54));

		assertTrue(set.remove(1));

	}

	@Test
	public void testLinkedSet() throws Exception
	{
		Set<Integer> set = MCollections.linkedSet(arr);

		// Size
		assertEquals(arr.length, set.size());

		// Contains
		for (Integer e : arr)
		{
			assertTrue(set.contains(e));
		}
		assertTrue(set.containsAll(MCollections.list(arr)));

		// Order
		int i = 0;
		for (Integer e : set)
		{
			assertEquals(set.toString(), e, arr[i]);
			i++;
		}

		// Equals
		assertTrue(set.equals(MCollections.set(arr)));

		// Empty
		assertTrue(MCollections.set().isEmpty());

		// Ensure no UnsupportedOperations is thrown.
		assertTrue(set.add(54));

		assertTrue(set.remove(1));
	}

	@Test
	public void testList() throws Exception
	{
		List<Integer> list = MCollections.list(arr);

		// Size
		assertEquals(arr.length, list.size());

		// Contains
		for (Integer e : arr)
		{
			assertTrue(list.contains(e));
		}
		assertTrue(list.containsAll(MCollections.list(arr)));

		// Order
		int i = 0;
		for (Integer e : list)
		{
			assertEquals(list.toString(), e, arr[i]);
			i++;
		}

		// Equals
		assertTrue(list.equals(Arrays.asList(arr)));

		// Empty
		assertTrue(MCollections.set().isEmpty());

		// Ensure no UnsupportedOperations is thrown.
		assertTrue(list.add(54));

		assertTrue(list.remove(Integer.valueOf(1)));
	}

	@Test
	public void testMap() throws Exception
	{
		Map<String, String> map = MCollections.map(String.class, String.class,
			"key1", "value1",
			"key2", "value2",
			"key3", "value3",
			"key4", "value4",
			"key5", "value5",
			"key6", "value6"
		);
		assertEquals("value1", map.get("key1"));
		assertEquals("value2", map.get("key2"));
		assertEquals("value3", map.get("key3"));
		assertEquals("value4", map.get("key4"));
		assertEquals("value5", map.get("key5"));
		assertEquals("value6", map.get("key6"));
		assertEquals(6, map.size());

		assertNull(map.put("key7", "value7"));
		assertEquals(7, map.size());

		assertEquals("value5", map.remove("key5"));
	}

	@Test
	public void testRangeAscending() throws Exception
	{
		List<Integer> list = MCollections.range(10);
		assertEquals(10, list.size());

		// Ensure contains, and stuff
		for (int i = 0; i < 10; i++)
		{
			assertEquals(i, list.get(i).intValue());
			assertEquals(i, list.indexOf(i));
			assertEquals(i, list.lastIndexOf(i));
			assertTrue(list.contains(i));
		}

		// Ensure doesn't contain
		for (int i = 10; i < 20; i++)
		{
			assertEquals(-1, list.indexOf(i));
			assertEquals(-1, list.lastIndexOf(i));
			assertFalse(list.contains(i));
		}

		// Ensure doesn't contain
		for (int i = -10; i < 0; i++)
		{
			assertEquals(-1, list.indexOf(i));
			assertEquals(-1, list.lastIndexOf(i));
			assertFalse(list.contains(i));
		}

		// Test sublist
		List<Integer> subList = list.subList(2, 5);
		assertEquals(3, subList.size());

		// Get index
		assertEquals(2, subList.get(0).intValue());
		assertEquals(3, subList.get(1).intValue());
		assertEquals(4, subList.get(2).intValue());

		// Index of
		assertEquals(0, subList.indexOf(2));
		assertEquals(1, subList.indexOf(3));
		assertEquals(2, subList.indexOf(4));
		assertEquals(-1, subList.indexOf(1));
		assertEquals(-1, subList.indexOf(0));
		assertEquals(-1, subList.indexOf(5));

		// Last index of
		assertEquals(0, subList.lastIndexOf(2));
		assertEquals(1, subList.lastIndexOf(3));
		assertEquals(2, subList.lastIndexOf(4));
		assertEquals(-1, subList.lastIndexOf(1));
		assertEquals(- 1, subList.lastIndexOf(0));
		assertEquals(- 1, subList.lastIndexOf(5));

		// Contains
		assertTrue(subList.contains(2));
		assertTrue(subList.contains(3));
		assertTrue(subList.contains(4));
		assertFalse(subList.contains(1));
		assertFalse(subList.contains(0));
		assertFalse(subList.contains(5));
	}

	@Test
	public void testRangeDescending() throws Exception
	{
		List<Integer> list = MCollections.range(10, 0);
		assertEquals(10, list.size());

		// Ensure contains, and stuff
		for (int i = 10, j = 0; i > 0; i--, j++)
		{
			assertEquals(i, list.get(j).intValue());
			assertEquals(j, list.indexOf(i));
			assertEquals(j, list.lastIndexOf(i));
			assertTrue(list.contains(i));
		}

		// Ensure doesn't contain
		for (int i = 11; i < 20; i++)
		{
			assertEquals(-1, list.indexOf(i));
			assertEquals(-1, list.lastIndexOf(i));
			assertFalse(list.contains(i));
		}

		// Ensure doesn't contain
		for (int i = -10; i < 0; i++)
		{
			assertEquals(-1, list.indexOf(i));
			assertEquals(-1, list.lastIndexOf(i));
			assertFalse(list.contains(i));
		}

		// Test sublist
		List<Integer> subList = list.subList(2, 5);
		assertEquals(3, subList.size());

		// Get index
		assertEquals(8, subList.get(0).intValue());
		assertEquals(7, subList.get(1).intValue());
		assertEquals(6, subList.get(2).intValue());

		// Index of
		assertEquals(0, subList.indexOf(8));
		assertEquals(1, subList.indexOf(7));
		assertEquals(2, subList.indexOf(6));
		assertEquals(-1, subList.indexOf(9));
		assertEquals(-1, subList.indexOf(10));
		assertEquals(-1, subList.indexOf(5));

		// Last index of
		assertEquals(0, subList.lastIndexOf(8));
		assertEquals(1, subList.lastIndexOf(7));
		assertEquals(2, subList.lastIndexOf(6));
		assertEquals(-1, subList.lastIndexOf(9));
		assertEquals(-1, subList.lastIndexOf(10));
		assertEquals(-1, subList.lastIndexOf(5));

		// Contains
		assertTrue(subList.contains(8));
		assertTrue(subList.contains(7));
		assertTrue(subList.contains(6));
		assertFalse(subList.contains(9));
		assertFalse(subList.contains(10));
		assertFalse(subList.contains(5));

	}

}


text:
Imports System
Imports System.Configuration
Imports System.Text.RegularExpressions

Namespace SecuritySwitch.Configuration

	''' <summary>
	''' The possible ways to ignore HTTP handlers.
	''' </summary>
	Public Enum IgnoreHandlers
		''' <summary>
		''' Indicates that the module should ignore the built-in HTTP handlers.
		''' <list type="bullet">
		'''		<item>Trace.axd</item>
		'''		<item>WebResource.axd</item>
		''' </list>
		''' </summary>
		BuiltIn

		''' <summary>
		''' Indicates that the module should ignore all files with extensions corresponding
		''' to the standard for HTTP handlers. Currently, that is .axd files.
		''' </summary>
		WithStandardExtensions

		''' <summary>
		''' Indicates that the module will not ignore handlers unless specifically
		''' specified in the files or directories entries.
		''' </summary>
		''' <remarks>
		''' This was the default behavior prior to version 3.1.
		''' </remarks>
		None

	End Enum

	''' <summary>
	''' The different modes supported for the <securitySwitch> configuration section.
	''' </summary>
	Public Enum Mode

		''' <summary>
		''' Indicates that web page security is on and all requests should be monitored.
		''' </summary>
		[On]

		''' <summary>
		''' Only remote requests are to be monitored.
		''' </summary>
		RemoteOnly

		''' <summary>
		''' Only local requests are to be monitored.
		''' </summary>
		LocalOnly

		''' <summary>
		''' Web page security is off and no monitoring should occur.
		''' </summary>
		Off

	End Enum

	''' <summary>
	''' The different modes for bypassing security warnings.
	''' </summary>
	Public Enum SecurityWarningBypassMode

		''' <summary>
		''' Always bypass security warnings when switching to an unencrypted page.
		''' </summary>
		AlwaysBypass

		''' <summary>
		''' Only bypass security warnings when switching to an unencrypted page if the proper query parameter is present.
		''' </summary>
		BypassWithQueryParam

		''' <summary>
		''' Never bypass security warnings when switching to an unencrypted page.
		''' </summary>
		NeverBypass

	End Enum

	''' <summary>
	''' Contains the settings of a <securitySwitch> configuration section.
	''' </summary>
	Public Class Settings
		Inherits ConfigurationSection

		''' <summary>
		''' Creates an instance of Settings.
		''' </summary>
		Public Sub New()
			MyBase.New()
		End Sub

#Region "Properties"

		''' <summary>
		''' Gets or sets the name of the query parameter that will indicate to the module to bypass
		''' any security warning if WarningBypassMode = BypassWithQueryParam.
		''' </summary>
		<ConfigurationProperty("bypassQueryParamName")> _
		Public Property BypassQueryParamName() As String
			Get
				Return CStr(Me("bypassQueryParamName"))
			End Get
			Set(ByVal value As String)
				Me("bypassQueryParamName") = value
			End Set
		End Property

		''' <summary>
		''' Gets or sets the path to a URI for encrypted redirections, if any.
		''' </summary>
		<ConfigurationProperty("encryptedUri"), RegexStringValidator("^(?:|(?:https://)?[\w\-][\w\.\-,]*(?:\:\d+)?(?:/[\w\.\-]+)*/?)$")> _
		Public Property EncryptedUri() As String
			Get
				Return CStr(Me("encryptedUri"))
			End Get
			Set(ByVal value As String)
				If Not String.IsNullOrEmpty(value) Then
					Me("encryptedUri") = value
				Else
					Me("encryptedUri") = Nothing
				End If
			End Set
		End Property

		''' <summary>
		''' Gets or sets a flag indicating how to ignore HTTP handlers, if at all.
		''' </summary>
		<ConfigurationProperty("ignoreHandlers", DefaultValue:=IgnoreHandlers.BuiltIn)> _
		Public Property IgnoreHandlers() As IgnoreHandlers
			Get
				Return CType(Me("ignoreHandlers"), IgnoreHandlers)
			End Get
			Set(ByVal value As IgnoreHandlers)
				Me("ignoreHandlers") = value
			End Set
		End Property

		''' <summary>
		''' Gets or sets a flag indicating whether or not to maintain the current path when redirecting
		''' to a different host.
		''' </summary>
		<ConfigurationProperty("maintainPath", DefaultValue:=True)> _
		Public Property MaintainPath() As Boolean
			Get
				Return CBool(Me("maintainPath"))
			End Get
			Set(ByVal value As Boolean)
				Me("maintainPath") = value
			End Set
		End Property

		''' <summary>
		''' Gets or sets the mode indicating how the secure switch settings are handled.
		''' </summary>
		<ConfigurationProperty("mode", DefaultValue:=Mode.On)> _
		Public Property Mode() As Mode
			Get
				Return CType(Me("mode"), Mode)
			End Get
			Set(ByVal value As Mode)
				Me("mode") = value
			End Set
		End Property

		''' <summary>
		''' Gets the collection of directory settings read from the configuration section.
		''' </summary>
		<ConfigurationProperty("directories")> _
		Public ReadOnly Property Directories() As DirectorySettingCollection
			Get
				Return CType(Me("directories"), DirectorySettingCollection)
			End Get
		End Property

		''' <summary>
		''' Gets the collection of file settings read from the configuration section.
		''' </summary>
		<ConfigurationProperty("files")> _
		Public ReadOnly Property Files() As FileSettingCollection
			Get
				Return CType(Me("files"), FileSettingCollection)
			End Get
		End Property

		''' <summary>
		''' Gets or sets the path to a URI for unencrypted redirections, if any.
		''' </summary>
		<ConfigurationProperty("unencryptedUri"), RegexStringValidator("^(?:|(?:http://)?[\w\-][\w\.\-,]*(?:\:\d+)?(?:/[\w\.\-]+)*/?)$")> _
		Public Property UnencryptedUri() As String
			Get
				Return CStr(Me("unencryptedUri"))
			End Get
			Set(ByVal value As String)
				If Not String.IsNullOrEmpty(value) Then
					Me("unencryptedUri") = value
				Else
					Me("unencryptedUri") = Nothing
				End If
			End Set
		End Property

		''' <summary>
		''' Gets or sets the bypass mode indicating whether or not to bypass security warnings
		''' when switching to a unencrypted page.
		''' </summary>
		<ConfigurationProperty("warningBypassMode", DefaultValue:=SecurityWarningBypassMode.BypassWithQueryParam)> _
		Public Property WarningBypassMode() As SecurityWarningBypassMode
			Get
				Return CType(Me("warningBypassMode"), SecurityWarningBypassMode)
			End Get
			Set(ByVal value As SecurityWarningBypassMode)
				Me("warningBypassMode") = value
			End Set
		End Property

		''' <summary>
		''' This property is for internal use and is not meant to be set.
		''' </summary>
		<ConfigurationProperty("xmlns")> _
		Public Property Xmlns() As String
			Get
				Return CStr(Me("xmlns"))
			End Get
			Set(ByVal value As String)
				Me("xmlns") = value
			End Set
		End Property

#End Region

	End Class

End Namespace

redpajama_set_name: RedPajamaGithub


text:
require "test_helper"

# Single controller test.
class NameSearch4TypeCultHybSetsComCultFlagToTrueT < ActionController::TestCase
  tests SearchController

  test "editor search 4 name type cult hybrid should set cultivar flag true" do
    skip # Expect this to be no longer needed under revised search.
    cultivar_hybrid = names(:a_cultivar_hybrid)
    # Set the common-and-cultivar flag to false.
    get(:index,
        { "query_on" => "name",
          "query" => "nt:cultivar hybrid",
          "query_common_and_cultivar" => "f",
          "query_limit" => "100" },
        username: "fred",
        user_full_name: "Fred Jones",
        groups: ["edit"])
    assert_response :success
    assert_select "input.checkbox[type=checkbox]
                  [id=query_common_and_cultivar][value=t]",
                  true,
                  "The query-common-and-cultivar checkbox should be true"
    assert_select "tr[id=search-result-#{cultivar_hybrid.id}]",
                  true,
                  "Should find one cultivar hybrid at least"
  end
end


text:
/**
 * Generates all SVG and PNG logo variations from a single SVG template.
 *
 * The generated files are stored at 'assets' (or whatever value of '*_dist' variables) folder.
 * There are 4 types of output that can be used (copied to desired location):
 *
 * (1) SVG files located at 'assets/svg' and generated directly from 'src/template.svg'
 * (2) PNG files located at 'assets/png' and generated from all the SVG files from previous step
 * (3) ICO files located at 'assets/ico' and generated from 'assets/png/logo_512@2x.png'
 * (4) SVG SPRITE files located at 'assets/sprite' in two format, symbol and css,
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Adnan M.Sagar, PhD. <adnan@websemantics.ca>
 */

var gulp           = require("gulp");
var template       = require("gulp-nunjucks-render");
var rename         = require("gulp-rename");
var minify         = require("gulp-svgmin");
var sprite 	  	   = require("gulp-svg-sprite");
var svg2png 	     = require("gulp-svg2png");
var favicons       = require("gulp-favicons");

var svg_template   = 'src/template.svg';
var index_template = 'src/template.html';
var index_dist 	   = 'assets/';
var png_dist 	     = 'assets/png/';
var svg_dist 	     = 'assets/svg/';
var ico_dist 	     = 'assets/ico/';
var sprite_dist    = 'assets/sprite/';

var white_fill     = '#ffffff';
var brand_fill     = '#61269E';

/* Preview index.html */
var html_data      = {svg:[],png:[],gh_pages: 'https://raw.githubusercontent.com/pyrocms/branding/gh-pages'};

/*
	List of all required PNG files and sizes for both, logo and logo+text
	key : file name
	value : 'svg' and image configs
*/

var logo_variants  = {
  'logo-inverted' : {
    svg : {
       symbol_fill: white_fill,
       background_fill: brand_fill,
       scale: 0.1
    },
    img : {
      height : [512,128,32,16]
    }
  },
  'logo' : {
    svg : {
       symbol_fill: brand_fill,
       scale: 0.1
    },
    img : {
      height : [512,128,32,16]
    }
  },
  'logo-full' : {
    svg : {
       symbol_fill: brand_fill
    },
    img : {
      height :[512,128,32,16]
    }
  },
  'logo-text' : {
    svg : {
      show_text: true,
      symbol_fill: brand_fill,
      text_fill: brand_fill,
      scale: 0.5
    },
    img : {
      height :[512,128,32,16]
    }
  },
  'logo-text-full' : {
    svg : {
      show_text: true,
      symbol_fill: brand_fill,
      text_fill: brand_fill,
    },
    img : {
      height :[512,128,32,16]
    }
  },
  'logo-text-inverted' : {
    svg : {
      show_text: true,
      symbol_fill: white_fill,
      text_fill: white_fill,
      background_fill: brand_fill,
      scale: 0.5
    },
    img : {
      height :[512,128,32,16]
    }
   }
	};

  /*
    Info used to generate ICO files
  */
  var fav_icon = {
          appName: "PyroCMS",
          appDescription: "Built for everyone",
          developerName: "Ryan Thompson",
          developerURL: "https://github.com/RyanThompson",
          background: "#fff",
          path: ico_dist,
          url: "http://pyrocms.com/",
          display: "standalone",
          orientation: "portrait",
          version: 1.0,
          logging: false,
          online: false,
          replace: true
  };

  /*
    Config params for the SVG Sprite Generator
  */
  var svg_sprite_config   = {
      mode                : {
          view            : {
              bust        : false,
              render      : {
                  css    : true
              }
          },
          symbol          : true
      }
  };

/**
 * Generate SVG files from the logo template
 *
 * @param {filename} string, the output filename
 * @param {data} array, the template data
 * @return {stream}.
 */

function svg(filename, data)
{
    data = JSON.parse(JSON.stringify(data)); /* clone */

    /* Oddly behaving scale factor, range 1 (full size) to 0.1, smallest )*/
    var scale                = data['scale'] || 1;

    data['text_fill']        = data['text_fill'] || '';
    data['width']            = data['width'] || (data['show_text'] ? 1405 : 512);
    data['height']           = data['height'] || 512;
    data['show_text']        = data['show_text'] || false;
    data['background_fill']  = data['background_fill'] || 'none';
    data['transform_symbol'] = data['show_text'] ? 'translate(950)' : 'translate(0)';   ;

    data['viewbox_x']        = data['viewbox_x'] || 0;
    data['viewbox_y']        = data['viewbox_y'] || 0;
    data['viewbox_width']    = data['viewbox_width'] || data['width'];
    data['viewbox_height']   = data['viewbox_height'] || data['height'];

    /* Apply the scale via the document viewbox */
    data['viewbox_x']        = data['viewbox_x'] - (1-scale) * data['width'] / 2;
    data['viewbox_y']        = data['viewbox_y'] - (1-scale) * data['height'] / 2;
    data['viewbox_width']    = data['width'] + data['width'] * (1-scale);
    data['viewbox_height']   = data['height'] + data['height'] * (1-scale);

    /* Append file */ html_data.svg.push(filename);

  	return gulp.src(svg_template)
		.pipe(template({ext:'.svg', data: data}))
		.pipe(minify())
		.pipe(rename(filename + '.svg'))
		.pipe(gulp.dest(svg_dist));
}

/**
 * Generate PNG file from an svg image
 *
 * @param {filename} string, the svg filename without extension
 * @param {height} int, the height in pixels
 * @return {void}.
 */

function png(filename, height)
{
  var scale = height / 512;

  /* Append file */ html_data.png.push({name: filename + '_'+ height , height: height });

  /* Generate normal image */
    gulp.src(svg_dist+filename + '.svg')
        .pipe(svg2png([scale]))
        .pipe(rename(filename + '_'+ height + '.png'))
        .pipe(gulp.dest(png_dist));

    /* Append file */ html_data.png.push({name: filename + '_'+ height +'@2x', height: height });

    /* Generate retina image */
    return gulp.src(svg_dist+filename + '.svg')
        .pipe(svg2png([scale * 2]))
        .pipe(rename(filename + '_' + height +'@2x.png'))
        .pipe(gulp.dest(png_dist));

};

// ---------------------------------------------------
// TASK : default - Generate index.html
// ---------------------------------------------------

gulp.task('default', ['process-sprites'], function() {

  return gulp.src(index_template)
  .pipe(template({ext:'.html', data: html_data}))
  .pipe(rename('index.html'))
  .pipe(gulp.dest(index_dist));

});

// ---------------------------------------------------
// TASK : process SVG sprites
// ---------------------------------------------------

gulp.task('process-sprites', ['process-favicons'], function() {

	return gulp
			.src(svg_dist+'*.svg')
			.pipe(sprite(svg_sprite_config ))
			.pipe(gulp.dest(sprite_dist));

});

// ---------------------------------------------------
// TASK : process-favicons
// ---------------------------------------------------

gulp.task('process-favicons', ['process-png'], function() {

    return gulp
		    .src(png_dist+'logo-inverted_512@2x.png') /* or logo_512@2x.png */
		    .pipe(favicons(fav_icon))
		    .on('error', function(){})
		    .pipe(gulp.dest(ico_dist));

});

// ---------------------------------------------------
// TASK : process-png
// ---------------------------------------------------

gulp.task('process-png', ['process-svg'], function() {

	var stream = gulp;

	/* Generate all PNG files */
	for (var filename in logo_variants) {

		var img = logo_variants[filename].img;

		/* Generate all icons */
		for (var i in img.height) {
			stream = png(filename, img.height[i]);
		}

	}

	return stream;
});

// ---------------------------------------------------
// TASK : process-svg
// ---------------------------------------------------

gulp.task('process-svg', function() {

  var stream = gulp;

	for (var filename in logo_variants) {
		stream = svg(filename , logo_variants[filename].svg);
	}

	return stream;
});


text:
package com.amazonaws.services.honeycode.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ErrorCode {

    ACCESS_DENIED("ACCESS_DENIED"),
    INVALID_URL_ERROR("INVALID_URL_ERROR"),
    INVALID_IMPORT_OPTIONS_ERROR("INVALID_IMPORT_OPTIONS_ERROR"),
    INVALID_TABLE_ID_ERROR("INVALID_TABLE_ID_ERROR"),
    INVALID_TABLE_COLUMN_ID_ERROR("INVALID_TABLE_COLUMN_ID_ERROR"),
    TABLE_NOT_FOUND_ERROR("TABLE_NOT_FOUND_ERROR"),
    FILE_EMPTY_ERROR("FILE_EMPTY_ERROR"),
    INVALID_FILE_TYPE_ERROR("INVALID_FILE_TYPE_ERROR"),
    FILE_PARSING_ERROR("FILE_PARSING_ERROR"),
    FILE_SIZE_LIMIT_ERROR("FILE_SIZE_LIMIT_ERROR"),
    FILE_NOT_FOUND_ERROR("FILE_NOT_FOUND_ERROR"),
    UNKNOWN_ERROR("UNKNOWN_ERROR"),
    RESOURCE_NOT_FOUND_ERROR("RESOURCE_NOT_FOUND_ERROR"),
    SYSTEM_LIMIT_ERROR("SYSTEM_LIMIT_ERROR");

    private String value;

    private ErrorCode(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ErrorCode corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ErrorCode fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ErrorCode enumEntry : ErrorCode.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
using namespace std;

int main(int argc, char *argv[]) {
	ArgumentManager am(argc, argv);
	string op = am.get("operation");
	string str = am.get("storage");
	string rec = am.get("recursive");
	string a = am.get("A");
	string b = am.get("B");
	string c = am.get("result");

	//preloads data into memory instead of copy/pasting code 4 times;
	string fileA = a.c_str(), fileB = b.c_str(), output = c.c_str();
	string operation = op.c_str(), storage = str.c_str(), recursive = rec.c_str();

		vector< vector<double> > mat, mat2, mat3;
		int rowsA = numLines(fileA);
		int rowsB = numLines(fileB);
		int i = 0, j = 0;					//i j values for the recursive functions
		matA = NULL, matB = NULL, matC = NULL;			//initilizes the head of all lists to NULL //GLOBAL VARIABLE

		//reads file into arrays
		mat = readFile(fileA, rowsA);
		mat2 = readFile(fileB, rowsB);

		//reads file into doubly linked lists
		readFileLL(fileA, matA);
		readFileLL(fileB, matB);

		if((str == "array" || str == "Array") && (rec == "N" || rec == "n"))
			add(mat, rowsA, mat2, rowsB, output);
		if ((str == "array" || str == "Array") && (rec == "Y" || rec == "y")) {
			int i = 0, j = 0;
			radd(mat, rowsA, mat2, rowsB, output, i, j);
		}
		if((str == "LinkedList" || str == "linkedlist") && (rec == "N" || rec == "n"))
				addLL(matA, matB, mat, rowsA, mat2, rowsB, output);
		if ((str == "LinkedList" || str == "linkedlist") && (rec == "Y" || rec == "y"))
				raddLL(matA, matB, mat, rowsA, mat2, rowsB, output);

	return 0;
}


text:
import datetime
import json
import csv
import os
from flask import Flask, render_template, url_for, redirect, request, flash
from flask import Response

app = Flask(__name__)
app.config.update(dict(Tracker=None))

class TimeTrackerMessage(object):
    def __init__(self, success, message):
        self.success = success
        self.message = message

    def as_json(self):
        resp = {'success':self.success, 'message': self.message}
        return json.dumps(resp)

class TimeTracker(object):
    def __init__(self, subjects, timer_file, logger_file):
        self.subjects = subjects
        self.timer_file = timer_file
        self.logger_file = logger_file
        self.start_time = None

    def __str__(self):
        return "TimeTracker: timer_file: %s, logger_file: %s, subjects: %s" % (
            self.timer_file,
            self.logger_file,
            ", ".join([s.name for s in self.subjects])
        )

    def start_timer(self):
        resp = None
        if self.start_time is None:
            self.start_time = datetime.datetime.now()
            # Write the time to a temp file as a backup
            with open("/tmp/timetracker.tmp", "w") as tmpfile:
                tmpfile.write(self.start_time.isoformat())
            resp = TimeTrackerMessage(True, "Timer started")
        else:
            resp = TimeTrackerMessage(False, "You've already started the timer")
        return resp

    def stop_timer(self):
        resp = None
        if self.start_time is not None:
            times = [
                self.start_time.isoformat(),
                datetime.datetime.now().isoformat()
            ]
            with open(self.timer_file, "a") as tfile:
                csvwriter = csv.writer(tfile)
                csvwriter.writerow(times)
            self.start_time = None
            resp = TimeTrackerMessage(True, "Timer stopped")
        else:
            if os.path.exists("/tmp/timetracker.tmp"):
                times = [datetime.datetime.now().isoformat()]
                with open("/tmp/timetracker.tmp", "r") as tmpfile:
                    times.append(datetime.datetime.strptime(
                        tmpfile.read(),
                        "%Y-%m-%dT%H:%M:%S.%f"
                    ))
                    times.reverse()
                with open(self.timer_file, "a") as tfile:
                    csvwriter = csv.writer(tfile)
                    csvwriter.writerow(times)
                self.start_time = None
                os.remove("/tmp/timetracker.tmp")
                resp = TimeTrackerMessage(True, "Timer stopped")
            else:
                resp = TimeTrackerMessage(False, "You haven't started the timer yet.")
        return resp

    def log_subject(self, subject, minutes_worked):
        resp = None
        if self.start_time is None:
            resp = TimeTrackerMessage(False, "You haven't started the timer yet.")
        else:
            log_entry = [
                minutes_worked,
                datetime.datetime.now().isoformat(),
                subject
            ]
            with open(self.logger_file, "a") as lfile:
                csvwriter = csv.writer(lfile)
                csvwriter.writerow(log_entry)
            resp = TimeTrackerMessage(
                True,
                "%s minutes of %s logged" % (minutes_worked, subject)
            )
        return resp

@app.route("/")
def index():
    subjects = app.config.Tracker.subjects
    return render_template(
        "index.html",
        subjects=subjects
    )

@app.route("/start-timer", methods=["POST"])
def start_timer():
    resp = app.config.Tracker.start_timer()
    flash(resp.message)
    return redirect(url_for("index"))

@app.route("/stop-timer", methods=["POST"])
def stop_timer():
    resp = app.config.Tracker.stop_timer()
    flash(resp.message)
    return redirect(url_for("index"))

@app.route("/log-subject", methods=["POST"])
def log_subject():
    resp =  app.config.Tracker.log_subject(
        request.form["subject"],
        request.form["minutes-worked"]
    )
    flash(resp.message)
    return redirect(url_for("index"))

@app.route("/api")
def api_info():
    return render_template("api.html")

@app.route("/api/subjects")
def api_subjects():
    data = app.config.Tracker.subjects
    resp = Response(json.dumps(data), mimetype='application/json')
    return resp

@app.route("/api/start-timer", methods=["POST"])
def api_start_timer():
    data = app.config.Tracker.start_timer()
    resp = Response(data.as_json(), mimetype='application/json')
    return resp

@app.route("/api/stop-timer", methods=["POST"])
def api_stop_timer():
    data = app.config.Tracker.stop_timer()
    resp = Response(data.as_json(), mimetype='application/json')
    return resp

@app.route("/api/log-subject", methods=["POST"])
def api_log_subject():
    data =  app.config.Tracker.log_subject(
        request.form["subject"],
        request.form["minutes-worked"]
    )
    resp = Response(data.as_json(), mimetype='application/json')
    return resp

def main():
    rawcfg = open("timetracker.json", "r")
    cfg = json.load(rawcfg)
    app.config.Tracker = TimeTracker(
        cfg['subjects'],
        cfg['timer-file'],
        cfg['logger-file']
    )
    with open("secret.key", "r") as sk:
        app.secret_key = sk.read()

main()


text:
#pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "modules/perception/lidar/lib/classifier/fused_classifier/type_fusion_interface.h"
#include "modules/perception/lidar/lib/classifier/fused_classifier/util.h"

namespace apollo {
namespace perception {
namespace lidar {

class CCRFOneShotTypeFusion : public BaseOneShotTypeFusion {
 public:
  bool Init(const TypeFusionInitOption& option) override;
  bool TypeFusion(const TypeFusionOption& option,
                  std::shared_ptr<perception::base::Object> object) override;
  std::string Name() const override { return "CCRFOneShotTypeFusion"; }
  bool FuseOneShotTypeProbs(
      const std::shared_ptr<perception::base::Object>& object,
      Vectord* log_prob);

 protected:
  std::map<std::string, Matrixd> smooth_matrices_;
  Matrixd confidence_smooth_matrix_;
};

class CCRFSequenceTypeFusion : public BaseSequenceTypeFusion {
 public:
  bool Init(const TypeFusionInitOption& option) override;
  bool TypeFusion(const TypeFusionOption& option,
                  TrackedObjects* tracked_objects) override;
  std::string Name() const override { return "CCRFSequenceTypeFusion"; }

 protected:
  // The fusion problem is modeled
  //     as inferring the discrete state in a chain CRFs.
  // Note, log(P({X}|O)) =
  //     sigma_i{E_unary(X_i,O)} + sigma_ij{E_pairwise(X_i,X_j)} - logZ;
  // E_unary(X_i,O) = sigma{logP(classifier)},
  // E_pairwise(X_i,X_j) = logTransition(X_i,X_j)
  // a) Maximize the sequence probability P(X_t|{X}^opt,O)
  //     based on optimal state inference.
  // b) (did not use) Maximize the marginal probability P(X_t|O)
  //     with history state integrated.

  // window version of Chain-CRFs inference
  bool FuseWithConditionalProbabilityInference(TrackedObjects* tracked_objects);
  // util
  bool RecoverFromLogProbability(Vectord* prob, std::vector<float>* dst,
                                 perception::base::ObjectType* type);

 protected:
  CCRFOneShotTypeFusion one_shot_fuser_;
  // Note all in the log space
  Matrixd transition_matrix_;

  // data member for window inference version
  std::vector<Vectord> fused_oneshot_probs_;
  std::vector<Vectord> fused_sequence_probs_;
  std::vector<Vectori> state_back_trace_;

 protected:
  double s_alpha_ = 1.8;
};

}  // namespace lidar
}  // namespace perception
}  // namespace apollo


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Bazam.Http;
using MargieBot.Utilities;
using MargieBot.WebSockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MargieBot
{
    public class Bot
    {
        #region Private properties
        private string _BotNameRegex;
        private string BotNameRegex
        {
            get
            {
                // only build the regex if we're connected - if we're not connected we won't know our bot's name or user ID
                if (_BotNameRegex == string.Empty && IsConnected)
                {
                    _BotNameRegex = new BotNameRegexComposer().ComposeFor(UserName, UserID, Aliases);
                }

                return _BotNameRegex;
            }
            set { _BotNameRegex = value; }
        }

        private Dictionary<string, string> UserNameCache { get; set; } = new Dictionary<string, string>();
        private MargieBotWebSocket WebSocket { get; set; }
        private string SlackRtmStartHelp = "https://api.slack.com/methods/rtm.start";
        #endregion

        #region Public properties
        private IEnumerable<string> _Aliases = new List<string>();
        public IEnumerable<string> Aliases
        {
            get { return _Aliases; }
            set
            {
                _Aliases = value;
                BotNameRegex = string.Empty;
            }
        }

        // TODO: think about this
        //
        // This is a List<IResponder> because I wanted the end dev to be really free to manipulate the responders programmatically. Even IList doesn't have everything I wanted (AddRange, for example),
        // so I made it a List for now.
        public List<IResponder> Responders { get; } = new List<IResponder>();

        public IReadOnlyList<SlackChatHub> ConnectedChannels
        {
            get { return ConnectedHubs.Values.Where(hub => hub.Type == SlackChatHubType.Channel).ToList(); }
        }

        public IReadOnlyList<SlackChatHub> ConnectedDMs
        {
            get { return ConnectedHubs.Values.Where(hub => hub.Type == SlackChatHubType.DM).ToList(); }
        }

        public IReadOnlyList<SlackChatHub> ConnectedGroups
        {
            get { return ConnectedHubs.Values.Where(hub => hub.Type == SlackChatHubType.Group).ToList(); }
        }

        public IReadOnlyDictionary<string, SlackChatHub> ConnectedHubs { get; private set; }

        public bool IsConnected
        {
            get { return ConnectedSince != null; }
        }

        private DateTime? _ConnectedSince = null;
        public DateTime? ConnectedSince
        {
            get { return _ConnectedSince; }
            set
            {
                if (_ConnectedSince != value)
                {
                    _ConnectedSince = value;
                    RaiseConnectionStatusChanged();
                }
            }
        }

        public Dictionary<string, object> ResponseContext { get; } = new Dictionary<string, object>();
        public string SlackKey { get; private set; }
        public string TeamID { get; private set; }
        public string TeamName { get; private set; }
        public string UserID { get; private set; }
        public string UserName { get; private set; }
        #endregion

        /// <summary>
        /// Connects this bot to Slack using the slack API key provided. Set yours up at https://yourteam.slack.com/apps/manage.
        /// </summary>
        /// <param name="slackKey">The API key the bot will use to identify itself to the Slack API.</param>
        public async Task Connect(string slackKey)
        {
            SlackKey = slackKey;

            // disconnect in case we're already connected like a crazy person
            Disconnect();

            // kill the regex for our bot's name - we'll rebuild it upon request with some of the info we get here
            BotNameRegex = string.Empty;

            // start session and get response
            var httpClient = new HttpClient();
            var json = await httpClient.GetStringAsync($"https://slack.com/api/rtm.start?token={SlackKey}");
            var jData = JObject.Parse(json);

            // Handle exceptions.

            if (! jData["ok"].Value<bool>())
            {
                var errorMessage = jData["ok"].Value<string>();
                switch (errorMessage)
                {
                    case "not_authed":
                    case "account_inactive":
                    case "invalid_auth":
                        InvalidCredentialException exIC = new InvalidCredentialException(errorMessage);
                        exIC.HelpLink = SlackRtmStartHelp;
                        throw exIC;
                    case "invalid_arg_name":
                    case "invalid_array_arg":
                    case "invalid_charset":
                    case "invalid_form_data":
                    case "invalid_post_type":
                    case "missing_post_type":
                        ArgumentException exAE = new ArgumentException(errorMessage);
                        exAE.HelpLink = SlackRtmStartHelp;
                        throw exAE;
                    case "request_timeout":
                        TimeoutException exTE = new TimeoutException(errorMessage);
                        exTE.HelpLink = SlackRtmStartHelp;
                        throw exTE;
                    default:
                      throw new Exception(errorMessage);
                }
            }

            // read various bot properties out of the response
            TeamID = jData["team"]["id"].Value<string>();
            TeamName = jData["team"]["name"].Value<string>();
            UserID = jData["self"]["id"].Value<string>();
            UserName = jData["self"]["name"].Value<string>();
            var webSocketUrl = jData["url"].Value<string>();

            // rebuild the username cache
            UserNameCache.Clear();
            foreach (JObject userObject in jData["users"])
            {
                UserNameCache.Add(userObject["id"].Value<string>(), userObject["name"].Value<string>());
            }

            // load the channels, groups, and DMs that margie's in
            Dictionary<string, SlackChatHub> hubs = new Dictionary<string, SlackChatHub>();
            ConnectedHubs = hubs;

            // channelz
            if (jData["channels"] != null)
            {
                foreach (JObject channelData in jData["channels"])
                {
                    if (!channelData["is_archived"].Value<bool>() && channelData["is_member"].Value<bool>())
                    {
                        var channel = new SlackChatHub()
                        {
                            ID = channelData["id"].Value<string>(),
                            Name = "#" + channelData["name"].Value<string>(),
                            Type = SlackChatHubType.Channel
                        };
                        hubs.Add(channel.ID, channel);
                    }
                }
            }

            // groupz
            if (jData["groups"] != null)
            {
                foreach (JObject groupData in jData["groups"])
                {
                    if (!groupData["is_archived"].Value<bool>() && groupData["members"].Values<string>().Contains(UserID))
                    {
                        var group = new SlackChatHub()
                        {
                            ID = groupData["id"].Value<string>(),
                            Name = groupData["name"].Value<string>(),
                            Type = SlackChatHubType.Group
                        };
                        hubs.Add(group.ID, group);
                    }
                }
            }

            // dmz
            if (jData["ims"] != null)
            {
                foreach (JObject dmData in jData["ims"])
                {
                    var userID = dmData["user"].Value<string>();
                    var dm = new SlackChatHub()
                    {
                        ID = dmData["id"].Value<string>(),
                        Name = "@" + (UserNameCache.ContainsKey(userID) ? UserNameCache[userID] : userID),
                        Type = SlackChatHubType.DM
                    };
                    hubs.Add(dm.ID, dm);
                }
            }

            // set up the websocket
            WebSocket = new MargieBotWebSocket();
            WebSocket.OnOpen += (object sender, EventArgs e) =>
            {
                // set connection-related properties
                ConnectedSince = DateTime.Now;
            };
            WebSocket.OnMessage += async (object sender, string message) =>
            {
                await ListenTo(message);
            };
            WebSocket.OnClose += (object sender, EventArgs e) =>
            {
                // set connection-related properties
                ConnectedSince = null;
                TeamID = null;
                TeamName = null;
                UserID = null;
                UserName = null;
            };

            // connect
            await WebSocket.Connect(webSocketUrl);
        }

        /// <summary>
        /// Disconnect this bot from Slack.
        /// </summary>
        public void Disconnect()
        {
            WebSocket?.Disconnect();
        }

        private async Task ListenTo(string json)
        {
            bool isValidJson = true;
            JObject jObject = null;
            try
            {
                jObject = JObject.Parse(json);
            }
            catch(JsonReaderException)
            {
                isValidJson = false;
#if DEBUG
                Console.WriteLine($"Illegal JSON message: {json}");
#endif
            }

            if (!isValidJson)
                return;

            if (jObject["type"]?.Value<string>() == "message")
            {
                var channelID = jObject["channel"]?.Value<string>();
                SlackChatHub hub = null;

                if (ConnectedHubs.ContainsKey(channelID))
                {
                    hub = ConnectedHubs[channelID];
                }
                else
                {
                    hub = SlackChatHub.FromID(channelID);
                    var hubs = new Dictionary<string, SlackChatHub>(ConnectedHubs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
                    hubs.Add(hub.ID, hub);
                    ConnectedHubs = hubs;
                }

                // some messages may not have text or a user (like unfurled data from URLs)
                string messageText = jObject["text"]?.Value<string>();

                SlackUser user = jObject["user"] != null
                    ? new SlackUser()
                    {
                        ID = jObject["user"].Value<string>()
                    }
                    : null;

                if (user == null)
                {
                    // a back door (for tests) to respond message from incoming webhook as a person.
                    string userSlackIdFile = Path.GetFullPath("UserSlackId.debug");

#if DEBUG
                    Console.WriteLine($"User Slack ID file: '{userSlackIdFile}'");
#endif

                    if (File.Exists(userSlackIdFile))
                    {
                        string userSlackId = File.ReadAllText(userSlackIdFile, Encoding.UTF8).Trim();
                        if (!string.IsNullOrWhiteSpace(userSlackId))
                        {
                            user = new SlackUser()
                            {
                                ID = userSlackId
                            };
                        }
                    }
                }

                SlackMessage message = new SlackMessage()
                {
                    ChatHub = hub,
                    // check to see if bot has been mentioned
                    MentionsBot = messageText != null && Regex.IsMatch(messageText, BotNameRegex, RegexOptions.IgnoreCase),
                    RawData = json,
                    Text = messageText,
                    User = user
                };

                ResponseContext context = new ResponseContext()
                {
                    BotHasResponded = false,
                    BotUserID = UserID,
                    BotUserName = UserName,
                    Message = message,
                    TeamID = TeamID,
                    UserNameCache = new ReadOnlyDictionary<string, string>(UserNameCache)
                };

                // if the end dev has added any static entries to the ResponseContext collection of Bot, add them to the context being passed to the responders.
                if (ResponseContext != null)
                {
                    foreach (string key in ResponseContext.Keys)
                    {
                        context.Set(key, ResponseContext[key]);
                    }
                }

                // margie can never respond to herself and requires that the message have text and be from an actual person
                if (message.User != null && message.User.ID != UserID && message.Text != null)
                {
                    foreach (var responder in Responders ?? Enumerable.Empty<IResponder>())
                    {
                        if (responder != null && responder.CanRespond(context))
                        {
                            await SendIsTyping(message.ChatHub);
                            await Say(responder.GetResponse(context), context);
                            context.BotHasResponded = true;
                        }
                    }
                }
            }

            RaiseMessageReceived(json);
        }

        /// <summary>
        /// Allows you to programmatically operate the bot. The bot will post the passed message in whichever "chat hub" (DM, channel, or group) the message specifies.
        /// </summary>
        /// <param name="message">The message you want the bot to post in Slack.</param>
        public async Task Say(BotMessage message)
        {
            await Say(message, null);
        }

        private async Task Say(BotMessage message, ResponseContext context)
        {
            string chatHubID = null;
            if (message == null)
            {
                return;
            }

            if (message.ChatHub != null)
            {
                chatHubID = message.ChatHub.ID;
            }
            else if (context != null && context.Message.ChatHub != null)
            {
                chatHubID = context.Message.ChatHub.ID;
            }

            if(chatHubID == null)
            {
                throw new ArgumentException($"When calling the {nameof(Say)}() method, the {nameof(message)} parameter must have its {nameof(message.ChatHub)} property set.");
            }

            var client = new NoobWebClient();
            var values = new List<string>() {
                    "token", SlackKey,
                    "channel", chatHubID,
                    "text", message.Text,
                    "as_user", "true"
                };

            if (message.Attachments.Count > 0)
            {
                values.Add("attachments");
                values.Add(JsonConvert.SerializeObject(message.Attachments));
            }

            await client.DownloadString(
                "https://slack.com/api/chat.postMessage",
                RequestMethod.Post,
                values.ToArray()
            );
        }

        /// <summary>
        /// Causes the bot to appear as though it's typing in whichever hub you specify. Useful for custom interactions, but note that you
        /// don't need to set this while typical responders are being evaluated - the Bot class does that for you.
        /// </summary>
        /// <param name="chatHub">The hub in which the bot should appear to be typing.</param>
        /// <returns></returns>
        public async Task SendIsTyping(SlackChatHub chatHub)
        {
            if(!IsConnected)
            {
                throw new InvalidOperationException(@"Can't send the ""Bot typing"" indicator when the bot is disconnected.");
            }

            var message = new {
                type = "typing",
                channel = chatHub.ID,
                user = UserID
            };

            await WebSocket.Send(JsonConvert.SerializeObject(message));
        }

        #region Events
        public event MargieConnectionStatusChangedEventHandler ConnectionStatusChanged;
        private void RaiseConnectionStatusChanged()
        {
            ConnectionStatusChanged?.Invoke(IsConnected);
        }

        public event MargieMessageReceivedEventHandler MessageReceived;
        private void RaiseMessageReceived(string debugText)
        {
            MessageReceived?.Invoke(debugText);
        }
        #endregion
    }
}


text:
namespace Jirapi.Resources
{
    public class ItemSprites
    {
        public string Default { get; set; }
    }
}


text:
          id.'/edit')}}" class="btn btn-success btn-sm">
             Editar

            Toggle Dropdown

            {{ Form::open(array('url' => 'clientes/' . $cliente->id, 'class' => '')) }}
                <button type="submit" class="btn btn-danger btn-block btn-sm" onclick="return confirm('Excluir permanetenmente?')" role="menuitem">
                     Excluir
                </button>
                <input type="hidden" name="_method" value="DELETE">
            {{ Form::close() }}

CLIENTE

 {{$cliente->empresa}}

{{$cliente->nome}}

                                @if ($cliente->telefone)

                                             {{$cliente->telefone}}

                                @endif
                                @if ($cliente->celular)

                                             {{$cliente->celular}}

                                @endif
                                @if ($cliente->email)

 {{$cliente->email}}

                                @endif

                                @if ($cliente->ie)

IE: {{$cliente->ie}}

                                @endif
                                @if ($cliente->cnpj)

CNPJ: {{$cliente->cnpj}}

                                @endif

                                @if ($cliente->endereco)

                                    {{$cliente->endereco}}

                                    @if ($cliente->bairro) Bairro {{$cliente->bairro}}
 @endif

                                    {{$cliente->cidade}}-{{$cliente->uf}}

                                    {{$cliente->cep}}

                            @endif

{{count( $cliente->pedidos )}}

                Pedidos

@{{conversas.length}}

                Conversas

@{{tarefas.length}}

                Tarefas

            id)}}" class="btn btn-success btn-sm">
                 Novo pedido

                 Ver todos

Pedidos do cliente

{{count( $cliente->pedidos )}} pedidos

                        Nº
                        Data
                        Cliente
                        Fornecedor
                        Total

                    @foreach($cliente->pedidos as $pedido)

                            {{$pedido->id}}
                            {{date("d/m", strtotime( $pedido->updated_at) )}}

                                id) }}" >
                                    {{ ($pedido->cliente['empresa']) ? $pedido->cliente['empresa'] : @$pedido->cliente['nome'] }}

                            {{($pedido->fornecedor->empresa)?$pedido->fornecedor->empresa: @$pedido->fornecedor->nome}}
                            {{$pedido->total}}

                                        id) }}" class="btn btn-primary btn-sm send" data-toggle="modal" data-target="#email">

                                            Opções

                                                id) }}" role="menuitem" tabindex="-1" class="">
                                                    Ver

                                                id.'/edit') }}" class="" role="menuitem" tabindex="-1" >
                                                     Editar

                                                id) }}" class="" role="menuitem" tabindex="-1" >
                                                     Visualizar impressão

                                                {{ Form::open(array('url' => 'pedidos/' . $pedido->id, 'class' => '')) }}
                                                    {{ Form::button(' Excluir', array('class' => 'btn btn-danger btn-block btn-sm', 'type'=>'sumbit', 'onclick'=>'javascript:return confirm("Deseja excluir este pedido da lista?")', 'role'=>"menuitem", 'tabindex'=>"-1" )) }}
                                                    {{ Form::hidden('_method', 'DELETE') }}
                                                {{ Form::close() }}

                    @endforeach
                    <?php // print_r($cliente->pedidos); exit; ?>

                  <button class="btn btn-success btn-sm" data-toggle="collapse" data-target="#add_conversa">
                     Nova conversa
                  </button>

@{{conversas.length}} conversas

                    @include('conversas.panels.create')

                            @include('conversas.item')

                  id)}}" class="btn btn-success btn-sm" data-toggle="collapse" data-target="#add_tarefa">
                     Nova tarefa

@{{tarefas.length}} tarefas

                    {{--@include('tarefas.panels.create')--}}

                            @include('tarefas.item')

@section('scripts')

@stop


text:
<?php

declare(strict_types = 1);

namespace Drupal\ckeditor5\Plugin\Validation\Constraint;

use Drupal\ckeditor5\HTMLRestrictions;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * Ensures Source Editing cannot be configured to allow self-XSS.
 *
 * @internal
 */
class SourceEditingPreventSelfXssConstraintValidator extends ConstraintValidator {

  use TextEditorObjectDependentValidatorTrait;

  /**
   * {@inheritdoc}
   *
   * @throws \Symfony\Component\Validator\Exception\UnexpectedTypeException
   *   Thrown when the given constraint is not supported by this validator.
   */
  public function validate($value, Constraint $constraint) {
    if (!$constraint instanceof SourceEditingPreventSelfXssConstraint) {
      throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\SourceEditingPreventSelfXssConstraint');
    }
    if (empty($value)) {
      return;
    }

    $restrictions = HTMLRestrictions::fromString($value);
    // @todo Remove this early return in
    //   https://www.drupal.org/project/drupal/issues/2820364. It is only
    //   necessary because CKEditor5ElementConstraintValidator does not run
    //   before this, which means that this validator cannot assume it receives
    //   valid values.
    if ($restrictions->allowsNothing() || count($restrictions->getAllowedElements()) > 1) {
      return;
    }

    // This validation constraint only validates attributes, not tags; so if all
    // attributes are allowed (TRUE) or no attributes are allowed (FALSE),
    // return early. Only proceed when some attributes are allowed (an array).
    $allowed_elements = $restrictions->getAllowedElements(FALSE);
    assert(count($allowed_elements) === 1);
    $tag = array_key_first($allowed_elements);
    $attribute_restrictions = $allowed_elements[$tag];
    if (!is_array($attribute_restrictions)) {
      return;
    }

    $text_editor = $this->createTextEditorObjectFromContext();
    $text_format_allowed_elements = HTMLRestrictions::fromTextFormat($text_editor->getFilterFormat())
      ->getAllowedElements();
    // Any XSS-prevention related measures imposed by filter plugins are relayed
    // through their ::getHtmlRestrictions() return value. The global attribute
    // `*` HTML tag allows attributes to be forbidden.
    // @see https://html.spec.whatwg.org/multipage/dom.html#global-attributes
    // @see \Drupal\ckeditor5\HTMLRestrictions::validateAllowedRestrictionsPhase4()
    // @see \Drupal\filter\Plugin\Filter\FilterHtml::getHTMLRestrictions()
    $forbidden_attributes = [];
    if (array_key_exists('*', $text_format_allowed_elements)) {
      $forbidden_attributes = array_keys(array_filter($text_format_allowed_elements['*'], function ($attribute_value_restriction, string $attribute_name) {
        return $attribute_value_restriction === FALSE;
      }, ARRAY_FILTER_USE_BOTH));
    }

    foreach ($forbidden_attributes as $forbidden_attribute_name) {
      // Forbidden attributes not containing wildcards, such as `style`.
      if (!self::isWildcardAttributeName($forbidden_attribute_name)) {
        if (array_key_exists($forbidden_attribute_name, $attribute_restrictions)) {
          $this->context->buildViolation($constraint->message)
            ->setParameter('%dangerous_tag', $value)
            ->addViolation();
        }
      }
      // Forbidden attributes containing wildcards such as `on*`.
      else {
        $regex = self::getRegExForWildCardAttributeName($forbidden_attribute_name);
        if (!empty(preg_grep($regex, array_keys($attribute_restrictions)))) {
          $this->context->buildViolation($constraint->message)
            ->setParameter('%dangerous_tag', $value)
            ->addViolation();
        }
      }
    }
  }

  /**
   * Checks whether the given attribute name contains a wildcard, e.g. `data-*`.
   *
   * @param string $attribute_name
   *   The attribute name to check.
   *
   * @return bool
   *   Whether the given attribute name contains a wildcard.
   */
  private static function isWildcardAttributeName(string $attribute_name): bool {
    assert($attribute_name !== '*');
    return strpos($attribute_name, '*') !== FALSE;
  }

  /**
   * Computes a regular expression for matching a wildcard attribute name.
   *
   * @param string $wildcard_attribute_name
   *   The wildcard attribute name for which to compute a regular expression.
   *
   * @return string
   *   The computed regular expression.
   */
  private static function getRegExForWildCardAttributeName(string $wildcard_attribute_name): string {
    assert(self::isWildcardAttributeName($wildcard_attribute_name));
    return '/^' . str_replace('*', '.*', $wildcard_attribute_name) . '$/';
  }

}


text:
body {
  padding-top: 50px;
  background-color: #eee;
  min-height: 2000px;
}

#fixed-menu
{
    position: fixed;
    width: 100%;
    height: 75px;
    background-color: #f00;
    padding: px;
}

.form-horizontal {
  max-width: 330px;
  padding: 15px;
  margin: 10px;
}
.form-horizontal .form-signin-heading{
  margin-bottom: 10px;
}

.form-horizontal .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-horizontal .form-control:focus {
  z-index: 2;
}
.form-horizontal input[type="text"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-horizontal input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}


text:
/*!
 * @brief Radio configuration data adapted from SiLabs's WDS software.
 *
 * Configuration for 433 MHz Zeta module.
 */

#pragma once

#include <stdint.h>

// INPUT DATA
/*
// Crys_freq(Hz): 30000000    Crys_tol(ppm): 30    IF_mode: 2    High_perf_Ch_Fil: 1    OSRtune: 0    Ch_Fil_Bw_AFC: 0    ANT_DIV: 0    PM_pattern: 0
// MOD_type: 2    Rsymb(sps): 128000    Fdev(Hz): 70000    RXBW(Hz): 305000    Manchester: 1    AFC_en: 1    Rsymb_error: 0.0    Chip-Version: 2
// RF Freq.(MHz): 868    API_TC: 28    fhst: 250000    inputBW: 0    BERT: 0    RAW_dout: 0    D_source: 0    Hi_pfm_div: 0
//
// # WB filter 2 (BW = 274.83 kHz);  NB-filter 2 (BW = 274.83 kHz)

//
// Modulation index: 1
*/

namespace ZetaRfConfigs {

struct Config433_FixedLength_CRC_Preamble10_Sync4_Payload8
{
    static const uint8_t RadioConfigurationDataArray[];

    constexpr static uint8_t DefaultChannel = 0;
    constexpr static uint8_t PacketLength = 0x08;
    constexpr static bool VariableLengthPacketConfiguration = false;
};

} // namespace ZetaRfConfigs


text:
template <typename T>
class BITW
{
public:
    enum { bitw = sizeof (T) * BITS_PER_BYTE };
};

// bit width of an variable of given type
template <typename T>
inline BYTE bitw ()
{
    return BITW<T>::bitw;
}

template <int SZ>
class EXBITW
{
public:
    enum { exbitw = EXBITW < (SZ+1)/2 >::exbitw + 1 };
};

template <>
class EXBITW < 1 >
{
public:
    enum { exbitw = 0 };
};

// exponential bit width - how many address bits are 'eaten up' by an instance of given type
template <typename T>
inline BYTE exbitw ()  // exponent bit width
{
    return EXBITW < sizeof (T) >::exbitw;
}

// writes the bit-wise representation of passed value to the given stream
// uses C-style byte layout: writes "most significant" component first.
// This is opposite to the memory layout on little-endian (intel-based) CPUs
// this template is layout-agnostic, it does not change order depending on 'endiness' of architecture
// To get byte order that matches little-endian memory layout, pass rev as 'false'
template <typename TYPE>
inline void print_bits (TYPE& value, std::ostream& ostr, bool rev = true)
{
    BYTE* base = (BYTE*) &value;
    unsigned begb = rev ?  sizeof (TYPE) : 1;
    unsigned endb = rev ?  0 : sizeof (TYPE) + 1;
    unsigned step = rev ? -1 : 1 ;
    for (unsigned bpos = begb; bpos != endb; bpos += step)
    {
        if (bpos != begb) ostr << SPACE_STR;
        print_bits (base [bpos-1], ostr, rev);
    }
}

// specialization of print_bits for 1-byte values
template <>
inline void print_bits <BYTE> (BYTE& val, std::ostream& o, bool rv)
{
    // assume all architectures are "bitwise little-endian" (Most Significant Bit is on the left)
    for (unsigned pos = BITS_PER_BYTE; pos != 0; --pos)
        o << ((val >> (pos-1)) & 1);
}

// writes the byte-wise (hexadecimal) representation of passed value to the given stream
// uses C-style byte layout: writes "most significant" component first.
// This is opposite to the memory layout on little-endian (intel-based) CPUs
// this template is layout-agnostic, it does not change order depending on 'endiness' of architecture
// To get byte order that matches little-endian memory layout, pass rv as 'false'
template <typename TYPE>
inline void print_bytes (TYPE& value, std::ostream& ostr, bool rev = true)
{
    BYTE* base = (BYTE*) &value;
    unsigned begb = rev ?  sizeof (TYPE) : 1;
    unsigned endb = rev ?  0 : sizeof (TYPE) + 1;
    unsigned step = rev ? -1 : 1 ;
    for (unsigned bpos = begb; bpos != endb; bpos += step)
    {
        if (bpos) ostr << SPACE_STR;
        ostr << std::hex << (unsigned) base [bpos-1];
    }
}

template <typename TYPE>
inline TYPE invert_bits (TYPE val)
{
    TYPE retval = 0;
    unsigned pos = (sizeof (TYPE) << 3);
    while (pos)
    {
        retval <<= 1;
        retval |= val & 1;
        val >>= 1;
        pos --;
    }
    return retval;
}

// helper class for printing out 32-bit masks
struct MASK
{
    public:
        DWORD mask_;
        BYTE l_;
        MASK (DWORD m, BYTE l)
        :
        mask_ (m),
        l_ (l)
        {
        }
        MASK ()
        :
        l_ (0)
        {
        }
};

inline std::ostream& operator << (std::ostream& ostr, const MASK& mask)
{
    DWORD mm = mask.mask_ & ((~ (DWORD) 0) >> (sizeof (DWORD) * 8 - mask.l_));
    print_bits (mm, ostr);
    return ostr;
}

inline Logger& operator << (Logger& logger, const MASK& mask)
{
    if (logger.enabled ())
        logger.o_ << mask;
    return logger;
}

#endif // __bitops_h__


text:
namespace blink {

ScriptWrappableVisitor::~ScriptWrappableVisitor()
{
}

void ScriptWrappableVisitor::TracePrologue()
{
    DCHECK(m_headersToUnmark.isEmpty());
    DCHECK(m_markingDeque.isEmpty());
    DCHECK(m_verifierDeque.isEmpty());
    m_tracingInProgress = true;
}

void ScriptWrappableVisitor::EnterFinalPause()
{
    ActiveScriptWrappable::traceActiveScriptWrappables(m_isolate, this);
}

void ScriptWrappableVisitor::TraceEpilogue()
{
    DCHECK(m_markingDeque.isEmpty());
#if DCHECK_IS_ON()
    ScriptWrappableVisitorVerifier verifier;
    for (auto& markingData : m_verifierDeque) {
        markingData.traceWrappers(&verifier);
    }
#endif
    performCleanup();
}

void ScriptWrappableVisitor::AbortTracing()
{
    performCleanup();
}

void ScriptWrappableVisitor::performCleanup()
{
    for (auto header : m_headersToUnmark) {
        header->unmarkWrapperHeader();
    }

    m_headersToUnmark.clear();
    m_markingDeque.clear();
    m_verifierDeque.clear();
    m_tracingInProgress = false;
}

void ScriptWrappableVisitor::RegisterV8Reference(const std::pair<void*, void*>& internalFields)
{
    if (!m_tracingInProgress) {
        return;
    }

    WrapperTypeInfo* wrapperTypeInfo = reinterpret_cast<WrapperTypeInfo*>(internalFields.first);
    if (wrapperTypeInfo->ginEmbedder != gin::GinEmbedder::kEmbedderBlink) {
        return;
    }
    DCHECK(wrapperTypeInfo->wrapperClassId == WrapperTypeInfo::NodeClassId
        || wrapperTypeInfo->wrapperClassId == WrapperTypeInfo::ObjectClassId);

    ScriptWrappable* scriptWrappable = reinterpret_cast<ScriptWrappable*>(internalFields.second);

    wrapperTypeInfo->traceWrappers(this, scriptWrappable);
}

void ScriptWrappableVisitor::RegisterV8References(const std::vector<std::pair<void*, void*>>& internalFieldsOfPotentialWrappers)
{
    // TODO(hlopko): Visit the vector in the V8 instead of passing it over if
    // there is no performance impact
    for (auto& pair : internalFieldsOfPotentialWrappers) {
        RegisterV8Reference(pair);
    }
}

bool ScriptWrappableVisitor::AdvanceTracing(double deadlineInMs, v8::EmbedderHeapTracer::AdvanceTracingActions actions)
{
    DCHECK(m_tracingInProgress);
    WTF::AutoReset<bool>(&m_advancingTracing, true);
    while (actions.force_completion == v8::EmbedderHeapTracer::ForceCompletionAction::FORCE_COMPLETION
        || WTF::monotonicallyIncreasingTimeMS() < deadlineInMs) {
        if (m_markingDeque.isEmpty()) {
            return false;
        }

        m_markingDeque.takeFirst().traceWrappers(this);
    }
    return true;
}

bool ScriptWrappableVisitor::markWrapperHeader(HeapObjectHeader* header) const
{
    if (header->isWrapperHeaderMarked())
        return false;

    header->markWrapperHeader();
    m_headersToUnmark.append(header);
    return true;
}

void ScriptWrappableVisitor::markWrappersInAllWorlds(const ScriptWrappable* scriptWrappable) const
{
    DOMWrapperWorld::markWrappersInAllWorlds(const_cast<ScriptWrappable*>(scriptWrappable), this);
}

void ScriptWrappableVisitor::traceWrappers(const ScopedPersistent<v8::Value>* scopedPersistent) const
{
    markWrapper(&(const_cast<ScopedPersistent<v8::Value>*>(scopedPersistent)->get()));
}

void ScriptWrappableVisitor::traceWrappers(const ScopedPersistent<v8::Object>* scopedPersistent) const
{
    markWrapper(&(const_cast<ScopedPersistent<v8::Object>*>(scopedPersistent)->get()));
}

void ScriptWrappableVisitor::markWrapper(const v8::PersistentBase<v8::Value>* handle) const
{
    handle->RegisterExternalReference(m_isolate);
}

void ScriptWrappableVisitor::markWrapper(const v8::PersistentBase<v8::Object>* handle) const
{
    handle->RegisterExternalReference(m_isolate);
}

void ScriptWrappableVisitor::dispatchTraceWrappers(const ScriptWrappable* wrappable) const
{
    wrappable->traceWrappers(this);
}

#define DEFINE_DISPATCH_TRACE_WRAPPERS(className)                    \
void ScriptWrappableVisitor::dispatchTraceWrappers(const className* traceable) const \
{                                                                    \
    traceable->traceWrappers(this);                                  \
}                                                                    \

WRAPPER_VISITOR_SPECIAL_CLASSES(DEFINE_DISPATCH_TRACE_WRAPPERS);

#undef DEFINE_DISPATCH_TRACE_WRAPPERS

void ScriptWrappableVisitor::invalidateDeadObjectsInMarkingDeque()
{
    for (auto it = m_markingDeque.begin(); it != m_markingDeque.end(); ++it) {
        auto& markingData = *it;
        if (markingData.shouldBeInvalidated()) {
            markingData.invalidate();
        }
    }
    for (auto it = m_verifierDeque.begin(); it != m_verifierDeque.end(); ++it) {
        auto& markingData = *it;
        if (markingData.shouldBeInvalidated()) {
            markingData.invalidate();
        }
    }
    for (auto it = m_headersToUnmark.begin(); it != m_headersToUnmark.end(); ++it) {
        auto header = *it;
        if (header && !header->isMarked()) {
            *it = nullptr;
        }
    }
}

void ScriptWrappableVisitor::invalidateDeadObjectsInMarkingDeque(v8::Isolate* isolate)
{
    ScriptWrappableVisitor* scriptWrappableVisitor = V8PerIsolateData::from(isolate)->scriptWrappableVisitor();
    if (scriptWrappableVisitor) {
        scriptWrappableVisitor->invalidateDeadObjectsInMarkingDeque();
    }
}

} // namespace blink


text:
version = node['thrift']['version']

include_recipe "build-essential"
include_recipe "boost"
include_recipe "python"
include_recipe "install_from"

# no seriously -- thrift wants these ancient and unjustified gem versions
gem_package('rspec'){   version '1.3.2';      action :install }
gem_package('mongrel'){ version '1.2.0.pre2'; action :install; options("--prerelease --no-rdoc --no-ri") }

packages = value_for_platform(
  ["centos", "redhat", "suse", "fedora" ] => {
    "default" => %w{ flex bison libtool autoconf pkgconfig }
  },
  "default" => %w{ flex bison libtool autoconf pkg-config }
)
packages.each do |pkg|
  package pkg
end

install_from_release(:thrift) do
  release_url   node[:thrift][:release_url]
  version       node[:thrift][:version]
  checksum      node[:thrift][:checksum]
  home_dir      node[:thrift][:home_dir]
  action        [:configure_with_autoconf, :install_with_make]
  autoconf_opts [node[:thrift][:configure_options], "--prefix #{node[:thrift][:prefix_root]}"].flatten.compact
  not_if{ ::File.file?("#{node[:thrift][:prefix_root]}/lib/libthrift-#{node[:thrift][:version]}.jar") }
end

# Tell everyone about all the awesome jars of stuff we have

node.set[:thrift][:exported_jars] = [
  "#{node[:thrift][:home_dir]}/lib/java/build/libthrift-0.8.0.jar",
]


text:
These exercises lean on Test-Driven Development (TDD), but they're not an
exact match.

The following steps assume that you are in the same directory as the test
suite.

## Step 1

Run the test suite. It's in Minitest, and can be run with ruby:

    $ ruby bob_test.rb

This will fail, complaining that there is no file called `bob`.

To fix the error create an empty file called `bob.rb` in the same
directory as the `bob_test.rb` file.

## Step 2

Run the test again. It will give you a new error.

    1) Error:
    BobTest#test_stating_something:
    NameError: uninitialized constant Bob
        bob_test.rb:12:in `test_stating_something'

Within the first test, we are telling ruby to create a new Bob object,
but it doesn't know anything about any Bob, so we need to make one.

Open up the bob.rb file and add the following code:

    class Bob
    end

## Step 3

Run the test again.

    1) Error:
    BobTest#test_stating_something:
    NoMethodError: undefined method `hey' for #<Bob:0x007fa531343e50>
        bob_test.rb:12:in `test_stating_something'

This time we have a Bob, but we're trying to call a method named "hey" on him.

Open up bob.rb and add a method definition inside the class:

    class Bob
      def hey
      end
    end

## Step 4

Run the test again.

    1) Error:
    BobTest#test_stating_something:
    ArgumentError: wrong number of arguments (1 for 0)
      in `hey' bob_test.rb:12:in `test_stating_something'

The method "hey" needs to take an argument.

These are examples of method definitions that take arguments:

    def greet(name)
    end

    def drink(beverage)
    end

Change the "hey" method definition so it takes an argument.

## Step 5

Run the test again.

    1) Failure:
    BobTest#test_stating_something [bob_test.rb:12]:
    Expected: "Whatever."
      Actual: nil

Up until now we've been getting errors, this time we get a failure.

An error means that ruby cannot even run properly because things like missing
files or referencing classes or methods that don't exist, or because of syntax
errors.

A failure is different—when you have a failure the ruby is running just fine,
but the test is expecting one outcome, but getting another.

The test is expecting the hey method to return the string "Whatever". The
easiest way to make it pass, is to simply stick the string "Whatever" inside
the method definition.

## Step 6

Run the test again.

If it fails you're going to need to read the error message carefully to figure
out what went wrong, and then try again.

If it passes, then you're ready to move to the next step.

Open the bob_test.rb file, and find the word "skip". All but the first test
start with "skip", which tells Minitest to ignore the test. This is so that
you don't have to deal with all the failures at once.

To activate the next test, delete the "skip", and run the test suite again.

## Wash, Rinse, Repeat

Delete one "skip" at a time, and make each test pass before you move to the
next one.

## Submit

When everything is passing, you can submit your code with the following
command:

    $ exercism submit bob.rb


text:
<?php
// determine the station from the url parameter
$stationjson = '';
if (isset($_GET['stationId'])) {
	$stationjson = getStationById($_GET['stationId']);
}
// trigger request to get station metadata
function getStationById($stationId) {
	$json = file_get_contents('http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/stations/' . $stationId);
	return $json;
}
?>

<!DOCTYPE html>

		<title>avi92 | ifgi Münster</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8;" />

		<link rel="stylesheet" type="text/css" href="style/dataViewer.css" />
		<link rel="stylesheet" type="text/css" href="style/lib/jquery-ui.css" />
		<link rel="stylesheet" type="text/css" href="style/lib/editablegrid-2.0.1.css" />

							View As

									Chart

									Table

									Raw (JSON)

							Set Timespan

							Loading

						Station Information

							ID

							Label

							X-Coordinate (EPSG: 900913)

							Y-Coordinate (EPSG: 900913)

									Date

							Select a Timespan

								Start Date

								End Date

								to

								<input type="button" value="Cancel" >

								<input type="button" value="Apply" onclick="applyTimespan()">

						Phenomena

						<form name="phenomenaRadios">

						</form>

						Timeseries


text:
play-url-binders
================

[![Build Status](https://travis-ci.org/hmrc/play-url-binders.svg)](https://travis-ci.org/hmrc/play-url-binders) [ ![Download](https://api.bintray.com/packages/hmrc/releases/play-url-binders/images/download.svg) ](https://bintray.com/hmrc/releases/play-url-binders/_latestVersion)

This library includes some basic functionality related to binding URL parameters and query string values in Play controller routes.

### Installing

Add the following to your SBT build:
```scala
resolvers += Resolver.bintrayRepo("hmrc", "releases")

libraryDependencies += "uk.gov.hmrc" %% "play-url-binders" % "[INSERT-VERSION]"
```

## License ##

This code is open source software licensed under the [Apache 2.0 License]("http://www.apache.org/licenses/LICENSE-2.0.html").


text:
class API::V1::ItemTypeSerializer < ActiveModel::Serializer
  include API::V1::TranslationSerialization
  include Rails.application.routes.url_helpers

  has_many :fields, :serializer => API::V1::FieldSerializer

  attributes :id, :slug
  attribute(:name) { translation_hash(object.name_translations) }
  attribute(:name_plural) { translation_hash(object.name_plural_translations) }

  attribute(:_links) do
    {
      :items => api_v1_catalog_items_url(
        object.catalog.slug, :item_type => object.slug
      )
    }
  end
end


text:
package com.amazonaws.services.ec2.waiters;

import javax.annotation.Generated;

import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.waiters.SdkFunction;
import com.amazonaws.services.ec2.model.DescribeVpcPeeringConnectionsRequest;
import com.amazonaws.services.ec2.model.DescribeVpcPeeringConnectionsResult;
import com.amazonaws.services.ec2.AmazonEC2;

@SdkInternalApi
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeVpcPeeringConnectionsFunction implements SdkFunction<DescribeVpcPeeringConnectionsRequest, DescribeVpcPeeringConnectionsResult> {

    /**
     * Represents the service client
     */
    private final AmazonEC2 client;

    /**
     * Constructs a new DescribeVpcPeeringConnectionsFunction with the given client
     *
     * @param client
     *        Service client
     */
    public DescribeVpcPeeringConnectionsFunction(AmazonEC2 client) {
        this.client = client;
    }

    /**
     * Makes a call to the operation specified by the waiter by taking the corresponding request and returns the
     * corresponding result
     *
     * @param describeVpcPeeringConnectionsRequest
     *        Corresponding request for the operation
     * @return Corresponding result of the operation
     */
    @Override
    public DescribeVpcPeeringConnectionsResult apply(DescribeVpcPeeringConnectionsRequest describeVpcPeeringConnectionsRequest) {
        return client.describeVpcPeeringConnections(describeVpcPeeringConnectionsRequest);
    }
}


text:
<?php
return array (
  'Change E-mail' => 'Cambia E-mail',
  'We´ve just sent an confirmation e-mail to your new address.
 Please follow the instructions inside.' => 'Abbiamo inviato una conferma via e-mail al tuo nuovo indirizzo.
Per favore segui le istruzioni all\'interno.',
);


text:
import { h, mount } from 'bore';
import * as expect from 'expect';
import { CardContent } from './index';

describe( CardContent.is, () => {

  describe( `Custom element`, () => {

    it( `should be registered`, () => {
      expect( customElements.get( CardContent.is ) ).toBe( CardContent );
    } );

    it( `should render via JSX IntrinsicElement`, () => {
      return mount( <bl-card-content>Content</bl-card-content> ).wait(( element ) => {
        expect( element.node.localName ).toBe( CardContent.is );
      } );
    } );

    it( `should render`, () => {
      return mount( <CardContent>Content</CardContent> ).wait(( element ) => {
        expect( element.has( '.c-card__body' ) ).toBe( true );
      } );
    } );
  } );

} );


text:
import { findKey } from "lodash";
export = findKey;


text:
"""The tests for the Demo vacuum platform."""
import unittest

from homeassistant.components import vacuum
from homeassistant.components.vacuum import (
    ATTR_BATTERY_LEVEL, ATTR_COMMAND, ATTR_ENTITY_ID, ATTR_FAN_SPEED,
    ATTR_FAN_SPEED_LIST, ATTR_PARAMS, ATTR_STATUS, DOMAIN,
    ENTITY_ID_ALL_VACUUMS,
    SERVICE_SEND_COMMAND, SERVICE_SET_FAN_SPEED,
    STATE_DOCKED, STATE_CLEANING, STATE_PAUSED, STATE_IDLE,
    STATE_RETURNING)
from homeassistant.components.vacuum.demo import (
    DEMO_VACUUM_BASIC, DEMO_VACUUM_COMPLETE, DEMO_VACUUM_MINIMAL,
    DEMO_VACUUM_MOST, DEMO_VACUUM_NONE, DEMO_VACUUM_STATE, FAN_SPEEDS)
from homeassistant.const import (
    ATTR_SUPPORTED_FEATURES, CONF_PLATFORM, STATE_OFF, STATE_ON)
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant, mock_service

ENTITY_VACUUM_BASIC = '{}.{}'.format(DOMAIN, DEMO_VACUUM_BASIC).lower()
ENTITY_VACUUM_COMPLETE = '{}.{}'.format(DOMAIN, DEMO_VACUUM_COMPLETE).lower()
ENTITY_VACUUM_MINIMAL = '{}.{}'.format(DOMAIN, DEMO_VACUUM_MINIMAL).lower()
ENTITY_VACUUM_MOST = '{}.{}'.format(DOMAIN, DEMO_VACUUM_MOST).lower()
ENTITY_VACUUM_NONE = '{}.{}'.format(DOMAIN, DEMO_VACUUM_NONE).lower()
ENTITY_VACUUM_STATE = '{}.{}'.format(DOMAIN, DEMO_VACUUM_STATE).lower()

class TestVacuumDemo(unittest.TestCase):
    """Test the Demo vacuum."""

    def setUp(self):  # pylint: disable=invalid-name
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.assertTrue(setup_component(
            self.hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: 'demo'}}))

    def tearDown(self):  # pylint: disable=invalid-name
        """Stop down everything that was started."""
        self.hass.stop()

    def test_supported_features(self):
        """Test vacuum supported features."""
        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertEqual(2047, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual("Charging", state.attributes.get(ATTR_STATUS))
        self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual("medium", state.attributes.get(ATTR_FAN_SPEED))
        self.assertListEqual(FAN_SPEEDS,
                             state.attributes.get(ATTR_FAN_SPEED_LIST))
        self.assertEqual(STATE_OFF, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_MOST)
        self.assertEqual(219, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual("Charging", state.attributes.get(ATTR_STATUS))
        self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST))
        self.assertEqual(STATE_OFF, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_BASIC)
        self.assertEqual(195, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual("Charging", state.attributes.get(ATTR_STATUS))
        self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST))
        self.assertEqual(STATE_OFF, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_MINIMAL)
        self.assertEqual(3, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual(None, state.attributes.get(ATTR_STATUS))
        self.assertEqual(None, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST))
        self.assertEqual(STATE_OFF, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_NONE)
        self.assertEqual(0, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual(None, state.attributes.get(ATTR_STATUS))
        self.assertEqual(None, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED))
        self.assertEqual(None, state.attributes.get(ATTR_FAN_SPEED_LIST))
        self.assertEqual(STATE_OFF, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(13436, state.attributes.get(ATTR_SUPPORTED_FEATURES))
        self.assertEqual(STATE_DOCKED, state.state)
        self.assertEqual(100, state.attributes.get(ATTR_BATTERY_LEVEL))
        self.assertEqual("medium", state.attributes.get(ATTR_FAN_SPEED))
        self.assertListEqual(FAN_SPEEDS,
                             state.attributes.get(ATTR_FAN_SPEED_LIST))

    def test_methods(self):
        """Test if methods call the services as expected."""
        self.hass.states.set(ENTITY_VACUUM_BASIC, STATE_ON)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC))

        self.hass.states.set(ENTITY_VACUUM_BASIC, STATE_OFF)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_BASIC))

        self.hass.states.set(ENTITY_ID_ALL_VACUUMS, STATE_ON)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass))

        self.hass.states.set(ENTITY_ID_ALL_VACUUMS, STATE_OFF)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass))

        vacuum.turn_on(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.turn_off(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.toggle(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.start_pause(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.start_pause(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.stop(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertLess(state.attributes.get(ATTR_BATTERY_LEVEL), 100)
        self.assertNotEqual("Charging", state.attributes.get(ATTR_STATUS))

        vacuum.locate(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertIn("I'm over here", state.attributes.get(ATTR_STATUS))

        vacuum.return_to_base(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertIn("Returning home", state.attributes.get(ATTR_STATUS))

        vacuum.set_fan_speed(self.hass, FAN_SPEEDS[-1],
                             entity_id=ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertEqual(FAN_SPEEDS[-1], state.attributes.get(ATTR_FAN_SPEED))

        vacuum.clean_spot(self.hass, entity_id=ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        self.assertIn("spot", state.attributes.get(ATTR_STATUS))
        self.assertEqual(STATE_ON, state.state)

        vacuum.start(self.hass, ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(STATE_CLEANING, state.state)

        vacuum.pause(self.hass, ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(STATE_PAUSED, state.state)

        vacuum.stop(self.hass, ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(STATE_IDLE, state.state)

        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertLess(state.attributes.get(ATTR_BATTERY_LEVEL), 100)
        self.assertNotEqual(STATE_DOCKED, state.state)

        vacuum.return_to_base(self.hass, ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(STATE_RETURNING, state.state)

        vacuum.set_fan_speed(self.hass, FAN_SPEEDS[-1],
                             entity_id=ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(FAN_SPEEDS[-1], state.attributes.get(ATTR_FAN_SPEED))

        vacuum.clean_spot(self.hass, entity_id=ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertEqual(STATE_CLEANING, state.state)

    def test_unsupported_methods(self):
        """Test service calls for unsupported vacuums."""
        self.hass.states.set(ENTITY_VACUUM_NONE, STATE_ON)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        vacuum.turn_off(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        vacuum.stop(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        self.hass.states.set(ENTITY_VACUUM_NONE, STATE_OFF)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        vacuum.turn_on(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        vacuum.toggle(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        # Non supported methods:
        vacuum.start_pause(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_NONE))

        vacuum.locate(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_NONE)
        self.assertIsNone(state.attributes.get(ATTR_STATUS))

        vacuum.return_to_base(self.hass, ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_NONE)
        self.assertIsNone(state.attributes.get(ATTR_STATUS))

        vacuum.set_fan_speed(self.hass, FAN_SPEEDS[-1],
                             entity_id=ENTITY_VACUUM_NONE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_NONE)
        self.assertNotEqual(FAN_SPEEDS[-1],
                            state.attributes.get(ATTR_FAN_SPEED))

        vacuum.clean_spot(self.hass, entity_id=ENTITY_VACUUM_BASIC)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_BASIC)
        self.assertNotIn("spot", state.attributes.get(ATTR_STATUS))
        self.assertEqual(STATE_OFF, state.state)

        # VacuumDevice should not support start and pause methods.
        self.hass.states.set(ENTITY_VACUUM_COMPLETE, STATE_ON)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.pause(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertTrue(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        self.hass.states.set(ENTITY_VACUUM_COMPLETE, STATE_OFF)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        vacuum.start(self.hass, ENTITY_VACUUM_COMPLETE)
        self.hass.block_till_done()
        self.assertFalse(vacuum.is_on(self.hass, ENTITY_VACUUM_COMPLETE))

        # StateVacuumDevice does not support on/off
        vacuum.turn_on(self.hass, entity_id=ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertNotEqual(STATE_CLEANING, state.state)

        vacuum.turn_off(self.hass, entity_id=ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertNotEqual(STATE_RETURNING, state.state)

        vacuum.toggle(self.hass, entity_id=ENTITY_VACUUM_STATE)
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_VACUUM_STATE)
        self.assertNotEqual(STATE_CLEANING, state.state)

    def test_services(self):
        """Test vacuum services."""
        # Test send_command
        send_command_calls = mock_service(
            self.hass, DOMAIN, SERVICE_SEND_COMMAND)

        params = {"rotate": 150, "speed": 20}
        vacuum.send_command(
            self.hass, 'test_command', entity_id=ENTITY_VACUUM_BASIC,
            params=params)

        self.hass.block_till_done()
        self.assertEqual(1, len(send_command_calls))
        call = send_command_calls[-1]

        self.assertEqual(DOMAIN, call.domain)
        self.assertEqual(SERVICE_SEND_COMMAND, call.service)
        self.assertEqual(ENTITY_VACUUM_BASIC, call.data[ATTR_ENTITY_ID])
        self.assertEqual('test_command', call.data[ATTR_COMMAND])
        self.assertEqual(params, call.data[ATTR_PARAMS])

        # Test set fan speed
        set_fan_speed_calls = mock_service(
            self.hass, DOMAIN, SERVICE_SET_FAN_SPEED)

        vacuum.set_fan_speed(
            self.hass, FAN_SPEEDS[0], entity_id=ENTITY_VACUUM_COMPLETE)

        self.hass.block_till_done()
        self.assertEqual(1, len(set_fan_speed_calls))
        call = set_fan_speed_calls[-1]

        self.assertEqual(DOMAIN, call.domain)
        self.assertEqual(SERVICE_SET_FAN_SPEED, call.service)
        self.assertEqual(ENTITY_VACUUM_COMPLETE, call.data[ATTR_ENTITY_ID])
        self.assertEqual(FAN_SPEEDS[0], call.data[ATTR_FAN_SPEED])

    def test_set_fan_speed(self):
        """Test vacuum service to set the fan speed."""
        group_vacuums = ','.join([ENTITY_VACUUM_BASIC,
                                  ENTITY_VACUUM_COMPLETE,
                                  ENTITY_VACUUM_STATE])
        old_state_basic = self.hass.states.get(ENTITY_VACUUM_BASIC)
        old_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        old_state_state = self.hass.states.get(ENTITY_VACUUM_STATE)

        vacuum.set_fan_speed(
            self.hass, FAN_SPEEDS[0], entity_id=group_vacuums)

        self.hass.block_till_done()
        new_state_basic = self.hass.states.get(ENTITY_VACUUM_BASIC)
        new_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE)
        new_state_state = self.hass.states.get(ENTITY_VACUUM_STATE)

        self.assertEqual(old_state_basic, new_state_basic)
        self.assertNotIn(ATTR_FAN_SPEED, new_state_basic.attributes)

        self.assertNotEqual(old_state_complete, new_state_complete)
        self.assertEqual(FAN_SPEEDS[1],
                         old_state_complete.attributes[ATTR_FAN_SPEED])
        self.assertEqual(FAN_SPEEDS[0],
                         new_state_complete.attributes[ATTR_FAN_SPEED])

        self.assertNotEqual(old_state_state, new_state_state)
        self.assertEqual(FAN_SPEEDS[1],
                         old_state_state.attributes[ATTR_FAN_SPEED])
        self.assertEqual(FAN_SPEEDS[0],
                         new_state_state.attributes[ATTR_FAN_SPEED])

    def test_send_command(self):
        """Test vacuum service to send a command."""
        group_vacuums = ','.join([ENTITY_VACUUM_BASIC,
                                  ENTITY_VACUUM_COMPLETE])
        old_state_basic = self.hass.states.get(ENTITY_VACUUM_BASIC)
        old_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE)

        vacuum.send_command(
            self.hass, 'test_command', params={"p1": 3},
            entity_id=group_vacuums)

        self.hass.block_till_done()
        new_state_basic = self.hass.states.get(ENTITY_VACUUM_BASIC)
        new_state_complete = self.hass.states.get(ENTITY_VACUUM_COMPLETE)

        self.assertEqual(old_state_basic, new_state_basic)
        self.assertNotEqual(old_state_complete, new_state_complete)
        self.assertEqual(STATE_ON, new_state_complete.state)
        self.assertEqual("Executing test_command({'p1': 3})",
                         new_state_complete.attributes[ATTR_STATUS])


text:
class LinkModelToTypeAndFormat < ActiveRecord::Migration
  def self.up
    remove_column :models,:model_type
    remove_column :models,:model_format
    add_column :models,:model_type_id,:integer
    add_column :models,:model_format_id,:integer
  end

  def self.down
    add_column :models,:model_type,:string
    add_column :models,:model_format,:string
    remove_column :models,:model_type_id
    remove_column :models,:model_format_id
  end
end