text:
package ricardo.com.br.musicplayer.itemdecoration;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by Ricardo on 01/01/2016.
 */
public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration{

    public static final Integer VERTICAL_ITEM_SPACE = 3;

    private final Integer verticalSpaceHeight;

    public VerticalSpaceItemDecoration(Integer verticalSpaceHeight){
        this.verticalSpaceHeight = verticalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if(parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1){
            outRect.bottom = verticalSpaceHeight;
        }
    }
}


text:
require 'spec_helper'

describe QuestionsController do

	describe '#index' do
		it 'renders the index page' do
			get :index
			expect(response).to render_template :index
		end
	end

	describe '#new' do
		it 'renders the new page' do
			get :new
			expect(response).to render_template :new
		end

		it 'creates a new instance' do
      question = Question.new
		  expect(question).should be_an_instance_of(Question)
    end
	end

	# context '#create' do
 # 		it "creates a question with valid params" do
 #      post :create, { question: { title: "hi david", body: "OMG" }}
 #      expect(assigns(:question)).to eq(Question.last)
 #    end
 #  end

  context "#edit" do
    let(:edit_question) { Question.create!(title: "Old Post", body: "Old Body") }
    it "updates a post with valid params" do
      expect do
        put :update, id: edit_question, question: {title: "New Post", body: "New Content"}
          edit_question.reload
      end.to change{edit_question.title}.from("Old Post").to "New Post"
    end
  end

	context '#destroy' do
    before :each do
      @delete_question = Question.create!(title: "Post", body: "Content")
    end
      it "should delete a Question" do
      expect do
          delete :destroy, id: @delete_question
      end.to change(Question, :count).by(-1)
    end
  end
end
  	# it 'deletes question' do
   #    question = Question.create!(title: "no more dishes", body: "boo!")
   #    expect{ delete :destroy, id: question.id }.to change(Question, :count).by(-1)

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Config-file for navigation bar.
 *
 */
return [

    // Use for styling the menu
    'class' => 'navbar',

    // Here comes the menu strcture
    'items' => [

        // This is a menu item
        'theme'  => [
            'text'  => 'Tema',
            'url'   => $this->di->get('url')->create('theme'),
            'title' => 'Home route of current frontcontroller'
        ],

        // This is a menu item
        'regioner' => [
            'text'  =>'Regioner',
            'url'   => $this->di->get('url')->create('regioner'),
            'title' => 'Url to relative frontcontroller, other file',
        ],

        // This is a menu item
        'typography' => [
            'text'  =>'Typography',
            'url'   => $this->di->get('url')->create('typography'),
            'title' => 'Internal route within this frontcontroller'
        ],

        // This is a menu item
        'fontawsome' => [
            'text'  =>'Font Awesome',
            'url'   => $this->di->get('url')->create('fontawesome'),
            'title' => 'Internal route within this frontcontroller'
        ],
        // This is a menu item
        'back' => [
            'text'  =>'Till Me-sidan',
            'url'   => '../',
            'title' => 'Internal route within this frontcontroller'
        ],
    ],

    /**
     * Callback tracing the current selected menu item base on scriptname
     *
     */
    'callback' => function ($url) {
        if ($url == $this->di->get('request')->getCurrentUrl(false)) {
            return true;
        }
    },

    /**
     * Callback to check if current page is a decendant of the menuitem, this check applies for those
     * menuitems that has the setting 'mark-if-parent' set to true.
     *
     */
    'is_parent' => function ($parent) {
        $route = $this->di->get('request')->getRoute();
        return !substr_compare($parent, $route, 0, strlen($parent));
    },

   /**
     * Callback to create the url, if needed, else comment out.
     *
     */
   /*
    'create_url' => function ($url) {
        return $this->di->get('url')->create($url);
    },
    */
];


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Yodiwo
{
    public static partial class Extensions
    {
        //----------------------------------------------------------------------------------------------------------------------------------------------

        public static string Name_Portable(this Type type)
        {
#if NETFX
            if (type.IsGenericType)
                return type.FullName.Split('`')[0] + "`" + type.GetGenericArguments().Count() + "[" + string.Join(", ", type.GetGenericArguments().Select(x => "[" + Name_Portable(x) + "]").ToArray()) + "]";
#elif UNIVERSAL
            if (type.GetTypeInfo().IsGenericType)
                return type.FullName.Split('`')[0] + "`" + type.GenericTypeArguments.Length + "[" + string.Join(", ", type.GenericTypeArguments.Select(x => "[" + Name_Portable(x) + "]").ToArray()) + "]";
#endif
            else
                return type.FullName;
        }

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

        public static string AssemblyQualifiedName_Portable(this Type type)
        {
#if NETFX
            if (type.IsGenericType)
                return type.FullName.Split('`')[0] + "`" + type.GetGenericArguments().Count() + "[" + string.Join(", ", type.GetGenericArguments().Select(x => "[" + AssemblyQualifiedName_Portable(x) + "]").ToArray()) + "] , " + type.Assembly.GetName().Name;
#elif UNIVERSAL
            if (type.GetTypeInfo().IsGenericType)
                return type.FullName.Split('`')[0] + "`" + type.GenericTypeArguments.Length + "[" + string.Join(", ", type.GenericTypeArguments.Select(x => "[" + AssemblyQualifiedName_Portable(x) + "]").ToArray()) + "] , " + type.GetTypeInfo().Assembly.GetName().Name;
#endif
            else
#if NETFX
                return type.FullName + ", " + type.Assembly.GetName().Name;
#elif UNIVERSAL
                return type.FullName + ", " + type.GetTypeInfo().Assembly.GetName().Name;
#endif
        }

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

        public static string GetFriendlyName(this Type type)
        {
            if (type == typeof(int))
                return "int";
            else if (type == typeof(short))
                return "short";
            else if (type == typeof(byte))
                return "byte";
            else if (type == typeof(bool))
                return "bool";
            else if (type == typeof(uint))
                return "uint";
            else if (type == typeof(long))
                return "long";
            else if (type == typeof(float))
                return "float";
            else if (type == typeof(double))
                return "double";
            else if (type == typeof(decimal))
                return "decimal";
            else if (type == typeof(string))
                return "string";
#if NETFX
            else if (type.IsGenericType)
                return (type.FullName.LeftOf('`') + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x))) + ">").Replace("+", ".");
#elif UNIVERSAL
            else if (type.GetTypeInfo().IsGenericType)
                return (type.FullName.LeftOf('`') + "<" + string.Join(", ", type.GetTypeInfo().GenericTypeArguments.Select(x => GetFriendlyName(x))) + ">").Replace("+", ".");
#endif
            else
                return type.FullName.Replace("+", ".");
        }

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

        public static string DeFriendlifyName(string type)
        {
            if (type == "int")
                return typeof(int).FullName;
            else if (type == "short")
                return typeof(short).FullName;
            else if (type == "byte")
                return typeof(byte).FullName;
            else if (type == "bool")
                return typeof(bool).FullName;
            else if (type == "long")
                return typeof(long).FullName;
            else if (type == "float")
                return typeof(float).FullName;
            else if (type == "double")
                return typeof(double).FullName;
            else if (type == "decimal")
                return typeof(decimal).FullName;
            else if (type == "string")
                return typeof(string).FullName;
            else
            {
                string retType = "";

                //processs generics
                if (type.Contains("<"))
                {
                    var lefovers = type.RightOf("<");
                    var generics = new List<string>();
                    int i = 0;
                    int start = 0;
                    for (int n = 0; n < lefovers.Length; n++)
                    {
                        var c = lefovers[n];
                        if (c == '<')
                            i++;
                        else if (c == '>')
                            i--;
                        else if (i == 0 && c == ',')
                        {
                            generics.Add(lefovers.Substring(start, n - start));
                            start = n + 1;
                        }
                    }
                    if (i == -1)
                        generics.Add(lefovers.Substring(start, lefovers.Length - start - 1));
                    //process found generics recursively
                    retType = type.LeftOf("<") + "`" + generics.Count + "[" + string.Join(", ", generics.Select(t => "[" + DeFriendlifyName(t))) + "]" + "]";
                }
                else
                    retType = type;

                //try to find it retType is valid
                if (TypeCache.GetType(retType, DeFriendlify: false) != null)
                    return retType;

                //break type appart and find what are nested classes
                var elem = retType.Split('.');
                string finalType = elem[0];
                for (int n = 1; n < elem.Length; n++)
                    finalType += (TypeCache.GetType(finalType) != null ? "+" : ".") + elem[n];
                return finalType;
            }
        }

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

        public static bool IsList(this Type type)
        {
            return typeof(IList).IsAssignableFrom(type)
                    ||
                    (
#if NETFX
                        type.IsGenericType &&
#elif UNIVERSAL
                        type.GetTypeInfo().IsGenericType &&
#endif
                        type.GetGenericTypeDefinition() == typeof(List<>)
                    );
        }

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

        public static bool IsDictionary(this Type type)
        {
            return typeof(IDictionary).IsAssignableFrom(type)
                    ||
                    (
#if NETFX
                        type.IsGenericType &&
#elif UNIVERSAL
                        type.GetTypeInfo().IsGenericType &&
#endif
                       type.GetGenericTypeDefinition() == typeof(Dictionary<,>)
                    );
        }

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

        public static bool IsInteger(this Type type)
        {
            return type == typeof(sbyte) || type == typeof(byte) ||
                   type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64) ||
                   type == typeof(UInt16) || type == typeof(UInt32) || type == typeof(UInt64);
        }

        public static bool IsDecimal(this Type type)
        {
            return type == typeof(float) || type == typeof(double) || type == typeof(decimal);

        }
        public static bool IsNumber(this Type type)
        {
            return type.IsInteger() || type.IsDecimal();
        }

        //----------------------------------------------------------------------------------------------------------------------------------------------
    }
}


text:
//#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE transport_iostream_endpoint
#include <boost/test/unit_test.hpp>

#include <iostream>

#include <websocketpp/transport/iostream/endpoint.hpp>

BOOST_AUTO_TEST_CASE( placeholder ) {}

/*BOOST_AUTO_TEST_CASE( blank_error ) {
    websocketpp::lib::error_code ec;

    BOOST_CHECK( !ec );
}*/


text:
package org.compass.core.metadata.impl;

import java.util.HashMap;
import java.util.Iterator;

import org.compass.core.metadata.MetaData;

/**
 * @author kimchy
 */
public class DefaultMetaData extends AbstractMetaDataItem implements MetaData {

    private String format;

    private HashMap values = new HashMap();

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public String getValue(String id) {
        return (String) values.get(id);
    }

    public void setValue(String id, String value) {
        values.put(id, value);
    }

    public MetaData copy() {
        DefaultMetaData copyMetaData = new DefaultMetaData();
        copy(copyMetaData);
        copyMetaData.setFormat(getFormat());
        for (Iterator it = values.keySet().iterator(); it.hasNext();) {
            String id = (String) it.next();
            copyMetaData.setValue(id, (String) values.get(id));
        }
        return copyMetaData;
    }

}


text:
using Xamarin.Forms;

namespace FreshMvvm.CoreMethods
{
    public class PageModelTransactions : IPageModelTransactions
    {
        private readonly Page _currentPage;

        public PageModelTransactions(Page currentPage)
        {
            _currentPage = currentPage;
        }

        public void BatchBegin()
        {
            _currentPage.BatchBegin();
        }

        public void BatchCommit()
        {
            _currentPage.BatchCommit();
        }

    }
}


text:
class ArtworksController < ApplicationController
  skip_before_action :verify_authenticity_token, :if => Proc.new{|c| c.request.format=='application/json'}
  before_action :api_auth, :if => Proc.new{|c| c.request.format=='application/json'}

  def callback
    # put output file, identified by source fingerprint
    artwork = Artwork.find_by_source_fingerprint params[:source]
    unless artwork.nil?
      artwork.output = params[:output]
      artwork.save
      artwork.decorate!
      artwork.sendfile
      render json: {"message"=>"ok"}, status: 200
    else
      render json: {"message"=>"not found"}, status: 404
    end
  end
end


text:
"""
Vessel classification: feature generation and model training/inference.
"""

__version__ = '3.0.2'
__author__ = 'Tim Hochberg'
__email__ = 'tim@globalfishingwatch.com'
__source__ = 'https://github.com/GlobalFishingWatch/vessel-classification'
__license__ = """
Copyright 2020 Global Fishing Watch Inc.
Authors:

Tim Hochberg <tim@globalfishingwatch.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""


text:
using System;
using System.IO.Ports;
using System.Collections.Generic;

namespace Hjemat
{
    public class Device
    {
        public byte deviceID;
        public int productID;
        public Dictionary<byte, short> values;

        public static SerialPort serialPort;

        public Device(byte deviceID = 0x0, int productID = 0x0, Dictionary<byte, Int16> values = null)
        {
            this.deviceID = deviceID;
            this.productID = productID;

            this.values = values ?? new Dictionary<byte, Int16>();
        }

        public bool SendMessage(CommandID command, byte byte1, byte byte2, byte byte3)
        {
            byte?[] data = new byte?[3];

            data[0] = byte1;
            data[1] = byte2;
            data[2] = byte3;

            var message = new Message(deviceID, command, data);
            message.Send();

            return true;
        }

        public bool SendMessage(CommandID command, byte byte1, int data)
        {
            var dataBytes = BitConverter.GetBytes(data);

            return SendMessage(command, byte1, dataBytes[1], dataBytes[0]);
        }

        public bool SendMessage(CommandID command, int data)
        {
            var dataBytes = BitConverter.GetBytes(data);

            return SendMessage(command, dataBytes[2], dataBytes[1], dataBytes[0]);
        }

        public short GetValue(byte dataID)
        {
            SendMessage(CommandID.Get, dataID, 0);

            try
            {
                var response = Message.Read();

                var expectedHeader = Message.CreateHeader(deviceID, CommandID.Return);

                if (response.GetHeader() == expectedHeader && response.bytes[1] == dataID)
                {
                    return response.GetShortData();
                }

                throw new System.Exception($"Unexpected header {response.GetHeader().ToString()}");
            }
            catch (System.TimeoutException) {
                Console.WriteLine("Something took a little too long");
                return 0;
            }

        }

        public void SetupValues(Product product)
        {
            this.values = new Dictionary<byte, short>();

            foreach (var productValue in product.values)
            {
                this.values.Add(productValue.id, this.GetValue(productValue.id));
            }
        }
        /*
                public bool SendData(byte dataID, int data)
                {
                    SendMessage(Command.Set, dataID, data);

                    byte[] confirmationMessage = new byte[4];
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();

                    bool reading = true;
                    int messageIndex = 0;

                    while (reading)
                    {
                        var numBytes = serialPort.BytesToRead;
                        if (numBytes < 1)
                            continue;

                        serialPort.Read(confirmationMessage, messageIndex, numBytes);
                        messageIndex += numBytes;

                        if (messageIndex >= 3)
                        {
                            reading = false;
                        }
                    }

                    var expectedHeader = Message.CreateHeader(deviceID, Command.Return);

                    if (confirmationMessage[0] == expectedHeader)
                    {
                        Console.WriteLine("Data confirmed received");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("No confirmation of reception");
                        foreach (var part in confirmationMessage)
                        {
                            Console.Write(part);
                            Console.Write(" ");
                        }
                        Console.WriteLine("");

                        return false;
                    }
                }
                */
    }
}


text:
var HEARTBEAT_PATH = '/heartbeat';
var heartbeat = function(name) {
  var self = this;
  self.appName = name || 'Untitled Application';

  self.Handler = function(req, res, next) {
    var paths = [
      (req.path || '').toLowerCase(),
      (req.originalUrl || '').toLowerCase(),
      (req.baseUrl || '').toLowerCase()];

    if(paths.indexOf(HEARTBEAT_PATH) === -1) { return next(); }

    if(req.accepts('json')) { res.json({name: self.appName, status: 200}); }
    else if(req.accepts('html')) { res.send(200); }

    res.status(200);
    res.end();
  };
};

module.exports = heartbeat;


text:
package org.cloudfoundry.client.lib.util;

import org.cloudfoundry.client.lib.HttpProxyConfiguration;
import org.cloudfoundry.client.lib.oauth2.OauthClient;
import org.cloudfoundry.client.lib.rest.LoggingRestTemplate;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.URL;

/**
 * Some helper utilities for creating classes used for the REST support.
 *
 * @author: Thomas Risberg
 */
public class RestUtil {

	public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration) {
		RestTemplate restTemplate = new LoggingRestTemplate();
		restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration));
		return restTemplate;
	}

	public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration) {
		CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
		if (httpProxyConfiguration != null) {
			requestFactory.getHttpClient().getHostConfiguration().setProxy(httpProxyConfiguration.getProxyHost(),
					httpProxyConfiguration.getProxyPort());
		}
                requestFactory.setConnectTimeout(Integer.MAX_VALUE);
                requestFactory.setReadTimeout(Integer.MAX_VALUE);
		return requestFactory;
	}

	public OauthClient createOauthClient(URL authorizationUrl, HttpProxyConfiguration httpProxyConfiguration) {
		return new OauthClient(authorizationUrl, createRestTemplate(httpProxyConfiguration));
	}
}


text:
package com.baidu.hsb.mysql.bio.executor;

/**
 * @author xiongzhao@baidu.com
 */
public abstract class NodeExecutor {
    /**
     * @return block until all tasks are finished
     */
    public abstract void terminate() throws InterruptedException;

}


text:
<?php get_header(); ?>

	<?php /* Start loop */ ?>
	<?php while (have_posts()) : the_post(); ?>
		<article <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

					<?php reverie_entry_meta(); ?>

<?php the_tags(); ?>

				<?php echo do_shortcode('[types field="podcast" id="$podcast"]'); ?>

Featured Newsletter:

				<?php echo do_shortcode('[p2p_connected type=newsletters_to_podcasts]'); ?>

				<?php wp_link_pages(array('before' => '
' . __('Pages:', 'reverie'), 'after' => '
' )); ?>
				<?php edit_post_link('Edit this Post'); ?>

					<?php echo get_avatar( get_the_author_meta('user_email'), 95 ); ?>

<?php the_author_posts_link(); ?>

<?php the_author_meta('description'); ?>

		<?php comments_template(); ?>
	<?php endwhile; // End the loop ?>

	<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
Description
===========

Manages FreeBSD services

Requirements
============

Needs FreeBSD.

Why
===

Because on FreeBSD, the built-in chef lib uses `faststart,faststop,fastrestart`. I want to use `start/stop/restart`.
Also try using the command `service -e` to detect enabled services (this method has a known issue: ntpd doesn't detect as enabled).
Also try to set enabled via `sysrc`

Usage
=====

```ruby
depends "svc"

svc 'sshd' do
  service_name node['openssh']['service_name']
  supports value_for_platform(
    'freebsd' => { 'default' => [:restart, :reload, :status] }
  )
  action [ :enable, :start ]
end

```

License and Author
==================

Author:: John Ko <git@johnko.ca>
Copyright:: 2014, John Ko

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>EPub class documentation</title>

EPub class documentation

This class has been designed for ease of use, and to enable ePub book creation on the fly.

The ePub standard contains a lot of parameters that can be set by the user, but in this implementation we are only relying on some of them, the important ones so to speak.

The mandatory fields are:

Title

setTitle($title), where $title is a text string.

Language

setLanguage($language), where $language is a RFC3066 Language code, such as "en", "da", "fr" etc. Language is "en" by default.

Identifier

setIdentifier($identifier, $identifierType), where both arguments are text strings.

    The $identifier should be unique for the book. If you don't have anything unique you can use the createUUID function mentioned later in the documentation.

    The $identifierType must be one of these:

"EPub::IDENTIFIER_URI"

When using the page URL as $identifier.

"EPub::IDENTIFIER_ISBN"

Usually used for published books, where the books unique ISBN number are available.

"EPub::IDENTIFIER_UUID"

A generated or random UUID string on the form c5bc871d-a20a-fc48-ccb4-bb134ae6c564

Where the additional optional fields are:

Description

A book description or synopsis

Author

Book author or creator. setAuthor($author, $authorSortKey) has two arguments, where the sort key can be left blank with ''.

    The $authorSortKey is basically how the name is to be sorted, usually it's "Lastname, First names" where the $author is the straight "Firstnames Lastname"

Publisher

Book publisher Information, use setPublisher($publisherName, $publisherURL) to set the name and URL of the publisher.

Date

The publishing date of the book, as a timestamp. If left blank the current date/time will be used.

Rights

Test string with the licence and copyrights that may apply to the book.

Source URL

The web address for the book, if any are available, but this eBook must be downloadable from somewhere. This is usually also the address used as an identifier, if that parameter is using the "URI" identifier type.


text:
from se34euca.testcase.testcase_base import *

class testcase_snapshot(testcase_base):
    def delete_snapshot(self):
        print "=== runTest: Delete Snapshot ==="
        self.eucaUITester.base.test_ui_login()
        self.eucaUITester.snapshot.test_ui_delete_snapshot()
        self.eucaUITester.base.test_ui_logout()

    def delete_all_snapshots(self):
        print "=== runTest: Delete Snapshot ==="
        self.eucaUITester.base.test_ui_login()
        self.eucaUITester.snapshot.test_ui_delete_all_snapshots()
        self.eucaUITester.base.test_ui_logout()

    def create_volume_from_snapshot(self):
        print "=== runTest: Create Volume From Snapshot ==="
        self.eucaUITester.base.test_ui_login()
        self.eucaUITester.snapshot.test_ui_create_volume_from_snapshot()
        self.eucaUITester.base.test_ui_logout()

    def register_snapshot_as_image(self):
        print "=== runTest: Register Snapshot as Image ==="
        self.eucaUITester.base.test_ui_login()
        self.eucaUITester.snapshot.test_ui_register_snapshot_as_image("myimage")
        self.eucaUITester.base.test_ui_logout()

if __name__ == "__main__":
    unittest.main()


text:
import { Component, OnInit, ViewChild, Injector, ElementRef } from '@angular/core';
import { AppComponentBase } from '@shared/app-component-base';
import { AccountServiceProxy } from '@shared/service-proxies/service-proxies';
import { IsTenantAvailableInput } from '@shared/service-proxies/service-proxies';
import { AppTenantAvailabilityState } from '@shared/AppEnums';
import { ModalDirective } from 'ngx-bootstrap';

@Component({
    selector: 'tenantChangeModal',
    templateUrl: './tenant-change-modal.component.html'
})
export class TenantChangeModalComponent extends AppComponentBase {

    @ViewChild('tenantChangeModal') modal: ModalDirective;
    @ViewChild('tenancyNameInput') tenancyNameInput: ElementRef;
    @ViewChild('modalContent') modalContent: ElementRef;

    tenancyName: string = '';
    active: boolean = false;
    saving: boolean = false;

    constructor(
        private _accountService: AccountServiceProxy,
        injector: Injector
    ) {
        super(injector);
    }

    show(tenancyName: string): void {
        this.tenancyName = tenancyName;
        this.active = true;
        this.modal.show();
    }

    onShown(): void {
        $(this.tenancyNameInput.nativeElement).focus().select();
    }

    save(): void {

        if (!this.tenancyName) {
            abp.multiTenancy.setTenantIdCookie(undefined);;
            this.close();
            location.reload();
            return;
        }

        var input = new IsTenantAvailableInput();
        input.tenancyName = this.tenancyName;

        this.saving = true;
        this._accountService.isTenantAvailable(input)
            .finally(() => { this.saving = false; })
            .subscribe((result) => {
                switch (result.state) {
                    case AppTenantAvailabilityState.Available:
                        abp.multiTenancy.setTenantIdCookie(result.tenantId);
                        this.close();
                        location.reload();
                        return;
                    case AppTenantAvailabilityState.InActive:
                        this.message.warn(this.l('TenantIsNotActive', this.tenancyName));
                        break;
                    case AppTenantAvailabilityState.NotFound: //NotFound
                        this.message.warn(this.l('ThereIsNoTenantDefinedWithName{0}', this.tenancyName));
                        break;
                }
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}


text:
namespace TodoListService_ManualJwt.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
package io.rx_cache;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Set of migrations to be performed in order to guaranty data integrity between releases if data
 * model changes has been performed.
 *
 * @see MigrationCache
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SchemeMigration {
  Migration[] value();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workbench progressCount="36" version="2.0">
<workbenchAdvisor/>
<window height="728" width="1024" x="50" y="0">
<fastViewData fastViewLocation="1024"/>
<perspectiveBar>
<itemSize x="160"/>
</perspectiveBar>
<coolbarLayout>
<coolItem id="group.file" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.file" itemType="typeToolBarContribution" x="99" y="22"/>
<coolItem id="additions" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.debug.ui.launchActionSet" itemType="typeToolBarContribution" x="129" y="22"/>
<coolItem id="org.eclipse.search.searchActionSet" itemType="typeToolBarContribution" x="53" y="22"/>
<coolItem id="org.eclipse.ui.edit.text.actionSet.presentation" itemType="typeToolBarContribution" x="-1" y="-1"/>
<coolItem id="org.eclipse.wst.xml.ui.perspective.NewFileToolBar" itemType="typeToolBarContribution" x="-1" y="-1"/>
<coolItem id="org.eclipse.wst.xml.ui.design.DesignToolBar" itemType="typeToolBarContribution" x="-1" y="-1"/>
<coolItem id="org.eclipse.debug.ui.launch.toolbar" itemType="typeToolBarContribution" x="-1" y="-1"/>
<coolItem id="org.eclipse.debug.ui.main.toolbar" itemType="typeToolBarContribution" x="38" y="22"/>
<coolItem id="com.zend.php.zendserver.ui.toolbar" itemType="typeToolBarContribution" x="-1" y="-1"/>
<coolItem id="com.zend.php.library.ui.phpLibrariesToolbar" itemType="typeToolBarContribution" x="38" y="22"/>
<coolItem id="group.nav" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.navigate" itemType="typeToolBarContribution" x="114" y="22"/>
<coolItem id="group.editor" itemType="typeGroupMarker"/>
<coolItem id="group.help" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.help" itemType="typeToolBarContribution" x="-1" y="-1"/>
</coolbarLayout>
<page aggregateWorkingSetId="Aggregate for window 1404328978688" focus="true" label="Workspace - PHP">
<editors>
<editorArea activeWorkbook="DefaultEditorWorkbook">
<info part="DefaultEditorWorkbook">
<folder appearance="1" expanded="2">
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory"/>
</folder>
</info>
</editorArea>
</editors>
<views>
<view id="org.eclipse.rse.ui.view.systemView" partName="Remote Systems"/>
<view id="org.eclipse.ui.views.ProblemView" partName="Problems">
<viewState PRIMARY_SORT_FIELD="org.eclipse.ui.ide.severityAndDescriptionField" categoryGroup="org.eclipse.ui.ide.severity" markerContentGenerator="org.eclipse.ui.ide.problemsGenerator" partName="Problems">
<columnWidths org.eclipse.ui.ide.locationField="90" org.eclipse.ui.ide.markerType="90" org.eclipse.ui.ide.pathField="120" org.eclipse.ui.ide.resourceField="90" org.eclipse.ui.ide.severityAndDescriptionField="300"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.severityAndDescriptionField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.resourceField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.pathField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.locationField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.markerType"/>
</viewState>
</view>
<view id="org.eclipse.php.ui.explorer" partName="PHP Explorer">
<viewState group_libraries="1" isWindowWorkingSet="false" layout="1" linkWithEditor="0" rootMode="1" workingSetName="">
<customFilters userDefinedPatternsEnabled="false">
<xmlDefinedFilters>
<child filterId="org.eclipse.php.ui.explorer.EmptyInnerPackageFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.PHPHTMLFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.NonScriptElementFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.NonFrameworkProjectsFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.NonPublicFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.NonScriptProjectsFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.RSEProjectFilter" isEnabled="true"/>
<child filterId="org.eclipse.php.ui.explorer.FieldsFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.EmptyPackageFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.UseStatementFilter" isEnabled="true"/>
<child filterId="org.eclipse.php.ui.explorer.LibraryFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.ContainMembersFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.NonSharedProjectsFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.SMFileFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.DotFilesFilter" isEnabled="true"/>
<child filterId="org.eclipse.php.ui.explorer.ClosedProjectsFilter" isEnabled="false"/>
<child filterId="org.eclipse.php.ui.explorer.ContainedLibraryFilter" isEnabled="false"/>
</xmlDefinedFilters>
</customFilters>
</viewState>
</view>
<view id="org.zend.php.zendserver.deployment.ui.targetsview" partName="Targets"/>
<view id="org.eclipse.ui.console.ConsoleView" partName="Console"/>
<view id="org.eclipse.ui.views.ContentOutline" partName="Outline">
<viewState/>
</view>
</views>
<perspectives activePart="org.eclipse.php.ui.explorer" activePerspective="org.eclipse.php.perspective">
<perspective editorAreaTrimState="2" editorAreaVisible="1" fixed="0" version="0.016">
<descriptor class="org.eclipse.php.internal.ui.PHPPerspectiveFactory" id="org.eclipse.php.perspective" label="PHP"/>
<alwaysOnActionSet id="org.eclipse.ui.cheatsheets.actionSet"/>
<alwaysOnActionSet id="org.eclipse.search.searchActionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.edit.text.actionSet.annotationNavigation"/>
<alwaysOnActionSet id="org.eclipse.ui.edit.text.actionSet.navigation"/>
<alwaysOnActionSet id="org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo"/>
<alwaysOnActionSet id="org.eclipse.ui.externaltools.ExternalToolsSet"/>
<alwaysOnActionSet id="org.eclipse.ui.actionSet.keyBindings"/>
<alwaysOnActionSet id="org.eclipse.ui.actionSet.openFiles"/>
<alwaysOnActionSet id="com.zend.php.ui.helpActionSet"/>
<alwaysOnActionSet id="org.eclipse.rse.core.search.searchActionSet"/>
<alwaysOnActionSet id="com.zend.php.debug.ui.tunnelingActionSet"/>
<alwaysOnActionSet id="org.eclipse.debug.ui.profileActionSet"/>
<alwaysOnActionSet id="com.zend.php.profile.ui.launchActionSet"/>
<alwaysOnActionSet id="com.zend.php.ui.EncodeActionSet"/>
<alwaysOnActionSet id="com.zend.php.zendserver.ui.serveractionset"/>
<alwaysOnActionSet id="org.eclipse.php.debug.ui.actionSet"/>
<alwaysOnActionSet id="org.eclipse.debug.ui.launchActionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.NavigateActionSet"/>
<alwaysOnActionSet id="org.eclipse.php.ui.PHPActionSet"/>
<alwaysOnActionSet id="org.eclipse.debug.ui.breakpointActionSet"/>
<alwaysOnActionSet id="org.eclipse.php.ui.text.php.actionSet.presentation"/>
<alwaysOnActionSet id="org.zend.php.framework.ZendToolActionSet"/>
<show_view_action id="org.eclipse.php.ui.explorer"/>
<show_view_action id="org.eclipse.php.ui.functions"/>
<show_view_action id="org.eclipse.php.ui.projectOutline"/>
<show_view_action id="org.eclipse.ui.console.ConsoleView"/>
<show_view_action id="org.eclipse.rse.ui.view.systemView"/>
<show_view_action id="com.zend.php.rss.ui.RSSView"/>
<show_view_action id="org.zend.php.framework.ui.views.mvc"/>
<show_view_action id="com.zend.php.codegallery"/>
<show_view_action id="com.zend.php.debug.ui.views.CodeCoverageView"/>
<show_view_action id="com.zend.php.phpunit.PHPUnitView"/>
<show_view_action id="org.eclipse.ui.views.ContentOutline"/>
<show_view_action id="org.eclipse.ui.views.ProblemView"/>
<show_view_action id="org.eclipse.ui.views.TaskList"/>
<show_view_action id="org.eclipse.dltk.ui.TypeHierarchy"/>
<show_view_action id="org.eclipse.ui.views.ResourceNavigator"/>
<show_view_action id="org.zend.php.zendserver.deployment.ui.targetsview"/>
<new_wizard_action id="com.zend.php.ccm.ui.ccmProjectWizard"/>
<new_wizard_action id="com.zend.php.ccm.ui.restfulProjectWizard"/>
<new_wizard_action id="com.zend.php.ide.git.ui.projectWizard"/>
<new_wizard_action id="com.zend.php.ide.github.ui.projectWizard"/>
<new_wizard_action id="com.zend.php.ide.openshift.ui.projectWizard"/>
<new_wizard_action id="com.zend.php.ide.phpcloud.ui.projectWizard"/>
<new_wizard_action id="com.zend.php.ide.svn.ui.SVNProjectWizard"/>
<new_wizard_action id="com.zend.php.ide.ui.project.wizard.localphp"/>
<new_wizard_action id="com.zend.php.ide.ui.project.wizard.existingphp"/>
<new_wizard_action id="com.zend.php.ui.wizards.phpElementsWizard.NewPHPClassWizard"/>
<new_wizard_action id="com.zend.php.ui.wizards.phpElementsWizard.NewPHPInterfaceWizard"/>
<new_wizard_action id="com.zend.php.ui.wizards.phpElementsWizard.NewPHPTraitWizard"/>
<new_wizard_action id="com.zend.php.phpunit.wizards.TestCaseWizard"/>
<new_wizard_action id="com.zend.php.phpunit.wizards.TestSuiteWizard"/>
<new_wizard_action id="com.zend.php.ui.wizards.PHPRemoteProjectCreationWizard"/>
<new_wizard_action id="com.zend.php.ui.wizards.wizards.RemoteFolderWizard"/>
<new_wizard_action id="org.eclipse.php.wst.jsdt.ui.NewJSWizard"/>
<new_wizard_action id="org.eclipse.php.ui.wizards.PHPProjectCreationWizard"/>
<new_wizard_action id="org.eclipse.php.ui.wizards.PHPFileCreationWizard"/>
<new_wizard_action id="org.eclipse.php.ui.wizards.UntitledPHPDocumentWizard"/>
<new_wizard_action id="org.eclipse.ui.wizards.new.folder"/>
<new_wizard_action id="org.eclipse.ui.wizards.new.file"/>
<new_wizard_action id="org.eclipse.wst.css.ui.internal.wizard.NewCSSWizard"/>
<new_wizard_action id="org.eclipse.wst.html.ui.internal.wizard.NewHTMLWizard"/>
<new_wizard_action id="org.eclipse.wst.xml.ui.internal.wizards.NewXMLWizard"/>
<new_wizard_action id="org.eclipse.ui.editors.wizards.UntitledTextFileWizard"/>
<new_wizard_action id="org.zend.php.framework.ui.wizards.ZendFrameworkProjectCreationWizard"/>
<new_wizard_action id="org.zend.php.framework.ui.wizards.NewZendItemWizard"/>
<perspective_action id="org.eclipse.php.perspective"/>
<perspective_action id="org.eclipse.debug.ui.DebugPerspective"/>
<perspective_action id="com.zend.php.profile.ui.perspective"/>
<perspective_action id="org.eclipse.atf.mozilla.ide.ui.perspective"/>
<hide_toolbar_item_id id="com.zend.php.profile.ui.actions.ProfileURL"/>
<hide_toolbar_item_id id="org.eclipse.ui.externaltools.ExternalToolMenuDelegateToolbar"/>
<hide_toolbar_item_id id="com.zend.php.ui.commands.EncodeProjectAction"/>
<hide_toolbar_item_id id="com.zend.php.zendserver.ui.showEventList"/>
<hide_toolbar_item_id id="org.eclipse.ui.window.pinEditor"/>
<hide_toolbar_item_id id="print.ext"/>
<hide_toolbar_item_id id="org.eclipse.ui.file.print"/>
<hide_toolbar_item_id id="print"/>
<hide_toolbar_item_id id="org.eclipse.ui.navigate.next"/>
<hide_toolbar_item_id id="org.eclipse.ui.navigate.previous"/>
<hide_toolbar_item_id id="org.eclipse.php.ui.navigate.open.type"/>
<hide_toolbar_item_id id="com.zend.php.debug.internal.ui.actions.TunnelingAction"/>
<hide_toolbar_item_id id="org.eclipse.php.ui.edit.text.toggleMarkOccurrences"/>
<hide_toolbar_item_id id="org.eclipse.wst.server.ui.internal.webbrowser.action.open"/>
<hide_toolbar_item_id id="org.eclipse.ui.edit.text.toggleBlockSelectionMode"/>
<hide_toolbar_item_id id="com.zend.php.ui.actions.new.untitled.document"/>
<hide_toolbar_item_id id="com.zend.php.ui.commands.GeneratePHPDocAction"/>
<hide_toolbar_item_id id="org.eclipse.ui.edit.text.toggleShowWhitespaceCharacters"/>
<hide_toolbar_item_id id="org.eclipse.ui.window.quickAccess"/>
<hide_toolbar_item_id id="SearchField"/>
<hide_toolbar_item_id id="org.eclipse.debug.ui.commands.RunToLine"/>
<hide_toolbar_item_id id="org.eclipse.jdt.ui.actions.OpenProjectWizard"/>
<hide_toolbar_item_id id="org.eclipse.ui.edit.text.toggleShowSelectedElementOnly"/>
<view id="org.eclipse.php.ui.explorer"/>
<view id="org.eclipse.ui.views.ProblemView"/>
<view id="org.eclipse.ui.console.ConsoleView"/>
<view id="org.eclipse.rse.ui.view.systemView"/>
<view id="org.zend.php.zendserver.deployment.ui.targetsview"/>
<view id="org.eclipse.ui.views.ContentOutline"/>
<fastViewBars/>
<layout>
<mainWindow>
<info folder="true" part="topLeft">
<folder activePageID="org.eclipse.php.ui.explorer" appearance="2" expanded="2">
<page content="org.eclipse.php.ui.explorer" label="PHP Explorer"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory">
<part id="0"/>
</presentation>
</folder>
</info>
<info folder="true" part="stickyFolderRight" ratio="0.75" ratioLeft="750" ratioRight="250" relationship="2" relative="topLeft">
<folder appearance="2" expanded="2">
<page content="org.eclipse.help.ui.HelpView" label="LabelNotFound"/>
<page content="org.eclipse.ui.internal.introview" label="LabelNotFound"/>
<page content="org.eclipse.ui.cheatsheets.views.CheatSheetView" label="LabelNotFound"/>
</folder>
</info>
<info part="org.eclipse.ui.editorss" ratio="0.22" ratioLeft="220" ratioRight="780" relationship="2" relative="topLeft"/>
<info folder="true" part="bottom" ratio="0.74958813" ratioLeft="455" ratioRight="152" relationship="4" relative="org.eclipse.ui.editorss">
<folder activePageID="org.eclipse.ui.views.ProblemView" appearance="2" expanded="2">
<page content="org.eclipse.ui.views.ProblemView" label="Problems"/>
<page content="org.eclipse.ui.console.ConsoleView" label="Console"/>
<page content="org.eclipse.rse.ui.view.systemView" label="Remote Systems"/>
<page content="org.zend.php.zendserver.deployment.ui.targetsview" label="Targets"/>
<page content="org.eclipse.ui.views.BookmarkView" label="LabelNotFound"/>
<page content="com.zend.php.phpunit.PHPUnitView" label="LabelNotFound"/>
<page content="com.zend.php.debug.ui.views.CodeCoverageView" label="LabelNotFound"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory">
<part id="0"/>
<part id="1"/>
<part id="2"/>
<part id="3"/>
</presentation>
</folder>
</info>
<info folder="true" part="right" ratio="0.75" ratioLeft="585" ratioRight="195" relationship="2" relative="org.eclipse.ui.editorss">
<folder activePageID="org.eclipse.ui.views.ContentOutline" appearance="2" expanded="2">
<page content="org.eclipse.ui.views.ContentOutline" label="Outline"/>
<page content="org.eclipse.php.ui.projectOutline" label="LabelNotFound"/>
<page content="org.zend.php.framework.ui.views.mvc" label="LabelNotFound"/>
<page content="org.eclipse.php.ui.functions" label="LabelNotFound"/>
<page content="com.zend.php.gateful.ui.views.testService" label="LabelNotFound"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory">
<part id="0"/>
</presentation>
</folder>
</info>
</mainWindow>
</layout>
</perspective>
</perspectives>
<workingSets/>
<navigationHistory/>
<input factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/" type="8"/>
</page>
<workbenchWindowAdvisor/>
<actionBarAdvisor/>
<trimLayout>
<trimArea IMemento.internal.id="128">
<trimItem IMemento.internal.id="org.eclipse.ui.internal.WorkbenchWindow.topBar"/>
</trimArea>
<trimArea IMemento.internal.id="1024">
<trimItem IMemento.internal.id="org.eclise.ui.internal.FastViewBar"/>
<trimItem IMemento.internal.id="org.eclipse.jface.action.StatusLineManager"/>
<trimItem IMemento.internal.id="org.eclipse.ui.internal.progress.ProgressRegion"/>
</trimArea>
</trimLayout>
</window>
<mruList>
<file factoryID="org.zend.php.common.welcome.WelcomePageEditorInput" id="org.zend.customization.welcome.welcomePageEditor" name="Welcome" tooltip="Welcome">
<persistable categories="true" discoveryFile="/directory.xml" id="welcomeBrowser" progressDialogMsg="Updating Zend Studio" style="16" url="file:/C:/Program Files (x86)/Zend/Zend Studio 10.5.0/plugins/com.zend.php.ui_10.6.0.v20140128-2127/resources/welcome/index-zend-studio-10-welcome-page.html"/>
</file>
</mruList>
</workbench>


text:
<?php
namespace empire\framework\mvc;

use \Exception;

class MVCException extends Exception {
}


text:
require 'rails_helper'

RSpec.describe 'Daily History', type: :system do
  use_moby_cats

  before do
    0.upto(9).each do |number_of|
      Timecop.travel number_of.days.ago do
        visit root_path
        search_for 'bobcat'
      end
    end

    10.upto(19).each do |number_of|
      Timecop.travel number_of.days.ago do
        visit root_path
        search_for 'lion'
      end
    end
  end

  it 'Displays searched words and pages' do
    visit histories_path
    expect(page).to have_link('bobcat', count: 10)
    click_on 'Older searches'
    expect(page).to have_link('lion', count: 10)
  end

  context 'when account history' do
    let(:user) { create :user }

    it 'Users see searched history' do
      sign_in user
      visit root_path
      search_for 'bobcat'

      click_on 'Settings'
      click_on 'Search History', match: :first
      expect(page).to have_link 'bobcat'
    end
  end
end


text:
require 'sslyze/xml/plugin'
require 'sslyze/xml/types'
require 'sslyze/xml/protocol/cipher_suite/key_exchange'
require 'sslyze/cipher_suites'

module SSLyze
  class XML
    class Protocol < Plugin
      #
      # Represents the `<cipherSuite>` XML element.
      #
      class CipherSuite

        include Types

        #
        # Initializes the cipher suite.
        #
        # @param [Nokogiri::XML::Node] node
        #   The `<cipherSuite>` XML element.
        #
        def initialize(node)
          @node = node
        end

        #
        # The cipher suite name.
        #
        # @return [String]
        #
        def name
          @name ||= @node['name']
        end

        alias rfc_name name

        #
        # Maps the RFC cipher name to it's OpenSSL name.
        #
        # @return [String, nil]
        #
        # @since 1.0.0
        #
        def openssl_name
          CipherSuites::OPENSSL_NAMES[rfc_name]
        end

        #
        # The connection status when the cipher suite was used.
        #
        # @return [String]
        #
        def connection_status
          @connection_status ||= @node['connectionStatus']
        end

        #
        # @return [Boolean]
        #
        def anonymous?
          Boolean[@node['anonymous']]
        end

        #
        # The key size required by the cipher suite.
        #
        # @return [Integer, nil]
        #
        # @since 1.0.0
        #
        def key_size
          @key_size ||= if (value = @node['keySize'])
                          value.to_i
                        end
        end

        #
        # Key exchange information.
        #
        # @return [KeyExchange, nil]
        #
        def key_exchange
          @key_exchange ||= if (element = @node.at_xpath('keyExchange'))
                              KeyExchange.new(element)
                            end
        end

        alias to_s name

      end
    end
  end
end


text:
package docker // import "docker.io/go-docker"

import (
	"encoding/json"
	"net/url"

	"docker.io/go-docker/api/types"
	"docker.io/go-docker/api/types/filters"
	"golang.org/x/net/context"
)

// NetworkList returns the list of networks configured in the docker host.
func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) {
	query := url.Values{}
	if options.Filters.Len() > 0 {
		filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
		if err != nil {
			return nil, err
		}

		query.Set("filters", filterJSON)
	}
	var networkResources []types.NetworkResource
	resp, err := cli.get(ctx, "/networks", query, nil)
	if err != nil {
		return networkResources, err
	}
	err = json.NewDecoder(resp.body).Decode(&networkResources)
	ensureReaderClosed(resp)
	return networkResources, err
}


text: var ngMap = angular.module('ngMap', []);


text:
.. _int: https://docs.python.org/2/library/stdtypes.html

.. _str: https://docs.python.org/2/library/stdtypes.html

.. _bool: https://docs.python.org/2/library/stdtypes.html

.. _vim.Folder: ../../vim/Folder.rst

.. _vimAccountName: ../../vim/host/ConnectSpec.rst#vimAccountName

.. _vmodl.DynamicData: ../../vmodl/DynamicData.rst

vim.host.ConnectSpec
====================
  Specifies the parameters needed to add a single host. This includes a small set of optional information about the host configuration. This allows the network and datastore configuration of the host to be synchronized with the naming conventions of the datacenter, as well as the configuration of a vim account (the username/password for the virtual machine files that is created on disk).
:extends: vmodl.DynamicData_

Attributes:
    hostName (`str`_, optional):

       The DNS name or IP address of the host. (Required for adding a host.)
    port (`int`_, optional):

       The port number for the connection. If this is not specified, the default port number is used. For ESX 2.x hosts this is the authd port (902 by default). For ESX 3.x and above and VMware Server hosts this is the https port (443 by default). If this is a reconnect, the port number is unchanged.
    sslThumbprint (`str`_, optional):

       The thumbprint of the SSL certificate, which the host is expected to have. If this value is set and matches the certificate thumbprint presented by the host, then the host is authenticated. If this value is not set or does not match the certificate thumbprint presented by the host, then the host's certificate is verified by checking whether it was signed by a recognized CA.The thumbprint is always computed using the SHA1 hash and is the string representation of that hash in the format: xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx where, 'x' represents a hexadecimal digit
    userName (`str`_, optional):

       The administration account on the host. (Required for adding a host.)
    password (`str`_, optional):

       The password for the administration account. (Required for adding a host.)
    vmFolder (`vim.Folder`_, optional):

       The folder in which to store the existing virtual machines on the host. If this folder is not specified, a default folder is chosen (and possibly created) by the VirtualCenter. This folder exists (or is possibly created) on the VirtualCenter server and is called "Discovered VM".
    force (`bool`_):

       If this flag is set to "true", then the connection succeeds even if the host is already being managed by another VirtualCenter server. The original VirtualCenter server loses connection to the host.
    vimAccountName (`str`_, optional):

       The username to be used for accessing the virtual machine files on the disk.
    vimAccountPassword (`str`_, optional):

       The password to be used with the `vimAccountName`_ property for accessing the virtual machine files on the disk.
    managementIp (`str`_, optional):

       The IP address of the VirtualCenter server that will manage this host. This field can be used to control which IP address the VirtualCenter agent will send heartbeats to. If it is not set, VirtualCenter will use the local IP address used when communicating with the host. Setting this field is useful when the VirtualCenter server is behind a NAT in which case the external NAT address must be used.


text:
package main

import (
	"flag"
	"log"
	"os"
	fp "path/filepath"

	"github.com/u-root/u-root/pkg/uefivars/boot"
)

// must run as root, as efi vars are not accessible otherwise
func main() {
	m := flag.Bool("m", false, "Mount FS containing boot file, print path.")
	flag.Parse()

	bv, err := boot.ReadCurrentBootVar()
	if err != nil {
		log.Fatalf("Reading current boot var: %s", err)
	}
	if bv == nil {
		log.Fatalf("Unable to read var... are you root?")
	}
	if *m {
		// actually mount FS, locate file
		exe := fp.Base(os.Args[0])
		tmp, err := os.MkdirTemp("", exe)
		if err != nil {
			log.Fatalf("creating temp dir: %s", err)
		}
		path := tmp
		for _, element := range bv.FilePathList {
			res, err := element.Resolver()
			if err != nil {
				log.Fatalf("%s", err)
			}
			path, err = res.Resolve(path)
			if err != nil {
				log.Printf("Resolving element %s: %s", element, err)
			}
		}
		log.Printf("file corresponding to CurrentBoot var can be found at %s\n", path)
		log.Printf("you will need to unmount the filesystem, remove temp dir, etc when done.\n")
	} else {
		// just print out elements in variable
		log.Printf("%s", bv)
		for _, element := range bv.FilePathList {
			res, err := element.Resolver()
			if err != nil {
				log.Fatalf("%s", err)
			}
			log.Printf("%s", res.String())
		}
	}
}


text:
package edu.duke.cabig.c3pr.rules.runtime.action;

import gov.nih.nci.cabig.c3pr.rules.brxml.Action;
import gov.nih.nci.cabig.c3pr.rules.brxml.Notification;
import edu.duke.cabig.c3pr.rules.exception.RuleException;
import edu.duke.cabig.c3pr.rules.runtime.RuleContext;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.context.ApplicationContext;

/**
 *
 * @author Sujith Vellat Thayyilthodi
 */
public class ActionDispatcher {

    Logger log = Logger.getLogger(ActionDispatcher.class.toString());

    private ApplicationContext applicationContext;

    public ActionDispatcher() {
        // Hard coding now...this value should be pluggable
    }

    public void dispatchAction(String actionId, RuleContext ruleContext) throws Exception {
        try {
            // instantiate the Mock-ScheduleReport
            /*
             * Report schedule = MockObjectFactory.getReportSchedule(); NotificationCalendarTemplate
             * template = MockObjectFactory.getNotificationCalendarTemplate();
             * schedule.applyNotificationCalendarTemplate(template);
             *
             * //Invoke the webservice of Scheduler String endPointOrg =
             * (String.valueOf(System.getenv("OS")).contains("Win")) ?
             * "http://localhost:8080/scheduler/services/SchedulerService" :
             * "http://10.10.10.2:8031/scheduler/services/SchedulerService";
             *
             * ObjectServiceFactory factory = new JaxbServiceFactory();
             *//*
                 * Service serviceModel = factory.create(SchedulerService.class); SchedulerService
                 * service = (SchedulerService) new XFireProxyFactory().create(serviceModel,
                 * endPointOrg); service.scheduleNotification(schedule);
                 */} catch (Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "error", e);
        }
    }

    public void dispatchActionOld(String actionId, RuleContext ruleContext)  throws RuleException {
        ActionContext actionContext = new ActionContext();
        actionContext.setActionId(actionId);
        Action action = actionContext.getAction();
        NotificationHandler notificationHandler = null;
        if (action instanceof Notification) {
            Notification notification = (Notification) action;
            String actionHandlerClass = notification.getActionHandlerClass();
            if (actionHandlerClass == null) {
                // actionHandlerClass = DefaultEmailNotificationHandler.class.getName();
                log.info("Could not find a actionHandler class. Using the Default class "
                                + actionHandlerClass);
                // bean name .. hard coding now ...needs to be pluggable...
                notificationHandler = (NotificationHandler) this.applicationContext
                                .getBean("defaultEmailNotificationHandler");
            } else {
                notificationHandler = (NotificationHandler) loadObject(actionHandlerClass);
            }
            notificationHandler.performNotify(actionContext, ruleContext);
        }
    }

    public Object loadObject(String className) throws RuleException {
        try {
            return loadClass(className).newInstance();
        } catch (InstantiationException e) {
            throw new RuleException(e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RuleException(e.getMessage(), e);
        }
    }

    public Class loadClass(String className) throws RuleException {
        try {
            return Class.forName(className, true, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            throw new RuleException(e.getMessage(), e);
        }
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}


text:
package generic.problem;

public class Caja<T extends Animal> {

}


text:
[![Build Status](https://travis-ci.org/wmoll/objvalidator.svg?branch=master)](https://travis-ci.org/wmoll/objvalidator)

# objvalidator

Simple nodejs module for validate object elements by custom rule with custom
error messages.

# Validator Declarations

Validators for various object types are declares in a config file (File may
contain validator definitions for one or more objects).

    // Properties in an ordered sequence
    var personvalidator = [
      {
        fieldId : 'firstname',
        fieldName : 'First Name',
        rules:[
          { method : 'notEmpty', message: 'First Name cannot be empty'},
          { method : 'maxLength', param : 2}
        ]
      },
      {
        fieldId : 'lastname',
        fieldName : 'Last Name',
        rules:[
          { method : 'notEmpty', message: 'Last Name cannot be empty'},
          { method : 'maxLength', param : 2}
        ]
      },

    ];
    module.exports.validationPool = {
       person: personvalidator
    };

# Usage

Load this config in your application (Node.js example)

    // Load Config
    var validatorConfig = require("./validationmodel.conf.js");
    // Load Object Validator Module
    var ObjValidation  = require('objvalidator');

Somewhere in the app - run validation...

    var type = 'person';
    // Lookup validator for the object
    var personvalidator = validatorConfig[type];
    // Instantiate validator
    var validator = new ObjValidation.ObjValidation();
    // Object to Validate
    var a_person = {'firstname': 'Bob', 'firstname': '',};
    // Run Validation
    var validation = validator.validateProcess(personvalidator, a_person);


text:
package main.tree;

import java.util.List;

import main.common.Entry;

import com.gaurav.tree.ArrayTree;
import com.gaurav.tree.NodeNotFoundException;

public class GauravTree implements TreeStructure<Entry>{

	private ArrayTree<Entry> tree;

	public GauravTree(Entry root) {
		tree = new ArrayTree<Entry>(9000);
		tree.add(root);
	}

	public TreeStructure<Entry> getSubTree(Entry element) {

		if(!tree.contains(element)) return null;
		GauravTree t = new GauravTree(element);
		try {
			addChildren(t, element);
		} catch (NodeNotFoundException e) {
			e.printStackTrace();
		}
		return t;
	}

	private void addChildren(GauravTree t, Entry parent) throws NodeNotFoundException {
		for(Entry child : tree.children(parent)) {
			t.addChild(parent, child);
			if(!isLeaf(child)) addChildren(t, child);
		}
	}

	public void addSubTree(Entry parent, TreeStructure<Entry> subTree) {
		try {
			tree.remove(subTree.root());
			tree.add(parent, subTree.root());
			copyChildren(subTree, subTree.root(), subTree.root());
		} catch (NodeNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void copyChildren(TreeStructure<Entry> subTree, Entry subParent, Entry parent) throws NodeNotFoundException {
		for(Entry child : subTree.getChildren(subParent)) {

			tree.add(parent, child);
			if(!isLeaf(child)) copyChildren(subTree, child, child);
		}
	}

	public void addChild(Entry parent, Entry child) {
		try {
			tree.add(parent, child);
		} catch (NodeNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Entry> getChildren(Entry arg0) {
		try {
			return tree.children(arg0);
		} catch (NodeNotFoundException e) {
			System.out.println(arg0);
			System.out.println("Getchildren");
			e.printStackTrace();
			return null;
		}

	}

	@Override
	public Entry getParent(Entry arg0) {
		try {
			return tree.parent(arg0);
		} catch (NodeNotFoundException e) {
			System.out.println("Getparent");
			e.printStackTrace();
			return null;
		}

	}

	@Override
	public void remove(Entry parent) {
		tree.remove(parent);
	}

	@Override
	public Entry root() {
		return tree.root();
	}

	@Override
	public boolean isInSubTree(Entry parent, Entry element) {
		try {
			return tree.isDescendant(parent, element);
		} catch (NodeNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean isLeaf(Entry element) {
		try {
			return tree.children(element).size() == 0;
		} catch (NodeNotFoundException e) {
			e.printStackTrace();
			return true;
		}
	}

	@Override
	public String toString() {
		String prefix = "";
		StringBuilder b = new StringBuilder();
		b.append(tree.root());
		b.append("\n");
		appendChildren(b, tree.root(), prefix);
		return b.toString();

	}

	private void appendChildren(StringBuilder b, Entry root, String prefix) {
		try {
			for(Entry e : tree.children(root)) {
				b.append(prefix);
				b.append("-");
				b.append(e);
				b.append("\n");
				if(!isLeaf(e)) appendChildren(b, e, prefix+"-");
			}
		} catch (NodeNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


text:
require 'rails_helper'

describe Scrap::CleanCrawlerHistoryContext do
  before { create :crawler_history }
  before { create :crawler_history, crawler_on: Time.zone.today - 2.months }

  describe 'perform' do
    context 'success' do
      subject { described_class.new.perform }
      it { expect { subject }.to change { CrawlerHistory.count } }
    end
  end
end


text:
.. Licensed to the Apache Software Foundation (ASF) under one
.. or more contributor license agreements.  See the NOTICE file
.. distributed with this work for additional information
.. regarding copyright ownership.  The ASF licenses this file
.. to you under the Apache License, Version 2.0 (the
.. "License"); you may not use this file except in compliance
.. with the License.  You may obtain a copy of the License at

..   http://www.apache.org/licenses/LICENSE-2.0

.. Unless required by applicable law or agreed to in writing,
.. software distributed under the License is distributed on an
.. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
.. KIND, either express or implied.  See the License for the
.. specific language governing permissions and limitations
.. under the License.

.. currentmodule:: pyarrow
.. _parquet:

Reading and Writing the Apache Parquet Format
=============================================

The `Apache Parquet <http://parquet.apache.org/>`_ project provides a
standardized open-source columnar storage format for use in data analysis
systems. It was created originally for use in `Apache Hadoop
<http://hadoop.apache.org/>`_ with systems like `Apache Drill
<http://drill.apache.org>`_, `Apache Hive <http://hive.apache.org>`_, `Apache
Impala (incubating) <http://impala.apache.org>`_, and `Apache Spark
<http://spark.apache.org>`_ adopting it as a shared standard for high
performance data IO.

Apache Arrow is an ideal in-memory transport layer for data that is being read
or written with Parquet files. We have been concurrently developing the `C++
implementation of Apache Parquet <http://github.com/apache/parquet-cpp>`_,
which includes a native, multithreaded C++ adapter to and from in-memory Arrow
data. PyArrow includes Python bindings to this code, which thus enables reading
and writing Parquet files with pandas as well.

Obtaining PyArrow with Parquet Support
--------------------------------------

If you installed ``pyarrow`` with pip or conda, it should be built with Parquet
support bundled:

.. ipython:: python

   import pyarrow.parquet as pq

If you are building ``pyarrow`` from source, you must also build `parquet-cpp
<http://github.com/apache/parquet-cpp>`_ and enable the Parquet extensions when
building ``pyarrow``. See the :ref:`Development <development>` page for more
details.

Reading and Writing Single Files
--------------------------------

The functions :func:`~.parquet.read_table` and :func:`~.parquet.write_table`
read and write the :ref:`pyarrow.Table <data.table>` objects, respectively.

Let's look at a simple table:

.. ipython:: python

   import numpy as np
   import pandas as pd
   import pyarrow as pa

   df = pd.DataFrame({'one': [-1, np.nan, 2.5],
                      'two': ['foo', 'bar', 'baz'],
                      'three': [True, False, True]},
                      index=list('abc'))
   table = pa.Table.from_pandas(df)

We write this to Parquet format with ``write_table``:

.. ipython:: python

   import pyarrow.parquet as pq
   pq.write_table(table, 'example.parquet')

This creates a single Parquet file. In practice, a Parquet dataset may consist
of many files in many directories. We can read a single file back with
``read_table``:

.. ipython:: python

   table2 = pq.read_table('example.parquet')
   table2.to_pandas()

You can pass a subset of columns to read, which can be much faster than reading
the whole file (due to the columnar layout):

.. ipython:: python

   pq.read_table('example.parquet', columns=['one', 'three'])

When reading a subset of columns from a file that used a Pandas dataframe as the
source, we use ``read_pandas`` to maintain any additional index column data:

.. ipython:: python

   pq.read_pandas('example.parquet', columns=['two']).to_pandas()

We need not use a string to specify the origin of the file. It can be any of:

* A file path as a string
* A :ref:`NativeFile <io.native_file>` from PyArrow
* A Python file object

In general, a Python file object will have the worst read performance, while a
string file path or an instance of :class:`~.NativeFile` (especially memory
maps) will perform the best.

Finer-grained Reading and Writing
---------------------------------

``read_table`` uses the :class:`~.ParquetFile` class, which has other features:

.. ipython:: python

   parquet_file = pq.ParquetFile('example.parquet')
   parquet_file.metadata
   parquet_file.schema

As you can learn more in the `Apache Parquet format
<https://github.com/apache/parquet-format>`_, a Parquet file consists of
multiple row groups. ``read_table`` will read all of the row groups and
concatenate them into a single table. You can read individual row groups with
``read_row_group``:

.. ipython:: python

   parquet_file.num_row_groups
   parquet_file.read_row_group(0)

We can similarly write a Parquet file with multiple row groups by using
``ParquetWriter``:

.. ipython:: python

   writer = pq.ParquetWriter('example2.parquet', table.schema)
   for i in range(3):
       writer.write_table(table)
   writer.close()

   pf2 = pq.ParquetFile('example2.parquet')
   pf2.num_row_groups

Alternatively python ``with`` syntax can also be use:

.. ipython:: python

   with pq.ParquetWriter('example3.parquet', table.schema) as writer:
       for i in range(3):
           writer.write_table(table)

.. ipython:: python
   :suppress:

   !rm example.parquet
   !rm example2.parquet
   !rm example3.parquet

Compression, Encoding, and File Compatibility
---------------------------------------------

The most commonly used Parquet implementations use dictionary encoding when
writing files; if the dictionaries grow too large, then they "fall back" to
plain encoding. Whether dictionary encoding is used can be toggled using the
``use_dictionary`` option:

.. code-block:: python

   pq.write_table(table, where, use_dictionary=False)

The data pages within a column in a row group can be compressed after the
encoding passes (dictionary, RLE encoding). In PyArrow we use Snappy
compression by default, but Brotli, Gzip, and uncompressed are also supported:

.. code-block:: python

   pq.write_table(table, where, compression='snappy')
   pq.write_table(table, where, compression='gzip')
   pq.write_table(table, where, compression='brotli')
   pq.write_table(table, where, compression='none')

Snappy generally results in better performance, while Gzip may yield smaller
files.

These settings can also be set on a per-column basis:

.. code-block:: python

   pq.write_table(table, where, compression={'foo': 'snappy', 'bar': 'gzip'},
                  use_dictionary=['foo', 'bar'])

Partitioned Datasets (Multiple Files)
------------------------------------------------

Multiple Parquet files constitute a Parquet *dataset*. These may present in a
number of ways:

* A list of Parquet absolute file paths
* A directory name containing nested directories defining a partitioned dataset

A dataset partitioned by year and month may look like on disk:

.. code-block:: text

   dataset_name/
     year=2007/
       month=01/
          0.parq
          1.parq
          ...
       month=02/
          0.parq
          1.parq
          ...
       month=03/
       ...
     year=2008/
       month=01/
       ...
     ...

Writing to Partitioned Datasets
------------------------------------------------

You can write a partitioned dataset for any ``pyarrow`` file system that is a file-store (e.g. local, HDFS, S3). The
default behaviour when no filesystem is added is to use the local filesystem.

.. code-block:: python

   # Local dataset write
   pq.write_to_dataset(table, root_path='dataset_name', partition_columns=['one', 'two'])

The root path in this case specifies the parent directory to which data will be saved. The partition columns are the
column names by which to partition the dataset. Columns are partitioned in the order they are given. The partition
splits are determined by the unique values in the partition columns.

To use another filesystem you only need to add the filesystem parameter, the individual table writes are wrapped
using ``with`` statements so the ``pq.write_to_dataset`` function does not need to be.

.. code-block:: python

   # Remote file-system example
   fs = pa.hdfs.connect(host, port, user=user, kerb_ticket=ticket_cache_path)
   pq.write_to_dataset(table, root_path='dataset_name', partition_cols=['one', 'two'], filesystem=fs)

Compatibility Note: if using ``pq.write_to_dataset`` to create a table that will then be used by HIVE then partition
column values must be compatible with the allowed character set of the HIVE version you are running.

Reading from Partitioned Datasets
------------------------------------------------

The :class:`~.ParquetDataset` class accepts either a directory name or a list
or file paths, and can discover and infer some common partition structures,
such as those produced by Hive:

.. code-block:: python

   dataset = pq.ParquetDataset('dataset_name/')
   table = dataset.read()

You can also use the convenience function ``read_table`` exposed by ``pyarrow.parquet``
that avoids the need for an additional Dataset object creation step.

.. code-block:: python

   table = pq.read_table('dataset_name')

Note: the partition columns in the original table will have their types converted to Arrow dictionary types
(pandas categorical) on load. Ordering of partition columns is not preserved through the save/load process. If reading
from a remote filesystem into a pandas dataframe you may need to run ``sort_index`` to maintain row ordering
(as long as the ``preserve_index`` option was enabled on write).

Using with Spark
----------------

Spark places some constraints on the types of Parquet files it will read. The
option ``flavor='spark'`` will set these options automatically and also
sanitize field characters unsupported by Spark SQL.

Multithreaded Reads
-------------------

Each of the reading functions have an ``nthreads`` argument which will read
columns with the indicated level of parallelism. Depending on the speed of IO
and how expensive it is to decode the columns in a particular file
(particularly with GZIP compression), this can yield significantly higher data
throughput:

.. code-block:: python

   pq.read_table(where, nthreads=4)
   pq.ParquetDataset(where).read(nthreads=4)

Reading a Parquet File from Azure Blob storage
----------------------------------------------

The code below shows how to use Azure's storage sdk along with pyarrow to read
a parquet file into a Pandas dataframe.
This is suitable for executing inside a Jupyter notebook running on a Python 3
kernel.

Dependencies:

* python 3.6.2
* azure-storage 0.36.0
* pyarrow 0.8.0

.. code-block:: python

   import pyarrow.parquet as pq
   from io import BytesIO
   from azure.storage.blob import BlockBlobService

   account_name = '...'
   account_key = '...'
   container_name = '...'
   parquet_file = 'mysample.parquet'

   byte_stream = io.BytesIO()
   block_blob_service = BlockBlobService(account_name=account_name, account_key=account_key)
   try:
      block_blob_service.get_blob_to_stream(container_name=container_name, blob_name=parquet_file, stream=byte_stream)
      df = pq.read_table(source=byte_stream).to_pandas()
      # Do work on df ...
   finally:
      # Add finally block to ensure closure of the stream
      byte_stream.close()

Notes:

* The ``account_key`` can be found under ``Settings -> Access keys`` in the Microsoft Azure portal for a given container
* The code above works for a container with private access, Lease State = Available, Lease Status = Unlocked
* The parquet file was Blob Type = Block blob


text:
var rewire = require('rewire'),
    expect = require('chai').expect,
    q      = require('q'),
    _      = require('lodash');

var x = rewire('../xtrudr');

var syncOkFn = function(inp){ syncOkFn.count++; return inp+1; },
    syncErrFn = function(inp){ syncErrFn.count++; throw inp-1; };

var asyncOkFn = function(inp){ asyncOkFn.count++; return q(inp+1);},
    asyncErrFn = function(inp){
      asyncErrFn.count++;
      return q.reject(inp-1);
    };

function reset(){
  syncOkFn.count = 0; syncErrFn.count = 0;
  asyncOkFn.count = 0; asyncErrFn.count = 0;
}

function xpect(x, inp, out, err){
  var args = arguments;
  ['inp', 'out', 'err'].forEach(function(t, i){
    expect(x[t]).to.deep.equal(args[i+1]);
  });
}

describe('Sync API', function(){
  ['permit', 'require'].forEach(function(meth){

    describe('#'+meth+'()', function(){

      describe('with str arg', function(){
        var name = 'foo';
        var myXtrudr = x()[meth](name);

        it('should simply pass parameter through', function(){
          var inp = {};
          inp[name] = 1;
          xpect(myXtrudr(inp), inp, inp);
        });

        if ( meth === 'permit' ) {
          it('should not populate anything if missing', function(){
            var inp = {baz:1};
            xpect(myXtrudr(inp), inp, {});
          });
        } else {
          it('should assign error for missing', function(){
            var inp = {baz:1};
            xpect(myXtrudr(inp), inp, {}, {foo:['is required']});
          });
        }
      });

      describe('with array arg', function(){

        var myXtrudr = x()[meth](['foo', 'baz']);

        it('should allow all names in array', function(){
          var inp = {foo:1, baz:2, zab: 3};
          xpect(myXtrudr(inp), inp, {foo:1, baz:2});
        });

        if ( meth === 'permit' ) {
          it('should not populate anything if missing', function(){
            var inp = {zab: 3};
            xpect(myXtrudr(inp), inp, {});
          });
        } else {
          it('should assign errors for missing', function(){
            var inp = {zab: 3};
            xpect(myXtrudr(inp), inp, {}, {
              foo:['is required'],
              baz:['is required']
            });
          });
        }

      });

      describe('with obj arg and validator', function(){
        var inp = {foo: 1},
            myXtrudr = x()[meth]({foo: syncOkFn});

        beforeEach(reset);

        if ( meth === 'permit' ) {
          it('should not populate anything if missing', function(){
            var inp = {baz:1};
            xpect(myXtrudr(inp), inp, {});
          });
        } else {
          it('should assign error for missing', function(){
            var inp = {baz:1};
            xpect(myXtrudr(inp), inp, {}, {foo:['is required']});
          });
        }

        it('should call function and assign result', function(){
          myXtrudr(inp);
          expect(syncOkFn.count).to.equal(1);
          xpect(myXtrudr, inp, {foo:2});
        });

        it('should call function and assign error', function(){
          var myXtrudr = x()[meth]({foo: syncErrFn})(inp);
          expect(syncErrFn.count).to.equal(1);
          xpect(myXtrudr, inp, {}, {foo:[0]});
        });
      });
    });
  });

  describe('#require() with validator as', function(){

    describe('array of fns', function(){

      function bazFn(i){ if (!i) throw "baz"; }
      function zabFn(i){ if (!i) throw "zab"; }
      function lastFn(){ return 'baz'; }

      var myXtrudr = x().require({
        foo: [syncOkFn, bazFn, zabFn, lastFn]
      });

      beforeEach(reset);

      it('should use value returned by last fn', function(){
        var inp = {foo: 1};
        expect(myXtrudr(inp), inp, {foo: 'baz'});
        expect(syncOkFn.count).to.equal(1);
      });

      it('should concatenate and assign errs', function(){
        var inp = {foo: 0};
        expect(myXtrudr(inp), inp, {}, {foo:['baz', 'zab']});
        expect(syncOkFn.count).to.equal(1);
      });
    });

    describe('chainable obj', function(){
      var myXtrudr = x().require({
        foo: x.isLength(2,2).msg(1).isInt().msg(2).toString().toInt()
      });

      it('should assign custom err msgs', function(){
        var inp = {foo: 'a'};
        xpect(myXtrudr(inp), inp, {}, {foo: [1,2]});

        inp = {foo: 1};
        xpect(myXtrudr(inp), inp, {}, {foo: [1]});

        inp = {foo: 'ab'};
        xpect(myXtrudr(inp), inp, {}, {foo: [2]});
      });

      it('should transform with final sanitizer', function(){
        var inp = {foo: '12'};
        xpect(myXtrudr(inp), inp, {foo: 12});
      });
    });
  });

  describe('#add()', function(){
    var props, checkNamed, checkGeneral,
        namedFlag = false, generalFlag = false;
    var myXtrudr = x()
      .permit({
        foo: function(){
          checkGeneral = generalFlag;
          namedFlag = true;
        }
      })
      .require('baz')
      .add(function(inp, out, err){
        checkNamed = namedFlag;
        generalFlag = true;
        props = {inp:inp, out:out, err:err};
      })({foo:1});

    it('should get access to instance props', function(){
      _.forEach(props, function(p, n){
        expect(myXtrudr[n]).to.equal(p);
      });
    });

    it('should be executed after named validators', function(){
      expect(checkNamed).to.be.true;
      expect(checkGeneral).to.be.false;
    });
  });

});

describe('handleErr()', function(){
  var handleErr = x.__get__('handleErr');

  it('should throw if given an Error inst', function(){
    var err = new Error('foo');
    try {
      handleErr('foo', err);
      throw "Should err!";
    } catch (e) { expect(e).to.equal(err); }
  });

  it('should create array with err', function(){
    var obj = {err:{}};
    handleErr.call(obj, 'foo', 1);
    expect(obj.err.foo).to.deep.equal([1]);
  });

  it('should concatenate errs', function(){
    var obj = {err:{foo:[1]}};
    handleErr.call(obj, 'foo', 2);
    expect(obj.err.foo).to.deep.equal([1,2]);
  });
});


text:
class ScreensaverWindowFinder : public ui::EnumerateWindowsDelegate {
 public:
  static bool ScreensaverWindowExists();

 protected:
  bool ShouldStopIterating(XID window) override;

 private:
  ScreensaverWindowFinder();

  bool IsScreensaverWindow(XID window) const;

  bool exists_;

  DISALLOW_COPY_AND_ASSIGN(ScreensaverWindowFinder);
};

#endif  // CHROME_BROWSER_SCREENSAVER_WINDOW_FINDER_X11_H_


text:
package io.crate.metadata;

import io.crate.metadata.ReferenceImplementation;
import io.crate.operation.Input;

/**
 * Base class for expressions. Implementations of expressions should inherit from it.
 * @param <T> The returnType of the expression
 */
public abstract class SimpleObjectExpression<T> implements ReferenceImplementation<T> {

    @Override
    public ReferenceImplementation getChildImplementation(String name) {
        return null;
    }

}


text:
package org.rocket.network;

import java.lang.reflect.Method;

public interface PropValidated {
    /**
     * Describe location of a validated action.
     */
    String describeLocation();

    public static PropValidated forString(String s) {
        return () -> s;
    }

    public static PropValidated forMethod(Method m) {
        // Apache BCEL can give more information
        return forString(m.toString());
    }

    public static PropValidated here() {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        StackTraceElement here = trace[2];
        return forString(here.getClassName() + "." + here.getMethodName() +
                "(" + here.getFileName() + ":" + here.getLineNumber() + ")");
    }
}


text: Deprecated: Use [undermore/mo-dash](https://github.com/atomantic/undermore)


text:
@interface PodsDummy_Pods_ACEToolKitDemo : NSObject
@end
@implementation PodsDummy_Pods_ACEToolKitDemo
@end


text:
import { AmsterdamWindmill } from "../../";

export = AmsterdamWindmill;


text:
.lists-content {
    padding-top: 15px;
}


text:
package kr.ac.kaist.jsaf.clone_refactor.model;

import java.util.ArrayList;

public class CloneCollection extends AbstractModel {
	public final static CloneCollection instance = new CloneCollection();

	protected static ArrayList<CloneGroup> groups;

	private static IModelVisitor adder = new Adder();
	private static IModelVisitor remover = new Remover();

	private CloneCollection() {
		groups = new ArrayList<CloneGroup>();
	}

	private static class Adder implements IModelVisitor {
		public void visitCloneInstance(CloneInstance instance, Object argument) {
			((CloneGroup) argument).addInstance(instance);
		}

		public void visitCloneGroup(CloneGroup group, Object argument) {
			((CloneCollection) argument).addGroup(group);
		}
	}

	private static class Remover implements IModelVisitor {
		public void visitCloneInstance(CloneInstance instance, Object argument) {
			((CloneGroup) argument).removeInstance(instance);
		}

		public void visitCloneGroup(CloneGroup group, Object argument) {
			((CloneCollection) argument).removeGroup(group);
			group.addListener(NullDeltaListener.getSoleInstance());
		}
	}

	public void addGroup(CloneGroup group) {
		groups.add(group);
		group.parent = this;
		fireAdd(group);
	}

	public void removeGroup(CloneGroup group) {
		groups.remove(group);
		group.addListener(NullDeltaListener.getSoleInstance());
		fireRemove(group);
	}

	public void add(AbstractModel toAdd) {
		toAdd.accept(adder, this);
	}

	public void remove(AbstractModel toRemove) {
		toRemove.accept(remover, this);
	}

	public int size() {
		return groups.size();
	}

	@Override
	public void accept(IModelVisitor visitor, Object passAlongArgument) {

	}

	public ArrayList<CloneGroup> getGroups() {
		return groups;
	}

	public void clearGroups() {
		groups.clear();
	}

	public static boolean contains(CloneInstance instance) {
		for (int i = 0; i < groups.size(); i++) {
			if (groups.get(i).contains(instance))
				return true;
		}
		return false;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Brittonia 12(1): 64 (1960)

#### Original name
Tricholomopsis sulphureoides var. megaspora A.H. Sm.

### Remarks
null