text:
module Knapsack
  module Distributors
    class BaseDistributor
      attr_reader :report, :node_tests, :test_file_pattern

      def initialize(args={})
        @report = args[:report] || raise('Missing report')
        @test_file_pattern = args[:test_file_pattern] || raise('Missing test_file_pattern')
        @ci_node_total = args[:ci_node_total] || raise('Missing ci_node_total')
        @ci_node_index = args[:ci_node_index] || raise('Missing ci_node_index')

        if ci_node_index >= ci_node_total
          raise("Node indexes are 0-based. Can't be higher or equal to the total number of nodes.")
        end
      end

      def ci_node_total
        @ci_node_total.to_i
      end

      def ci_node_index
        @ci_node_index.to_i
      end

      def tests_for_current_node
        tests_for_node(ci_node_index)
      end

      def tests_for_node(node_index)
        assign_test_files_to_node
        post_tests_for_node(node_index)
      end

      def assign_test_files_to_node
        default_node_tests
        post_assign_test_files_to_node
      end

      def all_tests
        @all_tests ||= Dir[test_file_pattern].sort
      end

      protected

      def post_tests_for_node(node_index)
        raise NotImplementedError
      end

      def post_assign_test_files_to_node
        raise NotImplementedError
      end

      def default_node_tests
        raise NotImplementedError
      end
    end
  end
end


text:
import { Injectable } from '@angular/core';
import { Host } from '../../util/host';
import { Observable } from 'rxjs/Rx';
import { PriceForCompany } from './priceForCompany';
import { HttpAuthService } from '../login/httpAuth.service';

const BASE_URL = Host.getURL();
const GET_CURRENT_URL = `${BASE_URL}${'finance/company/currentPrices'}`;
const POST_URL = `${BASE_URL}${'finance/company/newPrice'}`;

@Injectable()
export class CompaniesFinanceService {

  constructor(private httpAuthService: HttpAuthService) {
  }

  public getCurrentPriceList(): Observable<PriceForCompany[]> {
    return this.httpAuthService.get(GET_CURRENT_URL).map((resp) => {
        return resp.json().map(item => {
            return this.mapResponseItemToPrice(item);
          }
        );
      }
    );
  }

  public savePrice(priceDTO: PriceForCompany): Observable<any> {
    return this.httpAuthService.post(POST_URL, JSON.stringify(priceDTO));
  }

  private mapResponseItemToPrice(item: any): PriceForCompany {
    const price: PriceForCompany = new PriceForCompany();
    price.id = item.idPriceList;
    price.comment = item.comment;
    price.pricePerMonth = item.pricePerMonth;
    price.startTime = item.startTime;
    price.endTime = item.endTime;
    price.idWarehouseCompany = item.idWarehouseCompany;
    return price;
  }

}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Steven Graham's 101st Birthday
date: 2016-05-24
author: Philip Bowman
tags: weekly links, java
status: published
summary: Cum sociis natoque penatibus et.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/21/2016
  endDate: 07/23/2016
  ctyhocn: HARPAHX
  groupCode: SG1B
published: true
---
Nunc vestibulum pretium efficitur. Integer a dui in dui lobortis commodo in eget nulla. Etiam in libero lobortis lorem iaculis rhoncus. Quisque pharetra posuere lorem. Vestibulum malesuada nisl ex, a tristique sem tincidunt nec. Pellentesque pretium posuere ligula sit amet vestibulum. Curabitur egestas fringilla nibh, quis tempus nunc pharetra non. In mattis commodo nulla tempus blandit. Nulla facilisi. Proin aliquam, nisi non pellentesque pharetra, tortor eros aliquam leo, eu blandit sapien ipsum ac nisl.

* Proin at nisl posuere urna volutpat egestas at nec erat
* Cras lobortis dui quis lectus feugiat congue.

Nunc quis erat ut est tempus auctor. Donec varius, nulla a ullamcorper convallis, tellus odio sollicitudin augue, at suscipit est arcu nec libero. Sed sed gravida ex, sit amet cursus orci. Duis ultrices dui eu blandit vulputate. Nam vel pretium nisl, a tempor risus. Maecenas in arcu non diam rutrum consectetur. Aliquam ac bibendum justo. Maecenas arcu nisi, facilisis vitae egestas in, bibendum tempus diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris in mollis nibh. Aliquam eleifend lacinia sapien, a sollicitudin tortor vulputate quis.
Vivamus sed leo egestas, mattis felis a, auctor purus. Sed non dui diam. Nunc id enim ac neque consequat mollis in sed lorem. Vivamus egestas ut neque id lobortis. Suspendisse egestas mi id urna sollicitudin ultricies. Nunc eu arcu quis tortor porttitor tincidunt non ut nulla. Nam ut tempor neque. Vestibulum vel nisl mi. Proin sed tellus ultrices quam malesuada elementum. Quisque imperdiet, elit eget placerat malesuada, nisi enim vehicula nunc, at imperdiet lorem nibh eu nisl. Morbi posuere lacus risus, vestibulum iaculis nisi aliquam ac. Donec euismod dapibus gravida.


text:
<!DOCTYPE html>

<meta charset='utf-8'>
<title>ContactsManager Test: ContactsManager_save_urls_fullset</title>
<link rel="author" title="Intel" href="http://www.intel.com/">
<link rel="help" href="http://www.w3.org/2012/sysapps/contacts-manager-api/">


text:
export const SET_MENU_WECHAT_LIST = 'SET_MENU_WECHAT_LIST'

// contact
export const CONTACT_FRIENDS = 'CONTACT_FRIENDS'


text:
<?php

namespace Monolog\Formatter;

use Monolog\Logger;

class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('\Gelf\Message')) {
            $this->markTestSkipped("graylog2/gelf-php or mlehner/gelf-php is not installed");
        }
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testDefaultFormatter()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array(),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals(0, $message->getTimestamp());
        $this->assertEquals('log', $message->getShortMessage());
        $this->assertEquals('meh', $message->getFacility());
        $this->assertEquals(null, $message->getLine());
        $this->assertEquals(null, $message->getFile());
        $this->assertEquals($this->isLegacy() ? 3 : 'error', $message->getLevel());
        $this->assertNotEmpty($message->getHost());

        $formatter = new GelfMessageFormatter('mysystem');

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals('mysystem', $message->getHost());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithFileAndLine()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('file' => 'tests', 'line' => 14),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);
        $this->assertEquals('tests', $message->getFile());
        $this->assertEquals(14, $message->getLine());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     * @expectedException InvalidArgumentException
     */
    public function testFormatInvalidFails()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
        );

        $formatter->format($record);
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithContext()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_ctxt_from', $message_array);
        $this->assertEquals('logger', $message_array['_ctxt_from']);

        // Test with extraPrefix
        $formatter = new GelfMessageFormatter(null, null, 'CTX');
        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_CTXfrom', $message_array);
        $this->assertEquals('logger', $message_array['_CTXfrom']);
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithContextContainingException()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger', 'exception' => array(
                'class' => '\Exception',
                'file'  => '/some/file/in/dir.php:56',
                'trace' => array('/some/file/1.php:23', '/some/file/2.php:3'),
            )),
            'datetime' => new \DateTime("@0"),
            'extra' => array(),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $this->assertEquals("/some/file/in/dir.php", $message->getFile());
        $this->assertEquals("56", $message->getLine());
    }

    /**
     * @covers Monolog\Formatter\GelfMessageFormatter::format
     */
    public function testFormatWithExtra()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('from' => 'logger'),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => 'pair'),
            'message' => 'log',
        );

        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_key', $message_array);
        $this->assertEquals('pair', $message_array['_key']);

        // Test with extraPrefix
        $formatter = new GelfMessageFormatter(null, 'EXT');
        $message = $formatter->format($record);

        $this->assertInstanceOf('Gelf\Message', $message);

        $message_array = $message->toArray();

        $this->assertArrayHasKey('_EXTkey', $message_array);
        $this->assertEquals('pair', $message_array['_EXTkey']);
    }

    public function testFormatWithLargeData()
    {
        $formatter = new GelfMessageFormatter();
        $record = array(
            'level' => Logger::ERROR,
            'level_name' => 'ERROR',
            'channel' => 'meh',
            'context' => array('exception' => str_repeat(' ', 32767)),
            'datetime' => new \DateTime("@0"),
            'extra' => array('key' => str_repeat(' ', 32767)),
            'message' => 'log'
        );
        $message = $formatter->format($record);
        $messageArray = $message->toArray();

        // 200 for padding + metadata
        $length = 200;

        foreach ($messageArray as $key => $value) {
            if (!in_array($key, array('level', 'timestamp'))) {
                $length += strlen($value);
            }
        }

        // in graylog2/gelf-php before 1.4.1 empty strings are filtered and won't be included in the message
        // though it should be sufficient to ensure that the entire message length does not exceed the maximum
        // length being allowed
        $this->assertLessThanOrEqual(32766, $length, 'The message length is no longer than the maximum allowed length');
    }

    private function isLegacy()
    {
        return interface_exists('\Gelf\IMessagePublisher');
    }
}


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

  angular.module('pnc.artifacts').component('pncArtifactsDetailPage', {
    bindings: {
     artifact: '<',
     build: '<',
     usages: '<',
     revisions: '<'
    },
    templateUrl: 'artifacts/detail/pnc-artifacts-detail-page.html',
    controller: ['ArtifactModals', Controller]
  });

  function Controller(ArtifactModals) {
    const $ctrl = this;

    // -- Controller API --

    $ctrl.editQuality = editQuality;

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

    $ctrl.$onInit = () => {
      $ctrl.buildListDisplayFields = ['statusIcon', 'canonicalName', 'endTime', 'pushStatus'];
    };

    function editQuality() {
      return ArtifactModals.newArtifactQualityModal($ctrl.artifact)
          .result
          .then(updatedArtifact => $ctrl.artifact = updatedArtifact);
    }

  }

})();


text:
package org.drools.core.reteoo;

import java.util.Collection;
import java.util.Map;
import java.util.Queue;

import org.drools.core.WorkingMemoryEntryPoint;
import org.drools.core.common.EndOperationListener;
import org.drools.core.common.EventSupport;
import org.drools.core.common.InternalWorkingMemoryActions;
import org.drools.core.common.WorkingMemoryAction;
import org.kie.api.event.process.ProcessEventManager;
import org.kie.api.runtime.Channel;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.api.runtime.rule.LiveQuery;
import org.kie.api.runtime.rule.ViewChangedEventListener;
import org.kie.api.runtime.rule.EntryPoint;

/**
 * This is an interface for ReteooWorkingMemory implementations
 *
 * @author etirelli
 */
public interface ReteooWorkingMemoryInterface extends InternalWorkingMemoryActions,
                                             EventSupport,
                                             ProcessEventManager {

    Map<String, WorkingMemoryEntryPoint> getWorkingMemoryEntryPoints();

    void fireUntilHalt();

    void fireUntilHalt( AgendaFilter agendaFilterWrapper );

    ProcessInstance createProcessInstance( String processId, Map<String, Object> parameters );

    ProcessInstance startProcessInstance( long processInstanceId );

    void registerChannel( String name, Channel channel );

    void unregisterChannel( String name );

    Queue<WorkingMemoryAction> getActionQueue();

    LiveQuery openLiveQuery( String query, Object[] arguments, ViewChangedEventListener listener );

    void setEndOperationListener( EndOperationListener listener );

    long getLastIdleTimestamp();

}


text:
package macaron

import (
	"crypto/md5"
	"encoding/hex"
	"html/template"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/Unknwon/com"

	"github.com/go-macaron/inject"
)

// Locale reprents a localization interface.
type Locale interface {
	Language() string
	Tr(string, ...interface{}) string
}

// RequestBody represents a request body.
type RequestBody struct {
	reader io.ReadCloser
}

// Bytes reads and returns content of request body in bytes.
func (rb *RequestBody) Bytes() ([]byte, error) {
	return ioutil.ReadAll(rb.reader)
}

// String reads and returns content of request body in string.
func (rb *RequestBody) String() (string, error) {
	data, err := rb.Bytes()
	return string(data), err
}

// ReadCloser returns a ReadCloser for request body.
func (rb *RequestBody) ReadCloser() io.ReadCloser {
	return rb.reader
}

// Request represents an HTTP request received by a server or to be sent by a client.
type Request struct {
	*http.Request
}

func (r *Request) Body() *RequestBody {
	return &RequestBody{r.Request.Body}
}

// Context represents the runtime context of current request of Macaron instance.
// It is the integration of most frequently used middlewares and helper methods.
type Context struct {
	inject.Injector
	handlers []Handler
	action   Handler
	index    int

	*Router
	Req    Request
	Resp   ResponseWriter
	params Params
	Render // Not nil only if you use macaran.Render middleware.
	Locale
	Data map[string]interface{}
}

func (c *Context) handler() Handler {
	if c.index < len(c.handlers) {
		return c.handlers[c.index]
	}
	if c.index == len(c.handlers) {
		return c.action
	}
	panic("invalid index for context handler")
}

func (c *Context) Next() {
	c.index += 1
	c.run()
}

func (c *Context) Written() bool {
	return c.Resp.Written()
}

func (c *Context) run() {
	for c.index <= len(c.handlers) {
		vals, err := c.Invoke(c.handler())
		if err != nil {
			panic(err)
		}
		c.index += 1

		// if the handler returned something, write it to the http response
		if len(vals) > 0 {
			ev := c.GetVal(reflect.TypeOf(ReturnHandler(nil)))
			handleReturn := ev.Interface().(ReturnHandler)
			handleReturn(c, vals)
		}

		if c.Written() {
			return
		}
	}
}

// RemoteAddr returns more real IP address.
func (ctx *Context) RemoteAddr() string {
	addr := ctx.Req.Header.Get("X-Real-IP")
	if len(addr) == 0 {
		addr = ctx.Req.Header.Get("X-Forwarded-For")
		if addr == "" {
			addr = ctx.Req.RemoteAddr
			if i := strings.LastIndex(addr, ":"); i > -1 {
				addr = addr[:i]
			}
		}
	}
	return addr
}

func (ctx *Context) renderHTML(status int, setName, tplName string, data ...interface{}) {
	if ctx.Render == nil {
		panic("renderer middleware hasn't been registered")
	}
	if len(data) <= 0 {
		ctx.Render.HTMLSet(status, setName, tplName, ctx.Data)
	} else if len(data) == 1 {
		ctx.Render.HTMLSet(status, setName, tplName, data[0])
	} else {
		ctx.Render.HTMLSet(status, setName, tplName, data[0], data[1].(HTMLOptions))
	}
}

// HTML calls Render.HTML but allows less arguments.
func (ctx *Context) HTML(status int, name string, data ...interface{}) {
	ctx.renderHTML(status, _DEFAULT_TPL_SET_NAME, name, data...)
}

// HTML calls Render.HTMLSet but allows less arguments.
func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{}) {
	ctx.renderHTML(status, setName, tplName, data...)
}

func (ctx *Context) Redirect(location string, status ...int) {
	code := http.StatusFound
	if len(status) == 1 {
		code = status[0]
	}

	http.Redirect(ctx.Resp, ctx.Req.Request, location, code)
}

// Maximum amount of memory to use when parsing a multipart form.
// Set this to whatever value you prefer; default is 10 MB.
var MaxMemory = int64(1024 * 1024 * 10)

func (ctx *Context) parseForm() {
	if ctx.Req.Form != nil {
		return
	}

	contentType := ctx.Req.Header.Get(_CONTENT_TYPE)
	if (ctx.Req.Method == "POST" || ctx.Req.Method == "PUT") &&
		len(contentType) > 0 && strings.Contains(contentType, "multipart/form-data") {
		ctx.Req.ParseMultipartForm(MaxMemory)
	} else {
		ctx.Req.ParseForm()
	}
}

// Query querys form parameter.
func (ctx *Context) Query(name string) string {
	ctx.parseForm()
	return ctx.Req.Form.Get(name)
}

// QueryTrim querys and trims spaces form parameter.
func (ctx *Context) QueryTrim(name string) string {
	return strings.TrimSpace(ctx.Query(name))
}

// QueryStrings returns a list of results by given query name.
func (ctx *Context) QueryStrings(name string) []string {
	ctx.parseForm()

	vals, ok := ctx.Req.Form[name]
	if !ok {
		return []string{}
	}
	return vals
}

// QueryEscape returns escapred query result.
func (ctx *Context) QueryEscape(name string) string {
	return template.HTMLEscapeString(ctx.Query(name))
}

// QueryInt returns query result in int type.
func (ctx *Context) QueryInt(name string) int {
	return com.StrTo(ctx.Query(name)).MustInt()
}

// QueryInt64 returns query result in int64 type.
func (ctx *Context) QueryInt64(name string) int64 {
	return com.StrTo(ctx.Query(name)).MustInt64()
}

// QueryFloat64 returns query result in float64 type.
func (ctx *Context) QueryFloat64(name string) float64 {
	v, _ := strconv.ParseFloat(ctx.Query(name), 64)
	return v
}

// Params returns value of given param name.
// e.g. ctx.Params(":uid") or ctx.Params("uid")
func (ctx *Context) Params(name string) string {
	if len(name) == 0 {
		return ""
	}
	if len(name) > 1 && name[0] != ':' {
		name = ":" + name
	}
	return ctx.params[name]
}

// SetParams sets value of param with given name.
func (ctx *Context) SetParams(name, val string) {
	if !strings.HasPrefix(name, ":") {
		name = ":" + name
	}
	ctx.params[name] = val
}

// ParamsEscape returns escapred params result.
// e.g. ctx.ParamsEscape(":uname")
func (ctx *Context) ParamsEscape(name string) string {
	return template.HTMLEscapeString(ctx.Params(name))
}

// ParamsInt returns params result in int type.
// e.g. ctx.ParamsInt(":uid")
func (ctx *Context) ParamsInt(name string) int {
	return com.StrTo(ctx.Params(name)).MustInt()
}

// ParamsInt64 returns params result in int64 type.
// e.g. ctx.ParamsInt64(":uid")
func (ctx *Context) ParamsInt64(name string) int64 {
	return com.StrTo(ctx.Params(name)).MustInt64()
}

// ParamsFloat64 returns params result in int64 type.
// e.g. ctx.ParamsFloat64(":uid")
func (ctx *Context) ParamsFloat64(name string) float64 {
	v, _ := strconv.ParseFloat(ctx.Params(name), 64)
	return v
}

// GetFile returns information about user upload file by given form field name.
func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
	return ctx.Req.FormFile(name)
}

// SaveToFile reads a file from request by field name and saves to given path.
func (ctx *Context) SaveToFile(name, savePath string) error {
	fr, _, err := ctx.GetFile(name)
	if err != nil {
		return err
	}
	defer fr.Close()

	fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return err
	}
	defer fw.Close()

	_, err = io.Copy(fw, fr)
	return err
}

// SetCookie sets given cookie value to response header.
// FIXME: IE support? http://golanghome.com/post/620#reply2
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
	cookie := http.Cookie{}
	cookie.Name = name
	cookie.Value = url.QueryEscape(value)

	if len(others) > 0 {
		switch v := others[0].(type) {
		case int:
			cookie.MaxAge = v
		case int64:
			cookie.MaxAge = int(v)
		case int32:
			cookie.MaxAge = int(v)
		}
	}

	cookie.Path = "/"
	if len(others) > 1 {
		if v, ok := others[1].(string); ok && len(v) > 0 {
			cookie.Path = v
		}
	}

	if len(others) > 2 {
		if v, ok := others[2].(string); ok && len(v) > 0 {
			cookie.Domain = v
		}
	}

	if len(others) > 3 {
		switch v := others[3].(type) {
		case bool:
			cookie.Secure = v
		default:
			if others[3] != nil {
				cookie.Secure = true
			}
		}
	}

	if len(others) > 4 {
		if v, ok := others[4].(bool); ok && v {
			cookie.HttpOnly = true
		}
	}

	ctx.Resp.Header().Add("Set-Cookie", cookie.String())
}

// GetCookie returns given cookie value from request header.
func (ctx *Context) GetCookie(name string) string {
	cookie, err := ctx.Req.Cookie(name)
	if err != nil {
		return ""
	}
	val, _ := url.QueryUnescape(cookie.Value)
	return val
}

// GetCookieInt returns cookie result in int type.
func (ctx *Context) GetCookieInt(name string) int {
	return com.StrTo(ctx.GetCookie(name)).MustInt()
}

// GetCookieInt64 returns cookie result in int64 type.
func (ctx *Context) GetCookieInt64(name string) int64 {
	return com.StrTo(ctx.GetCookie(name)).MustInt64()
}

// GetCookieFloat64 returns cookie result in float64 type.
func (ctx *Context) GetCookieFloat64(name string) float64 {
	v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64)
	return v
}

var defaultCookieSecret string

// SetDefaultCookieSecret sets global default secure cookie secret.
func (m *Macaron) SetDefaultCookieSecret(secret string) {
	defaultCookieSecret = secret
}

// SetSecureCookie sets given cookie value to response header with default secret string.
func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) {
	ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...)
}

// GetSecureCookie returns given cookie value from request header with default secret string.
func (ctx *Context) GetSecureCookie(key string) (string, bool) {
	return ctx.GetSuperSecureCookie(defaultCookieSecret, key)
}

// SetSuperSecureCookie sets given cookie value to response header with secret string.
func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
	m := md5.Sum([]byte(secret))
	secret = hex.EncodeToString(m[:])
	text, err := com.AESEncrypt([]byte(secret), []byte(value))
	if err != nil {
		panic("error encrypting cookie: " + err.Error())
	}
	ctx.SetCookie(name, hex.EncodeToString(text), others...)
}

// GetSuperSecureCookie returns given cookie value from request header with secret string.
func (ctx *Context) GetSuperSecureCookie(secret, key string) (string, bool) {
	val := ctx.GetCookie(key)
	if val == "" {
		return "", false
	}

	data, err := hex.DecodeString(val)
	if err != nil {
		return "", false
	}

	m := md5.Sum([]byte(secret))
	secret = hex.EncodeToString(m[:])
	text, err := com.AESDecrypt([]byte(secret), data)
	return string(text), err == nil
}

func (ctx *Context) setRawContentHeader() {
	ctx.Resp.Header().Set("Content-Description", "Raw content")
	ctx.Resp.Header().Set("Content-Type", "text/plain")
	ctx.Resp.Header().Set("Expires", "0")
	ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
	ctx.Resp.Header().Set("Pragma", "public")
}

// ServeContent serves given content to response.
func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
	modtime := time.Now()
	for _, p := range params {
		switch v := p.(type) {
		case time.Time:
			modtime = v
		}
	}

	ctx.setRawContentHeader()
	http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
}

// ServeFileContent serves given file as content to response.
func (ctx *Context) ServeFileContent(file string, names ...string) {
	var name string
	if len(names) > 0 {
		name = names[0]
	} else {
		name = path.Base(file)
	}

	f, err := os.Open(file)
	if err != nil {
		if Env == PROD {
			http.Error(ctx.Resp, "Internal Server Error", 500)
		} else {
			http.Error(ctx.Resp, err.Error(), 500)
		}
		return
	}
	defer f.Close()

	ctx.setRawContentHeader()
	http.ServeContent(ctx.Resp, ctx.Req.Request, name, time.Now(), f)
}

// ServeFile serves given file to response.
func (ctx *Context) ServeFile(file string, names ...string) {
	var name string
	if len(names) > 0 {
		name = names[0]
	} else {
		name = path.Base(file)
	}
	ctx.Resp.Header().Set("Content-Description", "File Transfer")
	ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
	ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
	ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
	ctx.Resp.Header().Set("Expires", "0")
	ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
	ctx.Resp.Header().Set("Pragma", "public")
	http.ServeFile(ctx.Resp, ctx.Req.Request, file)
}

// ChangeStaticPath changes static path from old to new one.
func (ctx *Context) ChangeStaticPath(oldPath, newPath string) {
	if !filepath.IsAbs(oldPath) {
		oldPath = filepath.Join(Root, oldPath)
	}
	dir := statics.Get(oldPath)
	if dir != nil {
		statics.Delete(oldPath)

		if !filepath.IsAbs(newPath) {
			newPath = filepath.Join(Root, newPath)
		}
		*dir = http.Dir(newPath)
		statics.Set(dir)
	}
}


text:
{% extends "base.html" %}
{% block title %}Longhand{% endblock %}
{% block header %}Longhand{% endblock %}
{% block content %}

Convert number to cardinal form

<form id="form" action="#" onsubmit="return getLonghand()">

        Number

            <input type="tel" id="number" placeholder="Number" class="form-control">

                <button class="btn btn-primary" type="submit">Submit</button>

</form>

{% endblock %}


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

{% block content %}

Email Templates

Add Email Template

            <form action="{% url "create_email_template" %}" method="POST">
                {% csrf_token %}
                {% include "email_templates/_form.html" %}
                <button type="submit">Add</button>
                Cancel
            </form>

{% endblock %}

{% block scripts %}


text:
<link rel="import" href="toarm-toast-list.html">
<link rel="import" href="toarm-toast-error.html">
<link rel="import" href="toarm-toast-warning.html">
<link rel="import" href="toarm-toast-custom.html">


text:
typedef CGAL::Simple_cartesian<double> K;
typedef K::Point_2 Point;
typedef K::Vector_2 Vector;
typedef K::Iso_rectangle_2 Iso_rectangle;
typedef CGAL::Random_points_in_square_2<Point> Random_points_iterator;
typedef CGAL::Counting_iterator<Random_points_iterator> N_Random_points_iterator;
typedef CGAL::Search_traits_2<K> Traits;
typedef Point_with_info_helper<Point>::type                                   Point_with_info;
typedef Point_property_map<Point>                                             Ppmap;
typedef CGAL::Search_traits_adapter<Point_with_info,Ppmap,Traits>             Traits_with_info;

template <class SearchTraits>
void run(std::list<Point> all_points)
{
  typedef CGAL::Fuzzy_iso_box<SearchTraits> Fuzzy_box;

  // Insert also the N points in the tree
  CGAL::Kd_tree<SearchTraits> tree(
    boost::make_transform_iterator(all_points.begin(),Create_point_with_info<typename SearchTraits::Point_d>()),
    boost::make_transform_iterator(all_points.end(),Create_point_with_info<typename SearchTraits::Point_d>())
  );

  Point p(0.1, 0.2);
  Point q(0.3, 0.5);
  typename SearchTraits::Point_d pp(p);
  typename SearchTraits::Point_d qq(q);

  Iso_rectangle exact_ic(p,q);

  Fuzzy_box exact_range(pp,qq);

  std::list<typename SearchTraits::Point_d> result;
  // Searching the box r exactly
  tree.search( std::back_inserter( result ), exact_range);

  tree.search(CGAL::Emptyset_iterator(), Fuzzy_box(p,q) ); //test compilation when Point != Traits::Point_d

  // test the results of the exact query
  std::list<Point> copy_all_points(all_points);
  for (typename std::list<typename SearchTraits::Point_d>::iterator pt=result.begin(); (pt != result.end()); ++pt) {
    assert(! exact_ic.has_on_unbounded_side(get_point(*pt)) || exact_ic.has_on_boundary(get_point(*pt)));
    copy_all_points.remove(get_point(*pt));
  }

  for (std::list<Point>::iterator pt=copy_all_points.begin(); (pt != copy_all_points.end()); ++pt) {
    assert(exact_ic.has_on_unbounded_side(*pt) || exact_ic.has_on_boundary(*pt));
  }

  result.clear();
  // approximate range searching using value 0.1 for fuzziness parameter
  Fuzzy_box approximate_range(pp,qq,0.05);
  Iso_rectangle inner_ic(p+ 0.05*Vector(1,1),q-0.05*Vector(1,1));
  Iso_rectangle outer_ic(p- 0.05*Vector(1,1),q+0.05*Vector(1,1));

  tree.search(std::back_inserter( result ), approximate_range);
  // test the results of the approximate query
  for (typename std::list<typename SearchTraits::Point_d>::iterator pt=result.begin(); (pt != result.end()); ++pt) {
    // a point we found may be slighlty outside the isorectangle
    assert(! outer_ic.has_on_unbounded_side(get_point(*pt)) || outer_ic.has_on_boundary(get_point(*pt)));
    all_points.remove(get_point(*pt));
  }

  for (std::list<Point>::iterator pt=all_points.begin(); (pt != all_points.end()); ++pt) {
    assert(inner_ic.has_on_unbounded_side(*pt) || inner_ic.has_on_boundary(*pt));
  }
  std::cout << "done" << std::endl;
}

int main() {

  const int N=10000;

  // generator for random data points in the square ( (-1,-1), (1,1) )
  Random_points_iterator rpit( 1.0);

  // construct list containing N random points
  std::list<Point> all_points(N_Random_points_iterator(rpit,0),
			      N_Random_points_iterator(N));

  run<Traits>(all_points);
  run<Traits_with_info>(all_points);

  return 0;
}


text:
@protocol P2UXCacheable <NSObject>
- (NSDictionary*)cacheState;
- (void)restoreState:(NSDictionary*)state;
@optional
- (NSString*)cacheName;
@end


text:
/**
 * @providesModule ArityError.react
 */
var React = require('react');
var AudienceInsightsContainer = React.createClass({
  renderComponent(AudienceInsights: ReactClass): ReactElement {
    return <AudienceInsights />;
  },
});

module.exports = AudienceInsightsContainer;


text:
import React, { Component, PropTypes } from 'react';

class MenuOverlay extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        const { menuItems, menuTitle, onTitleClick } = this.props;
        let boxStyle = {
            display: 'inline-block'
        };
        let items = [];
        if(menuItems && menuItems.length > 0){
            menuItems.forEach((item, index) => {
                items.push(

                        {item.label}

                )
            });
        }
        let content = (

                    ×
                    {menuTitle}

                {items}

        );
        return (

                {content}

        );
    }
}

export default MenuOverlay;


text:
headless-firefox Cookbook
=========================

Install and prepare firefox (or iceweasel) for cucumber testing in a headless
environment.

Inspiration from [this blog
post](http://blog.aentos.com/post/4368402854/easy-setup-for-your-cucumber-scenarios-using-the).

Requirements
------------

Currently only tested on Debian.  Should also work on other Debian flavored
distros.

Usage
-----

To get cucumber working in the selenium driver using a headless X server, xvfb:

1. Add ```recipe[headless-firefox]``` to your run list.

2. Add

        gem 'headless'

   to your ```Gemfile``` under ```group :test```.

3. In your Cucumber settings env setup (e.g.
   ```features/support/env_custom.rb```) add:

        if ENV["SELENIUM_HEADLESS"] == 'true'
          require "headless"
          @headless = Headless.new.start
        end

License and Authors
-------------------

See [LICENSE](LICENSE).


text:
Hook
----

TODO.

Instruction
~~~~~~~~~~~

.. include:: /build/autogen/hilti-instr-hook.rst


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/jdbc
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

    <context:component-scan base-package="com.ihtsdo.snomed" />

    <jpa:repositories base-package="com.ihtsdo.snomed.repository" entity-manager-factory-ref="entityManagerFactory" />

    <!-- VALIDATOR -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

</beans>


text:
% Version 1.5.1
% greg
% 04/30/2013

Release 1.5.1
===========

Date: 2013-04-30

Notable Changes:

* Bug fixes
* Job Notification Plugins
    * Jobs can now trigger notification plugins in addition to the built-in email and webhook
    * plugins can be developed in Java or with a new Groovy DSL
    * See the [Notification Plugin Development](../developer/notification-plugin-development.html) Chapter.
    * Example code at [dtolabs/rundeck/examples](https://github.com/dtolabs/rundeck/tree/development/examples)
* Notification 'onstart' trigger
    * Jobs can now cause a notification trigger when started via the 'onstart' trigger
* Notifications can now use the email address of the user who executed a job, as `${job.user.email}`. (You can set an email for your account in the Profile page.)

Contributors:

* Alex Honor
* Charles Duffy
* Greg Schueler
* John Burbridge
* Jonathan Li
* Kim Ho

Issues:

* [Add static ordering to job options instead of always sorted by name](https://github.com/dtolabs/rundeck/issues/361)
* [Add job notification plugins](https://github.com/dtolabs/rundeck/issues/360)
* [Big number as option default causes exception on load job from xml](https://github.com/dtolabs/rundeck/issues/356)
* [Job XML parse fails if "false" value in an command step](https://github.com/dtolabs/rundeck/issues/353)
* [Local error handling command lost on export / import](https://github.com/dtolabs/rundeck/issues/351)
* [error handler has exception when attempting to handle No Matched Nodes failure for a job reference](https://github.com/dtolabs/rundeck/issues/350)
* [Multi-value options not pre-populated when doing a "run again"](https://github.com/dtolabs/rundeck/issues/346)
* [API: add "asUser" feature for running/killing jobs and executions](https://github.com/dtolabs/rundeck/issues/341)
* [init script doesn't work on CentOS (one-line fix provided)](https://github.com/dtolabs/rundeck/issues/338)
* [job group changes before authorization check in 1.5](https://github.com/dtolabs/rundeck/issues/330)
* [Many ACL policy files can slow down the Project drop down menu](https://github.com/dtolabs/rundeck/issues/328)
* [Unable to generate an api-token on rundeck 1.5](https://github.com/dtolabs/rundeck/issues/327)
* [Cannot send notification email using 1.5](https://github.com/dtolabs/rundeck/issues/325)
* [Long description for Option causes Job import failure in 1.5 for jobs exported from 1.4](https://github.com/dtolabs/rundeck/issues/320)
* [1.5: GUI regression: Success rate % in job popup always shows 0%](https://github.com/dtolabs/rundeck/issues/316)
* [1.5: GUI regression: Job execution follow page: progress meter stuck](https://github.com/dtolabs/rundeck/issues/315)
* [Invalid XML char in log output breaks CLI output follow mode.](https://github.com/dtolabs/rundeck/issues/313)
* [1.5: html and ajax errors about "Timeout trying to lock table"](https://github.com/dtolabs/rundeck/issues/312)
* [sudo responder hangs](https://github.com/dtolabs/rundeck/issues/311)
* [CLIUtils.generateArgline does not quote IFS characters other than space](https://github.com/dtolabs/rundeck/issues/298)
* [documentation: upgrade guide "admin" aclpolicy doesn't allow all permissions](https://github.com/dtolabs/rundeck/issues/280)
* [Add Job Notification/webhook on job start](https://github.com/dtolabs/rundeck/issues/250)
* [projects folder under version control - .svn folder treated as project](https://github.com/dtolabs/rundeck/issues/209)
* [incorrect aclpolicy yaml structure can cause NPE](https://github.com/dtolabs/rundeck/issues/206)
* [Options are not passed correctly to programs](https://github.com/dtolabs/rundeck/issues/201)
* [Allow Email Address substitution in notification recipients list](https://github.com/dtolabs/rundeck/issues/165)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/wamp/www/Tienda/escritorio/controladores/controladorUsuarios.php</file>
            <file>file:/C:/wamp/www/Tienda/escritorio/admin/paginas/agregarProducto.php</file>
        </group>
    </open-files>
</project-private>


text:
package com.vaadin.components.grid.selection;

import com.google.gwt.core.client.JavaScriptObject;
import com.vaadin.client.widget.grid.selection.SelectionModelNone;
import com.vaadin.components.common.js.JS;
import com.vaadin.components.common.js.JSArray;

/**
 * An {@link IndexBasedSelectionModel} for selection disabled.
 */
public class IndexBasedSelectionModelDisabled extends
        SelectionModelNone<Object> implements IndexBasedSelectionModel {

    @Override
    public int size() {
        return 0;
    }

    @Override
    public JSArray<Object> selected(JavaScriptObject mapper, Integer from,
            Integer to) {
        return JS.createArray();
    }

    @Override
    public JSArray<Object> deselected(JavaScriptObject mapper, Integer from,
            Integer to) {
        return JS.createArray();
    }

    @Override
    public boolean select(int index, boolean skipOwnEvents) {
        return false;
    }

    @Override
    public boolean deselect(int index, boolean skipOwnEvents) {
        return false;
    }

    @Override
    public void clear() {
    }

    @Override
    public void selectAll() {
    }

    @Override
    public IndexBasedSelectionMode getMode() {
        return IndexBasedSelectionMode.DISABLED;
    }

    @Override
    public void dataSizeUpdated(int newSize) {
    }

}


text:
function PUT() {
	var xhttp = new XMLHttpRequest();
	var link = document.getElementById('linkChosen').value;
	var update1 = document.getElementById('update1').value;
	var update2 = document.getElementById('update2').value;
	if ((update1 == "") || (update2 == "") || ((update1) == "" && (update2 == ""))) {
		document.getElementById("error").className = "alert alert-danger";
		document.getElementById("send").setAttribute("type", "button");
		document.getElementById('error').innerHTML = "Stop! You must fill all fields with values, no blanks!";
		refresh(1000);
	} else {
		var reqMethod = "PUT";
		var async = true;
		var data = {
			name: update1,
			email: update2
		};
		var string = JSON.stringify(data);
		xhttp.onreadystatechange = function() {
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				console.log(xhttp.responseText);
			}
		}
		xhttp.open(reqMethod, link, async);
		xhttp.setRequestHeader("Content-type", "application/json");
		xhttp.send(string);
		document.getElementById("success").className = "alert alert-success";
		document.getElementById("send").setAttribute("type", "button");
		document.getElementById('success').innerHTML = "Success! You updated the username to: " + update1 + " and email to: " + update2 + "!";
		refresh(2400);
	}
}

function refresh(timeoutPeriod) {
	refresh = setTimeout(function() {
		window.location.reload(true);
	}, timeoutPeriod);
}


text:
$(document).ready(function(){
	var currencies = [];
	var clickedElement = {};

	//Fetches newest exchange rate
	function getLatestExt(){
		chrome.runtime.sendMessage({req: "currency"}, function(response) {
			currencies = JSON.parse(response.currency);
		  /*
			$('body *').each(function(){
				var obj = $(this).text();
				var match = obj.match(/^\$\d+(?:\.\d+)?\s*$/);
				if(match){
					var number = Number(obj.replace(/[^0-9\.]+/g,""));
					$(this).append('

'+Math.round(currencies[0].value*number)+' Kr

  ');
				}
			});
		*/
	})
	};
	//Do this once
	getLatestExt();

	$(document).on('mousedown', function(event){
		clickedElement = $(event.target);
	})

	chrome.runtime.onMessage.addListener(
		function(request, sender, sendResponse) {
			if (request.req == "convert"){
				var obj = clickedElement.text();
				var match = obj.match(/^\$\d+(?:\.\d+)?\s*$/);
				if(match){
					var number = Number(obj.replace(/[^0-9\.]+/g,""));
					var currElement = $('#local');
					//currElement.val(number);
					//console.log(number);
					clickedElement.append('

'+Math.round(currencies[0].value*number)+' Kr

');
				}
			}
		});

	function deselect(element) {
		element.slideFadeToggle(function() {
			element.next().removeClass("selected");
		});
	}

	$(function() {
		$(document).on('click','#peningar', function() {
			var tooltip = $(this).prev();
			if(tooltip.hasClass("selected")) {
				deselect(tooltip);
			} else {
				tooltip.addClass("selected");
				tooltip.css('top',$(this).position().top+20);
				tooltip.css('left',$(this).position().left);
				tooltip.slideFadeToggle();
			}
			return false;
		});

	});

	$.fn.slideFadeToggle = function(easing, callback) {
		return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
	};

});


text:
<?php

namespace Spoort\Bundle\Symfony2EconomicBundle\Entity\Handle;

use Spoort\Bundle\Symfony2EconomicBundle\Entity\EconomicSoapEntity;

class CostTypeHandle extends EconomicSoapEntity
{

    /** @var string $Number */
    private $Number;

    /**
     * @return string
     */
    public function getNumber()
    {
        return $this->Number;
    }

    /**
     * @param string $number
     * @return self
     */
    public function setNumber($number)
    {
        $this->Number = $number;

        return $this;
    }
}


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "adrProductDetail";
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    $.__views.winDetail = Ti.UI.createWindow({
        backgroundColor: Alloy.Globals.ThemeStyles.win.backgroundColor,
        navBarHidden: true,
        orientationModes: [ Ti.UI.PORTRAIT ],
        id: "winDetail"
    });
    $.__views.winDetail && $.addTopLevelView($.__views.winDetail);
    var __alloyId2 = [];
    $.__views.scrollableView = Ti.UI.createScrollableView({
        showPagingControl: false,
        pagingControlColor: Alloy.Globals.ThemeStyles.win.backgroundColor,
        height: "180dp",
        left: "14dp",
        right: "14dp",
        top: "58dp",
        bottom: "10dp",
        zIndex: 4,
        views: __alloyId2,
        id: "scrollableView"
    });
    $.__views.winDetail.add($.__views.scrollableView);
    var __alloyId3 = [];
    $.__views.rowTitle = Ti.UI.createTableViewRow({
        height: Ti.UI.SIZE,
        selectionStyle: "none",
        backgroundColor: "transparent",
        layout: "vertical",
        id: "rowTitle"
    });
    __alloyId3.push($.__views.rowTitle);
    $.__views.lblName = Ti.UI.createLabel({
        color: Alloy.Globals.ThemeStyles.detail_title.color,
        font: Alloy.Globals.ThemeStyles.detail_title.font,
        top: 0,
        left: "14dp",
        wordWrap: true,
        height: Ti.UI.SIZE,
        id: "lblName"
    });
    $.__views.rowTitle.add($.__views.lblName);
    $.__views.tagView = Ti.UI.createView({
        height: Ti.UI.SIZE,
        layout: "horizontal",
        left: "14dp",
        id: "tagView"
    });
    $.__views.rowTitle.add($.__views.tagView);
    $.__views.rowDetail = Ti.UI.createTableViewRow({
        height: "auto",
        selectionStyle: "none",
        backgroundColor: "transparent",
        id: "rowDetail"
    });
    __alloyId3.push($.__views.rowDetail);
    $.__views.lblDetail = Ti.UI.createLabel({
        color: Alloy.Globals.ThemeStyles.detail_body.color,
        left: "14dp",
        right: "14dp",
        top: "10dp",
        wordWrap: true,
        font: Alloy.Globals.ThemeStyles.detail_body.font,
        id: "lblDetail"
    });
    $.__views.rowDetail.add($.__views.lblDetail);
    $.__views.detailTable = Ti.UI.createTableView({
        showVerticalScrollIndicator: false,
        height: "auto",
        top: "248dp",
        backgroundColor: "transparent",
        separatorColor: "transparent",
        data: __alloyId3,
        id: "detailTable"
    });
    $.__views.winDetail.add($.__views.detailTable);
    exports.destroy = function() {};
    _.extend($, $.__views);
    var args = arguments[0] || {};
    require("apiHelper");
    var headerBar = Alloy.createController("adrHeaderBar", {
        parentView: $.winDetail,
        title: "Product Detail",
        isFlyout: false
    }).getView();
    $.winDetail.add(headerBar);
    var Views = [];
    for (var i = 0; i < args.ProductItem.pictures.length; i++) {
        var view = Ti.UI.createView({
            backgroundColor: "transparent",
            height: Ti.UI.SIZE
        });
        var anImageView = Ti.UI.createImageView({
            height: Alloy.Globals.ThemeStyles.product_slider.height,
            width: Ti.Platform.displayCaps.platformWidth - 28 * Alloy.Globals.dp,
            preventDefaultImage: true,
            hires: true,
            image: args.ProductItem.pictures[i]
        });
        view.add(anImageView);
        Views.push(view);
    }
    $.scrollableView.views = Views;
    $.lblName.text = args.ProductItem.title;
    $.lblDetail.text = args.ProductItem.body;
    for (var i = 0; i < args.ProductItem.tags.length; i++) {
        var lblTag = Ti.UI.createLabel({
            color: Alloy.Globals.ThemeStyles.detail_tags.color,
            font: Alloy.Globals.ThemeStyles.detail_tags.font,
            left: 0
        });
        lblTag.text = i + 1 == args.ProductItem.tags.length ? args.ProductItem.tags[i] : args.ProductItem.tags[i] + ", ";
        $.tagView.add(lblTag);
    }
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
package com.swiftype.api.easy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import com.swiftype.api.easy.helper.SearchOptions;
import com.swiftype.api.easy.helper.SearchResult;
import com.swiftype.api.easy.helper.SuggestResult;
import com.swiftype.api.easy.helper.SwiftypeConfig;

public class DocumentTypesApiTest {
	private static final String ENGINE_ID = "engine_id1";
	private static final String DOCUMENT_TYPE_ID = "id1";

	private DocumentTypesApi api;

	@Before
	public void setUp() throws Exception {
		final SwiftypeConfig config = SwiftypeConfig.INSTANCE;
		config.setApiHost("127.0.0.1:9292");
		api = new DocumentTypesApi(ENGINE_ID);
	}

	@Test
	public void testGetAll() {
		final DocumentType[] documentTypes = api.getAll();
		assertEquals(2, documentTypes.length);
		assertEquals("doctype1", documentTypes[0].getName());
		assertEquals(ENGINE_ID, documentTypes[0].getEngineId());
	}

	@Test
	public void testGet() {
		final DocumentType documentType = api.get(DOCUMENT_TYPE_ID);
		assertEquals(DOCUMENT_TYPE_ID, documentType.getSlug());
		assertEquals(ENGINE_ID, documentType.getEngineId());
	}

	@Test
	public void testCreate() {
		final DocumentType documentType = api.create(DOCUMENT_TYPE_ID);
		assertEquals(DOCUMENT_TYPE_ID, documentType.getSlug());
		assertEquals(ENGINE_ID, documentType.getEngineId());
	}

	@Test
	public void testDelete() {
		assertTrue(api.destroy(DOCUMENT_TYPE_ID));
	}

	@Test
	public void testSearch() {
		final SearchResult results = api.search(DOCUMENT_TYPE_ID, "query");
		assertEquals(1, results.getInfo().page);
	}

	@Test
	public void testSearchWithOptions() {
		final int page = 2;
		final SearchOptions options = new SearchOptions.Builder().page(page).build();
		final SearchResult results = api.search(DOCUMENT_TYPE_ID, "query", options);
		assertEquals(page, results.getInfo().page);
	}

	@Test
	public void testSuggest() {
		final SuggestResult results = api.suggest(DOCUMENT_TYPE_ID, "query");
		assertEquals(1, results.getResults().size());
	}

	@Test
	public void testSuggestWithOptions() {
		final SearchOptions options = new SearchOptions.Builder().page(2).build();
		final SuggestResult results = api.suggest(DOCUMENT_TYPE_ID, "query", options);
		assertEquals(1, results.getResults().size());
	}
}


text:
'use strict';

/* global VideoPipe */

const video1 = document.querySelector('video#video1');
const video2 = document.querySelector('video#video2');

const statusDiv = document.querySelector('div#status');

const audioCheckbox = document.querySelector('input#audio');

const startButton = document.querySelector('button#start');
const callButton = document.querySelector('button#call');
const insertRelayButton = document.querySelector('button#insertRelay');
const hangupButton = document.querySelector('button#hangup');

startButton.onclick = start;
callButton.onclick = call;
insertRelayButton.onclick = insertRelay;
hangupButton.onclick = hangup;

const pipes = [];

let localStream;
let remoteStream;

function gotStream(stream) {
  console.log('Received local stream');
  video1.srcObject = stream;
  localStream = stream;
  callButton.disabled = false;
}

function gotremoteStream(stream) {
  remoteStream = stream;
  video2.srcObject = stream;
  console.log('Received remote stream');
  console.log(`${pipes.length} element(s) in chain`);
  statusDiv.textContent = `${pipes.length} element(s) in chain`;
  insertRelayButton.disabled = false;
}

function start() {
  console.log('Requesting local stream');
  startButton.disabled = true;
  const options = audioCheckbox.checked ? {audio: true, video: true} : {audio: false, video: true};
  navigator.mediaDevices
    .getUserMedia(options)
    .then(gotStream)
    .catch(function(e) {
      alert('getUserMedia() failed');
      console.log('getUserMedia() error: ', e);
    });
}

function call() {
  callButton.disabled = true;
  insertRelayButton.disabled = false;
  hangupButton.disabled = false;
  console.log('Starting call');
  pipes.push(new VideoPipe(localStream, gotremoteStream));
}

function insertRelay() {
  pipes.push(new VideoPipe(remoteStream, gotremoteStream));
  insertRelayButton.disabled = true;
}

function hangup() {
  console.log('Ending call');
  while (pipes.length > 0) {
    const pipe = pipes.pop();
    pipe.close();
  }
  insertRelayButton.disabled = true;
  hangupButton.disabled = true;
  callButton.disabled = false;
}


text:
<?php
/**
 * @package Snap
 */

if ( ! function_exists( 'snap_get_social_links' ) ) :
/**
 * Get the social links from options.
 *
 * @since  1.0.
 *
 * @return array    Keys are service names and the values are links.
 */
function snap_get_social_links() {
	// Define default services
	$default_services = array(
		'twitter' => array(
			'title' => 'Twitter',
		),
		'facebook' => array(
			'title' => 'Facebook',
		),
		'google' => array(
			'title' => 'Google+',
		),
		'flickr' => array(
			'title' => 'Flickr',
		),
		'pinterest' => array(
			'title' => 'Pinterest',
		),
		'linkedin' => array(
			'title' => 'LinkedIn',
		),
		'rss' => array(
			'title' => 'RSS',
		),
	);

	// Set up the collector array
	$services_with_links = array();

	// Get the links for these services
	foreach ( $default_services as $service => $details ) {
		$url = get_theme_mod( $service, false );
		if ( false !== $url ) {
			$services_with_links[ $service ] = array(
				'title' => $details['title'],
				'url'   => $url,
			);
		}
	}

	return apply_filters( 'snap_get_social_links', $services_with_links );
}
endif;

if ( ! function_exists( 'snap_sanitize_footer_text' ) ) :
/**
 * Sanitize the footer text option.
 *
 * @since  1.0.1.
 *
 * @param  string    $text    Unsanitized text.
 * @return string             Sanitized text.
 */
function snap_sanitize_footer_text( $text ) {
	return wp_kses_data( $text );
}
endif;

if ( ! function_exists( 'snap_sanitize_bool' ) ) :
/**
 * Sanitize the boolean values.
 *
 * @since  1.0.1.
 *
 * @param  bool    $value    Unsanitized value.
 * @return bool              Sanitized value.
 */
function snap_sanitize_bool( $value ) {
	return (bool) $value;
}
endif;

if ( ! function_exists( 'snap_disable_web_font' ) ) :
/**
 * Add a class that removes the use of the web font if the option is chosen.
 *
 * @since  1.0.
 *
 * @param  array     $classes    The classes added to the body element.
 * @param  string    $class      The current class.
 * @return array                 Modified classes.
 */
function snap_disable_web_font( $classes, $class ) {
	if ( true === get_theme_mod( 'disable-web-font' ) ) {
		$classes[] = 'disable-web-font';
	}

	return $classes;
}
endif;

add_filter( 'body_class', 'snap_disable_web_font', 10, 2 );


text:
var childProcess = require('child_process');

var alpha = 'bcdefghij';
for (var i = 1; i <= 6; i++) {
  for (var j = 0; j < alpha.length; j++) {
    childProcess.exec('cp public/images/image' + i + 'a.png public/images/image' + i + alpha[j] + '.png');
  }
}


text:
package sw

import (
	"testing"

	"github.com/hyperledger/fabric/bccsp/mocks"
	"github.com/stretchr/testify/require"
)

func TestNewDummyKeyStore(t *testing.T) {
	t.Parallel()

	ks := NewDummyKeyStore()
	require.NotNil(t, ks)
}

func TestDummyKeyStore_GetKey(t *testing.T) {
	t.Parallel()

	ks := NewDummyKeyStore()
	_, err := ks.GetKey([]byte{0, 1, 2, 3, 4})
	require.Error(t, err)
}

func TestDummyKeyStore_ReadOnly(t *testing.T) {
	t.Parallel()

	ks := NewDummyKeyStore()
	require.True(t, ks.ReadOnly())
}

func TestDummyKeyStore_StoreKey(t *testing.T) {
	t.Parallel()

	ks := NewDummyKeyStore()
	err := ks.StoreKey(&mocks.MockKey{})
	require.Error(t, err)
}


text:
This document explains how to write Storybook documentation in order to have consistent examples across the components.
Storybook documentation provides information about components for UX designers and FED developers:

- It provides a full overview of the component and its usage (no alternative information sources should be needed to make a decision)
- It shows if a component is developed, in development or deprecated.
- It explains what's still in development or why it's deprecated and what to use instead.

Guidelines Structure

- [Page Structure](#page-structure)
- [Demo Section](#demo-section)
- [Usage Section](#usage-section)
- [Import Section](#import-section)
- [Variations Section](#variations-section)
  - [1. Core Structure](#1-core-structure)
  - [2. Properties](#2-properties)
  - [3. Common Use Cases](#3-common-use-cases)
- [Code Snippets](#code-snippets)
- [API Section](#api-section)
- [Template](#templates)

## Page Structure

Each component story consists of following sections:

![](../assets/PageStructure.png)

## Demo Section

This section should contain a single interactive example that showcase default component usage:

      DO.
      Use content to display common use case, that component is designed for.

      DON'T.
      Don't display empty version that might raise more questions than answers.

## Usage Section

This section should provide enough information for a user to make a decision if it's a right component for a case or an alternative solution should be selected instead. Component description should explain:

- The primary purpose of the component
- If it's a building part for a larger component (i.e. ListItemSelect)
- Do and don't examples — when component should be used or should not (optional link to correct solutions per case)

```
Modal controls the overlay layout that appears on call functions. It's a container for components
like CustomModalLayout, ModalPreviewLayout and others.

Use it:
- To reveal all types of modal layouts
- To display a full page loading state

Don't use it:
- Example Don't use it
- Example Don't use it
```

## Import Section

This section should provide a line of code which can be copied and pasted to the developer's project, so component can be used right away.

```js
import { AddItem } from 'wix-style-react';
```

## Variations Section

This section should demonstrate how component behaves and when to use it. In order to maintain consistency between stories, examples should go in this order:

1. Core structure
2. Properties
3. Common use cases

### 1. Core Structure

Container box components should give an example how it is constructed. The example should list all available areas. This example should:

- Visually display existing content areas and design possibilities it provides
- Explain each content area purpose and accepted content types in the description (e.g. node, string, image)
- Use default properties or placeholder content without additional styling

#### Visuals

Use schematic drawing to visualise content areas, when containers do not have a default content type and accept any kind of content (node). If there are multiple content areas use text to communicate how each area is called.

    	DO.
    	Use schematic drawings to communicate structural areas that accept node content type.

    	DON'T.
    	Don't use sample content as it doesn't visually explain multiple content areas.

Showcase the effect of different values passed to the same prop if it helps to communicate the possibilities component provides. Use text to communicate what values have been passed and the effect it made.

    	DO.
    	Use content to communicate available options and difference it makes.

    	DON'T.
    	Don't leave blank space and force user to check code to figure out difference in code.

If a component has a predefined value types, stick to these to showcase primary and recommended usage of a component. If content type is text, use it to explain area name and purpose.

If i.e. 'title' also accepts node content, it should be mentioned in a description and API.

    	DO.
    	Use default styling for areas with predefined content types to set right patterns.

    	DON'T.
    	Don't override predefined styling with placeholder content.

Use other components from the library to explain mechanism containers behaviour, such as modal call out, native file upload, etc.

    	DO.
    	Use components from the library to explain behaviour, that is not visual.

    	DON'T.
    	Don't use native HTML elements if library components are available.

#### Description

Structure example description should state:

- What areas the component consist of (if there are multiple areas only)
- Which areas are mandatory and which are optional
- What type and amount of children elements areas accept
- How to control component behaviour (for mechanism containers only)

	Structure

      	Render modal content by using children prop. Control modal appearance with props:

isOpen - this bool prop shows and hides the modal.

onRequestClose - this prop calls a function you request. It can be used to control isOpen prop.

	Structure

      	A simple example for modal with an alert

    	DO.
    	Give a meaningful description.

    	DON'T.
    	Don't write a generic message that gives no value.

### 2. Properties

Property examples step by step introduce users to component features. This section should reveal and explain full component capabilities, also how to handle common edge cases (i.e. text wrapping).

Each component has a set of properties and features to explain. List them in order from least to most complex ones:

1. Appearance - list of properties that controls visual look and feel of a component

- Size and Layout _(i.e. width, height, position, direction)_
- Style _(i.e. skin, shape, shadow, border)_

2. States - list of predefined states of a component and when they should be displayed

- Selection _(i.e. selected, checked)_
- Validation _(i.e. error, warning, status)_

3. Content - list of properties that allow to customise content

- Content areas _(i.e. header, footer, suffix)_
- Text _(i.e. title, subtitle, additionalInfo)_
- Visual content _(i.e. thumbnail, avatar, image)_
- Actions _(i.e. actionText, primaryAction, secondaryAction)_

4. Behaviour - list of properties that control component behaviour or enable specific functionality for it

- Data loading _(i.e. lazyLoading, infiniteScroll)_
- Display _(i.e. horizontalScroll, overflow, collapse)_
- Other _(i.e. spellChecking, custom HTML tag)_

> Note: Order in which properties are listed can and should be adjusted depending per component and its most commonly used props

#### Visuals

Be aware that users are visual learners by nature. Examples we provide should be as self explanatory as possible.

In order to decide what content inside of a snippets would be suitable think about the following:

- What am I trying to communicate to the user (list of options to choose from, what behaviour property enables, etc.)?
- What is a property type (is it visual by its own, or does it need guidance)?
- How could we efficiently use initial component features to provide meaningful context?
- Could we help to set correct content patterns via snippets?

In cases where example lists down available value options use predefined component elements (if there are any) to communicate how passed value affects component appearance or behaviour.

    	DO.
    	Utilize component elements to communicate available prop values.

    	DON'T.
    	Don't use meaningless placeholder titles which force you to look for information somewhere else.

Merge statuses into a single snippet for interactive components. Use labels to communicate how each status is called.

    	DO.
    	Display all different states in a single snippet and use labels to display state name.

    	DON'T.
    	Don't use placeholder labels when your intention is to communicate different states.

Display single feature at the time. If example purpose is to list down the options, don't complicate it with content which is not relevant at that specific moment.

    	DO.
    	Display content which is necessary to communicate example purpose only, i.e. existing states.

    	DON'T.
    	Don't add content which is irrelevant in scenario you're showcasing (i.e. prefix icon in states example).

In cases where property value affects the content which is allowed to be displayed inside of a component use real case examples. This approach provides the user with context what each value is designed for, and also sets right content patterns.

    	DO.
    	Use real case content which both explains when skin could be used and sets correct content patterns

    	DON'T.
    	Don't communicate value names only when there's a direct dependency between accepted messaging and selected theme.

Use real content to demonstrate edge cases handling. It showcases the behaviour and sets correct content patterns at the same time. Avoid gibberish text that doesn't bring benefit.

    	DO.
    	Use real content for text overflow demonstration to set right content patterns.

    	DON'T.
    	Don't use gibberish text which don't bring benefit for a user.

Merge directly dependent or same purpose properties into a single example (i.e. width and height could be a single example named 'Dimensions'):

    	DO.
    	Display similar purpose properties in a single example.

    	DON'T.
    	Don't create separate examples for similar purpose props. It increases story length unnecessarily.

> Note: Examples of properties that could be shown in a single snippet:
>
>

>

> 		width
height
> 		maxWidth
maxHeight
ellipsis
textWrap
overflow
> 		primary
secondary
> 		border
borderRadius
borderWidth
> 		color
backgroundColour
textColor
> 		selected
disabled
 selected disabled
> 		header
footer
footnote
> 		primaryAction
secondaryAction
>

>

Don't merge property values which serve different purposes. Provide each of them with a dedicated example inside of the same snippet. Use real and meaningful copy to communicate purpose better:

> In example, selection items inside of a dropdown layout can be grouped using subheader or divider, but intentions are different. Subheader provides a name for a group. While divider separates list item that provide entirely different results, i.e. will add another field to the form where you can specify a custom length of a plan.

    	DO.
    	Have separate examples for different purpose prop values. Use real content to communicate purpose clearly.

    	DON'T.
    	Don't merge prop variations with different intentions in a single layout. It doesn't explain clearly how they differ.

Use content to communicate hard to notice functionality for the end user:

    	DO.
    	Use content to visualise behaviour of not so obvious features.

    	DON'T.
    	Don't use meaningless placeholder copy that leaves user to figure out what needs to be done by himself.

Guide users with content if they are required to make an action to see a feature or functionality:

    	DO.
    	Provide guidance for the hidden features (i.e. error message will be displayed in a tooltip on hover).

    	DON'T.
    	Don't leave features partially explained. It's easy to miss functionality which is explained only in API or longer descriptions.

Add external labels to communicate changes that happen in code for non visual features:

    	DO.
    	 Add labels if component change is not visual to help user figure out the difference instantly.

    	DON'T.
    	Don't leave visual examples unexplained. This will require user to check the code to see a difference.

#### Description

Property example should always be followed by a description explaining how and when to use it. Depending on a property type description could state:

- what purpose property should be used for (mandatory)
- what property values are available and what each option is used for
- what is a default value
- what are accepted child element types

> Tip: always start writing description with a verb

Selection of examples how to write example descriptions:

			Subtitle

      		Explain action in more detail with a subtitle. Keep in
 mind that long subtitles affect visual hierarchy and compete
 with main CTA.

			Subtitle

			A subtitle text can be set.

			DO.
			Define the purpose of a feature.

			DON'T.
			Don't write generic descriptions that don't bring value.

			Skin

      		Highlights the purpose of an action. It supports 3 skin types.

standard (default)- use in common layouts

dark - use in longer list of actions (>5) in order to not overwhelm the user

destructive - use for destructive actions only

			 Skin

      		Supports three different skins: standard, dark & destructive.

			DO.
			Explain when to use each property option.

			DON'T.
			Don't list options without explaining when to use each one of them.

			Subtoolbar

      		Provides a sticky container for related actions
 or content (i.e. list of applied filters). Area accepts any kind of content.

			Subtoolbar

			A Table can contain a sticky sub-toolbar, an area for a tag list of filtered items.

			DO.
			Define accepted content types.

			DON'T.
			Don't be too specific about the use case if feature is flexible.

			Letter Counting

      		Indicates the number of letters typed inside of an input area.
 Set both maxLength and hasCounter props to show the counter.

			Letter Counting

			InputArea can indicate how many letters were typed.

			DO.
			Highlight the required conditions for feature to work as expected.

			DON'T.
			Don't leave mandatory conditions unmentioned.

### 3. Common Use Cases

> Note:These examples are complex and should be made by WSR team only.

Common use cases is a list of examples which showcase recommended layouts and often used complex scenarios:

- Use real layouts and content to communicate cases where different variations of component should be used
- Use meaningful copy and set correct / recommended content patterns
- Showcase complex structures that can be achieved with a component

    	DO.
    	Use real case content to communicate recommended usage better

    	DON'T.
    	 Don't use placeholder copy just to illustrate areas that was introduced in property examples already

## Code Snippets

Snippets represent component expressions in code and should be easy to follow so that users can relate the visuals and the code. Component examples should have minimal properties to help users quickly understand their usage.

### Principles

| Clear                                                                                | Consistent                                                    | Meaningful                                                                |
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Design snippet examples in such a way that the user can immediately understand them. | Make snippet examples meaningful to communicate your message. | Utilize the patterns outlined below to write snippets that are intuitive. |

### Terminology

**Direct snippet** - an example that is directly inserted into the playground.

```jsx
<TextButton weight="thin">Thin</TextButton>
```

**Functional snippet** - an example containing components within a function.

```jsx
() => {
  return <TextButton weight="thin">Thin</TextButton>;
};
```

### General Guidelines

- Only two kind of snippet styling is allowed: direct or functional.
- The content for the snippets should be prepared together with UX writers and UX designers.
- Do not use native HTML tags except when necessary.
- Code duplication is preferable for readability.
- For property and structure examples layouting use StorybookComponents, but for commone use caases don't.
- Do not waste time on caching optimizations, as these examples are not effective code, but rather representation of usage. (useMemo, useCallback)

### StorybookComponents

StorybookComponents are dedicated components developed by Design Systems team
to meet the needs of example demonstration.
#### <StorybookComponents.Stack>

CSS Flex based component meant for stacking multiple components either horizontally or vertically.

| Property       | Tye    | Default    |
| -------------- | ------ | ---------- |
| justifyContent | string | flex-start |
| alignItems     | string | flex-start |
| gap            | string | 30px       |
| width          | string | ---------  |
| height         | string | ---------  |
| padding        | string | ---------  |
| margin         | string | ---------  |

#### <StorybookComponents.Placeholder>

CSS Block based component meant for structure examples.

| Property | Tye             | Default   |
| -------- | --------------- | --------- |
| skin     | 'dark', 'light' | 'dark     |
| width    | string          | --------- |
| height   | string          | --------- |

### Structure Example

Structure snippets are mostly used to represent components that are container based.

```jsx
<PageFooter>
  <PageFooter.Start>
    // Represents empty slot for other components
    <StorybookComponents.Placeholder>start</StorybookComponents.Placeholder>
  </PageFooter.Start>
  <PageFooter.Center>
    // Represents empty slot for other components
    <StorybookComponents.Placeholder>center</StorybookComponents.Placeholder>
  </PageFooter.Center>
  <PageFooter.End>
    // Represents empty slot for other components
    <StorybookComponents.Placeholder>end</StorybookComponents.Placeholder>
  </PageFooter.End>
</PageFooter>
```

Here we see a `<PageFooter/>` component, which main purpose is to give structure to the footer section of `<Page/>` component. `<StorybookComponents.Placeholder/>` should be used to represent available layouting options.

### Property Example

Property examples are meant to illustrate different types of property usage.

#### 1. Examples should not include additional properties unless additional properties are needed to represent the full feature.

```jsx
// do
<StorybookComponents.Stack>
  <TextButton weight="thin">Thin</TextButton>
  <TextButton weight="normal">Normal</TextButton>
<StorybookComponents.Stack>

// don't
<StorybookComponents.Stack>
  <TextButton weight="thin" size="small">Thin</TextButton>
  <TextButton weight="normal" size="small">Normal</TextButton>
<StorybookComponents.Stack>
```

#### 2. Properties that are image based url's should use assets directly from libraries dedicated assets folder.

> Why? External links tend to get taken down and so our story examples gets broken.

```jsx
// do
<CardGalleryItem backgroundImageUrl="table_with_fruits.jpg" />

// don't
<CardGalleryItem backgroundImageUrl="https://random-link.com/table_with_fruits.jpg" />
```

#### 3. In case property requires large data sets for interpretation - functional snippets can be used to move big data sets to meaningful variables.

```jsx
// do
() => {
  const options = [
    { id: 1, value: 'Option 1' },
    { id: 2, value: 'Option 2' },
    { id: 3, value: 'Option 3' },
    { id: 4, value: 'Option 4' },
    { id: 5, value: 'Option 5' },
    { id: 6, value: 'Option 6' },
    { id: 7, value: 'Option 7' },
    { id: 8, value: 'Option 8' },
    { id: 9, value: 'Option 9' },
    { id: 10, value: 'Option 10' },
  ];

  return <Dropdown options={options} />;
};

// don't
<Dropdown
  options={[
    { id: 1, value: 'Option 1' },
    { id: 2, value: 'Option 2' },
    { id: 3, value: 'Option 3' },
    { id: 4, value: 'Option 4' },
    { id: 5, value: 'Option 5' },
    { id: 6, value: 'Option 6' },
    { id: 7, value: 'Option 7' },
    { id: 8, value: 'Option 8' },
    { id: 9, value: 'Option 9' },
    { id: 10, value: 'Option 10' },
  ]}
/>;
```

#### 4. Complex structure components examples can be daunting to comprehend. In such cases, there is value in abstracting code into smaller modules in order to reduce mental effort in understanding the code.

```jsx
//do
() => {
  const renderTableToolbar = () => (
    <TableToolbar>
      <TableToolbar.Title>Published</TableToolbar.Title>
    </TableToolbar>
  );

  const renderEmptyState = () => (
    <Table.EmptyState>
      <TextButton prefixIcon={<Icons.Add />}>Create New Post</TextButton>
    </Table.EmptyState>
  );

  return (
    <Table>
      {renderTableToolbar()}
      {renderEmptyState()}
    </Table>
  );
};

// don't
() => (
  <Table>
    <TableToolbar>
      <TableToolbar.Title>Published</TableToolbar.Title>
    </TableToolbar>
    <Table.EmptyState>
      <TextButton prefixIcon={<Icons.Add />}>Create New Post</TextButton>
    </Table.EmptyState>
  </Table>
);
```

#### 5. Some component properties are controlled externally and hence require local state. React hooks should be used.

```jsx
() => {
  const [checked, setChecked] = React.useState(false);

  return (
    <CheckToggle checked={checked} onChange={() => setChecked(!checked)} />
  );
};
```

#### 6. Properties that are supposed to relate to the behavior of other components should be used meaningfully and provided with near real world examples.

```jsx
() => {
  const [isModalOpened, setModalOpened] = React.useState(false);

  return (
    <StorybookComponents.Stack>
      <StorybookComponents.Action onClick={() => setModalOpened(true)}>
        Open Announcement Modal
      </StorybookComponents.Action>
      <Modal
        isOpen={isModalOpened}
        onRequestClose={() => setModalOpened(false)}
      >
        Real World Example
      </Modal>
    </StorybookComponents.Stack>
  );
};
```

### Common Use Case

Used to illustrate real-world examples, such as interactivity and components with state and content that is used in actual applications. All components presented in the examples should be library components and content that it used inside must resemble real world use case.

#### 1. Simulating data fetching

Components examples that are meant to work with data fetched from server should use StorybookUtils.fetch function that simulates data coming from server.

```jsx
() => {
  const containerRef = React.useRef(null);
  const [data, setData] = React.useState([]);
  const [container, setContainer] = React.useState(null);

  const fetchMoreData = async (loaded) => {
    setData(
      await StorybookUtils.fetch('/api/table', {
        load: loaded + 5,
      }),
    );
  };

  React.useEffect(() => {
    setContainer(containerRef);
    fetchMoreData();
  }, []);

  const columns = [
    { title: 'First', render: (row) => row.firstName },
    { title: 'Last', render: (row) => row.lastName },
  ];

  return (
    <Table
      data={data}
      columns={columns}
      infiniteScroll
      hasMore={true}
      loadMore={fetchMoreData}
      itemsPerPage={20}
      scrollElement={container && container.current}
    >
      <Table.Content />
    </Table>
  );
};
```

## API Section

API table should list ALL available properties and methods of a presented component.
Each property listed in this sections should have:

- Description
- Type
- Default value written (If component has default value. Bool type props should always have it).
- List of possible value options to choose from, i.e. oneOf ('placement') should include available placement options such as top, bottom, left, right

#### Description

> Tip: always start writing description with a verb

      		fixed

      		Makes tooltip's position fixed to its original placement even if it's outside the boundary.

      		 fixed

      		whether to enable the fixed behaviour.

      		 maxWidth

      		Defines maximum width of tooltip content container in pixels.

      		 maxWidth

      		tooltip content container width in pixels

      		 secondary

		Sets text style to secondary. It affects font color only.

      		 secondary

      		is the text type is secondary. Affects the font color

      		 tooltipProps

		Allows to pass all available tooltip properties. Check <Tooltip/> API for the full list.

      		 tooltipProps

      		Properties for tooltip

      		 children

		Accepts any component as a child item. Common cases for this component are headings, text strings, badges or icons.

      		 children

      		any nodes to be rendered

## Templates

For all the future story docs, please start with this template:
[https://docs.google.com/document/d/1KmQ56KeyAPqsiQ7vskSMJxK2Lfq9XlO0vzYoM_Nwn3M/edit?usp=sharing]()


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>frame</artifactId>
        <groupId>com.robin</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <groupId>com.robin</groupId>
    <artifactId>web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>web</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <swagger.version>2.2.2</swagger.version>
        <logback.version>1.2.3</logback.version>
        <slf4j.version>1.7.8</slf4j.version>
        <frm.version>1.0-SNAPSHOT</frm.version>
        <brave.version>5.4.1</brave.version>
        <es.version>6.5.4</es.version>

    </properties>

    <dependencies>

         <dependency>
             <groupId>com.robin</groupId>
             <artifactId>common</artifactId>
             <version>${frm.version}</version>
         </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.14</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>${struts2.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

    </dependencies>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
SniperTower = Tower.create()
SniperTower.__index = SniperTower
SniperTower.radius = 320
SniperTower.cost = 850
SniperTower.name = "Sniper Tower"
SniperTower.shoot_speed = 6.0
SniperTower.shoot_frequency = 1.3
SniperTower.damage = 22

function SniperTower.create()
    local instance = {}
    setmetatable(instance, SniperTower)
    return instance
end

function SniperTower:shoot_projectile()
    local proj = LineProjectile.create()
    proj.target_pos = self.target:get_pos()
    proj.start_pos = self:get_pos()
    proj.damage = self.damage
    proj.source = self

    self.target:on_hit(self.damage)
    if self.target.destroyed == true then
        self.kill_count = self.kill_count + 1
    end
    return proj
end

function SniperTower:do_internal_upgrade()
    self.damage = self.damage + math.floor(self.upgrade * self.upgrade * 0.5) + 3
    self.radius = self.radius + 5
    self.shoot_frequency = self.shoot_frequency * 0.96
end

function SniperTower.draw_inner_shape(x, y, upgrade)
    love.graphics.setColor(213, 31, 229, 255)
    love.graphics.rectangle("fill", x - 10, y - 10, 20, 20)

    love.graphics.setColor(30,30,30, 255)

    love.graphics.circle("line", x, y, 6, 20)

    love.graphics.line(x - 5, y, x - 3, y)
    love.graphics.line(x + 3, y, x + 5, y)

    love.graphics.line(x, y - 5, x, y - 3)
    love.graphics.line(x, y + 3, x, y + 5)

    love.graphics.setColor(30,30,30, 255)
    love.graphics.rectangle("line", x - 11, y - 11, 22, 22)

end


text:
var GAME = gameModule;
var MENU = menuModule;
var ABOUT = aboutModule;

var mainModule = function (game, menu, about) {
    var main = {
        game: game,
        menu: menu,
        about: about,
        run: function(){
            this.menu.createMenu();
        }
    };

    return main;
}(GAME,MENU,ABOUT);

var main = mainModule;
main.run();


text:
1. Download Code from lite version repo.
 - Github
   ```bash
   $ git clone https://github.com/pkumza/LiteRadar
   ```

2. Download Feature File

  Download lite_datasetfile, then move it into LiteRadar/LiteRadar/Data directory.

  [Mirror 1 Github](https://github.com/pkumza/Data_for_LibRadar/blob/master/lite_dataset_10.csv)

3. Use LibRadar to detect libraries.

  ```bash
  $ python literadar.py someapp.apk
  ```

### Ordinary Version

1. Install dependencies. build-essential, python2, pip, git, redis

   Recommend to use pypy, install pypy and pypy-pip to boost LibRadar

  - Install redis>=3.2
  ```bash
    $ wget http://download.redis.io/releases/redis-3.2.7.tar.gz
	$ tar xzf redis-3.2.7.tar.gz
	$ cd redis-3.2.7
	$ make
	$ apt-get install tcl
	$ make test
	$ make install
  ```

2. Install modules

  ```
    $ pip install requirements.txt
  ```

3. Download code

 * Github Release (Recommanded)

 Click [https://github.com/pkumza/LibRadar/releases](https://github.com/pkumza/LibRadar/releases)

 Download zip or tar.gz, then extract code from it.

 - Github
   ```bash
   $ git clone https://github.com/pkumza/LibRadar
   ```

 - Pypi

   Download tar.gz code from https://pypi.python.org/pypi/LibRadar/ and extract the file into your work directory.
   Do not use pip install because I didn't include data file into the code, as libradar will get error that it could not
   find data file.

4. Download LibRadarData.rdb and run redis-server

  - [~Dropbox Link old~](https://www.dropbox.com/s/w31gig6msdo3cdy/dump-20170515-shrink.rdb.tar.gz?dl=0)
  - [Dropbox Link](https://www.dropbox.com/s/ljtzw74twt8xgy6/d.tar.gz?dl=0)

  ```bash
  $ vi LibRadar/tool/redis.conf.
  (
    find "dir /Users/marchon/Projects/Databases" and change it into your rdb path.
    find "dbfilename" and change it into your rdb filename.
  )

  $ redis-server tool/redis.conf
  ```

5. Use LibRadar to detect libraries.

  ```bash
  $ python libradar.py someapp.apk
  ```

# Example (Version 2.1.1)

```bash
$ python LibRadar/LibRadar/libradar.py happy.apk
[
    {
        "Library": "Android Support v4",
        "Match Ratio": "6777/6777",
        "Package": "Landroid/support/v4",
        "Permission": [
            "android.permission.BACKUP",
            "android.permission.BLUETOOTH_ADMIN",
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.INTERNET",
            "android.permission.WAKE_LOCK",
            "android.permission.WRITE_SECURE_SETTINGS"
        ],
        "Popularity": 1610,
        "Standard Package": "Landroid/support/v4",
        "Type": "Development Aid",
        "Website": "http://developer.android.com/reference/android/support/v4/app/package-summary.html"
    },
    {
        "Library": "Android Support v7",
        "Match Ratio": "3111/3111",
        "Package": "Landroid/support/v7",
        "Permission": [
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.INTERNET",
            "android.permission.MANAGE_APP_TOKENS"
        ],
        "Popularity": 2,
        "Standard Package": "Landroid/support/v7",
        "Type": "Development Aid",
        "Website": "https://developer.android.com/reference/android/support/v7/app/package-summary.html"
    },
    {
        "Library": "Bolts Base Library",
        "Match Ratio": "325/325",
        "Package": "Lbolts",
        "Permission": [
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.INTERNET"
        ],
        "Popularity": 3378,
        "Standard Package": "Lbolts",
        "Type": "Development Aid",
        "Website": "https://github.com/BoltsFramework/Bolts-Android"
    },
    {
        "Library": "Amazon AWS",
        "Match Ratio": "3673/3673",
        "Package": "Lcom/amazonaws",
        "Permission": [
            "android.permission.DUMP"
        ],
        "Popularity": 3,
        "Standard Package": "Lcom/amazonaws",
        "Type": "Development Aid",
        "Website": "http://mvnrepository.com/artifact/com.amazonaws"
    },
    {
        "Library": "Google Mobile Services",
        "Match Ratio": "26342/26344",
        "Package": "Lcom/google/android/gms",
        "Permission": [
            "android.permission.BACKUP",
            "android.permission.BLUETOOTH_ADMIN",
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.INTERNET",
            "android.permission.WAKE_LOCK",
            "android.permission.WRITE_SECURE_SETTINGS"
        ],
        "Popularity": "8619",
        "Standard Package": "Lcom/google/android/gms",
        "Type": "Development Aid",
        "Website": "https://developers.google.com/android/reference/com/google/android/gms/package-summary"
    },
    {
        "Library": "Google Gson",
        "Match Ratio": "390/390",
        "Package": "Lcom/google/gson",
        "Permission": [],
        "Popularity": 7366,
        "Standard Package": "Lcom/google/gson",
        "Type": "Development Aid",
        "Website": "https://github.com/google/gson"
    },
    {
        "Library": "Google Ads",
        "Match Ratio": "47/47",
        "Package": "Lcom/google/ads",
        "Permission": [
            "android.permission.DUMP"
        ],
        "Popularity": 23586,
        "Standard Package": "Lcom/google/ads",
        "Type": "Advertisement",
        "Website": "https://www.google.com/ads/"
    },
    {
        "Library": "Firebase",
        "Match Ratio": "554/554",
        "Package": "Lcom/google/firebase",
        "Permission": [
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.WRITE_SECURE_SETTINGS"
        ],
        "Popularity": 14,
        "Standard Package": "Lcom/google/firebase",
        "Type": "Development Aid",
        "Website": "http://firebase.com"
    },
    {
        "Library": "Facebook",
        "Match Ratio": "3758/3758",
        "Package": "Lcom/facebook",
        "Permission": [
            "android.permission.DUMP",
            "android.permission.INTERACT_ACROSS_USERS",
            "android.permission.INTERACT_ACROSS_USERS_FULL",
            "android.permission.INTERNET"
        ],
        "Popularity": 54,
        "Standard Package": "Lcom/facebook",
        "Type": "Social Network",
        "Website": "https://developers.facebook.com"
    },
    {
        "Library": "Google Play",
        "Match Ratio": "119/119",
        "Package": "Lcom/android/vending",
        "Permission": [
            "android.permission.DUMP"
        ],
        "Popularity": 44625,
        "Standard Package": "Lcom/android/vending",
        "Type": "App Market",
        "Website": "https://play.google.com"
    },
    {
        "Library": "Unknown",
        "Package": "Landroid/support/graphics",
        "Popularity": 1525,
        "Standard Package": "Landroid/support/graphics",
        "Weight": 299
    },
    {
        "Library": "Unknown",
        "Package": "Landroid/support/customtabs",
        "Popularity": 1805,
        "Standard Package": "Landroid/support/customtabs",
        "Weight": 221
    },
    {
        "Library": "Unknown",
        "Package": "Lcom/adcolony",
        "Popularity": 221,
        "Standard Package": "Lcom/adcolony",
        "Weight": 3602
    }
]

```

## How to develop LibRadar

#### For Professional use

1. Install LibRadar from [pypi](https://pypi.python.org/pypi/LibRadar) or download the code from [Github](http://github.com/pkumza/LibRadar).

2. Get some dependency.
 - Install Java Runtime Environment. If you already installed jre, ignore this.
 - Install JAD.
 - Install Redis.

3. Get android.jar from Android SDK and place them into $Project_HOME$/Data/RawData, Run APIDict.py

4. Change the apk folder name and run job_dispatching.py

PS: Change variables in _settings.py if you need.


text:
package org.tuxdevelop.spring.batch.lightmin.server.scheduler.repository;

public interface CleanUpRepository {

    void cleanUp();

}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// group_expression.h
//
// Identification: src/include/optimizer/group_expression.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include "optimizer/operator_node.h"
#include "optimizer/stats.h"
#include "optimizer/util.h"

#include <tuple>
#include <vector>
#include <map>

namespace peloton {
namespace optimizer {

using GroupID = int32_t;

//===--------------------------------------------------------------------===//
// Group Expression
//===--------------------------------------------------------------------===//
class GroupExpression {
 public:
  GroupExpression(Operator op, std::vector<GroupID> child_groups);

  GroupID GetGroupID() const;

  void SetGroupID(GroupID group_id);

  const std::vector<GroupID> &GetChildGroupIDs() const;

  Operator Op() const;

  std::shared_ptr<Stats> GetStats() const;

  double GetCost() const;

  void DeriveStatsAndCost(std::vector<std::shared_ptr<Stats>> child_stats,
                          std::vector<double> child_costs);

  hash_t Hash() const;

  bool operator==(const GroupExpression &r);

 private:
  GroupID group_id;
  Operator op;
  std::vector<GroupID> child_groups;

  std::shared_ptr<Stats> stats;
  double cost;
};

} /* namespace optimizer */
} /* namespace peloton */

namespace std {

template <>
struct hash<peloton::optimizer::GroupExpression> {
  typedef peloton::optimizer::GroupExpression argument_type;
  typedef std::size_t result_type;
  result_type operator()(argument_type const &s) const { return s.Hash(); }
};

} /* namespace std */